Bug 1310027 - Remove DOM/mobilemessage and related code. r=ehsan draft
authorMichelangelo De Simone <mds@mozilla.com>
Mon, 17 Oct 2016 17:26:51 -0700
changeset 427806 e61356da580e57dec6b041dd19919c53d667f20c
parent 427779 f0f1aaf051d6798e1e73d1feee07ca847333167a
child 534556 366032559ec04cf26602825d926ebb5354dad618
push id33116
push usermdesimone@mozilla.com
push dateThu, 20 Oct 2016 21:38:59 +0000
reviewersehsan
bugs1310027
milestone52.0a1
Bug 1310027 - Remove DOM/mobilemessage and related code. r=ehsan MozReview-Commit-ID: ENmSuOCdTnA
b2g/app/b2g.js
browser/installer/package-manifest.in
dom/base/Navigator.cpp
dom/base/Navigator.h
dom/bindings/Bindings.conf
dom/ipc/ContentChild.cpp
dom/ipc/ContentChild.h
dom/ipc/ContentParent.cpp
dom/ipc/ContentParent.h
dom/ipc/PContent.ipdl
dom/ipc/moz.build
dom/mobilemessage/Assertions.cpp
dom/mobilemessage/Constants.cpp
dom/mobilemessage/Constants.h
dom/mobilemessage/DOMMobileMessageError.cpp
dom/mobilemessage/DOMMobileMessageError.h
dom/mobilemessage/DeletedMessageInfo.cpp
dom/mobilemessage/DeletedMessageInfo.h
dom/mobilemessage/MmsMessage.cpp
dom/mobilemessage/MmsMessage.h
dom/mobilemessage/MmsMessageInternal.cpp
dom/mobilemessage/MmsMessageInternal.h
dom/mobilemessage/MobileMessageCallback.cpp
dom/mobilemessage/MobileMessageCallback.h
dom/mobilemessage/MobileMessageCursorCallback.cpp
dom/mobilemessage/MobileMessageCursorCallback.h
dom/mobilemessage/MobileMessageManager.cpp
dom/mobilemessage/MobileMessageManager.h
dom/mobilemessage/MobileMessageService.cpp
dom/mobilemessage/MobileMessageService.h
dom/mobilemessage/MobileMessageThread.cpp
dom/mobilemessage/MobileMessageThread.h
dom/mobilemessage/MobileMessageThreadInternal.cpp
dom/mobilemessage/MobileMessageThreadInternal.h
dom/mobilemessage/SmsMessage.cpp
dom/mobilemessage/SmsMessage.h
dom/mobilemessage/SmsMessageInternal.cpp
dom/mobilemessage/SmsMessageInternal.h
dom/mobilemessage/Types.h
dom/mobilemessage/android/MobileMessageDatabaseService.cpp
dom/mobilemessage/android/MobileMessageDatabaseService.h
dom/mobilemessage/android/SmsManager.cpp
dom/mobilemessage/android/SmsManager.h
dom/mobilemessage/android/SmsService.cpp
dom/mobilemessage/android/SmsService.h
dom/mobilemessage/gonk/MmsPduHelper.jsm
dom/mobilemessage/gonk/MmsService.js
dom/mobilemessage/gonk/MmsService.manifest
dom/mobilemessage/gonk/MobileMessageDB.jsm
dom/mobilemessage/gonk/MobileMessageDatabaseService.js
dom/mobilemessage/gonk/MobileMessageDatabaseService.manifest
dom/mobilemessage/gonk/SmsSegmentHelper.jsm
dom/mobilemessage/gonk/SmsService.js
dom/mobilemessage/gonk/SmsService.manifest
dom/mobilemessage/gonk/WspPduHelper.jsm
dom/mobilemessage/gonk/mms_consts.js
dom/mobilemessage/gonk/wap_consts.js
dom/mobilemessage/interfaces/moz.build
dom/mobilemessage/interfaces/nsIDeletedMessageInfo.idl
dom/mobilemessage/interfaces/nsIGonkMobileMessageDatabaseService.idl
dom/mobilemessage/interfaces/nsIGonkSmsService.idl
dom/mobilemessage/interfaces/nsIMmsMessage.idl
dom/mobilemessage/interfaces/nsIMmsService.idl
dom/mobilemessage/interfaces/nsIMobileMessageCallback.idl
dom/mobilemessage/interfaces/nsIMobileMessageCursorCallback.idl
dom/mobilemessage/interfaces/nsIMobileMessageDatabaseService.idl
dom/mobilemessage/interfaces/nsIMobileMessageService.idl
dom/mobilemessage/interfaces/nsIMobileMessageThread.idl
dom/mobilemessage/interfaces/nsISmsMessage.idl
dom/mobilemessage/interfaces/nsISmsMessenger.idl
dom/mobilemessage/interfaces/nsISmsService.idl
dom/mobilemessage/interfaces/nsIWapPushApplication.idl
dom/mobilemessage/ipc/PMobileMessageCursor.ipdl
dom/mobilemessage/ipc/PSms.ipdl
dom/mobilemessage/ipc/PSmsRequest.ipdl
dom/mobilemessage/ipc/SmsChild.cpp
dom/mobilemessage/ipc/SmsChild.h
dom/mobilemessage/ipc/SmsIPCService.cpp
dom/mobilemessage/ipc/SmsIPCService.h
dom/mobilemessage/ipc/SmsParent.cpp
dom/mobilemessage/ipc/SmsParent.h
dom/mobilemessage/ipc/SmsTypes.ipdlh
dom/mobilemessage/moz.build
dom/mobilemessage/tests/marionette/head.js
dom/mobilemessage/tests/marionette/manifest.ini
dom/mobilemessage/tests/marionette/mmdb_head.js
dom/mobilemessage/tests/marionette/test_between_emulators.py
dom/mobilemessage/tests/marionette/test_bug814761.js
dom/mobilemessage/tests/marionette/test_decode_spanish_fallback.js
dom/mobilemessage/tests/marionette/test_emulator_loopback.js
dom/mobilemessage/tests/marionette/test_error_of_mms_manual_retrieval.js
dom/mobilemessage/tests/marionette/test_error_of_mms_send.js
dom/mobilemessage/tests/marionette/test_error_of_sms_send.js
dom/mobilemessage/tests/marionette/test_filter_date.js
dom/mobilemessage/tests/marionette/test_filter_mixed.js
dom/mobilemessage/tests/marionette/test_filter_number.js
dom/mobilemessage/tests/marionette/test_filter_read.js
dom/mobilemessage/tests/marionette/test_filter_received.js
dom/mobilemessage/tests/marionette/test_filter_sent.js
dom/mobilemessage/tests/marionette/test_filter_unread.js
dom/mobilemessage/tests/marionette/test_getmessage.js
dom/mobilemessage/tests/marionette/test_getmessage_notfound.js
dom/mobilemessage/tests/marionette/test_getmessages.js
dom/mobilemessage/tests/marionette/test_getsegmentinfofortext.js
dom/mobilemessage/tests/marionette/test_getthreads.js
dom/mobilemessage/tests/marionette/test_incoming.js
dom/mobilemessage/tests/marionette/test_incoming_delete.js
dom/mobilemessage/tests/marionette/test_incoming_max_segments.js
dom/mobilemessage/tests/marionette/test_invalid_address.js
dom/mobilemessage/tests/marionette/test_mark_msg_read.js
dom/mobilemessage/tests/marionette/test_mark_msg_read_error.js
dom/mobilemessage/tests/marionette/test_massive_incoming_delete.js
dom/mobilemessage/tests/marionette/test_message_classes.js
dom/mobilemessage/tests/marionette/test_mmdb_foreachmatchedmmsdeliveryinfo.js
dom/mobilemessage/tests/marionette/test_mmdb_full_storage.js
dom/mobilemessage/tests/marionette/test_mmdb_new.js
dom/mobilemessage/tests/marionette/test_mmdb_ports_in_cdma_wappush.js
dom/mobilemessage/tests/marionette/test_mmdb_setmessagedeliverybyid_sms.js
dom/mobilemessage/tests/marionette/test_mmdb_upgradeSchema_22.js
dom/mobilemessage/tests/marionette/test_mmdb_upgradeSchema_current_structure.js
dom/mobilemessage/tests/marionette/test_mmsmessage_attachments.js
dom/mobilemessage/tests/marionette/test_mobilemessage_dsds_default_service_id.js
dom/mobilemessage/tests/marionette/test_mt_sms_concatenation.js
dom/mobilemessage/tests/marionette/test_ondeleted_event.js
dom/mobilemessage/tests/marionette/test_outgoing.js
dom/mobilemessage/tests/marionette/test_outgoing_delete.js
dom/mobilemessage/tests/marionette/test_outgoing_max_segments.js
dom/mobilemessage/tests/marionette/test_outgoing_unstable_voice_connection.js
dom/mobilemessage/tests/marionette/test_phone_number_normalization.js
dom/mobilemessage/tests/marionette/test_replace_short_message_type.js
dom/mobilemessage/tests/marionette/test_segment_info.js
dom/mobilemessage/tests/marionette/test_smsc_address.js
dom/mobilemessage/tests/marionette/test_strict_7bit_encoding.js
dom/mobilemessage/tests/marionette/test_thread_subject.js
dom/mobilemessage/tests/marionette/test_update_gsm_nl_on_mcc_chanages.js
dom/mobilemessage/tests/marionette/test_update_thread_record_in_delete.js
dom/mobilemessage/tests/mochitest/chrome.ini
dom/mobilemessage/tests/mochitest/test_sms_basics.html
dom/mobilemessage/tests/xpcshell/header_helpers.js
dom/mobilemessage/tests/xpcshell/test_mms_pdu_helper.js
dom/mobilemessage/tests/xpcshell/test_mms_service.js
dom/mobilemessage/tests/xpcshell/test_sms_segment_helper.js
dom/mobilemessage/tests/xpcshell/test_smsservice_createsmsmessage.js
dom/mobilemessage/tests/xpcshell/test_wsp_pdu_helper.js
dom/mobilemessage/tests/xpcshell/test_wsp_pdu_helper_header.js
dom/mobilemessage/tests/xpcshell/test_wsp_pdu_helper_numeric.js
dom/mobilemessage/tests/xpcshell/test_wsp_pdu_helper_parameter.js
dom/mobilemessage/tests/xpcshell/test_wsp_pdu_helper_text.js
dom/mobilemessage/tests/xpcshell/xpcshell.ini
dom/moz.build
dom/permission/moz.build
dom/permission/tests/mochitest-websms.ini
dom/permission/tests/test_sms.html
dom/webidl/DOMMobileMessageError.webidl
dom/webidl/MmsMessage.webidl
dom/webidl/MobileMessageThread.webidl
dom/webidl/MozMessageDeletedEvent.webidl
dom/webidl/MozMmsEvent.webidl
dom/webidl/MozMobileMessageManager.webidl
dom/webidl/MozSmsEvent.webidl
dom/webidl/Navigator.webidl
dom/webidl/SmsMessage.webidl
dom/webidl/moz.build
layout/build/nsLayoutModule.cpp
mobile/android/base/AppConstants.java.in
mobile/android/base/FennecManifest_permissions.xml.in
mobile/android/base/geckoview.ddf
mobile/android/base/java/org/mozilla/gecko/BrowserApp.java
mobile/android/base/java/org/mozilla/gecko/GeckoApp.java
mobile/android/base/moz.build
mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java
mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoSmsManager.java
mobile/android/geckoview/src/main/java/org/mozilla/gecko/SmsManager.java
modules/libpref/init/all.js
testing/marionette/harness/marionette/tests/webapi-tests.ini
toolkit/moz.configure
widget/android/AndroidBridge.cpp
widget/android/AndroidBridge.h
widget/android/GeneratedJNINatives.h
widget/android/GeneratedJNIWrappers.cpp
widget/android/GeneratedJNIWrappers.h
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -385,19 +385,16 @@ pref("dom.mozBrowserFramesEnabled", true
 pref("dom.ipc.processCount", 100000);
 
 pref("dom.ipc.browser_frames.oop_by_default", false);
 
 #if !defined(MOZ_MULET) && !defined(MOZ_GRAPHENE)
 pref("dom.meta-viewport.enabled", true);
 #endif
 
-// SMS/MMS
-pref("dom.sms.enabled", true);
-
 //The waiting time in network manager.
 pref("network.gonk.ms-release-mms-connection", 30000);
 
 // Shortnumber matching needed for e.g. Brazil:
 // 03187654321 can be found with 87654321
 pref("dom.phonenumber.substringmatching.BR", 8);
 pref("dom.phonenumber.substringmatching.CO", 10);
 pref("dom.phonenumber.substringmatching.VE", 7);
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -203,17 +203,16 @@
 @RESPATH@/components/dom_power.xpt
 @RESPATH@/components/dom_push.xpt
 @RESPATH@/components/dom_quota.xpt
 @RESPATH@/components/dom_range.xpt
 @RESPATH@/components/dom_security.xpt
 @RESPATH@/components/dom_settings.xpt
 @RESPATH@/components/dom_permissionsettings.xpt
 @RESPATH@/components/dom_sidebar.xpt
-@RESPATH@/components/dom_mobilemessage.xpt
 @RESPATH@/components/dom_storage.xpt
 @RESPATH@/components/dom_stylesheets.xpt
 @RESPATH@/components/dom_telephony.xpt
 @RESPATH@/components/dom_traversal.xpt
 #ifdef MOZ_WEBSPEECH
 @RESPATH@/components/dom_webspeechrecognition.xpt
 #endif
 @RESPATH@/components/dom_workers.xpt
--- a/dom/base/Navigator.cpp
+++ b/dom/base/Navigator.cpp
@@ -37,17 +37,16 @@
 #endif
 #include "mozilla/dom/PowerManager.h"
 #include "mozilla/dom/WakeLock.h"
 #include "mozilla/dom/power/PowerManagerService.h"
 #include "mozilla/dom/FlyWebPublishedServer.h"
 #include "mozilla/dom/FlyWebService.h"
 #include "mozilla/dom/IccManager.h"
 #include "mozilla/dom/InputPortManager.h"
-#include "mozilla/dom/MobileMessageManager.h"
 #include "mozilla/dom/Permissions.h"
 #include "mozilla/dom/Presentation.h"
 #include "mozilla/dom/ServiceWorkerContainer.h"
 #include "mozilla/dom/StorageManager.h"
 #include "mozilla/dom/TCPSocket.h"
 #include "mozilla/dom/Telephony.h"
 #include "mozilla/dom/VRDisplay.h"
 #include "mozilla/dom/workers/RuntimeService.h"
@@ -211,17 +210,16 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPlugins)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPermissions)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGeolocation)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mNotification)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBatteryManager)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBatteryPromise)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPowerManager)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mIccManager)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMobileMessageManager)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTelephony)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mInputPortManager)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mConnection)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStorageManager)
 #ifdef MOZ_B2G_RIL
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMobileConnections)
 #endif
 #ifdef MOZ_B2G_BT
@@ -287,21 +285,16 @@ Navigator::Invalidate()
     mPowerManager = nullptr;
   }
 
   if (mIccManager) {
     mIccManager->Shutdown();
     mIccManager = nullptr;
   }
 
-  if (mMobileMessageManager) {
-    mMobileMessageManager->Shutdown();
-    mMobileMessageManager = nullptr;
-  }
-
   if (mTelephony) {
     mTelephony = nullptr;
   }
 
   if (mInputPortManager) {
     mInputPortManager = nullptr;
   }
 
@@ -1619,31 +1612,16 @@ Navigator::RequestWakeLock(const nsAStri
   if (!pmService) {
     aRv.Throw(NS_ERROR_UNEXPECTED);
     return nullptr;
   }
 
   return pmService->NewWakeLock(aTopic, mWindow, aRv);
 }
 
-MobileMessageManager*
-Navigator::GetMozMobileMessage()
-{
-  if (!mMobileMessageManager) {
-    // Check that our window has not gone away
-    NS_ENSURE_TRUE(mWindow, nullptr);
-    NS_ENSURE_TRUE(mWindow->GetDocShell(), nullptr);
-
-    mMobileMessageManager = new MobileMessageManager(mWindow);
-    mMobileMessageManager->Init();
-  }
-
-  return mMobileMessageManager;
-}
-
 Telephony*
 Navigator::GetMozTelephony(ErrorResult& aRv)
 {
   if (!mTelephony) {
     if (!mWindow) {
       aRv.Throw(NS_ERROR_UNEXPECTED);
       return nullptr;
     }
--- a/dom/base/Navigator.h
+++ b/dom/base/Navigator.h
@@ -54,17 +54,16 @@ class Permissions;
 
 namespace battery {
 class BatteryManager;
 } // namespace battery
 
 class Promise;
 
 class DesktopNotificationCenter;
-class MobileMessageManager;
 class MozIdleObserver;
 #ifdef MOZ_GAMEPAD
 class Gamepad;
 class GamepadServiceTest;
 #endif // MOZ_GAMEPAD
 class NavigatorUserMediaSuccessCallback;
 class NavigatorUserMediaErrorCallback;
 class MozGetUserMediaDevicesSuccessCallback;
@@ -217,17 +216,16 @@ public:
                          ErrorResult& aRv);
 
   already_AddRefed<nsDOMDeviceStorage>
   GetDeviceStorageByNameAndType(const nsAString& aName, const nsAString& aType,
                                 ErrorResult& aRv);
 
   DesktopNotificationCenter* GetMozNotification(ErrorResult& aRv);
   IccManager* GetMozIccManager(ErrorResult& aRv);
-  MobileMessageManager* GetMozMobileMessage();
   Telephony* GetMozTelephony(ErrorResult& aRv);
   InputPortManager* GetInputPortManager(ErrorResult& aRv);
   already_AddRefed<LegacyMozTCPSocket> MozTCPSocket();
   network::Connection* GetConnection(ErrorResult& aRv);
   MediaDevices* GetMediaDevices(ErrorResult& aRv);
 
 #ifdef MOZ_B2G_RIL
   MobileConnectionArray* GetMozMobileConnections(ErrorResult& aRv);
@@ -322,17 +320,16 @@ private:
   RefPtr<nsPluginArray> mPlugins;
   RefPtr<Permissions> mPermissions;
   RefPtr<Geolocation> mGeolocation;
   RefPtr<DesktopNotificationCenter> mNotification;
   RefPtr<battery::BatteryManager> mBatteryManager;
   RefPtr<Promise> mBatteryPromise;
   RefPtr<PowerManager> mPowerManager;
   RefPtr<IccManager> mIccManager;
-  RefPtr<MobileMessageManager> mMobileMessageManager;
   RefPtr<Telephony> mTelephony;
   RefPtr<InputPortManager> mInputPortManager;
   RefPtr<network::Connection> mConnection;
 #ifdef MOZ_B2G_RIL
   RefPtr<MobileConnectionArray> mMobileConnections;
 #endif
 #ifdef MOZ_B2G_BT
   RefPtr<bluetooth::BluetoothManager> mBluetooth;
--- a/dom/bindings/Bindings.conf
+++ b/dom/bindings/Bindings.conf
@@ -681,20 +681,16 @@ DOMInterfaces = {
 'MozMobileConnectionArray': {
     'nativeType': 'mozilla::dom::MobileConnectionArray',
 },
 
 'MozMobileConnectionInfo': {
     'nativeType': 'mozilla::dom::MobileConnectionInfo',
 },
 
-'MozMobileMessageManager': {
-    'nativeType': 'mozilla::dom::MobileMessageManager',
-},
-
 'MozMobileNetworkInfo': {
     'nativeType': 'mozilla::dom::MobileNetworkInfo',
 },
 
 'MozSpeakerManager': {
     'nativeType': 'mozilla::dom::SpeakerManager',
     'headerFile': 'SpeakerManager.h'
 },
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -167,17 +167,16 @@
 
 #ifdef ACCESSIBILITY
 #include "nsAccessibilityService.h"
 #endif
 
 #include "mozilla/dom/File.h"
 #include "mozilla/dom/icc/IccChild.h"
 #include "mozilla/dom/mobileconnection/MobileConnectionChild.h"
-#include "mozilla/dom/mobilemessage/SmsChild.h"
 #include "mozilla/dom/devicestorage/DeviceStorageRequestChild.h"
 #include "mozilla/dom/bluetooth/PBluetoothChild.h"
 #include "mozilla/dom/PPresentationChild.h"
 #include "mozilla/dom/PresentationIPCService.h"
 #include "mozilla/ipc/InputStreamUtils.h"
 
 #ifdef MOZ_WEBSPEECH
 #include "mozilla/dom/PSpeechSynthesisChild.h"
@@ -203,17 +202,16 @@
 
 using namespace mozilla;
 using namespace mozilla::docshell;
 using namespace mozilla::dom::bluetooth;
 using namespace mozilla::dom::devicestorage;
 using namespace mozilla::dom::icc;
 using namespace mozilla::dom::ipc;
 using namespace mozilla::dom::mobileconnection;
-using namespace mozilla::dom::mobilemessage;
 using namespace mozilla::dom::telephony;
 using namespace mozilla::dom::workers;
 using namespace mozilla::media;
 using namespace mozilla::embedding;
 using namespace mozilla::gmp;
 using namespace mozilla::hal_sandbox;
 using namespace mozilla::ipc;
 using namespace mozilla::layers;
@@ -1972,29 +1970,16 @@ ContentChild::AllocPHandlerServiceChild(
 }
 
 bool ContentChild::DeallocPHandlerServiceChild(PHandlerServiceChild* aHandlerServiceChild)
 {
   static_cast<HandlerServiceChild*>(aHandlerServiceChild)->Release();
   return true;
 }
 
-PSmsChild*
-ContentChild::AllocPSmsChild()
-{
-  return new SmsChild();
-}
-
-bool
-ContentChild::DeallocPSmsChild(PSmsChild* aSms)
-{
-  delete aSms;
-  return true;
-}
-
 PTelephonyChild*
 ContentChild::AllocPTelephonyChild()
 {
   MOZ_CRASH("No one should be allocating PTelephonyChild actors");
 }
 
 bool
 ContentChild::DeallocPTelephonyChild(PTelephonyChild* aActor)
--- a/dom/ipc/ContentChild.h
+++ b/dom/ipc/ContentChild.h
@@ -330,20 +330,16 @@ public:
 
   virtual bool
   DeallocPExternalHelperAppChild(PExternalHelperAppChild *aService) override;
 
   virtual PHandlerServiceChild* AllocPHandlerServiceChild() override;
 
   virtual bool DeallocPHandlerServiceChild(PHandlerServiceChild*) override;
 
-  virtual PSmsChild* AllocPSmsChild() override;
-
-  virtual bool DeallocPSmsChild(PSmsChild*) override;
-
   virtual PTelephonyChild* AllocPTelephonyChild() override;
 
   virtual bool DeallocPTelephonyChild(PTelephonyChild*) override;
 
   virtual PMediaChild* AllocPMediaChild() override;
 
   virtual bool DeallocPMediaChild(PMediaChild* aActor) override;
 
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -56,17 +56,16 @@
 #include "mozilla/dom/PContentPermissionRequestParent.h"
 #include "mozilla/dom/PCycleCollectWithLogsParent.h"
 #include "mozilla/dom/PMemoryReportRequestParent.h"
 #include "mozilla/dom/ServiceWorkerRegistrar.h"
 #include "mozilla/dom/bluetooth/PBluetoothParent.h"
 #include "mozilla/dom/devicestorage/DeviceStorageRequestParent.h"
 #include "mozilla/dom/icc/IccParent.h"
 #include "mozilla/dom/mobileconnection/MobileConnectionParent.h"
-#include "mozilla/dom/mobilemessage/SmsParent.h"
 #include "mozilla/dom/power/PowerManagerService.h"
 #include "mozilla/dom/Permissions.h"
 #include "mozilla/dom/PresentationParent.h"
 #include "mozilla/dom/PPresentationParent.h"
 #include "mozilla/dom/PushNotifier.h"
 #include "mozilla/dom/FlyWebPublishedServerIPC.h"
 #include "mozilla/dom/quota/QuotaManagerService.h"
 #include "mozilla/dom/telephony/TelephonyParent.h"
@@ -287,17 +286,16 @@ using mozilla::ProfileGatherer;
 #ifdef MOZ_CRASHREPORTER
 using namespace CrashReporter;
 #endif
 using namespace mozilla::dom::bluetooth;
 using namespace mozilla::dom::devicestorage;
 using namespace mozilla::dom::icc;
 using namespace mozilla::dom::power;
 using namespace mozilla::dom::mobileconnection;
-using namespace mozilla::dom::mobilemessage;
 using namespace mozilla::dom::telephony;
 using namespace mozilla::media;
 using namespace mozilla::embedding;
 using namespace mozilla::gfx;
 using namespace mozilla::gmp;
 using namespace mozilla::hal;
 using namespace mozilla::ipc;
 using namespace mozilla::layers;
@@ -3427,35 +3425,16 @@ ContentParent::AllocPHandlerServiceParen
 
 bool
 ContentParent::DeallocPHandlerServiceParent(PHandlerServiceParent* aHandlerServiceParent)
 {
   static_cast<HandlerServiceParent*>(aHandlerServiceParent)->Release();
   return true;
 }
 
-PSmsParent*
-ContentParent::AllocPSmsParent()
-{
-  if (!AssertAppProcessPermission(this, "sms")) {
-    return nullptr;
-  }
-
-  SmsParent* parent = new SmsParent();
-  parent->AddRef();
-  return parent;
-}
-
-bool
-ContentParent::DeallocPSmsParent(PSmsParent* aSms)
-{
-  static_cast<SmsParent*>(aSms)->Release();
-  return true;
-}
-
 PTelephonyParent*
 ContentParent::AllocPTelephonyParent()
 {
   if (!AssertAppProcessPermission(this, "telephony")) {
     return nullptr;
   }
 
   TelephonyParent* actor = new TelephonyParent();
--- a/dom/ipc/ContentParent.h
+++ b/dom/ipc/ContentParent.h
@@ -838,20 +838,16 @@ private:
 
   virtual bool
   DeallocPExternalHelperAppParent(PExternalHelperAppParent* aService) override;
 
   virtual PHandlerServiceParent* AllocPHandlerServiceParent() override;
 
   virtual bool DeallocPHandlerServiceParent(PHandlerServiceParent*) override;
 
-  virtual PSmsParent* AllocPSmsParent() override;
-
-  virtual bool DeallocPSmsParent(PSmsParent*) override;
-
   virtual PTelephonyParent* AllocPTelephonyParent() override;
 
   virtual bool DeallocPTelephonyParent(PTelephonyParent*) override;
 
   virtual PMediaParent* AllocPMediaParent() override;
 
   virtual bool DeallocPMediaParent(PMediaParent* aActor) override;
 
--- a/dom/ipc/PContent.ipdl
+++ b/dom/ipc/PContent.ipdl
@@ -37,17 +37,16 @@ include protocol PGMPService;
 include protocol PPluginModule;
 include protocol PGMP;
 include protocol PPrinting;
 include protocol PSendStream;
 include protocol POfflineCacheUpdate;
 include protocol PRenderFrame;
 include protocol PScreenManager;
 include protocol PSharedBufferManager;
-include protocol PSms;
 include protocol PSpeechSynthesis;
 include protocol PStorage;
 include protocol PTelephony;
 include protocol PTestShell;
 include protocol PJavaScript;
 include protocol PRemoteSpellcheckEngine;
 include protocol PWebBrowserPersistDocument;
 include protocol PWebrtcGlobal;
@@ -366,17 +365,16 @@ nested(upto inside_cpow) sync protocol P
     manages PMedia;
     manages PMemoryReportRequest;
     manages PMobileConnection;
     manages PNecko;
     manages POfflineCacheUpdate;
     manages PPrinting;
     manages PSendStream;
     manages PScreenManager;
-    manages PSms;
     manages PSpeechSynthesis;
     manages PStorage;
     manages PTelephony;
     manages PTestShell;
     manages PJavaScript;
     manages PRemoteSpellcheckEngine;
     manages PWebBrowserPersistDocument;
     manages PWebrtcGlobal;
@@ -812,18 +810,16 @@ parent:
 
     async PSendStream();
 
     nested(inside_sync) sync PScreenManager()
         returns (uint32_t numberOfScreens,
                  float systemDefaultScale,
                  bool success);
 
-    async PSms();
-
     async PSpeechSynthesis();
 
     nested(inside_cpow) async PStorage();
 
     async PTelephony();
 
     async PMedia();
 
--- a/dom/ipc/moz.build
+++ b/dom/ipc/moz.build
@@ -127,17 +127,16 @@ LOCAL_INCLUDES += [
     '/dom/base',
     '/dom/bluetooth/common',
     '/dom/bluetooth/ipc',
     '/dom/devicestorage',
     '/dom/events',
     '/dom/filesystem',
     '/dom/geolocation',
     '/dom/media/webspeech/synth/ipc',
-    '/dom/mobilemessage/ipc',
     '/dom/security',
     '/dom/storage',
     '/dom/workers',
     '/embedding/components/printingui/ipc',
     '/extensions/cookie',
     '/extensions/spellcheck/src',
     '/gfx/2d',
     '/hal/sandbox',
deleted file mode 100644
--- a/dom/mobilemessage/Assertions.cpp
+++ /dev/null
@@ -1,47 +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/. */
-
-#include "mozilla/dom/MozMobileMessageManagerBinding.h"
-#include "nsISmsService.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-#define ASSERT_SMS_EQUALITY(webidlType, webidlState, xpidlState) \
-  static_assert(static_cast<uint32_t>(webidlType::webidlState) == nsISmsService::xpidlState, \
-  #webidlType "::" #webidlState " should equal to nsISmsService::" #xpidlState)
-
-/**
- * Enum TypeOfNumber
- */
-#define ASSERT_SMS_TYPE_OF_NUMBER_EQUALITY(webidlState, xpidlState) \
-  ASSERT_SMS_EQUALITY(TypeOfNumber, webidlState, xpidlState)
-
-ASSERT_SMS_TYPE_OF_NUMBER_EQUALITY(Unknown, TYPE_OF_NUMBER_UNKNOWN);
-ASSERT_SMS_TYPE_OF_NUMBER_EQUALITY(International, TYPE_OF_NUMBER_INTERNATIONAL);
-ASSERT_SMS_TYPE_OF_NUMBER_EQUALITY(National, TYPE_OF_NUMBER_NATIONAL);
-ASSERT_SMS_TYPE_OF_NUMBER_EQUALITY(Network_specific, TYPE_OF_NUMBER_NETWORK_SPECIFIC);
-ASSERT_SMS_TYPE_OF_NUMBER_EQUALITY(Dedicated_access_short_code, TYPE_OF_NUMBER_DEDICATED_ACCESS_SHORT_CODE);
-
-#undef ASSERT_SMS_TYPE_OF_NUMBER_EQUALITY
-
-/**
- * Enum NumberPlanIdentification
- */
-#define ASSERT_SMS_NUMBER_PLAN_IDENTIFICATION_EQUALITY(webidlState, xpidlState) \
-  ASSERT_SMS_EQUALITY(NumberPlanIdentification, webidlState, xpidlState)
-
-ASSERT_SMS_NUMBER_PLAN_IDENTIFICATION_EQUALITY(Unknown, NUMBER_PLAN_IDENTIFICATION_UNKNOWN);
-ASSERT_SMS_NUMBER_PLAN_IDENTIFICATION_EQUALITY(Isdn, NUMBER_PLAN_IDENTIFICATION_ISDN);
-ASSERT_SMS_NUMBER_PLAN_IDENTIFICATION_EQUALITY(Data, NUMBER_PLAN_IDENTIFICATION_DATA);
-ASSERT_SMS_NUMBER_PLAN_IDENTIFICATION_EQUALITY(Telex, NUMBER_PLAN_IDENTIFICATION_TELEX);
-ASSERT_SMS_NUMBER_PLAN_IDENTIFICATION_EQUALITY(National, NUMBER_PLAN_IDENTIFICATION_NATIONAL);
-ASSERT_SMS_NUMBER_PLAN_IDENTIFICATION_EQUALITY(Private, NUMBER_PLAN_IDENTIFICATION_PRIVATE);
-
-#undef ASSERT_SMS_EQUALITY
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/Constants.cpp
+++ /dev/null
@@ -1,25 +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/. */
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-const char* kSmsReceivedObserverTopic        = "sms-received";
-const char* kSmsRetrievingObserverTopic      = "sms-retrieving";
-const char* kSmsSendingObserverTopic         = "sms-sending";
-const char* kSmsSentObserverTopic            = "sms-sent";
-const char* kSmsFailedObserverTopic          = "sms-failed";
-const char* kSmsDeliverySuccessObserverTopic = "sms-delivery-success";
-const char* kSmsDeliveryErrorObserverTopic   = "sms-delivery-error";
-const char* kSilentSmsReceivedObserverTopic  = "silent-sms-received";
-const char* kSmsReadSuccessObserverTopic     = "sms-read-success";
-const char* kSmsReadErrorObserverTopic       = "sms-read-error";
-const char* kSmsDeletedObserverTopic         = "sms-deleted";
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/Constants.h
+++ /dev/null
@@ -1,58 +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_mobilemessage_Constants_h
-#define mozilla_dom_mobilemessage_Constants_h
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-// Defined in the .cpp.
-extern const char* kSmsReceivedObserverTopic;
-extern const char* kSmsRetrievingObserverTopic;
-extern const char* kSmsSendingObserverTopic;
-extern const char* kSmsSentObserverTopic;
-extern const char* kSmsFailedObserverTopic;
-extern const char* kSmsDeliverySuccessObserverTopic;
-extern const char* kSmsDeliveryErrorObserverTopic;
-extern const char* kSilentSmsReceivedObserverTopic;
-extern const char* kSmsReadSuccessObserverTopic;
-extern const char* kSmsReadErrorObserverTopic;
-extern const char* kSmsDeletedObserverTopic;
-
-#define DELIVERY_RECEIVED       NS_LITERAL_STRING("received")
-#define DELIVERY_SENDING        NS_LITERAL_STRING("sending")
-#define DELIVERY_SENT           NS_LITERAL_STRING("sent")
-#define DELIVERY_ERROR          NS_LITERAL_STRING("error")
-#define DELIVERY_NOT_DOWNLOADED NS_LITERAL_STRING("not-downloaded")
-
-#define DELIVERY_STATUS_NOT_APPLICABLE NS_LITERAL_STRING("not-applicable")
-#define DELIVERY_STATUS_SUCCESS        NS_LITERAL_STRING("success")
-#define DELIVERY_STATUS_PENDING        NS_LITERAL_STRING("pending")
-#define DELIVERY_STATUS_ERROR          NS_LITERAL_STRING("error")
-#define DELIVERY_STATUS_REJECTED       NS_LITERAL_STRING("rejected")
-#define DELIVERY_STATUS_MANUAL         NS_LITERAL_STRING("manual")
-
-#define READ_STATUS_NOT_APPLICABLE NS_LITERAL_STRING("not-applicable")
-#define READ_STATUS_SUCCESS        NS_LITERAL_STRING("success")
-#define READ_STATUS_PENDING        NS_LITERAL_STRING("pending")
-#define READ_STATUS_ERROR          NS_LITERAL_STRING("error")
-
-#define MESSAGE_CLASS_NORMAL  NS_LITERAL_STRING("normal")
-#define MESSAGE_CLASS_CLASS_0 NS_LITERAL_STRING("class-0")
-#define MESSAGE_CLASS_CLASS_1 NS_LITERAL_STRING("class-1")
-#define MESSAGE_CLASS_CLASS_2 NS_LITERAL_STRING("class-2")
-#define MESSAGE_CLASS_CLASS_3 NS_LITERAL_STRING("class-3")
-
-#define MESSAGE_TYPE_SMS NS_LITERAL_STRING("sms")
-#define MESSAGE_TYPE_MMS NS_LITERAL_STRING("mms")
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_Constants_h
deleted file mode 100644
--- a/dom/mobilemessage/DOMMobileMessageError.cpp
+++ /dev/null
@@ -1,74 +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 "DOMMobileMessageError.h"
-#include "mozilla/dom/DOMMobileMessageErrorBinding.h"
-#include "MmsMessage.h"
-#include "SmsMessage.h"
-
-namespace mozilla {
-namespace dom {
-
-NS_IMPL_CYCLE_COLLECTION_CLASS(DOMMobileMessageError)
-
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(DOMMobileMessageError, DOMError)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mSms)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mMms)
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(DOMMobileMessageError, DOMError)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSms)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMms)
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(DOMMobileMessageError)
-NS_INTERFACE_MAP_END_INHERITING(DOMError)
-
-NS_IMPL_ADDREF_INHERITED(DOMMobileMessageError, DOMError)
-NS_IMPL_RELEASE_INHERITED(DOMMobileMessageError, DOMError)
-
-DOMMobileMessageError::DOMMobileMessageError(nsPIDOMWindowInner* aWindow,
-                                             const nsAString& aName,
-                                             SmsMessage* aSms)
-  : DOMError(aWindow, aName)
-  , mSms(aSms)
-  , mMms(nullptr)
-{
-}
-
-DOMMobileMessageError::DOMMobileMessageError(nsPIDOMWindowInner* aWindow,
-                                             const nsAString& aName,
-                                             MmsMessage* aMms)
-  : DOMError(aWindow, aName)
-  , mSms(nullptr)
-  , mMms(aMms)
-{
-}
-
-void
-DOMMobileMessageError::GetData(OwningSmsMessageOrMmsMessage& aRetVal) const
-{
-  if (mSms) {
-    aRetVal.SetAsSmsMessage() = mSms;
-    return;
-  }
-
-  if (mMms) {
-    aRetVal.SetAsMmsMessage() = mMms;
-    return;
-  }
-
-  MOZ_CRASH("Bad object with invalid mSms and mMms.");
-}
-
-JSObject*
-DOMMobileMessageError::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
-{
-  return DOMMobileMessageErrorBinding::Wrap(aCx, this, aGivenProto);
-}
-
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/DOMMobileMessageError.h
+++ /dev/null
@@ -1,46 +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_MobileMessageError_h
-#define mozilla_dom_MobileMessageError_h
-
-#include "mozilla/dom/DOMError.h"
-
-namespace mozilla {
-namespace dom {
-
-class MmsMessage;
-class OwningSmsMessageOrMmsMessage;
-class SmsMessage;
-
-class DOMMobileMessageError final : public DOMError
-{
-public:
-  NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(DOMMobileMessageError, DOMError)
-
-  DOMMobileMessageError(nsPIDOMWindowInner* aWindow, const nsAString& aName,
-                        SmsMessage* aSms);
-
-  DOMMobileMessageError(nsPIDOMWindowInner* aWindow, const nsAString& aName,
-                        MmsMessage* aMms);
-
-  virtual JSObject*
-  WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
-
-  void GetData(OwningSmsMessageOrMmsMessage& aRetVal) const;
-
-private:
-  ~DOMMobileMessageError() {}
-
-  RefPtr<SmsMessage> mSms;
-  RefPtr<MmsMessage> mMms;
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_MobileMessageError_h
deleted file mode 100644
--- a/dom/mobilemessage/DeletedMessageInfo.cpp
+++ /dev/null
@@ -1,123 +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 "DeletedMessageInfo.h"
-#include "nsComponentManagerUtils.h"    // for do_CreateInstance
-#include "nsVariant.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-NS_IMPL_ISUPPORTS(DeletedMessageInfo, nsIDeletedMessageInfo)
-
-DeletedMessageInfo::DeletedMessageInfo(const DeletedMessageInfoData& aData)
-  : mData(aData)
-{
-}
-
-DeletedMessageInfo::DeletedMessageInfo(int32_t* aMessageIds,
-                                       uint32_t aMsgCount,
-                                       uint64_t* aThreadIds,
-                                       uint32_t  aThreadCount)
-{
-  mData.deletedMessageIds().AppendElements(aMessageIds, aMsgCount);
-  mData.deletedThreadIds().AppendElements(aThreadIds, aThreadCount);
-}
-
-DeletedMessageInfo::~DeletedMessageInfo()
-{
-}
-
-/* static */ nsresult
-DeletedMessageInfo::Create(int32_t* aMessageIds,
-                           uint32_t aMsgCount,
-                           uint64_t* aThreadIds,
-                           uint32_t  aThreadCount,
-                           nsIDeletedMessageInfo** aDeletedInfo)
-{
-  NS_ENSURE_ARG_POINTER(aDeletedInfo);
-  NS_ENSURE_TRUE(aMsgCount || aThreadCount, NS_ERROR_INVALID_ARG);
-
-  nsCOMPtr<nsIDeletedMessageInfo> deletedInfo =
-    new DeletedMessageInfo(aMessageIds,
-                           aMsgCount,
-                           aThreadIds,
-                           aThreadCount);
-  deletedInfo.forget(aDeletedInfo);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-DeletedMessageInfo::GetDeletedMessageIds(nsIVariant** aDeletedMessageIds)
-{
-  NS_ENSURE_ARG_POINTER(aDeletedMessageIds);
-
-  if (mDeletedMessageIds) {
-    NS_ADDREF(*aDeletedMessageIds = mDeletedMessageIds);
-    return NS_OK;
-  }
-
-  uint32_t length = mData.deletedMessageIds().Length();
-
-  if (length == 0) {
-    *aDeletedMessageIds = nullptr;
-    return NS_OK;
-  }
-
-  mDeletedMessageIds = new nsVariant();
-
-  nsresult rv;
-  rv = mDeletedMessageIds->SetAsArray(nsIDataType::VTYPE_INT32,
-                                      nullptr,
-                                      length,
-                                      mData.deletedMessageIds().Elements());
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  mDeletedMessageIds->SetWritable(false);
-
-  NS_ADDREF(*aDeletedMessageIds = mDeletedMessageIds);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-DeletedMessageInfo::GetDeletedThreadIds(nsIVariant** aDeletedThreadIds)
-{
-  NS_ENSURE_ARG_POINTER(aDeletedThreadIds);
-
-  if (mDeletedThreadIds) {
-    NS_ADDREF(*aDeletedThreadIds = mDeletedThreadIds);
-    return NS_OK;
-  }
-
-  uint32_t length = mData.deletedThreadIds().Length();
-
-  if (length == 0) {
-    *aDeletedThreadIds = nullptr;
-    return NS_OK;
-  }
-
-  mDeletedThreadIds = new nsVariant();
-
-  nsresult rv;
-  rv = mDeletedThreadIds->SetAsArray(nsIDataType::VTYPE_UINT64,
-                                     nullptr,
-                                     length,
-                                     mData.deletedThreadIds().Elements());
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  mDeletedThreadIds->SetWritable(false);
-
-  NS_ADDREF(*aDeletedThreadIds = mDeletedThreadIds);
-
-  return NS_OK;
-}
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/DeletedMessageInfo.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_mobilemessage_DeletedMessageInfo_h
-#define mozilla_dom_mobilemessage_DeletedMessageInfo_h
-
-#include "mozilla/dom/mobilemessage/SmsTypes.h"
-#include "nsIDeletedMessageInfo.h"
-
-class nsIWritableVariant;
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-class DeletedMessageInfo final : public nsIDeletedMessageInfo
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIDELETEDMESSAGEINFO
-
-  explicit DeletedMessageInfo(const DeletedMessageInfoData& aData);
-
-  DeletedMessageInfo(int32_t* aMessageIds,
-                     uint32_t aMsgCount,
-                     uint64_t* aThreadIds,
-                     uint32_t  aThreadCount);
-
-  static nsresult Create(int32_t* aMessageIds,
-                         uint32_t aMsgCount,
-                         uint64_t* aThreadIds,
-                         uint32_t  aThreadCount,
-                         nsIDeletedMessageInfo** aDeletedInfo);
-
-  const DeletedMessageInfoData& GetData() const { return mData; }
-
-private:
-  // Don't try to use the default constructor.
-  DeletedMessageInfo();
-
-  ~DeletedMessageInfo();
-
-  DeletedMessageInfoData mData;
-
-  nsCOMPtr<nsIWritableVariant> mDeletedMessageIds;
-  nsCOMPtr<nsIWritableVariant> mDeletedThreadIds;
-
-protected:
-  /* additional members */
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_DeletedMessageInfo_h
deleted file mode 100644
--- a/dom/mobilemessage/MmsMessage.cpp
+++ /dev/null
@@ -1,163 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* 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 "MmsMessage.h"
-
-#include "MmsMessageInternal.h"
-#include "mozilla/dom/MmsMessageBinding.h"
-#include "nsPIDOMWindow.h"
-
-using namespace mozilla::dom::mobilemessage;
-
-namespace mozilla {
-namespace dom {
-
-NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(MmsMessage, mWindow, mMessage)
-NS_IMPL_CYCLE_COLLECTING_ADDREF(MmsMessage)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(MmsMessage)
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MmsMessage)
-  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
-  NS_INTERFACE_MAP_ENTRY(nsISupports)
-NS_INTERFACE_MAP_END
-
-MmsMessage::MmsMessage(nsPIDOMWindowInner* aWindow, MmsMessageInternal* aMessage)
-  : mWindow(aWindow)
-  , mMessage(aMessage)
-{
-}
-
-MmsMessage::~MmsMessage()
-{
-}
-
-JSObject*
-MmsMessage::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
-{
-  return MmsMessageBinding::Wrap(aCx, this, aGivenProto);
-}
-
-void
-MmsMessage::GetType(nsString& aRetVal) const
-{
-  mMessage->GetType(aRetVal);
-}
-
-int32_t
-MmsMessage::Id() const
-{
-  int32_t id;
-  mMessage->GetId(&id);
-  return id;
-}
-
-uint64_t
-MmsMessage::ThreadId() const
-{
-  uint64_t id;
-  mMessage->GetThreadId(&id);
-  return id;
-}
-
-void
-MmsMessage::GetIccId(nsString& aRetVal) const
-{
-  mMessage->GetIccId(aRetVal);
-}
-
-void
-MmsMessage::GetDelivery(nsString& aRetVal) const
-{
-  mMessage->GetDelivery(aRetVal);
-}
-
-void
-MmsMessage::GetDeliveryInfo(nsTArray<MmsDeliveryInfo>& aRetVal) const
-{
-  aRetVal = mMessage->mDeliveryInfo;
-}
-
-void
-MmsMessage::GetSender(nsString& aRetVal) const
-{
-  mMessage->GetSender(aRetVal);
-}
-
-void
-MmsMessage::GetReceivers(nsTArray<nsString>& aRetVal) const
-{
-  aRetVal = mMessage->mReceivers;
-}
-
-uint64_t
-MmsMessage::Timestamp() const
-{
-  uint64_t timestamp;
-  mMessage->GetTimestamp(&timestamp);
-  return timestamp;
-}
-
-uint64_t
-MmsMessage::SentTimestamp() const
-{
-  uint64_t timestamp;
-  mMessage->GetSentTimestamp(&timestamp);
-  return timestamp;
-}
-
-bool
-MmsMessage::Read() const
-{
-  bool read;
-  mMessage->GetRead(&read);
-  return read;
-}
-
-void
-MmsMessage::GetSubject(nsString& aRetVal) const
-{
-  mMessage->GetSubject(aRetVal);
-}
-
-void
-MmsMessage::GetSmil(nsString& aRetVal) const
-{
-  mMessage->GetSmil(aRetVal);
-}
-
-void
-MmsMessage::GetAttachments(nsTArray<MmsAttachment>& aRetVal) const
-{
-  uint32_t length = mMessage->mAttachments.Length();
-
-  // Duplicating the Blob with the correct parent object.
-  for (uint32_t i = 0; i < length; i++) {
-    MmsAttachment attachment;
-    const MmsAttachment &element = mMessage->mAttachments[i];
-    attachment.mId = element.mId;
-    attachment.mLocation = element.mLocation;
-    attachment.mContent = Blob::Create(mWindow, element.mContent->Impl());
-    aRetVal.AppendElement(attachment);
-  }
-}
-
-uint64_t
-MmsMessage::ExpiryDate() const
-{
-  uint64_t date;
-  mMessage->GetExpiryDate(&date);
-  return date;
-}
-
-bool
-MmsMessage::ReadReportRequested() const
-{
-  bool reportRequested;
-  mMessage->GetReadReportRequested(&reportRequested);
-  return reportRequested;
-}
-
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/MmsMessage.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* 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_MmsMessage_h
-#define mozilla_dom_MmsMessage_h
-
-#include "mozilla/dom/BindingDeclarations.h"
-#include "nsWrapperCache.h"
-
-class nsPIDOMWindowInner;
-
-namespace mozilla {
-namespace dom {
-
-namespace mobilemessage {
-class MmsMessageInternal;
-} // namespace mobilemessage
-
-struct MmsAttachment;
-struct MmsDeliveryInfo;
-
-class MmsMessage final : public nsISupports,
-                         public nsWrapperCache
-{
-public:
-  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(MmsMessage)
-
-  MmsMessage(nsPIDOMWindowInner* aWindow,
-             mobilemessage::MmsMessageInternal* aMessage);
-
-  nsPIDOMWindowInner*
-  GetParentObject() const
-  {
-    return mWindow;
-  }
-
-  virtual JSObject*
-  WrapObject(JSContext* aCx,
-             JS::Handle<JSObject*> aGivenProto) override;
-
-  void
-  GetType(nsString& aRetVal) const;
-
-  int32_t
-  Id() const;
-
-  uint64_t
-  ThreadId() const;
-
-  void
-  GetIccId(nsString& aRetVal) const;
-
-  void
-  GetDelivery(nsString& aRetVal) const;
-
-  void
-  GetDeliveryInfo(nsTArray<MmsDeliveryInfo>& aRetVal) const;
-
-  void
-  GetSender(nsString& aRetVal) const;
-
-  void
-  GetReceivers(nsTArray<nsString>& aRetVal) const;
-
-  uint64_t
-  Timestamp() const;
-
-  uint64_t
-  SentTimestamp() const;
-
-  bool
-  Read() const;
-
-  void
-  GetSubject(nsString& aRetVal) const;
-
-  void
-  GetSmil(nsString& aRetVal) const;
-
-  void
-  GetAttachments(nsTArray<MmsAttachment>& aRetVal) const;
-
-  uint64_t
-  ExpiryDate() const;
-
-  bool
-  ReadReportRequested() const;
-
-private:
-  // Don't try to use the default constructor.
-  MmsMessage() = delete;
-
-  ~MmsMessage();
-
-  nsCOMPtr<nsPIDOMWindowInner> mWindow;
-  RefPtr<mobilemessage::MmsMessageInternal> mMessage;
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_MmsMessage_h
deleted file mode 100644
--- a/dom/mobilemessage/MmsMessageInternal.cpp
+++ /dev/null
@@ -1,614 +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 "MmsMessageInternal.h"
-
-#include "nsIDOMClassInfo.h"
-#include "jsapi.h" // For JS_IsArrayObject, JS_GetElement, etc.
-#include "nsJSUtils.h"
-#include "nsContentUtils.h"
-#include "nsTArrayHelpers.h"
-#include "mozilla/dom/ContentParent.h"
-#include "mozilla/dom/File.h"
-#include "mozilla/dom/mobilemessage/Constants.h" // For MessageType
-#include "mozilla/dom/mobilemessage/SmsTypes.h"
-#include "mozilla/dom/ScriptSettings.h"
-#include "mozilla/dom/ToJSValue.h"
-#include "mozilla/dom/ipc/BlobChild.h"
-#include "mozilla/dom/ipc/BlobParent.h"
-
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-NS_IMPL_CYCLE_COLLECTION_CLASS(MmsMessageInternal)
-
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(MmsMessageInternal)
-  for (uint32_t i = 0; i < tmp->mAttachments.Length(); i++) {
-    NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAttachments[i].mContent)
-  }
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(MmsMessageInternal)
-  for (uint32_t i = 0; i < tmp->mAttachments.Length(); i++) {
-    NS_IMPL_CYCLE_COLLECTION_UNLINK(mAttachments[i].mContent)
-  }
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MmsMessageInternal)
-  NS_INTERFACE_MAP_ENTRY(nsIMmsMessage)
-  NS_INTERFACE_MAP_ENTRY(nsISupports)
-NS_INTERFACE_MAP_END
-
-NS_IMPL_CYCLE_COLLECTING_ADDREF(MmsMessageInternal)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(MmsMessageInternal)
-
-MmsMessageInternal::MmsMessageInternal(int32_t                          aId,
-                                       uint64_t                         aThreadId,
-                                       const nsAString&                 aIccId,
-                                       DeliveryState                    aDelivery,
-                                       const nsTArray<MmsDeliveryInfo>& aDeliveryInfo,
-                                       const nsAString&                 aSender,
-                                       const nsTArray<nsString>&        aReceivers,
-                                       uint64_t                         aTimestamp,
-                                       uint64_t                         aSentTimestamp,
-                                       bool                             aRead,
-                                       const nsAString&                 aSubject,
-                                       const nsAString&                 aSmil,
-                                       const nsTArray<MmsAttachment>&   aAttachments,
-                                       uint64_t                         aExpiryDate,
-                                       bool                             aReadReportRequested)
-  : mId(aId),
-    mThreadId(aThreadId),
-    mIccId(aIccId),
-    mDelivery(aDelivery),
-    mDeliveryInfo(aDeliveryInfo),
-    mSender(aSender),
-    mReceivers(aReceivers),
-    mTimestamp(aTimestamp),
-    mSentTimestamp(aSentTimestamp),
-    mRead(aRead),
-    mSubject(aSubject),
-    mSmil(aSmil),
-    mAttachments(aAttachments),
-    mExpiryDate(aExpiryDate),
-    mReadReportRequested(aReadReportRequested)
-{
-}
-
-MmsMessageInternal::MmsMessageInternal(const MmsMessageData& aData)
-  : mId(aData.id())
-  , mThreadId(aData.threadId())
-  , mIccId(aData.iccId())
-  , mDelivery(aData.delivery())
-  , mSender(aData.sender())
-  , mReceivers(aData.receivers())
-  , mTimestamp(aData.timestamp())
-  , mSentTimestamp(aData.sentTimestamp())
-  , mRead(aData.read())
-  , mSubject(aData.subject())
-  , mSmil(aData.smil())
-  , mExpiryDate(aData.expiryDate())
-  , mReadReportRequested(aData.readReportRequested())
-{
-  uint32_t len = aData.attachments().Length();
-  mAttachments.SetCapacity(len);
-  for (uint32_t i = 0; i < len; i++) {
-    MmsAttachment att;
-    const MmsAttachmentData &element = aData.attachments()[i];
-    att.mId = element.id();
-    att.mLocation = element.location();
-
-    // mContent is not going to be exposed to JS directly so we can use
-    // nullptr as parent.
-    if (element.contentParent()) {
-      RefPtr<BlobImpl> impl = static_cast<BlobParent*>(element.contentParent())->GetBlobImpl();
-      att.mContent = Blob::Create(nullptr, impl);
-    } else if (element.contentChild()) {
-      RefPtr<BlobImpl> impl = static_cast<BlobChild*>(element.contentChild())->GetBlobImpl();
-      att.mContent = Blob::Create(nullptr, impl);
-    } else {
-      NS_WARNING("MmsMessage: Unable to get attachment content.");
-    }
-    mAttachments.AppendElement(att);
-  }
-
-  len = aData.deliveryInfo().Length();
-  mDeliveryInfo.SetCapacity(len);
-  for (uint32_t i = 0; i < len; i++) {
-    MmsDeliveryInfo info;
-    const MmsDeliveryInfoData &infoData = aData.deliveryInfo()[i];
-
-    // Prepare |info.mReceiver|.
-    info.mReceiver = infoData.receiver();
-
-    // Prepare |info.mDeliveryStatus|.
-    nsString statusStr;
-    switch (infoData.deliveryStatus()) {
-      case eDeliveryStatus_NotApplicable:
-        statusStr = DELIVERY_STATUS_NOT_APPLICABLE;
-        break;
-      case eDeliveryStatus_Success:
-        statusStr = DELIVERY_STATUS_SUCCESS;
-        break;
-      case eDeliveryStatus_Pending:
-        statusStr = DELIVERY_STATUS_PENDING;
-        break;
-      case eDeliveryStatus_Error:
-        statusStr = DELIVERY_STATUS_ERROR;
-        break;
-      case eDeliveryStatus_Reject:
-        statusStr = DELIVERY_STATUS_REJECTED;
-        break;
-      case eDeliveryStatus_Manual:
-        statusStr = DELIVERY_STATUS_MANUAL;
-        break;
-      case eDeliveryStatus_EndGuard:
-      default:
-        MOZ_CRASH("We shouldn't get any other delivery status!");
-    }
-    info.mDeliveryStatus = statusStr;
-
-    // Prepare |info.mDeliveryTimestamp|.
-    info.mDeliveryTimestamp = infoData.deliveryTimestamp();
-
-    // Prepare |info.mReadStatus|.
-    nsString statusReadString;
-    switch(infoData.readStatus()) {
-      case eReadStatus_NotApplicable:
-        statusReadString = READ_STATUS_NOT_APPLICABLE;
-        break;
-      case eReadStatus_Success:
-        statusReadString = READ_STATUS_SUCCESS;
-        break;
-      case eReadStatus_Pending:
-        statusReadString = READ_STATUS_PENDING;
-        break;
-      case eReadStatus_Error:
-        statusReadString = READ_STATUS_ERROR;
-        break;
-      case eReadStatus_EndGuard:
-      default:
-        MOZ_CRASH("We shouldn't get any other read status!");
-    }
-    info.mReadStatus = statusReadString;
-
-    // Prepare |info.mReadTimestamp|.
-    info.mReadTimestamp = infoData.readTimestamp();
-
-    mDeliveryInfo.AppendElement(info);
-  }
-}
-
-/* static */ nsresult
-MmsMessageInternal::Create(int32_t aId,
-                           uint64_t aThreadId,
-                           const nsAString& aIccId,
-                           const nsAString& aDelivery,
-                           const JS::Value& aDeliveryInfo,
-                           const nsAString& aSender,
-                           const JS::Value& aReceivers,
-                           uint64_t aTimestamp,
-                           uint64_t aSentTimestamp,
-                           bool aRead,
-                           const nsAString& aSubject,
-                           const nsAString& aSmil,
-                           const JS::Value& aAttachments,
-                           uint64_t aExpiryDate,
-                           bool aIsReadReportRequested,
-                           JSContext* aCx,
-                           nsIMmsMessage** aMessage)
-{
-  *aMessage = nullptr;
-
-  // Set |delivery|.
-  DeliveryState delivery;
-  if (aDelivery.Equals(DELIVERY_SENT)) {
-    delivery = eDeliveryState_Sent;
-  } else if (aDelivery.Equals(DELIVERY_RECEIVED)) {
-    delivery = eDeliveryState_Received;
-  } else if (aDelivery.Equals(DELIVERY_SENDING)) {
-    delivery = eDeliveryState_Sending;
-  } else if (aDelivery.Equals(DELIVERY_NOT_DOWNLOADED)) {
-    delivery = eDeliveryState_NotDownloaded;
-  } else if (aDelivery.Equals(DELIVERY_ERROR)) {
-    delivery = eDeliveryState_Error;
-  } else {
-    return NS_ERROR_INVALID_ARG;
-  }
-
-  // Set |deliveryInfo|.
-  if (!aDeliveryInfo.isObject()) {
-    return NS_ERROR_INVALID_ARG;
-  }
-  JS::Rooted<JSObject*> deliveryInfoObj(aCx, &aDeliveryInfo.toObject());
-  bool isArray;
-  if (!JS_IsArrayObject(aCx, deliveryInfoObj, &isArray)) {
-    return NS_ERROR_FAILURE;
-  }
-  if (!isArray) {
-    return NS_ERROR_INVALID_ARG;
-  }
-
-  uint32_t length;
-  MOZ_ALWAYS_TRUE(JS_GetArrayLength(aCx, deliveryInfoObj, &length));
-
-  nsTArray<MmsDeliveryInfo> deliveryInfo;
-  JS::Rooted<JS::Value> infoJsVal(aCx);
-  for (uint32_t i = 0; i < length; ++i) {
-    if (!JS_GetElement(aCx, deliveryInfoObj, i, &infoJsVal) ||
-        !infoJsVal.isObject()) {
-      return NS_ERROR_INVALID_ARG;
-    }
-
-    MmsDeliveryInfo info;
-    if (!info.Init(aCx, infoJsVal)) {
-      return NS_ERROR_TYPE_ERR;
-    }
-
-    deliveryInfo.AppendElement(info);
-  }
-
-  // Set |receivers|.
-  if (!aReceivers.isObject()) {
-    return NS_ERROR_INVALID_ARG;
-  }
-  JS::Rooted<JSObject*> receiversObj(aCx, &aReceivers.toObject());
-  if (!JS_IsArrayObject(aCx, receiversObj, &isArray)) {
-    return NS_ERROR_FAILURE;
-  }
-  if (!isArray) {
-    return NS_ERROR_INVALID_ARG;
-  }
-
-  MOZ_ALWAYS_TRUE(JS_GetArrayLength(aCx, receiversObj, &length));
-
-  nsTArray<nsString> receivers;
-  JS::Rooted<JS::Value> receiverJsVal(aCx);
-  for (uint32_t i = 0; i < length; ++i) {
-    if (!JS_GetElement(aCx, receiversObj, i, &receiverJsVal) ||
-        !receiverJsVal.isString()) {
-      return NS_ERROR_INVALID_ARG;
-    }
-
-    nsAutoJSString receiverStr;
-    if (!receiverStr.init(aCx, receiverJsVal.toString())) {
-      return NS_ERROR_FAILURE;
-    }
-
-    receivers.AppendElement(receiverStr);
-  }
-
-  // Set |attachments|.
-  if (!aAttachments.isObject()) {
-    return NS_ERROR_INVALID_ARG;
-  }
-  JS::Rooted<JSObject*> attachmentsObj(aCx, &aAttachments.toObject());
-  if (!JS_IsArrayObject(aCx, attachmentsObj, &isArray)) {
-    return NS_ERROR_FAILURE;
-  }
-  if (!isArray) {
-    return NS_ERROR_INVALID_ARG;
-  }
-
-  nsTArray<MmsAttachment> attachments;
-  MOZ_ALWAYS_TRUE(JS_GetArrayLength(aCx, attachmentsObj, &length));
-
-  JS::Rooted<JS::Value> attachmentJsVal(aCx);
-  for (uint32_t i = 0; i < length; ++i) {
-    if (!JS_GetElement(aCx, attachmentsObj, i, &attachmentJsVal)) {
-      return NS_ERROR_INVALID_ARG;
-    }
-
-    MmsAttachment attachment;
-    if (!attachment.Init(aCx, attachmentJsVal)) {
-      return NS_ERROR_TYPE_ERR;
-    }
-
-    NS_ENSURE_TRUE(attachment.mContent, NS_ERROR_TYPE_ERR);
-
-    attachments.AppendElement(attachment);
-  }
-
-  nsCOMPtr<nsIMmsMessage> message =
-    new MmsMessageInternal(aId,
-                           aThreadId,
-                           aIccId,
-                           delivery,
-                           deliveryInfo,
-                           aSender,
-                           receivers,
-                           aTimestamp,
-                           aSentTimestamp,
-                           aRead,
-                           aSubject,
-                           aSmil,
-                           attachments,
-                           aExpiryDate,
-                           aIsReadReportRequested);
-  message.forget(aMessage);
-  return NS_OK;
-}
-
-bool
-MmsMessageInternal::GetData(ContentParent* aParent,
-                            MmsMessageData& aData)
-{
-  NS_ASSERTION(aParent, "aParent is null");
-
-  aData.id() = mId;
-  aData.threadId() = mThreadId;
-  aData.iccId() = mIccId;
-  aData.delivery() = mDelivery;
-  aData.sender().Assign(mSender);
-  aData.receivers() = mReceivers;
-  aData.timestamp() = mTimestamp;
-  aData.sentTimestamp() = mSentTimestamp;
-  aData.read() = mRead;
-  aData.subject() = mSubject;
-  aData.smil() = mSmil;
-  aData.expiryDate() = mExpiryDate;
-  aData.readReportRequested() = mReadReportRequested;
-
-  aData.deliveryInfo().SetCapacity(mDeliveryInfo.Length());
-  for (uint32_t i = 0; i < mDeliveryInfo.Length(); i++) {
-    MmsDeliveryInfoData infoData;
-    const MmsDeliveryInfo &info = mDeliveryInfo[i];
-
-    // Prepare |infoData.mReceiver|.
-    infoData.receiver().Assign(info.mReceiver);
-
-    // Prepare |infoData.mDeliveryStatus|.
-    DeliveryStatus status;
-    if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_NOT_APPLICABLE)) {
-      status = eDeliveryStatus_NotApplicable;
-    } else if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_SUCCESS)) {
-      status = eDeliveryStatus_Success;
-    } else if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_PENDING)) {
-      status = eDeliveryStatus_Pending;
-    } else if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_ERROR)) {
-      status = eDeliveryStatus_Error;
-    } else if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_REJECTED)) {
-      status = eDeliveryStatus_Reject;
-    } else if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_MANUAL)) {
-      status = eDeliveryStatus_Manual;
-    } else {
-      return false;
-    }
-    infoData.deliveryStatus() = status;
-
-    // Prepare |infoData.mDeliveryTimestamp|.
-    infoData.deliveryTimestamp() = info.mDeliveryTimestamp;
-
-    // Prepare |infoData.mReadStatus|.
-    ReadStatus readStatus;
-    if (info.mReadStatus.Equals(READ_STATUS_NOT_APPLICABLE)) {
-      readStatus = eReadStatus_NotApplicable;
-    } else if (info.mReadStatus.Equals(READ_STATUS_SUCCESS)) {
-      readStatus = eReadStatus_Success;
-    } else if (info.mReadStatus.Equals(READ_STATUS_PENDING)) {
-      readStatus = eReadStatus_Pending;
-    } else if (info.mReadStatus.Equals(READ_STATUS_ERROR)) {
-      readStatus = eReadStatus_Error;
-    } else {
-      return false;
-    }
-    infoData.readStatus() = readStatus;
-
-    // Prepare |infoData.mReadTimestamp|.
-    infoData.readTimestamp() = info.mReadTimestamp;
-
-    aData.deliveryInfo().AppendElement(infoData);
-  }
-
-  aData.attachments().SetCapacity(mAttachments.Length());
-  for (uint32_t i = 0; i < mAttachments.Length(); i++) {
-    MmsAttachmentData mma;
-    const MmsAttachment &element = mAttachments[i];
-    mma.id().Assign(element.mId);
-    mma.location().Assign(element.mLocation);
-
-    // This is a workaround. Sometimes the blob we get from the database
-    // doesn't have a valid last modified date, making the ContentParent
-    // send a "Mystery Blob" to the ContentChild. Attempting to get the
-    // last modified date of blob can force that value to be initialized.
-    RefPtr<BlobImpl> impl = element.mContent->Impl();
-    if (impl && impl->IsDateUnknown()) {
-      ErrorResult rv;
-      impl->GetLastModified(rv);
-      if (rv.Failed()) {
-        NS_WARNING("Failed to get last modified date!");
-        rv.SuppressException();
-      }
-    }
-
-    mma.contentParent() = aParent->GetOrCreateActorForBlob(element.mContent);
-    if (!mma.contentParent()) {
-      return false;
-    }
-    aData.attachments().AppendElement(mma);
-  }
-
-  return true;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetType(nsAString& aType)
-{
-  aType = NS_LITERAL_STRING("mms");
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetId(int32_t* aId)
-{
-  *aId = mId;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetThreadId(uint64_t* aThreadId)
-{
-  *aThreadId = mThreadId;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetIccId(nsAString& aIccId)
-{
-  aIccId = mIccId;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetDelivery(nsAString& aDelivery)
-{
-  switch (mDelivery) {
-    case eDeliveryState_Received:
-      aDelivery = DELIVERY_RECEIVED;
-      break;
-    case eDeliveryState_Sending:
-      aDelivery = DELIVERY_SENDING;
-      break;
-    case eDeliveryState_Sent:
-      aDelivery = DELIVERY_SENT;
-      break;
-    case eDeliveryState_Error:
-      aDelivery = DELIVERY_ERROR;
-      break;
-    case eDeliveryState_NotDownloaded:
-      aDelivery = DELIVERY_NOT_DOWNLOADED;
-      break;
-    case eDeliveryState_Unknown:
-    case eDeliveryState_EndGuard:
-    default:
-      MOZ_CRASH("We shouldn't get any other delivery state!");
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetDeliveryInfo(JSContext* aCx, JS::MutableHandle<JS::Value> aDeliveryInfo)
-{
-  // TODO Bug 850525 It'd be better to depend on the delivery of MmsMessage
-  // to return a more correct value. Ex, if .delivery = 'received', we should
-  // also make .deliveryInfo = null, since the .deliveryInfo is useless.
-  uint32_t length = mDeliveryInfo.Length();
-  if (length == 0) {
-    aDeliveryInfo.setNull();
-    return NS_OK;
-  }
-
-  if (!ToJSValue(aCx, mDeliveryInfo, aDeliveryInfo)) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetSender(nsAString& aSender)
-{
-  aSender = mSender;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetReceivers(JSContext* aCx, JS::MutableHandle<JS::Value> aReceivers)
-{
-  JS::Rooted<JSObject*> receiversObj(aCx);
-  nsresult rv = nsTArrayToJSArray(aCx, mReceivers, &receiversObj);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  aReceivers.setObject(*receiversObj);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetTimestamp(DOMTimeStamp* aTimestamp)
-{
-  *aTimestamp = mTimestamp;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetSentTimestamp(DOMTimeStamp* aSentTimestamp)
-{
-  *aSentTimestamp = mSentTimestamp;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetRead(bool* aRead)
-{
-  *aRead = mRead;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetSubject(nsAString& aSubject)
-{
-  aSubject = mSubject;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetSmil(nsAString& aSmil)
-{
-  aSmil = mSmil;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetAttachments(JSContext* aCx, JS::MutableHandle<JS::Value> aAttachments)
-{
-  uint32_t length = mAttachments.Length();
-
-  if (length == 0) {
-    aAttachments.setNull();
-    return NS_OK;
-  }
-
-  // Duplicating the Blob with the correct parent object.
-  nsIGlobalObject* global = xpc::NativeGlobal(JS::CurrentGlobalOrNull(aCx));
-  MOZ_ASSERT(global);
-  nsTArray<MmsAttachment> result;
-  for (uint32_t i = 0; i < length; i++) {
-    MmsAttachment attachment;
-    const MmsAttachment &element = mAttachments[i];
-    attachment.mId = element.mId;
-    attachment.mLocation = element.mLocation;
-    attachment.mContent = Blob::Create(global, element.mContent->Impl());
-    result.AppendElement(attachment);
-  }
-
- if (!ToJSValue(aCx, result, aAttachments)) {
-    JS_ClearPendingException(aCx);
-    return NS_ERROR_TYPE_ERR;
- }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetExpiryDate(DOMTimeStamp* aExpiryDate)
-{
-  *aExpiryDate = mExpiryDate;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MmsMessageInternal::GetReadReportRequested(bool* aReadReportRequested)
-{
-  *aReadReportRequested = mReadReportRequested;
-  return NS_OK;
-}
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/MmsMessageInternal.h
+++ /dev/null
@@ -1,104 +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_mobilemessage_MmsMessageInternal_h
-#define mozilla_dom_mobilemessage_MmsMessageInternal_h
-
-#include "nsIMmsMessage.h"
-#include "nsString.h"
-#include "mozilla/dom/mobilemessage/Types.h"
-#include "mozilla/dom/MmsMessageBinding.h"
-#include "mozilla/dom/MozMobileMessageManagerBinding.h"
-#include "mozilla/Attributes.h"
-
-namespace mozilla {
-namespace dom {
-
-class ContentParent;
-class Blob;
-struct MmsAttachment;
-class MmsMessage;
-
-namespace mobilemessage {
-
-class MmsMessageData;
-
-class MmsMessageInternal final : public nsIMmsMessage
-{
-  // This allows the MmsMessage class to access jsval data members
-  // like |deliveryInfo|, |receivers|, and |attachments| without JS API.
-  friend class mozilla::dom::MmsMessage;
-
-public:
-  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_CYCLE_COLLECTION_CLASS(MmsMessageInternal)
-  NS_DECL_NSIMMSMESSAGE
-
-  MmsMessageInternal(int32_t aId,
-                     uint64_t aThreadId,
-                     const nsAString& aIccId,
-                     mobilemessage::DeliveryState aDelivery,
-                     const nsTArray<MmsDeliveryInfo>& aDeliveryInfo,
-                     const nsAString& aSender,
-                     const nsTArray<nsString>& aReceivers,
-                     uint64_t aTimestamp,
-                     uint64_t aSentTimestamp,
-                     bool aRead,
-                     const nsAString& aSubject,
-                     const nsAString& aSmil,
-                     const nsTArray<MmsAttachment>& aAttachments,
-                     uint64_t aExpiryDate,
-                     bool aReadReportRequested);
-
-  explicit MmsMessageInternal(const MmsMessageData& aData);
-
-  static nsresult Create(int32_t aId,
-                         uint64_t aThreadId,
-                         const nsAString& aIccId,
-                         const nsAString& aDelivery,
-                         const JS::Value& aDeliveryInfo,
-                         const nsAString& aSender,
-                         const JS::Value& aReceivers,
-                         uint64_t aTimestamp,
-                         uint64_t aSentTimestamp,
-                         bool aRead,
-                         const nsAString& aSubject,
-                         const nsAString& aSmil,
-                         const JS::Value& aAttachments,
-                         uint64_t aExpiryDate,
-                         bool aReadReportRequested,
-                         JSContext* aCx,
-                         nsIMmsMessage** aMessage);
-
-  bool GetData(ContentParent* aParent,
-               MmsMessageData& aData);
-
-private:
-
-  ~MmsMessageInternal() {}
-
-  int32_t mId;
-  uint64_t mThreadId;
-  nsString mIccId;
-  mobilemessage::DeliveryState mDelivery;
-  nsTArray<MmsDeliveryInfo> mDeliveryInfo;
-  nsString mSender;
-  nsTArray<nsString> mReceivers;
-  uint64_t mTimestamp;
-  uint64_t mSentTimestamp;
-  bool mRead;
-  nsString mSubject;
-  nsString mSmil;
-  nsTArray<MmsAttachment> mAttachments;
-  uint64_t mExpiryDate;
-  bool mReadReportRequested;
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_MmsMessageInternal_h
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageCallback.cpp
+++ /dev/null
@@ -1,381 +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 "MobileMessageCallback.h"
-#include "mozilla/dom/ToJSValue.h"
-#include "nsContentUtils.h"
-#include "nsIScriptGlobalObject.h"
-#include "nsPIDOMWindow.h"
-#include "MmsMessage.h"
-#include "MmsMessageInternal.h"
-#include "SmsMessage.h"
-#include "SmsMessageInternal.h"
-#include "mozilla/dom/ScriptSettings.h"
-#include "jsapi.h"
-#include "xpcpublic.h"
-#include "nsServiceManagerUtils.h"
-#include "nsTArrayHelpers.h"
-#include "DOMMobileMessageError.h"
-#include "mozilla/dom/Promise.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-static nsAutoString
-ConvertErrorCodeToErrorString(int32_t aError)
-{
-  nsAutoString errorStr;
-  switch (aError) {
-    case nsIMobileMessageCallback::NO_SIGNAL_ERROR:
-      errorStr = NS_LITERAL_STRING("NoSignalError");
-      break;
-    case nsIMobileMessageCallback::NOT_FOUND_ERROR:
-      errorStr = NS_LITERAL_STRING("NotFoundError");
-      break;
-    case nsIMobileMessageCallback::UNKNOWN_ERROR:
-      errorStr = NS_LITERAL_STRING("UnknownError");
-      break;
-    case nsIMobileMessageCallback::INTERNAL_ERROR:
-      errorStr = NS_LITERAL_STRING("InternalError");
-      break;
-    case nsIMobileMessageCallback::NO_SIM_CARD_ERROR:
-      errorStr = NS_LITERAL_STRING("NoSimCardError");
-      break;
-    case nsIMobileMessageCallback::RADIO_DISABLED_ERROR:
-      errorStr = NS_LITERAL_STRING("RadioDisabledError");
-      break;
-    case nsIMobileMessageCallback::INVALID_ADDRESS_ERROR:
-      errorStr = NS_LITERAL_STRING("InvalidAddressError");
-      break;
-    case nsIMobileMessageCallback::FDN_CHECK_ERROR:
-      errorStr = NS_LITERAL_STRING("FdnCheckError");
-      break;
-    case nsIMobileMessageCallback::NON_ACTIVE_SIM_CARD_ERROR:
-      errorStr = NS_LITERAL_STRING("NonActiveSimCardError");
-      break;
-    case nsIMobileMessageCallback::STORAGE_FULL_ERROR:
-      errorStr = NS_LITERAL_STRING("StorageFullError");
-      break;
-    case nsIMobileMessageCallback::SIM_NOT_MATCHED_ERROR:
-      errorStr = NS_LITERAL_STRING("SimNotMatchedError");
-      break;
-    case nsIMobileMessageCallback::NETWORK_PROBLEMS_ERROR:
-      errorStr = NS_LITERAL_STRING("NetworkProblemsError");
-      break;
-    case nsIMobileMessageCallback::GENERAL_PROBLEMS_ERROR:
-      errorStr = NS_LITERAL_STRING("GeneralProblemsError");
-      break;
-    case nsIMobileMessageCallback::SERVICE_NOT_AVAILABLE_ERROR:
-      errorStr = NS_LITERAL_STRING("ServiceNotAvailableError");
-      break;
-    case nsIMobileMessageCallback::MESSAGE_TOO_LONG_FOR_NETWORK_ERROR:
-      errorStr = NS_LITERAL_STRING("MessageTooLongForNetworkError");
-      break;
-    case nsIMobileMessageCallback::SERVICE_NOT_SUPPORTED_ERROR:
-      errorStr = NS_LITERAL_STRING("ServiceNotSupportedError");
-      break;
-    case nsIMobileMessageCallback::RETRY_REQUIRED_ERROR:
-      errorStr = NS_LITERAL_STRING("RetryRequiredError");
-      break;
-    default: // SUCCESS_NO_ERROR is handled above.
-      MOZ_CRASH("Should never get here!");
-  }
-
-  return errorStr;
-}
-
-NS_IMPL_ADDREF(MobileMessageCallback)
-NS_IMPL_RELEASE(MobileMessageCallback)
-
-NS_INTERFACE_MAP_BEGIN(MobileMessageCallback)
-  NS_INTERFACE_MAP_ENTRY(nsIMobileMessageCallback)
-  NS_INTERFACE_MAP_ENTRY(nsISupports)
-NS_INTERFACE_MAP_END
-
-MobileMessageCallback::MobileMessageCallback(DOMRequest* aDOMRequest)
-  : mDOMRequest(aDOMRequest)
-{
-}
-
-MobileMessageCallback::MobileMessageCallback(Promise* aPromise)
-  : mPromise(aPromise)
-{
-}
-
-MobileMessageCallback::~MobileMessageCallback()
-{
-}
-
-
-nsresult
-MobileMessageCallback::NotifySuccess(JS::Handle<JS::Value> aResult, bool aAsync)
-{
-  if (NS_WARN_IF(!mDOMRequest->GetOwner())) {
-    return NS_ERROR_FAILURE;
-  }
-
-  if (aAsync) {
-    nsCOMPtr<nsIDOMRequestService> rs =
-      do_GetService(DOMREQUEST_SERVICE_CONTRACTID);
-    NS_ENSURE_TRUE(rs, NS_ERROR_FAILURE);
-
-    return rs->FireSuccessAsync(mDOMRequest, aResult);
-  }
-
-  mDOMRequest->FireSuccess(aResult);
-  return NS_OK;
-}
-
-nsresult
-MobileMessageCallback::NotifySuccess(nsISupports *aMessage, bool aAsync)
-{
-  nsCOMPtr<nsPIDOMWindowInner> window = mDOMRequest->GetOwner();
-  NS_ENSURE_TRUE(window, NS_ERROR_FAILURE);
-
-  nsCOMPtr<nsISupports> result;
-
-  nsCOMPtr<nsISmsMessage> internalSms =
-    do_QueryInterface(aMessage);
-  if (internalSms) {
-    SmsMessageInternal* smsMsg = static_cast<SmsMessageInternal*>(internalSms.get());
-    result = new SmsMessage(window, smsMsg);
-  }
-
-  if (!result) {
-    nsCOMPtr<nsIMmsMessage> internalMms =
-      do_QueryInterface(aMessage);
-    if (internalMms) {
-      MmsMessageInternal* mmsMsg = static_cast<MmsMessageInternal*>(internalMms.get());
-      result = new MmsMessage(window, mmsMsg);
-    }
-  }
-
-  AutoJSAPI jsapi;
-  if (NS_WARN_IF(!jsapi.Init(window))) {
-    return NS_ERROR_FAILURE;
-  }
-  JSContext* cx = jsapi.cx();
-
-  JS::Rooted<JS::Value> wrappedMessage(cx);
-  nsresult rv =
-    nsContentUtils::WrapNative(cx, result, &wrappedMessage);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NotifySuccess(wrappedMessage, aAsync);
-}
-
-nsresult
-MobileMessageCallback::NotifyError(int32_t aError, DOMError *aDetailedError, bool aAsync)
-{
-  if (NS_WARN_IF(!mDOMRequest->GetOwner())) {
-    return NS_ERROR_FAILURE;
-  }
-
-  if (aAsync) {
-    NS_ASSERTION(!aDetailedError,
-      "No Support to FireDetailedErrorAsync() in nsIDOMRequestService!");
-
-    nsCOMPtr<nsIDOMRequestService> rs =
-      do_GetService(DOMREQUEST_SERVICE_CONTRACTID);
-    NS_ENSURE_TRUE(rs, NS_ERROR_FAILURE);
-
-    return rs->FireErrorAsync(mDOMRequest,
-                              ConvertErrorCodeToErrorString(aError));
-  }
-
-  if (aDetailedError) {
-    mDOMRequest->FireDetailedError(aDetailedError);
-  } else {
-    mDOMRequest->FireError(ConvertErrorCodeToErrorString(aError));
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifyMessageSent(nsISupports *aMessage)
-{
-  return NotifySuccess(aMessage);
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifySendMessageFailed(int32_t aError, nsISupports *aMessage)
-{
-  nsCOMPtr<nsPIDOMWindowInner> window = mDOMRequest->GetOwner();
-  if (NS_WARN_IF(!window)) {
-    return NS_ERROR_FAILURE;
-  }
-
-  RefPtr<DOMMobileMessageError> domMobileMessageError;
-  if (aMessage) {
-    nsAutoString errorStr = ConvertErrorCodeToErrorString(aError);
-    nsCOMPtr<nsISmsMessage> internalSms = do_QueryInterface(aMessage);
-    if (internalSms) {
-      domMobileMessageError =
-        new DOMMobileMessageError(window, errorStr,
-                                  new SmsMessage(window,
-                                  static_cast<SmsMessageInternal*>(internalSms.get())));
-    }
-    else {
-      nsCOMPtr<nsIMmsMessage> internalMms = do_QueryInterface(aMessage);
-      domMobileMessageError =
-        new DOMMobileMessageError(window, errorStr,
-                                  new MmsMessage(window,
-                                  static_cast<MmsMessageInternal*>(internalMms.get())));
-    }
-    NS_ASSERTION(domMobileMessageError, "Invalid DOMMobileMessageError!");
-  }
-
-  return NotifyError(aError, domMobileMessageError);
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifyMessageGot(nsISupports *aMessage)
-{
-  return NotifySuccess(aMessage);
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifyGetMessageFailed(int32_t aError)
-{
-  return NotifyError(aError);
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifyMessageDeleted(bool *aDeleted, uint32_t aSize)
-{
-  if (aSize == 1) {
-    AutoJSContext cx;
-    JS::Rooted<JS::Value> val(cx, JS::BooleanValue(*aDeleted));
-    return NotifySuccess(val);
-  }
-
-  AutoJSAPI jsapi;
-  if (NS_WARN_IF(!jsapi.Init(mDOMRequest->GetOwner()))) {
-    return NS_ERROR_FAILURE;
-  }
-  JSContext* cx = jsapi.cx();
-
-  JS::Rooted<JSObject*> deleteArrayObj(cx, JS_NewArrayObject(cx, aSize));
-  if (!deleteArrayObj) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-  for (uint32_t i = 0; i < aSize; i++) {
-    if (!JS_DefineElement(cx, deleteArrayObj, i, aDeleted[i],
-                          JSPROP_ENUMERATE)) {
-      return NS_ERROR_UNEXPECTED;
-    }
-  }
-
-  JS::Rooted<JS::Value> deleteArrayVal(cx, JS::ObjectValue(*deleteArrayObj));
-  return NotifySuccess(deleteArrayVal);
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifyDeleteMessageFailed(int32_t aError)
-{
-  return NotifyError(aError);
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifyMessageMarkedRead(bool aRead)
-{
-  AutoJSContext cx;
-  JS::Rooted<JS::Value> val(cx, JS::BooleanValue(aRead));
-  return NotifySuccess(val);
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifyMarkMessageReadFailed(int32_t aError)
-{
-  return NotifyError(aError);
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifySegmentInfoForTextGot(int32_t aSegments,
-                                                   int32_t aCharsPerSegment,
-                                                   int32_t aCharsAvailableInLastSegment)
-{
-  AutoJSAPI jsapi;
-  if (NS_WARN_IF(!jsapi.Init(mDOMRequest->GetOwner()))) {
-    return NotifyError(nsIMobileMessageCallback::INTERNAL_ERROR);
-  }
-
-  SmsSegmentInfo info;
-  info.mSegments = aSegments;
-  info.mCharsPerSegment = aCharsPerSegment;
-  info.mCharsAvailableInLastSegment = aCharsAvailableInLastSegment;
-
-  JSContext* cx = jsapi.cx();
-  JS::Rooted<JS::Value> val(cx);
-  if (!ToJSValue(cx, info, &val)) {
-    jsapi.ClearException();
-    return NotifyError(nsIMobileMessageCallback::INTERNAL_ERROR);
-  }
-
-  return NotifySuccess(val, true);
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifyGetSegmentInfoForTextFailed(int32_t aError)
-{
-  return NotifyError(aError, nullptr, true);
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifyGetSmscAddress(const nsAString& aSmscAddress,
-                                            uint32_t aTypeOfNumber,
-                                            uint32_t aNumberPlanIdentification)
-{
-  TypeOfAddress toa;
-
-  // Check the value is valid and set TON accordingly.
-  bool isTonValid = aTypeOfNumber < uint32_t(TypeOfNumber::EndGuard_);
-  toa.mTypeOfNumber = (isTonValid) ?
-    static_cast<TypeOfNumber>(aTypeOfNumber) : TypeOfNumber::Unknown;
-
-  // Check the value is valid and set NPI accordingly.
-  bool isNpiValid =
-    aNumberPlanIdentification < uint32_t(NumberPlanIdentification::EndGuard_);
-  toa.mNumberPlanIdentification = (isNpiValid) ?
-    static_cast<NumberPlanIdentification>(aNumberPlanIdentification) :
-    NumberPlanIdentification::Unknown;
-
-  SmscAddress smsc;
-  smsc.mTypeOfAddress = toa;
-  smsc.mAddress.Construct(nsString(aSmscAddress));
-
-  mPromise->MaybeResolve(smsc);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifyGetSmscAddressFailed(int32_t aError)
-{
-  const nsAString& errorStr = ConvertErrorCodeToErrorString(aError);
-  mPromise->MaybeRejectBrokenly(errorStr);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifySetSmscAddress()
-{
-  mPromise->MaybeResolveWithUndefined();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageCallback::NotifySetSmscAddressFailed(int32_t aError)
-{
-  const nsAString& errorStr = ConvertErrorCodeToErrorString(aError);
-  mPromise->MaybeRejectBrokenly(errorStr);
-  return NS_OK;
-}
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageCallback.h
+++ /dev/null
@@ -1,44 +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_mobilemessage_MobileMessageCallback_h
-#define mozilla_dom_mobilemessage_MobileMessageCallback_h
-
-#include "nsIMobileMessageCallback.h"
-#include "nsCOMPtr.h"
-#include "DOMRequest.h"
-
-class Promise;
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-class MobileMessageCallback final : public nsIMobileMessageCallback
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIMOBILEMESSAGECALLBACK
-
-  explicit MobileMessageCallback(DOMRequest* aDOMRequest);
-  explicit MobileMessageCallback(Promise* aPromise);
-
-private:
-  ~MobileMessageCallback();
-
-  RefPtr<DOMRequest> mDOMRequest;
-  RefPtr<Promise> mPromise;
-
-  nsresult NotifySuccess(JS::Handle<JS::Value> aResult, bool aAsync = false);
-  nsresult NotifySuccess(nsISupports *aMessage, bool aAsync = false);
-  nsresult NotifyError(int32_t aError, DOMError *aDetailedError = nullptr, bool aAsync = false);
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_MobileMessageCallback_h
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageCursorCallback.cpp
+++ /dev/null
@@ -1,216 +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 "MobileMessageCursorCallback.h"
-#include "MmsMessage.h"
-#include "MmsMessageInternal.h"
-#include "MobileMessageThread.h"
-#include "MobileMessageThreadInternal.h"
-#include "mozilla/dom/ScriptSettings.h"
-#include "nsIDOMDOMRequest.h"
-#include "SmsMessage.h"
-#include "SmsMessageInternal.h"
-#include "nsIMobileMessageCallback.h"
-#include "nsServiceManagerUtils.h"      // for do_GetService
-
-namespace mozilla {
-namespace dom {
-
-NS_IMPL_CYCLE_COLLECTION_INHERITED(MobileMessageCursor, DOMCursor,
-                                   mPendingResults)
-
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(MobileMessageCursor)
-NS_INTERFACE_MAP_END_INHERITING(DOMCursor)
-
-NS_IMPL_ADDREF_INHERITED(MobileMessageCursor, DOMCursor)
-NS_IMPL_RELEASE_INHERITED(MobileMessageCursor, DOMCursor)
-
-MobileMessageCursor::MobileMessageCursor(nsPIDOMWindowInner* aWindow,
-                                         nsICursorContinueCallback* aCallback)
-  : DOMCursor(aWindow, aCallback)
-{
-}
-
-NS_IMETHODIMP
-MobileMessageCursor::Continue()
-{
-  // We have originally:
-  //
-  //   DOMCursor::Continue()
-  //   +-> DOMCursor::Continue(ErrorResult& aRv)
-  //
-  // Now it becomes:
-  //
-  //   MobileMessageCursor::Continue()
-  //   +-> DOMCursor::Continue()
-  //       +-> MobileMessageCursor::Continue(ErrorResult& aRv)
-  //           o-> DOMCursor::Continue(ErrorResult& aRv)
-  return DOMCursor::Continue();
-}
-
-void
-MobileMessageCursor::Continue(ErrorResult& aRv)
-{
-  // An ordinary DOMCursor works in following flow:
-  //
-  //   DOMCursor::Continue()
-  //   +-> DOMCursor::Reset()
-  //   +-> nsICursorContinueCallback::HandleContinue()
-  //       +-> nsIMobileMessageCursorCallback::NotifyCursorResult()
-  //           +-> DOMCursor::FireSuccess()
-  //
-  // With no pending result, we call to |DOMCursor::Continue()| as usual.
-  if (!mPendingResults.Length()) {
-    DOMCursor::Continue(aRv);
-    return;
-  }
-
-  // Otherwise, reset current result and fire a success event with the last
-  // pending one.
-  Reset();
-
-  nsresult rv = FireSuccessWithNextPendingResult();
-  if (NS_FAILED(rv)) {
-    aRv.Throw(rv);
-  }
-}
-
-nsresult
-MobileMessageCursor::FireSuccessWithNextPendingResult()
-{
-  // We're going to pop the last element from mPendingResults, so it must not
-  // be empty.
-  MOZ_ASSERT(mPendingResults.Length());
-
-  nsCOMPtr<nsISupports> result;
-
-  nsCOMPtr<nsIMobileMessageThread> internalThread =
-    do_QueryInterface(mPendingResults.LastElement());
-  if (internalThread) {
-    MobileMessageThreadInternal* thread =
-      static_cast<MobileMessageThreadInternal*>(internalThread.get());
-    result = new MobileMessageThread(GetOwner(), thread);
-  }
-
-  if (!result) {
-    nsCOMPtr<nsISmsMessage> internalSms =
-      do_QueryInterface(mPendingResults.LastElement());
-    if (internalSms) {
-      SmsMessageInternal* sms = static_cast<SmsMessageInternal*>(internalSms.get());
-      result = new SmsMessage(GetOwner(), sms);
-    }
-  }
-
-  if (!result) {
-    nsCOMPtr<nsIMmsMessage> internalMms =
-      do_QueryInterface(mPendingResults.LastElement());
-    if (internalMms) {
-      MmsMessageInternal* mms = static_cast<MmsMessageInternal*>(internalMms.get());
-      result = new MmsMessage(GetOwner(), mms);
-    }
-  }
-
-  MOZ_ASSERT(result);
-
-  AutoJSAPI jsapi;
-  if (NS_WARN_IF(!jsapi.Init(GetOwner()))) {
-    return NS_ERROR_FAILURE;
-  }
-
-  JSContext* cx = jsapi.cx();
-  JS::Rooted<JS::Value> val(cx);
-  nsresult rv =
-    nsContentUtils::WrapNative(cx, result, &val);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  mPendingResults.RemoveElementAt(mPendingResults.Length() - 1);
-
-  FireSuccess(val);
-  return NS_OK;
-}
-
-namespace mobilemessage {
-
-NS_IMPL_CYCLE_COLLECTION(MobileMessageCursorCallback, mDOMCursor)
-
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MobileMessageCursorCallback)
-  NS_INTERFACE_MAP_ENTRY(nsIMobileMessageCursorCallback)
-  NS_INTERFACE_MAP_ENTRY(nsISupports)
-NS_INTERFACE_MAP_END
-
-NS_IMPL_CYCLE_COLLECTING_ADDREF(MobileMessageCursorCallback)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(MobileMessageCursorCallback)
-
-// nsIMobileMessageCursorCallback
-
-NS_IMETHODIMP
-MobileMessageCursorCallback::NotifyCursorError(int32_t aError)
-{
-  MOZ_ASSERT(mDOMCursor);
-
-  RefPtr<DOMCursor> cursor = mDOMCursor.forget();
-
-  switch (aError) {
-    case nsIMobileMessageCallback::NO_SIGNAL_ERROR:
-      cursor->FireError(NS_LITERAL_STRING("NoSignalError"));
-      break;
-    case nsIMobileMessageCallback::NOT_FOUND_ERROR:
-      cursor->FireError(NS_LITERAL_STRING("NotFoundError"));
-      break;
-    case nsIMobileMessageCallback::UNKNOWN_ERROR:
-      cursor->FireError(NS_LITERAL_STRING("UnknownError"));
-      break;
-    case nsIMobileMessageCallback::INTERNAL_ERROR:
-      cursor->FireError(NS_LITERAL_STRING("InternalError"));
-      break;
-    default: // SUCCESS_NO_ERROR is handled above.
-      MOZ_CRASH("Should never get here!");
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageCursorCallback::NotifyCursorResult(nsISupports** aResults,
-                                                uint32_t aSize)
-{
-  MOZ_ASSERT(mDOMCursor);
-  // We should only be notified with valid results. Or, either
-  // |NotifyCursorDone()| or |NotifyCursorError()| should be called instead.
-  MOZ_ASSERT(aResults && *aResults && aSize);
-  // There shouldn't be unexpected notifications before |Continue()| is called.
-  nsTArray<nsCOMPtr<nsISupports>>& pending = mDOMCursor->mPendingResults;
-  MOZ_ASSERT(pending.Length() == 0);
-
-  // Push pending results in reversed order.
-  pending.SetCapacity(pending.Length() + aSize);
-  while (aSize) {
-    --aSize;
-    pending.AppendElement(aResults[aSize]);
-  }
-
-  nsresult rv = mDOMCursor->FireSuccessWithNextPendingResult();
-  if (NS_FAILED(rv)) {
-    NotifyCursorError(nsIMobileMessageCallback::INTERNAL_ERROR);
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageCursorCallback::NotifyCursorDone()
-{
-  MOZ_ASSERT(mDOMCursor);
-
-  RefPtr<DOMCursor> cursor = mDOMCursor.forget();
-  cursor->FireDone();
-
-  return NS_OK;
-}
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageCursorCallback.h
+++ /dev/null
@@ -1,90 +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_mobilemessage_MobileMessageCursorCallback_h
-#define mozilla_dom_mobilemessage_MobileMessageCursorCallback_h
-
-#include "mozilla/Attributes.h"
-#include "mozilla/dom/DOMCursor.h"
-#include "nsIMobileMessageCursorCallback.h"
-#include "nsCycleCollectionParticipant.h"
-#include "nsCOMPtr.h"
-
-class nsICursorContinueCallback;
-
-namespace mozilla {
-namespace dom {
-
-class MobileMessageManager;
-
-namespace mobilemessage {
-class MobileMessageCursorCallback;
-} // namespace mobilemessage
-
-class MobileMessageCursor final : public DOMCursor
-{
-  friend class mobilemessage::MobileMessageCursorCallback;
-
-public:
-  NS_DECL_ISUPPORTS_INHERITED
-
-  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(MobileMessageCursor, DOMCursor)
-
-  MobileMessageCursor(nsPIDOMWindowInner* aWindow,
-                      nsICursorContinueCallback* aCallback);
-
-  // Override XPIDL continue function to suppress -Werror,-Woverloaded-virtual.
-  NS_IMETHOD
-  Continue(void) override;
-
-  virtual void
-  Continue(ErrorResult& aRv) override;
-
-private:
-  // final suppresses -Werror,-Wdelete-non-virtual-dtor
-  ~MobileMessageCursor() {}
-
-private:
-  // List of read-ahead results in reversed order.
-  nsTArray<nsCOMPtr<nsISupports>> mPendingResults;
-
-  nsresult
-  FireSuccessWithNextPendingResult();
-};
-
-namespace mobilemessage {
-
-class MobileMessageCursorCallback final : public nsIMobileMessageCursorCallback
-{
-  friend class mozilla::dom::MobileMessageManager;
-
-public:
-  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_NSIMOBILEMESSAGECURSORCALLBACK
-
-  NS_DECL_CYCLE_COLLECTION_CLASS(MobileMessageCursorCallback)
-
-  MobileMessageCursorCallback()
-  {
-    MOZ_COUNT_CTOR(MobileMessageCursorCallback);
-  }
-
-private:
-  // final suppresses -Werror,-Wdelete-non-virtual-dtor
-  ~MobileMessageCursorCallback()
-  {
-    MOZ_COUNT_DTOR(MobileMessageCursorCallback);
-  }
-
-  RefPtr<MobileMessageCursor> mDOMCursor;
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_MobileMessageCursorCallback_h
-
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageManager.cpp
+++ /dev/null
@@ -1,905 +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 "MobileMessageManager.h"
-
-#include "DeletedMessageInfo.h"
-#include "DOMCursor.h"
-#include "DOMRequest.h"
-#include "MmsMessage.h"
-#include "MmsMessageInternal.h"
-#include "MobileMessageCallback.h"
-#include "MobileMessageCursorCallback.h"
-#include "SmsMessage.h"
-#include "SmsMessageInternal.h"
-#include "mozilla/dom/mobilemessage/Constants.h" // For kSms*ObserverTopic
-#include "mozilla/dom/MozMessageDeletedEvent.h"
-#include "mozilla/dom/MozMmsEvent.h"
-#include "mozilla/dom/MozMobileMessageManagerBinding.h"
-#include "mozilla/dom/MozSmsEvent.h"
-#include "mozilla/dom/Promise.h"
-#include "mozilla/dom/ToJSValue.h"
-#include "mozilla/Preferences.h"
-#include "mozilla/Services.h"
-#include "mozilla/UniquePtr.h"
-#include "nsIMmsService.h"
-#include "nsIMobileMessageCallback.h"
-#include "nsIMobileMessageDatabaseService.h"
-#include "nsIMobileMessageService.h"
-#include "nsIObserverService.h"
-#include "nsISmsService.h"
-#include "nsServiceManagerUtils.h" // For do_GetService()
-
-// Service instantiation
-#include "ipc/SmsIPCService.h"
-#include "MobileMessageService.h"
-#if defined(MOZ_WIDGET_ANDROID) && defined(MOZ_WEBSMS_BACKEND)
-#include "android/MobileMessageDatabaseService.h"
-#include "android/SmsService.h"
-#elif defined(MOZ_WIDGET_GONK) && defined(MOZ_B2G_RIL)
-#include "nsIGonkMobileMessageDatabaseService.h"
-#include "nsIGonkSmsService.h"
-#endif
-#include "nsXULAppAPI.h" // For XRE_GetProcessType()
-
-#define RECEIVED_EVENT_NAME         NS_LITERAL_STRING("received")
-#define RETRIEVING_EVENT_NAME       NS_LITERAL_STRING("retrieving")
-#define SENDING_EVENT_NAME          NS_LITERAL_STRING("sending")
-#define SENT_EVENT_NAME             NS_LITERAL_STRING("sent")
-#define FAILED_EVENT_NAME           NS_LITERAL_STRING("failed")
-#define DELIVERY_SUCCESS_EVENT_NAME NS_LITERAL_STRING("deliverysuccess")
-#define DELIVERY_ERROR_EVENT_NAME   NS_LITERAL_STRING("deliveryerror")
-#define READ_SUCCESS_EVENT_NAME     NS_LITERAL_STRING("readsuccess")
-#define READ_ERROR_EVENT_NAME       NS_LITERAL_STRING("readerror")
-#define DELETED_EVENT_NAME          NS_LITERAL_STRING("deleted")
-
-using namespace mozilla::dom::mobilemessage;
-
-namespace mozilla {
-namespace dom {
-
-NS_INTERFACE_MAP_BEGIN(MobileMessageManager)
-  NS_INTERFACE_MAP_ENTRY(nsIObserver)
-NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
-
-NS_IMPL_ADDREF_INHERITED(MobileMessageManager, DOMEventTargetHelper)
-NS_IMPL_RELEASE_INHERITED(MobileMessageManager, DOMEventTargetHelper)
-
-MobileMessageManager::MobileMessageManager(nsPIDOMWindowInner* aWindow)
-  : DOMEventTargetHelper(aWindow)
-{
-}
-
-void
-MobileMessageManager::Init()
-{
-  nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
-  // GetObserverService() can return null is some situations like shutdown.
-  if (!obs) {
-    return;
-  }
-
-  obs->AddObserver(this, kSmsReceivedObserverTopic, false);
-  obs->AddObserver(this, kSmsRetrievingObserverTopic, false);
-  obs->AddObserver(this, kSmsSendingObserverTopic, false);
-  obs->AddObserver(this, kSmsSentObserverTopic, false);
-  obs->AddObserver(this, kSmsFailedObserverTopic, false);
-  obs->AddObserver(this, kSmsDeliverySuccessObserverTopic, false);
-  obs->AddObserver(this, kSmsDeliveryErrorObserverTopic, false);
-  obs->AddObserver(this, kSmsReadSuccessObserverTopic, false);
-  obs->AddObserver(this, kSmsReadErrorObserverTopic, false);
-  obs->AddObserver(this, kSmsDeletedObserverTopic, false);
-}
-
-void
-MobileMessageManager::Shutdown()
-{
-  nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
-  // GetObserverService() can return null is some situations like shutdown.
-  if (!obs) {
-    return;
-  }
-
-  obs->RemoveObserver(this, kSmsReceivedObserverTopic);
-  obs->RemoveObserver(this, kSmsRetrievingObserverTopic);
-  obs->RemoveObserver(this, kSmsSendingObserverTopic);
-  obs->RemoveObserver(this, kSmsSentObserverTopic);
-  obs->RemoveObserver(this, kSmsFailedObserverTopic);
-  obs->RemoveObserver(this, kSmsDeliverySuccessObserverTopic);
-  obs->RemoveObserver(this, kSmsDeliveryErrorObserverTopic);
-  obs->RemoveObserver(this, kSmsReadSuccessObserverTopic);
-  obs->RemoveObserver(this, kSmsReadErrorObserverTopic);
-  obs->RemoveObserver(this, kSmsDeletedObserverTopic);
-}
-
-JSObject*
-MobileMessageManager::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
-{
-  return MozMobileMessageManagerBinding::Wrap(aCx, this, aGivenProto);
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::GetSegmentInfoForText(const nsAString& aText,
-                                            ErrorResult& aRv)
-{
-  nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
-  if (!smsService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  if (!window) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  RefPtr<DOMRequest> request = new DOMRequest(window);
-  nsCOMPtr<nsIMobileMessageCallback> msgCallback =
-    new MobileMessageCallback(request);
-  nsresult rv = smsService->GetSegmentInfoForText(aText, msgCallback);
-  if (NS_FAILED(rv)) {
-    aRv.Throw(rv);
-    return nullptr;
-  }
-
-  return request.forget();
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::Send(nsISmsService* aSmsService,
-                           uint32_t aServiceId,
-                           const nsAString& aNumber,
-                           const nsAString& aText,
-                           ErrorResult& aRv)
-{
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  if (!window) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  RefPtr<DOMRequest> request = new DOMRequest(window);
-  nsCOMPtr<nsIMobileMessageCallback> msgCallback =
-    new MobileMessageCallback(request);
-
-  // By default, we don't send silent messages via MobileMessageManager.
-  nsresult rv = aSmsService->Send(aServiceId, aNumber, aText,
-                                  false, msgCallback);
-  if (NS_FAILED(rv)) {
-    aRv.Throw(rv);
-    return nullptr;
-  }
-
-  return request.forget();
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::Send(const nsAString& aNumber,
-                           const nsAString& aText,
-                           const SmsSendParameters& aSendParams,
-                           ErrorResult& aRv)
-{
-  nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
-  if (!smsService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  // Use the default one unless |aSendParams.serviceId| is available.
-  uint32_t serviceId;
-  if (aSendParams.mServiceId.WasPassed()) {
-    serviceId = aSendParams.mServiceId.Value();
-  } else {
-    nsresult rv = smsService->GetSmsDefaultServiceId(&serviceId);
-    if (NS_FAILED(rv)) {
-      aRv.Throw(rv);
-      return nullptr;
-    }
-  }
-
-  return Send(smsService, serviceId, aNumber, aText, aRv);
-}
-
-void
-MobileMessageManager::Send(const Sequence<nsString>& aNumbers,
-                           const nsAString& aText,
-                           const SmsSendParameters& aSendParams,
-                           nsTArray<RefPtr<DOMRequest>>& aReturn,
-                           ErrorResult& aRv)
-{
-  nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
-  if (!smsService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return;
-  }
-
-  // Use the default one unless |aSendParams.serviceId| is available.
-  uint32_t serviceId;
-  if (aSendParams.mServiceId.WasPassed()) {
-    serviceId = aSendParams.mServiceId.Value();
-  } else {
-    nsresult rv = smsService->GetSmsDefaultServiceId(&serviceId);
-    if (NS_FAILED(rv)) {
-      aRv.Throw(rv);
-      return;
-    }
-  }
-
-  const uint32_t size = aNumbers.Length();
-  for (uint32_t i = 0; i < size; ++i) {
-    RefPtr<DOMRequest> request = Send(smsService, serviceId, aNumbers[i], aText, aRv);
-    if (aRv.Failed()) {
-      return;
-    }
-    aReturn.AppendElement(request);
-  }
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::SendMMS(const MmsParameters& aParams,
-                              const MmsSendParameters& aSendParams,
-                              ErrorResult& aRv)
-{
-  nsCOMPtr<nsIMmsService> mmsService = do_GetService(MMS_SERVICE_CONTRACTID);
-  if (!mmsService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  // Use the default one unless |aSendParams.serviceId| is available.
-  uint32_t serviceId;
-  nsresult rv;
-  if (aSendParams.mServiceId.WasPassed()) {
-    serviceId = aSendParams.mServiceId.Value();
-  } else {
-    rv = mmsService->GetMmsDefaultServiceId(&serviceId);
-    if (NS_FAILED(rv)) {
-      aRv.Throw(rv);
-      return nullptr;
-    }
-  }
-
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  if (!window) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  AutoJSAPI jsapi;
-  if (NS_WARN_IF(!jsapi.Init(window))) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  JSContext *cx = jsapi.cx();
-  JS::Rooted<JS::Value> val(cx);
-  aRv.MightThrowJSException();
-  if (!ToJSValue(cx, aParams, &val)) {
-    aRv.StealExceptionFromJSContext(cx);
-    return nullptr;
-  }
-
-  RefPtr<DOMRequest> request = new DOMRequest(window);
-  nsCOMPtr<nsIMobileMessageCallback> msgCallback = new MobileMessageCallback(request);
-  rv = mmsService->Send(serviceId, val, msgCallback);
-  if (NS_FAILED(rv)) {
-    aRv.Throw(rv);
-    return nullptr;
-  }
-
-  return request.forget();
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::GetMessage(int32_t aId,
-                                 ErrorResult& aRv)
-{
-  nsCOMPtr<nsIMobileMessageDatabaseService> dbService =
-    do_GetService(MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
-  if (!dbService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  if (!window) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  RefPtr<DOMRequest> request = new DOMRequest(window);
-  nsCOMPtr<nsIMobileMessageCallback> msgCallback = new MobileMessageCallback(request);
-  nsresult rv = dbService->GetMessageMoz(aId, msgCallback);
-  if (NS_FAILED(rv)) {
-    aRv.Throw(rv);
-    return nullptr;
-  }
-
-  return request.forget();
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::Delete(int32_t* aIdArray,
-                             uint32_t aSize,
-                             ErrorResult& aRv)
-{
-  nsCOMPtr<nsIMobileMessageDatabaseService> dbService =
-    do_GetService(MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
-  if (!dbService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  if (!window) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  RefPtr<DOMRequest> request = new DOMRequest(window);
-  nsCOMPtr<nsIMobileMessageCallback> msgCallback =
-    new MobileMessageCallback(request);
-
-  nsresult rv = dbService->DeleteMessage(aIdArray, aSize, msgCallback);
-  if (NS_FAILED(rv)) {
-    aRv.Throw(rv);
-    return nullptr;
-  }
-
-  return request.forget();
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::Delete(int32_t aId,
-                             ErrorResult& aRv)
-{
-  return Delete(&aId, 1, aRv);
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::Delete(SmsMessage& aMessage,
-                             ErrorResult& aRv)
-{
-  return Delete(aMessage.Id(), aRv);
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::Delete(MmsMessage& aMessage,
-                             ErrorResult& aRv)
-{
-  return Delete(aMessage.Id(), aRv);
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::Delete(const Sequence<OwningLongOrSmsMessageOrMmsMessage>& aParams,
-                             ErrorResult& aRv)
-{
-  const uint32_t size = aParams.Length();
-  FallibleTArray<int32_t> idArray;
-  if (!idArray.SetLength(size, fallible)) {
-    aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
-    return nullptr;
-  }
-
-  DebugOnly<nsresult> rv;
-  for (uint32_t i = 0; i < size; i++) {
-    const OwningLongOrSmsMessageOrMmsMessage& element = aParams[i];
-    int32_t &id = idArray[i];
-
-    if (element.IsLong()) {
-      id = element.GetAsLong();
-    } else if (element.IsMmsMessage()) {
-      id = element.GetAsMmsMessage()->Id();
-    } else /*if (element.IsSmsMessage())*/ {
-      id = element.GetAsSmsMessage()->Id();
-    }
-  }
-
-  return Delete(idArray.Elements(), size, aRv);
-}
-
-already_AddRefed<DOMCursor>
-MobileMessageManager::GetMessages(const MobileMessageFilter& aFilter,
-                                  bool aReverse,
-                                  ErrorResult& aRv)
-{
-  nsCOMPtr<nsIMobileMessageDatabaseService> dbService =
-    do_GetService(MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
-  if (!dbService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  bool hasStartDate = !aFilter.mStartDate.IsNull();
-  uint64_t startDate = 0;
-  if (hasStartDate) {
-    startDate = aFilter.mStartDate.Value();
-  }
-
-  bool hasEndDate = !aFilter.mEndDate.IsNull();
-  uint64_t endDate = 0;
-  if (hasEndDate) {
-    endDate = aFilter.mEndDate.Value();
-  }
-
-  UniquePtr<const char16_t*[]> ptrNumbers;
-  uint32_t numbersCount = 0;
-  if (!aFilter.mNumbers.IsNull() &&
-      aFilter.mNumbers.Value().Length()) {
-    const FallibleTArray<nsString>& numbers = aFilter.mNumbers.Value();
-    uint32_t index;
-
-    numbersCount = numbers.Length();
-    ptrNumbers = MakeUnique<const char16_t*[]>(numbersCount);
-    for (index = 0; index < numbersCount; index++) {
-      ptrNumbers[index] = numbers[index].get();
-    }
-  }
-
-  nsString delivery;
-  delivery.SetIsVoid(true);
-  if (!aFilter.mDelivery.IsNull()) {
-    const uint32_t index = static_cast<uint32_t>(aFilter.mDelivery.Value());
-    const EnumEntry& entry =
-      MobileMessageFilterDeliveryValues::strings[index];
-    delivery.AssignASCII(entry.value, entry.length);
-  }
-
-  bool hasRead = !aFilter.mRead.IsNull();
-  bool read = false;
-  if (hasRead) {
-    read = aFilter.mRead.Value();
-  }
-
-  bool hasThreadId = !aFilter.mThreadId.IsNull();
-  uint64_t threadId = 0;
-  if (hasThreadId) {
-    threadId = aFilter.mThreadId.Value();
-  }
-
-  RefPtr<MobileMessageCursorCallback> cursorCallback =
-    new MobileMessageCursorCallback();
-  nsCOMPtr<nsICursorContinueCallback> continueCallback;
-  nsresult rv = dbService->CreateMessageCursor(hasStartDate, startDate,
-                                               hasEndDate, endDate,
-                                               ptrNumbers.get(), numbersCount,
-                                               delivery,
-                                               hasRead, read,
-                                               hasThreadId, threadId,
-                                               aReverse, cursorCallback,
-                                               getter_AddRefs(continueCallback));
-  if (NS_FAILED(rv)) {
-    aRv.Throw(rv);
-    return nullptr;
-  }
-
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  if (!window) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  cursorCallback->mDOMCursor =
-    new MobileMessageCursor(window, continueCallback);
-
-  RefPtr<DOMCursor> cursor(cursorCallback->mDOMCursor);
-  return cursor.forget();
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::MarkMessageRead(int32_t aId,
-                                      bool aValue,
-                                      bool aSendReadReport,
-                                      ErrorResult& aRv)
-{
-  nsCOMPtr<nsIMobileMessageDatabaseService> dbService =
-    do_GetService(MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
-  if (!dbService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  if (!window) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  RefPtr<DOMRequest> request = new DOMRequest(window);
-  nsCOMPtr<nsIMobileMessageCallback> msgCallback = new MobileMessageCallback(request);
-  nsresult rv = dbService->MarkMessageRead(aId, aValue, aSendReadReport,
-                                           msgCallback);
-  if (NS_FAILED(rv)) {
-    aRv.Throw(rv);
-    return nullptr;
-  }
-
-  return request.forget();
-}
-
-already_AddRefed<DOMCursor>
-MobileMessageManager::GetThreads(ErrorResult& aRv)
-{
-  nsCOMPtr<nsIMobileMessageDatabaseService> dbService =
-    do_GetService(MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
-  if (!dbService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  RefPtr<MobileMessageCursorCallback> cursorCallback =
-    new MobileMessageCursorCallback();
-
-  nsCOMPtr<nsICursorContinueCallback> continueCallback;
-  nsresult rv = dbService->CreateThreadCursor(cursorCallback,
-                                              getter_AddRefs(continueCallback));
-  if (NS_FAILED(rv)) {
-    aRv.Throw(rv);
-    return nullptr;
-  }
-
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  if (!window) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  cursorCallback->mDOMCursor =
-    new MobileMessageCursor(window, continueCallback);
-
-  RefPtr<DOMCursor> cursor(cursorCallback->mDOMCursor);
-  return cursor.forget();
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::RetrieveMMS(int32_t aId,
-                                  ErrorResult& aRv)
-{
-  nsCOMPtr<nsIMmsService> mmsService = do_GetService(MMS_SERVICE_CONTRACTID);
-  if (!mmsService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  if (!window) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  RefPtr<DOMRequest> request = new DOMRequest(window);
-  nsCOMPtr<nsIMobileMessageCallback> msgCallback = new MobileMessageCallback(request);
-
-  nsresult rv = mmsService->Retrieve(aId, msgCallback);
-  if (NS_FAILED(rv)) {
-    aRv.Throw(rv);
-    return nullptr;
-  }
-
-  return request.forget();
-}
-
-already_AddRefed<DOMRequest>
-MobileMessageManager::RetrieveMMS(MmsMessage& aMessage,
-                                  ErrorResult& aRv)
-{
-  return RetrieveMMS(aMessage.Id(), aRv);
-}
-
-nsresult
-MobileMessageManager::DispatchTrustedSmsEventToSelf(const char* aTopic,
-                                                    const nsAString& aEventName,
-                                                    nsISupports* aMsg)
-{
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  NS_ENSURE_TRUE(window, NS_ERROR_FAILURE);
-
-  nsCOMPtr<nsISmsMessage> sms = do_QueryInterface(aMsg);
-  if (sms) {
-    MozSmsEventInit init;
-    init.mBubbles = false;
-    init.mCancelable = false;
-    init.mMessage =
-      new SmsMessage(window, static_cast<SmsMessageInternal*>(sms.get()));
-
-    RefPtr<MozSmsEvent> event =
-      MozSmsEvent::Constructor(this, aEventName, init);
-    return DispatchTrustedEvent(event);
-  }
-
-  nsCOMPtr<nsIMmsMessage> mms = do_QueryInterface(aMsg);
-  if (mms) {
-    MozMmsEventInit init;
-    init.mBubbles = false;
-    init.mCancelable = false;
-    init.mMessage =
-      new MmsMessage(window, static_cast<MmsMessageInternal*>(mms.get()));
-
-    RefPtr<MozMmsEvent> event =
-      MozMmsEvent::Constructor(this, aEventName, init);
-    return DispatchTrustedEvent(event);
-  }
-
-  nsAutoCString errorMsg;
-  errorMsg.AssignLiteral("Got a '");
-  errorMsg.Append(aTopic);
-  errorMsg.AppendLiteral("' topic without a valid message!");
-  NS_ERROR(errorMsg.get());
-  return NS_OK;
-}
-
-nsresult
-MobileMessageManager::DispatchTrustedDeletedEventToSelf(nsISupports* aDeletedInfo)
-{
-  nsCOMPtr<nsIDeletedMessageInfo> deletedInfo = do_QueryInterface(aDeletedInfo);
-  if (deletedInfo) {
-    MozMessageDeletedEventInit init;
-    init.mBubbles = false;
-    init.mCancelable = false;
-    DeletedMessageInfo* info =
-      static_cast<DeletedMessageInfo*>(deletedInfo.get());
-
-    uint32_t msgIdLength = info->GetData().deletedMessageIds().Length();
-    if (msgIdLength) {
-      Sequence<int32_t>& deletedMsgIds = init.mDeletedMessageIds.SetValue();
-      if (!deletedMsgIds.AppendElements(info->GetData().deletedMessageIds(),
-                                        fallible)) {
-        return NS_ERROR_OUT_OF_MEMORY;
-      }
-    }
-
-    uint32_t threadIdLength = info->GetData().deletedThreadIds().Length();
-    if (threadIdLength) {
-      Sequence<uint64_t>& deletedThreadIds = init.mDeletedThreadIds.SetValue();
-      if (!deletedThreadIds.AppendElements(info->GetData().deletedThreadIds(),
-                                           fallible)) {
-        return NS_ERROR_OUT_OF_MEMORY;
-      }
-    }
-
-    RefPtr<MozMessageDeletedEvent> event =
-      MozMessageDeletedEvent::Constructor(this, DELETED_EVENT_NAME, init);
-    return DispatchTrustedEvent(event);
-  }
-
-  NS_ERROR("Got a 'deleted' topic without a valid message!");
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageManager::Observe(nsISupports* aSubject, const char* aTopic,
-                              const char16_t* aData)
-{
-  if (!strcmp(aTopic, kSmsReceivedObserverTopic)) {
-    return DispatchTrustedSmsEventToSelf(aTopic, RECEIVED_EVENT_NAME, aSubject);
-  }
-
-  if (!strcmp(aTopic, kSmsRetrievingObserverTopic)) {
-    return DispatchTrustedSmsEventToSelf(aTopic, RETRIEVING_EVENT_NAME, aSubject);
-  }
-
-  if (!strcmp(aTopic, kSmsSendingObserverTopic)) {
-    return DispatchTrustedSmsEventToSelf(aTopic, SENDING_EVENT_NAME, aSubject);
-  }
-
-  if (!strcmp(aTopic, kSmsSentObserverTopic)) {
-    return DispatchTrustedSmsEventToSelf(aTopic, SENT_EVENT_NAME, aSubject);
-  }
-
-  if (!strcmp(aTopic, kSmsFailedObserverTopic)) {
-    return DispatchTrustedSmsEventToSelf(aTopic, FAILED_EVENT_NAME, aSubject);
-  }
-
-  if (!strcmp(aTopic, kSmsDeliverySuccessObserverTopic)) {
-    return DispatchTrustedSmsEventToSelf(aTopic, DELIVERY_SUCCESS_EVENT_NAME, aSubject);
-  }
-
-  if (!strcmp(aTopic, kSmsDeliveryErrorObserverTopic)) {
-    return DispatchTrustedSmsEventToSelf(aTopic, DELIVERY_ERROR_EVENT_NAME, aSubject);
-  }
-
-  if (!strcmp(aTopic, kSmsReadSuccessObserverTopic)) {
-    return DispatchTrustedSmsEventToSelf(aTopic, READ_SUCCESS_EVENT_NAME, aSubject);
-  }
-
-  if (!strcmp(aTopic, kSmsReadErrorObserverTopic)) {
-    return DispatchTrustedSmsEventToSelf(aTopic, READ_ERROR_EVENT_NAME, aSubject);
-  }
-
-  if (!strcmp(aTopic, kSmsDeletedObserverTopic)) {
-    return DispatchTrustedDeletedEventToSelf(aSubject);
-  }
-
-  return NS_OK;
-}
-
-already_AddRefed<Promise>
-MobileMessageManager::GetSmscAddress(const Optional<uint32_t>& aServiceId,
-                                     ErrorResult& aRv)
-{
-  nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
-  if (!smsService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  // Use the default one unless |aSendParams.serviceId| is available.
-  uint32_t serviceId;
-  nsresult rv;
-  if (aServiceId.WasPassed()) {
-    serviceId = aServiceId.Value();
-  } else {
-    rv = smsService->GetSmsDefaultServiceId(&serviceId);
-    if (NS_FAILED(rv)) {
-      aRv.Throw(rv);
-      return nullptr;
-    }
-  }
-
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  if (!window) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(window);
-  if (!global) {
-    aRv.Throw(NS_ERROR_UNEXPECTED);
-    return nullptr;
-  }
-
-  RefPtr<Promise> promise = Promise::Create(global, aRv);
-  if (aRv.Failed()) {
-    return nullptr;
-  }
-
-  nsCOMPtr<nsIMobileMessageCallback> msgCallback =
-    new MobileMessageCallback(promise);
-
-  rv = smsService->GetSmscAddress(serviceId, msgCallback);
-  if (NS_FAILED(rv)) {
-    promise->MaybeReject(rv);
-    return promise.forget();
-  }
-
-  return promise.forget();
-}
-
-already_AddRefed<Promise>
-MobileMessageManager::SetSmscAddress(const SmscAddress& aSmscAddress,
-                                     const Optional<uint32_t>& aServiceId,
-                                     ErrorResult& aRv)
-{
-  nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
-  if (!smsService) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  // Use the default one unless |serviceId| is available.
-  uint32_t serviceId;
-  nsresult rv;
-  if (aServiceId.WasPassed()) {
-    serviceId = aServiceId.Value();
-  } else {
-    rv = smsService->GetSmsDefaultServiceId(&serviceId);
-    if (NS_FAILED(rv)) {
-      aRv.Throw(rv);
-      return nullptr;
-    }
-  }
-
-  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
-  if (!window) {
-    aRv.Throw(NS_ERROR_FAILURE);
-    return nullptr;
-  }
-
-  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(window);
-  if (!global) {
-    aRv.Throw(NS_ERROR_UNEXPECTED);
-    return nullptr;
-  }
-
-  RefPtr<Promise> promise = Promise::Create(global, aRv);
-  if (aRv.Failed()) {
-    return nullptr;
-  }
-
-  if (!aSmscAddress.mAddress.WasPassed()) {
-    NS_WARNING("SmscAddress.address is a mandatory field and can not be omitted.");
-    promise->MaybeReject(NS_ERROR_DOM_INVALID_ACCESS_ERR);
-    return promise.forget();
-  }
-
-  nsString address = aSmscAddress.mAddress.Value();
-  TypeOfNumber ton = aSmscAddress.mTypeOfAddress.mTypeOfNumber;
-  NumberPlanIdentification npi =
-    aSmscAddress.mTypeOfAddress.mNumberPlanIdentification;
-
-  // If the address begins with +, set TON to international no matter what has
-  // passed in.
-  if (!address.IsEmpty() && address[0] == '+') {
-    ton = TypeOfNumber::International;
-  }
-
-  nsCOMPtr<nsIMobileMessageCallback> msgCallback =
-    new MobileMessageCallback(promise);
-
-  rv = smsService->SetSmscAddress(serviceId, address,
-    static_cast<uint32_t>(ton), static_cast<uint32_t>(npi), msgCallback);
-  if (NS_FAILED(rv)) {
-    promise->MaybeReject(rv);
-    return promise.forget();
-  }
-
-  return promise.forget();
-}
-
-
-} // namespace dom
-} // namespace mozilla
-
-already_AddRefed<nsISmsService>
-NS_CreateSmsService()
-{
-  nsCOMPtr<nsISmsService> smsService;
-
-  if (XRE_IsContentProcess()) {
-    smsService = SmsIPCService::GetSingleton();
-  } else {
-#if defined(MOZ_WIDGET_ANDROID) && defined(MOZ_WEBSMS_BACKEND)
-    smsService = new SmsService();
-#elif defined(MOZ_WIDGET_GONK) && defined(MOZ_B2G_RIL)
-    smsService = do_GetService(GONK_SMSSERVICE_CONTRACTID);
-#endif
-  }
-
-  return smsService.forget();
-}
-
-already_AddRefed<nsIMobileMessageDatabaseService>
-NS_CreateMobileMessageDatabaseService()
-{
-  nsCOMPtr<nsIMobileMessageDatabaseService> mobileMessageDBService;
-  if (XRE_IsContentProcess()) {
-    mobileMessageDBService = SmsIPCService::GetSingleton();
-  } else {
-#if defined(MOZ_WIDGET_ANDROID) && defined(MOZ_WEBSMS_BACKEND)
-    mobileMessageDBService = new MobileMessageDatabaseService();
-#elif defined(MOZ_WIDGET_GONK) && defined(MOZ_B2G_RIL)
-    mobileMessageDBService =
-      do_CreateInstance(GONK_MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
-#endif
-  }
-
-  return mobileMessageDBService.forget();
-}
-
-already_AddRefed<nsIMmsService>
-NS_CreateMmsService()
-{
-  nsCOMPtr<nsIMmsService> mmsService;
-
-  if (XRE_IsContentProcess()) {
-    mmsService = SmsIPCService::GetSingleton();
-  } else {
-#if defined(MOZ_WIDGET_GONK) && defined(MOZ_B2G_RIL)
-    mmsService = do_CreateInstance("@mozilla.org/mms/gonkmmsservice;1");
-#endif
-  }
-
-  return mmsService.forget();
-}
-
-already_AddRefed<nsIMobileMessageService>
-NS_CreateMobileMessageService()
-{
-  nsCOMPtr<nsIMobileMessageService> service = new MobileMessageService();
-  return service.forget();
-}
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageManager.h
+++ /dev/null
@@ -1,167 +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_mobilemessage_MobileMessageManager_h
-#define mozilla_dom_mobilemessage_MobileMessageManager_h
-
-#include "mozilla/Attributes.h"
-#include "mozilla/DOMEventTargetHelper.h"
-#include "nsIObserver.h"
-
-class nsISmsService;
-
-namespace mozilla {
-namespace dom {
-
-class Promise;
-class DOMRequest;
-class DOMCursor;
-class MmsMessage;
-struct MmsParameters;
-struct MmsSendParameters;
-struct MobileMessageFilter;
-class OwningLongOrSmsMessageOrMmsMessage;
-class SmsMessage;
-struct SmsSendParameters;
-struct SmscAddress;
-
-class MobileMessageManager final : public DOMEventTargetHelper
-                                 , public nsIObserver
-{
-public:
-  NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_NSIOBSERVER
-
-  NS_REALLY_FORWARD_NSIDOMEVENTTARGET(DOMEventTargetHelper)
-
-  explicit MobileMessageManager(nsPIDOMWindowInner* aWindow);
-
-  void Init();
-  void Shutdown();
-
-  nsPIDOMWindowInner*
-  GetParentObject() const { return GetOwner(); }
-
-  // WrapperCache
-  virtual JSObject*
-  WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
-
-  // WebIDL Interface
-  already_AddRefed<DOMRequest>
-  GetSegmentInfoForText(const nsAString& aText,
-                        ErrorResult& aRv);
-
-  already_AddRefed<DOMRequest>
-  Send(const nsAString& aNumber,
-       const nsAString& aText,
-       const SmsSendParameters& aSendParams,
-       ErrorResult& aRv);
-
-  void
-  Send(const Sequence<nsString>& aNumbers,
-       const nsAString& aText,
-       const SmsSendParameters& aSendParams,
-       nsTArray<RefPtr<DOMRequest>>& aReturn,
-       ErrorResult& aRv);
-
-  already_AddRefed<DOMRequest>
-  SendMMS(const MmsParameters& aParameters,
-          const MmsSendParameters& aSendParams,
-          ErrorResult& aRv);
-
-  already_AddRefed<DOMRequest>
-  GetMessage(int32_t aId,
-             ErrorResult& aRv);
-
-  already_AddRefed<DOMRequest>
-  Delete(int32_t aId,
-         ErrorResult& aRv);
-
-  already_AddRefed<DOMRequest>
-  Delete(SmsMessage& aMessage,
-         ErrorResult& aRv);
-
-  already_AddRefed<DOMRequest>
-  Delete(MmsMessage& aMessage,
-         ErrorResult& aRv);
-
-  already_AddRefed<DOMRequest>
-  Delete(const Sequence<OwningLongOrSmsMessageOrMmsMessage>& aParams,
-         ErrorResult& aRv);
-
-  already_AddRefed<DOMCursor>
-  GetMessages(const MobileMessageFilter& aFilter,
-              bool aReverse,
-              ErrorResult& aRv);
-
-  already_AddRefed<DOMRequest>
-  MarkMessageRead(int32_t aId,
-                  bool aRead,
-                  bool aSendReadReport,
-                  ErrorResult& aRv);
-
-  already_AddRefed<DOMCursor>
-  GetThreads(ErrorResult& aRv);
-
-  already_AddRefed<DOMRequest>
-  RetrieveMMS(int32_t aId,
-              ErrorResult& aRv);
-
-  already_AddRefed<DOMRequest>
-  RetrieveMMS(MmsMessage& aMessage,
-              ErrorResult& aRv);
-
-  already_AddRefed<Promise>
-  GetSmscAddress(const Optional<uint32_t>& aServiceId,
-                 ErrorResult& aRv);
-
-  already_AddRefed<Promise>
-  SetSmscAddress(const SmscAddress& aSmscAddress,
-                 const Optional<uint32_t>& aServiceId,
-                 ErrorResult& aRv);
-
-  IMPL_EVENT_HANDLER(received)
-  IMPL_EVENT_HANDLER(retrieving)
-  IMPL_EVENT_HANDLER(sending)
-  IMPL_EVENT_HANDLER(sent)
-  IMPL_EVENT_HANDLER(failed)
-  IMPL_EVENT_HANDLER(deliverysuccess)
-  IMPL_EVENT_HANDLER(deliveryerror)
-  IMPL_EVENT_HANDLER(readsuccess)
-  IMPL_EVENT_HANDLER(readerror)
-  IMPL_EVENT_HANDLER(deleted)
-
-private:
-  ~MobileMessageManager() {}
-
-  /**
-   * Internal Send() method used to send one message.
-   */
-  already_AddRefed<DOMRequest>
-  Send(nsISmsService* aSmsService,
-       uint32_t aServiceId,
-       const nsAString& aNumber,
-       const nsAString& aText,
-       ErrorResult& aRv);
-
-  already_AddRefed<DOMRequest>
-  Delete(int32_t* aIdArray,
-         uint32_t aSize,
-         ErrorResult& aRv);
-
-  nsresult
-  DispatchTrustedSmsEventToSelf(const char* aTopic,
-                                const nsAString& aEventName,
-                                nsISupports* aMsg);
-
-  nsresult
-  DispatchTrustedDeletedEventToSelf(nsISupports* aDeletedInfo);
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_MobileMessageManager_h
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageService.cpp
+++ /dev/null
@@ -1,129 +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 "SmsMessageInternal.h"
-#include "MmsMessageInternal.h"
-#include "MobileMessageThreadInternal.h"
-#include "MobileMessageService.h"
-#include "DeletedMessageInfo.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-NS_IMPL_ISUPPORTS(MobileMessageService, nsIMobileMessageService)
-
-NS_IMETHODIMP
-MobileMessageService::CreateSmsMessage(int32_t aId,
-                                       uint64_t aThreadId,
-                                       const nsAString& aIccId,
-                                       const nsAString& aDelivery,
-                                       const nsAString& aDeliveryStatus,
-                                       const nsAString& aSender,
-                                       const nsAString& aReceiver,
-                                       const nsAString& aBody,
-                                       const nsAString& aMessageClass,
-                                       uint64_t aTimestamp,
-                                       uint64_t aSentTimestamp,
-                                       uint64_t aDeliveryTimestamp,
-                                       bool aRead,
-                                       JSContext* aCx,
-                                       nsISmsMessage** aMessage)
-{
-  return SmsMessageInternal::Create(aId,
-                                    aThreadId,
-                                    aIccId,
-                                    aDelivery,
-                                    aDeliveryStatus,
-                                    aSender,
-                                    aReceiver,
-                                    aBody,
-                                    aMessageClass,
-                                    aTimestamp,
-                                    aSentTimestamp,
-                                    aDeliveryTimestamp,
-                                    aRead,
-                                    aCx,
-                                    aMessage);
-}
-
-NS_IMETHODIMP
-MobileMessageService::CreateMmsMessage(int32_t aId,
-                                       uint64_t aThreadId,
-                                       const nsAString& aIccId,
-                                       const nsAString& aDelivery,
-                                       JS::Handle<JS::Value> aDeliveryInfo,
-                                       const nsAString& aSender,
-                                       JS::Handle<JS::Value> aReceivers,
-                                       uint64_t aTimestamp,
-                                       uint64_t aSentTimestamp,
-                                       bool aRead,
-                                       const nsAString& aSubject,
-                                       const nsAString& aSmil,
-                                       JS::Handle<JS::Value> aAttachments,
-                                       uint64_t aExpiryDate,
-                                       bool aReadReportRequested,
-                                       JSContext* aCx,
-                                       nsIMmsMessage** aMessage)
-{
-  return MmsMessageInternal::Create(aId,
-                                    aThreadId,
-                                    aIccId,
-                                    aDelivery,
-                                    aDeliveryInfo,
-                                    aSender,
-                                    aReceivers,
-                                    aTimestamp,
-                                    aSentTimestamp,
-                                    aRead,
-                                    aSubject,
-                                    aSmil,
-                                    aAttachments,
-                                    aExpiryDate,
-                                    aReadReportRequested,
-                                    aCx,
-                                    aMessage);
-}
-
-NS_IMETHODIMP
-MobileMessageService::CreateThread(uint64_t aId,
-                                   JS::Handle<JS::Value> aParticipants,
-                                   uint64_t aTimestamp,
-                                   const nsAString& aLastMessageSubject,
-                                   const nsAString& aBody,
-                                   uint64_t aUnreadCount,
-                                   const nsAString& aLastMessageType,
-                                   JSContext* aCx,
-                                   nsIMobileMessageThread** aThread)
-{
-  return MobileMessageThreadInternal::Create(aId,
-                                             aParticipants,
-                                             aTimestamp,
-                                             aLastMessageSubject,
-                                             aBody,
-                                             aUnreadCount,
-                                             aLastMessageType,
-                                             aCx,
-                                             aThread);
-}
-
-NS_IMETHODIMP
-MobileMessageService::CreateDeletedMessageInfo(int32_t* aMessageIds,
-                                               uint32_t aMsgCount,
-                                               uint64_t* aThreadIds,
-                                               uint32_t  aThreadCount,
-                                               nsIDeletedMessageInfo** aDeletedInfo)
-{
-  return DeletedMessageInfo::Create(aMessageIds,
-                                    aMsgCount,
-                                    aThreadIds,
-                                    aThreadCount,
-                                    aDeletedInfo);
-}
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageService.h
+++ /dev/null
@@ -1,34 +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_mobilemessage_MobileMessageService_h
-#define mozilla_dom_mobilemessage_MobileMessageService_h
-
-#include "mozilla/Attributes.h" // For final
-#include "nsIMobileMessageService.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-class MobileMessageService final : public nsIMobileMessageService
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIMOBILEMESSAGESERVICE
-
-  MobileMessageService() { MOZ_COUNT_CTOR(MobileMessageService); }
-
-private:
-  // final suppresses -Werror,-Wdelete-non-virtual-dtor
-  ~MobileMessageService() { MOZ_COUNT_DTOR(MobileMessageService); }
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_MobileMessageService_h
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageThread.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* 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 "MobileMessageThread.h"
-
-#include "MobileMessageThreadInternal.h"
-#include "mozilla/dom/MobileMessageThreadBinding.h"
-
-using namespace mozilla::dom::mobilemessage;
-
-namespace mozilla {
-namespace dom {
-
-NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(MobileMessageThread, mWindow, mThread)
-NS_IMPL_CYCLE_COLLECTING_ADDREF(MobileMessageThread)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(MobileMessageThread)
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MobileMessageThread)
-  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
-  NS_INTERFACE_MAP_ENTRY(nsISupports)
-NS_INTERFACE_MAP_END
-
-MobileMessageThread::MobileMessageThread(nsPIDOMWindowInner* aWindow,
-                                         MobileMessageThreadInternal* aThread)
-  : mWindow(aWindow)
-  , mThread(aThread)
-{
-}
-
-MobileMessageThread::~MobileMessageThread()
-{
-}
-
-JSObject*
-MobileMessageThread::WrapObject(JSContext* aCx,
-                                JS::Handle<JSObject*> aGivenProto)
-{
-  return MobileMessageThreadBinding::Wrap(aCx, this, aGivenProto);
-}
-
-uint64_t
-MobileMessageThread::Id() const
-{
-  uint64_t id;
-  mThread->GetId(&id);
-  return id;
-}
-
-void
-MobileMessageThread::GetLastMessageSubject(nsString& aRetVal) const
-{
-  mThread->GetLastMessageSubject(aRetVal);
-}
-
-void
-MobileMessageThread::GetBody(nsString& aRetVal) const
-{
-  mThread->GetBody(aRetVal);
-}
-
-uint64_t
-MobileMessageThread::UnreadCount() const
-{
-  uint64_t count;
-  mThread->GetUnreadCount(&count);
-  return count;
-}
-
-void
-MobileMessageThread::GetParticipants(nsTArray<nsString>& aRetVal) const
-{
-  aRetVal = mThread->mData.participants();
-}
-
-DOMTimeStamp
-MobileMessageThread::Timestamp() const
-{
-  DOMTimeStamp timestamp;
-  mThread->GetTimestamp(&timestamp);
-  return timestamp;
-}
-
-void
-MobileMessageThread::GetLastMessageType(nsString& aRetVal) const
-{
-  mThread->GetLastMessageType(aRetVal);
-}
-
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageThread.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* 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_MobileMessageThread_h
-#define mozilla_dom_MobileMessageThread_h
-
-#include "mozilla/dom/BindingDeclarations.h"
-#include "nsWrapperCache.h"
-
-class nsPIDOMWindowInner;
-
-namespace mozilla {
-namespace dom {
-
-namespace mobilemessage {
-class MobileMessageThreadInternal;
-} // namespace mobilemessage
-
-/**
- * Each instance of this class provides the DOM-level representation of
- * a MobileMessageThread object to bind it to a window being exposed to.
- */
-class MobileMessageThread final : public nsISupports,
-                                  public nsWrapperCache
-{
-public:
-  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(MobileMessageThread)
-
-  MobileMessageThread(nsPIDOMWindowInner* aWindow,
-                      mobilemessage::MobileMessageThreadInternal* aThread);
-
-  nsPIDOMWindowInner*
-  GetParentObject() const
-  {
-    return mWindow;
-  }
-
-  virtual JSObject*
-  WrapObject(JSContext* aCx,
-             JS::Handle<JSObject*> aGivenProto) override;
-
-  uint64_t
-  Id() const;
-
-  void
-  GetLastMessageSubject(nsString& aRetVal) const;
-
-  void
-  GetBody(nsString& aRetVal) const;
-
-  uint64_t
-  UnreadCount() const;
-
-  void
-  GetParticipants(nsTArray<nsString>& aRetVal) const;
-
-  DOMTimeStamp
-  Timestamp() const;
-
-  void
-  GetLastMessageType(nsString& aRetVal) const;
-
-private:
-  // Don't try to use the default constructor.
-  MobileMessageThread() = delete;
-
-  ~MobileMessageThread();
-
-  nsCOMPtr<nsPIDOMWindowInner> mWindow;
-  RefPtr<mobilemessage::MobileMessageThreadInternal> mThread;
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_MobileMessageThread_h
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageThreadInternal.cpp
+++ /dev/null
@@ -1,185 +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 "MobileMessageThreadInternal.h"
-#include "nsIDOMClassInfo.h"
-#include "jsapi.h"           // For OBJECT_TO_JSVAL and JS_NewDateObjectMsec
-#include "nsJSUtils.h"       // For nsAutoJSString
-#include "nsTArrayHelpers.h" // For nsTArrayToJSArray
-#include "mozilla/dom/mobilemessage/Constants.h" // For MessageType
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-NS_IMPL_ISUPPORTS(MobileMessageThreadInternal, nsIMobileMessageThread)
-
-/* static */ nsresult
-MobileMessageThreadInternal::Create(uint64_t aId,
-                                    const JS::Value& aParticipants,
-                                    uint64_t aTimestamp,
-                                    const nsAString& aLastMessageSubject,
-                                    const nsAString& aBody,
-                                    uint64_t aUnreadCount,
-                                    const nsAString& aLastMessageType,
-                                    JSContext* aCx,
-                                    nsIMobileMessageThread** aThread)
-{
-  *aThread = nullptr;
-
-  // ThreadData exposes these as references, so we can simply assign
-  // to them.
-  ThreadData data;
-  data.id() = aId;
-  data.lastMessageSubject().Assign(aLastMessageSubject);
-  data.body().Assign(aBody);
-  data.unreadCount() = aUnreadCount;
-
-  // Participants.
-  {
-    if (!aParticipants.isObject()) {
-      return NS_ERROR_INVALID_ARG;
-    }
-
-    JS::Rooted<JSObject*> obj(aCx, &aParticipants.toObject());
-    bool isArray;
-    if (!JS_IsArrayObject(aCx, obj, &isArray)) {
-      return NS_ERROR_FAILURE;
-    }
-    if (!isArray) {
-      return NS_ERROR_INVALID_ARG;
-    }
-
-    uint32_t length;
-    MOZ_ALWAYS_TRUE(JS_GetArrayLength(aCx, obj, &length));
-    NS_ENSURE_TRUE(length, NS_ERROR_INVALID_ARG);
-
-    for (uint32_t i = 0; i < length; ++i) {
-      JS::Rooted<JS::Value> val(aCx);
-
-      if (!JS_GetElement(aCx, obj, i, &val) || !val.isString()) {
-        return NS_ERROR_INVALID_ARG;
-      }
-
-      nsAutoJSString str;
-      if (!str.init(aCx, val.toString())) {
-        return NS_ERROR_FAILURE;
-      }
-
-      data.participants().AppendElement(str);
-    }
-  }
-
-  // Set |timestamp|;
-  data.timestamp() = aTimestamp;
-
-  // Set |lastMessageType|.
-  {
-    MessageType lastMessageType;
-    if (aLastMessageType.Equals(MESSAGE_TYPE_SMS)) {
-      lastMessageType = eMessageType_SMS;
-    } else if (aLastMessageType.Equals(MESSAGE_TYPE_MMS)) {
-      lastMessageType = eMessageType_MMS;
-    } else {
-      return NS_ERROR_INVALID_ARG;
-    }
-    data.lastMessageType() = lastMessageType;
-  }
-
-  nsCOMPtr<nsIMobileMessageThread> thread =
-    new MobileMessageThreadInternal(data);
-  thread.forget(aThread);
-  return NS_OK;
-}
-
-MobileMessageThreadInternal::MobileMessageThreadInternal(uint64_t aId,
-                                                         const nsTArray<nsString>& aParticipants,
-                                                         uint64_t aTimestamp,
-                                                         const nsString& aLastMessageSubject,
-                                                         const nsString& aBody,
-                                                         uint64_t aUnreadCount,
-                                                         MessageType aLastMessageType)
-  : mData(aId, aParticipants, aTimestamp, aLastMessageSubject, aBody,
-          aUnreadCount, aLastMessageType)
-{
-  MOZ_ASSERT(aParticipants.Length());
-}
-
-MobileMessageThreadInternal::MobileMessageThreadInternal(const ThreadData& aData)
-  : mData(aData)
-{
-  MOZ_ASSERT(aData.participants().Length());
-}
-
-NS_IMETHODIMP
-MobileMessageThreadInternal::GetId(uint64_t* aId)
-{
-  *aId = mData.id();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageThreadInternal::GetLastMessageSubject(nsAString& aLastMessageSubject)
-{
-  aLastMessageSubject = mData.lastMessageSubject();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageThreadInternal::GetBody(nsAString& aBody)
-{
-  aBody = mData.body();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageThreadInternal::GetUnreadCount(uint64_t* aUnreadCount)
-{
-  *aUnreadCount = mData.unreadCount();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageThreadInternal::GetParticipants(JSContext* aCx,
-                                             JS::MutableHandle<JS::Value> aParticipants)
-{
-  JS::Rooted<JSObject*> obj(aCx);
-
-  nsresult rv = nsTArrayToJSArray(aCx, mData.participants(), &obj);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  aParticipants.setObject(*obj);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageThreadInternal::GetTimestamp(DOMTimeStamp* aDate)
-{
-  *aDate = mData.timestamp();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageThreadInternal::GetLastMessageType(nsAString& aLastMessageType)
-{
-  switch (mData.lastMessageType()) {
-    case eMessageType_SMS:
-      aLastMessageType = MESSAGE_TYPE_SMS;
-      break;
-    case eMessageType_MMS:
-      aLastMessageType = MESSAGE_TYPE_MMS;
-      break;
-    case eMessageType_EndGuard:
-    default:
-      MOZ_CRASH("We shouldn't get any other message type!");
-  }
-
-  return NS_OK;
-}
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/MobileMessageThreadInternal.h
+++ /dev/null
@@ -1,69 +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_mobilemessage_MobileMessageThreadInternal_h
-#define mozilla_dom_mobilemessage_MobileMessageThreadInternal_h
-
-#include "mozilla/Attributes.h"
-#include "mozilla/dom/mobilemessage/SmsTypes.h"
-#include "nsIMobileMessageThread.h"
-#include "nsString.h"
-
-namespace mozilla {
-namespace dom {
-
-class MobileMessageThread;
-
-namespace mobilemessage {
-
-class ThreadData;
-
-class MobileMessageThreadInternal final : public nsIMobileMessageThread
-{
-  // This allows the MobileMessageThread class to access data members, i.e. participants
-  // without JS API.
-  friend class mozilla::dom::MobileMessageThread;
-
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIMOBILEMESSAGETHREAD
-
-  MobileMessageThreadInternal(uint64_t aId,
-                              const nsTArray<nsString>& aParticipants,
-                              uint64_t aTimestamp,
-                              const nsString& aLastMessageSubject,
-                              const nsString& aBody,
-                              uint64_t aUnreadCount,
-                              mobilemessage::MessageType aLastMessageType);
-
-  explicit MobileMessageThreadInternal(const ThreadData& aData);
-
-  static nsresult Create(uint64_t aId,
-                         const JS::Value& aParticipants,
-                         uint64_t aTimestamp,
-                         const nsAString& aLastMessageSubject,
-                         const nsAString& aBody,
-                         uint64_t aUnreadCount,
-                         const nsAString& aLastMessageType,
-                         JSContext* aCx,
-                         nsIMobileMessageThread** aThread);
-
-  const ThreadData& GetData() const { return mData; }
-
-private:
-  ~MobileMessageThreadInternal() {}
-
-  // Don't try to use the default constructor.
-  MobileMessageThreadInternal() = delete;
-
-  ThreadData mData;
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_MobileMessageThreadInternal_h
deleted file mode 100644
--- a/dom/mobilemessage/SmsMessage.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* 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 "SmsMessage.h"
-
-#include "SmsMessageInternal.h"
-#include "mozilla/dom/SmsMessageBinding.h"
-
-namespace mozilla {
-namespace dom {
-
-NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(SmsMessage, mWindow, mMessage)
-NS_IMPL_CYCLE_COLLECTING_ADDREF(SmsMessage)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(SmsMessage)
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(SmsMessage)
-  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
-  NS_INTERFACE_MAP_ENTRY(nsISupports)
-NS_INTERFACE_MAP_END
-
-SmsMessage::SmsMessage(nsPIDOMWindowInner* aWindow, SmsMessageInternal* aMessage)
-  : mWindow(aWindow)
-  , mMessage(aMessage)
-{
-}
-
-SmsMessage::~SmsMessage()
-{
-}
-
-JSObject*
-SmsMessage::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
-{
-  return SmsMessageBinding::Wrap(aCx, this, aGivenProto);
-}
-
-void
-SmsMessage::GetType(nsString& aRetVal) const
-{
-  mMessage->GetType(aRetVal);
-}
-
-int32_t
-SmsMessage::Id() const
-{
-  int32_t id;
-  mMessage->GetId(&id);
-  return id;
-}
-
-uint64_t
-SmsMessage::ThreadId() const
-{
-  uint64_t id;
-  mMessage->GetThreadId(&id);
-  return id;
-}
-
-void
-SmsMessage::GetIccId(nsString& aRetVal) const
-{
-  mMessage->GetIccId(aRetVal);
-}
-
-void
-SmsMessage::GetDelivery(nsString& aRetVal) const
-{
-  mMessage->GetDelivery(aRetVal);
-}
-
-void
-SmsMessage::GetDeliveryStatus(nsString& aRetVal) const
-{
-  mMessage->GetDeliveryStatus(aRetVal);
-}
-
-void
-SmsMessage::GetSender(nsString& aRetVal) const
-{
-  mMessage->GetSender(aRetVal);
-}
-
-void
-SmsMessage::GetReceiver(nsString& aRetVal) const
-{
-  mMessage->GetReceiver(aRetVal);
-}
-
-void
-SmsMessage::GetBody(nsString& aRetVal) const
-{
-  mMessage->GetBody(aRetVal);
-}
-
-void
-SmsMessage::GetMessageClass(nsString& aRetVal) const
-{
-  mMessage->GetMessageClass(aRetVal);
-}
-
-uint64_t
-SmsMessage::Timestamp() const
-{
-  uint64_t timestamp;
-  mMessage->GetTimestamp(&timestamp);
-  return timestamp;
-}
-
-uint64_t
-SmsMessage::SentTimestamp() const
-{
-  uint64_t timestamp;
-  mMessage->GetSentTimestamp(&timestamp);
-  return timestamp;
-}
-
-uint64_t
-SmsMessage::DeliveryTimestamp() const
-{
-  uint64_t timestamp;
-  mMessage->GetDeliveryTimestamp(&timestamp);
-  return timestamp;
-}
-
-bool
-SmsMessage::Read() const
-{
-  bool read;
-  mMessage->GetRead(&read);
-  return read;
-}
-
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/SmsMessage.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* 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_SmsMessage_h
-#define mozilla_dom_SmsMessage_h
-
-#include "mozilla/dom/BindingDeclarations.h"
-#include "nsWrapperCache.h"
-
-class nsPIDOMWindowInner;
-
-namespace mozilla {
-namespace dom {
-
-namespace mobilemessage {
-class SmsMessageInternal;
-} // namespace mobilemessage
-
-/**
- * Each instance of this class provides the DOM-level representation of
- * a SmsMessage object to bind it to a window being exposed to.
- */
-class SmsMessage final : public nsISupports,
-                         public nsWrapperCache
-{
-public:
-  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(SmsMessage)
-
-  SmsMessage(nsPIDOMWindowInner* aWindow,
-             mobilemessage::SmsMessageInternal* aMessage);
-
-public:
-  nsPIDOMWindowInner*
-  GetParentObject() const
-  {
-    return mWindow;
-  }
-
-  virtual JSObject*
-  WrapObject(JSContext* aCx,
-             JS::Handle<JSObject*> aGivenProto) override;
-
-  void
-  GetType(nsString& aRetVal) const;
-
-  int32_t
-  Id() const;
-
-  uint64_t
-  ThreadId() const;
-
-  void
-  GetIccId(nsString& aRetVal) const;
-
-  void
-  GetDelivery(nsString& aRetVal) const;
-
-  void
-  GetDeliveryStatus(nsString& aRetVal) const;
-
-  void
-  GetSender(nsString& aRetVal) const;
-
-  void
-  GetReceiver(nsString& aRetVal) const;
-
-  void
-  GetBody(nsString& aRetVal) const;
-
-  void
-  GetMessageClass(nsString& aRetVal) const;
-
-  uint64_t
-  Timestamp() const;
-
-  uint64_t
-  SentTimestamp() const;
-
-  uint64_t
-  DeliveryTimestamp() const;
-
-  bool
-  Read() const;
-
-private:
-  // Don't try to use the default constructor.
-  SmsMessage() = delete;
-
-  ~SmsMessage();
-
-  nsCOMPtr<nsPIDOMWindowInner> mWindow;
-  RefPtr<mobilemessage::SmsMessageInternal> mMessage;
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_SmsMessage_h
deleted file mode 100644
--- a/dom/mobilemessage/SmsMessageInternal.cpp
+++ /dev/null
@@ -1,283 +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 "SmsMessageInternal.h"
-#include "nsIDOMClassInfo.h"
-#include "mozilla/dom/mobilemessage/Constants.h" // For MessageType
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-NS_IMPL_ISUPPORTS(SmsMessageInternal, nsISmsMessage)
-
-SmsMessageInternal::SmsMessageInternal(int32_t aId,
-                                       uint64_t aThreadId,
-                                       const nsString& aIccId,
-                                       DeliveryState aDelivery,
-                                       DeliveryStatus aDeliveryStatus,
-                                       const nsString& aSender,
-                                       const nsString& aReceiver,
-                                       const nsString& aBody,
-                                       MessageClass aMessageClass,
-                                       uint64_t aTimestamp,
-                                       uint64_t aSentTimestamp,
-                                       uint64_t aDeliveryTimestamp,
-                                       bool aRead)
-  : mData(aId, aThreadId, aIccId, aDelivery, aDeliveryStatus,
-          aSender, aReceiver, aBody, aMessageClass, aTimestamp, aSentTimestamp,
-          aDeliveryTimestamp, aRead)
-{
-}
-
-SmsMessageInternal::SmsMessageInternal(const SmsMessageData& aData)
-  : mData(aData)
-{
-}
-
-/* static */ nsresult
-SmsMessageInternal::Create(int32_t aId,
-                           uint64_t aThreadId,
-                           const nsAString& aIccId,
-                           const nsAString& aDelivery,
-                           const nsAString& aDeliveryStatus,
-                           const nsAString& aSender,
-                           const nsAString& aReceiver,
-                           const nsAString& aBody,
-                           const nsAString& aMessageClass,
-                           uint64_t aTimestamp,
-                           uint64_t aSentTimestamp,
-                           uint64_t aDeliveryTimestamp,
-                           bool aRead,
-                           JSContext* aCx,
-                           nsISmsMessage** aMessage)
-{
-  *aMessage = nullptr;
-
-  // SmsMessageData exposes these as references, so we can simply assign
-  // to them.
-  SmsMessageData data;
-  data.id() = aId;
-  data.threadId() = aThreadId;
-  data.iccId() = nsString(aIccId);
-  data.sender() = nsString(aSender);
-  data.receiver() = nsString(aReceiver);
-  data.body() = nsString(aBody);
-  data.read() = aRead;
-
-  if (aDelivery.Equals(DELIVERY_RECEIVED)) {
-    data.delivery() = eDeliveryState_Received;
-  } else if (aDelivery.Equals(DELIVERY_SENDING)) {
-    data.delivery() = eDeliveryState_Sending;
-  } else if (aDelivery.Equals(DELIVERY_SENT)) {
-    data.delivery() = eDeliveryState_Sent;
-  } else if (aDelivery.Equals(DELIVERY_ERROR)) {
-    data.delivery() = eDeliveryState_Error;
-  } else {
-    return NS_ERROR_INVALID_ARG;
-  }
-
-  if (aDeliveryStatus.Equals(DELIVERY_STATUS_NOT_APPLICABLE)) {
-    data.deliveryStatus() = eDeliveryStatus_NotApplicable;
-  } else if (aDeliveryStatus.Equals(DELIVERY_STATUS_SUCCESS)) {
-    data.deliveryStatus() = eDeliveryStatus_Success;
-  } else if (aDeliveryStatus.Equals(DELIVERY_STATUS_PENDING)) {
-    data.deliveryStatus() = eDeliveryStatus_Pending;
-  } else if (aDeliveryStatus.Equals(DELIVERY_STATUS_ERROR)) {
-    data.deliveryStatus() = eDeliveryStatus_Error;
-  } else {
-    return NS_ERROR_INVALID_ARG;
-  }
-
-  if (aMessageClass.Equals(MESSAGE_CLASS_NORMAL)) {
-    data.messageClass() = eMessageClass_Normal;
-  } else if (aMessageClass.Equals(MESSAGE_CLASS_CLASS_0)) {
-    data.messageClass() = eMessageClass_Class0;
-  } else if (aMessageClass.Equals(MESSAGE_CLASS_CLASS_1)) {
-    data.messageClass() = eMessageClass_Class1;
-  } else if (aMessageClass.Equals(MESSAGE_CLASS_CLASS_2)) {
-    data.messageClass() = eMessageClass_Class2;
-  } else if (aMessageClass.Equals(MESSAGE_CLASS_CLASS_3)) {
-    data.messageClass() = eMessageClass_Class3;
-  } else {
-    return NS_ERROR_INVALID_ARG;
-  }
-
-  // Set |timestamp|.
-  data.timestamp() = aTimestamp;
-
-  // Set |sentTimestamp|.
-  data.sentTimestamp() = aSentTimestamp;
-
-  // Set |deliveryTimestamp|.
-  data.deliveryTimestamp() = aDeliveryTimestamp;
-
-  nsCOMPtr<nsISmsMessage> message = new SmsMessageInternal(data);
-  message.swap(*aMessage);
-  return NS_OK;
-}
-
-const SmsMessageData&
-SmsMessageInternal::GetData() const
-{
-  return mData;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetType(nsAString& aType)
-{
-  aType = NS_LITERAL_STRING("sms");
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetId(int32_t* aId)
-{
-  *aId = mData.id();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetThreadId(uint64_t* aThreadId)
-{
-  *aThreadId = mData.threadId();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetIccId(nsAString& aIccId)
-{
-  aIccId = mData.iccId();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetDelivery(nsAString& aDelivery)
-{
-  switch (mData.delivery()) {
-    case eDeliveryState_Received:
-      aDelivery = DELIVERY_RECEIVED;
-      break;
-    case eDeliveryState_Sending:
-      aDelivery = DELIVERY_SENDING;
-      break;
-    case eDeliveryState_Sent:
-      aDelivery = DELIVERY_SENT;
-      break;
-    case eDeliveryState_Error:
-      aDelivery = DELIVERY_ERROR;
-      break;
-    case eDeliveryState_Unknown:
-    case eDeliveryState_EndGuard:
-    default:
-      MOZ_CRASH("We shouldn't get any other delivery state!");
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetDeliveryStatus(nsAString& aDeliveryStatus)
-{
-  switch (mData.deliveryStatus()) {
-    case eDeliveryStatus_NotApplicable:
-      aDeliveryStatus = DELIVERY_STATUS_NOT_APPLICABLE;
-      break;
-    case eDeliveryStatus_Success:
-      aDeliveryStatus = DELIVERY_STATUS_SUCCESS;
-      break;
-    case eDeliveryStatus_Pending:
-      aDeliveryStatus = DELIVERY_STATUS_PENDING;
-      break;
-    case eDeliveryStatus_Error:
-      aDeliveryStatus = DELIVERY_STATUS_ERROR;
-      break;
-    case eDeliveryStatus_EndGuard:
-    default:
-      MOZ_CRASH("We shouldn't get any other delivery status!");
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetSender(nsAString& aSender)
-{
-  aSender = mData.sender();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetReceiver(nsAString& aReceiver)
-{
-  aReceiver = mData.receiver();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetBody(nsAString& aBody)
-{
-  aBody = mData.body();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetMessageClass(nsAString& aMessageClass)
-{
-  switch (mData.messageClass()) {
-    case eMessageClass_Normal:
-      aMessageClass = MESSAGE_CLASS_NORMAL;
-      break;
-    case eMessageClass_Class0:
-      aMessageClass = MESSAGE_CLASS_CLASS_0;
-      break;
-    case eMessageClass_Class1:
-      aMessageClass = MESSAGE_CLASS_CLASS_1;
-      break;
-    case eMessageClass_Class2:
-      aMessageClass = MESSAGE_CLASS_CLASS_2;
-      break;
-    case eMessageClass_Class3:
-      aMessageClass = MESSAGE_CLASS_CLASS_3;
-      break;
-    default:
-      MOZ_CRASH("We shouldn't get any other message class!");
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetTimestamp(DOMTimeStamp* aTimestamp)
-{
-  *aTimestamp = mData.timestamp();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetSentTimestamp(DOMTimeStamp* aSentTimestamp)
-{
-  *aSentTimestamp = mData.sentTimestamp();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetDeliveryTimestamp(DOMTimeStamp* aDate)
-{
-  *aDate = mData.deliveryTimestamp();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsMessageInternal::GetRead(bool* aRead)
-{
-  *aRead = mData.read();
-  return NS_OK;
-}
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/SmsMessageInternal.h
+++ /dev/null
@@ -1,74 +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_mobilemessage_SmsMessageInternal_h
-#define mozilla_dom_mobilemessage_SmsMessageInternal_h
-
-#include "mozilla/dom/mobilemessage/SmsTypes.h"
-#include "nsISmsMessage.h"
-#include "nsString.h"
-#include "mozilla/dom/mobilemessage/Types.h"
-#include "mozilla/Attributes.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-class SmsMessageData;
-
-class SmsMessageInternal final : public nsISmsMessage
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSISMSMESSAGE
-
-  SmsMessageInternal(int32_t aId,
-                     uint64_t aThreadId,
-                     const nsString& aIccId,
-                     mobilemessage::DeliveryState aDelivery,
-                     mobilemessage::DeliveryStatus aDeliveryStatus,
-                     const nsString& aSender,
-                     const nsString& aReceiver,
-                     const nsString& aBody,
-                     mobilemessage::MessageClass aMessageClass,
-                     uint64_t aTimestamp,
-                     uint64_t aSentTimestamp,
-                     uint64_t aDeliveryTimestamp,
-                     bool aRead);
-
-  explicit SmsMessageInternal(const SmsMessageData& aData);
-
-  static nsresult Create(int32_t aId,
-                         uint64_t aThreadId,
-                         const nsAString& aIccId,
-                         const nsAString& aDelivery,
-                         const nsAString& aDeliveryStatus,
-                         const nsAString& aSender,
-                         const nsAString& aReceiver,
-                         const nsAString& aBody,
-                         const nsAString& aMessageClass,
-                         uint64_t aTimestamp,
-                         uint64_t aSentTimestamp,
-                         uint64_t aDeliveryTimestamp,
-                         bool aRead,
-                         JSContext* aCx,
-                         nsISmsMessage** aMessage);
-  const SmsMessageData& GetData() const;
-
-private:
-  ~SmsMessageInternal() {}
-
-  // Don't try to use the default constructor.
-  SmsMessageInternal();
-
-  SmsMessageData mData;
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_SmsMessageInternal_h
deleted file mode 100644
--- a/dom/mobilemessage/Types.h
+++ /dev/null
@@ -1,134 +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_mobilemessage_Types_h
-#define mozilla_dom_mobilemessage_Types_h
-
-#include "IPCMessageUtils.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-// For MmsMessageData.state and SmsMessageData.deliveryState
-// Please keep the following files in sync with enum below:
-// mobile/android/base/GeckoSmsManager.java
-enum DeliveryState {
-  eDeliveryState_Sent = 0,
-  eDeliveryState_Received,
-  eDeliveryState_Sending,
-  eDeliveryState_Error,
-  eDeliveryState_Unknown,
-  eDeliveryState_NotDownloaded,
-  // This state should stay at the end.
-  eDeliveryState_EndGuard
-};
-
-// For {Mms,Sms}MessageData.deliveryStatus.
-enum DeliveryStatus {
-  eDeliveryStatus_NotApplicable = 0,
-  eDeliveryStatus_Success,
-  eDeliveryStatus_Pending,
-  eDeliveryStatus_Error,
-  eDeliveryStatus_Reject,
-  eDeliveryStatus_Manual,
-  // This state should stay at the end.
-  eDeliveryStatus_EndGuard
-};
-
-// For MmsMessageData.readStatus.
-enum ReadStatus {
-  eReadStatus_NotApplicable = 0,
-  eReadStatus_Success,
-  eReadStatus_Pending,
-  eReadStatus_Error,
-  // This state should stay at the end.
-  eReadStatus_EndGuard
-};
-
-// For {Mms,Sms}MessageData.messageClass.
-enum MessageClass {
-  eMessageClass_Normal = 0,
-  eMessageClass_Class0,
-  eMessageClass_Class1,
-  eMessageClass_Class2,
-  eMessageClass_Class3,
-  // This state should stay at the end.
-  eMessageClass_EndGuard
-};
-
-// For ThreadData.
-enum MessageType {
-  eMessageType_SMS = 0,
-  eMessageType_MMS,
-  // This state should stay at the end.
-  eMessageType_EndGuard
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-namespace IPC {
-
-/**
- * Delivery state serializer.
- */
-template <>
-struct ParamTraits<mozilla::dom::mobilemessage::DeliveryState>
-  : public ContiguousEnumSerializer<
-             mozilla::dom::mobilemessage::DeliveryState,
-             mozilla::dom::mobilemessage::eDeliveryState_Sent,
-             mozilla::dom::mobilemessage::eDeliveryState_EndGuard>
-{};
-
-/**
- * Delivery status serializer.
- */
-template <>
-struct ParamTraits<mozilla::dom::mobilemessage::DeliveryStatus>
-  : public ContiguousEnumSerializer<
-             mozilla::dom::mobilemessage::DeliveryStatus,
-             mozilla::dom::mobilemessage::eDeliveryStatus_NotApplicable,
-             mozilla::dom::mobilemessage::eDeliveryStatus_EndGuard>
-{};
-
-/**
- * Read status serializer.
- */
-template <>
-struct ParamTraits<mozilla::dom::mobilemessage::ReadStatus>
-  : public ContiguousEnumSerializer<
-             mozilla::dom::mobilemessage::ReadStatus,
-             mozilla::dom::mobilemessage::eReadStatus_NotApplicable,
-             mozilla::dom::mobilemessage::eReadStatus_EndGuard>
-{};
-
-/**
- * Message class serializer.
- */
-template <>
-struct ParamTraits<mozilla::dom::mobilemessage::MessageClass>
-  : public ContiguousEnumSerializer<
-             mozilla::dom::mobilemessage::MessageClass,
-             mozilla::dom::mobilemessage::eMessageClass_Normal,
-             mozilla::dom::mobilemessage::eMessageClass_EndGuard>
-{};
-
-/**
- * MessageType class serializer.
- */
-template <>
-struct ParamTraits<mozilla::dom::mobilemessage::MessageType>
-  : public ContiguousEnumSerializer<
-             mozilla::dom::mobilemessage::MessageType,
-             mozilla::dom::mobilemessage::eMessageType_SMS,
-             mozilla::dom::mobilemessage::eMessageType_EndGuard>
-{};
-
-} // namespace IPC
-
-#endif // mozilla_dom_mobilemessage_Types_h
deleted file mode 100644
--- a/dom/mobilemessage/android/MobileMessageDatabaseService.cpp
+++ /dev/null
@@ -1,129 +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 "MobileMessageDatabaseService.h"
-
-#include "AndroidBridge.h"
-#include "SmsManager.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-NS_IMPL_ISUPPORTS(MobileMessageDatabaseService, nsIMobileMessageDatabaseService)
-
-MobileMessageDatabaseService::MobileMessageDatabaseService()
-{
-  SmsManager::Init();
-}
-
-NS_IMETHODIMP
-MobileMessageDatabaseService::GetMessageMoz(int32_t aMessageId,
-                                            nsIMobileMessageCallback* aRequest)
-{
-  if (!AndroidBridge::Bridge()) {
-    return NS_OK;
-  }
-
-  AndroidBridge::Bridge()->GetMessage(aMessageId, aRequest);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageDatabaseService::DeleteMessage(int32_t *aMessageIds,
-                                            uint32_t aLength,
-                                            nsIMobileMessageCallback* aRequest)
-{
-  if (!AndroidBridge::Bridge()) {
-    return NS_OK;
-  }
-
-  if (!aMessageIds) {
-    return NS_OK;
-  }
-
-  if (aLength != 1) {
-    return NS_ERROR_FAILURE;
-  }
-
-  AndroidBridge::Bridge()->DeleteMessage(aMessageIds[0], aRequest);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageDatabaseService::CreateMessageCursor(bool aHasStartDate,
-                                                  uint64_t aStartDate,
-                                                  bool aHasEndDate,
-                                                  uint64_t aEndDate,
-                                                  const char16_t** aNumbers,
-                                                  uint32_t aNumbersCount,
-                                                  const nsAString& aDelivery,
-                                                  bool aHasRead,
-                                                  bool aRead,
-                                                  bool aHasThreadId,
-                                                  uint64_t aThreadId,
-                                                  bool aReverse,
-                                                  nsIMobileMessageCursorCallback* aCallback,
-                                                  nsICursorContinueCallback** aCursor)
-{
-  if (!AndroidBridge::Bridge()) {
-    *aCursor = nullptr;
-    return NS_OK;
-  }
-
-  nsCOMPtr<nsICursorContinueCallback> cursor =
-    AndroidBridge::Bridge()->CreateMessageCursor(aHasStartDate,
-                                                 aStartDate,
-                                                 aHasEndDate,
-                                                 aEndDate,
-                                                 aNumbers,
-                                                 aNumbersCount,
-                                                 aDelivery,
-                                                 aHasRead,
-                                                 aRead,
-                                                 aHasThreadId,
-                                                 aThreadId,
-                                                 aReverse,
-                                                 aCallback);
-  cursor.forget(aCursor);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageDatabaseService::MarkMessageRead(int32_t aMessageId,
-                                              bool aValue,
-                                              bool aSendReadReport,
-                                              nsIMobileMessageCallback* aRequest)
-{
-  if (!AndroidBridge::Bridge()) {
-    return NS_OK;
-  }
-
-  AndroidBridge::Bridge()->MarkMessageRead(aMessageId,
-                                           aValue,
-                                           aSendReadReport,
-                                           aRequest);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MobileMessageDatabaseService::CreateThreadCursor(nsIMobileMessageCursorCallback* aRequest,
-                                                 nsICursorContinueCallback** aCursor)
-{
-  if (!AndroidBridge::Bridge()) {
-    *aCursor = nullptr;
-    return NS_OK;
-  }
-
-  nsCOMPtr<nsICursorContinueCallback> cursor =
-    AndroidBridge::Bridge()->CreateThreadCursor(aRequest);
-  cursor.forget(aCursor);
-  return NS_OK;
-}
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/android/MobileMessageDatabaseService.h
+++ /dev/null
@@ -1,33 +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_mobilemessage_MobileMessageDatabaseService_h
-#define mozilla_dom_mobilemessage_MobileMessageDatabaseService_h
-
-#include "nsIMobileMessageDatabaseService.h"
-#include "mozilla/Attributes.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-class MobileMessageDatabaseService final : public nsIMobileMessageDatabaseService
-{
-private:
-  ~MobileMessageDatabaseService() {}
-
-public:
-  MobileMessageDatabaseService();
-
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIMOBILEMESSAGEDATABASESERVICE
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_MobileMessageDatabaseService_h
deleted file mode 100644
--- a/dom/mobilemessage/android/SmsManager.cpp
+++ /dev/null
@@ -1,391 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
- * 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 "SmsManager.h"
-
-#include "mozilla/dom/mobilemessage/Constants.h"
-#include "mozilla/dom/mobilemessage/PSms.h"
-#include "mozilla/dom/mobilemessage/SmsParent.h"
-#include "mozilla/dom/mobilemessage/SmsTypes.h"
-#include "mozilla/dom/mobilemessage/Types.h"
-#include "MobileMessageThreadInternal.h"
-#include "SmsMessageInternal.h"
-#include "mozilla/Services.h"
-#include "nsIMobileMessageDatabaseService.h"
-#include "nsIObserverService.h"
-#include "nsThreadUtils.h"
-#include "AndroidJavaWrappers.h"
-
-using namespace mozilla::dom;
-using namespace mozilla::dom::mobilemessage;
-
-namespace mozilla {
-
-/*static*/
-void
-SmsManager::NotifySmsReceived(int32_t aId,
-                              jni::String::Param aSender,
-                              jni::String::Param aBody,
-                              int32_t aMessageClass,
-                              int64_t aSentTimestamp,
-                              int64_t aTimestamp)
-{
-    // TODO Need to correct the message `threadId` parameter value. Bug 859098
-    SmsMessageData message;
-    message.id() = aId;
-    message.threadId() = 0;
-    message.iccId() = EmptyString();
-    message.delivery() = eDeliveryState_Received;
-    message.deliveryStatus() = eDeliveryStatus_Success;
-    message.sender() = aSender ? aSender->ToString() : EmptyString();
-    message.receiver() = EmptyString();
-    message.body() = aBody ? aBody->ToString() : EmptyString();
-    message.messageClass() = static_cast<MessageClass>(aMessageClass);
-    message.timestamp() = aTimestamp;
-    message.sentTimestamp() = aSentTimestamp;
-    message.deliveryTimestamp() = aTimestamp;
-    message.read() = false;
-
-    nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
-    if (!obs) {
-        return;
-    }
-
-    nsCOMPtr<nsISmsMessage> domMessage = new SmsMessageInternal(message);
-    obs->NotifyObservers(domMessage, kSmsReceivedObserverTopic, nullptr);
-}
-
-/*static*/
-void
-SmsManager::NotifySmsSent(int32_t aId,
-                          jni::String::Param aReceiver,
-                          jni::String::Param aBody,
-                          int64_t aTimestamp,
-                          int32_t aRequestId)
-{
-    // TODO Need to add the message `messageClass` parameter value. Bug 804476
-    // TODO Need to correct the message `threadId` parameter value. Bug 859098
-    SmsMessageData message;
-    message.id() = aId;
-    message.threadId() = 0;
-    message.iccId() = EmptyString();
-    message.delivery() = eDeliveryState_Sent;
-    message.deliveryStatus() = eDeliveryStatus_Pending;
-    message.sender() = EmptyString();
-    message.receiver() = aReceiver ? aReceiver->ToString() : EmptyString();
-    message.body() = aBody ? aBody->ToString() : EmptyString();
-    message.messageClass() = eMessageClass_Normal;
-    message.timestamp() = aTimestamp;
-    message.sentTimestamp() = aTimestamp;
-    message.deliveryTimestamp() = aTimestamp;
-    message.read() = true;
-
-    /*
-     * First, we are going to notify all SmsManager that a message has
-     * been sent. Then, we will notify the SmsRequest object about it.
-     */
-    nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
-    if (!obs) {
-        return;
-    }
-
-    nsCOMPtr<nsISmsMessage> domMessage = new SmsMessageInternal(message);
-    obs->NotifyObservers(domMessage, kSmsSentObserverTopic, nullptr);
-
-    nsCOMPtr<nsIMobileMessageCallback> request =
-        AndroidBridge::Bridge()->DequeueSmsRequest(aRequestId);
-    if (!request) {
-        return;
-    }
-
-    request->NotifyMessageSent(domMessage);
-}
-
-/*static*/
-void
-SmsManager::NotifySmsDelivery(int32_t aId,
-                              int32_t aDeliveryStatus,
-                              jni::String::Param aReceiver,
-                              jni::String::Param aBody,
-                              int64_t aTimestamp)
-{
-    // TODO Need to add the message `messageClass` parameter value. Bug 804476
-    // TODO Need to correct the message `threadId` parameter value. Bug 859098
-    SmsMessageData message;
-    message.id() = aId;
-    message.threadId() = 0;
-    message.iccId() = EmptyString();
-    message.delivery() = eDeliveryState_Sent;
-    message.deliveryStatus() = static_cast<DeliveryStatus>(aDeliveryStatus);
-    message.sender() = EmptyString();
-    message.receiver() = aReceiver ? aReceiver->ToString() : EmptyString();
-    message.body() = aBody ? aBody->ToString() : EmptyString();
-    message.messageClass() = eMessageClass_Normal;
-    message.timestamp() = aTimestamp;
-    message.sentTimestamp() = aTimestamp;
-    message.deliveryTimestamp() = aTimestamp;
-    message.read() = true;
-
-    nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
-    if (!obs) {
-        return;
-    }
-
-    nsCOMPtr<nsISmsMessage> domMessage = new SmsMessageInternal(message);
-    const char* topic = (message.deliveryStatus() == eDeliveryStatus_Success)
-                        ? kSmsDeliverySuccessObserverTopic
-                        : kSmsDeliveryErrorObserverTopic;
-    obs->NotifyObservers(domMessage, topic, nullptr);
-}
-
-/*static*/
-void
-SmsManager::NotifySmsSendFailed(int32_t aError, int32_t aRequestId)
-{
-    nsCOMPtr<nsIMobileMessageCallback> request =
-        AndroidBridge::Bridge()->DequeueSmsRequest(aRequestId);
-    if(!request) {
-        return;
-    }
-
-    request->NotifySendMessageFailed(aError, nullptr);
-}
-
-/*static*/
-void
-SmsManager::NotifyGetSms(int32_t aId,
-                         int32_t aDeliveryStatus,
-                         jni::String::Param aReceiver,
-                         jni::String::Param aSender,
-                         jni::String::Param aBody,
-                         int64_t aTimestamp,
-                         bool aRead,
-                         int32_t aRequestId)
-{
-    nsString receiver(aReceiver->ToString());
-    DeliveryState state = receiver.IsEmpty() ? eDeliveryState_Received
-                                             : eDeliveryState_Sent;
-
-    // TODO Need to add the message `messageClass` parameter value. Bug 804476
-    // TODO Need to correct the message `threadId` parameter value. Bug 859098
-    SmsMessageData message;
-    message.id() = aId;
-    message.threadId() = 0;
-    message.iccId() = EmptyString();
-    message.delivery() = state;
-    message.deliveryStatus() = static_cast<DeliveryStatus>(aDeliveryStatus);
-    message.sender() = aSender ? aSender->ToString() : EmptyString();
-    message.receiver() = receiver;
-    message.body() = aBody ? aBody->ToString() : EmptyString();
-    message.messageClass() = eMessageClass_Normal;
-    message.timestamp() = aTimestamp;
-    message.sentTimestamp() = aTimestamp;
-    message.deliveryTimestamp() = aTimestamp;
-    message.read() = aRead;
-
-    nsCOMPtr<nsIMobileMessageCallback> request =
-        AndroidBridge::Bridge()->DequeueSmsRequest(aRequestId);
-    if (!request) {
-        return;
-    }
-
-    nsCOMPtr<nsISmsMessage> domMessage = new SmsMessageInternal(message);
-    request->NotifyMessageGot(domMessage);
-}
-
-/*static*/
-void
-SmsManager::NotifyGetSmsFailed(int32_t aError, int32_t aRequestId)
-{
-    nsCOMPtr<nsIMobileMessageCallback> request =
-        AndroidBridge::Bridge()->DequeueSmsRequest(aRequestId);
-    if (!request) {
-        return;
-    }
-
-    request->NotifyGetMessageFailed(aError);
-}
-
-/*static*/
-void
-SmsManager::NotifySmsDeleted(bool aDeleted, int32_t aRequestId)
-{
-    nsCOMPtr<nsIMobileMessageCallback> request =
-        AndroidBridge::Bridge()->DequeueSmsRequest(aRequestId);
-    if (!request) {
-        return;
-    }
-
-    // For android, we support only single SMS deletion.
-    bool deleted = aDeleted;
-    request->NotifyMessageDeleted(&deleted, 1);
-}
-
-/*static*/
-void
-SmsManager::NotifySmsDeleteFailed(int32_t aError, int32_t aRequestId)
-{
-    nsCOMPtr<nsIMobileMessageCallback> request =
-        AndroidBridge::Bridge()->DequeueSmsRequest(aRequestId);
-    if (!request) {
-        return;
-    }
-
-    request->NotifyDeleteMessageFailed(aError);
-}
-
-/*static*/
-void
-SmsManager::NotifyCursorError(int32_t aError, int32_t aRequestId)
-{
-    nsCOMPtr<nsIMobileMessageCursorCallback> request =
-        AndroidBridge::Bridge()->DequeueSmsCursorRequest(aRequestId);
-    if (!request) {
-        return;
-    }
-
-    request->NotifyCursorError(aError);
-}
-
-/*static*/
-void
-SmsManager::NotifyThreadCursorResult(int64_t aId,
-                                     jni::String::Param aLastMessageSubject,
-                                     jni::String::Param aBody,
-                                     int64_t aUnreadCount,
-                                     jni::ObjectArray::Param aParticipants,
-                                     int64_t aTimestamp,
-                                     jni::String::Param aLastMessageType,
-                                     int32_t aRequestId)
-{
-    ThreadData thread;
-    thread.id() = aId;
-    thread.lastMessageSubject() = aLastMessageSubject ?
-                                    aLastMessageSubject->ToString() :
-                                    EmptyString();
-    thread.body() = aBody ? aBody->ToString() : EmptyString();
-    thread.unreadCount() = aUnreadCount;
-    thread.timestamp() = aTimestamp;
-    thread.lastMessageType() = eMessageType_SMS;
-
-    JNIEnv* const env = jni::GetGeckoThreadEnv();
-
-    jobjectArray participants = aParticipants.Get();
-    jsize length = env->GetArrayLength(participants);
-    for (jsize i = 0; i < length; ++i) {
-        jstring participant =
-            static_cast<jstring>(env->GetObjectArrayElement(participants, i));
-        if (participant) {
-            thread.participants().AppendElement(nsJNIString(participant, env));
-            env->DeleteLocalRef(participant);
-        }
-    }
-
-    nsCOMPtr<nsIMobileMessageCursorCallback> request =
-        AndroidBridge::Bridge()->GetSmsCursorRequest(aRequestId);
-    if (!request) {
-        return;
-    }
-
-    nsCOMArray<nsIMobileMessageThread> arr;
-    arr.AppendElement(new MobileMessageThreadInternal(thread));
-
-    nsIMobileMessageThread** elements;
-    int32_t size;
-    size = arr.Forget(&elements);
-
-    request->NotifyCursorResult(reinterpret_cast<nsISupports**>(elements),
-                                size);
-}
-
-/*static*/
-void
-SmsManager::NotifyMessageCursorResult(int32_t aMessageId,
-                                      int32_t aDeliveryStatus,
-                                      jni::String::Param aReceiver,
-                                      jni::String::Param aSender,
-                                      jni::String::Param aBody,
-                                      int64_t aTimestamp,
-                                      int64_t aThreadId,
-                                      bool aRead,
-                                      int32_t aRequestId)
-{
-    nsString receiver = aReceiver->ToString();
-    DeliveryState state = receiver.IsEmpty() ? eDeliveryState_Received
-                                             : eDeliveryState_Sent;
-
-    // TODO Need to add the message `messageClass` parameter value. Bug 804476
-    SmsMessageData message;
-    message.id() = aMessageId;
-    message.threadId() = aThreadId;
-    message.iccId() = EmptyString();
-    message.delivery() = state;
-    message.deliveryStatus() = static_cast<DeliveryStatus>(aDeliveryStatus);
-    message.sender() = aSender ? aSender->ToString() : EmptyString();
-    message.receiver() = receiver;
-    message.body() = aBody ? aBody->ToString() : EmptyString();
-    message.messageClass() = eMessageClass_Normal;
-    message.timestamp() = aTimestamp;
-    message.sentTimestamp() = aTimestamp;
-    message.deliveryTimestamp() = aTimestamp;
-    message.read() = aRead;
-
-    nsCOMPtr<nsIMobileMessageCursorCallback> request =
-        AndroidBridge::Bridge()->GetSmsCursorRequest(aRequestId);
-    if (!request) {
-        return;
-    }
-
-    nsCOMArray<nsISmsMessage> arr;
-    arr.AppendElement(new SmsMessageInternal(message));
-
-    nsISmsMessage** elements;
-    int32_t size;
-    size = arr.Forget(&elements);
-
-    request->NotifyCursorResult(reinterpret_cast<nsISupports**>(elements),
-                                size);
-}
-
-/*static*/
-void
-SmsManager::NotifyCursorDone(int32_t aRequestId)
-{
-    nsCOMPtr<nsIMobileMessageCursorCallback> request =
-        AndroidBridge::Bridge()->DequeueSmsCursorRequest(aRequestId);
-    if (!request) {
-        return;
-    }
-
-    request->NotifyCursorDone();
-}
-
-/*static*/
-void
-SmsManager::NotifySmsMarkedAsRead(bool aMarkedAsRead, int32_t aRequestId)
-{
-    nsCOMPtr<nsIMobileMessageCallback> request =
-        AndroidBridge::Bridge()->DequeueSmsRequest(aRequestId);
-    if (!request) {
-        return;
-    }
-
-    request->NotifyMessageMarkedRead(aMarkedAsRead);
-}
-
-/*static*/
-void
-SmsManager::NotifySmsMarkAsReadFailed(int32_t aError, int32_t aRequestId)
-{
-    nsCOMPtr<nsIMobileMessageCallback> request =
-        AndroidBridge::Bridge()->DequeueSmsRequest(aRequestId);
-    if (!request) {
-        return;
-    }
-
-    request->NotifyMarkMessageReadFailed(aError);
-}
-
-} // namespace
deleted file mode 100644
--- a/dom/mobilemessage/android/SmsManager.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
- * 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 SmsManager_h__
-#define SmsManager_h__
-
-#include "GeneratedJNINatives.h"
-
-namespace mozilla {
-
-class SmsManager : public java::GeckoSmsManager::Natives<SmsManager>
-{
-private:
-    SmsManager();
-
-public:
-    static void NotifySmsReceived(int32_t aId,
-                                  jni::String::Param aSender,
-                                  jni::String::Param aBody,
-                                  int32_t aMessageClass,
-                                  int64_t aSentTimestamp,
-                                  int64_t aTimestamp);
-    static void NotifySmsSent(int32_t aId,
-                              jni::String::Param aReceiver,
-                              jni::String::Param aBody,
-                              int64_t aTimestamp,
-                              int32_t aRequestId);
-    static void NotifySmsDelivery(int32_t aId,
-                                  int32_t aDeliveryStatus,
-                                  jni::String::Param aReceiver,
-                                  jni::String::Param aBody,
-                                  int64_t aTimestamp);
-    static void NotifySmsSendFailed(int32_t aError,
-                                    int32_t aRequestId);
-    static void NotifyGetSms(int32_t aId,
-                             int32_t aDeliveryStatus,
-                             jni::String::Param aReceiver,
-                             jni::String::Param aSender,
-                             jni::String::Param aBody,
-                             int64_t aTimestamp,
-                             bool aRead,
-                             int32_t aRequestId);
-    static void NotifyGetSmsFailed(int32_t aError,
-                                   int32_t aRequestId);
-    static void NotifySmsDeleted(bool aDeleted,
-                                 int32_t aRequestId);
-    static void NotifySmsDeleteFailed(int32_t aError,
-                                      int32_t aRequestId);
-    static void NotifyCursorError(int32_t aError,
-                                  int32_t aRequestId);
-    static void NotifyThreadCursorResult(int64_t aId,
-                                         jni::String::Param aLastMessageSubject,
-                                         jni::String::Param aBody,
-                                         int64_t aUnreadCount,
-                                         jni::ObjectArray::Param aParticipants,
-                                         int64_t aTimestamp,
-                                         jni::String::Param aLastMessageType,
-                                         int32_t aRequestId);
-    static void NotifyMessageCursorResult(int32_t aMessageId,
-                                          int32_t aDeliveryStatus,
-                                          jni::String::Param aReceiver,
-                                          jni::String::Param aSender,
-                                          jni::String::Param aBody,
-                                          int64_t aTimestamp,
-                                          int64_t aThreadId,
-                                          bool aRead,
-                                          int32_t aRequestId);
-    static void NotifyCursorDone(int32_t aRequestId);
-    static void NotifySmsMarkedAsRead(bool aMarkedAsRead, int32_t aRequestId);
-    static void NotifySmsMarkAsReadFailed(int32_t aError, int32_t aRequestId);
-};
-
-} // namespace
-
-#endif // SmsManager_h__
deleted file mode 100644
--- a/dom/mobilemessage/android/SmsService.cpp
+++ /dev/null
@@ -1,90 +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 "SmsService.h"
-#include "AndroidBridge.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-NS_IMPL_ISUPPORTS(SmsService, nsISmsService)
-
-NS_IMETHODIMP
-SmsService::GetSmsDefaultServiceId(uint32_t* aServiceId)
-{
-  // Android has no official DSDS support.
-  *aServiceId = 0;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsService::GetSegmentInfoForText(const nsAString& aText,
-                                  nsIMobileMessageCallback* aRequest)
-{
-  if (!AndroidBridge::Bridge()) {
-    return NS_ERROR_FAILURE;
-  }
-
-  nsresult rv = AndroidBridge::Bridge()->GetSegmentInfoForText(aText, aRequest);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsService::Send(uint32_t aServiceId,
-                 const nsAString& aNumber,
-                 const nsAString& aMessage,
-                 bool aSilent,
-                 nsIMobileMessageCallback* aRequest)
-{
-  if (!AndroidBridge::Bridge()) {
-    return NS_OK;
-  }
-
-  AndroidBridge::Bridge()->SendMessage(aNumber, aMessage, aRequest);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsService::AddSilentNumber(const nsAString& aNumber)
-{
-  NS_NOTYETIMPLEMENTED("Implement me!");
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-NS_IMETHODIMP
-SmsService::RemoveSilentNumber(const nsAString& aNumber)
-{
-  NS_NOTYETIMPLEMENTED("Implement me!");
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-NS_IMETHODIMP
-SmsService::GetSmscAddress(uint32_t aServiceId,
-                           nsIMobileMessageCallback *aRequest)
-{
-  // TODO: bug 878016 - Android backend: implement getSMSCAddress/setSMSCAddress
-  NS_NOTYETIMPLEMENTED("Implement me!");
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-NS_IMETHODIMP
-SmsService::SetSmscAddress(uint32_t aServiceId,
-                           const nsAString& aNumber,
-                           uint32_t aTypeOfNumber,
-                           uint32_t aNumberPlanIdentification,
-                           nsIMobileMessageCallback* aRequest)
-{
-  // TODO: bug 878016 - Android backend: implement getSMSCAddress/setSMSCAddress
-  NS_NOTYETIMPLEMENTED("Implement me!");
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/android/SmsService.h
+++ /dev/null
@@ -1,30 +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_mobilemessage_SmsService_h
-#define mozilla_dom_mobilemessage_SmsService_h
-
-#include "nsISmsService.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-class SmsService final : public nsISmsService
-{
-private:
-  ~SmsService() {}
-
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSISMSSERVICE
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_SmsService_h
deleted file mode 100644
--- a/dom/mobilemessage/gonk/MmsPduHelper.jsm
+++ /dev/null
@@ -1,1710 +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;
-
-var WSP = {};
-Cu.import("resource://gre/modules/WspPduHelper.jsm", WSP);
-
-Cu.import("resource://gre/modules/mms_consts.js");
-
-Cu.import("resource://gre/modules/PhoneNumberUtils.jsm");
-
-var DEBUG; // set to true to see debug messages
-
-this.MMS_VERSION = (function() {
-  Cu.import("resource://gre/modules/Services.jsm");
-
-  try {
-    return Services.prefs.getIntPref("dom.mms.version");
-  } catch(ex) {}
-
-  return MMS_VERSION_1_3;
-})();
-
-this.translatePduErrorToStatus = function translatePduErrorToStatus(error) {
-  if (error == MMS_PDU_ERROR_OK) {
-    return MMS_PDU_STATUS_RETRIEVED;
-  }
-
-  if ((error >= MMS_PDU_ERROR_TRANSIENT_FAILURE)
-      && (error < MMS_PDU_ERROR_PERMANENT_FAILURE)) {
-    return MMS_PDU_STATUS_DEFERRED;
-  }
-
-  return MMS_PDU_STATUS_UNRECOGNISED;
-}
-
-function defineLazyRegExp(obj, name, pattern) {
-  obj.__defineGetter__(name, function() {
-    delete obj[name];
-    return obj[name] = new RegExp(pattern);
-  });
-}
-
-function RangedValue(name, min, max) {
-  this.name = name;
-  this.min = min;
-  this.max = max;
-}
-RangedValue.prototype = {
-  name: null,
-  min: null,
-  max: null,
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded integer.
-   *
-   * @throws CodeError if decoded value is not in the range [this.min, this.max].
-   */
-  decode: function(data) {
-    let value = WSP.Octet.decode(data);
-    if ((value >= this.min) && (value <= this.max)) {
-      return value;
-    }
-
-    throw new WSP.CodeError(this.name + ": invalid value " + value);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An integer value within thr range [this.min, this.max].
-   */
-  encode: function(data, value) {
-    if ((value < this.min) || (value > this.max)) {
-      throw new WSP.CodeError(this.name + ": invalid value " + value);
-    }
-
-    WSP.Octet.encode(data, value);
-  },
-};
-
-/**
- * Internal decoding function for boolean values.
- *
- * Boolean-value = Yes | No
- * Yes = <Octet 128>
- * No = <Octet 129>
- */
-this.BooleanValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Boolean true or false.
-   *
-   * @throws CodeError if read octet equals to neither 128 nor 129.
-   */
-  decode: function(data) {
-    let value = WSP.Octet.decode(data);
-    if ((value != 128) && (value != 129)) {
-      throw new WSP.CodeError("Boolean-value: invalid value " + value);
-    }
-
-    return value == 128;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        A boolean value to be encoded.
-   */
-  encode: function(data, value) {
-    WSP.Octet.encode(data, value ? 128 : 129);
-  },
-};
-
-/**
- * MMS Address
- *
- * address = email | device-address | alphanum-shortcode | num-shortcode
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A section 8
- */
-this.Address = {
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   *
-   * @return An object of two string-typed attributes: address and type.
-   */
-  decode: function(data) {
-    let str = EncodedStringValue.decode(data);
-
-    let result;
-    if (((result = str.match(this.REGEXP_DECODE_PLMN)) != null)
-        || ((result = str.match(this.REGEXP_DECODE_IPV4)) != null)
-        || ((result = str.match(this.REGEXP_DECODE_IPV6)) != null)
-        || (((result = str.match(this.REGEXP_DECODE_CUSTOM)) != null)
-            && (result[2] != "PLMN")
-            && (result[2] != "IPv4")
-            && (result[2] != "IPv6"))) {
-      return {address: result[1], type: result[2]};
-    }
-
-    let type;
-    if (str.match(this.REGEXP_NUM)) {
-      type = "num";
-    } else if (str.match(this.REGEXP_ALPHANUM)) {
-      type = "alphanum";
-    } else if (str.match(this.REGEXP_EMAIL)) {
-      type = "email";
-    } else {
-      throw new WSP.CodeError("Address: invalid address");
-    }
-
-    return {address: str, type: type};
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An object of two string-typed attributes: address and type.
-   */
-  encode: function(data, value) {
-    if (!value || !value.type || !value.address) {
-      throw new WSP.CodeError("Address: invalid value");
-    }
-
-    let str;
-    switch (value.type) {
-      case "email":
-        if (value.address.match(this.REGEXP_EMAIL)) {
-          str = value.address;
-        }
-        break;
-      case "num":
-        if (value.address.match(this.REGEXP_NUM)) {
-          str = value.address;
-        }
-        break;
-      case "alphanum":
-        if (value.address.match(this.REGEXP_ALPHANUM)) {
-          str = value.address;
-        }
-        break;
-      case "IPv4":
-        if (value.address.match(this.REGEXP_ENCODE_IPV4)) {
-          str = value.address + "/TYPE=IPv4";
-        }
-        break;
-      case "IPv6":
-        if (value.address.match(this.REGEXP_ENCODE_IPV6)) {
-          str = value.address + "/TYPE=IPv6";
-        }
-        break;
-      case "PLMN":
-        if (value.address.match(this.REGEXP_ENCODE_PLMN)) {
-          str = value.address + "/TYPE=PLMN";
-        }
-        break;
-      default:
-        if (value.type.match(this.REGEXP_ENCODE_CUSTOM_TYPE)
-            && value.address.match(this.REGEXP_ENCODE_CUSTOM_ADDR)) {
-          str = value.address + "/TYPE=" + value.type;
-        }
-        break;
-    }
-
-    if (!str) {
-      throw new WSP.CodeError("Address: invalid value: " + JSON.stringify(value));
-    }
-
-    EncodedStringValue.encode(data, str);
-  },
-
-  /**
-   * @param address
-   *        Address string which want to find the type.
-   *
-   * @return Address type.
-   */
-  resolveType: function(address) {
-    if (address.match(this.REGEXP_EMAIL)) {
-      return "email";
-    }
-
-    if (address.match(this.REGEXP_ENCODE_IPV4)) {
-      return "IPv4";
-    }
-
-    if (address.match(this.REGEXP_ENCODE_IPV6)) {
-      return "IPv6";
-    }
-
-    let normalizedAddress = PhoneNumberUtils.normalize(address, false);
-    if (PhoneNumberUtils.isPlainPhoneNumber(normalizedAddress)) {
-      return "PLMN";
-    }
-
-    return "Others";
-  },
-};
-
-defineLazyRegExp(Address, "REGEXP_DECODE_PLMN",        "^(\\+?[\\d.-]+)\\/TYPE=(PLMN)$");
-defineLazyRegExp(Address, "REGEXP_DECODE_IPV4",        "^((?:(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9]){0,1}[0-9])\\.){3,3}(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9]){0,1}[0-9]))\\/TYPE=(IPv4)$");
-defineLazyRegExp(Address, "REGEXP_DECODE_IPV6",        "^(" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,7}:|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|" +
-                                                       "[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})|" +
-                                                       ":(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9]){0,1}[0-9])\\.){3,3}(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9]){0,1}[0-9])" +
-                                                       ")\\/TYPE=(IPv6)$");
-defineLazyRegExp(Address, "REGEXP_DECODE_CUSTOM",      "^([\\w\\+\\-.%]+)\\/TYPE=(\\w+)$");
-defineLazyRegExp(Address, "REGEXP_ENCODE_PLMN",        "^\\+?[\\d.-]+$");
-defineLazyRegExp(Address, "REGEXP_ENCODE_IPV4",        "^(?:(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9]){0,1}[0-9])\\.){3,3}(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9]){0,1}[0-9])$");
-defineLazyRegExp(Address, "REGEXP_ENCODE_IPV6",        "^(?:" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,7}:|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|" +
-                                                       "(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|" +
-                                                       "[0-9a-fA-F]{1,4}:(?::[0-9a-fA-F]{1,4}){1,6}|" +
-                                                       ":(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)" +
-                                                       ")$");
-defineLazyRegExp(Address, "REGEXP_ENCODE_CUSTOM_TYPE", "^\\w+$");
-defineLazyRegExp(Address, "REGEXP_ENCODE_CUSTOM_ADDR", "^[\\w\\+\\-.%]+$");
-defineLazyRegExp(Address, "REGEXP_NUM",                "^[\\+*#]?\\d+$");
-defineLazyRegExp(Address, "REGEXP_ALPHANUM",           "^\\w+$");
-// OMA-TS-MMS_ENC-V1_3-20110913-A chapter 8:
-//
-//   E-mail should match the definition of `mailbox` as described in section
-//   3.4 of RFC2822, but excluding the obsolete definitions as indicated by
-//   the "obs-" prefix.
-//
-// Here we try to match addr-spec only.
-defineLazyRegExp(Address, "REGEXP_EMAIL",              "(?:" +
-                                                       "[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|" +
-                                                       "\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\"" +
-                                                       ")@(?:" +
-                                                       "[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|" +
-                                                       "\\[(?:" +
-                                                       "[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\\\[\x01-\x09\x0b\x0c\x0e-\x7f]" +
-                                                       ")*\\]" +
-                                                       ")");
-
-/**
- * Header-field = MMS-header | Application-header
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.2
- */
-this.HeaderField = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param options
-   *        Extra context for decoding.
-   *
-   * @return A decoded object containing `name` and `value` properties or null
-   *         in case of a failed parsing. The `name` property must be a string,
-   *         but the `value` property can be many different types depending on
-   *         `name`.
-   */
-  decode: function(data, options) {
-    return WSP.decodeAlternatives(data, options,
-                                  MmsHeader, WSP.ApplicationHeader);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param octet
-   *        Octet value to be encoded.
-   * @param options
-   *        Extra context for encoding.
-   */
-  encode: function(data, value, options) {
-    WSP.encodeAlternatives(data, value, options,
-                           MmsHeader, WSP.ApplicationHeader);
-  },
-};
-
-/**
- * MMS-header = MMS-field-name MMS-value
- * MMS-field-name = Short-integer
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.2
- */
-this.MmsHeader = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param options
-   *        Extra context for decoding.
-   *
-   * @return A decoded object containing `name` and `value` properties or null
-   *         in case of a failed parsing. The `name` property must be a string,
-   *         but the `value` property can be many different types depending on
-   *         `name`.
-   *
-   * @throws NotWellKnownEncodingError if decoded well-known header field
-   *         number is not registered or supported.
-   */
-  decode: function(data, options) {
-    let index = WSP.ShortInteger.decode(data);
-
-    let entry = MMS_HEADER_FIELDS[index];
-    if (!entry) {
-      throw new WSP.NotWellKnownEncodingError(
-        "MMS-header: not well known header " + index);
-    }
-
-    let cur = data.offset, value;
-    try {
-      value = entry.coder.decode(data, options);
-    } catch (e) {
-      data.offset = cur;
-
-      value = WSP.skipValue(data);
-      debug("Skip malformed well known header: "
-            + JSON.stringify({name: entry.name, value: value}));
-
-      return null;
-    }
-
-    return {
-      name: entry.name,
-      value: value,
-    };
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param header
-   *        An object containing two attributes: a string-typed `name` and a
-   *        `value` of arbitrary type.
-   *
-   * @throws CodeError if got an empty header name.
-   * @throws NotWellKnownEncodingError if the well-known header field number is
-   *         not registered or supported.
-   */
-  encode: function(data, header) {
-    if (!header.name) {
-      throw new WSP.CodeError("MMS-header: empty header name");
-    }
-
-    let entry = MMS_HEADER_FIELDS[header.name.toLowerCase()];
-    if (!entry) {
-      throw new WSP.NotWellKnownEncodingError(
-        "MMS-header: not well known header " + header.name);
-    }
-
-    WSP.ShortInteger.encode(data, entry.number);
-    entry.coder.encode(data, header.value);
-  },
-};
-
-/**
- * Cancel-status-value = Cancel Request Successfully received |
- *                       Cancel Request corrupted
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.7
- */
-this.CancelStatusValue = new RangedValue("Cancel-status-value", 128, 129);
-
-/**
- * Content-class-value = text | image-basic| image-rich | video-basic |
- *                       video-rich | megapixel | content-basic | content-rich
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.9
- */
-this.ContentClassValue = new RangedValue("Content-class-value", 128, 135);
-
-/**
- * When used in a PDU other than M-Mbox-Delete.conf and M-Delete.conf:
- *
- *   Content-location-value = Uri-value
- *
- * When used in the M-Mbox-Delete.conf and M-Delete.conf PDU:
- *
- *   Content-location-Del-value = Value-length Status-count-value Content-location-value
- *   Status-count-value = Integer-value
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.10
- */
-this.ContentLocationValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param options
-   *        Extra context for decoding.
-   *
-   * @return A decoded object containing `uri` and conditional `statusCount`
-   *         properties.
-   */
-  decode: function(data, options) {
-    let type = WSP.ensureHeader(options, "x-mms-message-type");
-
-    let result = {};
-    if ((type == MMS_PDU_TYPE_MBOX_DELETE_CONF)
-        || (type == MMS_PDU_TYPE_DELETE_CONF)) {
-      let length = WSP.ValueLength.decode(data);
-      let end = data.offset + length;
-
-      result.statusCount = WSP.IntegerValue.decode(data);
-      result.uri = WSP.UriValue.decode(data);
-
-      if (data.offset != end) {
-        data.offset = end;
-      }
-    } else {
-      result.uri = WSP.UriValue.decode(data);
-    }
-
-    return result;
-  },
-};
-
-/**
- * Element-Descriptor-value = Value-length Content-Reference-value *(Parameter)
- * Content-Reference-value = Text-string
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.18
- */
-this.ElementDescriptorValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing a string property `contentReference`
-   *         and an optinal `params` name-value map.
-   */
-  decode: function(data) {
-    let length = WSP.ValueLength.decode(data);
-    let end = data.offset + length;
-
-    let result = {};
-    result.contentReference = WSP.TextString.decode(data);
-    if (data.offset < end) {
-      result.params = Parameter.decodeMultiple(data, end);
-    }
-
-    if (data.offset != end) {
-      // Explicitly seek to end in case of skipped parameters.
-      data.offset = end;
-    }
-
-    return result;
-  },
-};
-
-/**
- * OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.18:
- * `For well-known parameter names binary tokens MUST be used as defined in
- * Table 27.` So we can't reuse that of WSP.
- *
- *   Parameter = Parameter-name Parameter-value
- *   Parameter-name = Short-integer | Text-string
- *   Parameter-value = Constrained-encoding | Text-string
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.18
- */
-this.Parameter = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded string.
-   *
-   * @throws NotWellKnownEncodingError if decoded well-known parameter number
-   *         is not registered or supported.
-   */
-  decodeParameterName: function(data) {
-    let begin = data.offset;
-    let number;
-    try {
-      number = WSP.ShortInteger.decode(data);
-    } catch (e) {
-      data.offset = begin;
-      return WSP.TextString.decode(data).toLowerCase();
-    }
-
-    let entry = MMS_WELL_KNOWN_PARAMS[number];
-    if (!entry) {
-      throw new WSP.NotWellKnownEncodingError(
-        "Parameter-name: not well known parameter " + number);
-    }
-
-    return entry.name;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing `name` and `value` properties or null
-   *         in case of a failed parsing. The `name` property must be a string,
-   *         but the `value` property can be many different types depending on
-   *         `name`.
-   */
-  decode: function(data) {
-    let name = this.decodeParameterName(data);
-    let value = WSP.decodeAlternatives(data, null,
-                                       WSP.ConstrainedEncoding, WSP.TextString);
-    return {
-      name: name,
-      value: value,
-    };
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param end
-   *        Ending offset of following parameters.
-   *
-   * @return An array of decoded objects.
-   */
-  decodeMultiple: function(data, end) {
-    let params, param;
-
-    while (data.offset < end) {
-      try {
-        param = this.decode(data);
-      } catch (e) {
-        break;
-      }
-      if (param) {
-        if (!params) {
-          params = {};
-        }
-        params[param.name] = param.value;
-      }
-    }
-
-    return params;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param param
-   *        An object containing two attributes: `name` and `value`.
-   * @param options
-   *        Extra context for encoding.
-   */
-  encode: function(data, param, options) {
-    if (!param || !param.name) {
-      throw new WSP.CodeError("Parameter-name: empty param name");
-    }
-
-    let entry = MMS_WELL_KNOWN_PARAMS[param.name.toLowerCase()];
-    if (entry) {
-      WSP.ShortInteger.encode(data, entry.number);
-    } else {
-      WSP.TextString.encode(data, param.name);
-    }
-
-    WSP.encodeAlternatives(data, param.value, options,
-                           WSP.ConstrainedEncoding, WSP.TextString);
-  },
-};
-
-/**
- * The Char-set values are registered by IANA as MIBEnum value and SHALL be
- * encoded as Integer-value.
- *
- *   Encoded-string-value = Text-string | Value-length Char-set Text-string
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.19
- * @see OMA-TS-MMS_CONF-V1_3-20110913-A clause 10.2.1
- */
-this.EncodedStringValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded string.
-   *
-   * @throws CodeError if the raw octets cannot be converted.
-   * @throws NotWellKnownEncodingError if decoded well-known charset number is
-   *         not registered or supported.
-   */
-  decodeCharsetEncodedString: function(data) {
-    let length = WSP.ValueLength.decode(data);
-    let end = data.offset + length;
-
-    let charset = WSP.IntegerValue.decode(data);
-    let entry = WSP.WSP_WELL_KNOWN_CHARSETS[charset];
-    if (!entry) {
-      throw new WSP.NotWellKnownEncodingError(
-        "Charset-encoded-string: not well known charset " + charset);
-    }
-
-    let str;
-    if (entry.converter) {
-      // Read a possible string quote(<Octet 127>).
-      let begin = data.offset;
-      if (WSP.Octet.decode(data) != 127) {
-        data.offset = begin;
-      }
-
-      let raw = WSP.Octet.decodeMultiple(data, end - 1);
-      // Read NUL character.
-      WSP.Octet.decodeEqualTo(data, 0);
-
-      if (!raw) {
-        str = "";
-      } else {
-        let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
-                   .createInstance(Ci.nsIScriptableUnicodeConverter);
-        conv.charset = entry.converter;
-        try {
-          str = conv.convertFromByteArray(raw, raw.length);
-        } catch (e) {
-          throw new WSP.CodeError("Charset-encoded-string: " + e.message);
-        }
-      }
-    } else {
-      str = WSP.TextString.decode(data);
-    }
-
-    if (data.offset != end) {
-      data.offset = end;
-    }
-
-    return str;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded string.
-   */
-  decode: function(data) {
-    let begin = data.offset;
-    try {
-      return WSP.TextString.decode(data);
-    } catch (e) {
-      data.offset = begin;
-      return this.decodeCharsetEncodedString(data);
-    }
-  },
-
-  /**
-   * Always encode target string with UTF-8 encoding.
-   *
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param str
-   *        A string.
-   */
-  encodeCharsetEncodedString: function(data, str) {
-    let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
-               .createInstance(Ci.nsIScriptableUnicodeConverter);
-    // `When the text string cannot be represented as us-ascii, the character
-    // set SHALL be encoded as utf-8(IANA MIBenum 106) which has unique byte
-    // ordering.` ~ OMA-TS-MMS_CONF-V1_3-20110913-A clause 10.2.1
-    conv.charset = "UTF-8";
-
-    let raw;
-    try {
-      raw = conv.convertToByteArray(str);
-    } catch (e) {
-      throw new WSP.CodeError("Charset-encoded-string: " + e.message);
-    }
-
-    let length = raw.length + 2; // Charset number and NUL character
-    // Prepend <Octet 127> if necessary.
-    if (raw[0] >= 128) {
-      ++length;
-    }
-
-    WSP.ValueLength.encode(data, length);
-
-    let entry = WSP.WSP_WELL_KNOWN_CHARSETS["utf-8"];
-    WSP.IntegerValue.encode(data, entry.number);
-
-    if (raw[0] >= 128) {
-      WSP.Octet.encode(data, 127);
-    }
-    WSP.Octet.encodeMultiple(data, raw);
-    WSP.Octet.encode(data, 0);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param str
-   *        A string.
-   */
-  encode: function(data, str) {
-    let begin = data.offset;
-    try {
-      // Quoted from OMA-TS-MMS-CONF-V1_3-20110913-A:
-      // Some of the MMS headers have been defined as "Encoded-string-value".
-      // The character set IANA MIBEnum value in these headers SHALL be
-      // encoded as Integer-value ([WAPWSP] section 8.4.2.3). The character
-      // set us-ascii (IANA MIBenum 3) SHALL always be accepted. If the
-      // character set is not specified (simple Text-string encoding) the
-      // character set SHALL be identified as us-ascii (lower half of ISO
-      // 8859-1 [ISO8859-1]). When the text string cannot be represented as
-      // us-ascii, the character set SHALL be encoded as utf-8 (IANA MIBenum
-      // 106) which has unique byte ordering.
-      WSP.TextString.encode(data, str, true);
-    } catch (e) {
-      data.offset = begin;
-      this.encodeCharsetEncodedString(data, str);
-    }
-  },
-};
-
-/**
- * Expiry-value = Value-length (Absolute-token Date-value | Relative-token Delta-seconds-value)
- * Absolute-token = <Octet 128>
- * Relative-token = <Octet 129>
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.20
- */
-this.ExpiryValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A Date object for absolute expiry or an integer for relative one.
-   *
-   * @throws CodeError if decoded token equals to neither 128 nor 129.
-   */
-  decode: function(data) {
-    let length = WSP.ValueLength.decode(data);
-    let end = data.offset + length;
-
-    let token = WSP.Octet.decode(data);
-    if ((token != 128) && (token != 129)) {
-      throw new WSP.CodeError("Expiry-value: invalid token " + token);
-    }
-
-    let result;
-    if (token == 128) {
-      result = WSP.DateValue.decode(data);
-    } else {
-      result = WSP.DeltaSecondsValue.decode(data);
-    }
-
-    if (data.offset != end) {
-      data.offset = end;
-    }
-
-    return result;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        A Date object for absolute expiry or an integer for relative one.
-   */
-  encode: function(data, value) {
-    let isDate, begin = data.offset;
-    if (value instanceof Date) {
-      isDate = true;
-      WSP.DateValue.encode(data, value);
-    } else if (typeof value == "number") {
-      isDate = false;
-      WSP.DeltaSecondsValue.encode(data, value);
-    } else {
-      throw new CodeError("Expiry-value: invalid value type");
-    }
-
-    // Calculate how much octets will be written and seek back.
-    // TODO: use memmove, see bug 730873
-    let len = data.offset - begin;
-    data.offset = begin;
-
-    WSP.ValueLength.encode(data, len + 1);
-    if (isDate) {
-      WSP.Octet.encode(data, 128);
-      WSP.DateValue.encode(data, value);
-    } else {
-      WSP.Octet.encode(data, 129);
-      WSP.DeltaSecondsValue.encode(data, value);
-    }
-  },
-};
-
-/**
- * From-value = Value-length (Address-present-token Address | Insert-address-token)
- * Address-present-token = <Octet 128>
- * Insert-address-token = <Octet 129>
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.21
- */
-this.FromValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded Address-value or null for MMS Proxy-Relay Insert-Address
-   *         mode.
-   *
-   * @throws CodeError if decoded token equals to neither 128 nor 129.
-   */
-  decode: function(data) {
-    let length = WSP.ValueLength.decode(data);
-    let end = data.offset + length;
-
-    let token = WSP.Octet.decode(data);
-    if ((token != 128) && (token != 129)) {
-      throw new WSP.CodeError("From-value: invalid token " + token);
-    }
-
-    let result = null;
-    if (token == 128) {
-      result = Address.decode(data);
-    }
-
-    if (data.offset != end) {
-      data.offset = end;
-    }
-
-    return result;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        A Address-value or null for MMS Proxy-Relay Insert-Address mode.
-   */
-  encode: function(data, value) {
-    if (!value) {
-      WSP.ValueLength.encode(data, 1);
-      WSP.Octet.encode(data, 129);
-      return;
-    }
-
-    // Calculate how much octets will be written and seek back.
-    // TODO: use memmove, see bug 730873
-    let begin = data.offset;
-    Address.encode(data, value);
-    let len = data.offset - begin;
-    data.offset = begin;
-
-    WSP.ValueLength.encode(data, len + 1);
-    WSP.Octet.encode(data, 128);
-    Address.encode(data, value);
-  },
-};
-
-/**
- * Previously-sent-by-value = Value-length Forwarded-count-value Address
- * Forwarded-count-value = Integer-value
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.23
- */
-this.PreviouslySentByValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded object containing an integer `forwardedCount` and an
-   *         string-typed `originator` attributes.
-   */
-  decode: function(data) {
-    let length = WSP.ValueLength.decode(data);
-    let end = data.offset + length;
-
-    let result = {};
-    result.forwardedCount = WSP.IntegerValue.decode(data);
-    result.originator = Address.decode(data);
-
-    if (data.offset != end) {
-      data.offset = end;
-    }
-
-    return result;
-  },
-};
-
-/**
- * Previously-sent-date-value = Value-length Forwarded-count-value Date-value
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.23
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.24
- */
-this.PreviouslySentDateValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded object containing an integer `forwardedCount` and an
-   *         Date-typed `timestamp` attributes.
-   */
-  decode: function(data) {
-    let length = WSP.ValueLength.decode(data);
-    let end = data.offset + length;
-
-    let result = {};
-    result.forwardedCount = WSP.IntegerValue.decode(data);
-    result.timestamp = WSP.DateValue.decode(data);
-
-    if (data.offset != end) {
-      data.offset = end;
-    }
-
-    return result;
-  },
-};
-
-/**
- * Message-class-value = Class-identifier | Token-text
- * Class-identifier = Personal | Advertisement | Informational | Auto
- * Personal = <Octet 128>
- * Advertisement = <Octet 129>
- * Informational = <Octet 130>
- * Auto = <Octet 131>
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.27
- */
-this.MessageClassValue = {
-  WELL_KNOWN_CLASSES: ["personal", "advertisement", "informational", "auto"],
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded string.
-   *
-   * @throws CodeError if decoded value is not in the range 128..131.
-   */
-  decodeClassIdentifier: function(data) {
-    let value = WSP.Octet.decode(data);
-    if ((value >= 128) && (value < (128 + this.WELL_KNOWN_CLASSES.length))) {
-      return this.WELL_KNOWN_CLASSES[value - 128];
-    }
-
-    throw new WSP.CodeError("Class-identifier: invalid id " + value);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded string.
-   */
-  decode: function(data) {
-    let begin = data.offset;
-    try {
-      return this.decodeClassIdentifier(data);
-    } catch (e) {
-      data.offset = begin;
-      return WSP.TokenText.decode(data);
-    }
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param klass
-   */
-  encode: function(data, klass) {
-    let index = this.WELL_KNOWN_CLASSES.indexOf(klass.toLowerCase());
-    if (index >= 0) {
-      WSP.Octet.encode(data, index + 128);
-    } else {
-      WSP.TokenText.encode(data, klass);
-    }
-  },
-};
-
- /**
- * Message-type-value = <Octet 128..151>
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.30
- */
-this.MessageTypeValue = new RangedValue("Message-type-value", 128, 151);
-
-/**
- * MM-flags-value = Value-length ( Add-token | Remove-token | Filter-token ) Encoded-string-value
- * Add-token = <Octet 128>
- * Remove-token = <Octet 129>
- * Filter-token = <Octet 130>
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.32
- */
-this.MmFlagsValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded object containing an integer `type` and an string-typed
-   *         `text` attributes.
-   *
-   * @throws CodeError if decoded value is not in the range 128..130.
-   */
-  decode: function(data) {
-    let length = WSP.ValueLength.decode(data);
-    let end = data.offset + length;
-
-    let result = {};
-    result.type = WSP.Octet.decode(data);
-    if ((result.type < 128) || (result.type > 130)) {
-      throw new WSP.CodeError("MM-flags-value: invalid type " + result.type);
-    }
-    result.text = EncodedStringValue.decode(data);
-
-    if (data.offset != end) {
-      data.offset = end;
-    }
-
-    return result;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An object containing an integer `type` and an string-typed
-   *        `text` attributes.
-   */
-  encode: function(data, value) {
-    if ((value.type < 128) || (value.type > 130)) {
-      throw new WSP.CodeError("MM-flags-value: invalid type " + value.type);
-    }
-
-    // Calculate how much octets will be written and seek back.
-    // TODO: use memmove, see bug 730873
-    let begin = data.offset;
-    EncodedStringValue.encode(data, value.text);
-    let len = data.offset - begin;
-    data.offset = begin;
-
-    WSP.ValueLength.encode(data, len + 1);
-    WSP.Octet.encode(data, value.type);
-    EncodedStringValue.encode(data, value.text);
-  },
-};
-
-/**
- * MM-state-value = Draft | Sent | New | Retrieved | Forwarded
- * Draft = <Octet 128>
- * Sent = <Octet 129>
- * New = <Octet 130>
- * Retrieved = <Octet 131>
- * Forwarded = <Octet 132>
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.33
- */
-this.MmStateValue = new RangedValue("MM-state-value", 128, 132);
-
-/**
- * Priority-value = Low | Normal | High
- * Low = <Octet 128>
- * Normal = <Octet 129>
- * High = <Octet 130>
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.35
- */
-this.PriorityValue = new RangedValue("Priority-value", 128, 130);
-
-/**
- * Read-status-value = Read | Deleted without being read
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.38
- */
-this.ReadStatusValue = new RangedValue("Read-status-value", 128, 129);
-
-/**
- * Recommended-Retrieval-Mode-value = Manual
- * Manual = <Octet 128>
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.39
- */
-this.RecommendedRetrievalModeValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded integer.
-   */
-  decode: function(data) {
-    return WSP.Octet.decodeEqualTo(data, 128);
-  },
-};
-
-/**
- * Reply-charging-value = Requested | Requested text only | Accepted |
- *                        Accepted text only
- * Requested = <Octet 128>
- * Requested text only = <Octet 129>
- * Accepted = <Octet 130>
- * Accepted text only = <Octet 131>
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.43
- */
-this.ReplyChargingValue = new RangedValue("Reply-charging-value", 128, 131);
-
-/**
- * When used in a PDU other than M-Mbox-Delete.conf and M-Delete.conf:
- *
- *   Response-text-value = Encoded-string-value
- *
- * When used in the M-Mbox-Delete.conf and M-Delete.conf PDUs:
- *
- *   Response-text-Del-value = Value-length Status-count-value Response-text-value
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.49
- */
-this.ResponseText = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param options
-   *        Extra context for decoding.
-   *
-   * @return An object containing a string-typed `text` attribute and a
-   *         integer-typed `statusCount` one.
-   */
-  decode: function(data, options) {
-    let type = WSP.ensureHeader(options, "x-mms-message-type");
-
-    let result = {};
-    if ((type == MMS_PDU_TYPE_MBOX_DELETE_CONF)
-        || (type == MMS_PDU_TYPE_DELETE_CONF)) {
-      let length = WSP.ValueLength.decode(data);
-      let end = data.offset + length;
-
-      result.statusCount = WSP.IntegerValue.decode(data);
-      result.text = EncodedStringValue.decode(data);
-
-      if (data.offset != end) {
-        data.offset = end;
-      }
-    } else {
-      result.text = EncodedStringValue.decode(data);
-    }
-
-    return result;
-  },
-};
-
-/**
- * Retrieve-status-value = Ok | Error-transient-failure |
- *                         Error-transient-message-not-found |
- *                         Error-transient-network-problem |
- *                         Error-permanent-failure |
- *                         Error-permanent-service-denied |
- *                         Error-permanent-message-not-found |
- *                         Error-permanent-content-unsupported
- * Ok = <Octet 128>
- * Error-transient-failure = <Octet 192>
- * Error-transient-message-not-found = <Octet 193>
- * Error-transient-network-problem = <Octet 194>
- * Error-permanent-failure = <Octet 224>
- * Error-permanent-service-denied = <Octet 225>
- * Error-permanent-message-not-found = <Octet 226>
- * Error-permanent-content-unsupported = <Octet 227>
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.50
- */
-this.RetrieveStatusValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded integer.
-   */
-  decode: function(data) {
-    let value = WSP.Octet.decode(data);
-    if (value == MMS_PDU_ERROR_OK) {
-      return value;
-    }
-
-    if ((value >= MMS_PDU_ERROR_TRANSIENT_FAILURE) && (value < 256)) {
-      return value;
-    }
-
-    // Any other values SHALL NOT be used. They are reserved for future use.
-    // An MMS Client that receives such a reserved value MUST react the same
-    // as it does to the value 224 (Error-permanent-failure).
-    return MMS_PDU_ERROR_PERMANENT_FAILURE;
-  },
-};
-
-/**
- * Sender-visibility-value = Hide | Show
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.52
- */
-this.SenderVisibilityValue = new RangedValue("Sender-visibility-value", 128, 129);
-
-/**
- * Status-value = Expired | Retrieved | Rejected | Deferred | Unrecognised |
- *                Indeterminate | Forwarded | Unreachable
- * Expired = <Octet 128>
- * Retrieved = <Octet 129>
- * Rejected = <Octet 130>
- * Deferred = <Octet 131>
- * Unrecognised = <Octet 132>
- * Indeterminate = <Octet 133>
- * Forwarded = <Octet 134>
- * Unreachable = <Octet 135>
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.54
- */
-this.StatusValue = new RangedValue("Status-value", 128, 135);
-
-this.PduHelper = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param headers
-   *        An optional object to store parsed header fields. Created
-   *        automatically if undefined.
-   *
-   * @return A boolean value indicating whether it's followed by message body.
-   */
-  parseHeaders: function(data, headers) {
-    if (!headers) {
-      headers = {};
-    }
-
-    let header;
-    while (data.offset < data.array.length) {
-      // There is no `header length` information in MMS PDU. If we just got
-      // something wrong in parsing header fields, we might not be able to
-      // determine the correct header-content boundary.
-      header = HeaderField.decode(data, headers);
-
-      if (header) {
-        let orig = headers[header.name];
-        if (Array.isArray(orig)) {
-          headers[header.name].push(header.value);
-        } else if (orig) {
-          headers[header.name] = [orig, header.value];
-        } else {
-          headers[header.name] = header.value;
-        }
-        if (header.name == "content-type") {
-          // `... if the PDU contains a message body the Content Type MUST be
-          // the last header field, followed by message body.` See
-          // OMA-TS-MMS_ENC-V1_3-20110913-A section 7.
-          break;
-        }
-      }
-    }
-
-    return headers;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param msg
-   *        A message object to store decoded multipart or octet array content.
-   */
-  parseContent: function(data, msg) {
-    let contentType = msg.headers["content-type"].media;
-    if ((contentType == "application/vnd.wap.multipart.related")
-        || (contentType == "application/vnd.wap.multipart.mixed")) {
-      msg.parts = WSP.PduHelper.parseMultiPart(data);
-      return;
-    }
-
-    if (data.offset >= data.array.length) {
-      return;
-    }
-
-    msg.content = WSP.Octet.decodeMultiple(data, data.array.length);
-    if (false) {
-      for (let begin = 0; begin < msg.content.length; begin += 20) {
-        debug("content: " + JSON.stringify(msg.content.subarray(begin, begin + 20)));
-      }
-    }
-  },
-
-  /**
-   * Check existences of all mandatory fields of a MMS message. Also sets `type`
-   * for convenient access.
-   *
-   * @param msg
-   *        A MMS message object.
-   *
-   * @return The corresponding entry in MMS_PDU_TYPES;
-   *
-   * @throws FatalCodeError if the PDU type is not supported yet.
-   */
-  checkMandatoryFields: function(msg) {
-    let type = WSP.ensureHeader(msg.headers, "x-mms-message-type");
-    let entry = MMS_PDU_TYPES[type];
-    if (!entry) {
-      throw new WSP.FatalCodeError(
-        "checkMandatoryFields: unsupported message type " + type);
-    }
-
-    entry.mandatoryFields.forEach(function(name) {
-      WSP.ensureHeader(msg.headers, name);
-    });
-
-    // Setup convenient alias that referenced frequently.
-    msg.type = type;
-
-    return entry;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param msg [optional]
-   *        Optional target object for decoding.
-   *
-   * @return A MMS message object or null in case of errors found.
-   */
-  parse: function(data, msg) {
-    if (!msg) {
-      msg = {};
-    }
-
-    try {
-      msg.headers = this.parseHeaders(data, msg.headers);
-
-      // Validity checks
-      let typeinfo = this.checkMandatoryFields(msg);
-      if (typeinfo.hasContent) {
-        this.parseContent(data, msg);
-      }
-    } catch (e) {
-      debug("Failed to parse MMS message, error message: " + e.message);
-      return null;
-    }
-
-    return msg;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param headers
-   *        A dictionary object containing multiple name/value mapping.
-   * @param name
-   *        Name of the header field to be encoded.
-   */
-  encodeHeader: function(data, headers, name) {
-    let value = headers[name];
-    if (Array.isArray(value)) {
-      for (let i = 0; i < value.length; i++) {
-        HeaderField.encode(data, {name: name, value: value[i]}, headers);
-      }
-    } else {
-      HeaderField.encode(data, {name: name, value: value}, headers);
-    }
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param headers
-   *        A dictionary object containing multiple name/value mapping.
-   */
-  encodeHeaderIfExists: function(data, headers, name) {
-    // Header value could be zero or null.
-    if (headers[name] !== undefined) {
-      this.encodeHeader(data, headers, name);
-    }
-  },
-
-  /**
-   * @param data [optional]
-   *        A wrapped object to store encoded raw data. Created if undefined.
-   * @param headers
-   *        A dictionary object containing multiple name/value mapping.
-   *
-   * @return the passed data parameter or a created one.
-   */
-  encodeHeaders: function(data, headers) {
-    if (!data) {
-      data = {array: [], offset: 0};
-    }
-
-    // `In the encoding of the header fields, the order of the fields is not
-    // significant, except that X-Mms-Message-Type, X-Mms-Transaction-ID (when
-    // present) and X-Mms-MMS-Version MUST be at the beginning of the message
-    // headers, in that order, and if the PDU contains a message body the
-    // Content Type MUST be the last header field, followed by message body.`
-    // ~ OMA-TS-MMS_ENC-V1_3-20110913-A section 7
-    this.encodeHeader(data, headers, "x-mms-message-type");
-    this.encodeHeaderIfExists(data, headers, "x-mms-transaction-id");
-    this.encodeHeaderIfExists(data, headers, "x-mms-mms-version");
-
-    for (let key in headers) {
-      if ((key == "x-mms-message-type")
-          || (key == "x-mms-transaction-id")
-          || (key == "x-mms-mms-version")
-          || (key == "content-type")) {
-        continue;
-      }
-      this.encodeHeader(data, headers, key);
-    }
-
-    this.encodeHeaderIfExists(data, headers, "content-type");
-
-    return data;
-  },
-
-  /**
-   * @param multiStream
-   *        An exsiting nsIMultiplexInputStream.
-   * @param msg
-   *        A MMS message object.
-   *
-   * @return An instance of nsIMultiplexInputStream or null in case of errors.
-   */
-  compose: function(multiStream, msg) {
-    if (!multiStream) {
-      multiStream = Cc["@mozilla.org/io/multiplex-input-stream;1"]
-                    .createInstance(Ci.nsIMultiplexInputStream);
-    }
-
-    try {
-      // Validity checks
-      let typeinfo = this.checkMandatoryFields(msg);
-
-      let data = this.encodeHeaders(null, msg.headers);
-      debug("Composed PDU Header: " + JSON.stringify(data.array));
-      WSP.PduHelper.appendArrayToMultiStream(multiStream, data.array, data.offset);
-
-      if (msg.content) {
-        WSP.PduHelper.appendArrayToMultiStream(multiStream, msg.content, msg.content.length);
-      } else if (msg.parts) {
-        WSP.PduHelper.composeMultiPart(multiStream, msg.parts);
-      } else if (typeinfo.hasContent) {
-        throw new WSP.CodeError("Missing message content");
-      }
-
-      return multiStream;
-    } catch (e) {
-      debug("Failed to compose MMS message, error message: " + e.message);
-      return null;
-    }
-  },
-};
-
-const MMS_PDU_TYPES = (function() {
-  let pdus = {};
-  function add(number, hasContent, mandatoryFields) {
-    pdus[number] = {
-      number: number,
-      hasContent: hasContent,
-      mandatoryFields: mandatoryFields,
-    };
-  }
-
-  add(MMS_PDU_TYPE_SEND_REQ, true, ["x-mms-message-type",
-                                    "x-mms-transaction-id",
-                                    "x-mms-mms-version",
-                                    "from",
-                                    "content-type"]);
-  add(MMS_PDU_TYPE_SEND_CONF, false, ["x-mms-message-type",
-                                      "x-mms-transaction-id",
-                                      "x-mms-mms-version",
-                                      "x-mms-response-status"]);
-  add(MMS_PDU_TYPE_NOTIFICATION_IND, false, ["x-mms-message-type",
-                                             "x-mms-transaction-id",
-                                             "x-mms-mms-version",
-                                             "x-mms-message-class",
-                                             "x-mms-message-size",
-                                             "x-mms-expiry",
-                                             "x-mms-content-location"]);
-  add(MMS_PDU_TYPE_RETRIEVE_CONF, true, ["x-mms-message-type",
-                                         "x-mms-mms-version",
-                                         "date",
-                                         "content-type"]);
-  add(MMS_PDU_TYPE_NOTIFYRESP_IND, false, ["x-mms-message-type",
-                                           "x-mms-transaction-id",
-                                           "x-mms-mms-version",
-                                           "x-mms-status"]);
-  add(MMS_PDU_TYPE_DELIVERY_IND, false, ["x-mms-message-type",
-                                         "x-mms-mms-version",
-                                         "message-id",
-                                         "to",
-                                         "date",
-                                         "x-mms-status"]);
-  add(MMS_PDU_TYPE_ACKNOWLEDGE_IND, false, ["x-mms-message-type",
-                                            "x-mms-transaction-id",
-                                            "x-mms-mms-version"]);
-  add(MMS_PDU_TYPE_READ_REC_IND, false, ["x-mms-message-type",
-                                         "message-id",
-                                         "x-mms-mms-version",
-                                         "to",
-                                         "from",
-                                         "x-mms-read-status"]);
-  add(MMS_PDU_TYPE_READ_ORIG_IND, false, ["x-mms-message-type",
-                                          "x-mms-mms-version",
-                                          "message-id",
-                                          "to",
-                                          "from",
-                                          "date",
-                                          "x-mms-read-status"]);
-
-  return pdus;
-})();
-
-/**
- * Header field names and assigned numbers.
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.4
- */
-const MMS_HEADER_FIELDS = (function() {
-  let names = {};
-  function add(name, number, coder) {
-    let entry = {
-      name: name,
-      number: number,
-      coder: coder,
-    };
-    names[name] = names[number] = entry;
-  }
-
-  add("bcc",                                     0x01, Address);
-  add("cc",                                      0x02, Address);
-  add("x-mms-content-location",                  0x03, ContentLocationValue);
-  add("content-type",                            0x04, WSP.ContentTypeValue);
-  add("date",                                    0x05, WSP.DateValue);
-  add("x-mms-delivery-report",                   0x06, BooleanValue);
-  add("x-mms-delivery-time",                     0x07, ExpiryValue);
-  add("x-mms-expiry",                            0x08, ExpiryValue);
-  add("from",                                    0x09, FromValue);
-  add("x-mms-message-class",                     0x0A, MessageClassValue);
-  add("message-id",                              0x0B, WSP.TextString);
-  add("x-mms-message-type",                      0x0C, MessageTypeValue);
-  add("x-mms-mms-version",                       0x0D, WSP.ShortInteger);
-  add("x-mms-message-size",                      0x0E, WSP.LongInteger);
-  add("x-mms-priority",                          0x0F, PriorityValue);
-  add("x-mms-read-report",                       0x10, BooleanValue);
-  add("x-mms-report-allowed",                    0x11, BooleanValue);
-  add("x-mms-response-status",                   0x12, RetrieveStatusValue);
-  add("x-mms-response-text",                     0x13, ResponseText);
-  add("x-mms-sender-visibility",                 0x14, SenderVisibilityValue);
-  add("x-mms-status",                            0x15, StatusValue);
-  add("subject",                                 0x16, EncodedStringValue);
-  add("to",                                      0x17, Address);
-  add("x-mms-transaction-id",                    0x18, WSP.TextString);
-  add("x-mms-retrieve-status",                   0x19, RetrieveStatusValue);
-  add("x-mms-retrieve-text",                     0x1A, EncodedStringValue);
-  add("x-mms-read-status",                       0x1B, ReadStatusValue);
-  add("x-mms-reply-charging",                    0x1C, ReplyChargingValue);
-  add("x-mms-reply-charging-deadline",           0x1D, ExpiryValue);
-  add("x-mms-reply-charging-id",                 0x1E, WSP.TextString);
-  add("x-mms-reply-charging-size",               0x1F, WSP.LongInteger);
-  add("x-mms-previously-sent-by",                0x20, PreviouslySentByValue);
-  add("x-mms-previously-sent-date",              0x21, PreviouslySentDateValue);
-  add("x-mms-store",                             0x22, BooleanValue);
-  add("x-mms-mm-state",                          0x23, MmStateValue);
-  add("x-mms-mm-flags",                          0x24, MmFlagsValue);
-  add("x-mms-store-status",                      0x25, RetrieveStatusValue);
-  add("x-mms-store-status-text",                 0x26, EncodedStringValue);
-  add("x-mms-stored",                            0x27, BooleanValue);
-  //add("x-mms-attributes", 0x28);
-  add("x-mms-totals",                            0x29, BooleanValue);
-  //add("x-mms-mbox-totals", 0x2A);
-  add("x-mms-quotas",                            0x2B, BooleanValue);
-  //add("x-mms-mbox-quotas", 0x2C);
-  add("x-mms-message-count",                     0x2D, WSP.IntegerValue);
-  //add("content", 0x2E);
-  add("x-mms-start",                             0x2F, WSP.IntegerValue);
-  //add("additional-headers", 0x30);
-  add("x-mms-distribution-indicator",            0x31, BooleanValue);
-  add("x-mms-element-descriptor",                0x32, ElementDescriptorValue);
-  add("x-mms-limit",                             0x33, WSP.IntegerValue);
-  add("x-mms-recommended-retrieval-mode",        0x34, RecommendedRetrievalModeValue);
-  add("x-mms-recommended-retrieval-mode-text",   0x35, EncodedStringValue);
-  //add("x-mms-status-text", 0x36);
-  add("x-mms-applic-id",                         0x37, WSP.TextString);
-  add("x-mms-reply-applic-id",                   0x38, WSP.TextString);
-  add("x-mms-aux-applic-id",                     0x39, WSP.TextString);
-  add("x-mms-content-class",                     0x3A, ContentClassValue);
-  add("x-mms-drm-content",                       0x3B, BooleanValue);
-  add("x-mms-adaptation-allowed",                0x3C, BooleanValue);
-  add("x-mms-replace-id",                        0x3D, WSP.TextString);
-  add("x-mms-cancel-id",                         0x3E, WSP.TextString);
-  add("x-mms-cancel-status",                     0x3F, CancelStatusValue);
-
-  return names;
-})();
-
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A Table 27: Parameter Name Assignments
-const MMS_WELL_KNOWN_PARAMS = (function() {
-  let params = {};
-
-  function add(name, number, coder) {
-    let entry = {
-      name: name,
-      number: number,
-      coder: coder,
-    };
-    params[name] = params[number] = entry;
-  }
-
-  // Encoding Version: 1.2
-  add("type", 0x02, WSP.TypeValue);
-
-  return params;
-})();
-
-var debug;
-if (DEBUG) {
-  debug = function(s) {
-    dump("-$- MmsPduHelper: " + s + "\n");
-  };
-} else {
-  debug = function(s) {};
-}
-
-this.EXPORTED_SYMBOLS = ALL_CONST_SYMBOLS.concat([
-  // Constant values
-  "MMS_VERSION",
-
-  // Utility functions
-  "translatePduErrorToStatus",
-
-  // Decoders
-  "BooleanValue",
-  "Address",
-  "HeaderField",
-  "MmsHeader",
-  "CancelStatusValue",
-  "ContentClassValue",
-  "ContentLocationValue",
-  "ElementDescriptorValue",
-  "Parameter",
-  "EncodedStringValue",
-  "ExpiryValue",
-  "FromValue",
-  "PreviouslySentByValue",
-  "PreviouslySentDateValue",
-  "MessageClassValue",
-  "MessageTypeValue",
-  "MmFlagsValue",
-  "MmStateValue",
-  "PriorityValue",
-  "ReadStatusValue",
-  "RecommendedRetrievalModeValue",
-  "ReplyChargingValue",
-  "ResponseText",
-  "RetrieveStatusValue",
-  "SenderVisibilityValue",
-  "StatusValue",
-
-  // Parser
-  "PduHelper",
-]);
-
deleted file mode 100644
--- a/dom/mobilemessage/gonk/MmsService.js
+++ /dev/null
@@ -1,2736 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 sts=2 et filetype=javascript
- * 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;
-
-Cu.importGlobalProperties(['Blob', 'FileReader']);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/PhoneNumberUtils.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-
-const GONK_MMSSERVICE_CONTRACTID = "@mozilla.org/mms/gonkmmsservice;1";
-const GONK_MMSSERVICE_CID = Components.ID("{9b069b8c-8697-11e4-a406-474f5190272b}");
-
-var DEBUG = false;
-function debug(s) {
-  dump("-@- MmsService: " + s + "\n");
-};
-
-const kSmsSendingObserverTopic           = "sms-sending";
-const kSmsSentObserverTopic              = "sms-sent";
-const kSmsFailedObserverTopic            = "sms-failed";
-const kSmsReceivedObserverTopic          = "sms-received";
-const kSmsRetrievingObserverTopic        = "sms-retrieving";
-const kSmsDeliverySuccessObserverTopic   = "sms-delivery-success";
-const kSmsDeliveryErrorObserverTopic     = "sms-delivery-error";
-const kSmsReadSuccessObserverTopic       = "sms-read-success";
-const kSmsReadErrorObserverTopic         = "sms-read-error";
-const kSmsDeletedObserverTopic           = "sms-deleted";
-
-const NS_XPCOM_SHUTDOWN_OBSERVER_ID      = "xpcom-shutdown";
-const kNetworkConnStateChangedTopic      = "network-connection-state-changed";
-
-const kPrefMmsDebuggingEnabled           = "mms.debugging.enabled";
-
-// HTTP status codes:
-// @see http://tools.ietf.org/html/rfc2616#page-39
-const HTTP_STATUS_OK = 200;
-
-// Non-standard HTTP status for internal use.
-const _HTTP_STATUS_ACQUIRE_CONNECTION_SUCCESS  =  0;
-const _HTTP_STATUS_USER_CANCELLED              = -1;
-const _HTTP_STATUS_RADIO_DISABLED              = -2;
-const _HTTP_STATUS_NO_SIM_CARD                 = -3;
-const _HTTP_STATUS_ACQUIRE_TIMEOUT             = -4;
-const _HTTP_STATUS_FAILED_TO_ROUTE             = -5;
-
-// Non-standard MMS status for internal use.
-const _MMS_ERROR_MESSAGE_DELETED               = -1;
-const _MMS_ERROR_RADIO_DISABLED                = -2;
-const _MMS_ERROR_NO_SIM_CARD                   = -3;
-const _MMS_ERROR_SIM_CARD_CHANGED              = -4;
-const _MMS_ERROR_SHUTDOWN                      = -5;
-const _MMS_ERROR_USER_CANCELLED_NO_REASON      = -6;
-const _MMS_ERROR_SIM_NOT_MATCHED               = -7;
-const _MMS_ERROR_FAILED_TO_ROUTE               = -8;
-
-const CONFIG_SEND_REPORT_NEVER       = 0;
-const CONFIG_SEND_REPORT_DEFAULT_NO  = 1;
-const CONFIG_SEND_REPORT_DEFAULT_YES = 2;
-const CONFIG_SEND_REPORT_ALWAYS      = 3;
-
-const NS_PREFBRANCH_PREFCHANGE_TOPIC_ID = "nsPref:changed";
-
-const TIME_TO_BUFFER_MMS_REQUESTS    = 30000;
-const PREF_TIME_TO_RELEASE_MMS_CONNECTION =
-  Services.prefs.getIntPref("network.gonk.ms-release-mms-connection");
-
-const kPrefRetrievalMode       = 'dom.mms.retrieval_mode';
-const RETRIEVAL_MODE_MANUAL    = "manual";
-const RETRIEVAL_MODE_AUTOMATIC = "automatic";
-const RETRIEVAL_MODE_AUTOMATIC_HOME = "automatic-home";
-const RETRIEVAL_MODE_NEVER     = "never";
-
-//Internal const values.
-const DELIVERY_RECEIVED       = "received";
-const DELIVERY_NOT_DOWNLOADED = "not-downloaded";
-const DELIVERY_SENDING        = "sending";
-const DELIVERY_SENT           = "sent";
-const DELIVERY_ERROR          = "error";
-
-const DELIVERY_STATUS_SUCCESS        = "success";
-const DELIVERY_STATUS_PENDING        = "pending";
-const DELIVERY_STATUS_ERROR          = "error";
-const DELIVERY_STATUS_REJECTED       = "rejected";
-const DELIVERY_STATUS_MANUAL         = "manual";
-const DELIVERY_STATUS_NOT_APPLICABLE = "not-applicable";
-
-const PREF_SEND_RETRY_COUNT =
-  Services.prefs.getIntPref("dom.mms.sendRetryCount");
-
-const PREF_SEND_RETRY_INTERVAL = (function () {
-  let intervals =
-    Services.prefs.getCharPref("dom.mms.sendRetryInterval").split(",");
-  for (let i = 0; i < PREF_SEND_RETRY_COUNT; ++i) {
-    intervals[i] = parseInt(intervals[i], 10);
-    // If one of the intervals isn't valid (e.g., 0 or NaN),
-    // assign a 1-minute interval to it as a default.
-    if (!intervals[i]) {
-      intervals[i] = 60000;
-    }
-  }
-  intervals.length = PREF_SEND_RETRY_COUNT;
-  return intervals;
-})();
-
-const PREF_RETRIEVAL_RETRY_COUNT =
-  Services.prefs.getIntPref("dom.mms.retrievalRetryCount");
-
-const PREF_RETRIEVAL_RETRY_INTERVALS = (function() {
-  let intervals =
-    Services.prefs.getCharPref("dom.mms.retrievalRetryIntervals").split(",");
-  for (let i = 0; i < PREF_RETRIEVAL_RETRY_COUNT; ++i) {
-    intervals[i] = parseInt(intervals[i], 10);
-    // If one of the intervals isn't valid (e.g., 0 or NaN),
-    // assign a 10-minute interval to it as a default.
-    if (!intervals[i]) {
-      intervals[i] = 600000;
-    }
-  }
-  intervals.length = PREF_RETRIEVAL_RETRY_COUNT;
-  return intervals;
-})();
-
-const kPrefRilNumRadioInterfaces = "ril.numRadioInterfaces";
-const kPrefDefaultServiceId = "dom.mms.defaultServiceId";
-
-XPCOMUtils.defineLazyServiceGetter(this, "gpps",
-                                   "@mozilla.org/network/protocol-proxy-service;1",
-                                   "nsIProtocolProxyService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gIccService",
-                                   "@mozilla.org/icc/iccservice;1",
-                                   "nsIIccService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gUUIDGenerator",
-                                   "@mozilla.org/uuid-generator;1",
-                                   "nsIUUIDGenerator");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageDatabaseService",
-                                   "@mozilla.org/mobilemessage/gonkmobilemessagedatabaseservice;1",
-                                   "nsIGonkMobileMessageDatabaseService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageService",
-                                   "@mozilla.org/mobilemessage/mobilemessageservice;1",
-                                   "nsIMobileMessageService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSystemMessenger",
-                                   "@mozilla.org/system-message-internal;1",
-                                   "nsISystemMessagesInternal");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gRil",
-                                   "@mozilla.org/ril;1",
-                                   "nsIRadioInterfaceLayer");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkManager",
-                                   "@mozilla.org/network/manager;1",
-                                   "nsINetworkManager");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileConnectionService",
-                                   "@mozilla.org/mobileconnection/mobileconnectionservice;1",
-                                   "nsIMobileConnectionService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkService",
-                                   "@mozilla.org/network/service;1",
-                                   "nsINetworkService");
-
-XPCOMUtils.defineLazyGetter(this, "MMS", function() {
-  let MMS = {};
-  Cu.import("resource://gre/modules/MmsPduHelper.jsm", MMS);
-  return MMS;
-});
-
-// Internal Utilities
-
-/**
- * Return default service Id for MMS.
- */
-function getDefaultServiceId() {
-  let id = Services.prefs.getIntPref(kPrefDefaultServiceId);
-  let numRil = Services.prefs.getIntPref(kPrefRilNumRadioInterfaces);
-
-  if (id >= numRil || id < 0) {
-    id = 0;
-  }
-
-  return id;
-}
-
-/**
- * Return radio disabled state.
- */
-function isRadioOff(aServiceId) {
-    let connection = gMobileConnectionService.getItemByServiceId(aServiceId);
-    return connection.radioState
-      !== Ci.nsIMobileConnection.MOBILE_RADIO_STATE_ENABLED;
-}
-
-/**
- * Helper Class to control MMS Data Connection.
- */
-function MmsConnection(aServiceId) {
-  this.serviceId = aServiceId;
-  this.radioInterface = gRil.getRadioInterface(aServiceId);
-  this.pendingCallbacks = [];
-  this.hostsToRoute = [];
-  this.connectTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
-  this.disconnectTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
-};
-
-MmsConnection.prototype = {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]),
-
-  /** MMS proxy settings. */
-  mmsc:     "",
-  mmsProxy: "",
-  mmsPort:  -1,
-
-  setApnSetting: function(networkInfo) {
-    this.mmsc = networkInfo.mmsc;
-    this.mmsProxy = networkInfo.mmsProxy;
-    this.mmsPort = networkInfo.mmsPort;
-  },
-
-  get proxyInfo() {
-    if (!this.mmsProxy) {
-      if (DEBUG) debug("getProxyInfo: MMS proxy is not available.");
-      return null;
-    }
-
-    let port = this.mmsPort;
-
-    if (port <= 0) {
-      port = 80;
-      if (DEBUG) debug("getProxyInfo: port is not valid. Set to defult (80).");
-    }
-
-    let proxyInfo =
-      gpps.newProxyInfo("http", this.mmsProxy, port,
-                        Ci.nsIProxyInfo.TRANSPARENT_PROXY_RESOLVES_HOST,
-                        -1, null);
-    if (DEBUG) debug("getProxyInfo: " + JSON.stringify(proxyInfo));
-
-    return proxyInfo;
-  },
-
-  connected: false,
-
-  //A queue to buffer the MMS HTTP requests when the MMS network
-  //is not yet connected. The buffered requests will be cleared
-  //if the MMS network fails to be connected within a timer.
-  pendingCallbacks: null,
-
-  /** MMS network connection reference count. */
-  refCount: 0,
-
-  // cache of hosts to be accessed when this connection is alive.
-  hostsToRoute: null,
-
-  // cache of the networkInfo acquired during this connection.
-  networkInfo: null,
-
-  connectTimer: null,
-
-  disconnectTimer: null,
-
-  /**
-   * Callback when |connectTimer| is timeout or cancelled by shutdown.
-   */
-  flushPendingCallbacks: function(status) {
-    if (DEBUG) debug("flushPendingCallbacks: " + this.pendingCallbacks.length
-                     + " pending callbacks with status: " + status);
-    while (this.pendingCallbacks.length) {
-      let callback = this.pendingCallbacks.shift();
-      let connected = (status == _HTTP_STATUS_ACQUIRE_CONNECTION_SUCCESS);
-      callback(connected, status);
-    }
-  },
-
-  /**
-   * Callback when |disconnectTimer| is timeout or cancelled by shutdown.
-   */
-  onDisconnectTimerTimeout: function() {
-    if (DEBUG) debug("onDisconnectTimerTimeout: deactivate the MMS data call.");
-
-    if (!this.connected) {
-      return;
-    }
-
-    let deactivateMmsDataCall = (aError) => {
-      if (aError) debug("Failed to removeHostRoute: " + aError);
-
-      // Clear cache.
-      this.hostsToRoute = [];
-      this.networkInfo = null;
-
-      this.radioInterface.deactivateDataCallByType(Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_MMS);
-    };
-
-    let promises =
-      this.hostsToRoute.map((aHost) => {
-        return gNetworkManager.removeHostRoute(this.networkInfo, aHost);
-      });
-
-    return Promise.all(promises)
-      .then(() => deactivateMmsDataCall(),
-            (aError) => deactivateMmsDataCall(aError));
-  },
-
-  init: function() {
-    Services.obs.addObserver(this, kNetworkConnStateChangedTopic,
-                             false);
-    Services.obs.addObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
-  },
-
-  /**
-   * Return the roaming status of voice call.
-   *
-   * @return true if voice call is roaming.
-   */
-  isVoiceRoaming: function() {
-    let connection =
-      gMobileConnectionService.getItemByServiceId(this.serviceId);
-    let isRoaming = connection && connection.voice && connection.voice.roaming;
-    if (DEBUG) debug("isVoiceRoaming = " + isRoaming);
-    return isRoaming;
-  },
-
-  /**
-   * Get phone number from iccInfo.
-   *
-   * If the icc card is gsm card, the phone number is in msisdn.
-   * @see nsIGsmIccInfo
-   *
-   * Otherwise, the phone number is in mdn.
-   * @see nsICdmaIccInfo
-   */
-  getPhoneNumber: function() {
-    let number;
-    // Get the proper IccInfo based on the current card type.
-    try {
-      let iccInfo = null;
-      let baseIccInfo = this.getIccInfo();
-      if (baseIccInfo.iccType === 'ruim' || baseIccInfo.iccType === 'csim') {
-        iccInfo = baseIccInfo.QueryInterface(Ci.nsICdmaIccInfo);
-        number = iccInfo.mdn;
-      } else {
-        iccInfo = baseIccInfo.QueryInterface(Ci.nsIGsmIccInfo);
-        number = iccInfo.msisdn;
-      }
-    } catch (e) {
-      if (DEBUG) {
-       debug("Exception - QueryInterface failed on iccinfo for GSM/CDMA info");
-      }
-      return null;
-    }
-
-    return number;
-  },
-
-  /**
-   * A utility function to get IccInfo of the SIM card (if installed).
-   */
-  getIccInfo: function() {
-    let icc = gIccService.getIccByServiceId(this.serviceId);
-    return icc ? icc.iccInfo : null;
-  },
-
-  /**
-   * A utility function to get CardState of the SIM card (if installed).
-   */
-  getCardState: function() {
-    let icc = gIccService.getIccByServiceId(this.serviceId);
-    return icc ? icc.cardState : Ci.nsIIcc.CARD_STATE_UNKNOWN;
-  },
-
-  /**
-  * A utility function to get the ICC ID of the SIM card (if installed).
-  */
-  getIccId: function() {
-    let iccInfo = this.getIccInfo();
-
-    if (!iccInfo) {
-      return null;
-    }
-
-    return iccInfo.iccid;
-  },
-
-  /**
-   * Acquire the MMS network connection.
-   *
-   * @param callback
-   *        Callback function when either the connection setup is done,
-   *        timeout, or failed. Parameters are:
-   *        - A boolean value indicates whether the connection is ready.
-   *        - Acquire connection status: _HTTP_STATUS_ACQUIRE_*.
-   *
-   * @return true if the callback for MMS network connection is done; false
-   *         otherwise.
-   */
-  acquire: function(callback) {
-    this.refCount++;
-    this.connectTimer.cancel();
-    this.disconnectTimer.cancel();
-
-    // If the MMS network is not yet connected, buffer the
-    // MMS request and try to setup the MMS network first.
-    if (!this.connected) {
-      this.pendingCallbacks.push(callback);
-
-      let errorStatus;
-      if (isRadioOff(this.serviceId)) {
-        if (DEBUG) debug("Error! Radio is disabled when sending MMS.");
-        errorStatus = _HTTP_STATUS_RADIO_DISABLED;
-      } else if (this.getCardState() != Ci.nsIIcc.CARD_STATE_READY) {
-        if (DEBUG) debug("Error! SIM card is not ready when sending MMS.");
-        errorStatus = _HTTP_STATUS_NO_SIM_CARD;
-      }
-      if (errorStatus != null) {
-        this.flushPendingCallbacks(errorStatus);
-        return true;
-      }
-
-      // Set a timer to clear the buffered MMS requests if the
-      // MMS network fails to be connected within a time period.
-      this.connectTimer.
-        initWithCallback(() => this.flushPendingCallbacks(_HTTP_STATUS_ACQUIRE_TIMEOUT),
-                         TIME_TO_BUFFER_MMS_REQUESTS,
-                         Ci.nsITimer.TYPE_ONE_SHOT);
-
-      // Bug 1059110: Ensure all the initialization are done before setup data call.
-      if (DEBUG) debug("acquire: buffer the MMS request and setup the MMS data call.");
-      this.radioInterface.setupDataCallByType(Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_MMS);
-
-      return false;
-    }
-
-    callback(true, _HTTP_STATUS_ACQUIRE_CONNECTION_SUCCESS);
-    return true;
-  },
-
-  /**
-   * Release the MMS network connection.
-   */
-  release: function() {
-    this.refCount--;
-    if (this.refCount <= 0) {
-      this.refCount = 0;
-
-      // The waiting is too small, just skip the timer creation.
-      if (PREF_TIME_TO_RELEASE_MMS_CONNECTION < 1000) {
-        this.onDisconnectTimerTimeout();
-        return;
-      }
-
-      // Set a timer to delay the release of MMS network connection,
-      // since the MMS requests often come consecutively in a short time.
-      this.disconnectTimer.
-        initWithCallback(() => this.onDisconnectTimerTimeout(),
-                         PREF_TIME_TO_RELEASE_MMS_CONNECTION,
-                         Ci.nsITimer.TYPE_ONE_SHOT);
-    }
-  },
-
-  /**
-   * Helper to ensure the routing of each transaction.
-   *
-   * @param url
-   *        Optional url for retrieving mms.
-   *
-   * @return a Promise resolved if added or rejected, otherwise.
-   */
-  ensureRouting: function(url) {
-    let host = this.mmsProxy;
-
-    if (!this.mmsProxy) {
-      host = url;
-    }
-
-    try {
-      let uri = Services.io.newURI(host, null, null);
-      host = uri.host;
-    } catch (e) {}
-
-    return gNetworkManager.addHostRoute(this.networkInfo, host)
-      .then(() => {
-        if (this.hostsToRoute.indexOf(host) < 0) {
-          this.hostsToRoute.push(host);
-        }
-      });
-  },
-
-  shutdown: function() {
-    Services.obs.removeObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
-    Services.obs.removeObserver(this, kNetworkConnStateChangedTopic);
-
-    this.connectTimer.cancel();
-    this.flushPendingCallbacks(_HTTP_STATUS_RADIO_DISABLED);
-    this.disconnectTimer.cancel();
-    this.onDisconnectTimerTimeout();
-  },
-
-  // nsIObserver
-
-  observe: function(subject, topic, data) {
-    switch (topic) {
-      case kNetworkConnStateChangedTopic: {
-        // The network info for MMS connection must be nsIRilNetworkInfo.
-        if (!(subject instanceof Ci.nsIRilNetworkInfo)) {
-          return;
-        }
-
-        // Check if the network state change belongs to this service.
-        let networkInfo = subject.QueryInterface(Ci.nsIRilNetworkInfo);
-        if (networkInfo.serviceId != this.serviceId ||
-            networkInfo.type != Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_MMS) {
-          return;
-        }
-
-        let connected =
-          networkInfo.state == Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED;
-
-        // Return if the MMS network state doesn't change, where the network
-        // state change can come from other non-MMS networks.
-        if (connected == this.connected) {
-          return;
-        }
-
-        this.connected = connected;
-        if (!this.connected) {
-          this.hostsToRoute = [];
-          this.networkInfo = null;
-          return;
-        }
-
-        // Set up the MMS APN setting based on the connected MMS network,
-        // which is going to be used for the HTTP requests later.
-        this.setApnSetting(networkInfo);
-
-        // Cache connected network info.
-        this.networkInfo = networkInfo;
-
-        if (DEBUG) debug("Got the MMS network connected! Resend the buffered " +
-                         "MMS requests: number: " + this.pendingCallbacks.length);
-        this.connectTimer.cancel();
-        this.flushPendingCallbacks(_HTTP_STATUS_ACQUIRE_CONNECTION_SUCCESS);
-        break;
-      }
-      case NS_XPCOM_SHUTDOWN_OBSERVER_ID: {
-        this.shutdown();
-      }
-    }
-  }
-};
-
-XPCOMUtils.defineLazyGetter(this, "gMmsConnections", function() {
-  return {
-    _connections: null,
-    getConnByServiceId: function(id) {
-      if (!this._connections) {
-        this._connections = [];
-      }
-
-      let conn = this._connections[id];
-      if (conn) {
-        return conn;
-      }
-
-      conn = this._connections[id] = new MmsConnection(id);
-      conn.init();
-      return conn;
-    },
-    getConnByIccId: function(aIccId) {
-      if (!aIccId) {
-        // If the ICC ID isn't available, it means the MMS has been received
-        // during the previous version that didn't take the DSDS scenario
-        // into consideration. Tentatively, get connection from serviceId(0) by
-        // default is better than nothing. Although it might use the wrong
-        // SIM to download the desired MMS, eventually it would still fail to
-        // download due to the wrong MMSC and proxy settings.
-        return this.getConnByServiceId(0);
-      }
-
-      let numCardAbsent = 0;
-      let numRadioInterfaces = gRil.numRadioInterfaces;
-      for (let clientId = 0; clientId < numRadioInterfaces; clientId++) {
-        let mmsConnection = this.getConnByServiceId(clientId);
-        let iccId = mmsConnection.getIccId();
-        if (iccId === null) {
-          numCardAbsent++;
-          continue;
-        }
-
-        if (iccId === aIccId) {
-          return mmsConnection;
-        }
-      }
-
-      throw ((numCardAbsent === numRadioInterfaces)?
-               _MMS_ERROR_NO_SIM_CARD: _MMS_ERROR_SIM_NOT_MATCHED);
-    },
-  };
-});
-
-/**
- * Implementation of nsIProtocolProxyFilter for MMS Proxy
- */
-function MmsProxyFilter(mmsConnection, url) {
-  this.mmsConnection = mmsConnection;
-  this.uri = Services.io.newURI(url, null, null);
-}
-MmsProxyFilter.prototype = {
-
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolProxyFilter]),
-
-  // nsIProtocolProxyFilter
-
-  applyFilter: function(proxyService, uri, proxyInfo) {
-    if (!this.uri.equals(uri)) {
-      if (DEBUG) debug("applyFilter: content uri = " + JSON.stringify(this.uri) +
-                       " is not matched with uri = " + JSON.stringify(uri) + " .");
-      return proxyInfo;
-    }
-
-    // Fall-through, reutrn the MMS proxy info.
-    let mmsProxyInfo = this.mmsConnection.proxyInfo;
-
-    if (DEBUG) {
-      debug("applyFilter: MMSC/Content Location is matched with: " +
-            JSON.stringify({ uri: JSON.stringify(this.uri),
-                             mmsProxyInfo: mmsProxyInfo }));
-    }
-
-    return mmsProxyInfo ? mmsProxyInfo : proxyInfo;
-  }
-};
-
-XPCOMUtils.defineLazyGetter(this, "gMmsTransactionHelper", function() {
-  let helper = {
-    /**
-     * Send MMS request to MMSC.
-     *
-     * @param mmsConnection
-     *        The MMS connection.
-     * @param method
-     *        "GET" or "POST".
-     * @param url
-     *        Target url string or null to be replaced by mmsc url.
-     * @param istream
-     *        An nsIInputStream instance as data source to be sent or null.
-     * @param callback
-     *        A callback function that takes two arguments: one for http
-     *        status, the other for wrapped PDU data for further parsing.
-     */
-    sendRequest: function(mmsConnection, method, url, istream, callback) {
-      // TODO: bug 810226 - Support GPRS bearer for MMS transmission and reception.
-      let cancellable = {
-        callback: callback,
-
-        isDone: false,
-        isCancelled: false,
-
-        cancel: function() {
-          if (this.isDone) {
-            // It's too late to cancel.
-            return;
-          }
-
-          this.isCancelled = true;
-          if (this.isAcquiringConn) {
-            // We cannot cancel data connection setup here, so we invoke done()
-            // here and handle |cancellable.isDone| in callback function of
-            // |mmsConnection.acquire|.
-            this.done(_HTTP_STATUS_USER_CANCELLED, null);
-          } else if (this.xhr) {
-            // Client has already sent the HTTP request. Try to abort it.
-            this.xhr.abort();
-          }
-        },
-
-        done: function(httpStatus, data) {
-          this.isDone = true;
-          if (!this.callback) {
-            return;
-          }
-
-          if (this.isCancelled) {
-            this.callback(_HTTP_STATUS_USER_CANCELLED, null);
-          } else {
-            this.callback(httpStatus, data);
-          }
-        }
-      };
-
-      cancellable.isAcquiringConn =
-        !mmsConnection.acquire((connected, errorCode) => {
-
-        cancellable.isAcquiringConn = false;
-
-        if (!connected || cancellable.isCancelled) {
-          mmsConnection.release();
-
-          if (!cancellable.isDone) {
-            cancellable.done(cancellable.isCancelled ?
-                             _HTTP_STATUS_USER_CANCELLED : errorCode, null);
-          }
-          return;
-        }
-
-        // MMSC is available after an MMS connection is successfully acquired.
-        if (!url) {
-          url = mmsConnection.mmsc;
-        }
-
-        let startTransaction = netId => {
-          if (DEBUG) debug("sendRequest: register proxy filter to " + url);
-          let proxyFilter = new MmsProxyFilter(mmsConnection, url);
-          gpps.registerFilter(proxyFilter, 0);
-
-          cancellable.xhr =
-            this.sendHttpRequest(mmsConnection, method,
-                                 url, istream, proxyFilter, netId,
-                                 (aHttpStatus, aData) =>
-                                   cancellable.done(aHttpStatus, aData));
-        };
-
-        let onRejected = aReason => {
-          debug('Failed to start a transaction: ' + aReason);
-          mmsConnection.release();
-          cancellable.done(_HTTP_STATUS_FAILED_TO_ROUTE, null);
-        };
-
-        // TODO: |getNetId| will be implemented as a sync call in nsINetworkManager
-        //       once Bug 1141903 is landed.
-        mmsConnection.ensureRouting(url)
-          .then(() => gNetworkService.getNetId(mmsConnection.networkInfo.name))
-          .then((netId) => startTransaction(netId))
-          .catch((aReason) => onRejected(aReason));
-      });
-
-      return cancellable;
-    },
-
-    sendHttpRequest: function(mmsConnection, method, url, istream, proxyFilter,
-                              netId, callback) {
-      let releaseMmsConnectionAndCallback = (httpStatus, data) => {
-        gpps.unregisterFilter(proxyFilter);
-        // Always release the MMS network connection before callback.
-        mmsConnection.release();
-        callback(httpStatus, data);
-      };
-
-      try {
-        let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
-                  .createInstance(Ci.nsIXMLHttpRequest);
-
-        // Basic setups
-        xhr.networkInterfaceId = netId;
-        xhr.open(method, url, true);
-        xhr.responseType = "arraybuffer";
-        if (istream) {
-          xhr.setRequestHeader("Content-Type",
-                               "application/vnd.wap.mms-message");
-          xhr.setRequestHeader("Content-Length", istream.available());
-        }
-
-        // UAProf headers.
-        let uaProfUrl, uaProfTagname = "x-wap-profile";
-        try {
-          uaProfUrl = Services.prefs.getCharPref('wap.UAProf.url');
-          uaProfTagname = Services.prefs.getCharPref('wap.UAProf.tagname');
-        } catch (e) {}
-
-        if (uaProfUrl) {
-          xhr.setRequestHeader(uaProfTagname, uaProfUrl);
-        }
-
-        // Setup event listeners
-        xhr.onreadystatechange = () => {
-          if (xhr.readyState != Ci.nsIXMLHttpRequest.DONE) {
-            return;
-          }
-          let data = null;
-          switch (xhr.status) {
-            case HTTP_STATUS_OK: {
-              if (DEBUG) debug("xhr success, response headers: "
-                               + xhr.getAllResponseHeaders());
-              let array = new Uint8Array(xhr.response);
-              if (false) {
-                for (let begin = 0; begin < array.length; begin += 20) {
-                  let partial = array.subarray(begin, begin + 20);
-                  if (DEBUG) debug("res: " + JSON.stringify(partial));
-                }
-              }
-
-              data = {array: array, offset: 0};
-              break;
-            }
-
-            default: {
-              if (DEBUG) debug("xhr done, but status = " + xhr.status +
-                               ", statusText = " + xhr.statusText);
-              break;
-            }
-          }
-          releaseMmsConnectionAndCallback(xhr.status, data);
-        };
-        // Send request
-        xhr.send(istream);
-        return xhr;
-      } catch (e) {
-        if (DEBUG) debug("xhr error, can't send: " + e.message);
-        releaseMmsConnectionAndCallback(0, null);
-        return null;
-      }
-    },
-
-    /**
-     * Count number of recipients(to, cc, bcc fields).
-     *
-     * @param recipients
-     *        The recipients in MMS message object.
-     * @return the number of recipients
-     * @see OMA-TS-MMS_CONF-V1_3-20110511-C section 10.2.5
-     */
-    countRecipients: function(recipients) {
-      if (recipients && recipients.address) {
-        return 1;
-      }
-      let totalRecipients = 0;
-      if (!Array.isArray(recipients)) {
-        return 0;
-      }
-      totalRecipients += recipients.length;
-      for (let ix = 0; ix < recipients.length; ++ix) {
-        if (recipients[ix].address.length > MMS.MMS_MAX_LENGTH_RECIPIENT) {
-          throw new Error("MMS_MAX_LENGTH_RECIPIENT error");
-        }
-        if (recipients[ix].type === "email") {
-          let found = recipients[ix].address.indexOf("<");
-          let lenMailbox = recipients[ix].address.length - found;
-          if(lenMailbox > MMS.MMS_MAX_LENGTH_MAILBOX_PORTION) {
-            throw new Error("MMS_MAX_LENGTH_MAILBOX_PORTION error");
-          }
-        }
-      }
-      return totalRecipients;
-    },
-
-    /**
-     * Check maximum values of MMS parameters.
-     *
-     * @param msg
-     *        The MMS message object.
-     * @return true if the lengths are less than the maximum values of MMS
-     *         parameters.
-     * @see OMA-TS-MMS_CONF-V1_3-20110511-C section 10.2.5
-     */
-    checkMaxValuesParameters: function(msg) {
-      let subject = msg.headers["subject"];
-      if (subject && subject.length > MMS.MMS_MAX_LENGTH_SUBJECT) {
-        return false;
-      }
-
-      let totalRecipients = 0;
-      try {
-        totalRecipients += this.countRecipients(msg.headers["to"]);
-        totalRecipients += this.countRecipients(msg.headers["cc"]);
-        totalRecipients += this.countRecipients(msg.headers["bcc"]);
-      } catch (ex) {
-        if (DEBUG) debug("Exception caught : " + ex);
-        return false;
-      }
-
-      if (totalRecipients < 1 ||
-          totalRecipients > MMS.MMS_MAX_TOTAL_RECIPIENTS) {
-        return false;
-      }
-
-      if (!Array.isArray(msg.parts)) {
-        return true;
-      }
-      for (let i = 0; i < msg.parts.length; i++) {
-        if (msg.parts[i].headers["content-type"] &&
-          msg.parts[i].headers["content-type"].params) {
-          let name = msg.parts[i].headers["content-type"].params["name"];
-          if (name && name.length > MMS.MMS_MAX_LENGTH_NAME_CONTENT_TYPE) {
-            return false;
-          }
-        }
-      }
-      return true;
-    },
-
-    translateHttpStatusToMmsStatus: function(httpStatus, cancelledReason,
-                                             defaultStatus) {
-      switch(httpStatus) {
-        case _HTTP_STATUS_USER_CANCELLED:
-          return cancelledReason;
-        case _HTTP_STATUS_RADIO_DISABLED:
-          return _MMS_ERROR_RADIO_DISABLED;
-        case _HTTP_STATUS_NO_SIM_CARD:
-          return _MMS_ERROR_NO_SIM_CARD;
-        case _HTTP_STATUS_FAILED_TO_ROUTE:
-          return _MMS_ERROR_FAILED_TO_ROUTE;
-        case HTTP_STATUS_OK:
-          return MMS.MMS_PDU_ERROR_OK;
-        default:
-          return defaultStatus;
-      }
-    }
-  };
-
-  return helper;
-});
-
-/**
- * Send M-NotifyResp.ind back to MMSC.
- *
- * @param mmsConnection
- *        The MMS connection.
- * @param transactionId
- *        X-Mms-Transaction-ID of the message.
- * @param status
- *        X-Mms-Status of the response.
- * @param reportAllowed
- *        X-Mms-Report-Allowed of the response.
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A section 6.2
- */
-function NotifyResponseTransaction(mmsConnection, transactionId, status,
-                                   reportAllowed) {
-  this.mmsConnection = mmsConnection;
-  let headers = {};
-
-  // Mandatory fields
-  headers["x-mms-message-type"] = MMS.MMS_PDU_TYPE_NOTIFYRESP_IND;
-  headers["x-mms-transaction-id"] = transactionId;
-  headers["x-mms-mms-version"] = MMS.MMS_VERSION;
-  headers["x-mms-status"] = status;
-  // Optional fields
-  headers["x-mms-report-allowed"] = reportAllowed;
-
-  this.istream = MMS.PduHelper.compose(null, {headers: headers});
-}
-NotifyResponseTransaction.prototype = {
-  /**
-   * @param callback [optional]
-   *        A callback function that takes one argument -- the http status.
-   */
-  run: function(callback) {
-    let requestCallback;
-    if (callback) {
-      requestCallback = (httpStatus, data) => {
-        // `The MMS Client SHOULD ignore the associated HTTP POST response
-        // from the MMS Proxy-Relay.` ~ OMA-TS-MMS_CTR-V1_3-20110913-A
-        // section 8.2.2 "Notification".
-        callback(httpStatus);
-      };
-    }
-    gMmsTransactionHelper.sendRequest(this.mmsConnection,
-                                      "POST",
-                                      null,
-                                      this.istream,
-                                      requestCallback);
-  }
-};
-
-/**
- * CancellableTransaction - base class inherited by [Send|Retrieve]Transaction.
- * We can call |cancelRunning(reason)| to cancel the on-going transaction.
- * @param cancellableId
- *        An ID used to keep track of if an message is deleted from DB.
- * @param serviceId
- *        An ID used to keep track of if the primary SIM service is changed.
- */
-function CancellableTransaction(cancellableId, serviceId) {
-  this.cancellableId = cancellableId;
-  this.serviceId = serviceId;
-  this.isCancelled = false;
-}
-CancellableTransaction.prototype = {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
-                                         Ci.nsIMobileConnectionListener]),
-
-  // The timer for retrying sending or retrieving process.
-  timer: null,
-
-  // Keep a reference to the callback when calling
-  // |[Send|Retrieve]Transaction.run(callback)|.
-  runCallback: null,
-
-  isObserversAdded: false,
-
-  cancelledReason: _MMS_ERROR_USER_CANCELLED_NO_REASON,
-
-  registerRunCallback: function(callback) {
-    if (!this.isObserversAdded) {
-      Services.obs.addObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
-      Services.obs.addObserver(this, kSmsDeletedObserverTopic, false);
-      Services.prefs.addObserver(kPrefDefaultServiceId, this, false);
-      gMobileConnectionService
-        .getItemByServiceId(this.serviceId).registerListener(this);
-      this.isObserversAdded = true;
-    }
-
-    this.runCallback = callback;
-    this.isCancelled = false;
-  },
-
-  removeObservers: function() {
-    if (this.isObserversAdded) {
-      Services.obs.removeObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
-      Services.obs.removeObserver(this, kSmsDeletedObserverTopic);
-      Services.prefs.removeObserver(kPrefDefaultServiceId, this);
-      gMobileConnectionService
-        .getItemByServiceId(this.serviceId).unregisterListener(this);
-      this.isObserversAdded = false;
-    }
-  },
-
-  runCallbackIfValid: function(mmsStatus, msg) {
-    this.removeObservers();
-
-    if (this.runCallback) {
-      this.runCallback(mmsStatus, msg);
-      this.runCallback = null;
-    }
-  },
-
-  // Keep a reference to the cancellable when calling
-  // |gMmsTransactionHelper.sendRequest(...)|.
-  cancellable: null,
-
-  cancelRunning: function(reason) {
-    this.isCancelled = true;
-    this.cancelledReason = reason;
-
-    if (this.timer) {
-      // The sending or retrieving process is waiting for the next retry.
-      // What we only need to do is to cancel the timer.
-      this.timer.cancel();
-      this.timer = null;
-      this.runCallbackIfValid(reason, null);
-      return;
-    }
-
-    if (this.cancellable) {
-      // The sending or retrieving process is still running. We attempt to
-      // abort the HTTP request.
-      this.cancellable.cancel();
-      this.cancellable = null;
-    }
-  },
-
-  // nsIObserver
-
-  observe: function(subject, topic, data) {
-    switch (topic) {
-      case NS_XPCOM_SHUTDOWN_OBSERVER_ID: {
-        this.cancelRunning(_MMS_ERROR_SHUTDOWN);
-        break;
-      }
-      case kSmsDeletedObserverTopic: {
-        let deletedInfo = subject.QueryInterface(Ci.nsIDeletedMessageInfo);
-        if (deletedInfo && deletedInfo.deletedMessageIds &&
-            deletedInfo.deletedMessageIds.indexOf(this.cancellableId) >= 0) {
-          this.cancelRunning(_MMS_ERROR_MESSAGE_DELETED);
-        }
-        break;
-      }
-      case NS_PREFBRANCH_PREFCHANGE_TOPIC_ID: {
-        if (data === kPrefDefaultServiceId &&
-                   this.serviceId != getDefaultServiceId()) {
-          this.cancelRunning(_MMS_ERROR_SIM_CARD_CHANGED);
-        }
-        break;
-      }
-    }
-  },
-
-  // nsIMobileConnectionListener
-
-  notifyVoiceChanged: function() {},
-  notifyDataChanged: function() {},
-  notifyDataError: function(message) {},
-  notifyCFStateChanged: function(action, reason, number, timeSeconds, serviceClass) {},
-  notifyEmergencyCbModeChanged: function(active, timeoutMs) {},
-  notifyOtaStatusChanged: function(status) {},
-
-  notifyRadioStateChanged: function() {
-    if (isRadioOff(this.serviceId)) {
-      this.cancelRunning(_MMS_ERROR_RADIO_DISABLED);
-    }
-  },
-
-  notifyClirModeChanged: function(mode) {},
-  notifyLastKnownNetworkChanged: function() {},
-  notifyLastKnownHomeNetworkChanged: function() {},
-  notifyNetworkSelectionModeChanged: function() {},
-  notifyDeviceIdentitiesChanged: function() {}
-};
-
-/**
- * Class for retrieving message from MMSC, which inherits CancellableTransaction.
- *
- * @param contentLocation
- *        X-Mms-Content-Location of the message.
- */
-function RetrieveTransaction(mmsConnection, cancellableId, contentLocation) {
-  this.mmsConnection = mmsConnection;
-
-  // Call |CancellableTransaction| constructor.
-  CancellableTransaction.call(this, cancellableId, mmsConnection.serviceId);
-
-  this.contentLocation = contentLocation;
-}
-RetrieveTransaction.prototype = Object.create(CancellableTransaction.prototype, {
-  /**
-   * @param callback [optional]
-   *        A callback function that takes two arguments: one for X-Mms-Status,
-   *        the other for the parsed M-Retrieve.conf message.
-   */
-  run: {
-    value: function(callback) {
-      this.registerRunCallback(callback);
-
-      this.retryCount = 0;
-      let retryCallback = (mmsStatus, msg) => {
-        if (MMS.MMS_PDU_STATUS_DEFERRED == mmsStatus &&
-            this.retryCount < PREF_RETRIEVAL_RETRY_COUNT) {
-          let time = PREF_RETRIEVAL_RETRY_INTERVALS[this.retryCount];
-          if (DEBUG) debug("Fail to retrieve. Will retry after: " + time);
-
-          if (this.timer == null) {
-            this.timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
-          }
-
-          this.timer.initWithCallback(() => this.retrieve(retryCallback),
-                                      time, Ci.nsITimer.TYPE_ONE_SHOT);
-          this.retryCount++;
-          return;
-        }
-        this.runCallbackIfValid(mmsStatus, msg);
-      };
-
-      this.retrieve(retryCallback);
-    },
-    enumerable: true,
-    configurable: true,
-    writable: true
-  },
-
-  /**
-   * @param callback
-   *        A callback function that takes two arguments: one for X-Mms-Status,
-   *        the other for the parsed M-Retrieve.conf message.
-   */
-  retrieve: {
-    value: function(callback) {
-      this.timer = null;
-
-      this.cancellable =
-        gMmsTransactionHelper.sendRequest(this.mmsConnection,
-                                          "GET", this.contentLocation, null,
-                                          (httpStatus, data) => {
-        let mmsStatus = gMmsTransactionHelper
-                        .translateHttpStatusToMmsStatus(httpStatus,
-                                                        this.cancelledReason,
-                                                        MMS.MMS_PDU_STATUS_DEFERRED);
-        if (mmsStatus != MMS.MMS_PDU_ERROR_OK) {
-           callback(mmsStatus, null);
-           return;
-        }
-        if (!data) {
-          callback(MMS.MMS_PDU_STATUS_DEFERRED, null);
-          return;
-        }
-
-        let retrieved = MMS.PduHelper.parse(data, null);
-        if (!retrieved || (retrieved.type != MMS.MMS_PDU_TYPE_RETRIEVE_CONF)) {
-          callback(MMS.MMS_PDU_STATUS_UNRECOGNISED, null);
-          return;
-        }
-
-        // Fix default header field values.
-        if (retrieved.headers["x-mms-delivery-report"] == null) {
-          retrieved.headers["x-mms-delivery-report"] = false;
-        }
-
-        let retrieveStatus = retrieved.headers["x-mms-retrieve-status"];
-        if ((retrieveStatus != null) &&
-            (retrieveStatus != MMS.MMS_PDU_ERROR_OK)) {
-          callback(MMS.translatePduErrorToStatus(retrieveStatus), retrieved);
-          return;
-        }
-
-        callback(MMS.MMS_PDU_STATUS_RETRIEVED, retrieved);
-      });
-    },
-    enumerable: true,
-    configurable: true,
-    writable: true
-  }
-});
-
-/**
- * SendTransaction.
- *   Class for sending M-Send.req to MMSC, which inherits CancellableTransaction.
- *   @throws Error("Check max values parameters fail.")
- */
-function SendTransaction(mmsConnection, cancellableId, msg, requestDeliveryReport) {
-  this.mmsConnection = mmsConnection;
-
-  // Call |CancellableTransaction| constructor.
-  CancellableTransaction.call(this, cancellableId, mmsConnection.serviceId);
-
-  msg.headers["x-mms-message-type"] = MMS.MMS_PDU_TYPE_SEND_REQ;
-  if (!msg.headers["x-mms-transaction-id"]) {
-    // Create an unique transaction id
-    let tid = gUUIDGenerator.generateUUID().toString();
-    msg.headers["x-mms-transaction-id"] = tid;
-  }
-  msg.headers["x-mms-mms-version"] = MMS.MMS_VERSION;
-
-  // Insert Phone number if available.
-  // Otherwise, Let MMS Proxy Relay insert from address automatically for us.
-  let phoneNumber = mmsConnection.getPhoneNumber();
-  let from = (phoneNumber) ? { address: phoneNumber, type: "PLMN" } : null;
-  msg.headers["from"] = from;
-
-  msg.headers["date"] = new Date();
-  msg.headers["x-mms-message-class"] = "personal";
-  msg.headers["x-mms-expiry"] = 7 * 24 * 60 * 60;
-  msg.headers["x-mms-priority"] = 129;
-  msg.headers["x-mms-delivery-report"] = requestDeliveryReport;
-
-  if (!gMmsTransactionHelper.checkMaxValuesParameters(msg)) {
-    //We should notify end user that the header format is wrong.
-    if (DEBUG) debug("Check max values parameters fail.");
-    throw new Error("Check max values parameters fail.");
-  }
-
-  if (msg.parts) {
-    let contentType = {
-      params: {
-        // `The type parameter must be specified and its value is the MIME
-        // media type of the "root" body part.` ~ RFC 2387 clause 3.1
-        type: msg.parts[0].headers["content-type"].media,
-      },
-    };
-
-    // `The Content-Type in M-Send.req and M-Retrieve.conf SHALL be
-    // application/vnd.wap.multipart.mixed when there is no presentation, and
-    // application/vnd.wap.multipart.related SHALL be used when there is SMIL
-    // presentation available.` ~ OMA-TS-MMS_CONF-V1_3-20110913-A clause 10.2.1
-    if (contentType.params.type === "application/smil") {
-      contentType.media = "application/vnd.wap.multipart.related";
-
-      // `The start parameter, if given, is the content-ID of the compound
-      // object's "root".` ~ RFC 2387 clause 3.2
-      contentType.params.start = msg.parts[0].headers["content-id"];
-    } else {
-      contentType.media = "application/vnd.wap.multipart.mixed";
-    }
-
-    // Assign to Content-Type
-    msg.headers["content-type"] = contentType;
-  }
-
-  if (DEBUG) debug("msg: " + JSON.stringify(msg));
-
-  this.msg = msg;
-}
-SendTransaction.prototype = Object.create(CancellableTransaction.prototype, {
-  istreamComposed: {
-    value: false,
-    enumerable: true,
-    configurable: true,
-    writable: true
-  },
-
-  /**
-   * @param parts
-   *        'parts' property of a parsed MMS message.
-   * @param callback [optional]
-   *        A callback function that takes zero argument.
-   */
-  loadBlobs: {
-    value: function(parts, callback) {
-      let callbackIfValid = () => {
-        if (DEBUG) debug("All parts loaded: " + JSON.stringify(parts));
-        if (callback) {
-          callback();
-        }
-      };
-
-      if (!parts || !parts.length) {
-        callbackIfValid();
-        return;
-      }
-
-      let numPartsToLoad = parts.length;
-      parts.forEach((aPart) => {
-        if (!(aPart.content instanceof Blob)) {
-          numPartsToLoad--;
-          if (!numPartsToLoad) {
-            callbackIfValid();
-          }
-          return;
-        }
-
-        let fileReader = new FileReader();
-        fileReader.addEventListener("loadend", (aEvent) => {
-          let arrayBuffer = aEvent.target.result;
-          aPart.content = new Uint8Array(arrayBuffer);
-          numPartsToLoad--;
-          if (!numPartsToLoad) {
-            callbackIfValid();
-          }
-        });
-        fileReader.readAsArrayBuffer(aPart.content);
-      });
-    },
-    enumerable: true,
-    configurable: true,
-    writable: true
-  },
-
-  /**
-   * @param callback [optional]
-   *        A callback function that takes two arguments: one for
-   *        X-Mms-Response-Status, the other for the parsed M-Send.conf message.
-   */
-  run: {
-    value: function(callback) {
-      this.registerRunCallback(callback);
-
-      if (!this.istreamComposed) {
-        this.loadBlobs(this.msg.parts, () => {
-          this.istream = MMS.PduHelper.compose(null, this.msg);
-          this.istreamSize = this.istream.available();
-          this.istreamComposed = true;
-          if (this.isCancelled) {
-            this.runCallbackIfValid(_MMS_ERROR_MESSAGE_DELETED, null);
-          } else {
-            this.run(callback);
-          }
-        });
-        return;
-      }
-
-      if (!this.istream) {
-        this.runCallbackIfValid(MMS.MMS_PDU_ERROR_PERMANENT_FAILURE, null);
-        return;
-      }
-
-      this.retryCount = 0;
-      let retryCallback = (mmsStatus, msg) => {
-        if ((MMS.MMS_PDU_ERROR_TRANSIENT_FAILURE == mmsStatus ||
-              MMS.MMS_PDU_ERROR_PERMANENT_FAILURE == mmsStatus) &&
-            this.retryCount < PREF_SEND_RETRY_COUNT) {
-          if (DEBUG) {
-            debug("Fail to send. Will retry after: " + PREF_SEND_RETRY_INTERVAL[this.retryCount]);
-          }
-
-          if (this.timer == null) {
-            this.timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
-          }
-
-          // the input stream may be read in the previous failure request so
-          // we have to re-compose it.
-          if (this.istreamSize == null ||
-              this.istreamSize != this.istream.available()) {
-            this.istream = MMS.PduHelper.compose(null, this.msg);
-          }
-
-          this.timer.initWithCallback(() => this.send(retryCallback),
-                                      PREF_SEND_RETRY_INTERVAL[this.retryCount],
-                                      Ci.nsITimer.TYPE_ONE_SHOT);
-          this.retryCount++;
-          return;
-        }
-
-        this.runCallbackIfValid(mmsStatus, msg);
-      };
-
-      // This is the entry point to start sending.
-      this.send(retryCallback);
-    },
-    enumerable: true,
-    configurable: true,
-    writable: true
-  },
-
-  /**
-   * @param callback
-   *        A callback function that takes two arguments: one for
-   *        X-Mms-Response-Status, the other for the parsed M-Send.conf message.
-   */
-  send: {
-    value: function(callback) {
-      this.timer = null;
-
-      this.cancellable =
-        gMmsTransactionHelper.sendRequest(this.mmsConnection,
-                                          "POST",
-                                          null,
-                                          this.istream,
-                                          (httpStatus, data) => {
-        let mmsStatus = gMmsTransactionHelper.
-                          translateHttpStatusToMmsStatus(
-                            httpStatus,
-                            this.cancelledReason,
-                            MMS.MMS_PDU_ERROR_TRANSIENT_FAILURE);
-        if (httpStatus != HTTP_STATUS_OK) {
-          callback(mmsStatus, null);
-          return;
-        }
-
-        if (!data) {
-          callback(MMS.MMS_PDU_ERROR_PERMANENT_FAILURE, null);
-          return;
-        }
-
-        let response = MMS.PduHelper.parse(data, null);
-        if (DEBUG) {
-          debug("Parsed M-Send.conf: " + JSON.stringify(response));
-        }
-        if (!response || (response.type != MMS.MMS_PDU_TYPE_SEND_CONF)) {
-          callback(MMS.MMS_PDU_RESPONSE_ERROR_UNSUPPORTED_MESSAGE, null);
-          return;
-        }
-
-        let responseStatus = response.headers["x-mms-response-status"];
-        callback(responseStatus, response);
-      });
-    },
-    enumerable: true,
-    configurable: true,
-    writable: true
-  }
-});
-
-/**
- * Send M-acknowledge.ind back to MMSC.
- *
- * @param mmsConnection
- *        The MMS connection.
- * @param transactionId
- *        X-Mms-Transaction-ID of the message.
- * @param reportAllowed
- *        X-Mms-Report-Allowed of the response.
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A section 6.4
- */
-function AcknowledgeTransaction(mmsConnection, transactionId, reportAllowed) {
-  this.mmsConnection = mmsConnection;
-  let headers = {};
-
-  // Mandatory fields
-  headers["x-mms-message-type"] = MMS.MMS_PDU_TYPE_ACKNOWLEDGE_IND;
-  headers["x-mms-transaction-id"] = transactionId;
-  headers["x-mms-mms-version"] = MMS.MMS_VERSION;
-  // Optional fields
-  headers["x-mms-report-allowed"] = reportAllowed;
-
-  this.istream = MMS.PduHelper.compose(null, {headers: headers});
-}
-AcknowledgeTransaction.prototype = {
-  /**
-   * @param callback [optional]
-   *        A callback function that takes one argument -- the http status.
-   */
-  run: function(callback) {
-    let requestCallback;
-    if (callback) {
-      requestCallback = (httpStatus, data) => {
-        // `The MMS Client SHOULD ignore the associated HTTP POST response
-        // from the MMS Proxy-Relay.` ~ OMA-TS-MMS_CTR-V1_3-20110913-A
-        // section 8.2.3 "Retrieving an MM".
-        callback(httpStatus);
-      };
-    }
-    gMmsTransactionHelper.sendRequest(this.mmsConnection,
-                                      "POST",
-                                      null,
-                                      this.istream,
-                                      requestCallback);
-  }
-};
-
-/**
- * Return M-Read-Rec.ind back to MMSC
- *
- * @param messageID
- *        Message-ID of the message.
- * @param toAddress
- *        The address of the recipient of the Read Report, i.e. the originator
- *        of the original multimedia message.
- *
- * @see OMA-TS-MMS_ENC-V1_3-20110913-A section 6.7.2
- */
-function ReadRecTransaction(mmsConnection, messageID, toAddress) {
-  this.mmsConnection = mmsConnection;
-  let headers = {};
-
-  // Mandatory fields
-  headers["x-mms-message-type"] = MMS.MMS_PDU_TYPE_READ_REC_IND;
-  headers["x-mms-mms-version"] = MMS.MMS_VERSION;
-  headers["message-id"] = messageID;
-  let type = MMS.Address.resolveType(toAddress);
-  let to = {address: toAddress,
-            type: type}
-  headers["to"] = to;
-  // Insert Phone number if available.
-  // Otherwise, Let MMS Proxy Relay insert from address automatically for us.
-  let phoneNumber = mmsConnection.getPhoneNumber();
-  let from = (phoneNumber) ? { address: phoneNumber, type: "PLMN" } : null;
-  headers["from"] = from;
-  headers["x-mms-read-status"] = MMS.MMS_PDU_READ_STATUS_READ;
-
-  this.istream = MMS.PduHelper.compose(null, {headers: headers});
-  if (!this.istream) {
-    throw Cr.NS_ERROR_FAILURE;
-  }
-}
-ReadRecTransaction.prototype = {
-  run: function() {
-    gMmsTransactionHelper.sendRequest(this.mmsConnection,
-                                      "POST",
-                                      null,
-                                      this.istream,
-                                      null);
-  }
-};
-
-/**
- * MmsService
- */
-function MmsService() {
-  this._updateDebugFlag();
-  if (DEBUG) {
-    let macro = (MMS.MMS_VERSION >> 4) & 0x0f;
-    let minor = MMS.MMS_VERSION & 0x0f;
-    debug("Running protocol version: " + macro + "." + minor);
-  }
-
-  Services.prefs.addObserver(kPrefDefaultServiceId, this, false);
-  Services.prefs.addObserver(kPrefMmsDebuggingEnabled, this, false);
-  this.mmsDefaultServiceId = getDefaultServiceId();
-
-  // TODO: bug 810084 - support application identifier
-}
-MmsService.prototype = {
-
-  classID:   GONK_MMSSERVICE_CID,
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIMmsService,
-                                         Ci.nsIWapPushApplication,
-                                         Ci.nsIObserver]),
-  /*
-   * Whether or not should we enable X-Mms-Report-Allowed in M-NotifyResp.ind
-   * and M-Acknowledge.ind PDU.
-   */
-  confSendDeliveryReport: CONFIG_SEND_REPORT_DEFAULT_YES,
-
-  _updateDebugFlag: function() {
-    try {
-      DEBUG = Services.prefs.getBoolPref(kPrefMmsDebuggingEnabled);
-    } catch (e) {}
-  },
-
-  /**
-   * Calculate Whether or not should we enable X-Mms-Report-Allowed.
-   *
-   * @param config
-   *        Current configure value.
-   * @param wish
-   *        Sender wish. Could be undefined, false, or true.
-   */
-  getReportAllowed: function(config, wish) {
-    if ((config == CONFIG_SEND_REPORT_DEFAULT_NO)
-        || (config == CONFIG_SEND_REPORT_DEFAULT_YES)) {
-      if (wish != null) {
-        config += (wish ? 1 : -1);
-      }
-    }
-    return config >= CONFIG_SEND_REPORT_DEFAULT_YES;
-  },
-
-  /**
-   * Convert intermediate message to indexedDB savable object.
-   *
-   * @param mmsConnection
-   *        The MMS connection.
-   * @param retrievalMode
-   *        Retrieval mode for MMS receiving setting.
-   * @param intermediate
-   *        Intermediate MMS message parsed from PDU.
-   */
-  convertIntermediateToSavable: function(mmsConnection, intermediate,
-                                         retrievalMode) {
-    intermediate.type = "mms";
-    intermediate.delivery = DELIVERY_NOT_DOWNLOADED;
-
-    let deliveryStatus;
-    switch (retrievalMode) {
-      case RETRIEVAL_MODE_MANUAL:
-        deliveryStatus = DELIVERY_STATUS_MANUAL;
-        break;
-      case RETRIEVAL_MODE_NEVER:
-        deliveryStatus = DELIVERY_STATUS_REJECTED;
-        break;
-      case RETRIEVAL_MODE_AUTOMATIC:
-        deliveryStatus = DELIVERY_STATUS_PENDING;
-        break;
-      case RETRIEVAL_MODE_AUTOMATIC_HOME:
-        if (mmsConnection.isVoiceRoaming()) {
-          deliveryStatus = DELIVERY_STATUS_MANUAL;
-        } else {
-          deliveryStatus = DELIVERY_STATUS_PENDING;
-        }
-        break;
-      default:
-        deliveryStatus = DELIVERY_STATUS_NOT_APPLICABLE;
-        break;
-    }
-    // |intermediate.deliveryStatus| will be deleted after being stored in db.
-    intermediate.deliveryStatus = deliveryStatus;
-
-    intermediate.timestamp = Date.now();
-    intermediate.receivers = [];
-    intermediate.phoneNumber = mmsConnection.getPhoneNumber();
-    intermediate.iccId = mmsConnection.getIccId();
-    return intermediate;
-  },
-
-  /**
-   * Merge the retrieval confirmation into the savable message.
-   *
-   * @param mmsConnection
-   *        The MMS connection.
-   * @param intermediate
-   *        Intermediate MMS message parsed from PDU, which carries
-   *        the retrieval confirmation.
-   * @param savable
-   *        The indexedDB savable MMS message, which is going to be
-   *        merged with the extra retrieval confirmation.
-   */
-  mergeRetrievalConfirmation: function(mmsConnection, intermediate, savable) {
-    // Prepare timestamp/sentTimestamp.
-    savable.timestamp = Date.now();
-    savable.sentTimestamp = intermediate.headers["date"].getTime();
-
-    savable.receivers = [];
-    // We don't have Bcc in recevied MMS message.
-    for (let type of ["cc", "to"]) {
-      if (intermediate.headers[type]) {
-        if (intermediate.headers[type] instanceof Array) {
-          for (let index in intermediate.headers[type]) {
-            savable.receivers.push(intermediate.headers[type][index].address);
-          }
-        } else {
-          savable.receivers.push(intermediate.headers[type].address);
-        }
-      }
-    }
-
-    savable.delivery = DELIVERY_RECEIVED;
-    // |savable.deliveryStatus| will be deleted after being stored in db.
-    savable.deliveryStatus = DELIVERY_STATUS_SUCCESS;
-    for (let field in intermediate.headers) {
-      savable.headers[field] = intermediate.headers[field];
-    }
-    if (intermediate.parts) {
-      savable.parts = intermediate.parts;
-    }
-    if (intermediate.content) {
-      savable.content = intermediate.content;
-    }
-    return savable;
-  },
-
-  /**
-   * @param aMmsConnection
-   *        The MMS connection.
-   * @param aContentLocation
-   *        X-Mms-Content-Location of the message.
-   * @param aCallback [optional]
-   *        A callback function that takes two arguments: one for X-Mms-Status,
-   *        the other parsed MMS message.
-   * @param aDomMessage
-   *        The nsIMmsMessage object.
-   */
-  retrieveMessage: function(aMmsConnection, aContentLocation, aCallback,
-                            aDomMessage) {
-    // Notifying observers an MMS message is retrieving.
-    Services.obs.notifyObservers(aDomMessage, kSmsRetrievingObserverTopic, null);
-
-    let transaction = new RetrieveTransaction(aMmsConnection,
-                                              aDomMessage.id,
-                                              aContentLocation);
-    transaction.run(aCallback);
-  },
-
-  /**
-   * A helper to broadcast the system message to launch registered apps
-   * like Costcontrol, Notification and Message app... etc.
-   *
-   * @param aName
-   *        The system message name.
-   * @param aDomMessage
-   *        The nsIMmsMessage object.
-   */
-  broadcastMmsSystemMessage: function(aName, aDomMessage) {
-    if (DEBUG) debug("Broadcasting the MMS system message: " + aName);
-
-    // Sadly we cannot directly broadcast the aDomMessage object
-    // because the system message mechamism will rewrap the object
-    // based on the content window, which needs to know the properties.
-    try {
-      gSystemMessenger.broadcastMessage(aName, {
-        iccId:               aDomMessage.iccId,
-        type:                aDomMessage.type,
-        id:                  aDomMessage.id,
-        threadId:            aDomMessage.threadId,
-        delivery:            aDomMessage.delivery,
-        deliveryInfo:        aDomMessage.deliveryInfo,
-        sender:              aDomMessage.sender,
-        receivers:           aDomMessage.receivers,
-        timestamp:           aDomMessage.timestamp,
-        sentTimestamp:       aDomMessage.sentTimestamp,
-        read:                aDomMessage.read,
-        subject:             aDomMessage.subject,
-        smil:                aDomMessage.smil,
-        attachments:         aDomMessage.attachments,
-        expiryDate:          aDomMessage.expiryDate,
-        readReportRequested: aDomMessage.readReportRequested
-      });
-    } catch (e) {
-      if (DEBUG) {
-        debug("Failed to _broadcastSmsSystemMessage: " + e);
-      }
-    }
-  },
-
-  /**
-   * A helper function to broadcast system message and notify observers that
-   * an MMS is sent.
-   *
-   * @params aDomMessage
-   *         The nsIMmsMessage object.
-   */
-  broadcastSentMessageEvent: function(aDomMessage) {
-    // Broadcasting a 'sms-sent' system message to open apps.
-    this.broadcastMmsSystemMessage(kSmsSentObserverTopic, aDomMessage);
-
-    // Notifying observers an MMS message is sent.
-    Services.obs.notifyObservers(aDomMessage, kSmsSentObserverTopic, null);
-  },
-
-  /**
-   * A helper function to broadcast system message and notify observers that
-   * an MMS is failed to send.
-   *
-   * @params aDomMessage
-   *         The nsIMmsMessage object.
-   */
-  broadcastSentFailureMessageEvent: function(aDomMessage) {
-    // Broadcasting a 'sms-sent' system message to open apps.
-    this.broadcastMmsSystemMessage(kSmsFailedObserverTopic, aDomMessage);
-
-    // Notifying observers an MMS message is sent.
-    Services.obs.notifyObservers(aDomMessage, kSmsFailedObserverTopic, null);
-  },
-
-  /**
-   * A helper function to broadcast system message and notify observers that
-   * an MMS is received.
-   *
-   * @params aDomMessage
-   *         The nsIMmsMessage object.
-   */
-  broadcastReceivedMessageEvent: function(aDomMessage) {
-    // Broadcasting a 'sms-received' system message to open apps.
-    this.broadcastMmsSystemMessage(kSmsReceivedObserverTopic, aDomMessage);
-
-    // Notifying observers an MMS message is received.
-    Services.obs.notifyObservers(aDomMessage, kSmsReceivedObserverTopic, null);
-  },
-
-  /**
-   * Callback for retrieveMessage.
-   */
-  retrieveMessageCallback: function(mmsConnection, wish, savableMessage,
-                                    mmsStatus, retrievedMessage) {
-    if (DEBUG) debug("retrievedMessage = " + JSON.stringify(retrievedMessage));
-
-    let transactionId = savableMessage.headers["x-mms-transaction-id"];
-
-    // The absence of the field does not indicate any default
-    // value. So we go check the same field in the retrieved
-    // message instead.
-    if (wish == null && retrievedMessage) {
-      wish = retrievedMessage.headers["x-mms-delivery-report"];
-    }
-
-    let reportAllowed = this.getReportAllowed(this.confSendDeliveryReport,
-                                              wish);
-    // If the mmsStatus isn't MMS_PDU_STATUS_RETRIEVED after retrieving,
-    // something must be wrong with MMSC, so stop updating the DB record.
-    // We could send a message to content to notify the user the MMS
-    // retrieving failed. The end user has to retrieve the MMS again.
-    if (MMS.MMS_PDU_STATUS_RETRIEVED !== mmsStatus) {
-      if (mmsStatus != _MMS_ERROR_RADIO_DISABLED &&
-          mmsStatus != _MMS_ERROR_NO_SIM_CARD &&
-          mmsStatus != _MMS_ERROR_SIM_CARD_CHANGED) {
-        let transaction = new NotifyResponseTransaction(mmsConnection,
-                                                        transactionId,
-                                                        mmsStatus,
-                                                        reportAllowed);
-        transaction.run();
-      }
-      // Retrieved fail after retry, so we update the delivery status in DB and
-      // notify this domMessage that error happen.
-      gMobileMessageDatabaseService
-        .setMessageDeliveryByMessageId(savableMessage.id,
-                                       null,
-                                       null,
-                                       DELIVERY_STATUS_ERROR,
-                                       null,
-                                       (aRv, aDomMessage) => {
-        let mmsMessage = null;
-        try {
-          mmsMessage = aDomMessage.QueryInterface(Ci.nsIMmsMessage);
-        } catch (e) {}
-        this.broadcastReceivedMessageEvent(mmsMessage);
-      });
-      return;
-    }
-
-    savableMessage = this.mergeRetrievalConfirmation(mmsConnection,
-                                                     retrievedMessage,
-                                                     savableMessage);
-    gMobileMessageDatabaseService.saveReceivedMessage(savableMessage,
-                                                      (aRv, aDomMessage) => {
-      let mmsMessage = null;
-      try {
-        mmsMessage = aDomMessage.QueryInterface(Ci.nsIMmsMessage);
-      } catch (e) {}
-
-      let success = Components.isSuccessCode(aRv);
-
-      // Cite 6.2.1 "Transaction Flow" in OMA-TS-MMS_ENC-V1_3-20110913-A:
-      // The M-NotifyResp.ind response PDU SHALL provide a message retrieval
-      // status code. The status ‘retrieved’ SHALL be used only if the MMS
-      // Client has successfully retrieved the MM prior to sending the
-      // NotifyResp.ind response PDU.
-      let transaction =
-        new NotifyResponseTransaction(mmsConnection,
-                                      transactionId,
-                                      success ? MMS.MMS_PDU_STATUS_RETRIEVED
-                                              : MMS.MMS_PDU_STATUS_DEFERRED,
-                                      reportAllowed);
-      transaction.run();
-
-      if (!success) {
-        // At this point we could send a message to content to notify the user
-        // that storing an incoming MMS failed, most likely due to a full disk.
-        // The end user has to retrieve the MMS again.
-        if (DEBUG) debug("Could not store MMS , error code " + aRv);
-        return;
-      }
-
-      this.broadcastReceivedMessageEvent(mmsMessage);
-    });
-  },
-
-  /**
-   * Callback for saveReceivedMessage.
-   */
-  saveReceivedMessageCallback: function(mmsConnection, retrievalMode,
-                                        savableMessage, rv, domMessage) {
-    let success = Components.isSuccessCode(rv);
-    if (!success) {
-      // At this point we could send a message to content to notify the
-      // user that storing an incoming MMS notification indication failed,
-      // ost likely due to a full disk.
-      if (DEBUG) debug("Could not store MMS " + JSON.stringify(savableMessage) +
-            ", error code " + rv);
-      // Because MMSC will resend the notification indication once we don't
-      // response the notification. Hope the end user will clean some space
-      // for the resent notification indication.
-      return;
-    }
-
-    // For X-Mms-Report-Allowed and X-Mms-Transaction-Id
-    let wish = savableMessage.headers["x-mms-delivery-report"];
-    let transactionId = savableMessage.headers["x-mms-transaction-id"];
-
-    this.broadcastReceivedMessageEvent(domMessage);
-
-    // To avoid costing money, we only send notify response when it's under
-    // the "automatic" retrieval mode or it's not in the roaming environment.
-    if (retrievalMode !== RETRIEVAL_MODE_AUTOMATIC &&
-        mmsConnection.isVoiceRoaming()) {
-      return;
-    }
-
-    if (RETRIEVAL_MODE_MANUAL === retrievalMode ||
-        RETRIEVAL_MODE_NEVER === retrievalMode) {
-      let mmsStatus = RETRIEVAL_MODE_NEVER === retrievalMode
-                    ? MMS.MMS_PDU_STATUS_REJECTED
-                    : MMS.MMS_PDU_STATUS_DEFERRED;
-
-      // For X-Mms-Report-Allowed
-      let reportAllowed = this.getReportAllowed(this.confSendDeliveryReport,
-                                                wish);
-
-      let transaction = new NotifyResponseTransaction(mmsConnection,
-                                                      transactionId,
-                                                      mmsStatus,
-                                                      reportAllowed);
-      transaction.run();
-      return;
-    }
-
-    let url = savableMessage.headers["x-mms-content-location"].uri;
-
-    // For RETRIEVAL_MODE_AUTOMATIC or RETRIEVAL_MODE_AUTOMATIC_HOME but not
-    // roaming, proceed to retrieve MMS.
-    this.retrieveMessage(mmsConnection,
-                         url,
-                         (aMmsStatus, aRetrievedMsg) =>
-                           this.retrieveMessageCallback(mmsConnection,
-                                                        wish,
-                                                        savableMessage,
-                                                        aMmsStatus,
-                                                        aRetrievedMsg),
-                         domMessage);
-  },
-
-  /**
-   * Handle incoming M-Notification.ind PDU.
-   *
-   * @param serviceId
-   *        The ID of the service for receiving the PDU data.
-   * @param notification
-   *        The parsed MMS message object.
-   */
-  handleNotificationIndication: function(serviceId, notification) {
-    let transactionId = notification.headers["x-mms-transaction-id"];
-    gMobileMessageDatabaseService
-      .getMessageRecordByTransactionId(transactionId, (aRv, aMessageRecord) => {
-      if (Components.isSuccessCode(aRv) && aMessageRecord) {
-        if (DEBUG) debug("We already got the NotificationIndication with transactionId = "
-                         + transactionId + " before.");
-        return;
-      }
-
-      let retrievalMode = RETRIEVAL_MODE_MANUAL;
-      try {
-        retrievalMode = Services.prefs.getCharPref(kPrefRetrievalMode);
-      } catch (e) {}
-
-      // Under the "automatic"/"automatic-home" retrieval mode, we switch to
-      // the "manual" retrieval mode to download MMS for non-active SIM.
-      if ((retrievalMode == RETRIEVAL_MODE_AUTOMATIC ||
-           retrievalMode == RETRIEVAL_MODE_AUTOMATIC_HOME) &&
-          serviceId != this.mmsDefaultServiceId) {
-        if (DEBUG) {
-          debug("Switch to 'manual' mode to download MMS for non-active SIM: " +
-                "serviceId = " + serviceId + " doesn't equal to " +
-                "mmsDefaultServiceId = " + this.mmsDefaultServiceId);
-        }
-
-        retrievalMode = RETRIEVAL_MODE_MANUAL;
-      }
-
-      let mmsConnection = gMmsConnections.getConnByServiceId(serviceId);
-
-      let savableMessage = this.convertIntermediateToSavable(mmsConnection,
-                                                             notification,
-                                                             retrievalMode);
-
-      gMobileMessageDatabaseService
-        .saveReceivedMessage(savableMessage,
-                             (aRv, aDomMessage) => {
-          let mmsMessage = null;
-          try {
-            mmsMessage = aDomMessage.QueryInterface(Ci.nsIMmsMessage);
-          } catch (e) {}
-          this.saveReceivedMessageCallback(mmsConnection,
-                                           retrievalMode,
-                                           savableMessage,
-                                           aRv,
-                                           mmsMessage);
-      });
-    });
-  },
-
-  /**
-   * Handle incoming M-Delivery.ind PDU.
-   *
-   * @param aMsg
-   *        The MMS message object.
-   */
-  handleDeliveryIndication: function(aMsg) {
-    let headers = aMsg.headers;
-    let envelopeId = headers["message-id"];
-    let address = headers.to.address;
-    let mmsStatus = headers["x-mms-status"];
-    if (DEBUG) {
-      debug("Start updating the delivery status for envelopeId: " + envelopeId +
-            " address: " + address + " mmsStatus: " + mmsStatus);
-    }
-
-    // From OMA-TS-MMS_ENC-V1_3-20110913-A subclause 9.3 "X-Mms-Status",
-    // in the M-Delivery.ind the X-Mms-Status could be MMS.MMS_PDU_STATUS_{
-    // EXPIRED, RETRIEVED, REJECTED, DEFERRED, UNRECOGNISED, INDETERMINATE,
-    // FORWARDED, UNREACHABLE }.
-    let deliveryStatus;
-    switch (mmsStatus) {
-      case MMS.MMS_PDU_STATUS_RETRIEVED:
-        deliveryStatus = DELIVERY_STATUS_SUCCESS;
-        break;
-      case MMS.MMS_PDU_STATUS_EXPIRED:
-      case MMS.MMS_PDU_STATUS_REJECTED:
-      case MMS.MMS_PDU_STATUS_UNRECOGNISED:
-      case MMS.MMS_PDU_STATUS_UNREACHABLE:
-        deliveryStatus = DELIVERY_STATUS_REJECTED;
-        break;
-      case MMS.MMS_PDU_STATUS_DEFERRED:
-        deliveryStatus = DELIVERY_STATUS_PENDING;
-        break;
-      case MMS.MMS_PDU_STATUS_INDETERMINATE:
-        deliveryStatus = DELIVERY_STATUS_NOT_APPLICABLE;
-        break;
-      default:
-        if (DEBUG) debug("Cannot handle this MMS status. Returning.");
-        return;
-    }
-
-    if (DEBUG) debug("Updating the delivery status to: " + deliveryStatus);
-    gMobileMessageDatabaseService
-      .setMessageDeliveryStatusByEnvelopeId(envelopeId, address, deliveryStatus,
-                                            (aRv, aDomMessage) => {
-      if (DEBUG) debug("Marking the delivery status is done.");
-
-      let mmsMessage = null;
-      try {
-        mmsMessage = aDomMessage.QueryInterface(Ci.nsIMmsMessage);
-      } catch (e) {}
-
-      // TODO bug 832140 handle !Components.isSuccessCode(aRv)
-
-      let topic;
-      if (mmsStatus === MMS.MMS_PDU_STATUS_RETRIEVED) {
-        topic = kSmsDeliverySuccessObserverTopic;
-        // Broadcasting a 'sms-delivery-success' system message to open apps.
-        this.broadcastMmsSystemMessage(topic, mmsMessage);
-      } else if (mmsStatus === MMS.MMS_PDU_STATUS_REJECTED) {
-        topic = kSmsDeliveryErrorObserverTopic;
-        // Broadcasting a 'sms-delivery-error' system message to open apps.
-        this.broadcastMmsSystemMessage(topic, mmsMessage);
-      } else {
-        if (DEBUG) debug("Needn't fire event for this MMS status. Returning.");
-        return;
-      }
-
-      // Notifying observers the delivery status is updated.
-      Services.obs.notifyObservers(mmsMessage, topic, null);
-    });
-  },
-
-  /**
-   * Handle incoming M-Read-Orig.ind PDU.
-   *
-   * @param aIndication
-   *        The MMS message object.
-   */
-  handleReadOriginateIndication: function(aIndication) {
-
-    let headers = aIndication.headers;
-    let envelopeId = headers["message-id"];
-    let address = headers.from.address;
-    let mmsReadStatus = headers["x-mms-read-status"];
-    if (DEBUG) {
-      debug("Start updating the read status for envelopeId: " + envelopeId +
-            ", address: " + address + ", mmsReadStatus: " + mmsReadStatus);
-    }
-
-    // From OMA-TS-MMS_ENC-V1_3-20110913-A subclause 9.4 "X-Mms-Read-Status",
-    // in M-Read-Rec-Orig.ind the X-Mms-Read-Status could be
-    // MMS.MMS_READ_STATUS_{ READ, DELETED_WITHOUT_BEING_READ }.
-    let readStatus = mmsReadStatus == MMS.MMS_PDU_READ_STATUS_READ
-                   ? MMS.DOM_READ_STATUS_SUCCESS
-                   : MMS.DOM_READ_STATUS_ERROR;
-    if (DEBUG) debug("Updating the read status to: " + readStatus);
-
-    gMobileMessageDatabaseService
-      .setMessageReadStatusByEnvelopeId(envelopeId, address, readStatus,
-                                        (aRv, aDomMessage) => {
-      let mmsMessage = null;
-      try {
-        mmsMessage = aDomMessage.QueryInterface(Ci.nsIMmsMessage);
-      } catch (e) {}
-
-      if (!Components.isSuccessCode(aRv)) {
-        if (DEBUG) debug("Failed to update read status: " + aRv);
-        return;
-      }
-
-      if (DEBUG) debug("Marking the read status is done.");
-      let topic;
-      if (mmsReadStatus == MMS.MMS_PDU_READ_STATUS_READ) {
-        topic = kSmsReadSuccessObserverTopic;
-
-        // Broadcasting a 'sms-read-success' system message to open apps.
-        this.broadcastMmsSystemMessage(topic, mmsMessage);
-      } else {
-        topic = kSmsReadErrorObserverTopic;
-      }
-
-      // Notifying observers the read status is updated.
-      Services.obs.notifyObservers(mmsMessage, topic, null);
-    });
-  },
-
-  /**
-   * A utility function to convert the MmsParameters dictionary object
-   * to a database-savable message.
-   *
-   * @param aMmsConnection
-   *        The MMS connection.
-   * @param aParams
-   *        The MmsParameters dictionay object.
-   * @param aMessage (output)
-   *        The database-savable message.
-   * Return the error code by veryfying if the |aParams| is valid or not.
-   *
-   * Notes:
-   *
-   * OMA-TS-MMS-CONF-V1_3-20110913-A section 10.2.2 "Message Content Encoding":
-   *
-   * A name for multipart object SHALL be encoded using name-parameter for Content-Type
-   * header in WSP multipart headers. In decoding, name-parameter of Content-Type SHALL
-   * be used if available. If name-parameter of Content-Type is not available, filename
-   * parameter of Content-Disposition header SHALL be used if available. If neither
-   * name-parameter of Content-Type header nor filename parameter of Content-Disposition
-   * header is available, Content-Location header SHALL be used if available.
-   */
-  createSavableFromParams: function(aMmsConnection, aParams, aMessage) {
-    if (DEBUG) debug("createSavableFromParams: aParams: " + JSON.stringify(aParams));
-
-    let isAddrValid = true;
-    let smil = aParams.smil;
-
-    // |aMessage.headers|
-    let headers = aMessage["headers"] = {};
-
-    let receivers = aParams.receivers;
-    let headersTo = headers["to"] = [];
-    if (receivers.length != 0) {
-      for (let i = 0; i < receivers.length; i++) {
-        let receiver = receivers[i];
-        let type = MMS.Address.resolveType(receiver);
-        let address;
-        if (type == "PLMN") {
-          address = PhoneNumberUtils.normalize(receiver, false);
-          if (!PhoneNumberUtils.isPlainPhoneNumber(address)) {
-            isAddrValid = false;
-          }
-          if (DEBUG) debug("createSavableFromParams: normalize phone number " +
-                           "from " + receiver + " to " + address);
-        } else {
-          address = receiver;
-          if (type == "Others") {
-            isAddrValid = false;
-            if (DEBUG) debug("Error! Address is invalid to send MMS: " + address);
-          }
-        }
-        headersTo.push({"address": address, "type": type});
-      }
-    }
-    if (aParams.subject) {
-      headers["subject"] = aParams.subject;
-    }
-
-    // |aMessage.parts|
-    let attachments = aParams.attachments;
-    if (attachments.length != 0 || smil) {
-      let parts = aMessage["parts"] = [];
-
-      // Set the SMIL part if needed.
-      if (smil) {
-        let part = {
-          "headers": {
-            "content-type": {
-              "media": "application/smil",
-              "params": {
-                "name": "smil.xml",
-                "charset": {
-                  "charset": "utf-8"
-                }
-              }
-            },
-            "content-location": "smil.xml",
-            "content-id": "<smil>"
-          },
-          "content": smil
-        };
-        parts.push(part);
-      }
-
-      // Set other parts for attachments if needed.
-      for (let i = 0; i < attachments.length; i++) {
-        let attachment = attachments[i];
-        let content = attachment.content;
-        let location = attachment.location;
-
-        let params = {
-          "name": location
-        };
-
-        if (content.type && content.type.indexOf("text/") == 0) {
-          params.charset = {
-            "charset": "utf-8"
-          };
-        }
-
-        let part = {
-          "headers": {
-            "content-type": {
-              "media": content.type,
-              "params": params
-            },
-            "content-location": location,
-            "content-id": attachment.id
-          },
-          "content": content
-        };
-        parts.push(part);
-      }
-    }
-
-    // The following attributes are needed for saving message into DB.
-    aMessage["type"] = "mms";
-    aMessage["timestamp"] = Date.now();
-    aMessage["receivers"] = receivers;
-    aMessage["sender"] = aMmsConnection.getPhoneNumber();
-    aMessage["iccId"] = aMmsConnection.getIccId();
-    try {
-      aMessage["deliveryStatusRequested"] =
-        Services.prefs.getBoolPref("dom.mms.requestStatusReport");
-    } catch (e) {
-      aMessage["deliveryStatusRequested"] = false;
-    }
-    try {
-      headers["x-mms-read-report"] =
-        Services.prefs.getBoolPref("dom.mms.requestReadReport");
-    } catch (e) {
-      headers["x-mms-read-report"] = false;
-    }
-
-    if (DEBUG) debug("createSavableFromParams: aMessage: " +
-                     JSON.stringify(aMessage));
-
-    return isAddrValid ? Ci.nsIMobileMessageCallback.SUCCESS_NO_ERROR
-                       : Ci.nsIMobileMessageCallback.INVALID_ADDRESS_ERROR;
-  },
-
-  // nsIMmsService
-
-  mmsDefaultServiceId: 0,
-
-  send: function(aServiceId, aParams, aRequest) {
-    if (DEBUG) debug("send: aParams: " + JSON.stringify(aParams));
-
-    // Note that the following sanity checks for |aParams| should be consistent
-    // with the checks in SmsIPCService.GetSendMmsMessageRequestFromParams.
-
-    // Check if |aParams| is valid.
-    if (aParams == null || typeof aParams != "object") {
-      if (DEBUG) debug("Error! 'aParams' should be a non-null object.");
-      throw Cr.NS_ERROR_INVALID_ARG;
-      return;
-    }
-
-    // Check if |receivers| is valid.
-    if (!Array.isArray(aParams.receivers)) {
-      if (DEBUG) debug("Error! 'receivers' should be an array.");
-      throw Cr.NS_ERROR_INVALID_ARG;
-      return;
-    }
-
-    // Check if |subject| is valid.
-    if (aParams.subject != null && typeof aParams.subject != "string") {
-      if (DEBUG) debug("Error! 'subject' should be a string if passed.");
-      throw Cr.NS_ERROR_INVALID_ARG;
-      return;
-    }
-
-    // Check if |smil| is valid.
-    if (aParams.smil != null && typeof aParams.smil != "string") {
-      if (DEBUG) debug("Error! 'smil' should be a string if passed.");
-      throw Cr.NS_ERROR_INVALID_ARG;
-      return;
-    }
-
-    // Check if |attachments| is valid.
-    if (!Array.isArray(aParams.attachments)) {
-      if (DEBUG) debug("Error! 'attachments' should be an array.");
-      throw Cr.NS_ERROR_INVALID_ARG;
-      return;
-    }
-
-    let sendTransactionCb = (aDomMessage, aErrorCode, aEnvelopeId) => {
-      if (DEBUG) {
-        debug("The returned status of sending transaction: " +
-              "aErrorCode: " + aErrorCode + " aEnvelopeId: " + aEnvelopeId);
-      }
-
-      // If the messsage has been deleted (because the sending process is
-      // cancelled), we don't need to reset the its delievery state/status.
-      if (aErrorCode == Ci.nsIMobileMessageCallback.NOT_FOUND_ERROR) {
-        aRequest.notifySendMessageFailed(aErrorCode, aDomMessage);
-        this.broadcastSentFailureMessageEvent(aDomMessage);
-        return;
-      }
-
-      let isSentSuccess = (aErrorCode == Ci.nsIMobileMessageCallback.SUCCESS_NO_ERROR);
-      gMobileMessageDatabaseService
-        .setMessageDeliveryByMessageId(aDomMessage.id,
-                                       null,
-                                       isSentSuccess ? DELIVERY_SENT : DELIVERY_ERROR,
-                                       isSentSuccess ? null : DELIVERY_STATUS_ERROR,
-                                       aEnvelopeId,
-                                       (aRv, aDomMessage) => {
-        if (DEBUG) debug("Marking the delivery state/staus is done. Notify sent or failed.");
-
-        let mmsMessage = null;
-        try {
-          mmsMessage = aDomMessage.QueryInterface(Ci.nsIMmsMessage);
-        } catch (e) {}
-
-        // TODO bug 832140 handle !Components.isSuccessCode(aRv)
-        if (!isSentSuccess) {
-          if (DEBUG) debug("Sending MMS failed.");
-          aRequest.notifySendMessageFailed(aErrorCode, mmsMessage);
-          this.broadcastSentFailureMessageEvent(mmsMessage);
-          return;
-        }
-
-        if (DEBUG) debug("Sending MMS succeeded.");
-
-        // Notifying observers the MMS message is sent.
-        this.broadcastSentMessageEvent(mmsMessage);
-
-        // Return the request after sending the MMS message successfully.
-        aRequest.notifyMessageSent(mmsMessage);
-      });
-    };
-
-    let mmsConnection = gMmsConnections.getConnByServiceId(aServiceId);
-
-    let savableMessage = {};
-    let errorCode = this.createSavableFromParams(mmsConnection, aParams,
-                                                 savableMessage);
-    gMobileMessageDatabaseService
-      .saveSendingMessage(savableMessage,
-                          (aRv, aDomMessage) => {
-      let mmsMessage = null;
-      try {
-        mmsMessage = aDomMessage.QueryInterface(Ci.nsIMmsMessage);
-      } catch (e) {}
-
-      if (!Components.isSuccessCode(aRv)) {
-        if (DEBUG) debug("Error! Fail to save sending message! rv = " + aRv);
-        aRequest.notifySendMessageFailed(
-          gMobileMessageDatabaseService.translateCrErrorToMessageCallbackError(aRv),
-          mmsMessage);
-        this.broadcastSentFailureMessageEvent(mmsMessage);
-        return;
-      }
-
-      if (DEBUG) debug("Saving sending message is done. Start to send.");
-
-      Services.obs.notifyObservers(mmsMessage, kSmsSendingObserverTopic, null);
-
-      if (errorCode !== Ci.nsIMobileMessageCallback.SUCCESS_NO_ERROR) {
-        if (DEBUG) debug("Error! The params for sending MMS are invalid.");
-        sendTransactionCb(mmsMessage, errorCode, null);
-        return;
-      }
-
-      // Check radio state in prior to default service Id.
-      if (isRadioOff(aServiceId)) {
-        if (DEBUG) debug("Error! Radio is disabled when sending MMS.");
-        sendTransactionCb(mmsMessage,
-                          Ci.nsIMobileMessageCallback.RADIO_DISABLED_ERROR,
-                          null);
-        return;
-      }
-
-      // To support DSDS, we have to stop users sending MMS when the selected
-      // SIM is not active, thus avoiding the data disconnection of the current
-      // SIM. Users have to manually swith the default SIM before sending.
-      if (mmsConnection.serviceId != this.mmsDefaultServiceId) {
-        if (DEBUG) debug("RIL service is not active to send MMS.");
-        sendTransactionCb(mmsMessage,
-                          Ci.nsIMobileMessageCallback.NON_ACTIVE_SIM_CARD_ERROR,
-                          null);
-        return;
-      }
-
-      // This is the entry point starting to send MMS.
-      let sendTransaction;
-      try {
-        sendTransaction =
-          new SendTransaction(mmsConnection, mmsMessage.id, savableMessage,
-                              savableMessage["deliveryStatusRequested"]);
-      } catch (e) {
-        if (DEBUG) debug("Exception: fail to create a SendTransaction instance.");
-        sendTransactionCb(mmsMessage,
-                          Ci.nsIMobileMessageCallback.INTERNAL_ERROR, null);
-        return;
-      }
-      sendTransaction.run((aMmsStatus, aMsg) => {
-        if (DEBUG) debug("The sending status of sendTransaction.run(): " + aMmsStatus);
-        let errorCode;
-        if (aMmsStatus == _MMS_ERROR_MESSAGE_DELETED) {
-          errorCode = Ci.nsIMobileMessageCallback.NOT_FOUND_ERROR;
-        } else if (aMmsStatus == _MMS_ERROR_RADIO_DISABLED) {
-          errorCode = Ci.nsIMobileMessageCallback.RADIO_DISABLED_ERROR;
-        } else if (aMmsStatus == _MMS_ERROR_NO_SIM_CARD) {
-          errorCode = Ci.nsIMobileMessageCallback.NO_SIM_CARD_ERROR;
-        } else if (aMmsStatus == _MMS_ERROR_SIM_CARD_CHANGED) {
-          errorCode = Ci.nsIMobileMessageCallback.NON_ACTIVE_SIM_CARD_ERROR;
-        } else if (aMmsStatus != MMS.MMS_PDU_ERROR_OK) {
-          errorCode = Ci.nsIMobileMessageCallback.INTERNAL_ERROR;
-        } else {
-          errorCode = Ci.nsIMobileMessageCallback.SUCCESS_NO_ERROR;
-        }
-        let envelopeId =
-          aMsg && aMsg.headers && aMsg.headers["message-id"] || null;
-        sendTransactionCb(mmsMessage, errorCode, envelopeId);
-      });
-    });
-  },
-
-  retrieve: function(aMessageId, aRequest) {
-    if (DEBUG) debug("Retrieving message with ID " + aMessageId);
-    gMobileMessageDatabaseService
-      .getMessageRecordById(aMessageId, (aRv, aMessageRecord, aDomMessage) => {
-      let mmsMessage = null;
-      try {
-        mmsMessage = aDomMessage.QueryInterface(Ci.nsIMmsMessage);
-      } catch (e) {}
-
-      if (!Components.isSuccessCode(aRv)) {
-        if (DEBUG) debug("Function getMessageRecordById() return error: " + aRv);
-        aRequest.notifyGetMessageFailed(
-          gMobileMessageDatabaseService.translateCrErrorToMessageCallbackError(aRv));
-        return;
-      }
-      if ("mms" != aMessageRecord.type) {
-        if (DEBUG) debug("Type of message record is not 'mms'.");
-        aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
-        return;
-      }
-      if (!aMessageRecord.headers) {
-        if (DEBUG) debug("Must need the MMS' headers to proceed the retrieve.");
-        aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
-        return;
-      }
-      if (!aMessageRecord.headers["x-mms-content-location"]) {
-        if (DEBUG) debug("Can't find mms content url in database.");
-        aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
-        return;
-      }
-      if (DELIVERY_NOT_DOWNLOADED != aMessageRecord.delivery) {
-        if (DEBUG) debug("Delivery of message record is not 'not-downloaded'.");
-        aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
-        return;
-      }
-      let deliveryStatus = aMessageRecord.deliveryInfo[0].deliveryStatus;
-      if (DELIVERY_STATUS_PENDING == deliveryStatus) {
-        if (DEBUG) debug("Delivery status of message record is 'pending'.");
-        aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
-        return;
-      }
-
-      // Cite 6.2 "Multimedia Message Notification" in OMA-TS-MMS_ENC-V1_3-20110913-A:
-      // The field has only one format, relative. The recipient client calculates
-      // this length of time relative to the time it receives the notification.
-      if (aMessageRecord.headers["x-mms-expiry"] != undefined) {
-        let expiryDate = aMessageRecord.timestamp +
-                         aMessageRecord.headers["x-mms-expiry"] * 1000;
-        if (expiryDate < Date.now()) {
-          if (DEBUG) debug("The message to be retrieved is expired.");
-          aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.NOT_FOUND_ERROR);
-          return;
-        }
-      }
-
-      // IccInfo in RadioInterface is not available when radio is off and
-      // NO_SIM_CARD_ERROR will be replied instead of RADIO_DISABLED_ERROR.
-      // Hence, for manual retrieving, instead of checking radio state later
-      // in MmsConnection.acquire(), We have to check radio state in prior to
-      // iccId to return the error correctly.
-      let numRadioInterfaces = gMobileConnectionService.numItems;
-      let isAllRadioOff = true;
-      for (let serviceId = 0; serviceId < numRadioInterfaces; serviceId++) {
-        isAllRadioOff &= isRadioOff(serviceId);
-      }
-
-      if (isAllRadioOff) {
-        if (DEBUG) debug("Error! Radio is disabled when retrieving MMS.");
-        aRequest.notifyGetMessageFailed(
-          Ci.nsIMobileMessageCallback.RADIO_DISABLED_ERROR);
-        return;
-      }
-
-      // Get MmsConnection based on the saved MMS message record's ICC ID,
-      // which could fail when the corresponding SIM card isn't installed.
-      let mmsConnection;
-      try {
-        mmsConnection = gMmsConnections.getConnByIccId(aMessageRecord.iccId);
-      } catch (e) {
-        if (DEBUG) debug("Failed to get connection by IccId. e= " + e);
-        let error = (e === _MMS_ERROR_SIM_NOT_MATCHED) ?
-                      Ci.nsIMobileMessageCallback.SIM_NOT_MATCHED_ERROR :
-                      Ci.nsIMobileMessageCallback.NO_SIM_CARD_ERROR;
-        aRequest.notifyGetMessageFailed(error);
-        return;
-      }
-
-      // To support DSDS, we have to stop users retrieving MMS when the needed
-      // SIM is not active, thus avoiding the data disconnection of the current
-      // SIM. Users have to manually swith the default SIM before retrieving.
-      if (mmsConnection.serviceId != this.mmsDefaultServiceId) {
-        if (DEBUG) debug("RIL service is not active to retrieve MMS.");
-        aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.NON_ACTIVE_SIM_CARD_ERROR);
-        return;
-      }
-
-      let url =  aMessageRecord.headers["x-mms-content-location"].uri;
-      // For X-Mms-Report-Allowed
-      let wish = aMessageRecord.headers["x-mms-delivery-report"];
-      let responseNotify = (mmsStatus, retrievedMsg) => {
-        // If the messsage has been deleted (because the retrieving process is
-        // cancelled), we don't need to reset the its delievery state/status.
-        if (mmsStatus == _MMS_ERROR_MESSAGE_DELETED) {
-          aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.NOT_FOUND_ERROR);
-          return;
-        }
-
-        // If the mmsStatus is still MMS_PDU_STATUS_DEFERRED after retry,
-        // we should not store it into database and update its delivery
-        // status to 'error'.
-        if (MMS.MMS_PDU_STATUS_RETRIEVED !== mmsStatus) {
-          if (DEBUG) debug("RetrieveMessage fail after retry.");
-          let errorCode = Ci.nsIMobileMessageCallback.INTERNAL_ERROR;
-          if (mmsStatus == _MMS_ERROR_RADIO_DISABLED) {
-            errorCode = Ci.nsIMobileMessageCallback.RADIO_DISABLED_ERROR;
-          } else if (mmsStatus == _MMS_ERROR_NO_SIM_CARD) {
-            errorCode = Ci.nsIMobileMessageCallback.NO_SIM_CARD_ERROR;
-          } else if (mmsStatus == _MMS_ERROR_SIM_CARD_CHANGED) {
-            errorCode = Ci.nsIMobileMessageCallback.NON_ACTIVE_SIM_CARD_ERROR;
-          }
-          gMobileMessageDatabaseService
-            .setMessageDeliveryByMessageId(aMessageId,
-                                           null,
-                                           null,
-                                           DELIVERY_STATUS_ERROR,
-                                           null,
-                                           () => aRequest.notifyGetMessageFailed(errorCode));
-          return;
-        }
-        // In OMA-TS-MMS_ENC-V1_3, Table 5 in page 25. This header field
-        // (x-mms-transaction-id) SHALL be present when the MMS Proxy relay
-        // seeks an acknowledgement for the MM delivered though M-Retrieve.conf
-        // PDU during deferred retrieval. This transaction ID is used by the MMS
-        // Client and MMS Proxy-Relay to provide linkage between the originated
-        // M-Retrieve.conf and the response M-Acknowledge.ind PDUs.
-        let transactionId = retrievedMsg.headers["x-mms-transaction-id"];
-
-        // The absence of the field does not indicate any default
-        // value. So we go checking the same field in retrieved
-        // message instead.
-        if (wish == null && retrievedMsg) {
-          wish = retrievedMsg.headers["x-mms-delivery-report"];
-        }
-        let reportAllowed = this.getReportAllowed(this.confSendDeliveryReport,
-                                                  wish);
-
-        if (DEBUG) debug("retrievedMsg = " + JSON.stringify(retrievedMsg));
-        aMessageRecord = this.mergeRetrievalConfirmation(mmsConnection,
-                                                         retrievedMsg,
-                                                         aMessageRecord);
-
-        gMobileMessageDatabaseService.saveReceivedMessage(aMessageRecord,
-                                                          (aRv, aDomMessage) => {
-          let mmsMessage = null;
-          try {
-            mmsMessage = aDomMessage.QueryInterface(Ci.nsIMmsMessage);
-          } catch (e) {}
-
-          let success = Components.isSuccessCode(aRv);
-          if (!success) {
-            // At this point we could send a message to content to
-            // notify the user that storing an incoming MMS failed, most
-            // likely due to a full disk.
-            if (DEBUG) debug("Could not store MMS, error code " + aRv);
-            aRequest.notifyGetMessageFailed(
-              gMobileMessageDatabaseService.translateCrErrorToMessageCallbackError(aRv));
-            return;
-          }
-
-          // Notifying observers a new MMS message is retrieved.
-          this.broadcastReceivedMessageEvent(mmsMessage);
-
-          // Return the request after retrieving the MMS message successfully.
-          aRequest.notifyMessageGot(mmsMessage);
-
-          // Cite 6.3.1 "Transaction Flow" in OMA-TS-MMS_ENC-V1_3-20110913-A:
-          // If an acknowledgement is requested, the MMS Client SHALL respond
-          // with an M-Acknowledge.ind PDU to the MMS Proxy-Relay that supports
-          // the specific MMS Client. The M-Acknowledge.ind PDU confirms
-          // successful message retrieval to the MMS Proxy Relay.
-          let transaction = new AcknowledgeTransaction(mmsConnection,
-                                                       transactionId,
-                                                       reportAllowed);
-          transaction.run();
-        });
-      };
-
-      // Update the delivery status to pending in DB.
-      gMobileMessageDatabaseService
-        .setMessageDeliveryByMessageId(aMessageId,
-                                       null,
-                                       null,
-                                       DELIVERY_STATUS_PENDING,
-                                       null,
-                                       (rv) => {
-          let success = Components.isSuccessCode(rv);
-          if (!success) {
-            if (DEBUG) debug("Could not change the delivery status, error code " + rv);
-            aRequest.notifyGetMessageFailed(
-              gMobileMessageDatabaseService.translateCrErrorToMessageCallbackError(rv));
-            return;
-          }
-
-          this.retrieveMessage(mmsConnection,
-                               url,
-                               (aMmsStatus, aRetrievedMsg) =>
-                                 responseNotify(aMmsStatus, aRetrievedMsg),
-                               mmsMessage);
-        });
-    });
-  },
-
-  sendReadReport: function(messageID, toAddress, iccId) {
-    if (DEBUG) {
-      debug("messageID: " + messageID + " toAddress: " +
-            JSON.stringify(toAddress));
-    }
-
-    // Get MmsConnection based on the saved MMS message record's ICC ID,
-    // which could fail when the corresponding SIM card isn't installed.
-    let mmsConnection;
-    try {
-      mmsConnection = gMmsConnections.getConnByIccId(iccId);
-    } catch (e) {
-      if (DEBUG) debug("Failed to get connection by IccId. e = " + e);
-      return;
-    }
-
-    try {
-      let transaction =
-        new ReadRecTransaction(mmsConnection, messageID, toAddress);
-      transaction.run();
-    } catch (e) {
-      if (DEBUG) debug("sendReadReport fail. e = " + e);
-    }
-  },
-
-  // nsIWapPushApplication
-
-  receiveWapPush: function(array, length, offset, options) {
-    let data = {array: array, offset: offset};
-    let msg = MMS.PduHelper.parse(data, null);
-    if (!msg) {
-      return false;
-    }
-    if (DEBUG) debug("receiveWapPush: msg = " + JSON.stringify(msg));
-
-    switch (msg.type) {
-      case MMS.MMS_PDU_TYPE_NOTIFICATION_IND:
-        this.handleNotificationIndication(options.serviceId, msg);
-        break;
-      case MMS.MMS_PDU_TYPE_DELIVERY_IND:
-        this.handleDeliveryIndication(msg);
-        break;
-      case MMS.MMS_PDU_TYPE_READ_ORIG_IND:
-        this.handleReadOriginateIndication(msg);
-        break;
-      default:
-        if (DEBUG) debug("Unsupported X-MMS-Message-Type: " + msg.type);
-        break;
-    }
-  },
-
-  // nsIObserver
-
-  observe: function(aSubject, aTopic, aData) {
-    switch (aTopic) {
-      case NS_PREFBRANCH_PREFCHANGE_TOPIC_ID:
-        if (aData === kPrefDefaultServiceId) {
-          this.mmsDefaultServiceId = getDefaultServiceId();
-        } else if (aData === kPrefMmsDebuggingEnabled) {
-          this._updateDebugFlag();
-        }
-        break;
-    }
-  }
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([MmsService]);
deleted file mode 100644
--- a/dom/mobilemessage/gonk/MmsService.manifest
+++ /dev/null
@@ -1,3 +0,0 @@
-# MmsService.js
-component {9b069b8c-8697-11e4-a406-474f5190272b} MmsService.js
-contract @mozilla.org/mms/gonkmmsservice;1 {9b069b8c-8697-11e4-a406-474f5190272b}
deleted file mode 100644
--- a/dom/mobilemessage/gonk/MobileMessageDB.jsm
+++ /dev/null
@@ -1,5206 +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/. */
-
-/*
- * This file is documented in JSDoc format. To generate the document:
- *
- * 1. Follow the instruction of JSDoc project to install it. See
- *    https://github.com/jsdoc3/jsdoc for details.
- *
- * 2. Since JSDoc does not recognize ES6 syntax and XPCOM components, you should
- *    enable the "commentsOnly" plugin in your conf.json to strip all code out
- *    before generating the document. You'll need to change source.includePattern
- *    as well to include "*.jsm" since it's not included by default. Here's a
- *    minimal example of conf.json you need:
- *
- *    {
- *      "source": {
- *        "includePattern": ".+\\.js(m)?$"
- *      },
- *      "plugins": ["plugins/commentsOnly"]
- *    }
- *
- * 3. Run jsdoc:
- *
- *    $ jsdoc -c <path-to-conf-json> -d <output-directory> MobileMessageDB.jsm
- */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/PhoneNumberUtils.jsm");
-Cu.importGlobalProperties(["indexedDB"]);
-
-XPCOMUtils.defineLazyGetter(this, "RIL", function () {
-  let obj = {};
-  Cu.import("resource://gre/modules/ril_consts.js", obj);
-  return obj;
-});
-
-const RIL_GETMESSAGESCURSOR_CID =
-  Components.ID("{484d1ad8-840e-4782-9dc4-9ebc4d914937}");
-const RIL_GETTHREADSCURSOR_CID =
-  Components.ID("{95ee7c3e-d6f2-4ec4-ade5-0c453c036d35}");
-
-const DEBUG = false;
-const DISABLE_MMS_GROUPING_FOR_RECEIVING = true;
-
-const DB_VERSION = 23;
-
-/**
- * @typedef {string} MobileMessageDB.MESSAGE_STORE_NAME
- *
- * The name of the object store for messages.
- */
-const MESSAGE_STORE_NAME = "sms";
-
-/**
- * @typedef {string} MobileMessageDB.THREAD_STORE_NAME
- *
- * The name of the object store for threads.
- */
-const THREAD_STORE_NAME = "thread";
-
-/**
- * @typedef {string} MobileMessageDB.PARTICIPANT_STORE_NAME
- *
- * The name of the object store for participants.
- */
-const PARTICIPANT_STORE_NAME = "participant";
-
-/**
- * @typedef {string} MobileMessageDB.MOST_RECENT_STORE_NAME
- * @deprecated
- */
-const MOST_RECENT_STORE_NAME = "most-recent";
-
-/**
- * @typedef {string} MobileMessageDB.SMS_SEGMENT_STORE_NAME
- *
- * The name of the object store for incoming SMS segments.
- */
-const SMS_SEGMENT_STORE_NAME = "sms-segment";
-
-const DELIVERY_SENDING = "sending";
-const DELIVERY_SENT = "sent";
-const DELIVERY_RECEIVED = "received";
-const DELIVERY_NOT_DOWNLOADED = "not-downloaded";
-const DELIVERY_ERROR = "error";
-
-const DELIVERY_STATUS_NOT_APPLICABLE = "not-applicable";
-const DELIVERY_STATUS_SUCCESS = "success";
-const DELIVERY_STATUS_PENDING = "pending";
-const DELIVERY_STATUS_ERROR = "error";
-
-const MESSAGE_CLASS_NORMAL = "normal";
-
-const FILTER_TIMESTAMP = "timestamp";
-const FILTER_NUMBERS = "numbers";
-const FILTER_DELIVERY = "delivery";
-const FILTER_READ = "read";
-
-// We can´t create an IDBKeyCursor with a boolean, so we need to use numbers
-// instead.
-const FILTER_READ_UNREAD = 0;
-const FILTER_READ_READ = 1;
-
-const READ_ONLY = "readonly";
-const READ_WRITE = "readwrite";
-const PREV = "prev";
-const NEXT = "next";
-
-const COLLECT_ID_END = 0;
-const COLLECT_ID_ERROR = -1;
-const COLLECT_TIMESTAMP_UNUSED = 0;
-
-// Default value for integer preference "dom.sms.maxReadAheadEntries".
-const DEFAULT_READ_AHEAD_ENTRIES = 7;
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageService",
-                                   "@mozilla.org/mobilemessage/mobilemessageservice;1",
-                                   "nsIMobileMessageService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMMSService",
-                                   "@mozilla.org/mms/gonkmmsservice;1",
-                                   "nsIMmsService");
-
-XPCOMUtils.defineLazyGetter(this, "MMS", function() {
-  let MMS = {};
-  Cu.import("resource://gre/modules/MmsPduHelper.jsm", MMS);
-  return MMS;
-});
-
-/**
- * @typedef {Object} MobileMessageDB.MessageRecord
- *
- * Represents a SMS or MMS message.
- *
- * <pre>
- * +--------------------------------------------------------------------------+
- * | MessageRecord                                                            |
- * +--------------------------------------------------------------------------+
- * | id: Number (primary-key)                                                 |
- * |                                                                          |
- * | [SMS / MMS Common]                                                       |
- * | type: String                                                             |
- * | read: Number // Works as boolean, only use 0 or 1.                       |
- * | iccId: String                                                            |
- * | sender: String                                                           |
- * | delivery: String                                                         |
- * | timestamp: Number                                                        |
- * | sentTimestamp: Number                                                    |
- * |                                                                          |
- * | [Database Foreign Keys]                                                  |
- * | threadId: Number                                                         |
- * |                                                                          |
- * | [Common Indices]                                                         |
- * | threadIdIndex: Array // [threadId, timestamp]                            |
- * | deliveryIndex: Array // [delivery, timestamp]                            |
- * | readIndex: Array // [read, timpstamp]                                    |
- * | participantIdsIndex: Array of Array // [[participantId, timestamp], ...] |
- * |                                                                          |
- * | [SMS / Common Fields]                                                    |
- * | pid: Number                                                              |
- * | SMSC: String                                                             |
- * | receiver: String                                                         |
- * | encoding: Number                                                         |
- * | messageType: Number                                                      |
- * | teleservice: Number                                                      |
- * | messageClass: String                                                     |
- * | deliveryStatus: String                                                   |
- * | deliveryTimestamp: Number                                                |
- * |                                                                          |
- * | [SMS / Application Port Info]                                            |
- * | originatorPort: Number                                                   |
- * | destinationPort: Number                                                  |
- * |                                                                          |
- * | [SMS / MWI status]                                                       |
- * | mwiPresent: Boolean                                                      |
- * | mwiDiscard: Boolean                                                      |
- * | mwiMsgCount: Number                                                      |
- * | mwiActive: Boolean                                                       |
- * |                                                                          |
- * | [SMS / Message Body]                                                     |
- * | data: Array of Uint8 (available if it's 8bit encoding)                   |
- * | body: String (normal text body)                                          |
- * | fullBody: String                                                         |
- * |                                                                          |
- * | [SMS / CDMA Cellbroadcast Related]                                       |
- * | serviceCategory: Number                                                  |
- * | language: String                                                         |
- * |                                                                          |
- * | [MMS Info]                                                               |
- * | receivers: Array of String                                               |
- * | phoneNumber: String                                                      |
- * | transactionIdIndex: String                                               |
- * | envelopeIdIndex: String                                                  |
- * | isReadReportSent: Boolean                                                |
- * | deliveryInfo: Array of {                                                 |
- * |   receiver: String                                                       |
- * |   deliveryStatus: String                                                 |
- * |   deliveryTimestamp: Number                                              |
- * |   readStatus: String                                                     |
- * |   readTimestamp: Number                                                  |
- * | }                                                                        |
- * | headers: {                                                               |
- * |   x-mms-message-type: Number                                             |
- * |   x-mms-transaction-id: String                                           |
- * |   x-mms-mms-version: Number                                              |
- * |   from: {                                                                |
- * |     address: String                                                      |
- * |     type: String                                                         |
- * |   }                                                                      |
- * |   subject: String                                                        |
- * |   x-mms-message-class: String                                            |
- * |   x-mms-message-size: Number                                             |
- * |   x-mms-expiry: Number                                                   |
- * |   x-mms-content-location: {                                              |
- * |     uri: String                                                          |
- * |   }                                                                      |
- * |   to: Array of {                                                         |
- * |     address: String                                                      |
- * |     type: String                                                         |
- * |   }                                                                      |
- * |   x-mms-read-report: Boolean                                             |
- * |   x-mms-priority: Number                                                 |
- * |   message-id: String                                                     |
- * |   date: String                                                           |
- * |   x-mms-delivery-report: Boolean                                         |
- * |   content-type: {                                                        |
- * |     media: String                                                        |
- * |     params: {                                                            |
- * |       type: String                                                       |
- * |       start: String                                                      |
- * |     }                                                                    |
- * |   }                                                                      |
- * | }                                                                        |
- * | parts: Array of {                                                        |
- * |    index: Number                                                         |
- * |    headers: {                                                            |
- * |      content-type: {                                                     |
- * |        media: String                                                     |
- * |        params: {                                                         |
- * |          name: String                                                    |
- * |          charset: {                                                      |
- * |            charset: String                                               |
- * |          }                                                               |
- * |        }                                                                 |
- * |      content-length: Number                                              |
- * |      content-location: String                                            |
- * |      content-id: String                                                  |
- * |    }                                                                     |
- * |    content: String                                                       |
- * | }                                                                        |
- * +--------------------------------------------------------------------------+
- * </pre>
- */
-
-/**
- * @typedef {Object} MobileMessageDB.ThreadRecord
- *
- * Represents a message thread.
- *
- * <pre>
- * +---------------------------------------+
- * | ThreadRecord                          |
- * +---------------------------------------+
- * | id: Number (primary-key)              |
- * | participantIds: Array of Number       |
- * | participantAddresses: Array of String |
- * | lastMessageId: Number                 |
- * | lastTimestamp: Number                 |
- * | unreadCount: Number                   |
- * | lastMessageType: String               |
- * |                                       |
- * | [SMS Only]                            |
- * | body: String                          |
- * |                                       |
- * | [MMS Only]                            |
- * | lastMessageSubject: String            |
- * +---------------------------------------+
- * </pre>
- */
-
-/**
- * @typedef {Object} MobileMessageDB.ParticipantRecord
- *
- * Represents the mapping of a participant and one or multiple addresses.
- * (National and Int'l numbers)
- *
- * <pre>
- * +----------------------------+
- * | ParticipantRecord          |
- * +----------------------------+
- * | id: Number (primary-key)   |
- * | addresses: Array of String |
- * +----------------------------+
- * </pre>
- */
-
-/**
- * @typedef {Object} MobileMessageDB.SmsSegmentRecord
- *
- * Represents a SMS segment.
- *
- * <pre>
- * +---------------------------------------------------------------+
- * | SmsSegmentRecord                                              |
- * +---------------------------------------------------------------+
- * | [Common Fields in SMS segment]                                |
- * | messageType: Number                                           |
- * | teleservice: Number                                           |
- * | SMSC: String                                                  |
- * | sentTimestamp: Number                                         |
- * | timestamp: Number                                             |
- * | sender: String                                                |
- * | pid: Number                                                   |
- * | encoding: Number                                              |
- * | messageClass: String                                          |
- * | iccId: String                                                 |
- * |                                                               |
- * | [Concatenation Info]                                          |
- * | segmentRef: Number                                            |
- * | segmentSeq: Number                                            |
- * | segmentMaxSeq: Number                                         |
- * |                                                               |
- * | [Application Port Info]                                       |
- * | originatorPort: Number                                        |
- * | destinationPort: Number                                       |
- * |                                                               |
- * | [MWI Status]                                                  |
- * | mwiPresent: Boolean                                           |
- * | mwiDiscard: Boolean                                           |
- * | mwiMsgCount: Number                                           |
- * | mwiActive: Boolean                                            |
- * |                                                               |
- * | [CDMA Cell Broadcast Related Fields]                          |
- * | serviceCategory: Number                                       |
- * | language: String                                              |
- * |                                                               |
- * | [Message Body]                                                |
- * | data: Array of Uint8 (available if it's 8bit encoding)        |
- * | body: String (normal text body)                               |
- * |                                                               |
- * | [Handy Fields Created by DB for Concatenation]                |
- * | id: Number (primary-key)                                      |
- * | hash: String // Use to identify the segments to the same SMS. |
- * | receivedSegments: Number                                      |
- * | segments: Array                                               |
- * +---------------------------------------------------------------+
- * </pre>
- */
-
-/**
- * @class MobileMessageDB
- * @classdesc
- *
- * <p>
- * MobileMessageDB is used to store all SMS / MMS messages, as well as the
- * threads those messages belong to, and the participants of those messages.
- * </p>
- *
- * <p>
- * The relations between threads, messages and participants can be described as
- * the following ERD -- each thread consists of one or many messages, and
- * consists of one or many participants. A participant resolves to one or many
- * (usually up to 2) addresses -- which represent different formats of the same
- * address, for example a national number and an international number.
- * </p>
- *
- * <pre>
- *                      X
- *                     / \
- * +-----------+      /   \       +-----------+
- * |           |     /     \     /|           |
- * |  thread   |-|--|consist|--|--|participant|
- * |           |     \  of /     \|           |
- * +-----------+      \   /       +-----------+
- *       |             \ /              |
- *       -              V               -
- *       |                              |
- *       |                              |
- *       X                              X
- *      / \                            / \
- *     /   \                          /   \
- *    /     \                        /     \
- *   |consist|                      |resolve|
- *    \  of /                        \  to /
- *     \   /                          \   /
- *      \ /                            \ /
- *       V                              V
- *       |                              |
- *       |                              |
- *       -                              -
- *       |                              |
- *      /|\                            /|\
- * +-----------+                  +-----------+
- * |           |                  |           |
- * |  message  |                  |  address  |
- * |           |                  |           |
- * +-----------+                  +-----------+
- * </pre>
- *
- * <p>
- * There are 4 object stores in use: </br>
- * 1. MESSAGE_STORE: stores {@link MobileMessageDB.MessageRecord}. </br>
- * 2. THREAD_STORE: stores {@link MobileMessageDB.ThreadRecord}. </br>
- * 3. PARTICIPANT_STORE: stores {@link MobileMessageDB.ParticipantRecord}. </br>
- * 4. SMS_SEGMENT_STORE: stores partial incoming SMS segments defined in
- * {@link MobileMessageDB.SmsSegmentRecord}. The records are deleted as soon as
- * it's enough to compose a complete SMS message.
- * </p>
- *
- * <p>
- * Besides all object stores mentioned above, there was a MOST_RECENT_STORE
- * which is deprecated and no longer in use.
- * </p>
- */
-this.MobileMessageDB = function() {};
-MobileMessageDB.prototype = {
-  dbName: null,
-  dbVersion: null,
-
-  /**
-   * Cache the DB instance.
-   *
-   * @member {IDBDatabase} MobileMessageDB.db
-   * @private
-   */
-  db: null,
-
-  /**
-   * Last sms/mms object store key value in the database.
-   *
-   * @member {number} MobileMessageDB.lastMessageId
-   * @private
-   */
-  lastMessageId: 0,
-
-  /**
-   * @callback MobileMessageDB.EnsureDBCallback
-   * @param {number} aErrorCode
-   *        The error code on failure, or <code>null</code> on success.
-   * @param {IDBDatabase} aDatabase
-   *        The ready-to-use database object on success.
-   */
-
-  /**
-   * Prepare the database. This may include opening the database and upgrading
-   * it to the latest schema version.
-   *
-   * @function MobileMessageDB.ensureDB
-   * @param {MobileMessageDB.EnsureDBCallback} callback
-   *        Function that takes an error and db argument. It is called when
-   *        the database is ready to use or if an error occurs while preparing
-   *        the database.
-   */
-  ensureDB: function(callback) {
-    if (this.db) {
-      if (DEBUG) debug("ensureDB: already have a database, returning early.");
-      callback(null, this.db);
-      return;
-    }
-
-    let self = this;
-    function gotDB(db) {
-      self.db = db;
-      callback(null, db);
-    }
-
-    let request = indexedDB.open(this.dbName, this.dbVersion);
-    request.onsuccess = function(event) {
-      if (DEBUG) debug("Opened database:", self.dbName, self.dbVersion);
-      gotDB(event.target.result);
-    };
-    request.onupgradeneeded = function(event) {
-      if (DEBUG) {
-        debug("Database needs upgrade:", self.dbName,
-              event.oldVersion, event.newVersion);
-        debug("Correct new database version:", event.newVersion == self.dbVersion);
-      }
-
-      let db = event.target.result;
-
-      let currentVersion = event.oldVersion;
-
-      function update(currentVersion) {
-        if (currentVersion >= self.dbVersion) {
-          if (DEBUG) debug("Upgrade finished.");
-          return;
-        }
-
-        let next = update.bind(self, currentVersion + 1);
-        switch (currentVersion) {
-          case 0:
-            if (DEBUG) debug("New database");
-            self.createSchema(db, next);
-            break;
-          case 1:
-            if (DEBUG) debug("Upgrade to version 2. Including `read` index");
-            self.upgradeSchema(event.target.transaction, next);
-            break;
-          case 2:
-            if (DEBUG) debug("Upgrade to version 3. Fix existing entries.");
-            self.upgradeSchema2(event.target.transaction, next);
-            break;
-          case 3:
-            if (DEBUG) debug("Upgrade to version 4. Add quick threads view.");
-            self.upgradeSchema3(db, event.target.transaction, next);
-            break;
-          case 4:
-            if (DEBUG) debug("Upgrade to version 5. Populate quick threads view.");
-            self.upgradeSchema4(event.target.transaction, next);
-            break;
-          case 5:
-            if (DEBUG) debug("Upgrade to version 6. Use PhonenumberJS.");
-            self.upgradeSchema5(event.target.transaction, next);
-            break;
-          case 6:
-            if (DEBUG) debug("Upgrade to version 7. Use multiple entry indexes.");
-            self.upgradeSchema6(event.target.transaction, next);
-            break;
-          case 7:
-            if (DEBUG) debug("Upgrade to version 8. Add participant/thread stores.");
-            self.upgradeSchema7(db, event.target.transaction, next);
-            break;
-          case 8:
-            if (DEBUG) debug("Upgrade to version 9. Add transactionId index for incoming MMS.");
-            self.upgradeSchema8(event.target.transaction, next);
-            break;
-          case 9:
-            if (DEBUG) debug("Upgrade to version 10. Upgrade type if it's not existing.");
-            self.upgradeSchema9(event.target.transaction, next);
-            break;
-          case 10:
-            if (DEBUG) debug("Upgrade to version 11. Add last message type into threadRecord.");
-            self.upgradeSchema10(event.target.transaction, next);
-            break;
-          case 11:
-            if (DEBUG) debug("Upgrade to version 12. Add envelopeId index for outgoing MMS.");
-            self.upgradeSchema11(event.target.transaction, next);
-            break;
-          case 12:
-            if (DEBUG) debug("Upgrade to version 13. Replaced deliveryStatus by deliveryInfo.");
-            self.upgradeSchema12(event.target.transaction, next);
-            break;
-          case 13:
-            if (DEBUG) debug("Upgrade to version 14. Fix the wrong participants.");
-            // A workaround to check if we need to re-upgrade the DB schema 12. We missed this
-            // because we didn't properly uplift that logic to b2g_v1.2 and errors could happen
-            // when migrating b2g_v1.2 to b2g_v1.3. Please see Bug 960741 for details.
-            self.needReUpgradeSchema12(event.target.transaction, function(isNeeded) {
-              if (isNeeded) {
-                self.upgradeSchema12(event.target.transaction, function() {
-                  self.upgradeSchema13(event.target.transaction, next);
-                });
-              } else {
-                self.upgradeSchema13(event.target.transaction, next);
-              }
-            });
-            break;
-          case 14:
-            if (DEBUG) debug("Upgrade to version 15. Add deliveryTimestamp.");
-            self.upgradeSchema14(event.target.transaction, next);
-            break;
-          case 15:
-            if (DEBUG) debug("Upgrade to version 16. Add ICC ID for each message.");
-            self.upgradeSchema15(event.target.transaction, next);
-            break;
-          case 16:
-            if (DEBUG) debug("Upgrade to version 17. Add isReadReportSent for incoming MMS.");
-            self.upgradeSchema16(event.target.transaction, next);
-            break;
-          case 17:
-            if (DEBUG) debug("Upgrade to version 18. Add last message subject into threadRecord.");
-            self.upgradeSchema17(event.target.transaction, next);
-            break;
-          case 18:
-            if (DEBUG) debug("Upgrade to version 19. Add pid for incoming SMS.");
-            self.upgradeSchema18(event.target.transaction, next);
-            break;
-          case 19:
-            if (DEBUG) debug("Upgrade to version 20. Add readStatus and readTimestamp.");
-            self.upgradeSchema19(event.target.transaction, next);
-            break;
-          case 20:
-            if (DEBUG) debug("Upgrade to version 21. Add sentTimestamp.");
-            self.upgradeSchema20(event.target.transaction, next);
-            break;
-          case 21:
-            if (DEBUG) debug("Upgrade to version 22. Add sms-segment store.");
-            self.upgradeSchema21(db, event.target.transaction, next);
-            break;
-          case 22:
-            if (DEBUG) debug("Upgrade to version 23. Add type information to receivers and to");
-            self.upgradeSchema22(event.target.transaction, next);
-            break;
-          default:
-            event.target.transaction.abort();
-            if (DEBUG) debug("unexpected db version: " + event.oldVersion);
-            callback(Cr.NS_ERROR_FAILURE, null);
-            break;
-        }
-      }
-
-      update(currentVersion);
-    };
-    request.onerror = function(event) {
-      // TODO look at event.target.Code and change error constant accordingly.
-      if (DEBUG) debug("Error opening database!");
-      callback(Cr.NS_ERROR_FAILURE, null);
-    };
-    request.onblocked = function(event) {
-      if (DEBUG) debug("Opening database request is blocked.");
-      callback(Cr.NS_ERROR_FAILURE, null);
-    };
-  },
-
-  /**
-   * @callback MobileMessageDB.NewTxnCallback
-   * @param {number} aErrorCode
-   *        The error code on failure, or <code>null</code> on success.
-   * @param {IDBTransaction} aTransaction
-   *        The transaction object to operate the indexedDB on success.
-   * @param {IDBObjectStore|IDBObjectStore[]} aObjectStores
-   *        The object store(s) on success. If only one object store is passed,
-   *        it's passed as an <code>IDBObjectStore</code>; Otherwise, it's
-   *        <code>IDBObjectStore[]</code>.
-   */
-
-  /**
-   * Start a new transaction.
-   *
-   * @function MobileMessageDB.newTxn
-   * @param {string} txn_type
-   *        Type of transaction (e.g. READ_WRITE)
-   * @param {MobileMessageDB.NewTxnCallback} callback
-   *        Function to call when the transaction is available. It will
-   *        be invoked with the transaction and opened object stores.
-   * @param {string[]} [storeNames=[{@link MobileMessageDB.MESSAGE_STORE_NAME}]]
-   *        Names of the stores to open.
-   */
-  newTxn: function(txn_type, callback, storeNames) {
-    if (!storeNames) {
-      storeNames = [MESSAGE_STORE_NAME];
-    }
-    if (DEBUG) debug("Opening transaction for object stores: " + storeNames);
-    let self = this;
-    this.ensureDB(function(error, db) {
-      if (error) {
-        if (DEBUG) debug("Could not open database: " + error);
-        callback(error);
-        return;
-      }
-      let txn = db.transaction(storeNames, txn_type);
-      if (DEBUG) debug("Started transaction " + txn + " of type " + txn_type);
-      if (DEBUG) {
-        txn.oncomplete = function(event) {
-          debug("Transaction " + txn + " completed.");
-        };
-        txn.onerror = function(event) {
-          // TODO check event.target.error.name and show an appropiate error
-          // message according to it.
-          debug("Error occurred during transaction: " + event.target.error.name);
-        };
-      }
-      let stores;
-      if (storeNames.length == 1) {
-        if (DEBUG) debug("Retrieving object store " + storeNames[0]);
-        stores = txn.objectStore(storeNames[0]);
-      } else {
-        stores = [];
-        for (let storeName of storeNames) {
-          if (DEBUG) debug("Retrieving object store " + storeName);
-          stores.push(txn.objectStore(storeName));
-        }
-      }
-      callback(null, txn, stores);
-    });
-  },
-
-  /**
-   * @callback MobileMessageDB.InitCallback
-   * @param {number} aErrorCode
-   *        The error code on failure, or <code>null</code> on success.
-   */
-
-  /**
-   * Initialize this MobileMessageDB.
-   *
-   * @function MobileMessageDB.init
-   * @param {string} aDbName
-   *        A string name for that database.
-   * @param {number} aDbVersion
-   *        The version that mmdb should upgrade to. 0 for the latest version.
-   * @param {MobileMessageDB.InitCallback} aCallback
-   *        A function when either the initialization transaction is completed
-   *        or any error occurs.  Should take only one argument -- null when
-   *        initialized with success or the error object otherwise.
-   */
-  init: function(aDbName, aDbVersion, aCallback) {
-    this.dbName = aDbName;
-    this.dbVersion = aDbVersion || DB_VERSION;
-
-    let self = this;
-    this.newTxn(READ_ONLY, function(error, txn, messageStore){
-      if (error) {
-        if (aCallback) {
-          aCallback(error);
-        }
-        return;
-      }
-
-      if (aCallback) {
-        txn.oncomplete = function() {
-          aCallback(null);
-        };
-      }
-
-      // In order to get the highest key value, we open a key cursor in reverse
-      // order and get only the first pointed value.
-      let request = messageStore.openCursor(null, PREV);
-      request.onsuccess = function(event) {
-        let cursor = event.target.result;
-        if (!cursor) {
-          if (DEBUG) {
-            debug("Could not get the last key from mobile message database. " +
-                  "Probably empty database");
-          }
-          return;
-        }
-        self.lastMessageId = cursor.key || 0;
-        if (DEBUG) debug("Last assigned message ID was " + self.lastMessageId);
-      };
-      request.onerror = function(event) {
-        if (DEBUG) {
-          debug("Could not get the last key from mobile message database " +
-                event.target.error.name);
-        }
-      };
-    });
-  },
-
-  /**
-   * Close the MobileMessageDB.
-   *
-   * @function MobileMessageDB.close
-   */
-  close: function() {
-    if (!this.db) {
-      return;
-    }
-
-    this.db.close();
-    this.db = null;
-    this.lastMessageId = 0;
-  },
-
-  /**
-   * Sometimes user might reboot or remove battery while sending/receiving
-   * message. This function set the status of message records to error. The
-   * function can be used as the callback of {@link MobileMessageDB.init}.
-   *
-   * @function MobileMessageDB.updatePendingTransactionToError
-   * @param {number} aError
-   *        The function does nothing if <code>aError</code> is not
-   *        <code>null</code>.
-   */
-  updatePendingTransactionToError: function(aError) {
-    if (aError) {
-      return;
-    }
-
-    this.newTxn(READ_WRITE, function(error, txn, messageStore) {
-      if (error) {
-        return;
-      }
-
-      let deliveryIndex = messageStore.index("delivery");
-
-      // Set all 'delivery: sending' records to 'delivery: error' and 'deliveryStatus:
-      // error'.
-      let keyRange = IDBKeyRange.bound([DELIVERY_SENDING, 0], [DELIVERY_SENDING, ""]);
-      let cursorRequestSending = deliveryIndex.openCursor(keyRange);
-      cursorRequestSending.onsuccess = function(event) {
-        let messageCursor = event.target.result;
-        if (!messageCursor) {
-          return;
-        }
-
-        let messageRecord = messageCursor.value;
-
-        // Set delivery to error.
-        messageRecord.delivery = DELIVERY_ERROR;
-        messageRecord.deliveryIndex = [DELIVERY_ERROR, messageRecord.timestamp];
-
-        if (messageRecord.type == "sms") {
-          messageRecord.deliveryStatus = DELIVERY_STATUS_ERROR;
-        } else {
-          // Set delivery status to error.
-          for (let i = 0; i < messageRecord.deliveryInfo.length; i++) {
-            messageRecord.deliveryInfo[i].deliveryStatus = DELIVERY_STATUS_ERROR;
-          }
-        }
-
-        messageCursor.update(messageRecord);
-        messageCursor.continue();
-      };
-
-      // Set all 'delivery: not-downloaded' and 'deliveryStatus: pending'
-      // records to 'delivery: not-downloaded' and 'deliveryStatus: error'.
-      keyRange = IDBKeyRange.bound([DELIVERY_NOT_DOWNLOADED, 0], [DELIVERY_NOT_DOWNLOADED, ""]);
-      let cursorRequestNotDownloaded = deliveryIndex.openCursor(keyRange);
-      cursorRequestNotDownloaded.onsuccess = function(event) {
-        let messageCursor = event.target.result;
-        if (!messageCursor) {
-          return;
-        }
-
-        let messageRecord = messageCursor.value;
-
-        // We have no "not-downloaded" SMS messages.
-        if (messageRecord.type == "sms") {
-          messageCursor.continue();
-          return;
-        }
-
-        // Set delivery status to error.
-        let deliveryInfo = messageRecord.deliveryInfo;
-        if (deliveryInfo.length == 1 &&
-            deliveryInfo[0].deliveryStatus == DELIVERY_STATUS_PENDING) {
-          deliveryInfo[0].deliveryStatus = DELIVERY_STATUS_ERROR;
-        }
-
-        messageCursor.update(messageRecord);
-        messageCursor.continue();
-      };
-    });
-  },
-
-  /**
-   * Create the initial database schema.
-   *
-   * TODO need to worry about number normalization somewhere...
-   * TODO full text search on body???
-   */
-  createSchema: function(db, next) {
-    // This messageStore holds the main mobile message data.
-    let messageStore = db.createObjectStore(MESSAGE_STORE_NAME, { keyPath: "id" });
-    messageStore.createIndex("timestamp", "timestamp", { unique: false });
-    if (DEBUG) debug("Created object stores and indexes");
-    next();
-  },
-
-  /**
-   * Upgrade to the corresponding database schema version.
-   */
-  upgradeSchema: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-    messageStore.createIndex("read", "read", { unique: false });
-    next();
-  },
-
-  upgradeSchema2: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      messageRecord.messageClass = MESSAGE_CLASS_NORMAL;
-      messageRecord.deliveryStatus = DELIVERY_STATUS_NOT_APPLICABLE;
-      cursor.update(messageRecord);
-      cursor.continue();
-    };
-  },
-
-  upgradeSchema3: function(db, transaction, next) {
-    // Delete redundant "id" index.
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-    if (messageStore.indexNames.contains("id")) {
-      messageStore.deleteIndex("id");
-    }
-
-    /**
-     * This mostRecentStore can be used to quickly construct a thread view of
-     * the mobile message database. Each entry looks like this:
-     *
-     * { senderOrReceiver: <String> (primary key),
-     *   id: <Number>,
-     *   timestamp: <Date>,
-     *   body: <String>,
-     *   unreadCount: <Number> }
-     *
-     */
-    let mostRecentStore = db.createObjectStore(MOST_RECENT_STORE_NAME,
-                                               { keyPath: "senderOrReceiver" });
-    mostRecentStore.createIndex("timestamp", "timestamp");
-    next();
-  },
-
-  upgradeSchema4: function(transaction, next) {
-    let threads = {};
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-    let mostRecentStore = transaction.objectStore(MOST_RECENT_STORE_NAME);
-
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        for (let thread in threads) {
-          mostRecentStore.put(threads[thread]);
-        }
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      let contact = messageRecord.sender || messageRecord.receiver;
-
-      if (contact in threads) {
-        let thread = threads[contact];
-        if (!messageRecord.read) {
-          thread.unreadCount++;
-        }
-        if (messageRecord.timestamp > thread.timestamp) {
-          thread.id = messageRecord.id;
-          thread.body = messageRecord.body;
-          thread.timestamp = messageRecord.timestamp;
-        }
-      } else {
-        threads[contact] = {
-          senderOrReceiver: contact,
-          id: messageRecord.id,
-          timestamp: messageRecord.timestamp,
-          body: messageRecord.body,
-          unreadCount: messageRecord.read ? 0 : 1
-        };
-      }
-      cursor.continue();
-    };
-  },
-
-  upgradeSchema5: function(transaction, next) {
-    // Don't perform any upgrade. See Bug 819560.
-    next();
-  },
-
-  upgradeSchema6: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-
-    // Delete "delivery" index.
-    if (messageStore.indexNames.contains("delivery")) {
-      messageStore.deleteIndex("delivery");
-    }
-    // Delete "sender" index.
-    if (messageStore.indexNames.contains("sender")) {
-      messageStore.deleteIndex("sender");
-    }
-    // Delete "receiver" index.
-    if (messageStore.indexNames.contains("receiver")) {
-      messageStore.deleteIndex("receiver");
-    }
-    // Delete "read" index.
-    if (messageStore.indexNames.contains("read")) {
-      messageStore.deleteIndex("read");
-    }
-
-    // Create new "delivery", "number" and "read" indexes.
-    messageStore.createIndex("delivery", "deliveryIndex");
-    messageStore.createIndex("number", "numberIndex", { multiEntry: true });
-    messageStore.createIndex("read", "readIndex");
-
-    // Populate new "deliverIndex", "numberIndex" and "readIndex" attributes.
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      let timestamp = messageRecord.timestamp;
-      messageRecord.deliveryIndex = [messageRecord.delivery, timestamp];
-      messageRecord.numberIndex = [
-        [messageRecord.sender, timestamp],
-        [messageRecord.receiver, timestamp]
-      ];
-      messageRecord.readIndex = [messageRecord.read, timestamp];
-      cursor.update(messageRecord);
-      cursor.continue();
-    };
-  },
-
-  /**
-   * Add participant/thread stores.
-   *
-   * The message store now saves original phone numbers/addresses input from
-   * content to message records. No normalization is made.
-   *
-   * For filtering messages by phone numbers, it first looks up corresponding
-   * participant IDs from participant table and fetch message records with
-   * matching keys defined in per record "participantIds" field.
-   *
-   * For message threading, messages with the same participant ID array are put
-   * in the same thread. So updating "unreadCount", "lastMessageId" and
-   * "lastTimestamp" are through the "threadId" carried by per message record.
-   * Fetching threads list is now simply walking through the thread sotre. The
-   * "mostRecentStore" is dropped.
-   */
-  upgradeSchema7: function(db, transaction, next) {
-    /**
-     * This "participant" object store keeps mappings of multiple phone numbers
-     * of the same recipient to an integer participant id. Each entry looks
-     * like:
-     *
-     * { id: <Number> (primary key),
-     *   addresses: <Array of strings> }
-     */
-    let participantStore = db.createObjectStore(PARTICIPANT_STORE_NAME,
-                                                { keyPath: "id",
-                                                  autoIncrement: true });
-    participantStore.createIndex("addresses", "addresses", { multiEntry: true });
-
-    /**
-     * This "threads" object store keeps mappings from an integer thread id to
-     * ids of the participants of that message thread. Each entry looks like:
-     *
-     * { id: <Number> (primary key),
-     *   participantIds: <Array of participant IDs>,
-     *   participantAddresses: <Array of the first addresses of the participants>,
-     *   lastMessageId: <Number>,
-     *   lastTimestamp: <Date>,
-     *   subject: <String>,
-     *   unreadCount: <Number> }
-     *
-     */
-    let threadStore = db.createObjectStore(THREAD_STORE_NAME,
-                                           { keyPath: "id",
-                                             autoIncrement: true });
-    threadStore.createIndex("participantIds", "participantIds");
-    threadStore.createIndex("lastTimestamp", "lastTimestamp");
-
-    /**
-     * Replace "numberIndex" with "participantIdsIndex" and create an additional
-     * "threadId". "numberIndex" will be removed later.
-     */
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-    messageStore.createIndex("threadId", "threadIdIndex");
-    messageStore.createIndex("participantIds", "participantIdsIndex",
-                             { multiEntry: true });
-
-    // Now populate participantStore & threadStore.
-    let mostRecentStore = transaction.objectStore(MOST_RECENT_STORE_NAME);
-    let self = this;
-    let mostRecentRequest = mostRecentStore.openCursor();
-    mostRecentRequest.onsuccess = function(event) {
-      let mostRecentCursor = event.target.result;
-      if (!mostRecentCursor) {
-        db.deleteObjectStore(MOST_RECENT_STORE_NAME);
-
-        // No longer need the "number" index in messageStore, use
-        // "participantIds" index instead.
-        messageStore.deleteIndex("number");
-        next();
-        return;
-      }
-
-      let mostRecentRecord = mostRecentCursor.value;
-
-      // Each entry in mostRecentStore is supposed to be a unique thread, so we
-      // retrieve the records out and insert its "senderOrReceiver" column as a
-      // new record in participantStore.
-      let number = mostRecentRecord.senderOrReceiver;
-      self.findParticipantRecordByPlmnAddress(participantStore, number, true,
-                                              function(participantRecord) {
-        // Also create a new record in threadStore.
-        let threadRecord = {
-          participantIds: [participantRecord.id],
-          participantAddresses: [number],
-          lastMessageId: mostRecentRecord.id,
-          lastTimestamp: mostRecentRecord.timestamp,
-          subject: mostRecentRecord.body,
-          unreadCount: mostRecentRecord.unreadCount,
-        };
-        let addThreadRequest = threadStore.add(threadRecord);
-        addThreadRequest.onsuccess = function(event) {
-          threadRecord.id = event.target.result;
-
-          let numberRange = IDBKeyRange.bound([number, 0], [number, ""]);
-          let messageRequest = messageStore.index("number")
-                                           .openCursor(numberRange, NEXT);
-          messageRequest.onsuccess = function(event) {
-            let messageCursor = event.target.result;
-            if (!messageCursor) {
-              // No more message records, check next most recent record.
-              mostRecentCursor.continue();
-              return;
-            }
-
-            let messageRecord = messageCursor.value;
-            // Check whether the message really belongs to this thread.
-            let matchSenderOrReceiver = false;
-            if (messageRecord.delivery == DELIVERY_RECEIVED) {
-              if (messageRecord.sender == number) {
-                matchSenderOrReceiver = true;
-              }
-            } else if (messageRecord.receiver == number) {
-              matchSenderOrReceiver = true;
-            }
-            if (!matchSenderOrReceiver) {
-              // Check next message record.
-              messageCursor.continue();
-              return;
-            }
-
-            messageRecord.threadId = threadRecord.id;
-            messageRecord.threadIdIndex = [threadRecord.id,
-                                           messageRecord.timestamp];
-            messageRecord.participantIdsIndex = [
-              [participantRecord.id, messageRecord.timestamp]
-            ];
-            messageCursor.update(messageRecord);
-            // Check next message record.
-            messageCursor.continue();
-          };
-          messageRequest.onerror = function() {
-            // Error in fetching message records, check next most recent record.
-            mostRecentCursor.continue();
-          };
-        };
-        addThreadRequest.onerror = function() {
-          // Error in fetching message records, check next most recent record.
-          mostRecentCursor.continue();
-        };
-      });
-    };
-  },
-
-  /**
-   * Add transactionId index for MMS.
-   */
-  upgradeSchema8: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-
-    // Delete "transactionId" index.
-    if (messageStore.indexNames.contains("transactionId")) {
-      messageStore.deleteIndex("transactionId");
-    }
-
-    // Create new "transactionId" indexes.
-    messageStore.createIndex("transactionId", "transactionIdIndex", { unique: true });
-
-    // Populate new "transactionIdIndex" attributes.
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      if ("mms" == messageRecord.type &&
-          (DELIVERY_NOT_DOWNLOADED == messageRecord.delivery ||
-           DELIVERY_RECEIVED == messageRecord.delivery)) {
-        messageRecord.transactionIdIndex =
-          messageRecord.headers["x-mms-transaction-id"];
-        cursor.update(messageRecord);
-      }
-      cursor.continue();
-    };
-  },
-
-  upgradeSchema9: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-
-    // Update type attributes.
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      if (messageRecord.type == undefined) {
-        messageRecord.type = "sms";
-        cursor.update(messageRecord);
-      }
-      cursor.continue();
-    };
-  },
-
-  upgradeSchema10: function(transaction, next) {
-    let threadStore = transaction.objectStore(THREAD_STORE_NAME);
-
-    // Add 'lastMessageType' to each thread record.
-    threadStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let threadRecord = cursor.value;
-      let lastMessageId = threadRecord.lastMessageId;
-      let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-      let request = messageStore.mozGetAll(lastMessageId);
-
-      request.onsuccess = function() {
-        let messageRecord = request.result[0];
-        if (!messageRecord) {
-          if (DEBUG) debug("Message ID " + lastMessageId + " not found");
-          return;
-        }
-        if (messageRecord.id != lastMessageId) {
-          if (DEBUG) {
-            debug("Requested message ID (" + lastMessageId + ") is different from" +
-                  " the one we got");
-          }
-          return;
-        }
-        threadRecord.lastMessageType = messageRecord.type;
-        cursor.update(threadRecord);
-        cursor.continue();
-      };
-
-      request.onerror = function(event) {
-        if (DEBUG) {
-          if (event.target) {
-            debug("Caught error on transaction", event.target.error.name);
-          }
-        }
-        cursor.continue();
-      };
-    };
-  },
-
-  /**
-   * Add envelopeId index for MMS.
-   */
-  upgradeSchema11: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-
-    // Delete "envelopeId" index.
-    if (messageStore.indexNames.contains("envelopeId")) {
-      messageStore.deleteIndex("envelopeId");
-    }
-
-    // Create new "envelopeId" indexes.
-    messageStore.createIndex("envelopeId", "envelopeIdIndex", { unique: true });
-
-    // Populate new "envelopeIdIndex" attributes.
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      if (messageRecord.type == "mms" &&
-          messageRecord.delivery == DELIVERY_SENT) {
-        messageRecord.envelopeIdIndex = messageRecord.headers["message-id"];
-        cursor.update(messageRecord);
-      }
-      cursor.continue();
-    };
-  },
-
-  /**
-   * Replace deliveryStatus by deliveryInfo.
-   */
-  upgradeSchema12: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      if (messageRecord.type == "mms") {
-        messageRecord.deliveryInfo = [];
-
-        if (messageRecord.deliveryStatus.length == 1 &&
-            (messageRecord.delivery == DELIVERY_NOT_DOWNLOADED ||
-             messageRecord.delivery == DELIVERY_RECEIVED)) {
-          messageRecord.deliveryInfo.push({
-            receiver: null,
-            deliveryStatus: messageRecord.deliveryStatus[0] });
-        } else {
-          for (let i = 0; i < messageRecord.deliveryStatus.length; i++) {
-            messageRecord.deliveryInfo.push({
-              receiver: messageRecord.receivers[i],
-              deliveryStatus: messageRecord.deliveryStatus[i] });
-          }
-        }
-        delete messageRecord.deliveryStatus;
-        cursor.update(messageRecord);
-      }
-      cursor.continue();
-    };
-  },
-
-  /**
-   * Check if we need to re-upgrade the DB schema 12.
-   */
-  needReUpgradeSchema12: function(transaction, callback) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        callback(false);
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      if (messageRecord.type == "mms" &&
-          messageRecord.deliveryInfo === undefined) {
-        callback(true);
-        return;
-      }
-      cursor.continue();
-    };
-  },
-
-  /**
-   * Fix the wrong participants.
-   */
-  upgradeSchema13: function(transaction, next) {
-    let participantStore = transaction.objectStore(PARTICIPANT_STORE_NAME);
-    let threadStore = transaction.objectStore(THREAD_STORE_NAME);
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-    let self = this;
-
-    let isInvalid = function(participantRecord) {
-      let entries = [];
-      for (let addr of participantRecord.addresses) {
-        entries.push({
-          normalized: addr,
-          parsed: PhoneNumberUtils.parseWithMCC(addr, null)
-        })
-      }
-      for (let ix = 0 ; ix < entries.length - 1; ix++) {
-        let entry1 = entries[ix];
-        for (let iy = ix + 1 ; iy < entries.length; iy ++) {
-          let entry2 = entries[iy];
-          if (!self.matchPhoneNumbers(entry1.normalized, entry1.parsed,
-                                      entry2.normalized, entry2.parsed)) {
-            return true;
-          }
-        }
-      }
-      return false;
-    };
-
-    let invalidParticipantIds = [];
-    participantStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (cursor) {
-        let participantRecord = cursor.value;
-        // Check if this participant record is valid
-        if (isInvalid(participantRecord)) {
-          invalidParticipantIds.push(participantRecord.id);
-          cursor.delete();
-        }
-        cursor.continue();
-        return;
-      }
-
-      // Participant store cursor iteration done.
-      if (!invalidParticipantIds.length) {
-        next();
-        return;
-      }
-
-      // Find affected thread.
-      let wrongThreads = [];
-      threadStore.openCursor().onsuccess = function(event) {
-        let threadCursor = event.target.result;
-        if (threadCursor) {
-          let threadRecord = threadCursor.value;
-          let participantIds = threadRecord.participantIds;
-          let foundInvalid = false;
-          for (let invalidParticipantId of invalidParticipantIds) {
-            if (participantIds.indexOf(invalidParticipantId) != -1) {
-              foundInvalid = true;
-              break;
-            }
-          }
-          if (foundInvalid) {
-            wrongThreads.push(threadRecord.id);
-            threadCursor.delete();
-          }
-          threadCursor.continue();
-          return;
-        }
-
-        if (!wrongThreads.length) {
-          next();
-          return;
-        }
-        // Use recursive function to avoid we add participant twice.
-        (function createUpdateThreadAndParticipant(ix) {
-          let threadId = wrongThreads[ix];
-          let range = IDBKeyRange.bound([threadId, 0], [threadId, ""]);
-          messageStore.index("threadId").openCursor(range).onsuccess = function(event) {
-            let messageCursor = event.target.result;
-            if (!messageCursor) {
-              ix++;
-              if (ix === wrongThreads.length) {
-                next();
-                return;
-              }
-              createUpdateThreadAndParticipant(ix);
-              return;
-            }
-
-            let messageRecord = messageCursor.value;
-            let timestamp = messageRecord.timestamp;
-            let threadParticipants = [];
-            // Recaculate the thread participants of received message.
-            if (messageRecord.delivery === DELIVERY_RECEIVED ||
-                messageRecord.delivery === DELIVERY_NOT_DOWNLOADED) {
-              threadParticipants.push(messageRecord.sender);
-              if (messageRecord.type == "mms") {
-                this.fillReceivedMmsThreadParticipants(messageRecord, threadParticipants);
-              }
-            }
-            // Recaculate the thread participants of sent messages and error
-            // messages. In error sms messages, we don't have error received sms.
-            // In received MMS, we don't update the error to deliver field but
-            // deliverStatus. So we only consider sent message in DELIVERY_ERROR.
-            else if (messageRecord.delivery === DELIVERY_SENT ||
-                messageRecord.delivery === DELIVERY_ERROR) {
-              if (messageRecord.type == "sms") {
-                threadParticipants = [messageRecord.receiver];
-              } else if (messageRecord.type == "mms") {
-                threadParticipants = messageRecord.receivers;
-              }
-            }
-            self.findThreadRecordByPlmnAddresses(threadStore, participantStore,
-                                                 threadParticipants, true,
-                                                 function(threadRecord,
-                                                          participantIds) {
-              if (!participantIds) {
-                debug("participantIds is empty!");
-                return;
-              }
-
-              let timestamp = messageRecord.timestamp;
-              // Setup participantIdsIndex.
-              messageRecord.participantIdsIndex = [];
-              for (let id of participantIds) {
-                messageRecord.participantIdsIndex.push([id, timestamp]);
-              }
-              if (threadRecord) {
-                let needsUpdate = false;
-
-                if (threadRecord.lastTimestamp <= timestamp) {
-                  threadRecord.lastTimestamp = timestamp;
-                  threadRecord.subject = messageRecord.body;
-                  threadRecord.lastMessageId = messageRecord.id;
-                  threadRecord.lastMessageType = messageRecord.type;
-                  needsUpdate = true;
-                }
-
-                if (!messageRecord.read) {
-                  threadRecord.unreadCount++;
-                  needsUpdate = true;
-                }
-
-                if (needsUpdate) {
-                  threadStore.put(threadRecord);
-                }
-                messageRecord.threadId = threadRecord.id;
-                messageRecord.threadIdIndex = [threadRecord.id, timestamp];
-                messageCursor.update(messageRecord);
-                messageCursor.continue();
-                return;
-              }
-
-              threadRecord = {
-                participantIds: participantIds,
-                participantAddresses: threadParticipants,
-                lastMessageId: messageRecord.id,
-                lastTimestamp: timestamp,
-                subject: messageRecord.body,
-                unreadCount: messageRecord.read ? 0 : 1,
-                lastMessageType: messageRecord.type
-              };
-              threadStore.add(threadRecord).onsuccess = function(event) {
-                let threadId = event.target.result;
-                // Setup threadId & threadIdIndex.
-                messageRecord.threadId = threadId;
-                messageRecord.threadIdIndex = [threadId, timestamp];
-                messageCursor.update(messageRecord);
-                messageCursor.continue();
-              };
-            });
-          };
-        })(0);
-      };
-    };
-  },
-
-  /**
-   * Add deliveryTimestamp.
-   */
-  upgradeSchema14: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      if (messageRecord.type == "sms") {
-        messageRecord.deliveryTimestamp = 0;
-      } else if (messageRecord.type == "mms") {
-        let deliveryInfo = messageRecord.deliveryInfo;
-        for (let i = 0; i < deliveryInfo.length; i++) {
-          deliveryInfo[i].deliveryTimestamp = 0;
-        }
-      }
-      cursor.update(messageRecord);
-      cursor.continue();
-    };
-  },
-
-  /**
-   * Add ICC ID.
-   */
-  upgradeSchema15: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      messageRecord.iccId = null;
-      cursor.update(messageRecord);
-      cursor.continue();
-    };
-  },
-
-  /**
-   * Add isReadReportSent for incoming MMS.
-   */
-  upgradeSchema16: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-
-    // Update type attributes.
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      if (messageRecord.type == "mms") {
-        messageRecord.isReadReportSent = false;
-        cursor.update(messageRecord);
-      }
-      cursor.continue();
-    };
-  },
-
-  upgradeSchema17: function(transaction, next) {
-    let threadStore = transaction.objectStore(THREAD_STORE_NAME);
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-
-    // Add 'lastMessageSubject' to each thread record.
-    threadStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let threadRecord = cursor.value;
-      // We have defined 'threadRecord.subject' in upgradeSchema7(), but it
-      // actually means 'threadRecord.body'.  Swap the two values first.
-      threadRecord.body = threadRecord.subject;
-      delete threadRecord.subject;
-
-      // Only MMS supports subject so assign null for non-MMS one.
-      if (threadRecord.lastMessageType != "mms") {
-        threadRecord.lastMessageSubject = null;
-        cursor.update(threadRecord);
-
-        cursor.continue();
-        return;
-      }
-
-      messageStore.get(threadRecord.lastMessageId).onsuccess = function(event) {
-        let messageRecord = event.target.result;
-        let subject = messageRecord.headers.subject;
-        threadRecord.lastMessageSubject = subject || null;
-        cursor.update(threadRecord);
-
-        cursor.continue();
-      };
-    };
-  },
-
-  /**
-   * Add pid for incoming SMS.
-   */
-  upgradeSchema18: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      if (messageRecord.type == "sms") {
-        messageRecord.pid = RIL.PDU_PID_DEFAULT;
-        cursor.update(messageRecord);
-      }
-      cursor.continue();
-    };
-  },
-
-  /**
-   * Add readStatus and readTimestamp.
-   */
-  upgradeSchema19: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      if (messageRecord.type == "sms") {
-        cursor.continue();
-        return;
-      }
-
-      // We can always retrieve transaction id from
-      // |messageRecord.headers["x-mms-transaction-id"]|.
-      if (messageRecord.hasOwnProperty("transactionId")) {
-        delete messageRecord.transactionId;
-      }
-
-      // xpconnect gives "undefined" for an unassigned argument of an interface
-      // method.
-      if (messageRecord.envelopeIdIndex === "undefined") {
-        delete messageRecord.envelopeIdIndex;
-      }
-
-      // Convert some header fields that were originally decoded as BooleanValue
-      // to numeric enums.
-      for (let field of ["x-mms-cancel-status",
-                         "x-mms-sender-visibility",
-                         "x-mms-read-status"]) {
-        let value = messageRecord.headers[field];
-        if (value !== undefined) {
-          messageRecord.headers[field] = value ? 128 : 129;
-        }
-      }
-
-      // For all sent and received MMS messages, we have to add their
-      // |readStatus| and |readTimestamp| attributes in |deliveryInfo| array.
-      let readReportRequested =
-        messageRecord.headers["x-mms-read-report"] || false;
-      for (let element of messageRecord.deliveryInfo) {
-        element.readStatus = readReportRequested
-                           ? MMS.DOM_READ_STATUS_PENDING
-                           : MMS.DOM_READ_STATUS_NOT_APPLICABLE;
-        element.readTimestamp = 0;
-      }
-
-      cursor.update(messageRecord);
-      cursor.continue();
-    };
-  },
-
-  /**
-   * Add sentTimestamp.
-   */
-  upgradeSchema20: function(transaction, next) {
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-    messageStore.openCursor().onsuccess = function(event) {
-      let cursor = event.target.result;
-      if (!cursor) {
-        next();
-        return;
-      }
-
-      let messageRecord = cursor.value;
-      messageRecord.sentTimestamp = 0;
-
-      // We can still have changes to assign |sentTimestamp| for the existing
-      // MMS message records.
-      if (messageRecord.type == "mms" && messageRecord.headers["date"]) {
-        messageRecord.sentTimestamp = messageRecord.headers["date"].getTime();
-      }
-
-      cursor.update(messageRecord);
-      cursor.continue();
-    };
-  },
-
-  /**
-   * Add smsSegmentStore to store uncomplete SMS segments.
-   */
-  upgradeSchema21: function(db, transaction, next) {
-    /**
-     * This smsSegmentStore is used to store uncomplete SMS segments.
-     * Each entry looks like this:
-     *
-     * {
-     *   [Common fields in SMS segment]
-     *   messageType: <Number>,
-     *   teleservice: <Number>,
-     *   SMSC: <String>,
-     *   sentTimestamp: <Number>,
-     *   timestamp: <Number>,
-     *   sender: <String>,
-     *   pid: <Number>,
-     *   encoding: <Number>,
-     *   messageClass: <String>,
-     *   iccId: <String>,
-     *
-     *   [Concatenation Info]
-     *   segmentRef: <Number>,
-     *   segmentSeq: <Number>,
-     *   segmentMaxSeq: <Number>,
-     *
-     *   [Application Port Info]
-     *   originatorPort: <Number>,
-     *   destinationPort: <Number>,
-     *
-     *   [MWI status]
-     *   mwiPresent: <Boolean>,
-     *   mwiDiscard: <Boolean>,
-     *   mwiMsgCount: <Number>,
-     *   mwiActive: <Boolean>,
-     *
-     *   [CDMA Cellbroadcast related fields]
-     *   serviceCategory: <Number>,
-     *   language: <String>,
-     *
-     *   [Message Body]
-     *   data: <Uint8Array>, (available if it's 8bit encoding)
-     *   body: <String>, (normal text body)
-     *
-     *   [Handy fields created by DB for concatenation]
-     *   id: <Number>, keypath of this objectStore.
-     *   hash: <String>, Use to identify the segments to the same SMS.
-     *   receivedSegments: <Number>,
-     *   segments: []
-     * }
-     *
-     */
-    let smsSegmentStore = db.createObjectStore(SMS_SEGMENT_STORE_NAME,
-                                               { keyPath: "id",
-                                                 autoIncrement: true });
-    smsSegmentStore.createIndex("hash", "hash", { unique: true });
-    next();
-  },
-
-  /**
-   * Change receivers format to address and type.
-   */
-  upgradeSchema22: function(transaction, next) {
-    // Since bug 871433 (DB_VERSION 11), we normalize addresses before really
-    // diving into participant store in findParticipantRecordByPlmnAddress.
-    // This also follows that all addresses stored in participant store are
-    // normalized phone numbers, although they might not be phone numbers at the
-    // first place.  So addresses in participant store are not reliable.
-    //
-    // |participantAddresses| in a thread record are reliable, but several
-    // distinct threads can be wrongly mapped into one.  For example, an IPv4
-    // address "55.252.255.54" was normalized as US phone number "5525225554".
-    // So beginning with thread store is not really a good idea.
-    //
-    // The only correct way is to begin with all messages records and check if
-    // the findThreadRecordByTypedAddresses() call using a message record's
-    // thread participants returns the same thread record with the one it
-    // currently belong to.
-
-    function getThreadParticipantsFromMessageRecord(aMessageRecord) {
-      let threadParticipants;
-
-      if (aMessageRecord.type == "sms") {
-        let address;
-        if (aMessageRecord.delivery == DELIVERY_RECEIVED) {
-          address = aMessageRecord.sender;
-        } else {
-          address = aMessageRecord.receiver;
-        }
-        threadParticipants = [{
-          address: address,
-          type: MMS.Address.resolveType(address)
-        }];
-      } else { // MMS
-        if ((aMessageRecord.delivery == DELIVERY_RECEIVED) ||
-            (aMessageRecord.delivery == DELIVERY_NOT_DOWNLOADED)) {
-          // DISABLE_MMS_GROUPING_FOR_RECEIVING is set to true at the time, so
-          // we consider only |aMessageRecord.sender|.
-          threadParticipants = [{
-            address: aMessageRecord.sender,
-            type: MMS.Address.resolveType(aMessageRecord.sender)
-          }];
-        } else {
-          threadParticipants = aMessageRecord.headers.to;
-        }
-      }
-
-      return threadParticipants;
-    }
-
-    let participantStore = transaction.objectStore(PARTICIPANT_STORE_NAME);
-    let threadStore = transaction.objectStore(THREAD_STORE_NAME);
-    let messageStore = transaction.objectStore(MESSAGE_STORE_NAME);
-
-    let invalidThreadIds = [];
-
-    let self = this;
-    let messageCursorReq = messageStore.openCursor();
-    messageCursorReq.onsuccess = function(aEvent) {
-      let messageCursor = aEvent.target.result;
-      if (messageCursor) {
-        let messageRecord = messageCursor.value;
-        let threadParticipants =
-          getThreadParticipantsFromMessageRecord(messageRecord);
-
-        // 1. If thread ID of this message record has been marked as invalid,
-        //    skip further checks and go ahead for the next one.
-        if (invalidThreadIds.indexOf(messageRecord.threadId) >= 0) {
-          messageCursor.continue();
-          return;
-        }
-
-        // 2. Check if the thread record found with the new algorithm matches
-        //    the original one.
-        self.findThreadRecordByTypedAddresses(threadStore, participantStore,
-                                              threadParticipants, true,
-                                              function(aThreadRecord,
-                                                       aParticipantIds) {
-          if (!aThreadRecord || aThreadRecord.id !== messageRecord.threadId) {
-            invalidThreadIds.push(messageRecord.threadId);
-          }
-
-          messageCursor.continue();
-        });
-
-        // Only calls |messageCursor.continue()| inside the callback of
-        // findThreadRecordByTypedAddresses() because that may inserts new
-        // participant records and hurt concurrency.
-        return;
-      } // End of |if (messageCursor)|.
-
-      // 3. If there is no any mis-grouped message found, go on to next upgrade.
-      if (!invalidThreadIds.length) {
-        next();
-        return;
-      }
-
-      // 4. Remove invalid thread records first, so that we don't have
-      //    unexpected match in findThreadRecordByTypedAddresses().
-      invalidThreadIds.forEach(function(aInvalidThreadId) {
-        threadStore.delete(aInvalidThreadId);
-      });
-
-      // 5. For each affected thread, re-create a valid thread record for it.
-      (function redoThreading(aInvalidThreadId) {
-        // 5-1. For each message record originally belongs to this thread, find
-        //      a new home for it.
-        let range = IDBKeyRange.bound([aInvalidThreadId, 0],
-                                      [aInvalidThreadId, ""]);
-        let threadMessageCursorReq = messageStore.index("threadId")
-                                                 .openCursor(range, NEXT);
-        threadMessageCursorReq.onsuccess = function(aEvent) {
-          let messageCursor = aEvent.target.result;
-
-          // 5-2. If no more message records to process in this invalid thread,
-          //      go on to next invalid thread if available, or pass to next
-          //      upgradeSchema function.
-          if (!messageCursor) {
-            if (invalidThreadIds.length) {
-              redoThreading(invalidThreadIds.shift());
-            } else {
-              next();
-            }
-            return;
-          }
-
-          let messageRecord = messageCursor.value;
-          let threadParticipants =
-            getThreadParticipantsFromMessageRecord(messageRecord);
-
-          // 5-3. Assign a thread record for this message record. Basically
-          //      copied from |realSaveRecord|, but we don't have to worry
-          //      about |updateThreadByMessageChange| because we've removed
-          //      affected threads.
-          self.findThreadRecordByTypedAddresses(threadStore, participantStore,
-                                                threadParticipants, true,
-                                                function(aThreadRecord,
-                                                         aParticipantIds) {
-            // Setup participantIdsIndex.
-            messageRecord.participantIdsIndex =
-              aParticipantIds.map(function(aParticipantId) {
-                return [aParticipantId, messageRecord.timestamp];
-              });
-
-            let threadExists = aThreadRecord ? true : false;
-            if (!threadExists) {
-              aThreadRecord = {
-                participantIds: aParticipantIds,
-                participantAddresses:
-                  threadParticipants.map(function(aTypedAddress) {
-                    return aTypedAddress.address;
-                  }),
-                unreadCount: 0,
-                lastTimestamp: -1
-              };
-            }
-
-            let needsUpdate = false;
-            if (aThreadRecord.lastTimestamp <= messageRecord.timestamp) {
-              let lastMessageSubject;
-              if (messageRecord.type == "mms") {
-                lastMessageSubject = messageRecord.headers.subject;
-              }
-              aThreadRecord.lastMessageSubject = lastMessageSubject || null;
-              aThreadRecord.lastTimestamp = messageRecord.timestamp;
-              aThreadRecord.body = messageRecord.body;
-              aThreadRecord.lastMessageId = messageRecord.id;
-              aThreadRecord.lastMessageType = messageRecord.type;
-              needsUpdate = true;
-            }
-
-            if (!messageRecord.read) {
-              aThreadRecord.unreadCount++;
-              needsUpdate = true;
-            }
-
-            let updateMessageRecordThreadId = function(aThreadId) {
-              // Setup threadId & threadIdIndex.
-              messageRecord.threadId = aThreadId;
-              messageRecord.threadIdIndex = [aThreadId, messageRecord.timestamp];
-
-              messageCursor.update(messageRecord);
-              messageCursor.continue();
-            };
-
-            if (threadExists) {
-              if (needsUpdate) {
-                threadStore.put(aThreadRecord);
-              }
-              updateMessageRecordThreadId(aThreadRecord.id);
-            } else {
-              threadStore.add(aThreadRecord).onsuccess = function(aEvent) {
-                let threadId = aEvent.target.result;
-                updateMessageRecordThreadId(threadId);
-              };
-            }
-          }); // End of findThreadRecordByTypedAddresses().
-        }; // End of threadMessageCursorReq.onsuccess.
-      })(invalidThreadIds.shift()); // End of function redoThreading.
-    }; // End of messageStore.openCursor().onsuccess
-  },
-
-  /**
-   * Check if <code>addr1</code> matches <code>addr2</code>.
-   *
-   * @function MobileMessageDB.matchParsedPhoneNumbers
-   * @param {string} addr1
-   *        Normalized address 1.
-   * @param {Object} parsedAddr1
-   *        Parsed address 1.
-   * @param {string} addr2
-   *        Normalized address 2.
-   * @param {Object} parsedAddr2
-   *        Parsed address 2.
-   * @return {boolean}
-   *         <code>true</code> if the 2 addresses match.
-   */
-  matchParsedPhoneNumbers: function(addr1, parsedAddr1, addr2, parsedAddr2) {
-    if ((parsedAddr1.internationalNumber &&
-         parsedAddr1.internationalNumber === parsedAddr2.internationalNumber) ||
-        (parsedAddr1.nationalNumber &&
-         parsedAddr1.nationalNumber === parsedAddr2.nationalNumber)) {
-      return true;
-    }
-
-    if (parsedAddr1.countryName != parsedAddr2.countryName) {
-      return false;
-    }
-
-    let ssPref = "dom.phonenumber.substringmatching." + parsedAddr1.countryName;
-    if (Services.prefs.getPrefType(ssPref) != Ci.nsIPrefBranch.PREF_INT) {
-      return false;
-    }
-
-    let val = Services.prefs.getIntPref(ssPref);
-    return addr1.length > val &&
-           addr2.length > val &&
-           addr1.slice(-val) === addr2.slice(-val);
-  },
-
-  /**
-   * Check if <code>addr1</code> matches <code>addr2</code>.
-   *
-   * @function MobileMessageDB.matchPhoneNumbers
-   * @param {string} addr1
-   *        Normalized address 1.
-   * @param {Object} parsedAddr1
-   *        Parsed address 1. Try to parse from <code>addr1</code> if not given.
-   * @param {string} addr2
-   *        Normalized address 2.
-   * @param {Object} parsedAddr2
-   *        Parsed address 2. Try to parse from <code>addr2</code> if not given.
-   * @return {boolean}
-   *         <code>true</code> if the 2 addresses match.
-   */
-  matchPhoneNumbers: function(addr1, parsedAddr1, addr2, parsedAddr2) {
-    if (parsedAddr1 && parsedAddr2) {
-      return this.matchParsedPhoneNumbers(addr1, parsedAddr1, addr2, parsedAddr2);
-    }
-
-    if (parsedAddr1) {
-      parsedAddr2 = PhoneNumberUtils.parseWithCountryName(addr2, parsedAddr1.countryName);
-      if (parsedAddr2) {
-        return this.matchParsedPhoneNumbers(addr1, parsedAddr1, addr2, parsedAddr2);
-      }
-
-      return false;
-    }
-
-    if (parsedAddr2) {
-      parsedAddr1 = PhoneNumberUtils.parseWithCountryName(addr1, parsedAddr2.countryName);
-      if (parsedAddr1) {
-        return this.matchParsedPhoneNumbers(addr1, parsedAddr1, addr2, parsedAddr2);
-      }
-    }
-
-    return false;
-  },
-
-  /**
-   * Generate a <code>nsISmsMessage</code> or
-   * <code>nsIMmsMessage</code> instance from a stored message record.
-   *
-   * @function MobileMessageDB.createDomMessageFromRecord
-   * @param {MobileMessageDB.MessageRecord} aMessageRecord
-   *        The stored message record.
-   * @return {nsISmsMessage|nsIMmsMessage}
-   */
-  createDomMessageFromRecord: function(aMessageRecord) {
-    if (DEBUG) {
-      debug("createDomMessageFromRecord: " + JSON.stringify(aMessageRecord));
-    }
-    if (aMessageRecord.type == "sms") {
-      return gMobileMessageService.createSmsMessage(aMessageRecord.id,
-                                                    aMessageRecord.threadId,
-                                                    aMessageRecord.iccId,
-                                                    aMessageRecord.delivery,
-                                                    aMessageRecord.deliveryStatus,
-                                                    aMessageRecord.sender,
-                                                    aMessageRecord.receiver,
-                                                    aMessageRecord.body,
-                                                    aMessageRecord.messageClass,
-                                                    aMessageRecord.timestamp,
-                                                    aMessageRecord.sentTimestamp,
-                                                    aMessageRecord.deliveryTimestamp,
-                                                    aMessageRecord.read);
-    } else if (aMessageRecord.type == "mms") {
-      let headers = aMessageRecord["headers"];
-      if (DEBUG) {
-        debug("MMS: headers: " + JSON.stringify(headers));
-      }
-
-      let subject = headers["subject"];
-      if (subject == undefined) {
-        subject = "";
-      }
-
-      let smil = "";
-      let attachments = [];
-      let parts = aMessageRecord.parts;
-      if (parts) {
-        for (let i = 0; i < parts.length; i++) {
-          let part = parts[i];
-          if (DEBUG) {
-            debug("MMS: part[" + i + "]: " + JSON.stringify(part));
-          }
-          // Sometimes the part is incomplete because the device reboots when
-          // downloading MMS. Don't need to expose this part to the content.
-          if (!part) {
-            continue;
-          }
-
-          let partHeaders = part["headers"];
-          let partContent = part["content"];
-          // Don't need to make the SMIL part if it's present.
-          if (partHeaders["content-type"]["media"] == "application/smil") {
-            smil = partContent;
-            continue;
-          }
-          attachments.push({
-            "id": partHeaders["content-id"],
-            "location": partHeaders["content-location"],
-            "content": partContent
-          });
-        }
-      }
-      let expiryDate = 0;
-      if (headers["x-mms-expiry"] != undefined) {
-        expiryDate = aMessageRecord.timestamp + headers["x-mms-expiry"] * 1000;
-      }
-      let readReportRequested = headers["x-mms-read-report"] || false;
-      return gMobileMessageService.createMmsMessage(aMessageRecord.id,
-                                                    aMessageRecord.threadId,
-                                                    aMessageRecord.iccId,
-                                                    aMessageRecord.delivery,
-                                                    aMessageRecord.deliveryInfo,
-                                                    aMessageRecord.sender,
-                                                    aMessageRecord.receivers,
-                                                    aMessageRecord.timestamp,
-                                                    aMessageRecord.sentTimestamp,
-                                                    aMessageRecord.read,
-                                                    subject,
-                                                    smil,
-                                                    attachments,
-                                                    expiryDate,
-                                                    readReportRequested);
-    }
-  },
-
-  /**
-   * @callback MobileMessageDB.ParticipantRecordCallback
-   * @param {MobileMessageDB.ParticipantRecord} aParticipantRecord
-   *        The stored participant record.
-   */
-
-  /**
-   * Create a participant record with the given addresses, and add it into the
-   * participant object store immediately.
-   *
-   * @function MobileMessageDB.createParticipantRecord
-   * @param {IDBObjectStore} aParticipantStore
-   *        Object store for participants.
-   * @param {string[]} aAddresses
-   *        The addresses associated to the participant.
-   * @param {MobileMessageDB.ParticipantRecordCallback} aCallback
-   *        The callback function to invoke when the request finishes.
-   */
-  createParticipantRecord: function(aParticipantStore, aAddresses, aCallback) {
-    let participantRecord = { addresses: aAddresses };
-    let addRequest = aParticipantStore.add(participantRecord);
-    addRequest.onsuccess = function(event) {
-      participantRecord.id = event.target.result;
-      if (DEBUG) {
-        debug("createParticipantRecord: " + JSON.stringify(participantRecord));
-      }
-      aCallback(participantRecord);
-    };
-  },
-
-  /**
-   * Find or create the participant record associated to the given PLMN address.
-   *
-   * @function MobileMessageDB.findParticipantRecordByPlmnAddress
-   * @param {IDBObjectStore} aParticipantStore
-   *        The object store for participants.
-   * @param {string} aAddress
-   *        The PLMN address to look up with.
-   * @param {boolean} aCreate
-   *        <code>true</code> to create a new participant record if not exists
-   *        yet, otherwise return <code>null</code> to the callback if record
-   *        not found.
-   * @param {MobileMessageDB.ParticipantRecordCallback} aCallback
-   *        The callback function to invoke when the request finishes.
-   */
-  findParticipantRecordByPlmnAddress: function(aParticipantStore, aAddress,
-                                               aCreate, aCallback) {
-    if (DEBUG) {
-      debug("findParticipantRecordByPlmnAddress("
-            + JSON.stringify(aAddress) + ", " + aCreate + ")");
-    }
-
-    // Two types of input number to match here, international(+886987654321),
-    // and local(0987654321) types. The "nationalNumber" parsed from
-    // phonenumberutils will be "987654321" in this case.
-
-    // Normalize address before searching for participant record.
-    let normalizedAddress = PhoneNumberUtils.normalize(aAddress, false);
-    let allPossibleAddresses = [normalizedAddress];
-    let parsedAddress = PhoneNumberUtils.parse(normalizedAddress);
-    if (parsedAddress && parsedAddress.internationalNumber &&
-        allPossibleAddresses.indexOf(parsedAddress.internationalNumber) < 0) {
-      // We only stores international numbers into participant store because
-      // the parsed national number doesn't contain country info and may
-      // duplicate in different country.
-      allPossibleAddresses.push(parsedAddress.internationalNumber);
-    }
-    if (DEBUG) {
-      debug("findParticipantRecordByPlmnAddress: allPossibleAddresses = " +
-            JSON.stringify(allPossibleAddresses));
-    }
-
-    // Make a copy here because we may need allPossibleAddresses again.
-    let needles = allPossibleAddresses.slice(0);
-    let request = aParticipantStore.index("addresses").get(needles.pop());
-    request.onsuccess = (function onsuccess(event) {
-      let participantRecord = event.target.result;
-      // 1) First try matching through "addresses" index of participant store.
-      //    If we're lucky, return the fetched participant record.
-      if (participantRecord) {
-        if (DEBUG) {
-          debug("findParticipantRecordByPlmnAddress: got "
-                + JSON.stringify(participantRecord));
-        }
-        aCallback(participantRecord);
-        return;
-      }
-
-      // Try next possible address again.
-      if (needles.length) {
-        let request = aParticipantStore.index("addresses").get(needles.pop());
-        request.onsuccess = onsuccess.bind(this);
-        return;
-      }
-
-      // 2) Traverse throught all participants and check all alias addresses.
-      aParticipantStore.openCursor().onsuccess = (function(event) {
-        let cursor = event.target.result;
-        if (!cursor) {
-          // Have traversed whole object store but still in vain.
-          if (!aCreate) {
-            aCallback(null);
-            return;
-          }
-
-          this.createParticipantRecord(aParticipantStore, [normalizedAddress],
-                                       aCallback);
-          return;
-        }
-
-        let participantRecord = cursor.value;
-        for (let storedAddress of participantRecord.addresses) {
-          let parsedStoredAddress = PhoneNumberUtils.parseWithMCC(storedAddress, null);
-          let match = this.matchPhoneNumbers(normalizedAddress, parsedAddress,
-                                             storedAddress, parsedStoredAddress);
-          if (!match) {
-            // 3) Else we fail to match current stored participant record.
-            continue;
-          }
-          // Match!
-          if (aCreate) {
-            // In a READ-WRITE transaction, append one more possible address for
-            // this participant record.
-            participantRecord.addresses =
-              participantRecord.addresses.concat(allPossibleAddresses);
-            cursor.update(participantRecord);
-          }
-
-          if (DEBUG) {
-            debug("findParticipantRecordByPlmnAddress: match "
-                  + JSON.stringify(cursor.value));
-          }
-          aCallback(participantRecord);
-          return;
-        }
-
-        // Check next participant record if available.
-        cursor.continue();
-      }).bind(this);
-    }).bind(this);
-  },
-
-  /**
-   * Find or create the participant record associated to the given address other
-   * than PLMN address.
-   *
-   * @function MobileMessageDB.findParticipantRecordByOtherAddress
-   * @param {IDBObjectStore} aParticipantStore
-   *        The object store for participants.
-   * @param {string} aAddress
-   *        The address to look up with.
-   * @param {boolean} aCreate
-   *        <code>true</code> to create a new participant record if not exists
-   *        yet, otherwise return <code>null</code> to the callback if record
-   *        not found.
-   * @param {MobileMessageDB.ParticipantRecordCallback} aCallback
-   *        The callback function to invoke when the request finishes.
-   */
-  findParticipantRecordByOtherAddress: function(aParticipantStore, aAddress,
-                                                aCreate, aCallback) {
-    if (DEBUG) {
-      debug("findParticipantRecordByOtherAddress(" +
-            JSON.stringify(aAddress) + ", " + aCreate + ")");
-    }
-
-    // Go full match.
-    let request = aParticipantStore.index("addresses").get(aAddress);
-    request.onsuccess = (function(event) {
-      let participantRecord = event.target.result;
-      if (participantRecord) {
-        if (DEBUG) {
-          debug("findParticipantRecordByOtherAddress: got "
-                + JSON.stringify(participantRecord));
-        }
-        aCallback(participantRecord);
-        return;
-      }
-      if (aCreate) {
-        this.createParticipantRecord(aParticipantStore, [aAddress], aCallback);
-        return;
-      }
-      aCallback(null);
-    }).bind(this);
-  },
-
-  /**
-   * @typedef {Object} MobileMessageDB.TypedAddress
-   * @property {string} address Address
-   * @property {string} type Type of the address, such as "PLMN", "IPv4",
-   *           "IPv6", "email" or "Others"
-   */
-
-  /**
-   * Find or create the participant record associated to the given address.
-   *
-   * @function MobileMessageDB.findParticipantRecordByTypedAddress
-   * @param {IDBObjectStore} aParticipantStore
-   *        The object store for participants.
-   * @param {MobileMessageDB.TypedAddress} aTypedAddress
-   *        The address to look up with.
-   * @param {boolean} aCreate
-   *        <code>true</code> to create a new participant record if not exists
-   *        yet, otherwise return <code>null</code> to the callback if record
-   *        not found.
-   * @param {MobileMessageDB.ParticipantRecordCallback} aCallback
-   *        The callback function to invoke when the request finishes.
-   */
-  findParticipantRecordByTypedAddress: function(aParticipantStore,
-                                                aTypedAddress, aCreate,
-                                                aCallback) {
-    if (aTypedAddress.type == "PLMN") {
-      this.findParticipantRecordByPlmnAddress(aParticipantStore,
-                                              aTypedAddress.address, aCreate,
-                                              aCallback);
-    } else {
-      this.findParticipantRecordByOtherAddress(aParticipantStore,
-                                               aTypedAddress.address, aCreate,
-                                               aCallback);
-    }
-  },
-
-  // For upgradeSchema13 usage.
-  findParticipantIdsByPlmnAddresses: function(aParticipantStore, aAddresses,
-                                              aCreate, aSkipNonexistent, aCallback) {
-    if (DEBUG) {
-      debug("findParticipantIdsByPlmnAddresses("
-            + JSON.stringify(aAddresses) + ", "
-            + aCreate + ", " + aSkipNonexistent + ")");
-    }
-
-    if (!aAddresses || !aAddresses.length) {
-      if (DEBUG) debug("findParticipantIdsByPlmnAddresses: returning null");
-      aCallback(null);
-      return;
-    }
-
-    let self = this;
-    (function findParticipantId(index, result) {
-      if (index >= aAddresses.length) {
-        // Sort numerically.
-        result.sort(function(a, b) {
-          return a - b;
-        });
-        if (DEBUG) debug("findParticipantIdsByPlmnAddresses: returning " + result);
-        aCallback(result);
-        return;
-      }
-
-      self.findParticipantRecordByPlmnAddress(aParticipantStore,
-                                              aAddresses[index++], aCreate,
-                                              function(participantRecord) {
-        if (!participantRecord) {
-          if (!aSkipNonexistent) {
-            if (DEBUG) debug("findParticipantIdsByPlmnAddresses: returning null");
-            aCallback(null);
-            return;
-          }
-        } else if (result.indexOf(participantRecord.id) < 0) {
-          result.push(participantRecord.id);
-        }
-        findParticipantId(index, result);
-      });
-    }) (0, []);
-  },
-
-  /**
-   * @callback MobileMessageDB.ParticipantIdsCallback
-   * @param {number[]} aParticipantIds
-   *        An array of participant IDs. May be <code>null</code>.
-   */
-
-  /**
-   * Find or create participant records associated to the given addresses, and
-   * return the IDs of the participant records to the caller through the
-   * callback.
-   *
-   * @function MobileMessageDB.findParticipantIdsByTypedAddresses
-   * @param {IDBObjectStore} aParticipantStore
-   *        The object store for participants.
-   * @param {MobileMessageDB.TypedAddress[]} aTypedAddresses
-   *        Addresses to look up with.
-   * @param {boolean} aCreate
-   *        <code>true</code> to create a new participant record associates to
-   *        the given addresses if not exists yet, otherwise return
-   *        <code>null</code> to the callback if no record found.
-   * @param {boolean} aSkipNonexistent
-   *        <code>true</code> to skip the addresses not exist in the participant
-   *        store, otherwise return <code>null</code> to the callback when one
-   *        or more addresses not found.
-   * @param {MobileMessageDB.ParticipantIdsCallback} aCallback
-   *        The callback function to invoke when the request finishes.
-   */
-  findParticipantIdsByTypedAddresses: function(aParticipantStore,
-                                               aTypedAddresses, aCreate,
-                                               aSkipNonexistent, aCallback) {
-    if (DEBUG) {
-      debug("findParticipantIdsByTypedAddresses(" +
-            JSON.stringify(aTypedAddresses) + ", " +
-            aCreate + ", " + aSkipNonexistent + ")");
-    }
-
-    if (!aTypedAddresses || !aTypedAddresses.length) {
-      if (DEBUG) debug("findParticipantIdsByTypedAddresses: returning null");
-      aCallback(null);
-      return;
-    }
-
-    let self = this;
-    (function findParticipantId(index, result) {
-      if (index >= aTypedAddresses.length) {
-        // Sort numerically.
-        result.sort(function(a, b) {
-          return a - b;
-        });
-        if (DEBUG) {
-          debug("findParticipantIdsByTypedAddresses: returning " + result);
-        }
-        aCallback(result);
-        return;
-      }
-
-      self.findParticipantRecordByTypedAddress(aParticipantStore,
-                                               aTypedAddresses[index++],
-                                               aCreate,
-                                               function(participantRecord) {
-        if (!participantRecord) {
-          if (!aSkipNonexistent) {
-            if (DEBUG) {
-              debug("findParticipantIdsByTypedAddresses: returning null");
-            }
-            aCallback(null);
-            return;
-          }
-        } else if (result.indexOf(participantRecord.id) < 0) {
-          result.push(participantRecord.id);
-        }
-        findParticipantId(index, result);
-      });
-    }) (0, []);
-  },
-
-  // For upgradeSchema13 usage.
-  findThreadRecordByPlmnAddresses: function(aThreadStore, aParticipantStore,
-                                            aAddresses, aCreateParticipants,
-                                            aCallback) {
-    if (DEBUG) {
-      debug("findThreadRecordByPlmnAddresses(" + JSON.stringify(aAddresses)
-            + ", " + aCreateParticipants + ")");
-    }
-    this.findParticipantIdsByPlmnAddresses(aParticipantStore, aAddresses,
-                                           aCreateParticipants, false,
-                                           function(participantIds) {
-      if (!participantIds) {
-        if (DEBUG) debug("findThreadRecordByPlmnAddresses: returning null");
-        aCallback(null, null);
-        return;
-      }
-      // Find record from thread store.
-      let request = aThreadStore.index("participantIds").get(participantIds);
-      request.onsuccess = function(event) {
-        let threadRecord = event.target.result;
-        if (DEBUG) {
-          debug("findThreadRecordByPlmnAddresses: return "
-                + JSON.stringify(threadRecord));
-        }
-        aCallback(threadRecord, participantIds);
-      };
-    });
-  },
-
-  /**
-   * @callback MobileMessageDB.ThreadRecordCallback
-   * @param {MobileMessageDB.ThreadRecord} aThreadRecord
-   *        The stored thread record.
-   * @param {number[]} aParticipantIds
-   *        IDs of participants of the thread.
-   */
-
-  /**
-   * Find the thread record associated to the given address.
-   *
-   * @function MobileMessageDB.findThreadRecordByTypedAddresses
-   * @param {IDBObjectStore} aThreadStore
-   *        The object store for threads.
-   * @param {IDBObjectStore} aParticipantStore
-   *        The object store for participants.
-   * @param {MobileMessageDB.TypedAddress[]} aTypedAddresses
-   *        Addresses to look up with.
-   * @param {boolean} aCreateParticipants
-   *        <code>true</code> to create participant record associated to the
-   *        addresses if not exist yet.
-   * @param {MobileMessageDB.ThreadRecordCallback} aCallback
-   *        The callback function to invoke when the request finishes.
-   */
-  findThreadRecordByTypedAddresses: function(aThreadStore, aParticipantStore,
-                                             aTypedAddresses,
-                                             aCreateParticipants, aCallback) {
-    if (DEBUG) {
-      debug("findThreadRecordByTypedAddresses(" +
-          JSON.stringify(aTypedAddresses) + ", " + aCreateParticipants + ")");
-    }
-    this.findParticipantIdsByTypedAddresses(aParticipantStore, aTypedAddresses,
-                                            aCreateParticipants, false,
-                                            function(participantIds) {
-      if (!participantIds) {
-        if (DEBUG) debug("findThreadRecordByTypedAddresses: returning null");
-        aCallback(null, null);
-        return;
-      }
-      // Find record from thread store.
-      let request = aThreadStore.index("participantIds").get(participantIds);
-      request.onsuccess = function(event) {
-        let threadRecord = event.target.result;
-        if (DEBUG) {
-          debug("findThreadRecordByTypedAddresses: return " +
-                JSON.stringify(threadRecord));
-        }
-        aCallback(threadRecord, participantIds);
-      };
-    });
-  },
-
-  /**
-   * @callback MobileMessageDB.TransactionResultCallback
-   * @param {number} aErrorCode
-   *        The error code on failure, or <code>NS_OK</code> on success.
-   * @param {nsISmsMessage|nsIMmsMessage} aDomMessage
-   *        The DOM message instance of the transaction result.
-   */
-
-  /**
-   * @callback MobileMessageDB.NewTxnWithCallbackRequestCallback
-   * @param {Object} aCapture
-   *        An output parameter. The <code>messageRecord</code> property will be
-   *        set on transaction finishes.
-   * @param {MobileMessageDB.MessageRecord} aCapture.messageRecord
-   *        The stored message record. The property presents if the transaction
-   *        finished successfully.
-   * @param {IDBObjectStore|IDBObjectStore[]} aObjectStores
-   *        The object store(s) on success. If only one object store is passed,
-   *        it's passed as an <code>IDBObjectStore</code>; Otherwise, it's
-   *        <code>IDBObjectStore[]</code>.
-   */
-
-  /**
-   * Start a new transaction with default <code>oncomplete</code> /
-   * <code>onabort</code> implementation on the <code>IDBTransaction</code>
-   * object which redirects the error / result to <code>aCallback</code>.
-   *
-   * @function MobileMessageDB.newTxnWithCallback
-   * @param {Object} aCallback
-   *        The object which includes a callback function.
-   * @param {MobileMessageDB.TransactionResultCallback} aCallback.notify
-   *        The callback function to invoke when the transaction finishes.
-   * @param {MobileMessageDB.NewTxnWithCallbackRequestCallback} aFunc
-   *        The callback function to invoke when the request finishes.
-   * @param {string[]} [aStoreNames=[{@link MobileMessageDB.MESSAGE_STORE_NAME}]]
-   *        Names of the stores to open.
-   */
-  newTxnWithCallback: function(aCallback, aFunc, aStoreNames) {
-    let self = this;
-    this.newTxn(READ_WRITE, function(aError, aTransaction, aStores) {
-      let notifyResult = function(aRv, aMessageRecord) {
-        if (!aCallback) {
-          return;
-        }
-        let domMessage =
-          aMessageRecord && self.createDomMessageFromRecord(aMessageRecord);
-        aCallback.notify(aRv, domMessage);
-      };
-
-      if (aError) {
-        notifyResult(aError, null);
-        return;
-      }
-
-      let capture = {};
-      aTransaction.oncomplete = function(event) {
-        notifyResult(Cr.NS_OK, capture.messageRecord);
-      };
-      aTransaction.onabort = function(event) {
-        if (DEBUG) debug("transaction abort due to " + event.target.error.name);
-        let error = (event.target.error.name === 'QuotaExceededError')
-                    ? Cr.NS_ERROR_FILE_NO_DEVICE_SPACE
-                    : Cr.NS_ERROR_FAILURE;
-        notifyResult(error, null);
-      };
-
-      aFunc(capture, aStores);
-    }, aStoreNames);
-  },
-
-  /**
-   * Save a message record.
-   *
-   * @function MobileMessageDB.saveRecord
-   * @param {MobileMessageDB.MessageRecord} aMessageRecord
-   *        Message record to store.
-   * @param {MobileMessageDB.TypedAddress[]} aThreadParticipants
-   *        Participants of the thread of the message.
-   * @param {Object} aCallback
-   *        The object which includes a callback function.
-   * @param {MobileMessageDB.TransactionResultCallback} aCallback.notify
-   *        The callback function to invoke when the transaction finishes.
-   */
-  saveRecord: function(aMessageRecord, aThreadParticipants, aCallback) {
-    if (DEBUG) debug("Going to store " + JSON.stringify(aMessageRecord));
-
-    let self = this;
-    this.newTxn(READ_WRITE, function(error, txn, stores) {
-      let notifyResult = function(aRv, aMessageRecord) {
-        if (!aCallback) {
-          return;
-        }
-        let domMessage =
-          aMessageRecord && self.createDomMessageFromRecord(aMessageRecord);
-        aCallback.notify(aRv, domMessage);
-      };
-
-      if (error) {
-        notifyResult(error, null);
-        return;
-      }
-
-      let deletedInfo = { messageIds: [], threadIds: [] };
-
-      txn.oncomplete = function(event) {
-        if (aMessageRecord.id > self.lastMessageId) {
-          self.lastMessageId = aMessageRecord.id;
-        }
-        notifyResult(Cr.NS_OK, aMessageRecord);
-        self.notifyDeletedInfo(deletedInfo);
-      };
-      txn.onabort = function(event) {
-        if (DEBUG) debug("transaction abort due to " + event.target.error.name);
-        let error = (event.target.error.name === 'QuotaExceededError')
-                    ? Cr.NS_ERROR_FILE_NO_DEVICE_SPACE
-                    : Cr.NS_ERROR_FAILURE;
-        notifyResult(error, null);
-      };
-
-      let messageStore = stores[0];
-      let participantStore = stores[1];
-      let threadStore = stores[2];
-      self.replaceShortMessageOnSave(txn, messageStore, participantStore,
-                                     threadStore, aMessageRecord,
-                                     aThreadParticipants, deletedInfo);
-    }, [MESSAGE_STORE_NAME, PARTICIPANT_STORE_NAME, THREAD_STORE_NAME]);
-  },
-
-  /**
-   * @typedef {Object} MobileMessageDB.DeletedInfo
-   * @property {number[]} messageIds
-   *           IDs of deleted messages.
-   * @property {number[]} threadIds
-   *           IDs of deleted threads, which indicates all messages within the
-   *           threads have been deleted.
-   */
-
-  /**
-   * According to <i>3GPP 23.040 - subclause 9.2.3.9 TP-Protocol-Identifier (TP-PID)</i>,
-   * if the Protocol Identifier contains a <i>Replace Short Message Type</i> or
-   * <i>Return Call Message</i> code, it should replace any existing stored
-   * message having the same Protocol Identifier code and originating address.
-   *
-   * This function checks the Protocol Identifier before saving the message
-   * record to fulfill the feature.
-   *
-   * @function MobileMessageDB.replaceShortMessageOnSave
-   * @param {IDBTransaction} aTransaction
-   *        The transaction object.
-   * @param {IDBObjectStore} aMessageStore
-   *        The object store for messages.
-   * @param {IDBObjectStore} aParticipantStore
-   *        The object store for participants.
-   * @param {IDBObjectStore} aThreadStore
-   *        The object store for threads.
-   * @param {MobileMessageDB.MessageRecord} aMessageRecord
-   *        The message record to store.
-   * @param {MobileMessageDB.TypedAddress[]} aThreadParticipants
-   *        Participants of the thread of the message.
-   * @param {MobileMessageDB.DeletedInfo} aDeletedInfo
-   *        An out parameter indicating which messages have been deleted due to
-   *        the replacement.
-   */
-  replaceShortMessageOnSave: function(aTransaction, aMessageStore,
-                                      aParticipantStore, aThreadStore,
-                                      aMessageRecord, aThreadParticipants,
-                                      aDeletedInfo) {
-    let isReplaceTypePid = (aMessageRecord.pid) &&
-                           ((aMessageRecord.pid >= RIL.PDU_PID_REPLACE_SHORT_MESSAGE_TYPE_1 &&
-                             aMessageRecord.pid <= RIL.PDU_PID_REPLACE_SHORT_MESSAGE_TYPE_7) ||
-                            aMessageRecord.pid == RIL.PDU_PID_RETURN_CALL_MESSAGE);
-
-    if (aMessageRecord.type != "sms" ||
-        aMessageRecord.delivery != DELIVERY_RECEIVED ||
-        !isReplaceTypePid) {
-      this.realSaveRecord(aTransaction, aMessageStore, aParticipantStore,
-                          aThreadStore, aMessageRecord, aThreadParticipants,
-                          aDeletedInfo);
-      return;
-    }
-
-    // 3GPP TS 23.040 subclause 9.2.3.9 "TP-Protocol-Identifier (TP-PID)":
-    //
-    //   ... the MS shall check the originating address and replace any
-    //   existing stored message having the same Protocol Identifier code
-    //   and originating address with the new short message and other
-    //   parameter values. If there is no message to be replaced, the MS
-    //   shall store the message in the normal way. ... it is recommended
-    //   that the SC address should not be checked by the MS."
-    let self = this;
-    let typedSender = {
-      address: aMessageRecord.sender,
-      type: MMS.Address.resolveType(aMessageRecord.sender)
-    };
-    this.findParticipantRecordByTypedAddress(aParticipantStore, typedSender,
-                                             false,
-                                             function(participantRecord) {
-      if (!participantRecord) {
-        self.realSaveRecord(aTransaction, aMessageStore, aParticipantStore,
-                            aThreadStore, aMessageRecord, aThreadParticipants,
-                            aDeletedInfo);
-        return;
-      }
-
-      let participantId = participantRecord.id;
-      let range = IDBKeyRange.bound([participantId, 0], [participantId, ""]);
-      let request = aMessageStore.index("participantIds").openCursor(range);
-      request.onsuccess = function(event) {
-        let cursor = event.target.result;
-        if (!cursor) {
-          self.realSaveRecord(aTransaction, aMessageStore, aParticipantStore,
-                              aThreadStore, aMessageRecord, aThreadParticipants,
-                              aDeletedInfo);
-          return;
-        }
-
-        // A message record with same participantId found.
-        // Verify matching criteria.
-        let foundMessageRecord = cursor.value;
-        if (foundMessageRecord.type != "sms" ||
-            foundMessageRecord.sender != aMessageRecord.sender ||
-            foundMessageRecord.pid != aMessageRecord.pid) {
-          cursor.continue();
-          return;
-        }
-
-        // Match! Now replace that found message record with current one.
-        aMessageRecord.id = foundMessageRecord.id;
-        self.realSaveRecord(aTransaction, aMessageStore, aParticipantStore,
-                            aThreadStore, aMessageRecord, aThreadParticipants,
-                            aDeletedInfo);
-      };
-    });
-  },
-
-  /**
-   * The function where object store manipulations actually occur.
-   *
-   * @function MobileMessageDB.realSaveRecord
-   * @param {IDBTransaction} aTransaction
-   *        The transaction object.
-   * @param {IDBObjectStore} aMessageStore
-   *        The object store for messages.
-   * @param {IDBObjectStore} aParticipantStore
-   *        The object store for participants.
-   * @param {IDBObjectStore} aThreadStore
-   *        The object store for threads.
-   * @param {MobileMessageDB.MessageRecord} aMessageRecord
-   *        The message record to store.
-   * @param {MobileMessageDB.TypedAddress[]} aThreadParticipants
-   *        Participants of the thread of the message.
-   * @param {MobileMessageDB.DeletedInfo} aDeletedInfo
-   *        An out parameter indicating which messages have been deleted due to
-   *        the replacement.
-   */
-  realSaveRecord: function(aTransaction, aMessageStore, aParticipantStore,
-                           aThreadStore, aMessageRecord, aThreadParticipants,
-                           aDeletedInfo) {
-    let self = this;
-    this.findThreadRecordByTypedAddresses(aThreadStore, aParticipantStore,
-                                          aThreadParticipants, true,
-                                          function(threadRecord,
-                                                   participantIds) {
-      if (!participantIds) {
-        aTransaction.abort();
-        return;
-      }
-
-      let isOverriding = (aMessageRecord.id !== undefined);
-      if (!isOverriding) {
-        // |self.lastMessageId| is only updated in |txn.oncomplete|.
-        aMessageRecord.id = self.lastMessageId + 1;
-      }
-
-      let timestamp = aMessageRecord.timestamp;
-      let insertMessageRecord = function(threadId) {
-        // Setup threadId & threadIdIndex.
-        aMessageRecord.threadId = threadId;
-        aMessageRecord.threadIdIndex = [threadId, timestamp];
-        // Setup participantIdsIndex.
-        aMessageRecord.participantIdsIndex = [];
-        for (let id of participantIds) {
-          aMessageRecord.participantIdsIndex.push([id, timestamp]);
-        }
-
-        if (!isOverriding) {
-          // Really add to message store.
-          aMessageStore.put(aMessageRecord);
-          return;
-        }
-
-        // If we're going to override an old message, we need to update the
-        // info of the original thread containing the overridden message.
-        // To get the original thread ID and read status of the overridden
-        // message record, we need to retrieve it before overriding it.
-        aMessageStore.get(aMessageRecord.id).onsuccess = function(event) {
-          let oldMessageRecord = event.target.result;
-          aMessageStore.put(aMessageRecord);
-          if (oldMessageRecord) {
-            self.updateThreadByMessageChange(aMessageStore,
-                                             aThreadStore,
-                                             oldMessageRecord.threadId,
-                                             [aMessageRecord.id],
-                                             oldMessageRecord.read ? 0 : 1,
-                                             aDeletedInfo);
-          }
-        };
-      };
-
-      if (threadRecord) {
-        let needsUpdate = false;
-
-        if (threadRecord.lastTimestamp <= timestamp) {
-          let lastMessageSubject;
-          if (aMessageRecord.type == "mms") {
-            lastMessageSubject = aMessageRecord.headers.subject;
-          }
-          threadRecord.lastMessageSubject = lastMessageSubject || null;
-          threadRecord.lastTimestamp = timestamp;
-          threadRecord.body = aMessageRecord.body;
-          threadRecord.lastMessageId = aMessageRecord.id;
-          threadRecord.lastMessageType = aMessageRecord.type;
-          needsUpdate = true;
-        }
-
-        if (!aMessageRecord.read) {
-          threadRecord.unreadCount++;
-          needsUpdate = true;
-        }
-
-        if (needsUpdate) {
-          aThreadStore.put(threadRecord);
-        }
-
-        insertMessageRecord(threadRecord.id);
-        return;
-      }
-
-      let lastMessageSubject;
-      if (aMessageRecord.type == "mms") {
-        lastMessageSubject = aMessageRecord.headers.subject;
-      }
-
-      threadRecord = {
-        participantIds: participantIds,
-        participantAddresses: aThreadParticipants.map(function(typedAddress) {
-          return typedAddress.address;
-        }),
-        lastMessageId: aMessageRecord.id,
-        lastTimestamp: timestamp,
-        lastMessageSubject: lastMessageSubject || null,
-        body: aMessageRecord.body,
-        unreadCount: aMessageRecord.read ? 0 : 1,
-        lastMessageType: aMessageRecord.type,
-      };
-      aThreadStore.add(threadRecord).onsuccess = function(event) {
-        let threadId = event.target.result;
-        insertMessageRecord(threadId);
-      };
-    });
-  },
-
-  /**
-   * @typedef {Object} MobileMessageDB.MmsDeliveryInfoElement
-   * @property {string} receiver
-   * @property {string} deliveryStatus
-   * @property {number} deliveryTimestamp
-   * @property {string} readStatus
-   * @property {number} readTimestamp
-   */
-
-  /**
-   * @callback MobileMessageDB.ForEachMatchedMmsDeliveryInfoCallback
-   * @param {MobileMessageDB.MmsDeliveryInfoElement} aElement
-   *        An element of the MMS <code>deliverInfo</code> of a message record.
-   */
-
-  /**
-   * Iterate all elements of <code>aDeliveryInfo</code>, check if the receiver
-   * address matches <code>aNeedle</code> and invoke <code>aCallback</code> on
-   * each matched element.
-   *
-   * @function MobileMessageDB.forEachMatchedMmsDeliveryInfo
-   * @param {MobileMessageDB.MmsDeliveryInfoElement[]} aDeliveryInfo
-   *        The MMS <code>deliverInfo</code> of a message record.
-   * @param {string} aNeedle
-   *        The receiver address to look up with.
-   * @param {MobileMessageDB.ForEachMatchedMmsDeliveryInfoCallback} aCallback
-   *        The callback function to invoke on each match.
-   */
-  forEachMatchedMmsDeliveryInfo: function(aDeliveryInfo, aNeedle, aCallback) {
-
-    let typedAddress = {
-      type: MMS.Address.resolveType(aNeedle),
-      address: aNeedle
-    };
-    let normalizedAddress, parsedAddress;
-    if (typedAddress.type === "PLMN") {
-      normalizedAddress = PhoneNumberUtils.normalize(aNeedle, false);
-      parsedAddress = PhoneNumberUtils.parse(normalizedAddress);
-    }
-
-    for (let element of aDeliveryInfo) {
-      let typedStoredAddress = {
-        type: MMS.Address.resolveType(element.receiver),
-        address: element.receiver
-      };
-      if (typedAddress.type !== typedStoredAddress.type) {
-        // Not even my type.  Skip.
-        continue;
-      }
-
-      if (typedAddress.address == typedStoredAddress.address) {
-        // Have a direct match.
-        aCallback(element);
-        continue;
-      }
-
-      if (typedAddress.type !== "PLMN") {
-        // Address type other than "PLMN" must have direct match.  Or, skip.
-        continue;
-      }
-
-      // Both are of "PLMN" type.
-      let normalizedStoredAddress =
-        PhoneNumberUtils.normalize(element.receiver, false);
-      let parsedStoredAddress =
-        PhoneNumberUtils.parseWithMCC(normalizedStoredAddress, null);
-      if (this.matchPhoneNumbers(normalizedAddress, parsedAddress,
-                                 normalizedStoredAddress, parsedStoredAddress)) {
-        aCallback(element);
-      }
-    }
-  },
-
-  /**
-   * Find the message of a given message ID or envelope ID. Update its
-   * <code>delivery</code>, <code>deliveryStatus</code>, and
-   * <code>envelopeId</code> accordingly.
-   *
-   * @function MobileMessageDB.updateMessageDeliveryById
-   * @param {string} id
-   *        If <code>type</code> is "messageId", it represents the message ID;
-   *        If <code>type</code> is "envelopeId", it represents the envelope ID,
-   *        which is the "x-mms-transaction-id" in the header of an MMS message.
-   * @param {string} type
-   *        Either "messageId" or "envelopeId".
-   * @param {string} receiver
-   *        The receiver address.
-   * @param {string} delivery
-   *        If given, it will be used to update the <code>deliveryIndex</code>
-   *        property of a stored message record.
-   * @param {string} deliveryStatus
-   *        If given, it will be used to update the <code>deliveryStatus</code>
-   *        property of a stored message record.
-   * @param {string} envelopeId
-   *        If given, it will be used to update the <code>envelopeIdIndex</code>
-   *        property of a stored message record.
-   * @param {Object} callback
-   *        The object passed as <code>aCallback</code> to
-   *        {@link MobileMessageDB.newTxnWithCallback}.
-   */
-  updateMessageDeliveryById: function(id, type, receiver, delivery,
-                                      deliveryStatus, envelopeId, callback) {
-    if (DEBUG) {
-      debug("Setting message's delivery by " + type + " = "+ id
-            + " receiver: " + receiver
-            + " delivery: " + delivery
-            + " deliveryStatus: " + deliveryStatus
-            + " envelopeId: " + envelopeId);
-    }
-
-    let self = this;
-    this.newTxnWithCallback(callback, function(aCapture, aMessageStore) {
-      let getRequest;
-      if (type === "messageId") {
-        getRequest = aMessageStore.get(id);
-      } else if (type === "envelopeId") {
-        getRequest = aMessageStore.index("envelopeId").get(id);
-      }
-
-      getRequest.onsuccess = function(event) {
-        let messageRecord = event.target.result;
-        if (!messageRecord) {
-          if (DEBUG) debug("type = " + id + " is not found");
-          throw Cr.NS_ERROR_FAILURE;
-        }
-
-        let isRecordUpdated = false;
-
-        // Update |messageRecord.delivery| if needed.
-        if (delivery && messageRecord.delivery != delivery) {
-          messageRecord.delivery = delivery;
-          messageRecord.deliveryIndex = [delivery, messageRecord.timestamp];
-          isRecordUpdated = true;
-
-          // When updating an message's delivey state to 'sent', we also update
-          // its |sentTimestamp| by the current device timestamp to represent
-          // when the message is successfully sent.
-          if (delivery == DELIVERY_SENT) {
-            messageRecord.sentTimestamp = Date.now();
-          }
-        }
-
-        // Attempt to update |deliveryStatus| and |deliveryTimestamp| of:
-        // - the |messageRecord| for SMS.
-        // - the element(s) in |messageRecord.deliveryInfo| for MMS.
-        if (deliveryStatus) {
-          // A callback for updating the deliveyStatus/deliveryTimestamp of
-          // each target.
-          let updateFunc = function(aTarget) {
-            if (aTarget.deliveryStatus == deliveryStatus) {
-              return;
-            }
-
-            aTarget.deliveryStatus = deliveryStatus;
-
-            // Update |deliveryTimestamp| if it's successfully delivered.
-            if (deliveryStatus == DELIVERY_STATUS_SUCCESS) {
-              aTarget.deliveryTimestamp = Date.now();
-            }
-
-            isRecordUpdated = true;
-          };
-
-          if (messageRecord.type == "sms") {
-            updateFunc(messageRecord);
-          } else if (messageRecord.type == "mms") {
-            if (!receiver) {
-              // If the receiver is specified, we only need to update the
-              // element(s) in deliveryInfo that match the same receiver.
-              messageRecord.deliveryInfo.forEach(updateFunc);
-            } else {
-              self.forEachMatchedMmsDeliveryInfo(messageRecord.deliveryInfo,
-                                                 receiver, updateFunc);
-            }
-          }
-        }
-
-        // Update |messageRecord.envelopeIdIndex| if needed.
-        if (envelopeId) {
-          if (messageRecord.envelopeIdIndex != envelopeId) {
-            messageRecord.envelopeIdIndex = envelopeId;
-            isRecordUpdated = true;
-          }
-        }
-
-        aCapture.messageRecord = messageRecord;
-        if (!isRecordUpdated) {
-          if (DEBUG) {
-            debug("The values of delivery, deliveryStatus and envelopeId " +
-                  "don't need to be updated.");
-          }
-          return;
-        }
-
-        if (DEBUG) {
-          debug("The delivery, deliveryStatus or envelopeId are updated.");
-        }
-        aMessageStore.put(messageRecord);
-      };
-    });
-  },
-
-  /**
-   * Map receivers of a MMS message record to the thread participant list if MMS
-   * grouping is enabled.
-   *
-   * @function MobileMessageDB.fillReceivedMmsThreadParticipants
-   * @param {MobileMessageDB.MessageRecord} aMessage
-   *        The MMS message.
-   * @param {MobileMessageDB.TypedAddress[]} threadParticipants
-   *        Participants to add.
-   */
-  fillReceivedMmsThreadParticipants: function(aMessage, threadParticipants) {
-    let receivers = aMessage.receivers;
-    // If we don't want to disable the MMS grouping for receiving, we need to
-    // add the receivers (excluding the user's own number) to the participants
-    // for creating the thread. Some cases might be investigated as below:
-    //
-    // 1. receivers.length == 0
-    //    This usually happens when receiving an MMS notification indication
-    //    which doesn't carry any receivers.
-    // 2. receivers.length == 1
-    //    If the receivers contain single phone number, we don't need to
-    //    add it into participants because we know that number is our own.
-    // 3. receivers.length >= 2
-    //    If the receivers contain multiple phone numbers, we need to add all
-    //    of them but not the user's own number into participants.
-    if (DISABLE_MMS_GROUPING_FOR_RECEIVING || receivers.length < 2) {
-      return;
-    }
-    let isSuccess = false;
-    let slicedReceivers = receivers.slice();
-    if (aMessage.msisdn) {
-      let found = slicedReceivers.indexOf(aMessage.msisdn);
-      if (found !== -1) {
-        isSuccess = true;
-        slicedReceivers.splice(found, 1);
-      }
-    }
-
-    if (!isSuccess) {
-      // For some SIMs we cannot retrieve the valid MSISDN (i.e. the user's
-      // own phone number), so we cannot correctly exclude the user's own
-      // number from the receivers, thus wrongly building the thread index.
-      if (DEBUG) debug("Error! Cannot strip out user's own phone number!");
-    }
-
-    threadParticipants =
-      threadParticipants.concat(slicedReceivers).map(function(aAddress) {
-        return {
-          address: aAddress,
-          type: MMS.Address.resolveType(aAddress)
-        };
-      });
-  },
-
-  /**
-   * Update the thread when one or more messages are deleted / replaced.
-   *
-   * @function MobileMessageDB.updateThreadByMessageChange
-   * @param {IDBObjectStore} messageStore
-   *        The object store for messages.
-   * @param {IDBObjectStore} threadStore
-   *        The object store for threads.
-   * @param {number} threadId
-   *        The thread ID.
-   * @param {number[]} removedMsgIds
-   *        The IDs of removed messages.
-   * @param {number} ignoredUnreadCount
-   *        Negative offset for <code>unreadCount</code>. For example, if the
-   *        <code>unreadCount</code> was 5, given
-   *        <code>ignoredUnreadCount</code> to 3 causes <code>unreadCount</code>
-   *        becomes 2.
-   * @param {MobileMessageDB.DeletedInfo} deletedInfo
-   *        An out parameter indicating if the thread is deleted after the
-   *        operation.
-   */
-  updateThreadByMessageChange: function(messageStore, threadStore, threadId,
-                                        removedMsgIds, ignoredUnreadCount, deletedInfo) {
-    let self = this;
-    threadStore.get(threadId).onsuccess = function(event) {
-      // This must exist.
-      let threadRecord = event.target.result;
-      if (DEBUG) debug("Updating thread record " + JSON.stringify(threadRecord));
-
-      if (ignoredUnreadCount > 0) {
-        if (DEBUG) {
-          debug("Updating unread count : " + threadRecord.unreadCount +
-                " -> " + (threadRecord.unreadCount - ignoredUnreadCount));
-        }
-        threadRecord.unreadCount -= ignoredUnreadCount;
-      }
-
-      if (removedMsgIds.indexOf(threadRecord.lastMessageId) >= 0) {
-        if (DEBUG) debug("MRU entry was deleted.");
-        // Check most recent sender/receiver.
-        let range = IDBKeyRange.bound([threadId, 0], [threadId, ""]);
-        let request = messageStore.index("threadId")
-                                  .openCursor(range, PREV);
-        request.onsuccess = function(event) {
-          let cursor = event.target.result;
-          if (!cursor) {
-            if (DEBUG) {
-              debug("All messages were deleted. Delete this thread.");
-            }
-            threadStore.delete(threadId);
-            if (deletedInfo) {
-              deletedInfo.threadIds.push(threadId);
-            }
-            return;
-          }
-
-          let nextMsg = cursor.value;
-          let lastMessageSubject;
-          if (nextMsg.type == "mms") {
-            lastMessageSubject = nextMsg.headers.subject;
-          }
-          threadRecord.lastMessageSubject = lastMessageSubject || null;
-          threadRecord.lastMessageId = nextMsg.id;
-          threadRecord.lastTimestamp = nextMsg.timestamp;
-          threadRecord.body = nextMsg.body;
-          threadRecord.lastMessageType = nextMsg.type;
-          if (DEBUG) {
-            debug("Updating mru entry: " +
-                  JSON.stringify(threadRecord));
-          }
-          threadStore.put(threadRecord);
-        };
-      } else if (ignoredUnreadCount > 0) {
-        if (DEBUG) debug("Shortcut, just update the unread count.");
-        threadStore.put(threadRecord);
-      }
-    };
-  },
-
-  /**
-   * Notify the observers that one or more messages are deleted.
-   *
-   * @function MobileMessageDB.notifyDeletedInfo
-   * @param {MobileMessageDB.DeletedInfo} info
-   *        The IDs of deleted messages and threads.
-   */
-  notifyDeletedInfo: function(info) {
-    if (!info ||
-        (info.messageIds.length === 0 && info.threadIds.length === 0)) {
-      return;
-    }
-
-    let deletedInfo =
-      gMobileMessageService
-      .createDeletedMessageInfo(info.messageIds,
-                                info.messageIds.length,
-                                info.threadIds,
-                                info.threadIds.length);
-    Services.obs.notifyObservers(deletedInfo, "sms-deleted", null);
-  },
-
-  /**
-   * nsIGonkMobileMessageDatabaseService API
-   */
-
-  /**
-   * Store an incoming message.
-   *
-   * @function MobileMessageDB.saveReceivedMessage
-   * @param {MobileMessageDB.MessageRecord} aMessage
-   *        The message record to store.
-   * @param {Object} aCallback
-   *        The object which includes a callback function.
-   * @param {MobileMessageDB.TransactionResultCallback} aCallback.notify
-   *        The callback function to invoke when the transaction finishes.
-   */
-  saveReceivedMessage: function(aMessage, aCallback) {
-    if ((aMessage.type != "sms" && aMessage.type != "mms") ||
-        (aMessage.type == "sms" && (aMessage.messageClass == undefined ||
-                                    aMessage.sender == undefined)) ||
-        (aMessage.type == "mms" && (aMessage.delivery == undefined ||
-                                    aMessage.deliveryStatus == undefined ||
-                                    !Array.isArray(aMessage.receivers))) ||
-        aMessage.timestamp == undefined) {
-      if (aCallback) {
-        aCallback.notify(Cr.NS_ERROR_FAILURE, null);
-      }
-      return;
-    }
-
-    let threadParticipants;
-    if (aMessage.type == "mms") {
-      if (aMessage.headers.from) {
-        aMessage.sender = aMessage.headers.from.address;
-      } else {
-        aMessage.sender = "";
-      }
-
-      threadParticipants = [{
-        address: aMessage.sender,
-        type: MMS.Address.resolveType(aMessage.sender)
-      }];
-      this.fillReceivedMmsThreadParticipants(aMessage, threadParticipants);
-    } else { // SMS
-      threadParticipants = [{
-        address: aMessage.sender,
-        type: MMS.Address.resolveType(aMessage.sender)
-      }];
-    }
-
-    let timestamp = aMessage.timestamp;
-
-    // Adding needed indexes and extra attributes for internal use.
-    // threadIdIndex & participantIdsIndex are filled in saveRecord().
-    aMessage.readIndex = [FILTER_READ_UNREAD, timestamp];
-    aMessage.read = FILTER_READ_UNREAD;
-
-    // If |sentTimestamp| is not specified, use 0 as default.
-    if (aMessage.sentTimestamp == undefined) {
-      aMessage.sentTimestamp = 0;
-    }
-
-    if (aMessage.type == "mms") {
-      aMessage.transactionIdIndex = aMessage.headers["x-mms-transaction-id"];
-      aMessage.isReadReportSent = false;
-
-      // As a receiver, we don't need to care about the delivery status of
-      // others, so we put a single element with self's phone number in the
-      // |deliveryInfo| array.
-      aMessage.deliveryInfo = [{
-        receiver: aMessage.phoneNumber,
-        deliveryStatus: aMessage.deliveryStatus,
-        deliveryTimestamp: 0,
-        readStatus: MMS.DOM_READ_STATUS_NOT_APPLICABLE,
-        readTimestamp: 0,
-      }];
-
-      delete aMessage.deliveryStatus;
-    }
-
-    if (aMessage.type == "sms") {
-      aMessage.delivery = DELIVERY_RECEIVED;
-      aMessage.deliveryStatus = DELIVERY_STATUS_SUCCESS;
-      aMessage.deliveryTimestamp = 0;
-
-      if (aMessage.pid == undefined) {
-        aMessage.pid = RIL.PDU_PID_DEFAULT;
-      }
-    }
-    aMessage.deliveryIndex = [aMessage.delivery, timestamp];
-
-    this.saveRecord(aMessage, threadParticipants, aCallback);
-  },
-
-  /**
-   * Store an outgoing message.
-   *
-   * @function MobileMessageDB.saveSendingMessage
-   * @param {MobileMessageDB.MessageRecord} aMessage
-   *        The message record to store.
-   * @param {Object} aCallback
-   *        The object which includes a callback function.
-   * @param {MobileMessageDB.TransactionResultCallback} aCallback.notify
-   *        The callback function to invoke when the transaction finishes.
-   */
-  saveSendingMessage: function(aMessage, aCallback) {
-    if ((aMessage.type != "sms" && aMessage.type != "mms") ||
-        (aMessage.type == "sms" && aMessage.receiver == undefined) ||
-        (aMessage.type == "mms" && !Array.isArray(aMessage.receivers)) ||
-        aMessage.deliveryStatusRequested == undefined ||
-        aMessage.timestamp == undefined) {
-      if (aCallback) {
-        aCallback.notify(Cr.NS_ERROR_FAILURE, null);
-      }
-      return;
-    }
-
-    // Set |aMessage.deliveryStatus|. Note that for MMS record
-    // it must be an array of strings; For SMS, it's a string.
-    let deliveryStatus = aMessage.deliveryStatusRequested
-                       ? DELIVERY_STATUS_PENDING
-                       : DELIVERY_STATUS_NOT_APPLICABLE;
-    if (aMessage.type == "sms") {
-      aMessage.deliveryStatus = deliveryStatus;
-      // If |deliveryTimestamp| is not specified, use 0 as default.
-      if (aMessage.deliveryTimestamp == undefined) {
-        aMessage.deliveryTimestamp = 0;
-      }
-    } else if (aMessage.type == "mms") {
-      let receivers = aMessage.receivers;
-      let readStatus = aMessage.headers["x-mms-read-report"]
-                     ? MMS.DOM_READ_STATUS_PENDING
-                     : MMS.DOM_READ_STATUS_NOT_APPLICABLE;
-      aMessage.deliveryInfo = [];
-      for (let i = 0; i < receivers.length; i++) {
-        aMessage.deliveryInfo.push({
-          receiver: receivers[i],
-          deliveryStatus: deliveryStatus,
-          deliveryTimestamp: 0,
-          readStatus: readStatus,
-          readTimestamp: 0,
-        });
-      }
-    }
-
-    let timestamp = aMessage.timestamp;
-
-    // Adding needed indexes and extra attributes for internal use.
-    // threadIdIndex & participantIdsIndex are filled in saveRecord().
-    aMessage.deliveryIndex = [DELIVERY_SENDING, timestamp];
-    aMessage.readIndex = [FILTER_READ_READ, timestamp];
-    aMessage.delivery = DELIVERY_SENDING;
-    aMessage.messageClass = MESSAGE_CLASS_NORMAL;
-    aMessage.read = FILTER_READ_READ;
-
-    // |sentTimestamp| is not available when the message is still sedning.
-    aMessage.sentTimestamp = 0;
-
-    let threadParticipants;
-    if (aMessage.type == "sms") {
-      threadParticipants = [{
-        address: aMessage.receiver,
-        type :MMS.Address.resolveType(aMessage.receiver)
-      }];
-    } else if (aMessage.type == "mms") {
-      threadParticipants = aMessage.headers.to;
-    }
-    this.saveRecord(aMessage, threadParticipants, aCallback);
-  },
-
-  /**
-   * Update the <code>delivery</code>, <code>deliveryStatus</code>, and
-   * <code>envelopeId</code> of a stored message record matching the given
-   * message ID.
-   *
-   * @function MobileMessageDB.setMessageDeliveryByMessageId
-   * @param {number} messageId
-   *        The message ID.
-   * @param {string} receiver
-   *        The receiver address.
-   * @param {string} delivery
-   *        If given, it will be used to update the <code>deliveryIndex</code>
-   *        property of a stored message record.
-   * @param {string} deliveryStatus
-   *        If given, it will be used to update the <code>deliveryStatus</code>
-   *        property of a stored message record.
-   * @param {string} envelopeId
-   *        If given, it will be used to update the <code>envelopeIdIndex</code>
-   *        property of a stored message record.
-   * @param {Object} callback
-   *        The object passed as <code>aCallback</code> to
-   *        {@link MobileMessageDB.newTxnWithCallback}.
-   */
-  setMessageDeliveryByMessageId: function(messageId, receiver, delivery,
-                                          deliveryStatus, envelopeId, callback) {
-    this.updateMessageDeliveryById(messageId, "messageId",
-                                   receiver, delivery, deliveryStatus,
-                                   envelopeId, callback);
-
-  },
-
-  /**
-   * Update the <code>deliveryStatus</code> of the specified
-   * <code>aReceiver</code> within the <code>deliveryInfo</code> of the message
-   * record retrieved by the given <code>envelopeId</code>.
-   *
-   * @function MobileMessageDB.setMessageDeliveryStatusByEnvelopeId
-   * @param {string} aEnvelopeId
-   *        The envelope ID, which is the "x-mms-transaction-id" in the header
-   *        of an MMS message.
-   * @param {string} aReceiver
-   *        The receiver address.
-   * @param {string} aDeliveryStatus
-   *        If given, it will be used to update the <code>deliveryStatus</code>
-   *        property of a stored message record.
-   * @param {Object} aCallback
-   *        The object passed as <code>aCallback</code> to
-   *        {@link MobileMessageDB.newTxnWithCallback}.
-   */
-  setMessageDeliveryStatusByEnvelopeId: function(aEnvelopeId, aReceiver,
-                                                 aDeliveryStatus, aCallback) {
-    this.updateMessageDeliveryById(aEnvelopeId, "envelopeId", aReceiver, null,
-                                   aDeliveryStatus, null, aCallback);
-  },
-
-  /**
-   * Update the <code>readStatus</code> of the specified <code>aReceiver</code>
-   * within the <code>deliveryInfo</code> of the message record retrieved by the
-   * given <code>envelopeId</code>.
-   *
-   * @function MobileMessageDB.setMessageReadStatusByEnvelopeId
-   * @param {string} aEnvelopeId
-   *        The envelope ID, which is the "x-mms-transaction-id" in the header
-   *        of an MMS message.
-   * @param {string} aReceiver
-   *        The receiver address.
-   * @param {string} aReadStatus
-   *        The updated read status.
-   * @param {Object} aCallback
-   *        The object passed as <code>aCallback</code> to
-   *        {@link MobileMessageDB.newTxnWithCallback}.
-   */
-  setMessageReadStatusByEnvelopeId: function(aEnvelopeId, aReceiver,
-                                             aReadStatus, aCallback) {
-    if (DEBUG) {
-      debug("Setting message's read status by envelopeId = " + aEnvelopeId +
-            ", receiver: " + aReceiver + ", readStatus: " + aReadStatus);
-    }
-
-    let self = this;
-    this.newTxnWithCallback(aCallback, function(aCapture, aMessageStore) {
-      let getRequest = aMessageStore.index("envelopeId").get(aEnvelopeId);
-      getRequest.onsuccess = function(event) {
-        let messageRecord = event.target.result;
-        if (!messageRecord) {
-          if (DEBUG) debug("envelopeId '" + aEnvelopeId + "' not found");
-          throw Cr.NS_ERROR_FAILURE;
-        }
-
-        aCapture.messageRecord = messageRecord;
-
-        let isRecordUpdated = false;
-        self.forEachMatchedMmsDeliveryInfo(messageRecord.deliveryInfo,
-                                           aReceiver, function(aEntry) {
-          if (aEntry.readStatus == aReadStatus) {
-            return;
-          }
-
-          aEntry.readStatus = aReadStatus;
-          if (aReadStatus == MMS.DOM_READ_STATUS_SUCCESS) {
-            aEntry.readTimestamp = Date.now();
-          } else {
-            aEntry.readTimestamp = 0;
-          }
-          isRecordUpdated = true;
-        });
-
-        if (!isRecordUpdated) {
-          if (DEBUG) {
-            debug("The values of readStatus don't need to be updated.");
-          }
-          return;
-        }
-
-        if (DEBUG) {
-          debug("The readStatus is updated.");
-        }
-        aMessageStore.put(messageRecord);
-      };
-    });
-  },
-
-  /**
-   * @callback MobileMessageDB.GetMessageRecordCallback
-   * @param {number} aErrorCode
-   *        The error code on failure, or <code>NS_OK</code> on success.
-   * @param {MobileMessageDB.MessageRecord} aMessageRecord
-   *        The stored message record.
-   * @param {nsISmsMessage|nsIMmsMessage} aDomMessage
-   *        The DOM message instance of the message record.
-   */
-
-  /**
-   * Get the message record with given transaction ID.
-   *
-   * @function MobileMessageDB.getMessageRecordByTransactionId
-   * @param {string} aTransactionId
-   *        The transaction ID.
-   * @param {Object} aCallback
-   *        The object which includes a callback function.
-   * @param {MobileMessageDB.GetMessageRecordCallback} aCallback.notify
-   *        The callback function to invoke when the request finishes.
-   */
-  getMessageRecordByTransactionId: function(aTransactionId, aCallback) {
-    if (DEBUG) debug("Retrieving message with transaction ID " + aTransactionId);
-    let self = this;
-    this.newTxn(READ_ONLY, function(error, txn, messageStore) {
-      if (error) {
-        if (DEBUG) debug(error);
-        aCallback.notify(error, null, null);
-        return;
-      }
-      let request = messageStore.index("transactionId").get(aTransactionId);
-
-      txn.oncomplete = function(event) {
-        if (DEBUG) debug("Transaction " + txn + " completed.");
-        let messageRecord = request.result;
-        if (!messageRecord) {
-          if (DEBUG) debug("Transaction ID " + aTransactionId + " not found");
-          aCallback.notify(Cr.NS_ERROR_FILE_NOT_FOUND, null, null);
-          return;
-        }
-        // In this case, we don't need a dom message. Just pass null to the
-        // third argument.
-        aCallback.notify(Cr.NS_OK, messageRecord, null);
-      };
-
-      txn.onerror = function(event) {
-        if (DEBUG) {
-          if (event.target) {
-            debug("Caught error on transaction", event.target.error.name);
-          }
-        }
-        aCallback.notify(Cr.NS_ERROR_FAILURE, null, null);
-      };
-    });
-  },
-
-  /**
-   * Get the message record with given message ID.
-   *
-   * @function MobileMessageDB.getMessageRecordById
-   * @param {string} aMessageID
-   *        The message ID.
-   * @param {Object} aCallback
-   *        The object which includes a callback function.
-   * @param {MobileMessageDB.GetMessageRecordCallback} aCallback.notify
-   *        The callback function to invoke when the request finishes.
-   */
-  getMessageRecordById: function(aMessageId, aCallback) {
-    if (DEBUG) debug("Retrieving message with ID " + aMessageId);
-    let self = this;
-    this.newTxn(READ_ONLY, function(error, txn, messageStore) {
-      if (error) {
-        if (DEBUG) debug(error);
-        aCallback.notify(error, null, null);
-        return;
-      }
-      let request = messageStore.mozGetAll(aMessageId);
-
-      txn.oncomplete = function() {
-        if (DEBUG) debug("Transaction " + txn + " completed.");
-        if (request.result.length > 1) {
-          if (DEBUG) debug("Got too many results for id " + aMessageId);
-          aCallback.notify(Cr.NS_ERROR_UNEXPECTED, null, null);
-          return;
-        }
-        let messageRecord = request.result[0];
-        if (!messageRecord) {
-          if (DEBUG) debug("Message ID " + aMessageId + " not found");
-          aCallback.notify(Cr.NS_ERROR_FILE_NOT_FOUND, null, null);
-          return;
-        }
-        if (messageRecord.id != aMessageId) {
-          if (DEBUG) {
-            debug("Requested message ID (" + aMessageId + ") is " +
-                  "different from the one we got");
-          }
-          aCallback.notify(Cr.NS_ERROR_UNEXPECTED, null, null);
-          return;
-        }
-        let domMessage = self.createDomMessageFromRecord(messageRecord);
-        aCallback.notify(Cr.NS_OK, messageRecord, domMessage);
-      };
-
-      txn.onerror = function(event) {
-        if (DEBUG) {
-          if (event.target) {
-            debug("Caught error on transaction", event.target.error.name);
-          }
-        }
-        aCallback.notify(Cr.NS_ERROR_FAILURE, null, null);
-      };
-    });
-  },
-
-  /**
-   * Helper to translate NS errors to the error causes defined in
-   * <code>nsIMobileMessageCallback</code>.
-   *
-   * @function MobileMessageDB.translateCrErrorToMessageCallbackError
-   * @param {number} aCrError
-   *        The error code defined in <code>Components.result</code>
-   * @return {number}
-   *         The error code defined in <code>nsIMobileMessageCallback</code>
-   */
-  translateCrErrorToMessageCallbackError: function(aCrError) {
-    switch(aCrError) {
-      case Cr.NS_OK:
-        return Ci.nsIMobileMessageCallback.SUCCESS_NO_ERROR;
-      case Cr.NS_ERROR_UNEXPECTED:
-        return Ci.nsIMobileMessageCallback.UNKNOWN_ERROR;
-      case Cr.NS_ERROR_FILE_NOT_FOUND:
-        return Ci.nsIMobileMessageCallback.NOT_FOUND_ERROR;
-      case Cr.NS_ERROR_FILE_NO_DEVICE_SPACE:
-        return Ci.nsIMobileMessageCallback.STORAGE_FULL_ERROR;
-      default:
-        return Ci.nsIMobileMessageCallback.INTERNAL_ERROR;
-    }
-  },
-
-  /**
-   * @callback MobileMessageDB.SaveSmsSegmentCallback
-   * @param {number} aErrorCode
-   *        The error code on failure, or <code>NS_OK</code> on success.
-   * @param {MobileMessageDB.SmsSegmentRecord} aCompleteMessage
-   *        The composing message. It becomes a complete message once the last
-   *        segment is stored.
-   */
-
-  /**
-   * Store a single SMS segment.
-   *
-   * @function MobileMessageDB.saveSmsSegment
-   * @param {MobileMessageDB.SmsSegmentRecord} aSmsSegment
-   *        Single SMS segment.
-   * @param {Object} aCallback
-   *        The object which includes a callback function.
-   * @param {MobileMessageDB.SaveSmsSegmentCallback} aCallback.notify
-   *        The callback function to invoke when the request finishes.
-   */
-  saveSmsSegment: function(aSmsSegment, aCallback) {
-    let completeMessage = null;
-    this.newTxn(READ_WRITE, function(error, txn, segmentStore) {
-      if (error) {
-        if (DEBUG) debug(error);
-        aCallback.notify(error, null);
-        return;
-      }
-
-      txn.oncomplete = function(event) {
-        if (DEBUG) debug("Transaction " + txn + " completed.");
-        if (completeMessage) {
-          // Rebuild full body
-          if (completeMessage.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
-            // Uint8Array doesn't have `concat`, so
-            // we have to merge all segments by hand.
-            let fullDataLen = 0;
-            for (let i = 1; i <= completeMessage.segmentMaxSeq; i++) {
-              fullDataLen += completeMessage.segments[i].length;
-            }
-
-            completeMessage.fullData = new Uint8Array(fullDataLen);
-            for (let d = 0, i = 1; i <= completeMessage.segmentMaxSeq; i++) {
-              let data = completeMessage.segments[i];
-              for (let j = 0; j < data.length; j++) {
-                completeMessage.fullData[d++] = data[j];
-              }
-            }
-          } else {
-            completeMessage.fullBody = completeMessage.segments.join("");
-          }
-
-          // Remove handy fields after completing the concatenation.
-          delete completeMessage.id;
-          delete completeMessage.hash;
-          delete completeMessage.receivedSegments;
-          delete completeMessage.segments;
-        }
-        aCallback.notify(Cr.NS_OK, completeMessage);
-      };
-
-      txn.onabort = function(event) {
-        if (DEBUG) debug("transaction abort due to " + event.target.error.name);
-        let error = (event.target.error.name === 'QuotaExceededError')
-                    ? Cr.NS_ERROR_FILE_NO_DEVICE_SPACE
-                    : Cr.NS_ERROR_FAILURE;
-        aCallback.notify(error, null);
-      };
-
-      aSmsSegment.hash = aSmsSegment.sender + ":" +
-                         aSmsSegment.segmentRef + ":" +
-                         aSmsSegment.segmentMaxSeq + ":" +
-                         aSmsSegment.iccId;
-      let seq = aSmsSegment.segmentSeq;
-      if (DEBUG) {
-        debug("Saving SMS Segment: " + aSmsSegment.hash + ", seq: " + seq);
-      }
-      let getRequest = segmentStore.index("hash").get(aSmsSegment.hash);
-      getRequest.onsuccess = function(event) {
-        let segmentRecord = event.target.result;
-        if (!segmentRecord) {
-          if (DEBUG) {
-            debug("Not found! Create a new record to store the segments.");
-          }
-          aSmsSegment.receivedSegments = 1;
-          aSmsSegment.segments = [];
-          if (aSmsSegment.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
-            aSmsSegment.segments[seq] = aSmsSegment.data;
-          } else {
-            aSmsSegment.segments[seq] = aSmsSegment.body;
-          }
-
-          segmentStore.add(aSmsSegment);
-
-          return;
-        }
-
-        if (DEBUG) {
-          debug("Append SMS Segment into existed message object: " + segmentRecord.id);
-        }
-
-        if (segmentRecord.segments[seq]) {
-          if (segmentRecord.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET &&
-              segmentRecord.encoding == aSmsSegment.encoding &&
-              segmentRecord.segments[seq].length == aSmsSegment.data.length &&
-              segmentRecord.segments[seq].every(function(aElement, aIndex) {
-                return aElement == aSmsSegment.data[aIndex];
-              })) {
-            if (DEBUG) {
-              debug("Got duplicated binary segment no: " + seq);
-            }
-            return;
-          }
-
-          if (segmentRecord.encoding != RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET &&
-              aSmsSegment.encoding != RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET &&
-              segmentRecord.segments[seq] == aSmsSegment.body) {
-            if (DEBUG) {
-              debug("Got duplicated text segment no: " + seq);
-            }
-            return;
-          }
-
-          // Update mandatory properties to ensure that the segments could be
-          // concatenated properly.
-          segmentRecord.encoding = aSmsSegment.encoding;
-          segmentRecord.originatorPort = aSmsSegment.originatorPort;
-          segmentRecord.destinationPort = aSmsSegment.destinationPort;
-          segmentRecord.teleservice = aSmsSegment.teleservice;
-          // Decrease the counter for this collided segment.
-          segmentRecord.receivedSegments--;
-        }
-
-        segmentRecord.timestamp = aSmsSegment.timestamp;
-
-        if (segmentRecord.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
-          segmentRecord.segments[seq] = aSmsSegment.data;
-        } else {
-          segmentRecord.segments[seq] = aSmsSegment.body;
-        }
-        segmentRecord.receivedSegments++;
-
-        // The port information is only available in 1st segment for CDMA WAP Push.
-        // If the segments of a WAP Push are not received in sequence
-        // (e.g., SMS with seq == 1 is not the 1st segment received by the device),
-        // we have to retrieve the port information from 1st segment and
-        // save it into the segmentRecord.
-        if (aSmsSegment.teleservice === RIL.PDU_CDMA_MSG_TELESERIVCIE_ID_WAP
-            && seq === 1) {
-          if (aSmsSegment.originatorPort !== Ci.nsIGonkSmsService.SMS_APPLICATION_PORT_INVALID) {
-            segmentRecord.originatorPort = aSmsSegment.originatorPort;
-          }
-
-          if (aSmsSegment.destinationPort !== Ci.nsIGonkSmsService.SMS_APPLICATION_PORT_INVALID) {
-            segmentRecord.destinationPort = aSmsSegment.destinationPort;
-          }
-        }
-
-        if (segmentRecord.receivedSegments < segmentRecord.segmentMaxSeq) {
-          if (DEBUG) debug("Message is incomplete.");
-          segmentStore.put(segmentRecord);
-          return;
-        }
-
-        completeMessage = segmentRecord;
-
-        // Delete Record in DB
-        segmentStore.delete(segmentRecord.id);
-      };
-    }, [SMS_SEGMENT_STORE_NAME]);
-  },
-
-  /**
-   * nsIMobileMessageDatabaseService API
-   */
-
-  /**
-   * Get the message record with given message ID.
-   *
-   * @function MobileMessageDB.getMessage
-   * @param {string} aMessageID
-   *        The message ID.
-   * @param {nsIMobileMessageCallback} aRequest
-   *        The callback object.
-   */
-  getMessage: function(aMessageId, aRequest) {
-    if (DEBUG) debug("Retrieving message with ID " + aMessageId);
-    let self = this;
-    let notifyCallback = {
-      notify: function(aRv, aMessageRecord, aDomMessage) {
-        if (Cr.NS_OK == aRv) {
-          aRequest.notifyMessageGot(aDomMessage);
-          return;
-        }
-        aRequest.notifyGetMessageFailed(
-          self.translateCrErrorToMessageCallbackError(aRv), null);
-      }
-    };
-    this.getMessageRecordById(aMessageId, notifyCallback);
-  },
-
-  /**
-   * Delete the message record with given message IDs.
-   *
-   * @function MobileMessageDB.deleteMessage
-   * @param {number[]} messageIds
-   *        The IDs of messages to delete.
-   * @param {number} length
-   *        The length of the <code>messageIds</code> array.
-   * @param {nsIMobileMessageCallback} aRequest
-   *        The callback object.
-   */
-  deleteMessage: function(messageIds, length, aRequest) {
-    if (DEBUG) debug("deleteMessage: message ids " + JSON.stringify(messageIds));
-    let deleted = [];
-    let self = this;
-    this.newTxn(READ_WRITE, function(error, txn, stores) {
-      if (error) {
-        if (DEBUG) debug("deleteMessage: failed to open transaction");
-        aRequest.notifyDeleteMessageFailed(
-          self.translateCrErrorToMessageCallbackError(error));
-        return;
-      }
-
-      let deletedInfo = { messageIds: [], threadIds: [] };
-
-      txn.onabort = function(event) {
-        if (DEBUG) debug("transaction abort due to " + event.target.error.name);
-        let error = (event.target.error.name === 'QuotaExceededError')
-                    ? Ci.nsIMobileMessageCallback.STORAGE_FULL_ERROR
-                    : Ci.nsIMobileMessageCallback.INTERNAL_ERROR;
-        aRequest.notifyDeleteMessageFailed(error);
-      };
-
-      const messageStore = stores[0];
-      const threadStore = stores[1];
-
-      txn.oncomplete = function(event) {
-        if (DEBUG) debug("Transaction " + txn + " completed.");
-        aRequest.notifyMessageDeleted(deleted, length);
-        self.notifyDeletedInfo(deletedInfo);
-      };
-
-      let threadsToUpdate = {};
-      let numOfMessagesToDelete = length;
-      let updateThreadInfo = function() {
-        for (let threadId in threadsToUpdate) {
-          let threadInfo = threadsToUpdate[threadId];
-          self.updateThreadByMessageChange(messageStore,
-                                           threadStore,
-                                           threadInfo.threadId,
-                                           threadInfo.removedMsgIds,
-                                           threadInfo.ignoredUnreadCount,
-                                           deletedInfo);
-        }
-      };
-
-      for (let i = 0; i < length; i++) {
-        let messageId = messageIds[i];
-        deleted[i] = false;
-        messageStore.get(messageId).onsuccess = function(messageIndex, event) {
-          let messageRecord = event.target.result;
-          let messageId = messageIds[messageIndex];
-          if (messageRecord) {
-            if (DEBUG) debug("Deleting message id " + messageId);
-
-            // First actually delete the message.
-            messageStore.delete(messageId).onsuccess = function(event) {
-              if (DEBUG) debug("Message id " + messageId + " deleted");
-
-              numOfMessagesToDelete--;
-              deleted[messageIndex] = true;
-              deletedInfo.messageIds.push(messageId);
-
-              // Cache thread info to be updated.
-              let threadId = messageRecord.threadId;
-              if (!threadsToUpdate[threadId]) {
-                threadsToUpdate[threadId] = {
-                  threadId: threadId,
-                  removedMsgIds: [messageId],
-                  ignoredUnreadCount: (!messageRecord.read) ? 1 : 0
-                };
-              } else {
-                let threadInfo = threadsToUpdate[threadId];
-                threadInfo.removedMsgIds.push(messageId);
-                if (!messageRecord.read) {
-                  threadInfo.ignoredUnreadCount++;
-                }
-              }
-
-              // After all messsages are deleted, update unread count and most
-              // recent message of related threads at once.
-              if (!numOfMessagesToDelete) {
-                updateThreadInfo();
-              }
-            };
-          } else {
-            if (DEBUG) debug("Message id " + messageId + " does not exist");
-
-            numOfMessagesToDelete--;
-            if (!numOfMessagesToDelete) {
-              updateThreadInfo();
-            }
-          }
-        }.bind(null, i);
-      }
-    }, [MESSAGE_STORE_NAME, THREAD_STORE_NAME]);
-  },
-
-  /**
-   * Create a cursor to iterate on stored message records.
-   *
-   * @function MobileMessageDB.createMessageCursor
-   * @param {boolean} aHasStartDate
-   *        <code>true</code> to query only messages starts with
-   *        <code>aStartDate</code>
-   * @param {number} aStartDate
-   *        The timestamp of start date in milliseconds.
-   * @param {boolean} aHasEndDate
-   *        <code>true</code> to query only messages before the
-   *        <code>aEndDate</code>
-   * @param {number} aEndDate
-   *        The timestamp of end date in milliseconds.
-   * @param {string[]} aNumbers
-   *        If not <code>null</code>, query only messages with sender or
-   *        receiver who's number matches one of the numbers listed in the array.
-   * @param {number} aNumbersCount
-   *        The length of <code>aNumbers</code> array.
-   * @param {string} aDelivery
-   *        If not <code>null</code>, query only messages matching the delivery
-   *        value.
-   * @param {boolean} aHasRead
-   *        <code>true</code> to query only messages match the read value
-   *        specified by <code>aRead</code>
-   * @param {boolean} aRead
-   *        Specify the <code>read</code> query condition.
-   * @param {number} aThreadId
-   *        If not <code>null</code>, query only messages in the given thread.
-   * @param {boolean} aReverse
-   *        <code>true</code> to reverse the order.
-   * @param {nsIMobileMessageCursorCallback} aCallback
-   *        The callback object used by GetMessagesCursor
-   * @return {GetMessagesCursor}
-   *         The cursor to iterate on messages.
-   */
-  createMessageCursor: function(aHasStartDate, aStartDate, aHasEndDate,
-                                aEndDate, aNumbers, aNumbersCount, aDelivery,
-                                aHasRead, aRead, aHasThreadId, aThreadId,
-                                aReverse, aCallback) {
-    if (DEBUG) {
-      debug("Creating a message cursor. Filters:" +
-            " startDate: " + (aHasStartDate ? aStartDate : "(null)") +
-            " endDate: " + (aHasEndDate ? aEndDate : "(null)") +
-            " delivery: " + aDelivery +
-            " numbers: " + (aNumbersCount ? aNumbers : "(null)") +
-            " read: " + (aHasRead ? aRead : "(null)") +
-            " threadId: " + (aHasThreadId ? aThreadId : "(null)") +
-            " reverse: " + aReverse);
-    }
-
-    let filter = {};
-    if (aHasStartDate) {
-      filter.startDate = aStartDate;
-    }
-    if (aHasEndDate) {
-      filter.endDate = aEndDate;
-    }
-    if (aNumbersCount) {
-      filter.numbers = aNumbers.slice();
-    }
-    if (aDelivery !== null) {
-      filter.delivery = aDelivery;
-    }
-    if (aHasRead) {
-      filter.read = aRead;
-    }
-    if (aHasThreadId) {
-      filter.threadId = aThreadId;
-    }
-
-    let cursor = new GetMessagesCursor(this, aCallback);
-
-    let self = this;
-    self.newTxn(READ_ONLY, function(error, txn, stores) {
-      let collector = cursor.collector.idCollector;
-      let collect = collector.collect.bind(collector);
-      FilterSearcherHelper.transact(self, txn, error, filter, aReverse, collect);
-    }, [MESSAGE_STORE_NAME, PARTICIPANT_STORE_NAME]);
-
-    return cursor;
-  },
-
-  /**
-   * Change the <code>read</code> property of a stored message record.
-   *
-   * @function MobileMessageDB.markMessageRead
-   * @param {number} messageId
-   *        The message ID.
-   * @param {boolean} value
-   *        The updated <code>read</code> value.
-   * @param {boolean} aSendReadReport
-   *        <code>true</code> to reply the read report of an incoming MMS
-   *        message whose <code>isReadReportSent</code> is 'false'.
-   *        Note: <code>isReadReportSent</code> will be set to 'true' no
-   *        matter aSendReadReport is true or not when a message was marked
-   *        from UNREAD to READ. See bug 1180470 for the new UX policy.
-   * @param {nsIMobileMessageCallback} aRequest
-   *        The callback object.
-   */
-  markMessageRead: function(messageId, value, aSendReadReport, aRequest) {
-    if (DEBUG) debug("Setting message " + messageId + " read to " + value);
-    let self = this;
-    this.newTxn(READ_WRITE, function(error, txn, stores) {
-      if (error) {
-        if (DEBUG) debug(error);
-        aRequest.notifyMarkMessageReadFailed(
-          self.translateCrErrorToMessageCallbackError(error));
-        return;
-      }
-
-      txn.onabort = function(event) {
-        if (DEBUG) debug("transaction abort due to " + event.target.error.name);
-        let error = (event.target.error.name === 'QuotaExceededError')
-                    ? Ci.nsIMobileMessageCallback.STORAGE_FULL_ERROR
-                    : Ci.nsIMobileMessageCallback.INTERNAL_ERROR;
-        aRequest.notifyMarkMessageReadFailed(error);
-      };
-
-      let messageStore = stores[0];
-      let threadStore = stores[1];
-      messageStore.get(messageId).onsuccess = function(event) {
-        let messageRecord = event.target.result;
-        if (!messageRecord) {
-          if (DEBUG) debug("Message ID " + messageId + " not found");
-          aRequest.notifyMarkMessageReadFailed(Ci.nsIMobileMessageCallback.NOT_FOUND_ERROR);
-          return;
-        }
-
-        if (messageRecord.id != messageId) {
-          if (DEBUG) {
-            debug("Retrieve message ID (" + messageId + ") is " +
-                  "different from the one we got");
-          }
-          aRequest.notifyMarkMessageReadFailed(Ci.nsIMobileMessageCallback.UNKNOWN_ERROR);
-          return;
-        }
-
-        // If the value to be set is the same as the current message `read`
-        // value, we just notify successfully.
-        if (messageRecord.read == value) {
-          if (DEBUG) debug("The value of messageRecord.read is already " + value);
-          aRequest.notifyMessageMarkedRead(messageRecord.read);
-          return;
-        }
-
-        messageRecord.read = value ? FILTER_READ_READ : FILTER_READ_UNREAD;
-        messageRecord.readIndex = [messageRecord.read, messageRecord.timestamp];
-        let readReportMessageId, readReportTo;
-        if (messageRecord.type == "mms" &&
-            messageRecord.delivery == DELIVERY_RECEIVED &&
-            messageRecord.read == FILTER_READ_READ &&
-            messageRecord.headers["x-mms-read-report"] &&
-            !messageRecord.isReadReportSent) {
-          messageRecord.isReadReportSent = true;
-
-          if (aSendReadReport) {
-            let from = messageRecord.headers["from"];
-            readReportTo = from && from.address;
-            readReportMessageId = messageRecord.headers["message-id"];
-          }
-        }
-
-        if (DEBUG) debug("Message.read set to: " + value);
-        messageStore.put(messageRecord).onsuccess = function(event) {
-          if (DEBUG) {
-            debug("Update successfully completed. Message: " +
-                  JSON.stringify(event.target.result));
-          }
-
-          // Now update the unread count.
-          let threadId = messageRecord.threadId;
-
-          threadStore.get(threadId).onsuccess = function(event) {
-            let threadRecord = event.target.result;
-            threadRecord.unreadCount += value ? -1 : 1;
-            if (DEBUG) {
-              debug("Updating unreadCount for thread id " + threadId + ": " +
-                    (value ?
-                     threadRecord.unreadCount + 1 :
-                     threadRecord.unreadCount - 1) +
-                     " -> " + threadRecord.unreadCount);
-            }
-            threadStore.put(threadRecord).onsuccess = function(event) {
-              if(readReportMessageId && readReportTo) {
-                gMMSService.sendReadReport(readReportMessageId,
-                                           readReportTo,
-                                           messageRecord.iccId);
-              }
-              aRequest.notifyMessageMarkedRead(messageRecord.read);
-            };
-          };
-        };
-      };
-    }, [MESSAGE_STORE_NAME, THREAD_STORE_NAME]);
-  },
-
-  /**
-   * Create a cursor to iterate on stored threads.
-   *
-   * @function MobileMessageDB.createThreadCursor
-   * @param {nsIMobileMessageCursorCallback} callback
-   *        The callback object used by GetMessagesCursor
-   * @return {GetThreadsCursor}
-   *         The cursor to iterate on threads.
-   */
-  createThreadCursor: function(callback) {
-    if (DEBUG) debug("Getting thread list");
-
-    let cursor = new GetThreadsCursor(this, callback);
-    this.newTxn(READ_ONLY, function(error, txn, threadStore) {
-      let collector = cursor.collector.idCollector;
-      if (error) {
-        collector.collect(null, COLLECT_ID_ERROR, COLLECT_TIMESTAMP_UNUSED);
-        return;
-      }
-      txn.onerror = function(event) {
-        if (DEBUG) debug("Caught error on transaction ", event.target.error.name);
-        collector.collect(null, COLLECT_ID_ERROR, COLLECT_TIMESTAMP_UNUSED);
-      };
-      let request = threadStore.index("lastTimestamp").openKeyCursor(null, PREV);
-      request.onsuccess = function(event) {
-        let cursor = event.target.result;
-        if (cursor) {
-          if (collector.collect(txn, cursor.primaryKey, cursor.key)) {
-            cursor.continue();
-          }
-        } else {
-          collector.collect(txn, COLLECT_ID_END, COLLECT_TIMESTAMP_UNUSED);
-        }
-      };
-    }, [THREAD_STORE_NAME]);
-
-    return cursor;
-  }
-};
-
-var FilterSearcherHelper = {
-
-  /**
-   * @param index
-   *        The name of a message store index to filter on.
-   * @param range
-   *        A IDBKeyRange.
-   * @param direction
-   *        NEXT or PREV.
-   * @param txn
-   *        Ongoing IDBTransaction context object.
-   * @param collect
-   *        Result colletor function. It takes three parameters -- txn, message
-   *        id, and message timestamp.
-   */
-  filterIndex: function(index, range, direction, txn, collect) {
-    let messageStore = txn.objectStore(MESSAGE_STORE_NAME);
-    let request = messageStore.index(index).openKeyCursor(range, direction);
-    request.onsuccess = function(event) {
-      let cursor = event.target.result;
-      // Once the cursor has retrieved all keys that matches its key range,
-      // the filter search is done.
-      if (cursor) {
-        let timestamp = Array.isArray(cursor.key) ? cursor.key[1] : cursor.key;
-        if (collect(txn, cursor.primaryKey, timestamp)) {
-          cursor.continue();
-        }
-      } else {
-        collect(txn, COLLECT_ID_END, COLLECT_TIMESTAMP_UNUSED);
-      }
-    };
-    request.onerror = function(event) {
-      if (DEBUG && event) debug("IDBRequest error " + event.target.error.name);
-      collect(txn, COLLECT_ID_ERROR, COLLECT_TIMESTAMP_UNUSED);
-    };
-  },
-
-  /**
-   * Explicitly filter message on the timestamp index.
-   *
-   * @param startDate
-   *        Timestamp of the starting date.
-   * @param endDate
-   *        Timestamp of the ending date.
-   * @param direction
-   *        NEXT or PREV.
-   * @param txn
-   *        Ongoing IDBTransaction context object.
-   * @param collect
-   *        Result colletor function. It takes three parameters -- txn, message
-   *        id, and message timestamp.
-   */
-  filterTimestamp: function(startDate, endDate, direction, txn, collect) {
-    let range = null;
-    if (startDate != null && endDate != null) {
-      range = IDBKeyRange.bound(startDate, endDate);
-    } else if (startDate != null) {
-      range = IDBKeyRange.lowerBound(startDate);
-    } else if (endDate != null) {
-      range = IDBKeyRange.upperBound(endDate);
-    }
-    this.filterIndex("timestamp", range, direction, txn, collect);
-  },
-
-  /**
-   * Initiate a filtering transaction.
-   *
-   * @param mmdb
-   *        A MobileMessageDB.
-   * @param txn
-   *        Ongoing IDBTransaction context object.
-   * @param error
-   *        Previous error while creating the transaction.
-   * @param filter
-   *        A MobileMessageFilter dictionary.
-   * @param reverse
-   *        A boolean value indicating whether we should filter message in
-   *        reversed order.
-   * @param collect
-   *        Result collector function. It takes three parameters -- txn, message
-   *        id, and message timestamp.
-   */
-  transact: function(mmdb, txn, error, filter, reverse, collect) {
-    if (error) {
-      // TODO look at event.target.error.name, pick appropriate error constant.
-      if (DEBUG) debug("IDBRequest error " + event.target.error.name);
-      collect(txn, COLLECT_ID_ERROR, COLLECT_TIMESTAMP_UNUSED);
-      return;
-    }
-
-    let direction = reverse ? PREV : NEXT;
-
-    // We support filtering by date range only (see `else` block below) or by
-    // number/delivery status/read status with an optional date range.
-    if (filter.delivery == null &&
-        filter.numbers == null &&
-        filter.read == null &&
-        filter.threadId == null) {
-      // Filtering by date range only.
-      if (DEBUG) {
-        debug("filter.timestamp " + filter.startDate + ", " + filter.endDate);
-      }
-
-      this.filterTimestamp(filter.startDate, filter.endDate, direction, txn,
-                           collect);
-      return;
-    }
-
-    // Numeric 0 is smaller than any time stamp, and empty string is larger
-    // than all numeric values.
-    let startDate = 0, endDate = "";
-    if (filter.startDate != null) {
-      startDate = filter.startDate;
-    }
-    if (filter.endDate != null) {
-      endDate = filter.endDate;
-    }
-
-    let single, intersectionCollector;
-    {
-      let num = 0;
-      if (filter.delivery) num++;
-      if (filter.numbers) num++;
-      if (filter.read != undefined) num++;
-      if (filter.threadId != undefined) num++;
-      single = (num == 1);
-    }
-
-    if (!single) {
-      intersectionCollector = new IntersectionResultsCollector(collect, reverse);
-    }
-
-    // Retrieve the keys from the 'delivery' index that matches the value of
-    // filter.delivery.
-    if (filter.delivery) {
-      if (DEBUG) debug("filter.delivery " + filter.delivery);
-      let delivery = filter.delivery;
-      let range = IDBKeyRange.bound([delivery, startDate], [delivery, endDate]);
-      this.filterIndex("delivery", range, direction, txn,
-                       single ? collect : intersectionCollector.newContext());
-    }
-
-    // Retrieve the keys from the 'read' index that matches the value of
-    // filter.read.
-    if (filter.read != undefined) {
-      if (DEBUG) debug("filter.read " + filter.read);
-      let read = filter.read ? FILTER_READ_READ : FILTER_READ_UNREAD;
-      let range = IDBKeyRange.bound([read, startDate], [read, endDate]);
-      this.filterIndex("read", range, direction, txn,
-                       single ? collect : intersectionCollector.newContext());
-    }
-
-    // Retrieve the keys from the 'threadId' index that matches the value of
-    // filter.threadId.
-    if (filter.threadId != undefined) {
-      if (DEBUG) debug("filter.threadId " + filter.threadId);
-      let threadId = filter.threadId;
-      let range = IDBKeyRange.bound([threadId, startDate], [threadId, endDate]);
-      this.filterIndex("threadId", range, direction, txn,
-                       single ? collect : intersectionCollector.newContext());
-    }
-
-    // Retrieve the keys from the 'sender' and 'receiver' indexes that
-    // match the values of filter.numbers
-    if (filter.numbers) {
-      if (DEBUG) debug("filter.numbers " + filter.numbers.join(", "));
-
-      if (!single) {
-        collect = intersectionCollector.newContext();
-      }
-
-      let participantStore = txn.objectStore(PARTICIPANT_STORE_NAME);
-      let typedAddresses = filter.numbers.map(function(number) {
-        return {
-          address: number,
-          type: MMS.Address.resolveType(number)
-        };
-      });
-      mmdb.findParticipantIdsByTypedAddresses(participantStore, typedAddresses,
-                                              false, true,
-                                              (function(participantIds) {
-        if (!participantIds || !participantIds.length) {
-          // Oops! No such participant at all.
-
-          collect(txn, COLLECT_ID_END, COLLECT_TIMESTAMP_UNUSED);
-          return;
-        }
-
-        if (participantIds.length == 1) {
-          let id = participantIds[0];
-          let range = IDBKeyRange.bound([id, startDate], [id, endDate]);
-          this.filterIndex("participantIds", range, direction, txn, collect);
-          return;
-        }
-
-        let unionCollector = new UnionResultsCollector(collect);
-
-        this.filterTimestamp(filter.startDate, filter.endDate, direction, txn,
-                             unionCollector.newTimestampContext());
-
-        for (let i = 0; i < participantIds.length; i++) {
-          let id = participantIds[i];
-          let range = IDBKeyRange.bound([id, startDate], [id, endDate]);
-          this.filterIndex("participantIds", range, direction, txn,
-                           unionCollector.newContext());
-        }
-      }).bind(this));
-    }
-  }
-};
-
-/**
- * Collector class for read-ahead result objects. Mmdb may now try to fetch
- * message/thread records before it's requested explicitly.
- *
- * The read ahead behavior can be controlled by an integer mozSettings entry
- * "ril.sms.maxReadAheadEntries" as well as an integer holding preference
- * "dom.sms.maxReadAheadEntries". The meanings are:
- *
- *   positive: finite read-ahead entries,
- *   0: don't read ahead unless explicitly requested, (default)
- *   negative: read ahead all IDs if possible.
- *
- * The order of ID filtering objects are now:
- *
- *   [UnionResultsCollector]
- *   +-> [IntersectionResultsCollector]
- *       +-> IDsCollector
- *           +-> ResultsCollector
- *
- * ResultsCollector has basically similar behaviour with IDsCollector. When
- * RC::squeeze() is called, either RC::drip() is called instantly if we have
- * already fetched results available, or the request is kept and IC::squeeze()
- * is called.
- *
- * When RC::collect is called by IC::drip, it proceeds to fetch the
- * corresponding record given that collected ID is neither an error nor an end
- * mark. After the message/thread record being fetched, ResultsCollector::drip
- * is called if we have pending request. Anyway, RC::maybeSqueezeIdCollector is
- * called to determine whether we need to call IC::squeeze again.
- *
- * RC::squeeze is called when nsICursorContinueCallback::handleContinue() is
- * called. ResultsCollector::drip will call to
- * nsIMobileMessageCursorCallback::notifyFoo.
- *
- * In summary, the major call paths are:
- *
- *   RC::squeeze
- *   o-> RC::drip
- *       +-> RC::notifyCallback
- *           +-> nsIMobileMessageCursorCallback::notifyFoo
- *   +-> RC::maybeSqueezeIdCollector
- *       o-> IC::squeeze
- *           o-> IC::drip
- *               +-> RC::collect
- *                   o-> RC::readAhead
- *                       +-> RC::notifyResult
- *                           o-> RC::drip ...
- *                           +-> RC::maybeSqueezeIdCollector ...
- *                   o-> RC::notifyResult ...
- */
-function ResultsCollector(readAheadFunc) {
-  this.idCollector = new IDsCollector();
-  this.results = [];
-  this.readAhead = readAheadFunc;
-
-  this.maxReadAhead = DEFAULT_READ_AHEAD_ENTRIES;
-  try {
-    // positive: finite read-ahead entries,
-    // 0: don't read ahead unless explicitly requested,
-    // negative: read ahead all IDs if possible.
-    this.maxReadAhead =
-      Services.prefs.getIntPref("dom.sms.maxReadAheadEntries");
-  } catch (e) {}
-}
-ResultsCollector.prototype = {
-  /**
-   * Underlying ID collector object.
-   */
-  idCollector: null,
-
-  /**
-   * An array keeping fetched result objects. Replaced by a new empty array
-   * every time when |this.drip| is called.
-   */
-  results: null,
-
-  /**
-   * A function that takes (<txn>, <id>, <collector>). It fetches the object
-   * specified by <id> and notify <collector> with that by calling
-   * |<collector>.notifyResult()|. If <txn> is null, this function should
-   * create a new read-only transaction itself. The returned result object may
-   * be null to indicate an error during the fetch process.
-   */
-  readAhead: null,
-
-  /**
-   * A boolean value inidicating a readAhead call is ongoing. Set before calling
-   * |this.readAhead| and reset in |this.notifyResult|.
-   */
-  readingAhead: false,
-
-  /**
-   * A numeric value read from preference "dom.sms.maxReadAheadEntries".
-   */
-  maxReadAhead: 0,
-
-  /**
-   * An active IDBTransaction object to be reused.
-   */
-  activeTxn: null,
-
-  /**
-   * A nsIMobileMessageCursorCallback.
-   */
-  requestWaiting: null,
-
-  /**
-   * A boolean value indicating either a COLLECT_ID_END or COLLECT_ID_ERROR has
-   * been received.
-   */
-  done: false,
-
-  /**
-   * When |this.done|, it's either COLLECT_ID_END or COLLECT_ID_ERROR.
-   */
-  lastId: null,
-
-  /**
-   * Receive collected id from IDsCollector and fetch the correspond result
-   * object if necessary.
-   *
-   * @param txn
-   *        An IDBTransaction object. Null if there is no active transaction in
-   *        IDsCollector. That is, the ID collecting transaction is completed.
-   * @param id
-   *        A positive numeric id, COLLECT_ID_END(0), or COLLECT_ID_ERROR(-1).
-   */
-  collect: function(txn, id) {
-    if (this.done) {
-      // If this callector has been terminated because of previous errors in
-      // |this.readAhead|, ignore any further IDs from IDsCollector.
-      return;
-    }
-
-    if (DEBUG) debug("ResultsCollector::collect ID = " + id);
-
-    // Reuse the active transaction cached if IDsCollector has no active
-    // transaction.
-    txn = txn || this.activeTxn;
-
-    if (id > 0) {
-      this.readingAhead = true;
-      this.readAhead(txn, id, this);
-    } else {
-      this.notifyResult(txn, id, null);
-    }
-  },
-
-  /**
-   * Callback function for |this.readAhead|.
-   *
-   * This function pushes result object to |this.results| or updates
-   * |this.done|, |this.lastId| if an end mark or an error is found. Since we
-   * have already a valid result entry, check |this.requestWaiting| and deal
-   * with it. At last, call to |this.maybeSqueezeIdCollector| to ask more id
-   * again if necessary.
-   *
-   * @param txn
-   *        An IDBTransaction object. Null if caller has no active transaction.
-   * @param id
-   *        A positive numeric id, COLLECT_ID_END(0), or COLLECT_ID_ERROR(-1).
-   * @param result
-   *        An object associated with id. Null if |this.readAhead| failed.
-   */
-  notifyResult: function(txn, id, result) {
-    if (DEBUG) debug("notifyResult(txn, " + id + ", <result>)");
-
-    this.readingAhead = false;
-
-    if (id > 0) {
-      if (result != null) {
-        this.results.push(result);
-      } else {
-        id = COLLECT_ID_ERROR;
-      }
-    }
-
-    if (id <= 0) {
-      this.lastId = id;
-      this.done = true;
-    }
-
-    if (!this.requestWaiting) {
-      if (DEBUG) debug("notifyResult: cursor.continue() not called yet");
-    } else {
-      let callback = this.requestWaiting;
-      this.requestWaiting = null;
-
-      this.drip(callback);
-    }
-
-    this.maybeSqueezeIdCollector(txn);
-  },
-
-  /**
-   * Request for one more ID if necessary.
-   *
-   * @param txn
-   *        An IDBTransaction object. Null if caller has no active transaction.
-   */
-  maybeSqueezeIdCollector: function(txn) {
-    if (this.done || // Nothing to be read.
-        this.readingAhead || // Already in progress.
-        this.idCollector.requestWaiting) { // Already requested.
-      return;
-    }
-
-    let max = this.maxReadAhead;
-    if (!max && this.requestWaiting) {
-      // If |this.requestWaiting| is set, try to read ahead at least once.
-      max = 1;
-    }
-    if (max >= 0 && this.results.length >= max) {
-      // More-equal than <max> entries has been read. Stop.
-      if (DEBUG) debug("maybeSqueezeIdCollector: max " + max + " entries read. Stop.");
-      return;
-    }
-
-    // A hack to pass current txn to |this.collect| when it's called directly by
-    // |IDsCollector.squeeze|.
-    this.activeTxn = txn;
-    this.idCollector.squeeze(this.collect.bind(this));
-    this.activeTxn = null;
-  },
-
-  /**
-   * Request to pass available results or wait.
-   *
-   * @param callback
-   *        A nsIMobileMessageCursorCallback.
-   */
-  squeeze: function(callback) {
-    if (this.requestWaiting) {
-      throw new Error("Already waiting for another request!");
-    }
-
-    if (this.results.length || this.done) {
-      // If |this.results.length| is non-zero, we have already some results to
-      // pass. Otherwise, if |this.done| evaluates to true, we have also a
-      // confirmed result to pass.
-      this.drip(callback);
-    } else {
-      this.requestWaiting = callback;
-    }
-
-    // If we called |this.drip| in the last step, the fetched results have been
-    // consumed and we should ask some more for read-ahead now.
-    //
-    // Otherwise, kick start read-ahead again because it may be stopped
-    // previously because of |this.maxReadAhead| had been reached.
-    this.maybeSqueezeIdCollector(null);
-  },
-
-  /**
-   * Consume fetched resutls.
-   *
-   * @param callback
-   *        A nsIMobileMessageCursorCallback.
-   */
-  drip: function(callback) {
-    let results = this.results;
-    this.results = [];
-
-    let func = this.notifyCallback.bind(this, callback, results, this.lastId);
-    Services.tm.currentThread.dispatch(func, Ci.nsIThread.DISPATCH_NORMAL);
-  },
-
-  /**
-   * Notify a nsIMobileMessageCursorCallback.
-   *
-   * @param callback
-   *        A nsIMobileMessageCursorCallback.
-   * @param results
-   *        An array of result objects.
-   * @param lastId
-   *        Since we only call |this.drip| when either there are results
-   *        available or the read-ahead has done, so lastId here will be
-   *        COLLECT_ID_END or COLLECT_ID_ERROR when results is empty and null
-   *        otherwise.
-   */
-  notifyCallback: function(callback, results, lastId) {
-    if (DEBUG) {
-      debug("notifyCallback(results[" + results.length + "], " + lastId + ")");
-    }
-
-    if (results.length) {
-      callback.notifyCursorResult(results, results.length);
-    } else if (lastId == COLLECT_ID_END) {
-      callback.notifyCursorDone();
-    } else {
-      callback.notifyCursorError(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
-    }
-  }
-};
-
-function IDsCollector() {
-  this.results = [];
-  this.done = false;
-}
-IDsCollector.prototype = {
-  results: null,
-  requestWaiting: null,
-  done: null,
-
-  /**
-   * Queue up passed id, reply if necessary.
-   *
-   * @param txn
-   *        Ongoing IDBTransaction context object.
-   * @param id
-   *        COLLECT_ID_END(0) for no more results, COLLECT_ID_ERROR(-1) for
-   *        errors and valid otherwise.
-   * @param timestamp
-   *        We assume this function is always called in timestamp order. So
-   *        this parameter is actually unused.
-   *
-   * @return true if expects more. false otherwise.
-   */
-  collect: function(txn, id, timestamp) {
-    if (this.done) {
-      return false;
-    }
-
-    if (DEBUG) debug("IDsCollector::collect ID = " + id);
-    // Queue up any id.
-    this.results.push(id);
-    if (id <= 0) {
-      // No more processing on '0' or negative values passed.
-      this.done = true;
-    }
-
-    if (!this.requestWaiting) {
-      if (DEBUG) debug("IDsCollector::squeeze() not called yet");
-      return !this.done;
-    }
-
-    // We assume there is only one request waiting throughout the message list
-    // retrieving process. So we don't bother continuing to process further
-    // waiting requests here. This assumption comes from DOMCursor::Continue()
-    // implementation.
-    let callback = this.requestWaiting;
-    this.requestWaiting = null;
-
-    this.drip(txn, callback);
-
-    return !this.done;
-  },
-
-  /**
-   * Callback right away with the first queued result entry if the filtering is
-   * done. Or queue up the request and callback when a new entry is available.
-   *
-   * @param callback
-   *        A callback function that accepts a numeric id.
-   */
-  squeeze: function(callback) {
-    if (this.requestWaiting) {
-      throw new Error("Already waiting for another request!");
-    }
-
-    if (!this.done) {
-      // Database transaction ongoing, let it reply for us so that we won't get
-      // blocked by the existing transaction.
-      this.requestWaiting = callback;
-      return;
-    }
-
-    this.drip(null, callback);
-  },
-
-  /**
-   * @param txn
-   *        Ongoing IDBTransaction context object or null.
-   * @param callback
-   *        A callback function that accepts a numeric id.
-   */
-  drip: function(txn, callback) {
-    let firstId = this.results[0];
-    if (firstId > 0) {
-      this.results.shift();
-    }
-    callback(txn, firstId);
-  }
-};
-
-function IntersectionResultsCollector(collect, reverse) {
-  this.cascadedCollect = collect;
-  this.reverse = reverse;
-  this.contexts = [];
-}
-IntersectionResultsCollector.prototype = {
-  cascadedCollect: null,
-  reverse: false,
-  contexts: null,
-
-  /**
-   * Queue up {id, timestamp} pairs, find out intersections and report to
-   * |cascadedCollect|. Return true if it is still possible to have another match.
-   */
-  collect: function(contextIndex, txn, id, timestamp) {
-    if (DEBUG) {
-      debug("IntersectionResultsCollector: "
-            + contextIndex + ", " + id + ", " + timestamp);
-    }
-
-    let contexts = this.contexts;
-    let context = contexts[contextIndex];
-
-    if (id < 0) {
-      // Act as no more matched records.
-      id = 0;
-    }
-    if (!id) {
-      context.done = true;
-
-      if (!context.results.length) {
-        // Already empty, can't have further intersection results.
-        return this.cascadedCollect(txn, COLLECT_ID_END, COLLECT_TIMESTAMP_UNUSED);
-      }
-
-      for (let i = 0; i < contexts.length; i++) {
-        if (!contexts[i].done) {
-          // Don't call |this.cascadedCollect| because |context.results| might not
-          // be empty, so other contexts might still have a chance here.
-          return false;
-        }
-      }
-
-      // It was the last processing context and is no more processing.
-      return this.cascadedCollect(txn, COLLECT_ID_END, COLLECT_TIMESTAMP_UNUSED);
-    }
-
-    // Search id in other existing results. If no other results has it,
-    // and A) the last timestamp is smaller-equal to current timestamp,
-    // we wait for further results; either B) record timestamp is larger
-    // then current timestamp or C) no more processing for a filter, then we
-    // drop this id because there can't be a match anymore.
-    for (let i = 0; i < contexts.length; i++) {
-      if (i == contextIndex) {
-        continue;
-      }
-
-      let ctx = contexts[i];
-      let results = ctx.results;
-      let found = false;
-      for (let j = 0; j < results.length; j++) {
-        let result = results[j];
-        if (result.id == id) {
-          found = true;
-          break;
-        }
-        if ((!this.reverse && (result.timestamp > timestamp)) ||
-            (this.reverse && (result.timestamp < timestamp))) {
-          // B) Cannot find a match anymore. Drop.
-          return true;
-        }
-      }
-
-      if (!found) {
-        if (ctx.done) {
-          // C) Cannot find a match anymore. Drop.
-          if (results.length) {
-            let lastResult = results[results.length - 1];
-            if ((!this.reverse && (lastResult.timestamp >= timestamp)) ||
-                (this.reverse && (lastResult.timestamp <= timestamp))) {
-              // Still have a chance to get another match. Return true.
-              return true;
-            }
-          }
-
-          // Impossible to find another match because all results in ctx have
-          // timestamps smaller than timestamp.
-          context.done = true;
-          return this.cascadedCollect(txn, COLLECT_ID_END, COLLECT_TIMESTAMP_UNUSED);
-        }
-
-        // A) Pending.
-        context.results.push({
-          id: id,
-          timestamp: timestamp
-        });
-        return true;
-      }
-    }
-
-    // Now id is found in all other results. Report it.
-    return this.cascadedCollect(txn, id, timestamp);
-  },
-
-  newContext: function() {
-    let contextIndex = this.contexts.length;
-    this.contexts.push({
-      results: [],
-      done: false
-    });
-    return this.collect.bind(this, contextIndex);
-  }
-};
-
-function UnionResultsCollector(collect) {
-  this.cascadedCollect = collect;
-  this.contexts = [{
-    // Timestamp.
-    processing: 1,
-    results: []
-  }, {
-    processing: 0,
-    results: []
-  }];
-}
-UnionResultsCollector.prototype = {
-  cascadedCollect: null,
-  contexts: null,
-
-  collect: function(contextIndex, txn, id, timestamp) {
-    if (DEBUG) {
-      debug("UnionResultsCollector: "
-            + contextIndex + ", " + id + ", " + timestamp);
-    }
-
-    let contexts = this.contexts;
-    let context = contexts[contextIndex];
-
-    if (id < 0) {
-      // Act as no more matched records.
-      id = 0;
-    }
-    if (id) {
-      if (!contextIndex) {
-        // Timestamp.
-        context.results.push({
-          id: id,
-          timestamp: timestamp
-        });
-      } else {
-        context.results.push(id);
-      }
-      return true;
-    }
-
-    context.processing -= 1;
-    if (contexts[0].processing || contexts[1].processing) {
-      // At least one queue is still processing, but we got here because
-      // current cursor gives 0 as id meaning no more messages are
-      // available. Return false here to stop further cursor.continue() calls.
-      return false;
-    }
-
-    let tres = contexts[0].results;
-    let qres = contexts[1].results;
-    tres = tres.filter(function(element) {
-      return qres.indexOf(element.id) != -1;
-    });
-
-    for (let i = 0; i < tres.length; i++) {
-      this.cascadedCollect(txn, tres[i].id, tres[i].timestamp);
-    }
-    this.cascadedCollect(txn, COLLECT_ID_END, COLLECT_TIMESTAMP_UNUSED);
-
-    return false;
-  },
-
-  newTimestampContext: function() {
-    return this.collect.bind(this, 0);
-  },
-
-  newContext: function() {
-    this.contexts[1].processing++;
-    return this.collect.bind(this, 1);
-  }
-};
-
-function GetMessagesCursor(mmdb, callback) {
-  this.mmdb = mmdb;
-  this.callback = callback;
-  this.collector = new ResultsCollector(this.getMessage.bind(this));
-
-  this.handleContinue(); // Trigger first run.
-}
-GetMessagesCursor.prototype = {
-  classID: RIL_GETMESSAGESCURSOR_CID,
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsICursorContinueCallback]),
-
-  mmdb: null,
-  callback: null,
-  collector: null,
-
-  getMessageTxn: function(txn, messageStore, messageId, collector) {
-    if (DEBUG) debug ("Fetching message " + messageId);
-
-    let getRequest = messageStore.get(messageId);
-    let self = this;
-    getRequest.onsuccess = function(event) {
-      if (DEBUG) {
-        debug("notifyNextMessageInListGot - messageId: " + messageId);
-      }
-      let domMessage =
-        self.mmdb.createDomMessageFromRecord(event.target.result);
-      collector.notifyResult(txn, messageId, domMessage);
-    };
-    getRequest.onerror = function(event) {
-      // Error reporting is done in ResultsCollector.notifyCallback.
-      event.stopPropagation();
-      event.preventDefault();
-
-      if (DEBUG) {
-        debug("notifyCursorError - messageId: " + messageId);
-      }
-      collector.notifyResult(txn, messageId, null);
-    };
-  },
-
-  getMessage: function(txn, messageId, collector) {
-    // When filter transaction is not yet completed, we're called with current
-    // ongoing transaction object.
-    if (txn) {
-      let messageStore = txn.objectStore(MESSAGE_STORE_NAME);
-      this.getMessageTxn(txn, messageStore, messageId, collector);
-      return;
-    }
-
-    // Or, we have to open another transaction ourselves.
-    let self = this;
-    this.mmdb.newTxn(READ_ONLY, function(error, txn, messageStore) {
-      if (error) {
-        debug("getMessage: failed to create new transaction");
-        collector.notifyResult(null, messageId, null);
-      } else {
-        self.getMessageTxn(txn, messageStore, messageId, collector);
-      }
-    }, [MESSAGE_STORE_NAME]);
-  },
-
-  // nsICursorContinueCallback
-
-  handleContinue: function() {
-    if (DEBUG) debug("Getting next message in list");
-    this.collector.squeeze(this.callback);
-  }
-};
-
-function GetThreadsCursor(mmdb, callback) {
-  this.mmdb = mmdb;
-  this.callback = callback;
-  this.collector = new ResultsCollector(this.getThread.bind(this));
-
-  this.handleContinue(); // Trigger first run.
-}
-GetThreadsCursor.prototype = {
-  classID: RIL_GETTHREADSCURSOR_CID,
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsICursorContinueCallback]),
-
-  mmdb: null,
-  callback: null,
-  collector: null,
-
-  getThreadTxn: function(txn, threadStore, threadId, collector) {
-    if (DEBUG) debug ("Fetching thread " + threadId);
-
-    let getRequest = threadStore.get(threadId);
-    getRequest.onsuccess = function(event) {
-      let threadRecord = event.target.result;
-      if (DEBUG) {
-        debug("notifyCursorResult: " + JSON.stringify(threadRecord));
-      }
-      let thread =
-        gMobileMessageService.createThread(threadRecord.id,
-                                           threadRecord.participantAddresses,
-                                           threadRecord.lastTimestamp,
-                                           threadRecord.lastMessageSubject || "",
-                                           threadRecord.body,
-                                           threadRecord.unreadCount,
-                                           threadRecord.lastMessageType);
-      collector.notifyResult(txn, threadId, thread);
-    };
-    getRequest.onerror = function(event) {
-      // Error reporting is done in ResultsCollector.notifyCallback.
-      event.stopPropagation();
-      event.preventDefault();
-
-      if (DEBUG) {
-        debug("notifyCursorError - threadId: " + threadId);
-      }
-      collector.notifyResult(txn, threadId, null);
-    };
-  },
-
-  getThread: function(txn, threadId, collector) {
-    // When filter transaction is not yet completed, we're called with current
-    // ongoing transaction object.
-    if (txn) {
-      let threadStore = txn.objectStore(THREAD_STORE_NAME);
-      this.getThreadTxn(txn, threadStore, threadId, collector);
-      return;
-    }
-
-    // Or, we have to open another transaction ourselves.
-    let self = this;
-    this.mmdb.newTxn(READ_ONLY, function(error, txn, threadStore) {
-      if (error) {
-        collector.notifyResult(null, threadId, null);
-      } else {
-        self.getThreadTxn(txn, threadStore, threadId, collector);
-      }
-    }, [THREAD_STORE_NAME]);
-  },
-
-  // nsICursorContinueCallback
-
-  handleContinue: function() {
-    if (DEBUG) debug("Getting next thread in list");
-    this.collector.squeeze(this.callback);
-  }
-}
-
-this.EXPORTED_SYMBOLS = [
-  'MobileMessageDB'
-];
-
-function debug() {
-  dump("MobileMessageDB: " + Array.slice(arguments).join(" ") + "\n");
-}
deleted file mode 100644
--- a/dom/mobilemessage/gonk/MobileMessageDatabaseService.js
+++ /dev/null
@@ -1,130 +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;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-var MMDB = {};
-Cu.import("resource://gre/modules/MobileMessageDB.jsm", MMDB);
-
-const GONK_MOBILEMESSAGEDATABASESERVICE_CONTRACTID =
-  "@mozilla.org/mobilemessage/gonkmobilemessagedatabaseservice;1";
-const GONK_MOBILEMESSAGEDATABASESERVICE_CID =
-  Components.ID("{7db05024-8038-11e4-b7fa-a3edb6f1bf0c}");
-
-const DB_NAME = "sms";
-
-/**
- * MobileMessageDatabaseService
- */
-function MobileMessageDatabaseService() {
-  // Prime the directory service's cache to ensure that the ProfD entry exists
-  // by the time IndexedDB queries for it off the main thread. (See bug 743635.)
-  Services.dirsvc.get("ProfD", Ci.nsIFile);
-
-  let mmdb = new MMDB.MobileMessageDB();
-  mmdb.init(DB_NAME, 0, mmdb.updatePendingTransactionToError.bind(mmdb));
-  this.mmdb = mmdb;
-}
-MobileMessageDatabaseService.prototype = {
-
-  classID: GONK_MOBILEMESSAGEDATABASESERVICE_CID,
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIGonkMobileMessageDatabaseService,
-                                         Ci.nsIMobileMessageDatabaseService,
-                                         Ci.nsIObserver]),
-
-  /**
-   * MobileMessageDB instance.
-   */
-  mmdb: null,
-
-  /**
-   * nsIObserver
-   */
-  observe: function() {},
-
-  /**
-   * nsIGonkMobileMessageDatabaseService API
-   */
-
-  saveReceivedMessage: function(aMessage, aCallback) {
-    this.mmdb.saveReceivedMessage(aMessage, aCallback);
-  },
-
-  saveSendingMessage: function(aMessage, aCallback) {
-    this.mmdb.saveSendingMessage(aMessage, aCallback);
-  },
-
-  setMessageDeliveryByMessageId: function(aMessageId, aReceiver, aDelivery,
-                                          aDeliveryStatus, aEnvelopeId,
-                                          aCallback) {
-    this.mmdb.updateMessageDeliveryById(aMessageId, "messageId", aReceiver,
-                                        aDelivery, aDeliveryStatus,
-                                        aEnvelopeId, aCallback);
-  },
-
-  setMessageDeliveryStatusByEnvelopeId: function(aEnvelopeId, aReceiver,
-                                                 aDeliveryStatus, aCallback) {
-    this.mmdb.updateMessageDeliveryById(aEnvelopeId, "envelopeId", aReceiver,
-                                        null, aDeliveryStatus, null, aCallback);
-  },
-
-  setMessageReadStatusByEnvelopeId: function(aEnvelopeId, aReceiver,
-                                             aReadStatus, aCallback) {
-    this.mmdb.setMessageReadStatusByEnvelopeId(aEnvelopeId, aReceiver,
-                                               aReadStatus, aCallback);
-  },
-
-  getMessageRecordByTransactionId: function(aTransactionId, aCallback) {
-    this.mmdb.getMessageRecordByTransactionId(aTransactionId, aCallback);
-  },
-
-  getMessageRecordById: function(aMessageId, aCallback) {
-    this.mmdb.getMessageRecordById(aMessageId, aCallback);
-  },
-
-  translateCrErrorToMessageCallbackError: function(aCrError) {
-    return this.mmdb.translateCrErrorToMessageCallbackError(aCrError);
-  },
-
-  saveSmsSegment: function(aSmsSegment, aCallback) {
-    this.mmdb.saveSmsSegment(aSmsSegment, aCallback);
-  },
-
-  /**
-   * nsIMobileMessageDatabaseService API
-   */
-
-  getMessage: function(aMessageId, aRequest) {
-    this.mmdb.getMessage(aMessageId, aRequest);
-  },
-
-  deleteMessage: function(aMessageIds, aLength, aRequest) {
-    this.mmdb.deleteMessage(aMessageIds, aLength, aRequest);
-  },
-
-  createMessageCursor: function(aHasStartDate, aStartDate, aHasEndDate,
-                                aEndDate, aNumbers, aNumbersCount, aDelivery,
-                                aHasRead, aRead, aHasThreadId, aThreadId,
-                                aReverse, aCallback) {
-    return this.mmdb.createMessageCursor(aHasStartDate, aStartDate, aHasEndDate,
-                                         aEndDate, aNumbers, aNumbersCount,
-                                         aDelivery, aHasRead, aRead, aHasThreadId,
-                                         aThreadId, aReverse, aCallback);
-  },
-
-  markMessageRead: function(aMessageId, aValue, aSendReadReport, aRequest) {
-    this.mmdb.markMessageRead(aMessageId, aValue, aSendReadReport, aRequest);
-  },
-
-  createThreadCursor: function(aCallback) {
-    return this.mmdb.createThreadCursor(aCallback);
-  }
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([MobileMessageDatabaseService]);
deleted file mode 100644
--- a/dom/mobilemessage/gonk/MobileMessageDatabaseService.manifest
+++ /dev/null
@@ -1,3 +0,0 @@
-component {7db05024-8038-11e4-b7fa-a3edb6f1bf0c} MobileMessageDatabaseService.js
-contract @mozilla.org/mobilemessage/gonkmobilemessagedatabaseservice;1 {7db05024-8038-11e4-b7fa-a3edb6f1bf0c}
-category profile-after-change MobileMessageDatabaseService @mozilla.org/mobilemessage/gonkmobilemessagedatabaseservice;1
deleted file mode 100644
--- a/dom/mobilemessage/gonk/SmsSegmentHelper.jsm
+++ /dev/null
@@ -1,425 +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;
-
-var RIL = {};
-Cu.import("resource://gre/modules/ril_consts.js", RIL);
-
-/**
- * SmsSegmentHelper
- */
-this.SmsSegmentHelper = {
-  /**
-   * Get valid SMS concatenation reference number.
-   */
-  _segmentRef: 0,
-  get nextSegmentRef() {
-    let ref = this._segmentRef++;
-
-    this._segmentRef %= (this.segmentRef16Bit ? 65535 : 255);
-
-    // 0 is not a valid SMS concatenation reference number.
-    return ref + 1;
-  },
-
-  /**
-   * Calculate encoded length using specified locking/single shift table
-   *
-   * @param aMessage
-   *        message string to be encoded.
-   * @param aLangTable
-   *        locking shift table string.
-   * @param aLangShiftTable
-   *        single shift table string.
-   * @param aStrict7BitEncoding [Optional]
-   *        Enable Latin characters replacement with corresponding
-   *        ones in GSM SMS 7-bit default alphabet.
-   *
-   * @return encoded length in septets.
-   *
-   * @note The algorithm used in this function must match exactly with
-   *       GsmPDUHelper#writeStringAsSeptets.
-   */
-  countGsm7BitSeptets: function(aMessage, aLangTable, aLangShiftTable, aStrict7BitEncoding) {
-    let length = 0;
-    for (let msgIndex = 0; msgIndex < aMessage.length; msgIndex++) {
-      let c = aMessage.charAt(msgIndex);
-      if (aStrict7BitEncoding) {
-        c = RIL.GSM_SMS_STRICT_7BIT_CHARMAP[c] || c;
-      }
-
-      let septet = aLangTable.indexOf(c);
-
-      // According to 3GPP TS 23.038, section 6.1.1 General notes, "The
-      // characters marked '1)' are not used but are displayed as a space."
-      if (septet == RIL.PDU_NL_EXTENDED_ESCAPE) {
-        continue;
-      }
-
-      if (septet >= 0) {
-        length++;
-        continue;
-      }
-
-      septet = aLangShiftTable.indexOf(c);
-      if (septet < 0) {
-        if (!aStrict7BitEncoding) {
-          return -1;
-        }
-
-        // Bug 816082, when aStrict7BitEncoding is enabled, we should replace
-        // characters that can't be encoded with GSM 7-Bit alphabets with '*'.
-        c = "*";
-        if (aLangTable.indexOf(c) >= 0) {
-          length++;
-        } else if (aLangShiftTable.indexOf(c) >= 0) {
-          length += 2;
-        } else {
-          // We can't even encode a '*' character with current configuration.
-          return -1;
-        }
-
-        continue;
-      }
-
-      // According to 3GPP TS 23.038 B.2, "This code represents a control
-      // character and therefore must not be used for language specific
-      // characters."
-      if (septet == RIL.PDU_NL_RESERVED_CONTROL) {
-        continue;
-      }
-
-      // The character is not found in locking shfit table, but could be
-      // encoded as <escape><char> with single shift table. Note that it's
-      // still possible for septet to has the value of PDU_NL_EXTENDED_ESCAPE,
-      // but we can display it as a space in this case as said in previous
-      // comment.
-      length += 2;
-    }
-
-    return length;
-  },
-
-  /**
-   * Calculate user data length of specified message string encoded in GSM 7Bit
-   * alphabets.
-   *
-   * @param aMessage
-   *        a message string to be encoded.
-   * @param aStrict7BitEncoding [Optional]
-   *        Enable Latin characters replacement with corresponding
-   *        ones in GSM SMS 7-bit default alphabet.
-   *
-   * @return null or an options object with attributes `dcs`,
-   *         `userDataHeaderLength`, `encodedFullBodyLength`, `langIndex`,
-   *         `langShiftIndex`, `segmentMaxSeq` set.
-   *
-   * @see #calculateUserDataLength().
-   *
-   * |enabledGsmTableTuples|:
-   *   List of tuples of national language identifier pairs.
-   * |segmentRef16Bit|:
-   *   Use 16-bit reference number for concatenated outgoint messages.
-   *   TODO: Support static/runtime settings, see bug 1019443.
-   */
-  enabledGsmTableTuples: [
-    [RIL.PDU_NL_IDENTIFIER_DEFAULT, RIL.PDU_NL_IDENTIFIER_DEFAULT],
-  ],
-  segmentRef16Bit: false,
-  calculateUserDataLength7Bit: function(aMessage, aStrict7BitEncoding) {
-    let options = null;
-    let minUserDataSeptets = Number.MAX_VALUE;
-    for (let i = 0; i < this.enabledGsmTableTuples.length; i++) {
-      let [langIndex, langShiftIndex] = this.enabledGsmTableTuples[i];
-
-      const langTable = RIL.PDU_NL_LOCKING_SHIFT_TABLES[langIndex];
-      const langShiftTable = RIL.PDU_NL_SINGLE_SHIFT_TABLES[langShiftIndex];
-
-      let bodySeptets = this.countGsm7BitSeptets(aMessage,
-                                                  langTable,
-                                                  langShiftTable,
-                                                  aStrict7BitEncoding);
-      if (bodySeptets < 0) {
-        continue;
-      }
-
-      let headerLen = 0;
-      if (langIndex != RIL.PDU_NL_IDENTIFIER_DEFAULT) {
-        headerLen += 3; // IEI + len + langIndex
-      }
-      if (langShiftIndex != RIL.PDU_NL_IDENTIFIER_DEFAULT) {
-        headerLen += 3; // IEI + len + langShiftIndex
-      }
-
-      // Calculate full user data length, note the extra byte is for header len
-      let headerSeptets = Math.ceil((headerLen ? headerLen + 1 : 0) * 8 / 7);
-      let segmentSeptets = RIL.PDU_MAX_USER_DATA_7BIT;
-      if ((bodySeptets + headerSeptets) > segmentSeptets) {
-        headerLen += this.segmentRef16Bit ? 6 : 5;
-        headerSeptets = Math.ceil((headerLen + 1) * 8 / 7);
-      }
-      segmentSeptets -= headerSeptets;
-
-      let segments = Math.ceil(bodySeptets / segmentSeptets);
-      let userDataSeptets = bodySeptets + headerSeptets * segments;
-      if (userDataSeptets >= minUserDataSeptets) {
-        continue;
-      }
-
-      minUserDataSeptets = userDataSeptets;
-
-      options = {
-        dcs: RIL.PDU_DCS_MSG_CODING_7BITS_ALPHABET,
-        encodedFullBodyLength: bodySeptets,
-        userDataHeaderLength: headerLen,
-        langIndex: langIndex,
-        langShiftIndex: langShiftIndex,
-        segmentMaxSeq: segments,
-        segmentChars: segmentSeptets,
-      };
-    }
-
-    return options;
-  },
-
-  /**
-   * Calculate user data length of specified message string encoded in UCS2.
-   *
-   * @param aMessage
-   *        a message string to be encoded.
-   *
-   * @return an options object with attributes `dcs`, `userDataHeaderLength`,
-   *         `encodedFullBodyLength`, `segmentMaxSeq` set.
-   *
-   * @see #calculateUserDataLength().
-   */
-  calculateUserDataLengthUCS2: function(aMessage) {
-    let bodyChars = aMessage.length;
-    let headerLen = 0;
-    let headerChars = Math.ceil((headerLen ? headerLen + 1 : 0) / 2);
-    let segmentChars = RIL.PDU_MAX_USER_DATA_UCS2;
-    if ((bodyChars + headerChars) > segmentChars) {
-      headerLen += this.segmentRef16Bit ? 6 : 5;
-      headerChars = Math.ceil((headerLen + 1) / 2);
-      segmentChars -= headerChars;
-    }
-
-    let segments = Math.ceil(bodyChars / segmentChars);
-
-    return {
-      dcs: RIL.PDU_DCS_MSG_CODING_16BITS_ALPHABET,
-      encodedFullBodyLength: bodyChars * 2,
-      userDataHeaderLength: headerLen,
-      segmentMaxSeq: segments,
-      segmentChars: segmentChars,
-    };
-  },
-
-  /**
-   * Calculate user data length and its encoding.
-   *
-   * @param aMessage
-   *        a message string to be encoded.
-   * @param aStrict7BitEncoding [Optional]
-   *        Enable Latin characters replacement with corresponding
-   *        ones in GSM SMS 7-bit default alphabet.
-   *
-   * @return an options object with some or all of following attributes set:
-   *
-   * @param dcs
-   *        Data coding scheme. One of the PDU_DCS_MSG_CODING_*BITS_ALPHABET
-   *        constants.
-   * @param userDataHeaderLength
-   *        Length of embedded user data header, in bytes. The whole header
-   *        size will be userDataHeaderLength + 1; 0 for no header.
-   * @param encodedFullBodyLength
-   *        Length of the message body when encoded with the given DCS. For
-   *        UCS2, in bytes; for 7-bit, in septets.
-   * @param langIndex
-   *        Table index used for normal 7-bit encoded character lookup.
-   * @param langShiftIndex
-   *        Table index used for escaped 7-bit encoded character lookup.
-   * @param segmentMaxSeq
-   *        Max sequence number of a multi-part messages, or 1 for single one.
-   *        This number might not be accurate for a multi-part message until
-   *        it's processed by #fragmentText() again.
-   */
-  calculateUserDataLength: function(aMessage, aStrict7BitEncoding) {
-    let options = this.calculateUserDataLength7Bit(aMessage, aStrict7BitEncoding);
-    if (!options) {
-      options = this.calculateUserDataLengthUCS2(aMessage);
-    }
-
-    return options;
-  },
-
-  /**
-   * Fragment GSM 7-Bit encodable string for transmission.
-   *
-   * @param aText
-   *        text string to be fragmented.
-   * @param aLangTable
-   *        locking shift table string.
-   * @param aLangShiftTable
-   *        single shift table string.
-   * @param aSegmentSeptets
-   *        Number of available spetets per segment.
-   * @param aStrict7BitEncoding [Optional]
-   *        Enable Latin characters replacement with corresponding
-   *        ones in GSM SMS 7-bit default alphabet.
-   *
-   * @return an array of objects. See #fragmentText() for detailed definition.
-   */
-  fragmentText7Bit: function(aText, aLangTable, aLangShiftTable, aSegmentSeptets, aStrict7BitEncoding) {
-    let ret = [];
-    let body = "", len = 0;
-    // If the message is empty, we only push the empty message to ret.
-    if (aText.length === 0) {
-      ret.push({
-        body: aText,
-        encodedBodyLength: aText.length,
-      });
-      return ret;
-    }
-
-    for (let i = 0, inc = 0; i < aText.length; i++) {
-      let c = aText.charAt(i);
-      if (aStrict7BitEncoding) {
-        c = RIL.GSM_SMS_STRICT_7BIT_CHARMAP[c] || c;
-      }
-
-      let septet = aLangTable.indexOf(c);
-      if (septet == RIL.PDU_NL_EXTENDED_ESCAPE) {
-        continue;
-      }
-
-      if (septet >= 0) {
-        inc = 1;
-      } else {
-        septet = aLangShiftTable.indexOf(c);
-        if (septet == RIL.PDU_NL_RESERVED_CONTROL) {
-          continue;
-        }
-
-        inc = 2;
-        if (septet < 0) {
-          if (!aStrict7BitEncoding) {
-            throw new Error("Given text cannot be encoded with GSM 7-bit Alphabet!");
-          }
-
-          // Bug 816082, when aStrict7BitEncoding is enabled, we should replace
-          // characters that can't be encoded with GSM 7-Bit alphabets with '*'.
-          c = "*";
-          if (aLangTable.indexOf(c) >= 0) {
-            inc = 1;
-          }
-        }
-      }
-
-      if ((len + inc) > aSegmentSeptets) {
-        ret.push({
-          body: body,
-          encodedBodyLength: len,
-        });
-        body = c;
-        len = inc;
-      } else {
-        body += c;
-        len += inc;
-      }
-    }
-
-    if (len) {
-      ret.push({
-        body: body,
-        encodedBodyLength: len,
-      });
-    }
-
-    return ret;
-  },
-
-  /**
-   * Fragment UCS2 encodable string for transmission.
-   *
-   * @param aText
-   *        text string to be fragmented.
-   * @param aSegmentChars
-   *        Number of available characters per segment.
-   *
-   * @return an array of objects. See #fragmentText() for detailed definition.
-   */
-  fragmentTextUCS2: function(aText, aSegmentChars) {
-    let ret = [];
-    // If the message is empty, we only push the empty message to ret.
-    if (aText.length === 0) {
-      ret.push({
-        body: aText,
-        encodedBodyLength: aText.length,
-      });
-      return ret;
-    }
-
-    for (let offset = 0; offset < aText.length; offset += aSegmentChars) {
-      let str = aText.substr(offset, aSegmentChars);
-      ret.push({
-        body: str,
-        encodedBodyLength: str.length * 2,
-      });
-    }
-
-    return ret;
-  },
-
-  /**
-   * Fragment string for transmission.
-   *
-   * Fragment input text string into an array of objects that contains
-   * attributes `body`, substring for this segment, `encodedBodyLength`,
-   * length of the encoded segment body in septets.
-   *
-   * @param aText
-   *        Text string to be fragmented.
-   * @param aOptions [Optional]
-   *        Optional pre-calculated option object. The output array will be
-   *        stored at aOptions.segments if there are multiple segments.
-   * @param aStrict7BitEncoding [Optional]
-   *        Enable Latin characters replacement with corresponding
-   *        ones in GSM SMS 7-bit default alphabet.
-   *
-   * @return Populated options object.
-   */
-  fragmentText: function(aText, aOptions, aStrict7BitEncoding) {
-    if (!aOptions) {
-      aOptions = this.calculateUserDataLength(aText, aStrict7BitEncoding);
-    }
-
-    if (aOptions.dcs == RIL.PDU_DCS_MSG_CODING_7BITS_ALPHABET) {
-      const langTable = RIL.PDU_NL_LOCKING_SHIFT_TABLES[aOptions.langIndex];
-      const langShiftTable = RIL.PDU_NL_SINGLE_SHIFT_TABLES[aOptions.langShiftIndex];
-      aOptions.segments = this.fragmentText7Bit(aText,
-                                                langTable, langShiftTable,
-                                                aOptions.segmentChars,
-                                                aStrict7BitEncoding);
-    } else {
-      aOptions.segments = this.fragmentTextUCS2(aText,
-                                                aOptions.segmentChars);
-    }
-
-    // Re-sync aOptions.segmentMaxSeq with actual length of returning array.
-    aOptions.segmentMaxSeq = aOptions.segments.length;
-
-    if (aOptions.segmentMaxSeq > 1) {
-      aOptions.segmentRef16Bit = this.segmentRef16Bit;
-      aOptions.segmentRef = this.nextSegmentRef;
-    }
-
-    return aOptions;
-  }
-};
-
-this.EXPORTED_SYMBOLS = [ 'SmsSegmentHelper' ];
deleted file mode 100644
--- a/dom/mobilemessage/gonk/SmsService.js
+++ /dev/null
@@ -1,1418 +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;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-var RIL = {};
-Cu.import("resource://gre/modules/ril_consts.js", RIL);
-
-const GONK_SMSSERVICE_CONTRACTID = "@mozilla.org/sms/gonksmsservice;1";
-const GONK_SMSSERVICE_CID = Components.ID("{f9b9b5e2-73b4-11e4-83ff-a33e27428c86}");
-
-const NS_XPCOM_SHUTDOWN_OBSERVER_ID      = "xpcom-shutdown";
-const NS_PREFBRANCH_PREFCHANGE_TOPIC_ID  = "nsPref:changed";
-
-const kPrefDefaultServiceId = "dom.sms.defaultServiceId";
-const kPrefRilDebuggingEnabled = "ril.debugging.enabled";
-const kPrefRilNumRadioInterfaces = "ril.numRadioInterfaces";
-const kPrefLastKnownSimMcc = "ril.lastKnownSimMcc";
-
-const kDiskSpaceWatcherObserverTopic = "disk-space-watcher";
-
-const kSmsReceivedObserverTopic          = "sms-received";
-const kSilentSmsReceivedObserverTopic    = "silent-sms-received";
-const kSmsSendingObserverTopic           = "sms-sending";
-const kSmsSentObserverTopic              = "sms-sent";
-const kSmsFailedObserverTopic            = "sms-failed";
-const kSmsDeliverySuccessObserverTopic   = "sms-delivery-success";
-const kSmsDeliveryErrorObserverTopic     = "sms-delivery-error";
-const kSmsDeletedObserverTopic           = "sms-deleted";
-
-const DOM_MOBILE_MESSAGE_DELIVERY_RECEIVED = "received";
-const DOM_MOBILE_MESSAGE_DELIVERY_SENDING  = "sending";
-const DOM_MOBILE_MESSAGE_DELIVERY_SENT     = "sent";
-const DOM_MOBILE_MESSAGE_DELIVERY_ERROR    = "error";
-
-const SMS_HANDLED_WAKELOCK_TIMEOUT = 5000;
-
-XPCOMUtils.defineLazyGetter(this, "gRadioInterfaces", function() {
-  let ril = { numRadioInterfaces: 0 };
-  try {
-    ril = Cc["@mozilla.org/ril;1"].getService(Ci.nsIRadioInterfaceLayer);
-  } catch(e) {}
-
-  let interfaces = [];
-  for (let i = 0; i < ril.numRadioInterfaces; i++) {
-    interfaces.push(ril.getRadioInterface(i));
-  }
-  return interfaces;
-});
-
-XPCOMUtils.defineLazyGetter(this, "gSmsSegmentHelper", function() {
-  let ns = {};
-  Cu.import("resource://gre/modules/SmsSegmentHelper.jsm", ns);
-
-  // Initialize enabledGsmTableTuples from current MCC.
-  ns.SmsSegmentHelper.enabledGsmTableTuples = getEnabledGsmTableTuplesFromMcc();
-
-  return ns.SmsSegmentHelper;
-});
-
-XPCOMUtils.defineLazyGetter(this, "gPhoneNumberUtils", function() {
-  let ns = {};
-  Cu.import("resource://gre/modules/PhoneNumberUtils.jsm", ns);
-  return ns.PhoneNumberUtils;
-});
-
-XPCOMUtils.defineLazyGetter(this, "gWAP", function() {
-  let ns = {};
-  Cu.import("resource://gre/modules/WapPushManager.js", ns);
-  return ns;
-});
-
-XPCOMUtils.defineLazyGetter(this, "gSmsSendingSchedulers", function() {
-  return {
-    _schedulers: [],
-    getSchedulerByServiceId: function(aServiceId) {
-      let scheduler = this._schedulers[aServiceId];
-      if (!scheduler) {
-        scheduler = this._schedulers[aServiceId] =
-          new SmsSendingScheduler(aServiceId);
-      }
-
-      return scheduler;
-    }
-  };
-});
-
-XPCOMUtils.defineLazyServiceGetter(this, "gCellBroadcastService",
-                                   "@mozilla.org/cellbroadcast/cellbroadcastservice;1",
-                                   "nsIGonkCellBroadcastService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gIccService",
-                                   "@mozilla.org/icc/iccservice;1",
-                                   "nsIIccService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileConnectionService",
-                                   "@mozilla.org/mobileconnection/mobileconnectionservice;1",
-                                   "nsIMobileConnectionService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageDatabaseService",
-                                   "@mozilla.org/mobilemessage/gonkmobilemessagedatabaseservice;1",
-                                   "nsIGonkMobileMessageDatabaseService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageService",
-                                   "@mozilla.org/mobilemessage/mobilemessageservice;1",
-                                   "nsIMobileMessageService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gPowerManagerService",
-                                   "@mozilla.org/power/powermanagerservice;1",
-                                   "nsIPowerManagerService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSmsMessenger",
-                                   "@mozilla.org/ril/system-messenger-helper;1",
-                                   "nsISmsMessenger");
-
-var DEBUG = RIL.DEBUG_RIL;
-function debug(s) {
-  dump("SmsService: " + s);
-}
-
-function SmsService() {
-  this._updateDebugFlag();
-  this._silentNumbers = [];
-  this.smsDefaultServiceId = this._getDefaultServiceId();
-
-  this._portAddressedSmsApps = {};
-  this._portAddressedSmsApps[gWAP.WDP_PORT_PUSH] =
-    (aMessage, aServiceId) => this._handleSmsWdpPortPush(aMessage, aServiceId);
-
-  this._receivedSmsSegmentsMap = {};
-
-  Services.prefs.addObserver(kPrefRilDebuggingEnabled, this, false);
-  Services.prefs.addObserver(kPrefDefaultServiceId, this, false);
-  Services.prefs.addObserver(kPrefLastKnownSimMcc, this, false);
-  Services.obs.addObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
-  Services.obs.addObserver(this, kDiskSpaceWatcherObserverTopic, false);
-}
-SmsService.prototype = {
-  classID: GONK_SMSSERVICE_CID,
-
-  classInfo: XPCOMUtils.generateCI({classID: GONK_SMSSERVICE_CID,
-                                    contractID: GONK_SMSSERVICE_CONTRACTID,
-                                    classDescription: "SmsService",
-                                    interfaces: [Ci.nsISmsService,
-                                                 Ci.nsIGonkSmsService],
-                                    flags: Ci.nsIClassInfo.SINGLETON}),
-
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsISmsService,
-                                         Ci.nsIGonkSmsService,
-                                         Ci.nsIObserver]),
-
-  _updateDebugFlag: function() {
-    try {
-      DEBUG = RIL.DEBUG_RIL ||
-              Services.prefs.getBoolPref(kPrefRilDebuggingEnabled);
-    } catch (e) {}
-  },
-
-  _getDefaultServiceId: function() {
-    let id = Services.prefs.getIntPref(kPrefDefaultServiceId);
-    let numRil = Services.prefs.getIntPref(kPrefRilNumRadioInterfaces);
-
-    if (id >= numRil || id < 0) {
-      id = 0;
-    }
-
-    return id;
-  },
-
-  _getPhoneNumber: function(aServiceId) {
-    let number;
-    // Get the proper IccInfo based on the current card type.
-    try {
-      let iccInfo = null;
-      let baseIccInfo = this._getIccInfo(aServiceId);
-      if (baseIccInfo.iccType === 'ruim' || baseIccInfo.iccType === 'csim') {
-        iccInfo = baseIccInfo.QueryInterface(Ci.nsICdmaIccInfo);
-        number = iccInfo.mdn;
-      } else {
-        iccInfo = baseIccInfo.QueryInterface(Ci.nsIGsmIccInfo);
-        number = iccInfo.msisdn;
-      }
-    } catch (e) {
-      if (DEBUG) {
-       debug("Exception - QueryInterface failed on iccinfo for GSM/CDMA info");
-      }
-      return null;
-    }
-
-    return number;
-  },
-
-  _getIccInfo: function(aServiceId) {
-    let icc = gIccService.getIccByServiceId(aServiceId);
-    return icc ? icc.iccInfo : null;
-  },
-
-  _getCardState: function(aServiceId) {
-    let icc = gIccService.getIccByServiceId(aServiceId);
-    return icc ? icc.cardState : Ci.nsIIcc.CARD_STATE_UNKNOWN;
-  },
-
-  _getIccId: function(aServiceId) {
-    let iccInfo = this._getIccInfo(aServiceId);
-
-    if (!iccInfo) {
-      return null;
-    }
-
-    return iccInfo.iccid;
-  },
-
-  // The following attributes/functions are used for acquiring/releasing the
-  // CPU wake lock when the RIL handles the received SMS. Note that we need
-  // a timer to bound the lock's life cycle to avoid exhausting the battery.
-  _smsHandledWakeLock: null,
-  _smsHandledWakeLockTimer: null,
-  _acquireSmsHandledWakeLock: function() {
-    if (!this._smsHandledWakeLock) {
-      if (DEBUG) debug("Acquiring a CPU wake lock for handling SMS.");
-      this._smsHandledWakeLock = gPowerManagerService.newWakeLock("cpu");
-    }
-    if (!this._smsHandledWakeLockTimer) {
-      if (DEBUG) debug("Creating a timer for releasing the CPU wake lock.");
-      this._smsHandledWakeLockTimer =
-        Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
-    }
-    if (DEBUG) debug("Setting the timer for releasing the CPU wake lock.");
-    this._smsHandledWakeLockTimer
-        .initWithCallback(() => this._releaseSmsHandledWakeLock(),
-                          SMS_HANDLED_WAKELOCK_TIMEOUT,
-                          Ci.nsITimer.TYPE_ONE_SHOT);
-  },
-
-  _releaseSmsHandledWakeLock: function() {
-    if (DEBUG) debug("Releasing the CPU wake lock for handling SMS.");
-    if (this._smsHandledWakeLockTimer) {
-      this._smsHandledWakeLockTimer.cancel();
-    }
-    if (this._smsHandledWakeLock) {
-      this._smsHandledWakeLock.unlock();
-      this._smsHandledWakeLock = null;
-    }
-  },
-
-  _convertSmsMessageClassToString: function(aMessageClass) {
-    return RIL.GECKO_SMS_MESSAGE_CLASSES[aMessageClass] || null;
-  },
-
-  _convertSmsMessageClass: function(aMessageClass) {
-    let index = RIL.GECKO_SMS_MESSAGE_CLASSES.indexOf(aMessageClass);
-
-    if (index < 0) {
-      throw new Error("Invalid MessageClass: " + aMessageClass);
-    }
-
-    return index;
-  },
-
-  _convertSmsDelivery: function(aDelivery) {
-    let index = [DOM_MOBILE_MESSAGE_DELIVERY_RECEIVED,
-                 DOM_MOBILE_MESSAGE_DELIVERY_SENDING,
-                 DOM_MOBILE_MESSAGE_DELIVERY_SENT,
-                 DOM_MOBILE_MESSAGE_DELIVERY_ERROR].indexOf(aDelivery);
-
-    if (index < 0) {
-      throw new Error("Invalid Delivery: " + aDelivery);
-    }
-
-    return index;
-  },
-
-  _convertSmsDeliveryStatus: function(aDeliveryStatus) {
-    let index = [RIL.GECKO_SMS_DELIVERY_STATUS_NOT_APPLICABLE,
-                 RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS,
-                 RIL.GECKO_SMS_DELIVERY_STATUS_PENDING,
-                 RIL.GECKO_SMS_DELIVERY_STATUS_ERROR].indexOf(aDeliveryStatus);
-
-    if (index < 0) {
-      throw new Error("Invalid DeliveryStatus: " + aDeliveryStatus);
-    }
-
-    return index;
-  },
-
-  _notifySendingError: function(aErrorCode, aSendingMessage, aSilent, aRequest) {
-    if (aSilent || aErrorCode === Ci.nsIMobileMessageCallback.NOT_FOUND_ERROR) {
-      // There is no way to modify nsISmsMessage attributes as they
-      // are read only so we just create a new sms instance to send along
-      // with the notification.
-      aRequest.notifySendMessageFailed(aErrorCode,
-        gMobileMessageService.createSmsMessage(aSendingMessage.id,
-                                               aSendingMessage.threadId,
-                                               aSendingMessage.iccId,
-                                               DOM_MOBILE_MESSAGE_DELIVERY_ERROR,
-                                               RIL.GECKO_SMS_DELIVERY_STATUS_ERROR,
-                                               aSendingMessage.sender,
-                                               aSendingMessage.receiver,
-                                               aSendingMessage.body,
-                                               aSendingMessage.messageClass,
-                                               aSendingMessage.timestamp,
-                                               0,
-                                               0,
-                                               aSendingMessage.read));
-
-      if (!aSilent) {
-        Services.obs.notifyObservers(aSendingMessage, kSmsFailedObserverTopic, null);
-      }
-      return;
-    }
-
-    gMobileMessageDatabaseService
-      .setMessageDeliveryByMessageId(aSendingMessage.id,
-                                     null,
-                                     DOM_MOBILE_MESSAGE_DELIVERY_ERROR,
-                                     RIL.GECKO_SMS_DELIVERY_STATUS_ERROR,
-                                     null,
-                                     (aRv, aDomMessage) => {
-      let smsMessage = null;
-      try {
-        smsMessage = aDomMessage.QueryInterface(Ci.nsISmsMessage);
-      } catch (e) {}
-      // TODO bug 832140 handle !Components.isSuccessCode(aRv)
-      this._broadcastSmsSystemMessage(
-        Ci.nsISmsMessenger.NOTIFICATION_TYPE_SENT_FAILED, smsMessage);
-      aRequest.notifySendMessageFailed(aErrorCode, smsMessage);
-      Services.obs.notifyObservers(smsMessage, kSmsFailedObserverTopic, null);
-    });
-  },
-
-  /**
-   * Schedule the sending request.
-   */
-  _scheduleSending: function(aServiceId, aDomMessage, aSilent, aOptions, aRequest) {
-    gSmsSendingSchedulers.getSchedulerByServiceId(aServiceId)
-      .schedule({
-        messageId: aDomMessage.id,
-        onSend: () => {
-          if (DEBUG) {
-            debug("onSend: messageId=" + aDomMessage.id +
-                  ", serviceId=" + aServiceId);
-          }
-          this._sendToTheAir(aServiceId,
-                             aDomMessage,
-                             aSilent,
-                             aOptions,
-                             aRequest);
-        },
-        onCancel: (aErrorCode) => {
-          if (DEBUG) debug("onCancel: " + aErrorCode);
-          this._notifySendingError(aErrorCode, aDomMessage, aSilent, aRequest);
-        }
-      });
-  },
-
-  /**
-   * Send a SMS message to the modem.
-   */
-  _sendToTheAir: function(aServiceId, aDomMessage, aSilent, aOptions, aRequest) {
-    // Keep current SMS message info for sent/delivered notifications
-    let sentMessage = aDomMessage;
-    let requestStatusReport = aOptions.requestStatusReport;
-
-    // Retry count for GECKO_ERROR_SMS_SEND_FAIL_RETRY
-    if (!aOptions.retryCount) {
-      aOptions.retryCount = 0;
-    }
-
-    gRadioInterfaces[aServiceId].sendWorkerMessage("sendSMS",
-                                                   aOptions,
-                                                   (aResponse) => {
-      // Failed to send SMS out.
-      if (aResponse.errorMsg) {
-        let error = Ci.nsIMobileMessageCallback.UNKNOWN_ERROR;
-        if (aResponse.errorMsg === RIL.GECKO_ERROR_RADIO_NOT_AVAILABLE) {
-          error = Ci.nsIMobileMessageCallback.NO_SIGNAL_ERROR;
-        } else if (aResponse.errorMsg === RIL.GECKO_ERROR_FDN_CHECK_FAILURE) {
-          error = Ci.nsIMobileMessageCallback.FDN_CHECK_ERROR;
-        } else if (aResponse.errorMsg === RIL.GECKO_ERROR_SMS_SEND_FAIL_RETRY &&
-          aOptions.retryCount < RIL.SMS_RETRY_MAX) {
-          aOptions.retryCount++;
-          this._scheduleSending(aServiceId,
-                                aDomMessage,
-                                aSilent,
-                                aOptions,
-                                aRequest);
-          return;
-        }
-
-        this._notifySendingError(error, sentMessage, aSilent, aRequest);
-        return false;
-      } // End of send failure.
-
-      // Message was sent to SMSC.
-      if (!aResponse.deliveryStatus) {
-        if (aSilent) {
-          // There is no way to modify nsISmsMessage attributes as they
-          // are read only so we just create a new sms instance to send along
-          // with the notification.
-          aRequest.notifyMessageSent(
-            gMobileMessageService.createSmsMessage(sentMessage.id,
-                                                   sentMessage.threadId,
-                                                   sentMessage.iccId,
-                                                   DOM_MOBILE_MESSAGE_DELIVERY_SENT,
-                                                   sentMessage.deliveryStatus,
-                                                   sentMessage.sender,
-                                                   sentMessage.receiver,
-                                                   sentMessage.body,
-                                                   sentMessage.messageClass,
-                                                   sentMessage.timestamp,
-                                                   Date.now(),
-                                                   0,
-                                                   sentMessage.read));
-          // We don't wait for SMS-STATUS-REPORT for silent one.
-          return false;
-        }
-
-        gMobileMessageDatabaseService
-          .setMessageDeliveryByMessageId(sentMessage.id,
-                                         null,
-                                         DOM_MOBILE_MESSAGE_DELIVERY_SENT,
-                                         sentMessage.deliveryStatus,
-                                         null,
-                                         (aRv, aDomMessage) => {
-          let smsMessage = null;
-          try {
-            smsMessage = aDomMessage.QueryInterface(Ci.nsISmsMessage);
-          } catch (e) {}
-          // TODO bug 832140 handle !Components.isSuccessCode(aRv)
-
-          if (requestStatusReport) {
-            // Update the sentMessage and wait for the status report.
-            sentMessage = smsMessage;
-          }
-
-          this._broadcastSmsSystemMessage(
-            Ci.nsISmsMessenger.NOTIFICATION_TYPE_SENT, smsMessage);
-          aRequest.notifyMessageSent(smsMessage);
-          Services.obs.notifyObservers(smsMessage, kSmsSentObserverTopic, null);
-        });
-
-        // Keep this callback if we have status report waiting.
-        return requestStatusReport;
-      } // End of Message Sent to SMSC.
-
-      // Got valid deliveryStatus for the delivery to the remote party when
-      // the status report is requested.
-      gMobileMessageDatabaseService
-        .setMessageDeliveryByMessageId(sentMessage.id,
-                                       null,
-                                       sentMessage.delivery,
-                                       aResponse.deliveryStatus,
-                                       null,
-                                       (aRv, aDomMessage) => {
-        let smsMessage = null;
-        try {
-          smsMessage = aDomMessage.QueryInterface(Ci.nsISmsMessage);
-        } catch (e) {}
-        // TODO bug 832140 handle !Components.isSuccessCode(aRv)
-
-        let [topic, notificationType] =
-          (aResponse.deliveryStatus == RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS)
-            ? [kSmsDeliverySuccessObserverTopic,
-               Ci.nsISmsMessenger.NOTIFICATION_TYPE_DELIVERY_SUCCESS]
-            : [kSmsDeliveryErrorObserverTopic,
-               Ci.nsISmsMessenger.NOTIFICATION_TYPE_DELIVERY_ERROR];
-
-        // Broadcasting a "sms-delivery-success/sms-delivery-error" system
-        // message to open apps.
-        this._broadcastSmsSystemMessage(notificationType, smsMessage);
-
-        // Notifying observers the delivery status is updated.
-        Services.obs.notifyObservers(smsMessage, topic, null);
-      });
-
-      // Send transaction has ended completely.
-      return false;
-    });
-  },
-
-  /**
-   * A helper to broadcast the system message to launch registered apps
-   * like Costcontrol, Notification and Message app... etc.
-   *
-   * @param aNotificationType
-   *        Ci.nsISmsMessenger.NOTIFICATION_TYPE_*.
-   * @param aDomMessage
-   *        The nsISmsMessage object.
-   */
-  _broadcastSmsSystemMessage: function(aNotificationType, aDomMessage) {
-    if (DEBUG) debug("Broadcasting the SMS system message: " + aNotificationType);
-
-    // Sadly we cannot directly broadcast the aDomMessage object
-    // because the system message mechamism will rewrap the object
-    // based on the content window, which needs to know the properties.
-    try {
-      gSmsMessenger.notifySms(aNotificationType,
-                              aDomMessage.id,
-                              aDomMessage.threadId,
-                              aDomMessage.iccId,
-                              this._convertSmsDelivery(
-                                aDomMessage.delivery),
-                              this._convertSmsDeliveryStatus(
-                                aDomMessage.deliveryStatus),
-                              aDomMessage.sender,
-                              aDomMessage.receiver,
-                              aDomMessage.body,
-                              this._convertSmsMessageClass(
-                                aDomMessage.messageClass),
-                              aDomMessage.timestamp,
-                              aDomMessage.sentTimestamp,
-                              aDomMessage.deliveryTimestamp,
-                              aDomMessage.read);
-    } catch (e) {
-      if (DEBUG) {
-        debug("Failed to _broadcastSmsSystemMessage: " + e);
-      }
-    }
-  },
-
-  /**
-   * Helper for processing received multipart SMS.
-   *
-   * @return null for handled segments, and an object containing full message
-   *         body/data once all segments are received.
-   *
-   * |_receivedSmsSegmentsMap|:
-   *   Hash map for received multipart sms fragments. Messages are hashed with
-   *   its sender address and concatenation reference number. Three additional
-   *   attributes `segmentMaxSeq`, `receivedSegments`, `segments` are inserted.
-   */
-  _receivedSmsSegmentsMap: null,
-  _processReceivedSmsSegment: function(aSegment) {
-    // Directly replace full message body for single SMS.
-    if (!(aSegment.segmentMaxSeq && (aSegment.segmentMaxSeq > 1))) {
-      if (aSegment.encoding == Ci.nsIGonkSmsService.SMS_MESSAGE_ENCODING_8BITS_ALPHABET) {
-        aSegment.fullData = aSegment.data;
-      } else {
-        aSegment.fullBody = aSegment.body;
-      }
-      return aSegment;
-    }
-
-    // Handle Concatenation for Class 0 SMS
-    let hash = aSegment.sender + ":" +
-               aSegment.segmentRef + ":" +
-               aSegment.segmentMaxSeq;
-    let seq = aSegment.segmentSeq;
-
-    let options = this._receivedSmsSegmentsMap[hash];
-    if (!options) {
-      options = aSegment;
-      this._receivedSmsSegmentsMap[hash] = options;
-
-      options.receivedSegments = 0;
-      options.segments = [];
-    } else if (options.segments[seq]) {
-      if (options.encoding == Ci.nsIGonkSmsService.SMS_MESSAGE_ENCODING_8BITS_ALPHABET &&
-          options.encoding == aSegment.encoding &&
-          options.segments[seq].length == aSegment.data.length &&
-          options.segments[seq].every(function(aElement, aIndex) {
-            return aElement == aSegment.data[aIndex];
-          })) {
-        if (DEBUG) {
-          debug("Got duplicated binary segment no: " + seq);
-        }
-        return null;
-      }
-
-      if (options.encoding != Ci.nsIGonkSmsService.SMS_MESSAGE_ENCODING_8BITS_ALPHABET &&
-          aSegment.encoding != Ci.nsIGonkSmsService.SMS_MESSAGE_ENCODING_8BITS_ALPHABET &&
-          options.segments[seq] == aSegment.body) {
-        if (DEBUG) {
-          debug("Got duplicated text segment no: " + seq);
-        }
-        return null;
-      }
-
-      // Update mandatory properties to ensure that the segments could be
-      // concatenated properly.
-      options.encoding = aSegment.encoding;
-      options.originatorPort = aSegment.originatorPort;
-      options.destinationPort = aSegment.destinationPort;
-      options.teleservice = aSegment.teleservice;
-      // Decrease the counter for this collided segment.
-      options.receivedSegments--;
-    }
-
-    if (options.receivedSegments > 0) {
-      // Update received timestamp.
-      options.timestamp = aSegment.timestamp;
-    }
-
-    if (options.encoding == Ci.nsIGonkSmsService.SMS_MESSAGE_ENCODING_8BITS_ALPHABET) {
-      options.segments[seq] = aSegment.data;
-    } else {
-      options.segments[seq] = aSegment.body;
-    }
-    options.receivedSegments++;
-
-    // The port information is only available in 1st segment for CDMA WAP Push.
-    // If the segments of a WAP Push are not received in sequence
-    // (e.g., SMS with seq == 1 is not the 1st segment received by the device),
-    // we have to retrieve the port information from 1st segment and
-    // save it into the cached options.
-    if (aSegment.teleservice === RIL.PDU_CDMA_MSG_TELESERIVCIE_ID_WAP
-        && seq === 1) {
-      if (options.originatorPort === Ci.nsIGonkSmsService.SMS_APPLICATION_PORT_INVALID
-          && aSegment.originatorPort !== Ci.nsIGonkSmsService.SMS_APPLICATION_PORT_INVALID) {
-        options.originatorPort = aSegment.originatorPort;
-      }
-
-      if (options.destinationPort === Ci.nsIGonkSmsService.SMS_APPLICATION_PORT_INVALID
-          && aSegment.destinationPort !== Ci.nsIGonkSmsService.SMS_APPLICATION_PORT_INVALID) {
-        options.destinationPort = aSegment.destinationPort;
-      }
-    }
-
-    if (options.receivedSegments < options.segmentMaxSeq) {
-      if (DEBUG) {
-        debug("Got segment no." + seq + " of a multipart SMS: " +
-                           JSON.stringify(options));
-      }
-      return null;
-    }
-
-    // Remove from map
-    delete this._receivedSmsSegmentsMap[hash];
-
-    // Rebuild full body
-    if (options.encoding == Ci.nsIGonkSmsService.SMS_MESSAGE_ENCODING_8BITS_ALPHABET) {
-      // Uint8Array doesn't have `concat`, so we have to merge all segements
-      // by hand.
-      let fullDataLen = 0;
-      for (let i = 1; i <= options.segmentMaxSeq; i++) {
-        fullDataLen += options.segments[i].length;
-      }
-
-      options.fullData = new Uint8Array(fullDataLen);
-      for (let d= 0, i = 1; i <= options.segmentMaxSeq; i++) {
-        let data = options.segments[i];
-        for (let j = 0; j < data.length; j++) {
-          options.fullData[d++] = data[j];
-        }
-      }
-    } else {
-      options.fullBody = options.segments.join("");
-    }
-
-    // Remove handy fields after completing the concatenation.
-    delete options.receivedSegments;
-    delete options.segments;
-
-    if (DEBUG) {
-      debug("Got full multipart SMS: " + JSON.stringify(options));
-    }
-
-    return options;
-  },
-
-  /**
-   * Helper to purge complete message.
-   *
-   * We remove unnessary fields after completing the concatenation.
-   */
-  _purgeCompleteSmsMessage: function(aMessage) {
-    // Purge concatenation info
-    delete aMessage.segmentRef;
-    delete aMessage.segmentSeq;
-    delete aMessage.segmentMaxSeq;
-
-    // Purge partial message body
-    delete aMessage.data;
-    delete aMessage.body;
-  },
-
-  /**
-   * Handle WDP port push PDU. Constructor WDP bearer information and deliver
-   * to WapPushManager.
-   *
-   * @param aMessage
-   *        A SMS message.
-   */
-  _handleSmsWdpPortPush: function(aMessage, aServiceId) {
-    if (aMessage.encoding != Ci.nsIGonkSmsService.SMS_MESSAGE_ENCODING_8BITS_ALPHABET) {
-      if (DEBUG) {
-        debug("Got port addressed SMS but not encoded in 8-bit alphabet." +
-                   " Drop!");
-      }
-      return;
-    }
-
-    let options = {
-      bearer: gWAP.WDP_BEARER_GSM_SMS_GSM_MSISDN,
-      sourceAddress: aMessage.sender,
-      sourcePort: aMessage.originatorPort,
-      destinationAddress: this._getPhoneNumber(aServiceId),
-      destinationPort: aMessage.destinationPort,
-      serviceId: aServiceId
-    };
-    gWAP.WapPushManager.receiveWdpPDU(aMessage.fullData, aMessage.fullData.length,
-                                     0, options);
-  },
-
-  _handleCellbroadcastMessageReceived: function(aMessage, aServiceId) {
-    gCellBroadcastService
-      .notifyMessageReceived(aServiceId,
-                             Ci.nsICellBroadcastService.GSM_GEOGRAPHICAL_SCOPE_INVALID,
-                             aMessage.messageCode,
-                             aMessage.messageId,
-                             aMessage.language,
-                             aMessage.fullBody,
-                             Ci.nsICellBroadcastService.GSM_MESSAGE_CLASS_NORMAL,
-                             Date.now(),
-                             aMessage.serviceCategory,
-                             false,
-                             Ci.nsICellBroadcastService.GSM_ETWS_WARNING_INVALID,
-                             false,
-                             false);
-  },
-
-  _handleMwis: function(aMwi, aServiceId) {
-    let service = Cc["@mozilla.org/voicemail/voicemailservice;1"]
-                  .getService(Ci.nsIGonkVoicemailService);
-    service.notifyStatusChanged(aServiceId, aMwi.active, aMwi.msgCount,
-                                aMwi.returnNumber, aMwi.returnMessage);
-
-    gRadioInterfaces[aServiceId].sendWorkerMessage("updateMwis", { mwi: aMwi });
-  },
-
-  _portAddressedSmsApps: null,
-  _handleSmsReceived: function(aMessage, aServiceId) {
-    if (DEBUG) debug("_handleSmsReceived: " + JSON.stringify(aMessage));
-
-    if (aMessage.messageType == RIL.PDU_CDMA_MSG_TYPE_BROADCAST) {
-      this._handleCellbroadcastMessageReceived(aMessage, aServiceId);
-      return true;
-    }
-
-    // Dispatch to registered handler if application port addressing is
-    // available. Note that the destination port can possibly be zero when
-    // representing a UDP/TCP port.
-    if (aMessage.destinationPort !== Ci.nsIGonkSmsService.SMS_APPLICATION_PORT_INVALID) {
-      let handler = this._portAddressedSmsApps[aMessage.destinationPort];
-      if (handler) {
-        handler(aMessage, aServiceId);
-      }
-      return true;
-    }
-
-    if (aMessage.encoding == Ci.nsIGonkSmsService.SMS_MESSAGE_ENCODING_8BITS_ALPHABET) {
-      // Don't know how to handle binary data yet.
-      return true;
-    }
-
-    aMessage.type = "sms";
-    aMessage.sender = aMessage.sender || null;
-    aMessage.receiver = this._getPhoneNumber(aServiceId);
-    aMessage.body = aMessage.fullBody = aMessage.fullBody || null;
-
-    if (this._isSilentNumber(aMessage.sender)) {
-      aMessage.id = -1;
-      aMessage.threadId = 0;
-      aMessage.delivery = DOM_MOBILE_MESSAGE_DELIVERY_RECEIVED;
-      aMessage.deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS;
-      aMessage.read = false;
-
-      let domMessage =
-        gMobileMessageService.createSmsMessage(aMessage.id,
-                                               aMessage.threadId,
-                                               aMessage.iccId,
-                                               aMessage.delivery,
-                                               aMessage.deliveryStatus,
-                                               aMessage.sender,
-                                               aMessage.receiver,
-                                               aMessage.body,
-                                               aMessage.messageClass,
-                                               aMessage.timestamp,
-                                               aMessage.sentTimestamp,
-                                               0,
-                                               aMessage.read);
-
-      Services.obs.notifyObservers(domMessage,
-                                   kSilentSmsReceivedObserverTopic,
-                                   null);
-      return true;
-    }
-
-    if (aMessage.mwiPresent) {
-      let mwi = {
-        discard: aMessage.mwiDiscard,
-        msgCount: aMessage.mwiMsgCount,
-        active: aMessage.mwiActive,
-        returnNumber: aMessage.sender || null,
-        returnMessage: aMessage.fullBody || null
-      };
-
-      this._handleMwis(mwi, aServiceId);
-
-      // Dicarded MWI comes without text body.
-      // Hence, we discard it here after notifying the MWI status.
-      if (aMessage.mwiDiscard) {
-        return true;
-      }
-    }
-
-    let notifyReceived = (aRv, aDomMessage) => {
-      let smsMessage = null;
-      try {
-        smsMessage = aDomMessage.QueryInterface(Ci.nsISmsMessage);
-      } catch (e) {}
-      let success = Components.isSuccessCode(aRv);
-
-      this._sendAckSms(aRv, aMessage, aServiceId);
-
-      if (!success) {
-        // At this point we could send a message to content to notify the user
-        // that storing an incoming SMS failed, most likely due to a full disk.
-        if (DEBUG) {
-          debug("Could not store SMS, error code " + aRv);
-        }
-        return;
-      }
-
-      this._broadcastSmsSystemMessage(
-        Ci.nsISmsMessenger.NOTIFICATION_TYPE_RECEIVED, smsMessage);
-      Services.obs.notifyObservers(smsMessage, kSmsReceivedObserverTopic, null);
-    };
-
-    if (aMessage.messageClass != RIL.GECKO_SMS_MESSAGE_CLASSES[RIL.PDU_DCS_MSG_CLASS_0]) {
-      gMobileMessageDatabaseService.saveReceivedMessage(aMessage,
-                                                        notifyReceived);
-    } else {
-      aMessage.id = -1;
-      aMessage.threadId = 0;
-      aMessage.delivery = DOM_MOBILE_MESSAGE_DELIVERY_RECEIVED;
-      aMessage.deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS;
-      aMessage.read = false;
-
-      let domMessage =
-        gMobileMessageService.createSmsMessage(aMessage.id,
-                                               aMessage.threadId,
-                                               aMessage.iccId,
-                                               aMessage.delivery,
-                                               aMessage.deliveryStatus,
-                                               aMessage.sender,
-                                               aMessage.receiver,
-                                               aMessage.body,
-                                               aMessage.messageClass,
-                                               aMessage.timestamp,
-                                               aMessage.sentTimestamp,
-                                               0,
-                                               aMessage.read);
-
-      notifyReceived(Cr.NS_OK, domMessage);
-    }
-
-    // SMS ACK will be sent in notifyReceived. Return false here.
-    return false;
-  },
-
-  /**
-   * Handle ACK response of received SMS.
-   */
-  _sendAckSms: function(aRv, aMessage, aServiceId) {
-    if (aMessage.messageClass === RIL.GECKO_SMS_MESSAGE_CLASSES[RIL.PDU_DCS_MSG_CLASS_2]) {
-      return;
-    }
-
-    let result = RIL.PDU_FCS_OK;
-    if (!Components.isSuccessCode(aRv)) {
-      if (DEBUG) debug("Failed to handle received sms: " + aRv);
-      result = (aRv === Cr.NS_ERROR_FILE_NO_DEVICE_SPACE)
-                ? RIL.PDU_FCS_MEMORY_CAPACITY_EXCEEDED
-                : RIL.PDU_FCS_UNSPECIFIED;
-    }
-
-    gRadioInterfaces[aServiceId]
-      .sendWorkerMessage("ackSMS", { result: result });
-
-  },
-
-  /**
-   * Report SMS storage status to modem.
-   *
-   * Note: GonkDiskSpaceWatcher repeats the notification every 5 seconds when
-   *       storage is full.
-   *       Report status to modem only when the availability is changed.
-   *       Set |_smsStorageAvailable| to |null| to ensure the first run after
-   *       bootup.
-   */
-  _smsStorageAvailable: null,
-  _reportSmsMemoryStatus: function(aIsAvailable) {
-    if (this._smsStorageAvailable !== aIsAvailable) {
-      this._smsStorageAvailable = aIsAvailable;
-      for (let serviceId = 0; serviceId < gRadioInterfaces.length; serviceId++) {
-        gRadioInterfaces[serviceId]
-          .sendWorkerMessage("reportSmsMemoryStatus", { isAvailable: aIsAvailable });
-      }
-    }
-  },
-
-  // An array of silent numbers.
-  _silentNumbers: null,
-  _isSilentNumber: function(aNumber) {
-    return this._silentNumbers.indexOf(aNumber) >= 0;
-  },
-
-  /**
-   * nsISmsService interface
-   */
-  smsDefaultServiceId: 0,
-
-  getSegmentInfoForText: function(aText, aRequest) {
-    let strict7BitEncoding;
-    try {
-      strict7BitEncoding = Services.prefs.getBoolPref("dom.sms.strict7BitEncoding");
-    } catch (e) {
-      strict7BitEncoding = false;
-    }
-
-    let options = gSmsSegmentHelper.fragmentText(aText, null, strict7BitEncoding);
-    let charsInLastSegment;
-    if (options.segmentMaxSeq) {
-      let lastSegment = options.segments[options.segmentMaxSeq - 1];
-      charsInLastSegment = lastSegment.encodedBodyLength;
-      if (options.dcs == RIL.PDU_DCS_MSG_CODING_16BITS_ALPHABET) {
-        // In UCS2 encoding, encodedBodyLength is in octets.
-        charsInLastSegment /= 2;
-      }
-    } else {
-      charsInLastSegment = 0;
-    }
-
-    aRequest.notifySegmentInfoForTextGot(options.segmentMaxSeq,
-                                         options.segmentChars,
-                                         options.segmentChars - charsInLastSegment);
-  },
-
-  send: function(aServiceId, aNumber, aMessage, aSilent, aRequest) {
-    if (aServiceId > (gRadioInterfaces.length - 1)) {
-      throw Cr.NS_ERROR_INVALID_ARG;
-    }
-
-    let strict7BitEncoding;
-    try {
-      strict7BitEncoding = Services.prefs.getBoolPref("dom.sms.strict7BitEncoding");
-    } catch (e) {
-      strict7BitEncoding = false;
-    }
-
-    let options = gSmsSegmentHelper.fragmentText(aMessage, null, strict7BitEncoding);
-    options.number = gPhoneNumberUtils.normalize(aNumber);
-    let requestStatusReport;
-    try {
-      requestStatusReport =
-        Services.prefs.getBoolPref("dom.sms.requestStatusReport");
-    } catch (e) {
-      requestStatusReport = true;
-    }
-    options.requestStatusReport = requestStatusReport && !aSilent;
-
-    let sendingMessage = {
-      type: "sms",
-      sender: this._getPhoneNumber(aServiceId),
-      receiver: aNumber,
-      body: aMessage,
-      deliveryStatusRequested: options.requestStatusReport,
-      timestamp: Date.now(),
-      iccId: this._getIccId(aServiceId)
-    };
-
-    let saveSendingMessageCallback = (aRv, aDomMessage) => {
-      let smsMessage = null;
-      try {
-        smsMessage = aDomMessage.QueryInterface(Ci.nsISmsMessage);
-      } catch (e) {}
-
-      if (!Components.isSuccessCode(aRv)) {
-        if (DEBUG) debug("Error! Fail to save sending message! aRv = " + aRv);
-        this._broadcastSmsSystemMessage(
-          Ci.nsISmsMessenger.NOTIFICATION_TYPE_SENT_FAILED, smsMessage);
-        aRequest.notifySendMessageFailed(
-          gMobileMessageDatabaseService.translateCrErrorToMessageCallbackError(aRv),
-          smsMessage);
-        Services.obs.notifyObservers(smsMessage, kSmsFailedObserverTopic, null);
-        return;
-      }
-
-      if (!aSilent) {
-        Services.obs.notifyObservers(smsMessage, kSmsSendingObserverTopic, null);
-      }
-
-      let connection =
-        gMobileConnectionService.getItemByServiceId(aServiceId);
-      // If the radio is disabled or the SIM card is not ready, just directly
-      // return with the corresponding error code.
-      let errorCode;
-      let radioState = connection && connection.radioState;
-      if (!gPhoneNumberUtils.isPlainPhoneNumber(options.number)) {
-        if (DEBUG) debug("Error! Address is invalid when sending SMS: " + options.number);
-        errorCode = Ci.nsIMobileMessageCallback.INVALID_ADDRESS_ERROR;
-      } else if (radioState == Ci.nsIMobileConnection.MOBILE_RADIO_STATE_UNKNOWN ||
-                 radioState == Ci.nsIMobileConnection.MOBILE_RADIO_STATE_DISABLED) {
-        if (DEBUG) debug("Error! Radio is disabled when sending SMS.");
-        errorCode = Ci.nsIMobileMessageCallback.RADIO_DISABLED_ERROR;
-      } else if (this._getCardState(aServiceId) != Ci.nsIIcc.CARD_STATE_READY) {
-        if (DEBUG) debug("Error! SIM card is not ready when sending SMS.");
-        errorCode = Ci.nsIMobileMessageCallback.NO_SIM_CARD_ERROR;
-      }
-      if (errorCode) {
-        this._notifySendingError(errorCode, smsMessage, aSilent, aRequest);
-        return;
-      }
-
-      this._scheduleSending(aServiceId, smsMessage, aSilent, options,
-        aRequest);
-    }; // End of |saveSendingMessageCallback|.
-
-    // Don't save message into DB for silent SMS.
-    if (aSilent) {
-      let delivery = DOM_MOBILE_MESSAGE_DELIVERY_SENDING;
-      let deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_PENDING;
-      let domMessage =
-        gMobileMessageService.createSmsMessage(-1, // id
-                                               0,  // threadId
-                                               sendingMessage.iccId,
-                                               delivery,
-                                               deliveryStatus,
-                                               sendingMessage.sender,
-                                               sendingMessage.receiver,
-                                               sendingMessage.body,
-                                               "normal", // message class
-                                               sendingMessage.timestamp,
-                                               0,
-                                               0,
-                                               false);
-      saveSendingMessageCallback(Cr.NS_OK, domMessage);
-      return;
-    }
-
-    gMobileMessageDatabaseService.saveSendingMessage(
-      sendingMessage, saveSendingMessageCallback);
-  },
-
-  addSilentNumber: function(aNumber) {
-    if (this._isSilentNumber(aNumber)) {
-      throw Cr.NS_ERROR_UNEXPECTED;
-    }
-
-    this._silentNumbers.push(aNumber);
-  },
-
-  removeSilentNumber: function(aNumber) {
-   let index = this._silentNumbers.indexOf(aNumber);
-   if (index < 0) {
-     throw Cr.NS_ERROR_INVALID_ARG;
-   }
-
-   this._silentNumbers.splice(index, 1);
-  },
-
-  getSmscAddress: function(aServiceId, aRequest) {
-    if (aServiceId > (gRadioInterfaces.length - 1)) {
-      throw Cr.NS_ERROR_INVALID_ARG;
-    }
-
-    gRadioInterfaces[aServiceId].sendWorkerMessage("getSmscAddress",
-                                                   null,
-                                                   (aResponse) => {
-      if (!aResponse.errorMsg) {
-        aRequest.notifyGetSmscAddress(aResponse.smscAddress,
-                                      aResponse.typeOfNumber,
-                                      aResponse.numberPlanIdentification);
-      } else {
-        aRequest.notifyGetSmscAddressFailed(
-          Ci.nsIMobileMessageCallback.NOT_FOUND_ERROR);
-      }
-    });
-  },
-
-  setSmscAddress: function(aServiceId, aNumber, aTypeOfNumber,
-                      aNumberPlanIdentification, aRequest) {
-    if (aServiceId > (gRadioInterfaces.length - 1)) {
-      throw Cr.NS_ERROR_INVALID_ARG;
-    }
-
-    let options = {
-      smscAddress: aNumber,
-      typeOfNumber: aTypeOfNumber,
-      numberPlanIdentification: aNumberPlanIdentification
-    };
-
-    gRadioInterfaces[aServiceId].sendWorkerMessage("setSmscAddress",
-                                                   options,
-                                                   (aResponse) => {
-      if (!aResponse.errorMsg) {
-        aRequest.notifySetSmscAddress();
-      } else {
-        aRequest.notifySetSmscAddressFailed(
-          Ci.nsIMobileMessageCallback.INVALID_ADDRESS_ERROR);
-      }
-    });
-  },
-
-  /**
-   * nsIGonkSmsService interface
-   */
-  notifyMessageReceived: function(aServiceId, aSMSC, aSentTimestamp,
-                                  aSender, aPid, aEncoding, aMessageClass,
-                                  aLanguage, aSegmentRef, aSegmentSeq,
-                                  aSegmentMaxSeq, aOriginatorPort,
-                                  aDestinationPort, aMwiPresent, aMwiDiscard,
-                                  aMwiMsgCount, aMwiActive, aCdmaMessageType,
-                                  aCdmaTeleservice, aCdmaServiceCategory,
-                                  aBody, aData, aDataLength) {
-
-    this._acquireSmsHandledWakeLock();
-
-    let segment = {};
-    segment.iccId = this._getIccId(aServiceId);
-    segment.SMSC = aSMSC;
-    segment.sentTimestamp = aSentTimestamp;
-    segment.timestamp = Date.now();
-    segment.sender = aSender;
-    segment.pid = aPid;
-    segment.encoding = aEncoding;
-    segment.messageClass = this._convertSmsMessageClassToString(aMessageClass);
-    segment.language = aLanguage;
-    segment.segmentRef = aSegmentRef;
-    segment.segmentSeq = aSegmentSeq;
-    segment.segmentMaxSeq = aSegmentMaxSeq;
-    segment.originatorPort = aOriginatorPort;
-    segment.destinationPort = aDestinationPort;
-    segment.mwiPresent = aMwiPresent;
-    segment.mwiDiscard = aMwiDiscard;
-    segment.mwiMsgCount = aMwiMsgCount;
-    segment.mwiActive = aMwiActive;
-    segment.messageType = aCdmaMessageType;
-    segment.teleservice = aCdmaTeleservice;
-    segment.serviceCategory = aCdmaServiceCategory;
-    segment.body = aBody;
-    segment.data = (aData && aDataLength > 0) ? aData : null;
-
-    let isMultipart = (segment.segmentMaxSeq && (segment.segmentMaxSeq > 1));
-    let messageClass = segment.messageClass;
-
-    let handleReceivedAndAck = (aRvOfIncompleteMsg, aCompleteMessage) => {
-      if (aCompleteMessage) {
-        this._purgeCompleteSmsMessage(aCompleteMessage);
-        if (this._handleSmsReceived(aCompleteMessage, aServiceId)) {
-          this._sendAckSms(Cr.NS_OK, aCompleteMessage, aServiceId);
-        }
-        // else Ack will be sent after further process in _handleSmsReceived.
-      } else {
-        this._sendAckSms(aRvOfIncompleteMsg, segment, aServiceId);
-      }
-    };
-
-    // No need to access SmsSegmentStore for Class 0 SMS and Single SMS.
-    if (!isMultipart ||
-        (messageClass == RIL.GECKO_SMS_MESSAGE_CLASSES[RIL.PDU_DCS_MSG_CLASS_0])) {
-      // `When a mobile terminated message is class 0 and the MS has the
-      // capability of displaying short messages, the MS shall display the
-      // message immediately and send an acknowledgement to the SC when the
-      // message has successfully reached the MS irrespective of whether
-      // there is memory available in the (U)SIM or ME. The message shall
-      // not be automatically stored in the (U)SIM or ME.`
-      // ~ 3GPP 23.038 clause 4
-
-      handleReceivedAndAck(Cr.NS_OK,  // ACK OK For Incomplete Class 0
-                           this._processReceivedSmsSegment(segment));
-    } else {
-      gMobileMessageDatabaseService
-        .saveSmsSegment(segment, (aRv, aCompleteMessage) => {
-        handleReceivedAndAck(aRv,  // Ack according to the result after saving
-                             aCompleteMessage);
-      });
-    }
-  },
-
-  /**
-   * nsIObserver interface.
-   */
-  observe: function(aSubject, aTopic, aData) {
-    switch (aTopic) {
-      case NS_PREFBRANCH_PREFCHANGE_TOPIC_ID:
-        if (aData === kPrefRilDebuggingEnabled) {
-          this._updateDebugFlag();
-        }
-        else if (aData === kPrefDefaultServiceId) {
-          this.smsDefaultServiceId = this._getDefaultServiceId();
-        }
-        else if ( aData === kPrefLastKnownSimMcc) {
-          gSmsSegmentHelper.enabledGsmTableTuples =
-            getEnabledGsmTableTuplesFromMcc();
-        }
-        break;
-      case kDiskSpaceWatcherObserverTopic:
-        if (DEBUG) {
-          debug("Observe " + kDiskSpaceWatcherObserverTopic + ": " + aData);
-        }
-        this._reportSmsMemoryStatus(aData != "full");
-        break;
-      case NS_XPCOM_SHUTDOWN_OBSERVER_ID:
-        // Release the CPU wake lock for handling the received SMS.
-        this._releaseSmsHandledWakeLock();
-        Services.prefs.removeObserver(kPrefRilDebuggingEnabled, this);
-        Services.prefs.removeObserver(kPrefDefaultServiceId, this);
-        Services.obs.removeObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
-        Services.obs.removeObserver(this, kDiskSpaceWatcherObserverTopic);
-        break;
-    }
-  }
-};
-
-/**
- * Get enabled GSM national language locking shift / single shift table pairs
- * for current SIM MCC.
- *
- * @return a list of pairs of national language identifiers for locking shift
- * table and single shfit table, respectively.
- */
-function getEnabledGsmTableTuplesFromMcc() {
-  let mcc;
-  try {
-    mcc = Services.prefs.getCharPref(kPrefLastKnownSimMcc);
-  } catch (e) {}
-  let tuples = [[RIL.PDU_NL_IDENTIFIER_DEFAULT,
-    RIL.PDU_NL_IDENTIFIER_DEFAULT]];
-  let extraTuples = RIL.PDU_MCC_NL_TABLE_TUPLES_MAPPING[mcc];
-  if (extraTuples) {
-    tuples = tuples.concat(extraTuples);
-  }
-
-  return tuples;
-};
-
-function SmsSendingScheduler(aServiceId) {
-  this._serviceId = aServiceId;
-  this._queue = [];
-
-  Services.obs.addObserver(this, kSmsDeletedObserverTopic, false);
-  Services.obs.addObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
-}
-SmsSendingScheduler.prototype = {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIMobileConnectionListener]),
-
-  _serviceId: 0,
-  _isObservingMoboConn: false,
-  _queue: null,
-
-  /**
-   * Ensure the handler is listening on MobileConnection events.
-   */
-  _ensureMoboConnObserverRegistration: function() {
-    if (!this._isObservingMoboConn) {
-      let connection =
-        gMobileConnectionService.getItemByServiceId(this._serviceId);
-      if (connection) {
-        connection.registerListener(this);
-        this._isObservingMoboConn = true;
-      }
-    }
-  },
-
-  /**
-   * Ensure the handler is not listening on MobileConnection events.
-   */
-  _ensureMoboConnObserverUnregistration: function() {
-    if (this._isObservingMoboConn) {
-      let connection =
-        gMobileConnectionService.getItemByServiceId(this._serviceId);
-      if (connection) {
-        connection.unregisterListener(this);
-        this._isObservingMoboConn = false;
-      }
-    }
-  },
-
-  /**
-   * Schedule a sending request.
-   *
-   * @param aSendingRequest
-   *        An object with the following properties:
-   *        - messageId
-   *          The messageId in MobileMessageDB.
-   *        - onSend
-   *          The callback to invoke to trigger a sending or retry.
-   *        - onCancel
-   *          The callback to invoke when the request is canceled and won't
-   *          retry.
-   */
-  schedule: function(aSendingRequest) {
-    if (aSendingRequest) {
-      if (DEBUG) {
-        debug("scheduling message: messageId=" + aSendingRequest.messageId +
-              ", serviceId=" + this._serviceId);
-      }
-      this._ensureMoboConnObserverRegistration();
-      this._queue.push(aSendingRequest)
-
-      // Keep the queue in order to guarantee the sending order matches user
-      // expectation.
-      this._queue.sort(function(a, b) {
-        return a.messageId - b.messageId;
-      });
-    }
-
-    this.send();
-  },
-
-  /**
-   * Send all requests in the queue if voice connection is available.
-   */
-  send: function() {
-    let connection =
-      gMobileConnectionService.getItemByServiceId(this._serviceId);
-
-    // If the voice connection is temporarily unavailable, pend the request.
-    let voiceInfo = connection && connection.voice;
-    let voiceConnected = voiceInfo && voiceInfo.connected;
-    if (!voiceConnected) {
-      if (DEBUG) {
-        debug("Voice connection is temporarily unavailable. Skip sending.");
-      }
-      return;
-    }
-
-    let snapshot = this._queue;
-    this._queue = [];
-    let req;
-    while ((req = snapshot.shift())) {
-      req.onSend();
-    }
-
-    // The sending / retry could fail and being re-scheduled immediately.
-    // Only unregister listener when the queue is empty after retries.
-    if (this._queue.length === 0) {
-      this._ensureMoboConnObserverUnregistration();
-    }
-  },
-
-  /**
-   * nsIObserver interface.
-   */
-  observe: function(aSubject, aTopic, aData) {
-    switch (aTopic) {
-      case kSmsDeletedObserverTopic:
-        let deletedInfo = aSubject.QueryInterface(Ci.nsIDeletedMessageInfo);
-        if (DEBUG) {
-          debug("Observe " + kSmsDeletedObserverTopic + ": " +
-            JSON.stringify(deletedInfo));
-        }
-
-        if (deletedInfo && deletedInfo.deletedMessageIds) {
-          for (let i = 0; i < this._queue.length; i++) {
-            let id = this._queue[i].messageId;
-            if (deletedInfo.deletedMessageIds.includes(id)) {
-              if (DEBUG) debug("Deleting message with id=" + id);
-              this._queue.splice(i, 1)[0].onCancel(
-                Ci.nsIMobileMessageCallback.NOT_FOUND_ERROR);
-            }
-          }
-        }
-        break;
-      case NS_XPCOM_SHUTDOWN_OBSERVER_ID:
-        this._ensureMoboConnObserverUnregistration();
-        Services.obs.removeObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
-        Services.obs.removeObserver(this, kSmsDeletedObserverTopic);
-
-        // Cancel all pending requests and clear the queue.
-        for (let req of this._queue) {
-          req.onCancel(Ci.nsIMobileMessageCallback.NO_SIGNAL_ERROR);
-        }
-        this._queue = [];
-        break;
-    }
-  },
-
-  /**
-   * nsIMobileConnectionListener implementation.
-   */
-  notifyVoiceChanged: function() {
-    let connection = gMobileConnectionService.getItemByServiceId(this._serviceId);
-    let voiceInfo = connection && connection.voice;
-    let voiceConnected = voiceInfo && voiceInfo.connected;
-    if (voiceConnected) {
-      if (DEBUG) {
-        debug("Voice connected. Resend pending requests.");
-      }
-
-      this.send();
-    }
-  },
-
-  // Unused nsIMobileConnectionListener methods.
-  notifyDataChanged: function() {},
-  notifyDataError: function(message) {},
-  notifyCFStateChanged: function(action, reason, number, timeSeconds, serviceClass) {},
-  notifyEmergencyCbModeChanged: function(active, timeoutMs) {},
-  notifyOtaStatusChanged: function(status) {},
-  notifyRadioStateChanged: function() {},
-  notifyClirModeChanged: function(mode) {},
-  notifyLastKnownNetworkChanged: function() {},
-  notifyLastKnownHomeNetworkChanged: function() {},
-  notifyNetworkSelectionModeChanged: function() {},
-  notifyDeviceIdentitiesChanged: function() {}
-
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([SmsService]);
deleted file mode 100644
--- a/dom/mobilemessage/gonk/SmsService.manifest
+++ /dev/null
@@ -1,7 +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/.
-
-component {f9b9b5e2-73b4-11e4-83ff-a33e27428c86} SmsService.js
-contract @mozilla.org/sms/gonksmsservice;1 {f9b9b5e2-73b4-11e4-83ff-a33e27428c86}
-category profile-after-change SmsService @mozilla.org/sms/gonksmsservice;1
\ No newline at end of file
deleted file mode 100644
--- a/dom/mobilemessage/gonk/WspPduHelper.jsm
+++ /dev/null
@@ -1,2912 +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;
-
-Cu.importGlobalProperties(['Blob']);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/wap_consts.js", this);
-
-var DEBUG; // set to true to see debug messages
-
-// Special ASCII characters
-const NUL = 0;
-const CR = 13;
-const LF = 10;
-const SP = 32;
-const HT = 9;
-const DQUOTE = 34;
-const DEL = 127;
-
-XPCOMUtils.defineConstant(this, "NUL", NUL);
-XPCOMUtils.defineConstant(this, "CR", CR);
-XPCOMUtils.defineConstant(this, "LF", LF);
-XPCOMUtils.defineConstant(this, "SP", SP);
-XPCOMUtils.defineConstant(this, "HT", HT);
-XPCOMUtils.defineConstant(this, "DQUOTE", DQUOTE);
-XPCOMUtils.defineConstant(this, "DEL", DEL);
-
-// Special ASCII character ranges
-const CTLS = 32;
-const ASCIIS = 128;
-
-XPCOMUtils.defineConstant(this, "CTLS", CTLS);
-XPCOMUtils.defineConstant(this, "ASCIIS", ASCIIS);
-
-/**
- * Error class for generic encoding/decoding failures.
- */
-this.CodeError = function CodeError(message) {
-  this.name = "CodeError";
-  this.message = message || "Invalid format";
-}
-CodeError.prototype = new Error();
-CodeError.prototype.constructor = CodeError;
-
-/**
- * Error class for unexpected NUL char at decoding text elements.
- *
- * @param message [optional]
- *        A short description for the error.
- */
-function NullCharError(message) {
-  this.name = "NullCharError";
-  this.message = message || "Null character found";
-}
-NullCharError.prototype = new CodeError();
-NullCharError.prototype.constructor = NullCharError;
-
-/**
- * Error class for fatal encoding/decoding failures.
- *
- * This error is only raised when expected format isn't met and the parser
- * context can't do anything more to either skip it or hand over to other
- * alternative encoding/decoding steps.
- *
- * @param message [optional]
- *        A short description for the error.
- */
-this.FatalCodeError = function FatalCodeError(message) {
-  this.name = "FatalCodeError";
-  this.message = message || "Decoding fails";
-}
-FatalCodeError.prototype = new Error();
-FatalCodeError.prototype.constructor = FatalCodeError;
-
-/**
- * Error class for undefined well known encoding.
- *
- * When a encoded header field/parameter has unknown/unsupported value, we may
- * never know how to decode the next value. For example, a parameter of
- * undefined well known encoding may be followed by a Q-value, which is
- * basically a uintvar. However, there is no way you can distiguish an Q-value
- * 0.64, encoded as 0x41, from a string begins with 'A', which is also 0x41.
- * The `skipValue` will try the latter one, which is not expected.
- *
- * @param message [optional]
- *        A short description for the error.
- */
-this.NotWellKnownEncodingError = function NotWellKnownEncodingError(message) {
-  this.name = "NotWellKnownEncodingError";
-  this.message = message || "Not well known encoding";
-}
-NotWellKnownEncodingError.prototype = new FatalCodeError();
-NotWellKnownEncodingError.prototype.constructor = NotWellKnownEncodingError;
-
-/**
- * Internal helper function to retrieve the value of a property with its name
- * specified by `name` inside the object `headers`.
- *
- * @param headers
- *        An object that contains parsed header fields.
- * @param name
- *        Header name string to be checked.
- *
- * @return Value of specified header field.
- *
- * @throws FatalCodeError if headers[name] is undefined.
- */
-this.ensureHeader = function ensureHeader(headers, name) {
-  let value = headers[name];
-  // Header field might have a null value as NoValue
-  if (value === undefined) {
-    throw new FatalCodeError("ensureHeader: header " + name + " not defined");
-  }
-  return value;
-}
-
-/**
- * Skip field value.
- *
- * The WSP field values are encoded so that the length of the field value can
- * always be determined, even if the detailed format of a specific field value
- * is not known. This makes it possible to skip over individual header fields
- * without interpreting their content. ... the first octet in all the field
- * values can be interpreted as follows:
- *
- *   0 -  30 | This octet is followed by the indicated number (0 - 30) of data
- *             octets.
- *        31 | This octet is followed by a unitvar, which indicates the number
- *             of data octets after it.
- *  32 - 127 | The value is a text string, terminated by a zero octet (NUL
- *             character).
- * 128 - 255 | It is an encoded 7-bit value; this header has no more data.
- *
- * @param data
- *        A wrapped object containing raw PDU data.
- *
- * @return Skipped value of several possible types like string, integer, or
- *         an array of octets.
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.1.2
- */
-this.skipValue = function skipValue(data) {
-  let begin = data.offset;
-  let value = Octet.decode(data);
-  if (value <= 31) {
-    if (value == 31) {
-      value = UintVar.decode(data);
-    }
-
-    if (value) {
-      // `value` can be larger than 30, max length of a multi-octet integer
-      // here. So we must decode it as an array instead.
-      value = Octet.decodeMultiple(data, data.offset + value);
-    } else {
-      value = null;
-    }
-  } else if (value <= 127) {
-    data.offset = begin;
-    value = NullTerminatedTexts.decode(data);
-  } else {
-    value &= 0x7F;
-  }
-
-  return value;
-}
-
-/**
- * Helper function for decoding multiple alternative forms.
- *
- * @param data
- *        A wrapped object containing raw PDU data.
- * @param options
- *        Extra context for decoding.
- *
- * @return Decoded value.
- */
-this.decodeAlternatives = function decodeAlternatives(data, options) {
-  let begin = data.offset;
-  for (let i = 2; i < arguments.length; i++) {
-    try {
-      return arguments[i].decode(data, options);
-    } catch (e) {
-      // Throw the last exception we get
-      if (i == (arguments.length - 1)) {
-        throw e;
-      }
-
-      data.offset = begin;
-    }
-  }
-}
-
-/**
- * Helper function for encoding multiple alternative forms.
- *
- * @param data
- *        A wrapped object to store encoded raw data.
- * @param value
- *        Object value of arbitrary type to be encoded.
- * @param options
- *        Extra context for encoding.
- */
-this.encodeAlternatives = function encodeAlternatives(data, value, options) {
-  let begin = data.offset;
-  for (let i = 3; i < arguments.length; i++) {
-    try {
-      arguments[i].encode(data, value, options);
-      return;
-    } catch (e) {
-      // Throw the last exception we get
-      if (i == (arguments.length - 1)) {
-        throw e;
-      }
-
-      data.offset = begin;
-    }
-  }
-}
-
-this.Octet = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @throws RangeError if no more data is available.
-   */
-  decode: function(data) {
-    if (data.offset >= data.array.length) {
-      throw new RangeError();
-    }
-
-    return data.array[data.offset++];
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param end
-   *        An ending offset indicating the end of octet array to read.
-   *
-   * @return A decoded array object.
-   *
-   * @throws RangeError if no enough data to read.
-   * @throws TypeError if `data` has neither subarray() nor slice() method.
-   */
-  decodeMultiple: function(data, end) {
-    if ((end < data.offset) || (end > data.array.length)) {
-      throw new RangeError();
-    }
-    if (end == data.offset) {
-      return [];
-    }
-
-    let result;
-    if (data.array.subarray) {
-      result = data.array.subarray(data.offset, end);
-    } else if (data.array.slice) {
-      result = data.array.slice(data.offset, end);
-    } else {
-      throw new TypeError();
-    }
-
-    data.offset = end;
-    return result;
-  },
-
-  /**
-   * Internal octet decoding for specific value.
-   *
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param expected
-   *        Expected octet value.
-   *
-   * @return Expected octet value.
-   *
-   * @throws CodeError if read octet is not equal to expected one.
-   */
-  decodeEqualTo: function(data, expected) {
-    if (this.decode(data) != expected) {
-      throw new CodeError("Octet - decodeEqualTo: doesn't match " + expected);
-    }
-
-    return expected;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param octet
-   *        Octet value to be encoded.
-   */
-  encode: function(data, octet) {
-    if (data.offset >= data.array.length) {
-      data.array.push(octet);
-      data.offset++;
-    } else {
-      data.array[data.offset++] = octet;
-    }
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param octet
-   *        An octet array object.
-   */
-  encodeMultiple: function(data, array) {
-    for (let i = 0; i < array.length; i++) {
-      this.encode(data, array[i]);
-    }
-  },
-};
-
-/**
- * TEXT = <any OCTET except CTLs, but including LWS>
- * CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
- * LWS = [CRLF] 1*(SP|HT)
- * CRLF = CR LF
- * CR = <US-ASCII CR, carriage return (13)>
- * LF = <US-ASCII LF, linefeed (10)>
- * SP = <US-ASCII SP, space (32)>
- * HT = <US-ASCII HT, horizontal-tab(9)>
- *
- * @see RFC 2616 clause 2.2 Basic Rules
- */
-this.Text = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded character.
-   *
-   * @throws NullCharError if a NUL character read.
-   * @throws CodeError if a control character read.
-   */
-  decode: function(data) {
-    let code = Octet.decode(data);
-    if ((code >= CTLS) && (code != DEL)) {
-      return String.fromCharCode(code);
-    }
-
-    if (code == NUL) {
-      throw new NullCharError();
-    }
-
-    if (code != CR) {
-      throw new CodeError("Text: invalid char code " + code);
-    }
-
-    // "A CRLF is allowed in the definition of TEXT only as part of a header
-    // field continuation. It is expected that the folding LWS will be
-    // replaced with a single SP before interpretation of the TEXT value."
-    // ~ RFC 2616 clause 2.2
-
-    let extra;
-
-    // Rethrow everything as CodeError. We had already a successful read above.
-    try {
-      extra = Octet.decode(data);
-      if (extra != LF) {
-        throw new CodeError("Text: doesn't match LWS sequence");
-      }
-
-      extra = Octet.decode(data);
-      if ((extra != SP) && (extra != HT)) {
-        throw new CodeError("Text: doesn't match LWS sequence");
-      }
-    } catch (e if e instanceof CodeError) {
-      throw e;
-    } catch (e) {
-      throw new CodeError("Text: doesn't match LWS sequence");
-    }
-
-    // Let's eat as many SP|HT as possible.
-    let begin;
-
-    // Do not throw anything here. We had already matched (SP | HT).
-    try {
-      do {
-        begin = data.offset;
-        extra = Octet.decode(data);
-      } while ((extra == SP) || (extra == HT));
-    } catch (e) {}
-
-    data.offset = begin;
-    return " ";
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param text
-   *        String text of one character to be encoded.
-   * @param asciiOnly
-   *        A boolean to decide if it's only allowed to encode ASCII (0 ~ 127).
-   *
-   * @throws CodeError if a control character got.
-   */
-  encode: function(data, text, asciiOnly) {
-    if (!text) {
-      throw new CodeError("Text: empty string");
-    }
-
-    let code = text.charCodeAt(0);
-    if ((code < CTLS) || (code == DEL) || (code > 255) ||
-        (code >= 128 && asciiOnly)) {
-      throw new CodeError("Text: invalid char code " + code);
-    }
-    Octet.encode(data, code);
-  },
-};
-
-this.NullTerminatedTexts = {
-  /**
-   * Decode internal referenced null terminated text string.
-   *
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded string.
-   */
-  decode: function(data) {
-    let str = "";
-    try {
-      // A End-of-string is also a CTL, which should cause a error.
-      while (true) {
-        str += Text.decode(data);
-      }
-    } catch (e if e instanceof NullCharError) {
-      return str;
-    }
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param str
-   *        A String to be encoded.
-   * @param asciiOnly
-   *        A boolean to decide if it's only allowed to encode ASCII (0 ~ 127).
-   */
-  encode: function(data, str, asciiOnly) {
-    if (str) {
-      for (let i = 0; i < str.length; i++) {
-        Text.encode(data, str.charAt(i), asciiOnly);
-      }
-    }
-    Octet.encode(data, 0);
-  },
-};
-
-/**
- * TOKEN = 1*<any CHAR except CTLs or separators>
- * CHAR = <any US-ASCII character (octets 0 - 127)>
- * SEPARATORS = ()<>@,;:\"/[]?={} SP HT
- *
- * @see RFC 2616 clause 2.2 Basic Rules
- */
-this.Token = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded character.
-   *
-   * @throws NullCharError if a NUL character read.
-   * @throws CodeError if an invalid character read.
-   */
-  decode: function(data) {
-    let code = Octet.decode(data);
-    if ((code < ASCIIS) && (code >= CTLS)) {
-      if ((code == HT) || (code == SP)
-          || (code == 34) || (code == 40) || (code == 41) // ASCII "()
-          || (code == 44) || (code == 47)                 // ASCII ,/
-          || ((code >= 58) && (code <= 64))               // ASCII :;<=>?@
-          || ((code >= 91) && (code <= 93))               // ASCII [\]
-          || (code == 123) || (code == 125)) {            // ASCII {}
-        throw new CodeError("Token: invalid char code " + code);
-      }
-
-      return String.fromCharCode(code);
-    }
-
-    if (code == NUL) {
-      throw new NullCharError();
-    }
-
-    throw new CodeError("Token: invalid char code " + code);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param token
-   *        String text of one character to be encoded.
-   *
-   * @throws CodeError if an invalid character got.
-   */
-  encode: function(data, token) {
-    if (!token) {
-      throw new CodeError("Token: empty string");
-    }
-
-    let code = token.charCodeAt(0);
-    if ((code < ASCIIS) && (code >= CTLS)) {
-      if ((code == HT) || (code == SP)
-          || (code == 34) || (code == 40) || (code == 41) // ASCII "()
-          || (code == 44) || (code == 47)                 // ASCII ,/
-          || ((code >= 58) && (code <= 64))               // ASCII :;<=>?@
-          || ((code >= 91) && (code <= 93))               // ASCII [\]
-          || (code == 123) || (code == 125)) {            // ASCII {}
-        // Fallback to throw CodeError
-      } else {
-        Octet.encode(data, token.charCodeAt(0));
-        return;
-      }
-    }
-
-    throw new CodeError("Token: invalid char code " + code);
-  },
-};
-
-/**
- * uric       = reserved | unreserved | escaped
- * reserved   = ;/?:@&=+$,
- * unreserved = alphanum | mark
- * mark       = -_.!~*'()
- * escaped    = % hex hex
- * excluded but used = #%
- *
- * Or, in decimal, they are: 33,35-59,61,63-90,95,97-122,126
- *
- * @see RFC 2396 Uniform Resource Indentifiers (URI)
- */
-this.URIC = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded character.
-   *
-   * @throws NullCharError if a NUL character read.
-   * @throws CodeError if an invalid character read.
-   */
-  decode: function(data) {
-    let code = Octet.decode(data);
-    if (code == NUL) {
-      throw new NullCharError();
-    }
-
-    if ((code <= CTLS) || (code >= ASCIIS) || (code == 34) || (code == 60)
-        || (code == 62) || ((code >= 91) && (code <= 94)) || (code == 96)
-        || ((code >= 123) && (code <= 125)) || (code == 127)) {
-      throw new CodeError("URIC: invalid char code " + code);
-    }
-
-    return String.fromCharCode(code);
-  },
-};
-
-/**
- * If the first character in the TEXT is in the range of 128-255, a Quote
- * character must precede it. Otherwise the Quote character must be omitted.
- * The Quote is not part of the contents.
- *
- *   Text-string = [Quote] *TEXT End-of-string
- *   Quote = <Octet 127>
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.1
- */
-this.TextString = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded string.
-   */
-  decode: function(data) {
-    let begin = data.offset;
-    let firstCode = Octet.decode(data);
-    if (firstCode == 127) {
-      // Quote found, check if first char code is larger-equal than 128.
-      begin = data.offset;
-      try {
-        if (Octet.decode(data) < 128) {
-          throw new CodeError("Text-string: illegal quote found.");
-        }
-      } catch (e if e instanceof CodeError) {
-        throw e;
-      } catch (e) {
-        throw new CodeError("Text-string: unexpected error.");
-      }
-    } else if (firstCode >= 128) {
-      throw new CodeError("Text-string: invalid char code " + firstCode);
-    }
-
-    data.offset = begin;
-    return NullTerminatedTexts.decode(data);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param str
-   *        A String to be encoded.
-   * @param asciiOnly
-   *        A boolean to decide if it's only allowed to encode ASCII (0 ~ 127).
-   */
-  encode: function(data, str, asciiOnly) {
-    if (!str) {
-      Octet.encode(data, 0);
-      return;
-    }
-
-    let firstCharCode = str.charCodeAt(0);
-    if (firstCharCode >= 128) {
-      if (asciiOnly) {
-        throw new CodeError("Text: invalid char code " + code);
-      }
-
-      Octet.encode(data, 127);
-    }
-
-    NullTerminatedTexts.encode(data, str, asciiOnly);
-  },
-};
-
-/**
- * Token-text = Token End-of-string
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.1
- */
-this.TokenText = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded string.
-   */
-  decode: function(data) {
-    let str = "";
-    try {
-      // A End-of-string is also a CTL, which should cause a error.
-      while (true) {
-        str += Token.decode(data);
-      }
-    } catch (e if e instanceof NullCharError) {
-      return str;
-    }
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param str
-   *        A String to be encoded.
-   */
-  encode: function(data, str) {
-    if (str) {
-      for (let i = 0; i < str.length; i++) {
-        Token.encode(data, str.charAt(i));
-      }
-    }
-    Octet.encode(data, 0);
-  },
-};
-
-/**
- * The TEXT encodes an RFC2616 Quoted-string with the enclosing
- * quotation-marks <"> removed.
- *
- *   Quoted-string = <Octet 34> *TEXT End-of-string
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.1
- */
-this.QuotedString = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded string.
-   *
-   * @throws CodeError if first octet read is not 0x34.
-   */
-  decode: function(data) {
-    let value = Octet.decode(data);
-    if (value != 34) {
-      throw new CodeError("Quoted-string: not quote " + value);
-    }
-
-    return NullTerminatedTexts.decode(data);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param str
-   *        A String to be encoded.
-   */
-  encode: function(data, str) {
-    Octet.encode(data, 34);
-    NullTerminatedTexts.encode(data, str);
-  },
-};
-
-/**
- * Integers in range 0-127 shall be encoded as a one octet value with the
- * most significant bit set to one (1xxx xxxx) and with the value in the
- * remaining least significant bits.
- *
- *   Short-integer = OCTET
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.1
- */
-this.ShortInteger = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded integer value.
-   *
-   * @throws CodeError if the octet read is less than 0x80.
-   */
-  decode: function(data) {
-    let value = Octet.decode(data);
-    if (!(value & 0x80)) {
-      throw new CodeError("Short-integer: invalid value " + value);
-    }
-
-    return (value & 0x7F);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        A numeric value to be encoded.
-   *
-   * @throws CodeError if the octet read is larger-equal than 0x80.
-   */
-  encode: function(data, value) {
-    if (value >= 0x80) {
-      throw new CodeError("Short-integer: invalid value " + value);
-    }
-
-    Octet.encode(data, value | 0x80);
-  },
-};
-
-/**
- * The content octets shall be an unsigned integer value with the most
- * significant octet encoded first (big-endian representation). The minimum
- * number of octets must be used to encode the value.
- *
- *   Long-integer = Short-length Multi-octet-integer
- *   Short-length = <Any octet 0-30>
- *   Multi-octet-integer = 1*30 OCTET
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.1
- */
-this.LongInteger = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param length
-   *        Number of octets to read.
-   *
-   * @return A decoded integer value or an octets array of max 30 elements.
-   */
-  decodeMultiOctetInteger: function(data, length) {
-    if (length < 7) {
-      // Return a integer instead of an array as possible. For a multi-octet
-      // integer, there are only maximum 53 bits for integer in javascript. We
-      // will get an inaccurate one beyond that. We can't neither use bitwise
-      // operation here, for it will be limited in 32 bits.
-      let value = 0;
-      while (length--) {
-        value = value * 256 + Octet.decode(data);
-      }
-      return value;
-    }
-
-    return Octet.decodeMultiple(data, data.offset + length);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded integer value or an octets array of max 30 elements.
-   *
-   * @throws CodeError if the length read is not in 1..30.
-   */
-  decode: function(data) {
-    let length = Octet.decode(data);
-    if ((length < 1) || (length > 30)) {
-      throw new CodeError("Long-integer: invalid length " + length);
-    }
-
-    return this.decodeMultiOctetInteger(data, length);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param numOrArray
-   *        An octet array of less-equal than 30 elements or an integer
-   *        greater-equal than 128.
-   */
-  encode: function(data, numOrArray) {
-    if (typeof numOrArray === "number") {
-      let num = numOrArray;
-      if (num >= 0x1000000000000) {
-        throw new CodeError("Long-integer: number too large " + num);
-      }
-
-      let stack = [];
-      do {
-        stack.push(Math.floor(num % 256));
-        num = Math.floor(num / 256);
-      } while (num);
-
-      Octet.encode(data, stack.length);
-      while (stack.length) {
-        Octet.encode(data, stack.pop());
-      }
-      return;
-    }
-
-    let array = numOrArray;
-    if ((array.length < 1) || (array.length > 30)) {
-      throw new CodeError("Long-integer: invalid length " + array.length);
-    }
-
-    Octet.encode(data, array.length);
-    Octet.encodeMultiple(data, array);
-  },
-};
-
-/**
- * @see WAP-230-WSP-20010705-a clause 8.4.2.1
- */
-this.UintVar = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded integer value.
-   */
-  decode: function(data) {
-    let value = Octet.decode(data);
-    let result = value & 0x7F;
-    while (value & 0x80) {
-      value = Octet.decode(data);
-      result = result * 128 + (value & 0x7F);
-    }
-
-    return result;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An integer value.
-   */
-  encode: function(data, value) {
-    if (value < 0) {
-      throw new CodeError("UintVar: invalid value " + value);
-    }
-
-    let stack = [];
-    while (value >= 128) {
-      stack.push(Math.floor(value % 128));
-      value = Math.floor(value / 128);
-    }
-
-    while (stack.length) {
-      Octet.encode(data, value | 0x80);
-      value = stack.pop();
-    }
-    Octet.encode(data, value);
-  },
-};
-
-/**
- * This encoding is used for token values, which have no well-known binary
- * encoding, or when the assigned number of the well-known encoding is small
- * enough to fit into Short-Integer. We change Extension-Media from
- * NullTerminatedTexts to TextString because of Bug 823816.
- *
- *   Constrained-encoding = Extension-Media | Short-integer
- *   Extension-Media = TextString
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.1
- * @see https://bugzilla.mozilla.org/show_bug.cgi?id=823816
- */
-this.ConstrainedEncoding = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decode integer value or string.
-   */
-  decode: function(data) {
-    return decodeAlternatives(data, null, TextString, ShortInteger);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An integer or a string value.
-   */
-  encode: function(data, value) {
-    if (typeof value == "number") {
-      ShortInteger.encode(data, value);
-    } else {
-      TextString.encode(data, value);
-    }
-  },
-};
-
-/**
- * Value-length = Short-length | (Length-quote Length)
- * Short-length = <Any octet 0-30>
- * Length-quote = <Octet 31>
- * Length = Uintvar-integer
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.2
- */
-this.ValueLength = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded integer value.
-   *
-   * @throws CodeError if the first octet read is larger than 31.
-   */
-  decode: function(data) {
-    let value = Octet.decode(data);
-    if (value <= 30) {
-      return value;
-    }
-
-    if (value == 31) {
-      return UintVar.decode(data);
-    }
-
-    throw new CodeError("Value-length: invalid value " + value);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   */
-  encode: function(data, value) {
-    if (value <= 30) {
-      Octet.encode(data, value);
-    } else {
-      Octet.encode(data, 31);
-      UintVar.encode(data, value);
-    }
-  },
-};
-
-/**
- * No-value = <Octet 0>
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.3
- */
-this.NoValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Always returns null.
-   */
-  decode: function(data) {
-    Octet.decodeEqualTo(data, 0);
-    return null;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        A null or undefined value.
-   */
-  encode: function(data, value) {
-    if (value != null) {
-      throw new CodeError("No-value: invalid value " + value);
-    }
-    Octet.encode(data, 0);
-  },
-};
-
-/**
- * Text-value = No-value | Token-text | Quoted-string
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.3
- */
-this.TextValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded string or null for No-value.
-   */
-  decode: function(data) {
-    return decodeAlternatives(data, null, NoValue, TokenText, QuotedString);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param text
-   *        A null or undefined or text string.
-   */
-  encode: function(data, text) {
-    encodeAlternatives(data, text, null, NoValue, TokenText, QuotedString);
-  },
-};
-
-/**
- * Integer-Value = Short-integer | Long-integer
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.3
- */
-this.IntegerValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded integer value or array of octets.
-   */
-  decode: function(data) {
-    return decodeAlternatives(data, null, ShortInteger, LongInteger);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An integer value or an octet array of less-equal than 31 elements.
-   */
-  encode: function(data, value) {
-    if (typeof value === "number") {
-      encodeAlternatives(data, value, null, ShortInteger, LongInteger);
-    } else if (Array.isArray(value) || (value instanceof Uint8Array)) {
-      LongInteger.encode(data, value);
-    } else {
-      throw new CodeError("Integer-Value: invalid value type");
-    }
-  },
-};
-
-/**
- * The encoding of dates shall be done in number of seconds from
- * 1970-01-01, 00:00:00 GMT.
- *
- *   Date-value = Long-integer
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.3
- */
-this.DateValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A Date object.
-   */
-  decode: function(data) {
-    let numOrArray = LongInteger.decode(data);
-    let seconds;
-    if (typeof numOrArray == "number") {
-      seconds = numOrArray;
-    } else {
-      seconds = 0;
-      for (let i = 0; i < numOrArray.length; i++) {
-        seconds = seconds * 256 + numOrArray[i];
-      }
-    }
-
-    return new Date(seconds * 1000);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param date
-   *        A Date object.
-   */
-  encode: function(data, date) {
-    let seconds = date.getTime() / 1000;
-    if (seconds < 0) {
-      throw new CodeError("Date-value: negative seconds " + seconds);
-    }
-
-    LongInteger.encode(data, seconds);
-  },
-};
-
-/**
- * Delta-seconds-value = Integer-value
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.3
- */
-this.DeltaSecondsValue = IntegerValue;
-
-/**
- * Quality factor 0 and quality factors with one or two decimal digits are
- * encoded into 1-100; three digits ones into 101-1099.
- *
- *   Q-value = 1*2 OCTET
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.3
- */
-this.QValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded integer value of 1..1099.
-   *
-   * @throws CodeError if decoded UintVar is not in range 1..1099.
-   */
-  decode: function(data) {
-    let value = UintVar.decode(data);
-    if (value > 0) {
-      if (value <= 100) {
-        return (value - 1) / 100.0;
-      }
-      if (value <= 1099) {
-        return (value - 100) / 1000.0;
-      }
-    }
-
-    throw new CodeError("Q-value: invalid value " + value);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An integer within the range 1..1099.
-   */
-  encode: function(data, value) {
-    if ((value < 0) || (value >= 1)) {
-      throw new CodeError("Q-value: invalid value " + value);
-    }
-
-    value *= 1000;
-    if ((value % 10) == 0) {
-      // Two digits only.
-      UintVar.encode(data, Math.floor(value / 10 + 1));
-    } else {
-      // Three digits.
-      UintVar.encode(data, Math.floor(value + 100));
-    }
-  },
-};
-
-/**
- * The three most significant bits of the Short-integer value are interpreted
- * to encode a major version number in the range 1-7, and the four least
- * significant bits contain a minor version number in the range 0-14. If
- * there is only a major version number, this is encoded by placing the value
- * 15 in the four least significant bits.
- *
- *   Version-value = Short-integer | Text-string
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.3
- */
-this.VersionValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Binary encoded version number.
-   */
-  decode: function(data) {
-    let begin = data.offset;
-    let value;
-    try {
-      value = ShortInteger.decode(data);
-      if ((value >= 0x10) && (value < 0x80)) {
-        return value;
-      }
-
-      throw new CodeError("Version-value: invalid value " + value);
-    } catch (e) {}
-
-    data.offset = begin;
-
-    let str = TextString.decode(data);
-    if (!str.match(/^[1-7](\.1?\d)?$/)) {
-      throw new CodeError("Version-value: invalid value " + str);
-    }
-
-    let major = str.charCodeAt(0) - 0x30;
-    let minor = 0x0F;
-    if (str.length > 1) {
-      minor = str.charCodeAt(2) - 0x30;
-      if (str.length > 3) {
-        minor = 10 + (str.charCodeAt(3) - 0x30);
-        if (minor > 14) {
-          throw new CodeError("Version-value: invalid minor " + minor);
-        }
-      }
-    }
-
-    return major << 4 | minor;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param version
-   *        A binary encoded version number.
-   */
-  encode: function(data, version) {
-    if ((version < 0x10) || (version >= 0x80)) {
-      throw new CodeError("Version-value: invalid version " + version);
-    }
-
-    ShortInteger.encode(data, version);
-  },
-};
-
-/**
- * URI value should be encoded per [RFC2616], but service user may use a
- * different format.
- *
- *   Uri-value = Text-string
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.3
- * @see RFC 2616 clause 2.2 Basic Rules
- */
-this.UriValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded uri string.
-   */
-  decode: function(data) {
-    let str = "";
-    try {
-      // A End-of-string is also a CTL, which should cause a error.
-      while (true) {
-        str += URIC.decode(data);
-      }
-    } catch (e if e instanceof NullCharError) {
-      return str;
-    }
-  },
-};
-
-/**
- * Internal coder for "type" parameter.
- *
- *   Type-value = Constrained-encoding
- *
- * @see WAP-230-WSP-20010705-a table 38
- */
-this.TypeValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded content type string.
-   */
-  decode: function(data) {
-    let numOrStr = ConstrainedEncoding.decode(data);
-    if (typeof numOrStr == "string") {
-      return numOrStr.toLowerCase();
-    }
-
-    let number = numOrStr;
-    let entry = WSP_WELL_KNOWN_CONTENT_TYPES[number];
-    if (!entry) {
-      throw new NotWellKnownEncodingError(
-        "Constrained-media: not well known media " + number);
-    }
-
-    return entry.type;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param type
-   *        A content type string.
-   */
-  encode: function(data, type) {
-    let entry = WSP_WELL_KNOWN_CONTENT_TYPES[type.toLowerCase()];
-    if (entry) {
-      ConstrainedEncoding.encode(data, entry.number);
-    } else {
-      ConstrainedEncoding.encode(data, type);
-    }
-  },
-};
-
-/**
- * Parameter = Typed-parameter | Untyped-parameter
- *
- * For Typed-parameters, the actual expected type of the value is implied by
- * the well-known parameter. In addition to the expected type, there may be no
- * value. If the value cannot be encoded using expected type, it shall be
- * encoded as text.
- *
- *   Typed-parameter = Well-known-parameter-token Typed-value
- *   Well-known-parameter-token = Integer-value
- *   Typed-value = Compact-value | Text-value
- *   Compact-value = Integer-value | Date-value | Delta-seconds-value | Q-value
- *                   | Version-value | Uri-value
- *
- * For Untyped-parameters, the type of the value is unknown, but is shall be
- * encoded as an integer, if that is possible.
- *
- *   Untyped-parameter = Token-text Untyped-value
- *   Untyped-value = Integer-value | Text-value
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.4
- */
-this.Parameter = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing `name` and `value` properties or null
-   *         if something wrong. The `name` property must be a string, but the
-   *         `value` property can be many different types depending on `name`.
-   *
-   * @throws CodeError if decoded IntegerValue is an array.
-   * @throws NotWellKnownEncodingError if decoded well-known parameter number
-   *         is not registered or supported.
-   */
-  decodeTypedParameter: function(data) {
-    let numOrArray = IntegerValue.decode(data);
-    // `decodeIntegerValue` can return a array, which doesn't apply here.
-    if (typeof numOrArray != "number") {
-      throw new CodeError("Typed-parameter: invalid integer type");
-    }
-
-    let number = numOrArray;
-    let param = WSP_WELL_KNOWN_PARAMS[number];
-    if (!param) {
-      throw new NotWellKnownEncodingError(
-        "Typed-parameter: not well known parameter " + number);
-    }
-
-    let begin = data.offset, value;
-    try {
-      // Althought Text-string is not included in BNF of Compact-value, but
-      // some service provider might still pass a less-strict text form and
-      // cause a unexpected CodeError raised. For example, the `start`
-      // parameter expects its value of Text-value, but service provider might
-      // gives "<smil>", which contains illegal characters "<" and ">".
-      value = decodeAlternatives(data, null,
-                                 param.coder, TextValue, TextString);
-    } catch (e) {
-      data.offset = begin;
-
-      // Skip current parameter.
-      value = skipValue(data);
-      debug("Skip malformed typed parameter: "
-            + JSON.stringify({name: param.name, value: value}));
-
-      return null;
-    }
-
-    return {
-      name: param.name,
-      value: value,
-    };
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing `name` and `value` properties or null
-   *         if something wrong. The `name` property must be a string, but the
-   *         `value` property can be many different types depending on `name`.
-   */
-  decodeUntypedParameter: function(data) {
-    let name = TokenText.decode(data);
-
-    let begin = data.offset, value;
-    try {
-      value = decodeAlternatives(data, null, IntegerValue, TextValue);
-    } catch (e) {
-      data.offset = begin;
-
-      // Skip current parameter.
-      value = skipValue(data);
-      debug("Skip malformed untyped parameter: "
-            + JSON.stringify({name: name, value: value}));
-
-      return null;
-    }
-
-    return {
-      name: name.toLowerCase(),
-      value: value,
-    };
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing `name` and `value` properties or null
-   *         if something wrong. The `name` property must be a string, but the
-   *         `value` property can be many different types depending on `name`.
-   */
-  decode: function(data) {
-    let begin = data.offset;
-    try {
-      return this.decodeTypedParameter(data);
-    } catch (e) {
-      data.offset = begin;
-      return this.decodeUntypedParameter(data);
-    }
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param end
-   *        Ending offset of following parameters.
-   *
-   * @return An array of decoded objects.
-   */
-  decodeMultiple: function(data, end) {
-    let params = null, param;
-
-    while (data.offset < end) {
-      try {
-        param = this.decode(data);
-      } catch (e) {
-        break;
-      }
-      if (param) {
-        if (!params) {
-          params = {};
-        }
-        params[param.name] = param.value;
-      }
-    }
-
-    return params;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param param
-   *        An object containing `name` and `value` properties.
-   */
-  encodeTypedParameter: function(data, param) {
-    let entry = WSP_WELL_KNOWN_PARAMS[param.name.toLowerCase()];
-    if (!entry) {
-      throw new NotWellKnownEncodingError(
-        "Typed-parameter: not well known parameter " + param.name);
-    }
-
-    IntegerValue.encode(data, entry.number);
-    encodeAlternatives(data, param.value, null,
-                       entry.coder, TextValue, TextString);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param param
-   *        An object containing `name` and `value` properties.
-   */
-  encodeUntypedParameter: function(data, param) {
-    TokenText.encode(data, param.name);
-    encodeAlternatives(data, param.value, null, IntegerValue, TextValue);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param param
-   *        An array of parameter objects.
-   */
-  encodeMultiple: function(data, params) {
-    for (let name in params) {
-      this.encode(data, {name: name, value: params[name]});
-    }
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param param
-   *        An object containing `name` and `value` properties.
-   */
-  encode: function(data, param) {
-    let begin = data.offset;
-    try {
-      this.encodeTypedParameter(data, param);
-    } catch (e) {
-      data.offset = begin;
-      this.encodeUntypedParameter(data, param);
-    }
-  },
-};
-
-/**
- * Header = Message-header | Shift-sequence
- * Message-header = Well-known-header | Application-header
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.6
- */
-this.Header = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing `name` and `value` properties or null
-   *         in case of a failed parsing. The `name` property must be a string,
-   *         but the `value` property can be many different types depending on
-   *         `name`.
-   */
-  decodeMessageHeader: function(data) {
-    return decodeAlternatives(data, null, WellKnownHeader, ApplicationHeader);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing `name` and `value` properties or null
-   *         in case of a failed parsing. The `name` property must be a string,
-   *         but the `value` property can be many different types depending on
-   *         `name`.
-   */
-  decode: function(data) {
-    // TODO: support header code page shift-sequence
-    return this.decodeMessageHeader(data);
-  },
-
-  encodeMessageHeader: function(data, header) {
-    encodeAlternatives(data, header, null, WellKnownHeader, ApplicationHeader);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param header
-   *        An object containing two attributes: a string-typed `name` and a
-   *        `value` of arbitrary type.
-   */
-  encode: function(data, header) {
-    // TODO: support header code page shift-sequence
-    this.encodeMessageHeader(data, header);
-  },
-};
-
-/**
- * Well-known-header = Well-known-field-name Wap-value
- * Well-known-field-name = Short-integer
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.6
- */
-this.WellKnownHeader = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing `name` and `value` properties or null
-   *         in case of a failed parsing. The `name` property must be a string,
-   *         but the `value` property can be many different types depending on
-   *         `name`.
-   *
-   * @throws NotWellKnownEncodingError if decoded well-known header field
-   *         number is not registered or supported.
-   */
-  decode: function(data) {
-    let index = ShortInteger.decode(data);
-
-    let entry = WSP_HEADER_FIELDS[index];
-    if (!entry) {
-      throw new NotWellKnownEncodingError(
-        "Well-known-header: not well known header " + index);
-    }
-
-    let begin = data.offset, value;
-    try {
-      value = decodeAlternatives(data, null, entry.coder, TextValue);
-    } catch (e) {
-      data.offset = begin;
-
-      value = skipValue(data);
-      debug("Skip malformed well known header(" + index + "): "
-            + JSON.stringify({name: entry.name, value: value}));
-
-      return null;
-    }
-
-    return {
-      name: entry.name,
-      value: value,
-    };
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param header
-   *        An object containing two attributes: a string-typed `name` and a
-   *        `value` of arbitrary type.
-   */
-  encode: function(data, header) {
-    let entry = WSP_HEADER_FIELDS[header.name.toLowerCase()];
-    if (!entry) {
-      throw new NotWellKnownEncodingError(
-        "Well-known-header: not well known header " + header.name);
-    }
-
-    ShortInteger.encode(data, entry.number);
-    encodeAlternatives(data, header.value, null, entry.coder, TextValue);
-  },
-};
-
-/**
- * Application-header = Token-text Application-specific-value
- * Application-specific-value = Text-string
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.6
- */
-this.ApplicationHeader = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing `name` and `value` properties or null
-   *         in case of a failed parsing. The `name` property must be a string,
-   *         but the `value` property can be many different types depending on
-   *         `name`.
-   */
-  decode: function(data) {
-    let name = TokenText.decode(data);
-
-    let begin = data.offset, value;
-    try {
-      value = TextString.decode(data);
-    } catch (e) {
-      data.offset = begin;
-
-      value = skipValue(data);
-      debug("Skip malformed application header: "
-            + JSON.stringify({name: name, value: value}));
-
-      return null;
-    }
-
-    return {
-      name: name.toLowerCase(),
-      value: value,
-    };
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param header
-   *        An object containing two attributes: a string-typed `name` and a
-   *        `value` of arbitrary type.
-   *
-   * @throws CodeError if got an empty header name.
-   */
-  encode: function(data, header) {
-    if (!header.name) {
-      throw new CodeError("Application-header: empty header name");
-    }
-
-    TokenText.encode(data, header.name);
-    TextString.encode(data, header.value);
-  },
-};
-
-/**
- * Field-name = Token-text | Well-known-field-name
- * Well-known-field-name = Short-integer
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.6
- */
-this.FieldName = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A field name string.
-   *
-   * @throws NotWellKnownEncodingError if decoded well-known header field
-   *         number is not registered or supported.
-   */
-  decode: function(data) {
-    let begin = data.offset;
-    try {
-      return TokenText.decode(data).toLowerCase();
-    } catch (e) {}
-
-    data.offset = begin;
-
-    let number = ShortInteger.decode(data);
-    let entry = WSP_HEADER_FIELDS[number];
-    if (!entry) {
-      throw new NotWellKnownEncodingError(
-        "Field-name: not well known encoding " + number);
-    }
-
-    return entry.name;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param name
-   *        A field name string.
-   */
-  encode: function(data, name) {
-    let entry = WSP_HEADER_FIELDS[name.toLowerCase()];
-    if (entry) {
-      ShortInteger.encode(data, entry.number);
-    } else {
-      TokenText.encode(data, name);
-    }
-  },
-};
-
-/**
- * Accept-charset-value = Constrained-charset | Accept-charset-general-form
- * Constrained-charset = Any-charset | Constrained-encoding
- * Any-charset = <Octet 128>
- * Accept-charset-general-form = Value-length (Well-known-charset | Token-text) [Q-value]
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.8
- */
-this.AcceptCharsetValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A object with a property `charset` of string "*".
-   */
-  decodeAnyCharset: function(data) {
-    Octet.decodeEqualTo(data, 128);
-    return {charset: "*"};
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A object with a string property `charset` and a optional integer
-   *         property `q`.
-   *
-   * @throws NotWellKnownEncodingError if decoded well-known charset number is
-   *         not registered or supported.
-   */
-  decodeConstrainedCharset: function(data) {
-    let begin = data.offset;
-    try {
-      return this.decodeAnyCharset(data);
-    } catch (e) {}
-
-    data.offset = begin;
-
-    let numOrStr = ConstrainedEncoding.decode(data);
-    if (typeof numOrStr == "string") {
-      return {charset: numOrStr};
-    }
-
-    let charset = numOrStr;
-    let entry = WSP_WELL_KNOWN_CHARSETS[charset];
-    if (!entry) {
-      throw new NotWellKnownEncodingError(
-        "Constrained-charset: not well known charset: " + charset);
-    }
-
-    return {charset: entry.name};
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A object with a string property `charset` and a optional integer
-   *         property `q`.
-   */
-  decodeAcceptCharsetGeneralForm: function(data) {
-    let length = ValueLength.decode(data);
-
-    let begin = data.offset;
-    let end = begin + length;
-
-    let result;
-    try {
-      result = WellKnownCharset.decode(data);
-    } catch (e) {
-      data.offset = begin;
-
-      result = {charset: TokenText.decode(data)};
-      if (data.offset < end) {
-        result.q = QValue.decode(data);
-      }
-    }
-
-    if (data.offset != end) {
-      data.offset = end;
-    }
-
-    return result;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A object with a string property `charset` and a optional integer
-   *         property `q`.
-   */
-  decode: function(data) {
-    let begin = data.offset;
-    try {
-      return this.decodeConstrainedCharset(data);
-    } catch (e) {
-      data.offset = begin;
-      return this.decodeAcceptCharsetGeneralForm(data);
-    }
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An object with a string property `charset`.
-   */
-  encodeAnyCharset: function(data, value) {
-    if (!value || !value.charset || (value.charset === "*")) {
-      Octet.encode(data, 128);
-      return;
-    }
-
-    throw new CodeError("Any-charset: invalid value " + value);
-  },
-};
-
-/**
- * Well-known-charset = Any-charset | Integer-value
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.8
- */
-this.WellKnownCharset = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A object with a string property `charset`.
-   *
-   * @throws CodeError if decoded charset number is an array.
-   * @throws NotWellKnownEncodingError if decoded well-known charset number
-   *         is not registered or supported.
-   */
-  decode: function(data) {
-    let begin = data.offset;
-
-    try {
-      return AcceptCharsetValue.decodeAnyCharset(data);
-    } catch (e) {}
-
-    data.offset = begin;
-
-    // `IntegerValue.decode` can return a array, which doesn't apply here.
-    let numOrArray = IntegerValue.decode(data);
-    if (typeof numOrArray != "number") {
-      throw new CodeError("Well-known-charset: invalid integer type");
-    }
-
-    let charset = numOrArray;
-    let entry = WSP_WELL_KNOWN_CHARSETS[charset];
-    if (!entry) {
-      throw new NotWellKnownEncodingError(
-        "Well-known-charset: not well known charset " + charset);
-    }
-
-    return {charset: entry.name};
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   */
-  encode: function(data, value) {
-    let begin = data.offset;
-    try {
-      AcceptCharsetValue.encodeAnyCharset(data, value);
-      return;
-    } catch (e) {}
-
-    data.offset = begin;
-    let entry = WSP_WELL_KNOWN_CHARSETS[value.charset.toLowerCase()];
-    if (!entry) {
-      throw new NotWellKnownEncodingError(
-        "Well-known-charset: not well known charset " + value.charset);
-    }
-
-    IntegerValue.encode(data, entry.number);
-  },
-};
-
-/**
- * The short form of the Content-type-value MUST only be used when the
- * well-known media is in the range of 0-127 or a text string. In all other
- * cases the general form MUST be used.
- *
- *   Content-type-value = Constrained-media | Content-general-form
- *   Constrained-media = Constrained-encoding
- *   Content-general-form = Value-length Media-type
- *   Media-type = Media *(Parameter)
- *   Media = Well-known-media | Extension-Media
- *   Well-known-media = Integer-value
- *   Extension-Media = *TEXT End-of-string
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.24
- */
-this.ContentTypeValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing `media` and `params` properties or
-   *         null in case of a failed parsing. The `media` property must be a
-   *         string, and the `params` property is always null.
-   *
-   * @throws NotWellKnownEncodingError if decoded well-known content type number
-   *         is not registered or supported.
-   */
-  decodeConstrainedMedia: function(data) {
-    return {
-      media: TypeValue.decode(data),
-      params: null,
-    };
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decode string.
-   *
-   * @throws CodeError if decoded content type number is an array.
-   * @throws NotWellKnownEncodingError if decoded well-known content type
-   *         number is not registered or supported.
-   */
-  decodeMedia: function(data) {
-    let begin = data.offset, number;
-    try {
-      number = IntegerValue.decode(data);
-    } catch (e) {
-      data.offset = begin;
-      return NullTerminatedTexts.decode(data).toLowerCase();
-    }
-
-    // `decodeIntegerValue` can return a array, which doesn't apply here.
-    if (typeof number != "number") {
-      throw new CodeError("Media: invalid integer type");
-    }
-
-    let entry = WSP_WELL_KNOWN_CONTENT_TYPES[number];
-    if (!entry) {
-      throw new NotWellKnownEncodingError("Media: not well known media " + number);
-    }
-
-    return entry.type;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param end
-   *        Ending offset of the Media-type value.
-   *
-   * @return A decoded object containing `media` and `params` properties or
-   *         null in case of a failed parsing. The `media` property must be a
-   *         string, and the `params` property is a hash map from a string to
-   *         an value of unspecified type.
-   */
-  decodeMediaType: function(data, end) {
-    let media = this.decodeMedia(data);
-    let params = Parameter.decodeMultiple(data, end);
-
-    return {
-      media: media,
-      params: params,
-    };
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing `media` and `params` properties or
-   *         null in case of a failed parsing. The `media` property must be a
-   *         string, and the `params` property is null or a hash map from a
-   *         string to an value of unspecified type.
-   */
-  decodeContentGeneralForm: function(data) {
-    let length = ValueLength.decode(data);
-    let end = data.offset + length;
-
-    let value = this.decodeMediaType(data, end);
-
-    if (data.offset != end) {
-      data.offset = end;
-    }
-
-    return value;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return A decoded object containing `media` and `params` properties or
-   *         null in case of a failed parsing. The `media` property must be a
-   *         string, and the `params` property is null or a hash map from a
-   *         string to an value of unspecified type.
-   */
-  decode: function(data) {
-    let begin = data.offset;
-
-    try {
-      return this.decodeConstrainedMedia(data);
-    } catch (e) {
-      data.offset = begin;
-      return this.decodeContentGeneralForm(data);
-    }
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An object containing `media` and `params` properties.
-   */
-  encodeConstrainedMedia: function(data, value) {
-    if (value.params) {
-      throw new CodeError("Constrained-media: should use general form instead");
-    }
-
-    TypeValue.encode(data, value.media);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An object containing `media` and `params` properties.
-   */
-  encodeMediaType: function(data, value) {
-    let entry = WSP_WELL_KNOWN_CONTENT_TYPES[value.media.toLowerCase()];
-    if (entry) {
-      IntegerValue.encode(data, entry.number);
-    } else {
-      NullTerminatedTexts.encode(data, value.media);
-    }
-
-    Parameter.encodeMultiple(data, value.params);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An object containing `media` and `params` properties.
-   */
-  encodeContentGeneralForm: function(data, value) {
-    let begin = data.offset;
-    this.encodeMediaType(data, value);
-
-    // Calculate how much octets will be written and seek back.
-    // TODO: use memmove, see bug 730873
-    let len = data.offset - begin;
-    data.offset = begin;
-
-    ValueLength.encode(data, len);
-    this.encodeMediaType(data, value);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object to store encoded raw data.
-   * @param value
-   *        An object containing `media` and `params` properties.
-   */
-  encode: function(data, value) {
-    let begin = data.offset;
-
-    try {
-      this.encodeConstrainedMedia(data, value);
-    } catch (e) {
-      data.offset = begin;
-      this.encodeContentGeneralForm(data, value);
-    }
-  },
-};
-
-/**
- * Application-id-value = Uri-value | App-assigned-code
- * App-assigned-code = Integer-value
- *
- * @see WAP-230-WSP-20010705-a clause 8.4.2.54
- */
-this.ApplicationIdValue = {
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return Decoded string value.
-   *
-   * @throws CodeError if decoded application id number is an array.
-   * @throws NotWellKnownEncodingError if decoded well-known application id
-   *         number is not registered or supported.
-   */
-  decode: function(data) {
-    let begin = data.offset;
-    try {
-      return UriValue.decode(data);
-    } catch (e) {}
-
-    data.offset = begin;
-
-    // `decodeIntegerValue` can return a array, which doesn't apply here.
-    let numOrArray = IntegerValue.decode(data);
-    if (typeof numOrArray != "number") {
-      throw new CodeError("Application-id-value: invalid integer type");
-    }
-
-    let id = numOrArray;
-    let entry = OMNA_PUSH_APPLICATION_IDS[id];
-    if (!entry) {
-      throw new NotWellKnownEncodingError(
-        "Application-id-value: not well known id: " + id);
-    }
-
-    return entry.urn;
-  },
-};
-
-this.PduHelper = {
-  /**
-   * @param data
-   *        A UInt8Array of data for decode.
-   * @param charset
-   *        charset for decode
-   *
-   * @return Decoded string.
-   */
-  decodeStringContent: function(data, charset) {
-      let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
-                 .createInstance(Ci.nsIScriptableUnicodeConverter);
-
-      let entry;
-      if (charset) {
-        entry = WSP_WELL_KNOWN_CHARSETS[charset];
-      }
-      // Set converter to default one if (entry && entry.converter) is null.
-      // @see OMA-TS-MMS-CONF-V1_3-20050526-D 7.1.9
-      conv.charset = (entry && entry.converter) || "UTF-8";
-      try {
-        return conv.convertFromByteArray(data, data.length);
-      } catch (e) {
-      }
-      return null;
-  },
-
-  /**
-  * @param strContent
-  *        Decoded string content.
-  * @param charset
-  *        Charset for encode.
-  *
-  * @return An encoded UInt8Array of string content.
-  */
-  encodeStringContent: function(strContent, charset) {
-    let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
-               .createInstance(Ci.nsIScriptableUnicodeConverter);
-
-    let entry;
-    if (charset) {
-      entry = WSP_WELL_KNOWN_CHARSETS[charset];
-    }
-    // Set converter to default one if (entry && entry.converter) is null.
-    // @see OMA-TS-MMS-CONF-V1_3-20050526-D 7.1.9
-    conv.charset = (entry && entry.converter) || "UTF-8";
-    try {
-      return conv.convertToByteArray(strContent);
-    } catch (e) {
-    }
-    return null;
-  },
-
-  /**
-   * Parse multiple header fields with end mark.
-   *
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param end
-   *        An ending offset indicating the end of headers.
-   * @param headers [optional]
-   *        An optional object to store parsed header fields. Created
-   *        automatically if undefined.
-   *
-   * @return A object containing decoded header fields as its attributes.
-   */
-  parseHeaders: function(data, end, headers) {
-    if (!headers) {
-      headers = {};
-    }
-
-    let header;
-    while (data.offset < end) {
-      try {
-        header = Header.decode(data);
-      } catch (e) {
-        break;
-      }
-      if (header) {
-        headers[header.name] = header.value;
-      }
-    }
-
-    if (data.offset != end) {
-      debug("Parser expects ending in " + end + ", but in " + data.offset);
-      // Explicitly seek to end in case of skipped header fields.
-      data.offset = end;
-    }
-
-    return headers;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param msg
-   *        Message object to be populated with decoded header fields.
-   *
-   * @see WAP-230-WSP-20010705-a clause 8.2.4
-   */
-  parsePushHeaders: function(data, msg) {
-    if (!msg.headers) {
-      msg.headers = {};
-    }
-
-    let headersLen = UintVar.decode(data);
-    let headersEnd = data.offset + headersLen;
-
-    let contentType = ContentTypeValue.decode(data);
-    msg.headers["content-type"] = contentType;
-
-    msg.headers = this.parseHeaders(data, headersEnd, msg.headers);
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   *
-   * @return An array of objects representing multipart entries or null in case
-   *         of errors found.
-   *
-   * @see WAP-230-WSP-20010705-a section 8.5
-   */
-  parseMultiPart: function(data) {
-    let nEntries = UintVar.decode(data);
-    if (!nEntries) {
-      return null;
-    }
-
-    let parts = new Array(nEntries);
-    for (let i = 0; i < nEntries; i++) {
-      // Length of the ContentType and Headers fields combined.
-      let headersLen = UintVar.decode(data);
-      // Length of the Data field
-      let contentLen = UintVar.decode(data);
-
-      let headersEnd = data.offset + headersLen;
-      let contentEnd = headersEnd + contentLen;
-
-      try {
-        let headers = {};
-
-        let contentType = ContentTypeValue.decode(data);
-        headers["content-type"] = contentType;
-        headers["content-length"] = contentLen;
-
-        headers = this.parseHeaders(data, headersEnd, headers);
-
-        let octetArray = Octet.decodeMultiple(data, contentEnd);
-        let content = null;
-        let charset = headers["content-type"].params &&
-                      headers["content-type"].params.charset
-                    ? headers["content-type"].params.charset.charset
-                    : null;
-
-        let mimeType = headers["content-type"].media;
-
-        if (mimeType) {
-          if (mimeType == "application/smil") {
-            // If the content is a SMIL type, convert it to a string.
-            // We hope to save and expose the SMIL content in a string way.
-            content = this.decodeStringContent(octetArray, charset);
-          } else if (mimeType.indexOf("text/") == 0 && charset != "utf-8") {
-            // If the content is a "text/plain" type, we have to make sure
-            // the encoding of the blob content should always be "utf-8".
-            let tmpStr = this.decodeStringContent(octetArray, charset);
-            let encoder = new TextEncoder("UTF-8");
-            content = new Blob([encoder.encode(tmpStr)], {type : mimeType});
-
-            // Make up the missing encoding info.
-            if (!headers["content-type"].params) {
-              headers["content-type"].params = {};
-            }
-            if (!headers["content-type"].params.charset) {
-              headers["content-type"].params.charset = {};
-            }
-            headers["content-type"].params.charset.charset = "utf-8";
-          }
-        }
-
-        if (!content) {
-          content = new Blob([octetArray], {type : mimeType});
-        }
-
-        parts[i] = {
-          index: i,
-          headers: headers,
-          content: content,
-        };
-      } catch (e) {
-        debug("Failed to parse multipart entry, message: " + e.message);
-        // Placeholder to keep original index of following entries.
-        parts[i] = null;
-      }
-
-      if (data.offset != contentEnd) {
-        // Seek to entry boundary for next entry.
-        data.offset = contentEnd;
-      }
-    }
-
-    return parts;
-  },
-
-  /**
-   * @param data
-   *        A wrapped object containing raw PDU data.
-   * @param isSessionless
-   *        Whether or not the PDU contains a session less WSP PDU.
-   * @param msg [optional]
-   *        Optional pre-defined PDU object.
-   *
-   * @return Parsed WSP PDU object or null in case of errors found.
-   */
-  parse: function(data, isSessionless, msg) {
-    if (!msg) {
-      msg = {
-        type: null,
-      };
-    }
-
-    try {
-      if (isSessionless) {
-        // "The `transactionId` is used to associate requests with replies in
-        // the connectionless session service." ~ WAP-230-WSP-20010705-a 8.2.1
-        msg.transactionId = Octet.decode(data);
-      }
-
-      msg.type = Octet.decode(data);
-      switch (msg.type) {
-        case WSP_PDU_TYPE_PUSH:
-          this.parsePushHeaders(data, msg);
-          break;
-      }
-    } catch (e) {
-      debug("Parse error. Message: " + e.message);
-      msg = null;
-    }
-
-    return msg;
-  },
-
-  /**
-   * @param multiStream
-   *        An exsiting nsIMultiplexInputStream.
-   * @param array
-   *        An octet array.
-   * @param length
-   *        Max number of octets to be coverted into an input stream.
-   */
-  appendArrayToMultiStream: function(multiStream, array, length) {
-    let storageStream = Cc["@mozilla.org/storagestream;1"]
-                        .createInstance(Ci.nsIStorageStream);
-    storageStream.init(4096, length, null);
-
-    let boStream = Cc["@mozilla.org/binaryoutputstream;1"]
-                   .createInstance(Ci.nsIBinaryOutputStream);
-    boStream.setOutputStream(storageStream.getOutputStream(0));
-    boStream.writeByteArray(array, length);
-    boStream.close();
-
-    multiStream.appendStream(storageStream.newInputStream(0));
-  },
-
-  /**
-   * @param multiStream
-   *        An exsiting nsIMultiplexInputStream.
-   * @param parts
-   *        An array of objects representing multipart entries.
-   *
-   * @see WAP-230-WSP-20010705-a section 8.5
-   */
-  composeMultiPart: function(multiStream, parts) {
-    // Encode multipart header
-    {
-      let data = {array: [], offset: 0};
-      UintVar.encode(data, parts.length);
-      debug("Encoded multipart header: " + JSON.stringify(data.array));
-      this.appendArrayToMultiStream(multiStream, data.array, data.offset);
-    }
-
-    // Encode each part
-    for (let i = 0; i < parts.length; i++) {
-      let part = parts[i];
-      let data = {array: [], offset: 0};
-
-      // Encode Content-Type
-      let contentType = part.headers["content-type"];
-      ContentTypeValue.encode(data, contentType);
-
-      // Encode other headers
-      if (Object.keys(part).length > 1) {
-        // Remove Content-Type temporarily
-        delete part.headers["content-type"];
-
-        for (let name in part.headers) {
-          Header.encode(data, {name: name, value: part.headers[name]});
-        }
-
-        // Restore Content-Type back
-        part.headers["content-type"] = contentType;
-      }
-
-      // Encode headersLen, DataLen
-      let headersLen = data.offset;
-      let content = part.content;
-      UintVar.encode(data, headersLen);
-      if (typeof content === "string") {
-        let charset;
-        if (contentType && contentType.params && contentType.params.charset &&
-          contentType.params.charset.charset) {
-          charset = contentType.params.charset.charset;
-        }
-        content = this.encodeStringContent(content, charset);
-        UintVar.encode(data, content.length);
-      } else if (part.content instanceof Uint8Array) {
-        UintVar.encode(data, content.length);
-      } else {
-        throw new TypeError();
-      }
-
-      // Move them to the beginning of encoded octet array.
-      let slice1 = data.array.slice(headersLen);
-      let slice2 = data.array.slice(0, headersLen);
-      data.array = slice1.concat(slice2);
-      debug("Encoded per-part header: " + JSON.stringify(data.array));
-
-      // Append per-part header
-      this.appendArrayToMultiStream(multiStream, data.array, data.offset);
-      // Append part content
-      this.appendArrayToMultiStream(multiStream, content, content.length);
-    }
-  },
-};
-
-// WSP Header Field Name Assignments
-// Note: Items commented out are either deprecated or not implemented.
-//       Deprecated items should only be supported for backward compatibility
-//       purpose.
-// @see WAP-230-WSP-20010705-a Appendix A. Assigned Numbers.
-this.WSP_HEADER_FIELDS = (function() {
-  let names = {};
-  function add(name, number, coder) {
-    let entry = {
-      name: name,
-      number: number,
-      coder: coder,
-    };
-    names[name] = names[number] = entry;
-  }
-
-  // Encoding Version: 1.1
-  //add("accept",               0x00);
-  //add("accept-charset",       0x01); Deprecated
-  //add("accept-encoding",      0x02); Deprecated
-  //add("accept-language",      0x03);
-  //add("accept-ranges",        0x04);
-  add("age",                    0x05, DeltaSecondsValue);
-  //add("allow",                0x06);
-  //add("authorization",        0x07);
-  //add("cache-control",        0x08); Deprecated
-  //add("connection",           0x09);
-  //add("content-base",         0x0A); Deprecated
-  //add("content-encoding",     0x0B);
-  //add("content-language",     0x0C);
-  add("content-length",         0x0D, IntegerValue);
-  add("content-location",       0x0E, UriValue);
-  //add("content-md5",          0x0F);
-  //add("content-range",        0x10); Deprecated
-  add("content-type",           0x11, ContentTypeValue);
-  add("date",                   0x12, DateValue);
-  add("etag",                   0x13, TextString);
-  add("expires",                0x14, DateValue);
-  add("from",                   0x15, TextString);
-  add("host",                   0x16, TextString);
-  add("if-modified-since",      0x17, DateValue);
-  add("if-match",               0x18, TextString);
-  add("if-none-match",          0x19, TextString);
-  //add("if-range",             0x1A);
-  add("if-unmodified-since",    0x1B, DateValue);
-  add("location",               0x1C, UriValue);
-  add("last-modified",          0x1D, DateValue);
-  add("max-forwards",           0x1E, IntegerValue);
-  //add("pragma",               0x1F);
-  //add("proxy-authenticate",   0x20);
-  //add("proxy-authentication", 0x21);
-  //add("public",               0x22);
-  //add("range",                0x23);
-  add("referer",                0x24, UriValue);
-  //add("retry-after",          0x25);
-  add("server",                 0x26, TextString);
-  //add("transfer-encoding",    0x27);
-  add("upgrade",                0x28, TextString);
-  add("user-agent",             0x29, TextString);
-  //add("vary",                 0x2A);
-  add("via",                    0x2B, TextString);
-  //add("warning",              0x2C);
-  //add("www-authenticate",     0x2D);
-  //add("content-disposition",  0x2E); Deprecated
-
-  // Encoding Version: 1.2
-  add("x-wap-application-id",   0x2F, ApplicationIdValue);
-  add("x-wap-content-uri",      0x30, UriValue);
-  add("x-wap-initiator-uri",    0x31, UriValue);
-  //add("accept-application",   0x32);
-  add("bearer-indication",      0x33, IntegerValue);
-  add("push-flag",              0x34, ShortInteger);
-  add("profile",                0x35, UriValue);
-  //add("profile-diff",         0x36);
-  //add("profile-warning",      0x37); Deprecated
-
-  // Encoding Version: 1.3
-  //add("expect",               0x38);
-  //add("te",                   0x39);
-  //add("trailer",              0x3A);
-  add("accept-charset",         0x3B, AcceptCharsetValue);
-  //add("accept-encoding",      0x3C);
-  //add("cache-control",        0x3D); Deprecated
-  //add("content-range",        0x3E);
-  add("x-wap-tod",              0x3F, DateValue);
-  add("content-id",             0x40, QuotedString);
-  //add("set-cookie",           0x41);
-  //add("cookie",               0x42);
-  //add("encoding-version",     0x43);
-
-  // Encoding Version: 1.4
-  //add("profile-warning",      0x44);
-  //add("content-disposition",  0x45);
-  //add("x-wap-security",       0x46);
-  //add("cache-control",        0x47);
-
-  return names;
-})();
-
-// WSP Content Type Assignments
-// @see http://www.openmobilealliance.org/tech/omna/omna-wsp-content-type.aspx
-this.WSP_WELL_KNOWN_CONTENT_TYPES = (function() {
-  let types = {};
-
-  function add(type, number) {
-    let entry = {
-      type: type,
-      number: number,
-    };
-    // For case like "text/x-vCalendar", we need toLoweCase() for generating
-    // the same index.
-    types[type.toLowerCase()] = types[number] = entry;
-  }
-
-  // Well Known Values
-  // Encoding Version: 1.1
-  add("*/*", 0x00);
-  add("text/*", 0x01);
-  add("text/html", 0x02);
-  add("text/plain", 0x03);
-  add("text/x-hdml", 0x04);
-  add("text/x-ttml", 0x05);
-  add("text/x-vCalendar", 0x06);
-  add("text/x-vCard", 0x07);
-  add("text/vnd.wap.wml", 0x08);
-  add("text/vnd.wap.wmlscript", 0x09);
-  add("text/vnd.wap.wta-event", 0x0A);
-  add("multipart/*", 0x0B);
-  add("multipart/mixed", 0x0C);
-  add("multipart/form-data", 0x0D);
-  add("multipart/byterantes", 0x0E);
-  add("multipart/alternative", 0x0F);
-  add("application/*", 0x10);
-  add("application/java-vm", 0x11);
-  add("application/x-www-form-urlencoded", 0x12);
-  add("application/x-hdmlc", 0x13);
-  add("application/vnd.wap.wmlc", 0x14);
-  add("application/vnd.wap.wmlscriptc", 0x15);
-  add("application/vnd.wap.wta-eventc", 0x16);
-  add("application/vnd.wap.uaprof", 0x17);
-  add("application/vnd.wap.wtls-ca-certificate", 0x18);
-  add("application/vnd.wap.wtls-user-certificate", 0x19);
-  add("application/x-x509-ca-cert", 0x1A);
-  add("application/x-x509-user-cert", 0x1B);
-  add("image/*", 0x1C);
-  add("image/gif", 0x1D);
-  add("image/jpeg", 0x1E);
-  add("image/tiff", 0x1F);
-  add("image/png", 0x20);
-  add("image/vnd.wap.wbmp", 0x21);
-  add("application/vnd.wap.multipart.*", 0x22);
-  add("application/vnd.wap.multipart.mixed", 0x23);
-  add("application/vnd.wap.multipart.form-data", 0x24);
-  add("application/vnd.wap.multipart.byteranges", 0x25);
-  add("application/vnd.wap.multipart.alternative", 0x26);
-  add("application/xml", 0x27);
-  add("text/xml", 0x28);
-  add("application/vnd.wap.wbxml", 0x29);
-  add("application/x-x968-cross-cert", 0x2A);
-  add("application/x-x968-ca-cert", 0x2B);
-  add("application/x-x968-user-cert", 0x2C);
-  add("text/vnd.wap.si", 0x2D);
-
-  // Encoding Version: 1.2
-  add("application/vnd.wap.sic", 0x2E);
-  add("text/vnd.wap.sl", 0x2F);
-  add("application/vnd.wap.slc", 0x30);
-  add("text/vnd.wap.co", 0x31);
-  add("application/vnd.wap.coc", 0x32);
-  add("application/vnd.wap.multipart.related", 0x33);
-  add("application/vnd.wap.sia", 0x34);
-
-  // Encoding Version: 1.3
-  add("text/vnd.wap.connectivity-xml", 0x35);
-  add("application/vnd.wap.connectivity-wbxml", 0x36);
-
-  // Encoding Version: 1.4
-  add("application/pkcs7-mime", 0x37);
-  add("application/vnd.wap.hashed-certificate", 0x38);
-  add("application/vnd.wap.signed-certificate", 0x39);
-  add("application/vnd.wap.cert-response", 0x3A);
-  add("application/xhtml+xml", 0x3B);
-  add("application/wml+xml", 0x3C);
-  add("text/css", 0x3D);
-  add("application/vnd.wap.mms-message", 0x3E);
-  add("application/vnd.wap.rollover-certificate", 0x3F);
-
-  // Encoding Version: 1.5
-  add("application/vnd.wap.locc+wbxml", 0x40);
-  add("application/vnd.wap.loc+xml", 0x41);
-  add("application/vnd.syncml.dm+wbxml", 0x42);
-  add("application/vnd.syncml.dm+xml", 0x43);
-  add("application/vnd.syncml.notification", 0x44);
-  add("application/vnd.wap.xhtml+xml", 0x45);
-  add("application/vnd.wv.csp.cir", 0x46);
-  add("application/vnd.oma.dd+xml", 0x47);
-  add("application/vnd.oma.drm.message", 0x48);
-  add("application/vnd.oma.drm.content", 0x49);
-  add("application/vnd.oma.drm.rights+xml", 0x4A);
-  add("application/vnd.oma.drm.rights+wbxml", 0x4B);
-  add("application/vnd.wv.csp+xml", 0x4C);
-  add("application/vnd.wv.csp+wbxml", 0x4D);
-  add("application/vnd.syncml.ds.notification", 0x4E);
-
-  // Encoding Version: 1.6
-  add("audio/*", 0x4F);
-  add("video/*", 0x50);
-
-  // Encoding Version: TBD
-  add("application/vnd.oma.dd2+xml", 0x51);
-  add("application/mikey", 0x52);
-  add("application/vnd.oma.dcd", 0x53);
-  add("application/vnd.oma.dcdc", 0x54);
-  add("text/x-vMessage", 0x55);
-  add("application/vnd.omads-email+wbxml", 0x56);
-  add("text/x-vBookmark", 0x57);
-  add("application/vnd.syncml.dm.notification", 0x58);
-  add("application/octet-stream", 0x5A);
-
-  return types;
-})();
-
-// WSP Well-Known Parameter Assignments
-// Note: Items commented out are either deprecated or not implemented.
-//       Deprecated items should not be used.
-// @see WAP-230-WSP-20010705-a Appendix A. Assigned Numbers.
-this.WSP_WELL_KNOWN_PARAMS = (function() {
-  let params = {};
-
-  function add(name, number, coder) {
-    let entry = {
-      name: name,
-      number: number,
-      coder: coder,
-    };
-    params[name] = params[number] = entry;
-  }
-
-  // Encoding Version: 1.1
-  add("q",                 0x00, QValue);
-  add("charset",           0x01, WellKnownCharset);
-  add("level",             0x02, VersionValue);
-  add("type",              0x03, IntegerValue);
-  add("name",              0x05, TextValue); // Deprecated, but used in some carriers, eg. Hinet.
-  //add("filename",        0x06); Deprecated
-  add("differences",       0x07, FieldName);
-  add("padding",           0x08, ShortInteger);
-
-  // Encoding Version: 1.2
-  add("type",              0x09, TypeValue);
-  add("start",             0x0A, TextValue); // Deprecated, but used in some carriers, eg. T-Mobile.
-  //add("start-info",      0x0B); Deprecated
-
-  // Encoding Version: 1.3
-  //add("comment",         0x0C); Deprecated
-  //add("domain",          0x0D); Deprecated
-  add("max-age",           0x0E, DeltaSecondsValue);
-  //add("path",            0x0F); Deprecated
-  add("secure",            0x10, NoValue);
-
-  // Encoding Version: 1.4
-  add("sec",               0x11, ShortInteger);
-  add("mac",               0x12, TextValue);
-  add("creation-date",     0x13, DateValue);
-  add("modification-date", 0x14, DateValue);
-  add("read-date",         0x15, DateValue);
-  add("size",              0x16, IntegerValue);
-  //add("name",            0x17, TextValue); // Not supported in some carriers, eg. Hinet.
-  add("filename",          0x18, TextValue);
-  //add("start",           0x19, TextValue); // Not supported in some carriers, eg. Hinet.
-  add("start-info",        0x1A, TextValue);
-  add("comment",           0x1B, TextValue);
-  add("domain",            0x1C, TextValue);
-  add("path",              0x1D, TextValue);
-
-  return params;
-})();
-
-// WSP Character Set Assignments
-// @see WAP-230-WSP-20010705-a Appendix A. Assigned Numbers.
-// @see http://www.iana.org/assignments/character-sets
-this.WSP_WELL_KNOWN_CHARSETS = (function() {
-  let charsets = {};
-
-  function add(name, number, converter) {
-    let entry = {
-      name: name,
-      number: number,
-      converter: converter,
-    };
-
-    charsets[name] = charsets[number] = entry;
-  }
-
-  add("us-ascii",           3, null);
-  add("iso-8859-1",         4, "ISO-8859-1");
-  add("iso-8859-2",         5, "ISO-8859-2");
-  add("iso-8859-3",         6, "ISO-8859-3");
-  add("iso-8859-4",         7, "ISO-8859-4");
-  add("iso-8859-5",         8, "ISO-8859-5");
-  add("iso-8859-6",         9, "ISO-8859-6");
-  add("iso-8859-7",        10, "ISO-8859-7");
-  add("iso-8859-8",        11, "ISO-8859-8");
-  add("iso-8859-9",        12, "ISO-8859-9");
-  add("iso-8859-10",       13, "ISO-8859-10");
-  add("shift_jis",         17, "Shift_JIS");
-  add("euc-jp",            18, "EUC-JP");
-  add("iso-2022-kr",       37, "ISO-2022-KR");
-  add("euc-kr",            38, "EUC-KR");
-  add("iso-2022-jp",       39, "ISO-2022-JP");
-  add("iso-2022-jp-2",     40, "iso-2022-jp-2");
-  add("iso-8859-6-e",      81, "ISO-8859-6-E");
-  add("iso-8859-6-i",      82, "ISO-8859-6-I");
-  add("iso-8859-8-e",      84, "ISO-8859-8-E");
-  add("iso-8859-8-i",      85, "ISO-8859-8-I");
-  add("utf-8",            106, "UTF-8");
-  add("iso-10646-ucs-2", 1000, "iso-10646-ucs-2");
-  add("utf-16",          1015, "UTF-16");
-  add("gb2312",          2025, "GB2312");
-  add("big5",            2026, "Big5");
-  add("koi8-r",          2084, "KOI8-R");
-  add("windows-1252",    2252, "windows-1252");
-
-  return charsets;
-})();
-
-// OMNA PUSH Application ID
-// @see http://www.openmobilealliance.org/tech/omna/omna-push-app-id.aspx
-this.OMNA_PUSH_APPLICATION_IDS = (function() {
-  let ids = {};
-
-  function add(urn, number) {
-    let entry = {
-      urn: urn,
-      number: number,
-    };
-
-    ids[urn] = ids[number] = entry;
-  }
-
-  add("x-wap-application:wml.ua", 0x02);
-  add("x-wap-application:mms.ua", 0x04);
-
-  return ids;
-})();
-
-var debug;
-if (DEBUG) {
-  debug = function(s) {
-    dump("-@- WspPduHelper: " + s + "\n");
-  };
-} else {
-  debug = function(s) {};
-}
-
-this.EXPORTED_SYMBOLS = ALL_CONST_SYMBOLS.concat([
-  // Constant values
-  "WSP_HEADER_FIELDS",
-  "WSP_WELL_KNOWN_CONTENT_TYPES",
-  "WSP_WELL_KNOWN_PARAMS",
-  "WSP_WELL_KNOWN_CHARSETS",
-  "OMNA_PUSH_APPLICATION_IDS",
-
-  // Error classes
-  "CodeError",
-  "FatalCodeError",
-  "NotWellKnownEncodingError",
-
-  // Utility functions
-  "ensureHeader",
-  "skipValue",
-  "decodeAlternatives",
-  "encodeAlternatives",
-
-  // Decoders
-  "Octet",
-  "Text",
-  "NullTerminatedTexts",
-  "Token",
-  "URIC",
-  "TextString",
-  "TokenText",
-  "QuotedString",
-  "ShortInteger",
-  "LongInteger",
-  "UintVar",
-  "ConstrainedEncoding",
-  "ValueLength",
-  "NoValue",
-  "TextValue",
-  "IntegerValue",
-  "DateValue",
-  "DeltaSecondsValue",
-  "QValue",
-  "VersionValue",
-  "UriValue",
-  "TypeValue",
-  "Parameter",
-  "Header",
-  "WellKnownHeader",
-  "ApplicationHeader",
-  "FieldName",
-  "AcceptCharsetValue",
-  "WellKnownCharset",
-  "ContentTypeValue",
-  "ApplicationIdValue",
-
-  // Parser
-  "PduHelper",
-]);
deleted file mode 100644
--- a/dom/mobilemessage/gonk/mms_consts.js
+++ /dev/null
@@ -1,131 +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/. */
-
-// Encoded X-Mms-Message-Type values
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.30
-this.MMS_PDU_TYPE_SEND_REQ = 128;
-this.MMS_PDU_TYPE_SEND_CONF = 129;
-this.MMS_PDU_TYPE_NOTIFICATION_IND = 130;
-this.MMS_PDU_TYPE_NOTIFYRESP_IND = 131;
-this.MMS_PDU_TYPE_RETRIEVE_CONF = 132;
-this.MMS_PDU_TYPE_ACKNOWLEDGE_IND = 133;
-this.MMS_PDU_TYPE_DELIVERY_IND = 134;
-this.MMS_PDU_TYPE_READ_REC_IND = 135;
-this.MMS_PDU_TYPE_READ_ORIG_IND = 136;
-this.MMS_PDU_TYPE_FORWARD_REQ = 137;
-this.MMS_PDU_TYPE_FORWARD_CONF = 138;
-this.MMS_PDU_TYPE_MBOX_STORE_REQ = 139;
-this.MMS_PDU_TYPE_MBOX_STORE_CONF = 140;
-this.MMS_PDU_TYPE_MBOX_VIEW_REQ = 141;
-this.MMS_PDU_TYPE_MBOX_VIEW_CONF = 142;
-this.MMS_PDU_TYPE_MBOX_UPLOAD_REQ = 143;
-this.MMS_PDU_TYPE_MBOX_UPLOAD_CONF = 144;
-this.MMS_PDU_TYPE_MBOX_DELETE_REQ = 145;
-this.MMS_PDU_TYPE_MBOX_DELETE_CONF = 146;
-this.MMS_PDU_TYPE_MBOX_DESCR = 147;
-this.MMS_PDU_TYPE_DELETE_REQ = 148;
-this.MMS_PDU_TYPE_DELETE_CONF = 149;
-this.MMS_PDU_TYPE_CANCEL_REQ = 150;
-this.MMS_PDU_TYPE_CANCEL_CONF = 151;
-
-// MMS version
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.34
-this.MMS_VERSION_1_1 = (0x01 << 4) | 0x01;
-this.MMS_VERSION_1_3 = (0x01 << 4) | 0x03;
-
-// Common Status Values
-this.MMS_PDU_ERROR_OK                = 128;
-this.MMS_PDU_ERROR_TRANSIENT_FAILURE = 192;
-this.MMS_PDU_ERROR_PERMANENT_FAILURE = 224;
-
-// X-Mms-Response-Status values
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.48
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A Table 28, 29, 30
-//this.MMS_PDU_RESPONSE_ERROR_UNSPECIFIED                                 = 129; (obsolete)
-//this.MMS_PDU_RESPONSE_ERROR_SERVICE_DENIED                              = 130; (obsolete)
-//this.MMS_PDU_RESPONSE_ERROR_MESSAGE_FORMAT_CORRUPT                      = 131; (obsolete)
-//this.MMS_PDU_RESPONSE_ERROR_SENDING_ADDRESS_UNRESOLVED                  = 132; (obsolete)
-//this.MMS_PDU_RESPONSE_ERROR_MESSAGE_NOT_FOUND                           = 133; (obsolete)
-//this.MMS_PDU_RESPONSE_ERROR_NETWORK_PROBLEM                             = 134; (obsolete)
-//this.MMS_PDU_RESPONSE_ERROR_CONTENT_NOT_ACCEPTED                        = 135; (obsolete)
-this.MMS_PDU_RESPONSE_ERROR_UNSUPPORTED_MESSAGE                           = 136;
-this.MMS_PDU_RESPONSE_ERROR_TRANSIENT_SENDING_ADDRESS_UNRESOLVED          = 193;
-this.MMS_PDU_RESPONSE_ERROR_TRANSIENT_MESSAGE_NOT_FOUND                   = 194;
-this.MMS_PDU_RESPONSE_ERROR_TRANSIENT_NETWORK_PROBLEM                     = 195;
-this.MMS_PDU_RESPONSE_ERROR_TRANSIENT_PARTIAL_SUCCESS                     = 196;
-this.MMS_PDU_RESPONSE_ERROR_PERMANENT_SERVICE_DENIED                      = 225;
-this.MMS_PDU_RESPONSE_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT              = 226;
-this.MMS_PDU_RESPONSE_ERROR_PERMANENT_SENDING_ADDRESS_UNRESOLVED          = 227;
-this.MMS_PDU_RESPONSE_ERROR_PERMANENT_MESSAGE_NOT_FOUND                   = 228;
-this.MMS_PDU_RESPONSE_ERROR_PERMANENT_CONTENT_NOT_ACCEPTED                = 229;
-this.MMS_PDU_RESPONSE_ERROR_PERMANENT_REPLY_CHARGING_LIMITATIONS_NOT_MET  = 230;
-this.MMS_PDU_RESPONSE_ERROR_PERMANENT_REPLY_CHARGING_REQUEST_NOT_ACCEPTED = 231;
-this.MMS_PDU_RESPONSE_ERROR_PERMANENT_REPLY_CHARGING_FORWARDING_DENIED    = 232;
-this.MMS_PDU_RESPONSE_ERROR_PERMANENT_REPLY_CHARGING_NOT_SUPPORTED        = 233;
-this.MMS_PDU_RESPONSE_ERROR_PERMANENT_ADDRESS_HIDING_NOT_SUPPORTED        = 234;
-this.MMS_PDU_RESPONSE_ERROR_PERMANENT_LACK_OF_PREPAID                     = 235;
-
-// X-Mms-Retrieve-Status values
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.50
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A Table 31
-this.MMS_PDU_RETRIEVE_ERROR_TRANSIENT_MESSAGE_NOT_FOUND   = 193;
-this.MMS_PDU_RETRIEVE_ERROR_TRANSIENT_NETWORK_PROBLEM     = 194;
-this.MMS_PDU_RETRIEVE_ERROR_PERMANENT_SERVICE_DENIED      = 225;
-this.MMS_PDU_RETRIEVE_ERROR_PERMANENT_MESSAGE_NOT_FOUND   = 226;
-this.MMS_PDU_RETRIEVE_ERROR_PERMANENT_CONTENT_UNSUPPORTED = 227;
-
-// X-Mms-Store-Status values
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.58
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A Table 35
-this.MMS_PDU_STORE_ERROR_TRANSIENT_NETWORK_PROBLEM        = 193;
-this.MMS_PDU_STORE_ERROR_PERMANENT_SERVICE_DENIED         = 225;
-this.MMS_PDU_STORE_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT = 226;
-this.MMS_PDU_STORE_ERROR_PERMANENT_MESSAGE_NOT_FOUND      = 227;
-this.MMS_PDU_STORE_ERROR_PERMANENT_MMBOX_FULL             = 228;
-
-// X-Mms-Status values
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.54
-this.MMS_PDU_STATUS_EXPIRED       = 128;
-this.MMS_PDU_STATUS_RETRIEVED     = 129;
-this.MMS_PDU_STATUS_REJECTED      = 130;
-this.MMS_PDU_STATUS_DEFERRED      = 131;
-this.MMS_PDU_STATUS_UNRECOGNISED  = 132;
-this.MMS_PDU_STATUS_INDETERMINATE = 133;
-this.MMS_PDU_STATUS_FORWARDED     = 134;
-this.MMS_PDU_STATUS_UNREACHABLE   = 135;
-
-// X-Mms-Cancel-Status values
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.7
-this.MMS_PDU_CANCEL_STATUS_RECEIVED  = 128;
-this.MMS_PDU_CANCEL_STATUS_CORRUPTED = 129;
-
-// X-Mms-Sender-Visibility
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.52
-this.MMS_PDU_SENDER_VISIBILITY_HIDE = 128;
-this.MMS_PDU_SENDER_VISIBILITY_SHOW = 129;
-
-// X-Mms-Read-Status
-// @see OMA-TS-MMS_ENC-V1_3-20110913-A clause 7.3.38
-this.MMS_PDU_READ_STATUS_READ           = 128;
-this.MMS_PDU_READ_STATUS_DELETED_UNREAD = 129;
-
-// Maximum Values of MMS Parameters
-// @see OMA-TS-MMS_CONF-V1_3-20110511-C 10.2.5
-this.MMS_MAX_LENGTH_SUBJECT                = 40;
-this.MMS_MAX_LENGTH_RECIPIENT              = 312;
-this.MMS_MAX_TOTAL_RECIPIENTS              = 20;
-this.MMS_MAX_LENGTH_NAME_CONTENT_TYPE      = 40;
-this.MMS_MAX_LENGTH_MAILBOX_PORTION        = 256;
-
-this.DOM_READ_STATUS_NOT_APPLICABLE = "not-applicable";
-this.DOM_READ_STATUS_SUCCESS        = "success";
-this.DOM_READ_STATUS_PENDING        = "pending";
-this.DOM_READ_STATUS_ERROR          = "error";
-
-this.ALL_CONST_SYMBOLS = undefined; // We want ALL_CONST_SYMBOLS to be exported.
-this.ALL_CONST_SYMBOLS = Object.keys(this);
-
-// Allow this file to be imported via Components.utils.import().
-this.EXPORTED_SYMBOLS = ALL_CONST_SYMBOLS;
-
deleted file mode 100644
--- a/dom/mobilemessage/gonk/wap_consts.js
+++ /dev/null
@@ -1,22 +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";
-
-// WSP PDU Type Assignments
-// @see WAP-230-WSP-20010705-a Appendix A. Assigned Numbers.
-this.WSP_PDU_TYPE_PUSH = 0x06;
-
-// Registered WDP Port Numbers
-// @see WAP-259-WDP-20010614-a Appendix B. Port Number Definitions.
-this.WDP_PORT_PUSH = 2948;
-
-// Bearer Type Assignments
-// @see WAP-259-WDP-20010614-a Appendix C. Network Bearer Table.
-this.WDP_BEARER_GSM_SMS_GSM_MSISDN = 0x03;
-
-this.ALL_CONST_SYMBOLS = undefined; // We want ALL_CONST_SYMBOLS to be exported.
-this.ALL_CONST_SYMBOLS = Object.keys(this);
-
-this.EXPORTED_SYMBOLS = ALL_CONST_SYMBOLS;
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/moz.build
+++ /dev/null
@@ -1,29 +0,0 @@
-# -*- Mode: python; 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 += [
-    'nsIDeletedMessageInfo.idl',
-    'nsIMmsMessage.idl',
-    'nsIMmsService.idl',
-    'nsIMobileMessageCallback.idl',
-    'nsIMobileMessageCursorCallback.idl',
-    'nsIMobileMessageDatabaseService.idl',
-    'nsIMobileMessageService.idl',
-    'nsIMobileMessageThread.idl',
-    'nsISmsMessage.idl',
-    'nsISmsService.idl',
-    'nsIWapPushApplication.idl',
-]
-
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' and CONFIG['MOZ_B2G_RIL']:
-    XPIDL_SOURCES += [
-        'nsIGonkMobileMessageDatabaseService.idl',
-        'nsIGonkSmsService.idl',
-        'nsISmsMessenger.idl',
-    ]
-
-XPIDL_MODULE = 'dom_mobilemessage'
-
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIDeletedMessageInfo.idl
+++ /dev/null
@@ -1,17 +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/. */
-
-#include "nsISupports.idl"
-
-interface nsIVariant;
-
-[scriptable, builtinclass, uuid(174139d8-00e1-11e4-818a-f38357d90920)]
-interface nsIDeletedMessageInfo : nsISupports
-{
-   /* Array of messages ids in long if available. */
-   readonly attribute nsIVariant deletedMessageIds;
-
-   /* Array of thread ids in unsigned long long. if available */
-   readonly attribute nsIVariant deletedThreadIds;
-};
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIGonkMobileMessageDatabaseService.idl
+++ /dev/null
@@ -1,153 +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/. */
-
-#include "domstubs.idl"
-#include "nsISupports.idl"
-#include "nsIMobileMessageDatabaseService.idl"
-
-[scriptable, function, uuid(2ae081ac-8038-11e4-a472-1ba11eb89d79)]
-interface nsIGonkMobileMessageDatabaseCallback : nsISupports
-{
-  /**
-   * |aDomMessage|: the nsI{Mms,Sms}Message
-   */
-  void notify(in nsresult aRv, in nsISupports aDomMessage);
-};
-
-[scriptable, function, uuid(2f7a6fde-8038-11e4-9d93-5b9ffba492fb)]
-interface nsIGonkMobileMessageDatabaseRecordCallback : nsISupports
-{
-  /**
-   * |aMessageRecord| Object: the mobile-message database record
-   * |aDomMessage|: the nsI{Mms,Sms}Message. Noted, this value might be null.
-   */
-  void notify(in nsresult aRv, in jsval aMessageRecord, in nsISupports aDomMessage);
-};
-
-[scriptable, function, uuid(36f9732c-8038-11e4-b634-3f7e3df5232a)]
-interface nsIGonkMobileMessageDatabaseConcatenationCallback : nsISupports
-{
-  /**
-   * |aCompleteMessage|: jsval: the completely concatenated message. Noted, this value might be null.
-   */
-  void notify(in nsresult aRv, in jsval aCompleteMessage);
-};
-
-%{C++
-#define GONK_MOBILE_MESSAGE_DATABASE_SERVICE_CID \
-  { 0x7db05024, 0x8038, 0x11e4, { 0xb7, 0xfa, 0xa3, 0xed, 0xb6, 0xf1, 0xbf, 0x0c } }
-#define GONK_MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID \
-  "@mozilla.org/mobilemessage/gonkmobilemessagedatabaseservice;1"
-%}
-
-[scriptable, uuid(48a3c28a-8038-11e4-b7b9-0f2df5b53100)]
-interface nsIGonkMobileMessageDatabaseService : nsIMobileMessageDatabaseService
-{
-  /**
-   * |aMessage| Object: should contain the following properties for internal use:
-   *   - |type| DOMString: "sms" or "mms"
-   *   - |timestamp| Number: the timestamp of received message
-   *   - |iccId| DOMString: [optional] the ICC ID of the SIM for receiving
-   *                        message if available.
-   *
-   *   - If |type| == "sms", we also need:
-   *     - |messageClass| DOMString: the message class of received message
-   *     - |receiver| DOMString: the phone number of receiver
-   *     - |pid| Number: the TP-PID field of the SMS TPDU, default 0.
-   *     - |sender| DOMString: the phone number of sender
-   *
-   *   - If |type| == "mms", we also need:
-   *     - |delivery| DOMString: the delivery state of received message
-   *     - |deliveryStatus| DOMString: the delivery status of received message
-   *     - |receivers| DOMString Array: the phone numbers of receivers
-   *     - |phoneNumber| DOMString: [optional] my own phone number.
-   */
-  void saveReceivedMessage(in jsval aMessage,
-                [optional] in nsIGonkMobileMessageDatabaseCallback aCallback);
-
-  /**
-   * |aMessage| Object: should contain the following properties for internal use:
-   *   - |type| DOMString: "sms" or "mms"
-   *   - |sender| DOMString: the phone number of sender
-   *   - |timestamp| Number: the timestamp of sending message
-   *   - |deliveryStatusRequested| Bool: true when the delivery report is requested.
-   *   - |iccId| DOMString: the ICC ID of the SIM for sending message
-   *
-   *   - If |type| == "sms", we also need:
-   *     - |receiver| DOMString: the phone number of receiver
-   *
-   *   - If |type| == "mms", we also need:
-   *     - |receivers| DOMString Array: the phone numbers of receivers
-   */
-  void saveSendingMessage(in jsval aMessage,
-               [optional] in nsIGonkMobileMessageDatabaseCallback aCallback);
-
-  /**
-   * |aMessageId| Number: the message's DB record ID.
-   * |aReceiver| DOMString: the phone number of receiver (for MMS; can be null).
-   * |aDelivery| DOMString: the new delivery value to update (can be null).
-   * |aDeliveryStatus| DOMString: the new delivery status to update (can be null).
-   * |aEnvelopeId| DOMString: the "message-id" specified in the MMS PDU headers.
-   * |aCallback| nsIGonkMobileMessageDatabaseCallback: an optional callback.
-   */
-  void setMessageDeliveryByMessageId(in long aMessageId,
-                                     in DOMString aReceiver,
-                                     in DOMString aDelivery,
-                                     in DOMString aDeliveryStatus,
-                                     in DOMString aEnvelopeId,
-                          [optional] in nsIGonkMobileMessageDatabaseCallback aCallback);
-
-  /**
-   * |aEnvelopeId| DOMString: the "message-id" specified in the MMS PDU headers.
-   * |aReceiver| DOMString: the phone number of receiver (for MMS; can be null).
-   * |aDeliveryStatus| DOMString: the new delivery status to be updated (can be null).
-   * |aCallback| nsIGonkMobileMessageDatabaseCallback: an optional callback.
-   */
-  void setMessageDeliveryStatusByEnvelopeId(in DOMString aEnvelopeId,
-                                            in DOMString aReceiver,
-                                            in DOMString aDeliveryStatus,
-                                 [optional] in nsIGonkMobileMessageDatabaseCallback aCallback);
-
-  /**
-   * |aEnvelopeId| DOMString: the "message-id" specified in the MMS PDU headers.
-   * |aReceiver| DOMString: the phone number of receiver (for MMS; can be null).
-   * |aReadStatus| DOMString: the new read status to be updated.
-   * |aCallback| nsIGonkMobileMessageDatabaseCallback: an optional callback.
-   */
-  void setMessageReadStatusByEnvelopeId(in DOMString aEnvelopeId,
-                                        in DOMString aReceiver,
-                                        in DOMString aReadStatus,
-                             [optional] in nsIGonkMobileMessageDatabaseCallback aCallback);
-
-  /**
-   * |aMessageId| Number: the message's DB record ID.
-   * |aCallback| nsIGonkMobileMessageDatabaseRecordCallback: a callback which
-   *   takes result flag, message record and domMessage as parameters.
-   */
-  void getMessageRecordById(in long aMessageId,
-                            in nsIGonkMobileMessageDatabaseRecordCallback aCallback);
-
-  /**
-   * |aTransactionId| DOMString: the transaction ID of MMS PDU.
-   * |aCallback| nsIGonkMobileMessageDatabaseRecordCallback: a callback which
-   *   takes result flag and message record as parameters.
-   */
-  void getMessageRecordByTransactionId(in DOMString aTransactionId,
-                                       in nsIGonkMobileMessageDatabaseRecordCallback aCallback);
-
-  /**
-   * |aCrError| nsresult: the NS_ERROR defined in Components.results.
-   *
-   * @returns the error code defined in nsIMobileMessageCallback
-   */
-  jsval translateCrErrorToMessageCallbackError(in nsresult aCrError);
-
-  /**
-   * |aSmsSegment| jsval: Decoded Single SMS PDU.
-   * |aCallback| nsIGonkMobileMessageDatabaseConcatenationCallback: a callback which
-   *   takes result flag, and complete mesage as parameters.
-   */
-  void saveSmsSegment(in jsval aSmsSegment,
-                      in nsIGonkMobileMessageDatabaseConcatenationCallback aCallback);
-};
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIGonkSmsService.idl
+++ /dev/null
@@ -1,95 +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/. */
-
-#include "domstubs.idl"
-#include "nsISmsService.idl"
-
-%{C++
-#define GONK_SMSSERVICE_CONTRACTID \
-        "@mozilla.org/sms/gonksmsservice;1"
-%}
-
-[scriptable, uuid(76681431-8261-4540-bab8-24ef3866e8b6)]
-interface nsIGonkSmsService : nsISmsService
-{
-  const unsigned short SMS_MESSAGE_ENCODING_7BITS_ALPHABET = 0x00;
-  const unsigned short SMS_MESSAGE_ENCODING_8BITS_ALPHABET = 0x04;
-  const unsigned short SMS_MESSAGE_ENCODING_16BITS_ALPHABET = 0x08;
-
-  const unsigned long SMS_APPLICATION_PORT_INVALID = 0xFFFFFFFF;
-
-  /**
-   * Called when a short message has been received by the network.
-   *
-   * @param aServiceId
-   *        The ID of the service where this message is received from.
-   * @param aSMSC
-   *        SMS Center address.
-   * @param aSentTimestamp
-   *        The time stamp when message is arrived to SMSC.
-   * @param aSender
-   *        The sender's address of this message.
-   * @param aPid
-   *        Protocol Identifier, See TS 23.040, subcluase 9.2.3.9.
-   *        Set to 0 if invalid.
-   * @param aEncoding
-   *        The encoding of message body.
-   *        SMS_MESSAGE_ENCODING_*.
-   * @param aMessageClass
-   *        A predefined constant of nsISmsService.MESSAGE_CLASS_TYPE_*.
-   * @param aLanguage
-   *        ISO-639-1 language code for this message. Null if unspecified.
-   * @param aSegmentRef, aSegmentSeq, aSegmentMaxSeq
-   *        Concatenation info. See TS 23.040, subclause 9.2.3.24.1.
-   *        All set to 1 if no need for concatenatenation.
-   * @param aOriginatorPort, aDestinationPort
-   *        Application Port Addressing. See TS 23.040 subclause 9.2.3.24.3~4.
-   *        All set to 1 if no need for concatenatenation.
-   * @param aMwiPresent
-   *        True if MWI is presented in this message.
-   * @param aMwiDiscard
-   *        True if MWI has to be discarded after received.
-   * @param aMwiMsgCount
-   *        The number of messages waiting in the voicemail server.
-   *        -1 if number is unknown from the decoded MWI.
-   * @param aMwiActive
-   *        True if there are messages waiting in the voicemail server.
-   * @param aCdmaMessageType
-   *        CDMA SMS Message Type, as defined in 3GPP2 C.S0015-A v2.0, Table 3.4-1
-   *        Set to 0 if invalid.
-   * @param aCdmaTeleservice
-   *        SMS Teleservice Identitifier, as defined in 3GPP2 N.S0005, Table 175.
-   *        Set to 0 if invalid.
-   * @param aCdmaServiceCategory
-   *        CDMA Service Category, 3GPP2 C.R1001-D v2.0, 9.3 Service Category.
-   *        Set to 0 if invalid.
-   * @param aBody
-   *        Text message body.
-   * @param aData
-   *        Binary message body.
-   */
-  void notifyMessageReceived(in unsigned long aServiceId,
-                             in DOMString aSMSC,
-                             in DOMTimeStamp aSentTimestamp,
-                             in DOMString aSender,
-                             in unsigned short aPid,
-                             in unsigned short aEncoding,
-                             in unsigned long aMessageClass,
-                             in DOMString aLanguage,
-                             in unsigned short aSegmentRef,
-                             in unsigned short aSegmentSeq,
-                             in unsigned short aSegmentMaxSeq,
-                             in unsigned long aOriginatorPort,
-                             in unsigned long aDestinationPort,
-                             in boolean aMwiPresent,
-                             in boolean aMwiDiscard,
-                             in short aMwiMsgCount,
-                             in boolean aMwiActive,
-                             in unsigned short aCdmaMessageType,
-                             in unsigned long aCdmaTeleservice,
-                             in unsigned long aCdmaServiceCategory,
-                             in DOMString aBody,
-                             [array, size_is(aDataLength)] in octet aData,
-                             in uint32_t aDataLength);
-};
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIMmsMessage.idl
+++ /dev/null
@@ -1,60 +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/. */
-
-#include "domstubs.idl"
-#include "nsISupports.idl"
-
-interface nsIDOMBlob;
-
-[scriptable, builtinclass, uuid(cd2ff09a-8853-11e5-ac49-0f655992cef6)]
-interface nsIMmsMessage : nsISupports
-{
-  /**
-   * |type| is always "mms".
-   */
-  readonly attribute DOMString type;
-
-  readonly attribute long      id;
-
-  readonly attribute unsigned long long threadId;
-
-  /**
-   * Integrated Circuit Card Identifier.
-   *
-   * Will be null if ICC is not available.
-   */
-  readonly attribute DOMString iccId;
-
-  /**
-   * Should be "not-downloaded", "received", "sending", "sent" or "error".
-   */
-  readonly attribute DOMString delivery;
-
-  [implicit_jscontext]
-  readonly attribute jsval     deliveryInfo;   // MmsDeliveryInfo[]
-
-  readonly attribute DOMString sender;
-
-  [implicit_jscontext]
-  readonly attribute jsval     receivers;      // DOMString[]
-
-  readonly attribute DOMTimeStamp timestamp;
-
-  readonly attribute DOMTimeStamp sentTimestamp;
-                                  // 0 if not available (e.g., |delivery| =
-                                  // "sending").
-
-  readonly attribute boolean   read;
-  readonly attribute DOMString subject;
-  readonly attribute DOMString smil;
-
-  [implicit_jscontext]
-  readonly attribute jsval     attachments;    // MmsAttachment[]
-
-  readonly attribute DOMTimeStamp expiryDate;  // Expiry date for an MMS to be
-                                               // manually downloaded.
-
-  // Request read report from sender or not.
-  readonly attribute boolean   readReportRequested;
-};
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIMmsService.idl
+++ /dev/null
@@ -1,38 +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/. */
-
-#include "nsISupports.idl"
-
-interface nsIMobileMessageCallback;
-interface nsIDOMBlob;
-
-%{C++
-#define MMS_SERVICE_CID { 0x06d9124b, 0x80e0, 0x40ed, \
-  { 0x98, 0x71, 0x4d, 0x23, 0x4a, 0x0f, 0xd4, 0x31 } }
-#define MMS_SERVICE_CONTRACTID "@mozilla.org/mms/mmsservice;1"
-%}
-
-[scriptable, uuid(543278b3-d926-4c65-84b8-b49ad7a17d21)]
-interface nsIMmsService : nsISupports
-{
-  readonly attribute unsigned long mmsDefaultServiceId;
-
-  void send(in unsigned long serviceId,
-            in jsval parameters /* MmsParameters */,
-            in nsIMobileMessageCallback request);
-
-  void retrieve(in long id,
-                in nsIMobileMessageCallback request);
-
-  void sendReadReport(in DOMString messageID,
-                      in DOMString toAddress,
-                      in DOMString iccId);
-};
-
-%{C++
-template<typename T> struct already_AddRefed;
-
-already_AddRefed<nsIMmsService>
-NS_CreateMmsService();
-%}
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIMobileMessageCallback.idl
+++ /dev/null
@@ -1,67 +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/. */
-
-#include "nsISupports.idl"
-
-[scriptable, uuid(19b24f93-7c02-4acf-addd-2f53bbb4e3fd)]
-interface nsIMobileMessageCallback : nsISupports
-{
-  /**
-   * All SMS related errors.
-   * Make sure to keep this list in sync with the list in:
-   * mobile/android/base/GeckoSmsManager.java
-   */
-  const unsigned short SUCCESS_NO_ERROR          = 0;
-  const unsigned short NO_SIGNAL_ERROR           = 1;
-  const unsigned short NOT_FOUND_ERROR           = 2;
-  const unsigned short UNKNOWN_ERROR             = 3;
-  const unsigned short INTERNAL_ERROR            = 4;
-  const unsigned short NO_SIM_CARD_ERROR         = 5;
-  const unsigned short RADIO_DISABLED_ERROR      = 6;
-  const unsigned short INVALID_ADDRESS_ERROR     = 7;
-  const unsigned short FDN_CHECK_ERROR           = 8;
-  const unsigned short NON_ACTIVE_SIM_CARD_ERROR = 9;
-  const unsigned short STORAGE_FULL_ERROR        = 10;
-  const unsigned short SIM_NOT_MATCHED_ERROR     = 11;
-  const unsigned short NETWORK_PROBLEMS_ERROR    = 12;
-  const unsigned short GENERAL_PROBLEMS_ERROR    = 13;
-  const unsigned short SERVICE_NOT_AVAILABLE_ERROR          = 14;
-  const unsigned short MESSAGE_TOO_LONG_FOR_NETWORK_ERROR   = 15;
-  const unsigned short SERVICE_NOT_SUPPORTED_ERROR          = 16;
-  const unsigned short RETRY_REQUIRED_ERROR      = 17;
-
-  /**
-   * |message| can be nsI{Mms,Sms}Message.
-   */
-  void notifyMessageSent(in nsISupports message);
-  void notifySendMessageFailed(in long error, in nsISupports message);
-
-  /**
-   * |message| can be nsI{Mms,Sms}Message.
-   */
-  void notifyMessageGot(in nsISupports message);
-  void notifyGetMessageFailed(in long error);
-
-  void notifyMessageDeleted([array, size_is(count)] in boolean deleted,
-                            in uint32_t count);
-  void notifyDeleteMessageFailed(in long error);
-
-  void notifyMessageMarkedRead(in boolean read);
-  void notifyMarkMessageReadFailed(in long error);
-
-  void notifySegmentInfoForTextGot(in long segments,
-                                   in long charsPerSegment,
-                                   in long charsAvailableInLastSegment);
-  void notifyGetSegmentInfoForTextFailed(in long error);
-
-  /**
-   *  SMSC Address get/set result
-   */
-  void notifyGetSmscAddress(in DOMString aSmscAddress,
-                            in unsigned long aTypeOfNumber,
-                            in unsigned long aNumberPlanIdentification);
-  void notifyGetSmscAddressFailed(in long error);
-  void notifySetSmscAddress();
-  void notifySetSmscAddressFailed(in long error);
-};
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIMobileMessageCursorCallback.idl
+++ /dev/null
@@ -1,14 +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/. */
-
-#include "nsISupports.idl"
-
-[scriptable, builtinclass, uuid(134a6958-543b-46e2-b419-4631a2314164)]
-interface nsIMobileMessageCursorCallback : nsISupports
-{
-  void notifyCursorError(in long error);
-  void notifyCursorResult([array, size_is(size)] in nsISupports results,
-                          in uint32_t size);
-  void notifyCursorDone();
-};
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIMobileMessageDatabaseService.idl
+++ /dev/null
@@ -1,56 +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/. */
-
-#include "nsISupports.idl"
-
-%{C++
-#define MOBILE_MESSAGE_DATABASE_SERVICE_CID \
-{ 0x0d84b9c2, 0x8f76, 0x4ba4,    \
-{ 0xa5, 0xcd, 0xdb, 0xfb, 0x01, 0xdf, 0xda, 0x99 } }
-#define MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID "@mozilla.org/mobilemessage/mobilemessagedatabaseservice;1"
-%}
-
-interface nsICursorContinueCallback;
-interface nsIMobileMessageCallback;
-interface nsIMobileMessageCursorCallback;
-
-[scriptable, uuid(18672be2-c185-4f9c-8af6-2e6ea004de73)]
-interface nsIMobileMessageDatabaseService : nsISupports
-{
-  [binaryname(GetMessageMoz)]
-  void getMessage(in long messageId,
-                  in nsIMobileMessageCallback request);
-
-  void deleteMessage([array, size_is(count)] in long messageIds,
-                     in uint32_t count,
-                     in nsIMobileMessageCallback request);
-
-  nsICursorContinueCallback createMessageCursor(in boolean hasStartDate,
-                                                in unsigned long long startDate,
-                                                in boolean hasEndDate,
-                                                in unsigned long long endDate,
-                                                [array, size_is(numbersCount)] in wstring numbers,
-                                                in uint32_t numbersCount,
-                                                [Null(Null), Undefined(Null)] in DOMString delivery,
-                                                in boolean hasRead,
-                                                in boolean read,
-                                                in boolean hasThreadId,
-                                                in unsigned long long threadId,
-                                                in boolean reverse,
-                                                in nsIMobileMessageCursorCallback callback);
-
-  void markMessageRead(in long messageId,
-                       in boolean value,
-                       in boolean sendReadReport,
-                       in nsIMobileMessageCallback request);
-
-  nsICursorContinueCallback createThreadCursor(in nsIMobileMessageCursorCallback callback);
-};
-
-%{C++
-template<typename T> struct already_AddRefed;
-
-already_AddRefed<nsIMobileMessageDatabaseService>
-NS_CreateMobileMessageDatabaseService();
-%}
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIMobileMessageService.idl
+++ /dev/null
@@ -1,73 +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/. */
-
-#include "nsISupports.idl"
-
-interface nsIDeletedMessageInfo;
-interface nsISmsMessage;
-interface nsIMmsMessage;
-interface nsIMobileMessageThread;
-
-%{C++
-#define MOBILE_MESSAGE_SERVICE_CID { 0x829c1dd6, 0x0466, 0x4591, { 0x83, 0x6f, 0xb8, 0xf6, 0xfd, 0x1f, 0x7b, 0xa5 } }
-#define MOBILE_MESSAGE_SERVICE_CONTRACTID "@mozilla.org/mobilemessage/mobilemessageservice;1"
-%}
-
-[scriptable, builtinclass, uuid(15267554-8854-11e5-8947-8f2150f4eabc)]
-interface nsIMobileMessageService : nsISupports
-{
-  [implicit_jscontext]
-  nsISmsMessage createSmsMessage(in long               id,
-                                 in unsigned long long threadId,
-                                 in DOMString          iccId,
-                                 in DOMString          delivery,
-                                 in DOMString          deliveryStatus,
-                                 in DOMString          sender,
-                                 in DOMString          receiver,
-                                 in DOMString          body,
-                                 in DOMString          messageClass,
-                                 in unsigned long long timestamp,
-                                 in unsigned long long sentTimestamp,
-                                 in unsigned long long deliveryTimestamp,
-                                 in bool               read);
-
-  [implicit_jscontext]
-  nsIMmsMessage createMmsMessage(in long               id,
-                                 in unsigned long long threadId,
-                                 in DOMString          iccId,
-                                 in DOMString          delivery,
-                                 in jsval              deliveryInfo,
-                                 in DOMString          sender,
-                                 in jsval              receivers,
-                                 in unsigned long long timestamp,
-                                 in unsigned long long sentTimestamp,
-                                 in boolean            read,
-                                 in DOMString          subject,
-                                 in DOMString          smil,
-                                 in jsval              attachments,
-                                 in unsigned long long expiryDate,
-                                 in boolean            readReportRequested);
-
-  [implicit_jscontext]
-  nsIMobileMessageThread createThread(in unsigned long long id,
-                                      in jsval              participants,
-                                      in unsigned long long timestamp,
-                                      in DOMString          lastMessageSubject,
-                                      in DOMString          body,
-                                      in unsigned long long unreadCount,
-                                      in DOMString          aLastMessageType);
-
-  nsIDeletedMessageInfo createDeletedMessageInfo(
-    [array, size_is(msgCount)] in long messageIds,
-    in uint32_t msgCount,
-    [array, size_is(threadCount)] in unsigned long long threadIds,
-    in uint32_t threadCount);
-};
-
-%{C++
-template<typename T> struct already_AddRefed;
-
-already_AddRefed<nsIMobileMessageService>
-NS_CreateMobileMessageService();
-%}
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIMobileMessageThread.idl
+++ /dev/null
@@ -1,32 +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/. */
-
-#include "domstubs.idl"
-#include "nsISupports.idl"
-
-[scriptable, builtinclass, uuid(dd6794cc-8853-11e5-89b4-278852073d45)]
-interface nsIMobileMessageThread : nsISupports
-{
-  // Unique identity of the thread.
-  readonly attribute unsigned long long id;
-
-  // Last (MMS) message subject.
-  readonly attribute DOMString          lastMessageSubject;
-
-  // Message body of the last message in the thread.
-  readonly attribute DOMString          body;
-
-  // Total unread messages in the thread.
-  readonly attribute unsigned long long unreadCount;
-
-  // Participant addresses of the thread.
-  [implicit_jscontext]
-  readonly attribute jsval              participants; // DOMString[]
-
-  // Timestamp of the last message in the thread.
-  readonly attribute DOMTimeStamp       timestamp;
-
-  // Message type of the last message in the thread.
-  readonly attribute DOMString          lastMessageType;
-};
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsISmsMessage.idl
+++ /dev/null
@@ -1,64 +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/. */
-
-#include "domstubs.idl"
-#include "nsISupports.idl"
-
-[scriptable, builtinclass, uuid(d7670dfa-8853-11e5-8e3e-43cd171289cc)]
-interface nsISmsMessage : nsISupports
-{
-  /**
-   * |type| is always "sms".
-   */
-  readonly attribute DOMString type;
-
-  readonly attribute long      id;
-
-  readonly attribute unsigned long long threadId;
-
-  /**
-   * Integrated Circuit Card Identifier.
-   *
-   * Will be null if ICC is not available.
-   */
-  readonly attribute DOMString iccId;
-
-  /**
-   * Should be "received", "sending", "sent" or "error".
-   */
-  readonly attribute DOMString delivery;
-
-  /**
-   * Possible delivery status values for above delivery states are:
-   *
-   * "received": "success"
-   * "sending" : "pending", or "not-applicable" if the message was sent without
-   *             status report requisition.
-   * "sent"    : "pending", "success", "error", or "not-applicable"
-   *             if the message was sent without status report requisition.
-   * "error"   : "error"
-   */
-  readonly attribute DOMString deliveryStatus;
-
-  readonly attribute DOMString sender;
-  readonly attribute DOMString receiver;
-  readonly attribute DOMString body;
-
-  /**
-   * Should be "normal", "class-0", "class-1", "class-2" or "class-3".
-   */
-  readonly attribute DOMString messageClass;
-
-  readonly attribute DOMTimeStamp timestamp;
-
-  readonly attribute DOMTimeStamp sentTimestamp;
-                                  // 0 if not available (e.g., |delivery| =
-                                  // "sending").
-
-  readonly attribute DOMTimeStamp deliveryTimestamp;
-                                  // 0 if not available (e.g., |delivery| =
-                                  // "received" or not yet delivered).
-
-  readonly attribute boolean   read;
-};
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsISmsMessenger.idl
+++ /dev/null
@@ -1,74 +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/. */
-
-#include "domstubs.idl"
-#include "nsISupports.idl"
-
-[scriptable, uuid(3be7c6ac-e27d-11e4-b6da-7bbe0e4cd4ec)]
-interface nsISmsMessenger : nsISupports
-{
-  /* 'sms-received' system message */
-  const unsigned short NOTIFICATION_TYPE_RECEIVED = 0;
-  /* 'sms-sent' system message */
-  const unsigned short NOTIFICATION_TYPE_SENT = 1;
-  /* 'sms-delivery-success' system message */
-  const unsigned short NOTIFICATION_TYPE_DELIVERY_SUCCESS = 2;
-  /* 'sms-failed' system message */
-  const unsigned short NOTIFICATION_TYPE_SENT_FAILED = 3;
-  /* 'sms-delivery-error' system message */
-  const unsigned short NOTIFICATION_TYPE_DELIVERY_ERROR = 4;
-
-  /**
-   * To broadcast system messages of 'sms-received', 'sms-delivery-success',
-   * 'sms-sent', 'sms-failed' and 'sms-delivery-error'.
-   *
-   * Note: Except aNotificationType, all parameters are the attributes of the
-   * nsISmsMessage generated by nsIMobileMessageService.createSmsMessage().
-   *
-   * @param aNotificationType
-   *        A predefined constant of nsISmsMessenger.NOTIFICATION_TYPE_*.
-   * @param aId
-   *        The unique identity of this message.
-   * @param aThreadId
-   *        The unique identity of the thread this message belongs to.
-   * @param aIccId
-   *        Integrated Circuit Card Identifier. null if ICC is not available.
-   * @param aDelivery
-   *        A predefined constant of nsISmsService.DELIVERY_TYPE_*.
-   * @param aDeliveryStatus
-   *        A predefined constant of nsISmsService.DELIVERY_STATUS_TYPE_*.
-   * @param aSender
-   *        Sender address. null if not available.
-   * @param aReceiver
-   *        Receiver address. null if not available.
-   * @param aBody
-   *        Text message body. null if not available.
-   * @param aMessageClass
-   *        A predefined constant of nsISmsService.MESSAGE_CLASS_TYPE_*.
-   * @param aTimestamp
-   *        The device system time when creating or saving this message.
-   * @param aSentTimestamp
-   *        The SMSC timestamp of the incoming message.
-   *        0 if not available.
-   * @param aDeliveryTimestamp
-   *        The delivery timestamp to the remote party of the sent message.
-   *        0 if not available.
-   * @param aRead
-   *        True if the message was read.
-   */
-  void notifySms(in unsigned short aNotificationType,
-                 in long aId,
-                 in unsigned long long aThreadId,
-                 in DOMString aIccId,
-                 in unsigned long aDelivery,
-                 in unsigned long aDeliveryStatus,
-                 in DOMString aSender,
-                 in DOMString aReceiver,
-                 in DOMString aBody,
-                 in unsigned long aMessageClass,
-                 in DOMTimeStamp aTimestamp,
-                 in DOMTimeStamp aSentTimestamp,
-                 in DOMTimeStamp aDeliveryTimestamp,
-                 in boolean aRead);
-};
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsISmsService.idl
+++ /dev/null
@@ -1,178 +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/. */
-
-#include "nsISupports.idl"
-
-interface nsIMobileMessageCallback;
-
-%{C++
-#define SMS_SERVICE_CID { 0xbada3cb8, 0xa568, 0x4dff, { 0xb5, 0x43, 0x52, 0xbb, 0xb3, 0x14, 0x31, 0x21 } }
-#define SMS_SERVICE_CONTRACTID "@mozilla.org/sms/smsservice;1"
-%}
-
-[scriptable, uuid(c8ca5f06-ad76-44b0-a324-9e2910fd37da)]
-interface nsISmsService : nsISupports
-{
-  /**
-   * Constant definitions of predefined GSM Message Class
-   * See 3GPP TS 23.038 clause 4 SMS Data Coding Scheme
-   */
-  const unsigned short MESSAGE_CLASS_TYPE_CLASS_0 = 0;
-  const unsigned short MESSAGE_CLASS_TYPE_CLASS_1 = 1;
-  const unsigned short MESSAGE_CLASS_TYPE_CLASS_2 = 2;
-  const unsigned short MESSAGE_CLASS_TYPE_CLASS_3 = 3;
-  const unsigned short MESSAGE_CLASS_TYPE_NORMAL  = 6;
-
-  /**
-   * Constant definitions of SMS Delivery
-   */
-  const unsigned short DELIVERY_TYPE_RECEIVED = 0;
-  const unsigned short DELIVERY_TYPE_SENDING  = 1;
-  const unsigned short DELIVERY_TYPE_SENT     = 2;
-  const unsigned short DELIVERY_TYPE_ERROR    = 3;
-
-  /**
-   * Constant definitions of SMS Delivery Status
-   */
-  const unsigned short DELIVERY_STATUS_TYPE_NOT_APPLICABLE = 0;
-  const unsigned short DELIVERY_STATUS_TYPE_SUCCESS        = 1;
-  const unsigned short DELIVERY_STATUS_TYPE_PENDING        = 2;
-  const unsigned short DELIVERY_STATUS_TYPE_ERROR          = 3;
-
-  /**
-   * Constant definitions of SM-RP type of number as defined in
-   * |Table 10.5.118: Called party BCD number| of 3GPP TS 24.008.
-   */
-  const unsigned short TYPE_OF_NUMBER_UNKNOWN                     = 0;
-  const unsigned short TYPE_OF_NUMBER_INTERNATIONAL               = 1;
-  const unsigned short TYPE_OF_NUMBER_NATIONAL                    = 2;
-  const unsigned short TYPE_OF_NUMBER_NETWORK_SPECIFIC            = 3;
-  const unsigned short TYPE_OF_NUMBER_DEDICATED_ACCESS_SHORT_CODE = 4;
-
-  /**
-   * Constant definitions of SM-RP number plan identification as defined in
-   * |Table 10.5.118: Called party BCD number| of 3GPP TS 24.008. These values
-   * do not represent the actual protocol values defined in the 3GPP standard,
-   * but rather the corresponding enum values of NumberPlanIdentification in
-   * MozMobileMessageManager.
-   */
-  const unsigned short NUMBER_PLAN_IDENTIFICATION_UNKNOWN  = 0;
-  const unsigned short NUMBER_PLAN_IDENTIFICATION_ISDN     = 1;
-  const unsigned short NUMBER_PLAN_IDENTIFICATION_DATA     = 2;
-  const unsigned short NUMBER_PLAN_IDENTIFICATION_TELEX    = 3;
-  const unsigned short NUMBER_PLAN_IDENTIFICATION_NATIONAL = 4;
-  const unsigned short NUMBER_PLAN_IDENTIFICATION_PRIVATE  = 5;
-
-  /**
-   * The default RIL service ID used for SMS.
-   */
-  readonly attribute unsigned long smsDefaultServiceId;
-
-  /**
-   * Get the information necessary to create a multi-part SMS for a given text.
-   *
-   * @param text
-   *        The text message content.
-   * @param request
-   *        The callback object to use. It invokes
-   *        |notifySegmentInfoForTextGot| on success, or
-   *        |notifyGetSegmentInfoForTextFailed| on failure.
-   */
-  void getSegmentInfoForText(in DOMString text,
-                             in nsIMobileMessageCallback request);
-
-  /**
-   * Send a SMS.
-   *
-   * @param serviceId
-   *        The ID of RIL service to use.
-   * @param number
-   *        Destination number in string.
-   * @param message
-   *        The text message content.
-   * @param silent
-   *        |true| to send a silent message. It's used to make a SMS based
-   *        authentication for some services such as mobile billing.
-   * @param request
-   *        The callback object to use. It invokes |notifyMessageSent| on
-   *        success, or |notifySendMessageFailed| on failure.
-   * @throws NS_ERROR_INVALID_ARG
-   *         If |serviceId| exceeds the max value of available IDs.
-   */
-  void send(in unsigned long serviceId,
-            in DOMString number,
-            in DOMString message,
-            in boolean silent,
-            in nsIMobileMessageCallback request);
-
-  /**
-   * Add a number to the list of silent message originators. When receiving a
-   * SMS sent from one of the numbers in the list, |SmsService| will notify
-   * observers through the topic "silent-sms-received".
-   *
-   * It's used when a SMS based authentication has been initiated and the client
-   * is waiting for an incoming silent message containing the authentication
-   * result.
-   *
-   * @param number
-   *        Originator number in string.
-   * @throw NS_ERROR_UNEXPECTED
-   *        If the given number has already been added before.
-   */
-  void addSilentNumber(in DOMString number);
-
-  /**
-   * Remove a number from the silent message originator list.
-   *
-   * @param number
-   *        Originator number in string.
-   * @throws NS_ERROR_INVALID_ARG
-   *         If the number doesn't exist in the list.
-   */
-  void removeSilentNumber(in DOMString number);
-
-  /**
-   * Get the short message service center address of given |serviceId|.
-   *
-   * @param serviceId
-   *        The ID of RIL service to use.
-   * @param request
-   *        The callback object to use. It invokes |notifyGetSmscAddress| on
-   *        success, or |notifyGetSmscAddressFailed| on failure.
-   * @throws NS_ERROR_INVALID_ARG
-   *         If |serviceId| exceeds the max value of available IDs.
-   */
-  void getSmscAddress(in unsigned long serviceId,
-                      in nsIMobileMessageCallback request);
-
-  /**
-   * Set the short message service center address of given |serviceId|.
-   *
-   * @param serviceId
-   *        The ID of RIL service to use.
-   * @param number
-   *        Number part of the SMSC address.
-   * @param typeOfNumber
-   *        Type of number of the SMSC address.
-   * @param numberPlanIdentification
-   *        Number plan identification of the SMSC address.
-   * @param request
-   *        The callback object to use. It invokes |notifySetSmscAddress| on
-   *        success, or |notifySetSmscAddressFailed| on failure.
-   * @throws NS_ERROR_INVALID_ARG
-   *         If |serviceId| exceeds the max value of available IDs.
-   */
-  void setSmscAddress(in unsigned long serviceId,
-                      in DOMString number,
-                      in unsigned long typeOfNumber,
-                      in unsigned long numberPlanIdentification,
-                      in nsIMobileMessageCallback request);
-};
-
-%{C++
-template<typename T> struct already_AddRefed;
-
-already_AddRefed<nsISmsService>
-NS_CreateSmsService();
-%}
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIWapPushApplication.idl
+++ /dev/null
@@ -1,30 +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/. */
-
-#include "nsISupports.idl"
-
-/**
- * Handle WAP Push notifications.
- */
-[scriptable, uuid(fd6f7f6b-a67e-4892-930d-fca864df8fe7)]
-interface nsIWapPushApplication : nsISupports
-{
-  /**
-   * Receive WAP Push message.
-   *
-   * @param aData
-   *        An array containing raw PDU data.
-   * @param aLength
-   *        Length of aData.
-   * @param aOffset
-   *        Start offset of aData containing message body of the Push PDU.
-   * @param options
-   *        An object containing various attributes from lower transport layer.
-   */
-  void receiveWapPush([array, size_is(aLength)] in octet aData,
-                      in unsigned long                   aLength,
-                      in unsigned long                   aOffset,
-                      in jsval                           aOptions);
-};
-
deleted file mode 100644
--- a/dom/mobilemessage/ipc/PMobileMessageCursor.ipdl
+++ /dev/null
@@ -1,33 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* vim: set 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/. */
-
-include protocol PSms;
-include protocol PBlob;
-include SmsTypes;
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-protocol PMobileMessageCursor
-{
-  manager PSms;
-
-child:
-  async NotifyResult(MobileMessageCursorData aData);
-
-  /**
-   * Sent when the asynchronous cursor request has completed.
-   */
-  async __delete__(int32_t aError);
-
-parent:
-  async Continue();
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/ipc/PSms.ipdl
+++ /dev/null
@@ -1,158 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set sw=2 ts=8 et ft=cpp : */
-/* 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 protocol PContent;
-include protocol PSmsRequest;
-include protocol PMobileMessageCursor;
-include protocol PBlob;
-include SmsTypes;
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-struct SendMmsMessageRequest
-{
-  uint32_t serviceId;
-  nsString[] receivers;
-  nsString subject;
-  nsString smil;
-  MmsAttachmentData[] attachments;
-};
-
-struct SendSmsMessageRequest
-{
-  uint32_t serviceId;
-  nsString number;
-  nsString message;
-  bool     silent;
-};
-
-union SendMessageRequest
-{
-  SendMmsMessageRequest;
-  SendSmsMessageRequest;
-};
-
-struct RetrieveMessageRequest
-{
-  int32_t messageId;
-};
-
-struct GetMessageRequest
-{
-  int32_t messageId;
-};
-
-struct DeleteMessageRequest
-{
-  int32_t[] messageIds;
-};
-
-struct CreateMessageCursorRequest
-{
-  SmsFilterData filter;
-  bool reverse;
-};
-
-struct MarkMessageReadRequest
-{
-  int32_t messageId;
-  bool value;
-  bool sendReadReport;
-};
-
-struct GetSegmentInfoForTextRequest
-{
-  nsString text;
-};
-
-struct CreateThreadCursorRequest
-{
-};
-
-struct GetSmscAddressRequest
-{
-  uint32_t serviceId;
-};
-
-struct SetSmscAddressRequest
-{
-  uint32_t serviceId;
-  nsString number;
-  uint32_t typeOfNumber;
-  uint32_t numberPlanIdentification;
-};
-
-union IPCSmsRequest
-{
-  SendMessageRequest;
-  RetrieveMessageRequest;
-  GetMessageRequest;
-  DeleteMessageRequest;
-  MarkMessageReadRequest;
-  GetSegmentInfoForTextRequest;
-  GetSmscAddressRequest;
-  SetSmscAddressRequest;
-};
-
-union IPCMobileMessageCursor
-{
-  CreateMessageCursorRequest;
-  CreateThreadCursorRequest;
-};
-
-sync protocol PSms {
-    manager PContent;
-    manages PSmsRequest;
-    manages PMobileMessageCursor;
-
-child:
-  async NotifyReceivedMessage(MobileMessageData aMessageData);
-
-  async NotifyRetrievingMessage(MobileMessageData aMessageData);
-
-  async NotifySendingMessage(MobileMessageData aMessageData);
-
-  async NotifySentMessage(MobileMessageData aMessageData);
-
-  async NotifyFailedMessage(MobileMessageData aMessageData);
-
-  async NotifyDeliverySuccessMessage(MobileMessageData aMessageData);
-
-  async NotifyDeliveryErrorMessage(MobileMessageData aMessageData);
-
-  async NotifyReceivedSilentMessage(MobileMessageData aMessageData);
-
-  async NotifyReadSuccessMessage(MobileMessageData aMessageData);
-
-  async NotifyReadErrorMessage(MobileMessageData aMessageData);
-
-  async NotifyDeletedMessageInfo(DeletedMessageInfoData aDeletedInfo);
-
-parent:
-  /**
-   * Sent when the child no longer needs to use sms.
-   */
-  async __delete__();
-
-  /**
-   * Sent when the child makes an asynchronous request to the parent.
-   */
-  async PSmsRequest(IPCSmsRequest request);
-
-  /**
-   * Sent when the child makes an asynchronous cursor to the parent.
-   */
-  async PMobileMessageCursor(IPCMobileMessageCursor request);
-
-  async AddSilentNumber(nsString aNumber);
-  async RemoveSilentNumber(nsString aNumber);
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/ipc/PSmsRequest.ipdl
+++ /dev/null
@@ -1,128 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* vim: set 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/. */
-
-include protocol PSms;
-include protocol PBlob;
-include SmsTypes;
-
-using struct mozilla::void_t from "ipc/IPCMessageUtils.h";
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-protocol PSmsRequest
-{
-  manager PSms;
-
-child:
-  /**
-   * Sent when the asynchronous request has completed.
-   */
-  async __delete__(MessageReply response);
-};
-
-struct ReplyMessageSend
-{
-  MobileMessageData messageData;
-};
-
-union OptionalMobileMessageData
-{
-  void_t;
-  MobileMessageData;
-};
-
-struct ReplyMessageSendFail
-{
-  int32_t error;
-  OptionalMobileMessageData messageData;
-};
-
-struct ReplyGetMessage
-{
-  MobileMessageData messageData;
-};
-
-struct ReplyGetMessageFail
-{
-  int32_t error;
-};
-
-struct ReplyMessageDelete
-{
-  bool[] deleted;
-};
-
-struct ReplyMessageDeleteFail
-{
-  int32_t error;
-};
-
-struct ReplyMarkeMessageRead
-{
-  bool read;
-};
-
-struct ReplyMarkeMessageReadFail
-{
-  int32_t error;
-};
-
-struct ReplyGetSegmentInfoForText
-{
-  int32_t segments;
-  int32_t charsPerSegment;
-  int32_t charsAvailableInLastSegment;
-};
-
-struct ReplyGetSegmentInfoForTextFail
-{
-  int32_t error;
-};
-
-struct ReplyGetSmscAddress
-{
-  nsString smscAddress;
-  uint32_t typeOfNumber;
-  uint32_t numberPlanIdentification;
-};
-
-struct ReplyGetSmscAddressFail
-{
-  int32_t error;
-};
-
-struct ReplySetSmscAddress
-{
-};
-
-struct ReplySetSmscAddressFail
-{
-  int32_t error;
-};
-
-union MessageReply
-{
-  ReplyMessageSend;
-  ReplyMessageSendFail;
-  ReplyGetMessage;
-  ReplyGetMessageFail;
-  ReplyMessageDelete;
-  ReplyMessageDeleteFail;
-  ReplyMarkeMessageRead;
-  ReplyMarkeMessageReadFail;
-  ReplyGetSegmentInfoForText;
-  ReplyGetSegmentInfoForTextFail;
-  ReplyGetSmscAddress;
-  ReplyGetSmscAddressFail;
-  ReplySetSmscAddress;
-  ReplySetSmscAddressFail;
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/ipc/SmsChild.cpp
+++ /dev/null
@@ -1,391 +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 "SmsChild.h"
-
-#include "SmsMessageInternal.h"
-#include "MmsMessageInternal.h"
-#include "DeletedMessageInfo.h"
-#include "nsIObserverService.h"
-#include "mozilla/Services.h"
-#include "mozilla/dom/ContentChild.h"
-#include "mozilla/dom/mobilemessage/Constants.h" // For MessageType
-#include "MobileMessageThreadInternal.h"
-#include "MainThreadUtils.h"
-
-using namespace mozilla;
-using namespace mozilla::dom;
-using namespace mozilla::dom::mobilemessage;
-
-namespace {
-
-already_AddRefed<nsISupports>
-CreateMessageFromMessageData(const MobileMessageData& aData)
-{
-  nsCOMPtr<nsISupports> message;
-
-  switch(aData.type()) {
-    case MobileMessageData::TMmsMessageData:
-      message = new MmsMessageInternal(aData.get_MmsMessageData());
-      break;
-    case MobileMessageData::TSmsMessageData:
-      message = new SmsMessageInternal(aData.get_SmsMessageData());
-      break;
-    default:
-      MOZ_CRASH("Unexpected type of MobileMessageData");
-  }
-
-  return message.forget();
-}
-
-void
-NotifyObserversWithMobileMessage(const char* aEventName,
-                                 const MobileMessageData& aData)
-{
-  nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
-  if (!obs) {
-    return;
-  }
-
-  nsCOMPtr<nsISupports> msg = CreateMessageFromMessageData(aData);
-  obs->NotifyObservers(msg, aEventName, nullptr);
-}
-
-} // namespace
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-void
-SmsChild::ActorDestroy(ActorDestroyReason aWhy)
-{
-}
-
-bool
-SmsChild::RecvNotifyReceivedMessage(const MobileMessageData& aData)
-{
-  NotifyObserversWithMobileMessage(kSmsReceivedObserverTopic, aData);
-  return true;
-}
-
-bool
-SmsChild::RecvNotifyRetrievingMessage(const MobileMessageData& aData)
-{
-  NotifyObserversWithMobileMessage(kSmsRetrievingObserverTopic, aData);
-  return true;
-}
-
-bool
-SmsChild::RecvNotifySendingMessage(const MobileMessageData& aData)
-{
-  NotifyObserversWithMobileMessage(kSmsSendingObserverTopic, aData);
-  return true;
-}
-
-bool
-SmsChild::RecvNotifySentMessage(const MobileMessageData& aData)
-{
-  NotifyObserversWithMobileMessage(kSmsSentObserverTopic, aData);
-  return true;
-}
-
-bool
-SmsChild::RecvNotifyFailedMessage(const MobileMessageData& aData)
-{
-  NotifyObserversWithMobileMessage(kSmsFailedObserverTopic, aData);
-  return true;
-}
-
-bool
-SmsChild::RecvNotifyDeliverySuccessMessage(const MobileMessageData& aData)
-{
-  NotifyObserversWithMobileMessage(kSmsDeliverySuccessObserverTopic, aData);
-  return true;
-}
-
-bool
-SmsChild::RecvNotifyDeliveryErrorMessage(const MobileMessageData& aData)
-{
-  NotifyObserversWithMobileMessage(kSmsDeliveryErrorObserverTopic, aData);
-  return true;
-}
-
-bool
-SmsChild::RecvNotifyReceivedSilentMessage(const MobileMessageData& aData)
-{
-  NotifyObserversWithMobileMessage(kSilentSmsReceivedObserverTopic, aData);
-  return true;
-}
-
-bool
-SmsChild::RecvNotifyReadSuccessMessage(const MobileMessageData& aData)
-{
-  NotifyObserversWithMobileMessage(kSmsReadSuccessObserverTopic, aData);
-  return true;
-}
-
-bool
-SmsChild::RecvNotifyReadErrorMessage(const MobileMessageData& aData)
-{
-  NotifyObserversWithMobileMessage(kSmsReadErrorObserverTopic, aData);
-  return true;
-}
-
-bool
-SmsChild::RecvNotifyDeletedMessageInfo(const DeletedMessageInfoData& aDeletedInfo)
-{
-  nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
-  if (!obs) {
-    NS_ERROR("Failed to get nsIObserverService!");
-    return false;
-  }
-
-  nsCOMPtr<nsISupports> info = new DeletedMessageInfo(aDeletedInfo);
-  obs->NotifyObservers(info, kSmsDeletedObserverTopic, nullptr);
-
-  return true;
-}
-
-PSmsRequestChild*
-SmsChild::AllocPSmsRequestChild(const IPCSmsRequest& aRequest)
-{
-  MOZ_CRASH("Caller is supposed to manually construct a request!");
-}
-
-bool
-SmsChild::DeallocPSmsRequestChild(PSmsRequestChild* aActor)
-{
-  delete aActor;
-  return true;
-}
-
-PMobileMessageCursorChild*
-SmsChild::AllocPMobileMessageCursorChild(const IPCMobileMessageCursor& aCursor)
-{
-  MOZ_CRASH("Caller is supposed to manually construct a cursor!");
-}
-
-bool
-SmsChild::DeallocPMobileMessageCursorChild(PMobileMessageCursorChild* aActor)
-{
-  // MobileMessageCursorChild is refcounted, must not be freed manually.
-  // Originally AddRefed in SendCursorRequest() in SmsIPCService.cpp.
-  static_cast<MobileMessageCursorChild*>(aActor)->Release();
-  return true;
-}
-
-/*******************************************************************************
- * SmsRequestChild
- ******************************************************************************/
-
-SmsRequestChild::SmsRequestChild(nsIMobileMessageCallback* aReplyRequest)
-  : mReplyRequest(aReplyRequest)
-{
-  MOZ_COUNT_CTOR(SmsRequestChild);
-  MOZ_ASSERT(aReplyRequest);
-}
-
-void
-SmsRequestChild::ActorDestroy(ActorDestroyReason aWhy)
-{
-  // Nothing needed here.
-}
-
-bool
-SmsRequestChild::Recv__delete__(const MessageReply& aReply)
-{
-  MOZ_ASSERT(NS_IsMainThread());
-  MOZ_ASSERT(mReplyRequest);
-  switch(aReply.type()) {
-    case MessageReply::TReplyMessageSend: {
-        const MobileMessageData& data =
-          aReply.get_ReplyMessageSend().messageData();
-        nsCOMPtr<nsISupports> msg = CreateMessageFromMessageData(data);
-        mReplyRequest->NotifyMessageSent(msg);
-      }
-      break;
-    case MessageReply::TReplyMessageSendFail: {
-        const ReplyMessageSendFail &replyFail = aReply.get_ReplyMessageSendFail();
-        nsCOMPtr<nsISupports> msg;
-
-        if (replyFail.messageData().type() ==
-            OptionalMobileMessageData::TMobileMessageData) {
-          msg = CreateMessageFromMessageData(
-            replyFail.messageData().get_MobileMessageData());
-        }
-
-        mReplyRequest->NotifySendMessageFailed(replyFail.error(), msg);
-      }
-      break;
-    case MessageReply::TReplyGetMessage: {
-        const MobileMessageData& data =
-          aReply.get_ReplyGetMessage().messageData();
-        nsCOMPtr<nsISupports> msg = CreateMessageFromMessageData(data);
-        mReplyRequest->NotifyMessageGot(msg);
-      }
-      break;
-    case MessageReply::TReplyGetMessageFail:
-      mReplyRequest->NotifyGetMessageFailed(aReply.get_ReplyGetMessageFail().error());
-      break;
-    case MessageReply::TReplyMessageDelete: {
-        const InfallibleTArray<bool>& deletedResult = aReply.get_ReplyMessageDelete().deleted();
-        mReplyRequest->NotifyMessageDeleted(const_cast<bool *>(deletedResult.Elements()),
-                                            deletedResult.Length());
-      }
-      break;
-    case MessageReply::TReplyMessageDeleteFail:
-      mReplyRequest->NotifyDeleteMessageFailed(aReply.get_ReplyMessageDeleteFail().error());
-      break;
-    case MessageReply::TReplyMarkeMessageRead:
-      mReplyRequest->NotifyMessageMarkedRead(aReply.get_ReplyMarkeMessageRead().read());
-      break;
-    case MessageReply::TReplyMarkeMessageReadFail:
-      mReplyRequest->NotifyMarkMessageReadFailed(aReply.get_ReplyMarkeMessageReadFail().error());
-      break;
-    case MessageReply::TReplyGetSegmentInfoForText: {
-        const ReplyGetSegmentInfoForText& reply =
-          aReply.get_ReplyGetSegmentInfoForText();
-        mReplyRequest->NotifySegmentInfoForTextGot(reply.segments(),
-                                                   reply.charsPerSegment(),
-                                                   reply.charsAvailableInLastSegment());
-      }
-      break;
-    case MessageReply::TReplyGetSegmentInfoForTextFail:
-      mReplyRequest->NotifyGetSegmentInfoForTextFailed(
-        aReply.get_ReplyGetSegmentInfoForTextFail().error());
-      break;
-    case MessageReply::TReplyGetSmscAddress:
-      mReplyRequest->NotifyGetSmscAddress(aReply.get_ReplyGetSmscAddress().smscAddress(),
-                                          aReply.get_ReplyGetSmscAddress().typeOfNumber(),
-                                          aReply.get_ReplyGetSmscAddress().numberPlanIdentification());
-      break;
-    case MessageReply::TReplyGetSmscAddressFail:
-      mReplyRequest->NotifyGetSmscAddressFailed(aReply.get_ReplyGetSmscAddressFail().error());
-      break;
-    case MessageReply::TReplySetSmscAddress:
-      mReplyRequest->NotifySetSmscAddress();
-      break;
-    case MessageReply::TReplySetSmscAddressFail:
-      mReplyRequest->NotifySetSmscAddressFailed(aReply.get_ReplySetSmscAddressFail().error());
-      break;
-    default:
-      MOZ_CRASH("Received invalid response parameters!");
-  }
-
-  return true;
-}
-
-/*******************************************************************************
- * MobileMessageCursorChild
- ******************************************************************************/
-
-NS_IMPL_ISUPPORTS(MobileMessageCursorChild, nsICursorContinueCallback)
-
-MobileMessageCursorChild::MobileMessageCursorChild(nsIMobileMessageCursorCallback* aCallback)
-  : mCursorCallback(aCallback)
-{
-  MOZ_COUNT_CTOR(MobileMessageCursorChild);
-  MOZ_ASSERT(aCallback);
-}
-
-void
-MobileMessageCursorChild::ActorDestroy(ActorDestroyReason aWhy)
-{
-  // Nothing needed here.
-}
-
-bool
-MobileMessageCursorChild::RecvNotifyResult(const MobileMessageCursorData& aData)
-{
-  MOZ_ASSERT(mCursorCallback);
-
-  switch(aData.type()) {
-    case MobileMessageCursorData::TMobileMessageArrayData:
-      DoNotifyResult(aData.get_MobileMessageArrayData().messages());
-      break;
-    case MobileMessageCursorData::TThreadArrayData:
-      DoNotifyResult(aData.get_ThreadArrayData().threads());
-      break;
-    default:
-      MOZ_CRASH("Received invalid response parameters!");
-  }
-
-  return true;
-}
-
-bool
-MobileMessageCursorChild::Recv__delete__(const int32_t& aError)
-{
-  MOZ_ASSERT(mCursorCallback);
-
-  if (aError != nsIMobileMessageCallback::SUCCESS_NO_ERROR) {
-    mCursorCallback->NotifyCursorError(aError);
-  } else {
-    mCursorCallback->NotifyCursorDone();
-  }
-  mCursorCallback = nullptr;
-
-  return true;
-}
-
-// nsICursorContinueCallback
-
-NS_IMETHODIMP
-MobileMessageCursorChild::HandleContinue()
-{
-  MOZ_ASSERT(mCursorCallback);
-
-  SendContinue();
-  return NS_OK;
-}
-
-void
-MobileMessageCursorChild::DoNotifyResult(const nsTArray<MobileMessageData>& aDataArray)
-{
-  const uint32_t length = aDataArray.Length();
-  MOZ_ASSERT(length);
-
-  AutoTArray<nsISupports*, 1> autoArray;
-  NS_ENSURE_TRUE_VOID(autoArray.SetCapacity(length, fallible));
-
-  AutoTArray<nsCOMPtr<nsISupports>, 1> messages;
-  NS_ENSURE_TRUE_VOID(messages.SetCapacity(length, fallible));
-
-  for (uint32_t i = 0; i < length; i++) {
-    nsCOMPtr<nsISupports> message = CreateMessageFromMessageData(aDataArray[i]);
-    NS_ENSURE_TRUE_VOID(messages.AppendElement(message, fallible));
-    NS_ENSURE_TRUE_VOID(autoArray.AppendElement(message.get(), fallible));
-  }
-
-  mCursorCallback->NotifyCursorResult(autoArray.Elements(), length);
-}
-
-void
-MobileMessageCursorChild::DoNotifyResult(const nsTArray<ThreadData>& aDataArray)
-{
-  const uint32_t length = aDataArray.Length();
-  MOZ_ASSERT(length);
-
-  AutoTArray<nsISupports*, 1> autoArray;
-  NS_ENSURE_TRUE_VOID(autoArray.SetCapacity(length, fallible));
-
-  AutoTArray<nsCOMPtr<nsISupports>, 1> threads;
-  NS_ENSURE_TRUE_VOID(threads.SetCapacity(length, fallible));
-
-  for (uint32_t i = 0; i < length; i++) {
-    nsCOMPtr<nsISupports> thread =
-      new MobileMessageThreadInternal(aDataArray[i]);
-    NS_ENSURE_TRUE_VOID(threads.AppendElement(thread, fallible));
-    NS_ENSURE_TRUE_VOID(autoArray.AppendElement(thread.get(), fallible));
-  }
-
-  mCursorCallback->NotifyCursorResult(autoArray.Elements(), length);
-}
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/ipc/SmsChild.h
+++ /dev/null
@@ -1,146 +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_mobilemessage_SmsChild_h
-#define mozilla_dom_mobilemessage_SmsChild_h
-
-#include "mozilla/dom/mobilemessage/PSmsChild.h"
-#include "mozilla/dom/mobilemessage/PSmsRequestChild.h"
-#include "mozilla/dom/mobilemessage/PMobileMessageCursorChild.h"
-#include "nsIDOMDOMCursor.h"
-#include "nsIMobileMessageCallback.h"
-#include "nsIMobileMessageCursorCallback.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-class SmsChild : public PSmsChild
-{
-public:
-  SmsChild()
-  {
-    MOZ_COUNT_CTOR(SmsChild);
-  }
-
-protected:
-  virtual ~SmsChild()
-  {
-    MOZ_COUNT_DTOR(SmsChild);
-  }
-
-  virtual void
-  ActorDestroy(ActorDestroyReason aWhy) override;
-
-  virtual bool
-  RecvNotifyReceivedMessage(const MobileMessageData& aMessage) override;
-
-  virtual bool
-  RecvNotifyRetrievingMessage(const MobileMessageData& aMessage) override;
-
-  virtual bool
-  RecvNotifySendingMessage(const MobileMessageData& aMessage) override;
-
-  virtual bool
-  RecvNotifySentMessage(const MobileMessageData& aMessage) override;
-
-  virtual bool
-  RecvNotifyFailedMessage(const MobileMessageData& aMessage) override;
-
-  virtual bool
-  RecvNotifyDeliverySuccessMessage(const MobileMessageData& aMessage) override;
-
-  virtual bool
-  RecvNotifyDeliveryErrorMessage(const MobileMessageData& aMessage) override;
-
-  virtual bool
-  RecvNotifyReceivedSilentMessage(const MobileMessageData& aMessage) override;
-
-  virtual bool
-  RecvNotifyReadSuccessMessage(const MobileMessageData& aMessage) override;
-
-  virtual bool
-  RecvNotifyReadErrorMessage(const MobileMessageData& aMessage) override;
-
-  virtual bool
-  RecvNotifyDeletedMessageInfo(const DeletedMessageInfoData& aDeletedInfo) override;
-
-  virtual PSmsRequestChild*
-  AllocPSmsRequestChild(const IPCSmsRequest& aRequest) override;
-
-  virtual bool
-  DeallocPSmsRequestChild(PSmsRequestChild* aActor) override;
-
-  virtual PMobileMessageCursorChild*
-  AllocPMobileMessageCursorChild(const IPCMobileMessageCursor& aCursor) override;
-
-  virtual bool
-  DeallocPMobileMessageCursorChild(PMobileMessageCursorChild* aActor) override;
-};
-
-class SmsRequestChild : public PSmsRequestChild
-{
-  friend class SmsChild;
-
-  nsCOMPtr<nsIMobileMessageCallback> mReplyRequest;
-
-public:
-  explicit SmsRequestChild(nsIMobileMessageCallback* aReplyRequest);
-
-protected:
-  virtual ~SmsRequestChild()
-  {
-    MOZ_COUNT_DTOR(SmsRequestChild);
-  }
-
-  virtual void
-  ActorDestroy(ActorDestroyReason aWhy) override;
-
-  virtual bool
-  Recv__delete__(const MessageReply& aReply) override;
-};
-
-class MobileMessageCursorChild : public PMobileMessageCursorChild
-                               , public nsICursorContinueCallback
-{
-  friend class SmsChild;
-
-  nsCOMPtr<nsIMobileMessageCursorCallback> mCursorCallback;
-
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSICURSORCONTINUECALLBACK
-
-  explicit MobileMessageCursorChild(nsIMobileMessageCursorCallback* aCallback);
-
-protected:
-  virtual ~MobileMessageCursorChild()
-  {
-    MOZ_COUNT_DTOR(MobileMessageCursorChild);
-  }
-
-  virtual void
-  ActorDestroy(ActorDestroyReason aWhy) override;
-
-  virtual bool
-  RecvNotifyResult(const MobileMessageCursorData& aData) override;
-
-  virtual bool
-  Recv__delete__(const int32_t& aError) override;
-
-private:
-  void
-  DoNotifyResult(const nsTArray<MobileMessageData>& aData);
-
-  void
-  DoNotifyResult(const nsTArray<ThreadData>& aData);
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_SmsChild_h
deleted file mode 100644
--- a/dom/mobilemessage/ipc/SmsIPCService.cpp
+++ /dev/null
@@ -1,396 +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/ContentChild.h"
-#include "SmsIPCService.h"
-#include "nsXULAppAPI.h"
-#include "mozilla/dom/mobilemessage/SmsChild.h"
-#include "nsJSUtils.h"
-#include "mozilla/dom/MozMobileMessageManagerBinding.h"
-#include "mozilla/dom/BindingUtils.h"
-#include "mozilla/Preferences.h"
-#include "nsString.h"
-#include "mozilla/dom/ipc/BlobChild.h"
-#include "mozilla/Unused.h"
-
-using namespace mozilla::dom;
-using namespace mozilla::dom::mobilemessage;
-
-namespace {
-
-#define kPrefMmsDefaultServiceId "dom.mms.defaultServiceId"
-#define kPrefSmsDefaultServiceId "dom.sms.defaultServiceId"
-
-// TODO: Bug 767082 - WebSMS: sSmsChild leaks at shutdown
-PSmsChild* gSmsChild;
-
-// SmsIPCService is owned by nsLayoutModule.
-SmsIPCService* sSingleton = nullptr;
-
-PSmsChild*
-GetSmsChild()
-{
-  MOZ_ASSERT(NS_IsMainThread());
-
-  if (!gSmsChild) {
-    gSmsChild = ContentChild::GetSingleton()->SendPSmsConstructor();
-
-    NS_WARNING_ASSERTION(gSmsChild,
-                         "Calling methods on SmsIPCService during shutdown!");
-  }
-
-  return gSmsChild;
-}
-
-nsresult
-SendRequest(const IPCSmsRequest& aRequest,
-            nsIMobileMessageCallback* aRequestReply)
-{
-  PSmsChild* smsChild = GetSmsChild();
-  NS_ENSURE_TRUE(smsChild, NS_ERROR_FAILURE);
-
-  SmsRequestChild* actor = new SmsRequestChild(aRequestReply);
-  smsChild->SendPSmsRequestConstructor(actor, aRequest);
-
-  return NS_OK;
-}
-
-nsresult
-SendCursorRequest(const IPCMobileMessageCursor& aRequest,
-                  nsIMobileMessageCursorCallback* aRequestReply,
-                  nsICursorContinueCallback** aResult)
-{
-  PSmsChild* smsChild = GetSmsChild();
-  NS_ENSURE_TRUE(smsChild, NS_ERROR_FAILURE);
-
-  RefPtr<MobileMessageCursorChild> actor =
-    new MobileMessageCursorChild(aRequestReply);
-
-  // Add an extra ref for IPDL. Will be released in
-  // SmsChild::DeallocPMobileMessageCursor().
-  RefPtr<MobileMessageCursorChild> actorCopy(actor);
-  mozilla::Unused << actorCopy.forget().take();
-
-  smsChild->SendPMobileMessageCursorConstructor(actor, aRequest);
-
-  actor.forget(aResult);
-  return NS_OK;
-}
-
-uint32_t
-getDefaultServiceId(const char* aPrefKey)
-{
-  static const char* kPrefRilNumRadioInterfaces = "ril.numRadioInterfaces";
-  int32_t id = mozilla::Preferences::GetInt(aPrefKey, 0);
-  int32_t numRil = mozilla::Preferences::GetInt(kPrefRilNumRadioInterfaces, 1);
-
-  if (id >= numRil || id < 0) {
-    id = 0;
-  }
-
-  return id;
-}
-
-} // namespace
-
-NS_IMPL_ISUPPORTS(SmsIPCService,
-                  nsISmsService,
-                  nsIMmsService,
-                  nsIMobileMessageDatabaseService,
-                  nsIObserver)
-
-/* static */ already_AddRefed<SmsIPCService>
-SmsIPCService::GetSingleton()
-{
-  MOZ_ASSERT(NS_IsMainThread());
-
-  if (!sSingleton) {
-    sSingleton = new SmsIPCService();
-  }
-
-  RefPtr<SmsIPCService> service = sSingleton;
-  return service.forget();
-}
-
-SmsIPCService::SmsIPCService()
-{
-  static const char* kObservedPrefs[] = {
-    kPrefMmsDefaultServiceId,
-    kPrefSmsDefaultServiceId,
-    nullptr
-  };
-  Preferences::AddStrongObservers(this, kObservedPrefs);
-  mMmsDefaultServiceId = getDefaultServiceId(kPrefMmsDefaultServiceId);
-  mSmsDefaultServiceId = getDefaultServiceId(kPrefSmsDefaultServiceId);
-}
-
-SmsIPCService::~SmsIPCService()
-{
-  sSingleton = nullptr;
-}
-
-/*
- * Implementation of nsIObserver.
- */
-
-NS_IMETHODIMP
-SmsIPCService::Observe(nsISupports* aSubject,
-                       const char* aTopic,
-                       const char16_t* aData)
-{
-  if (!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
-    nsDependentString data(aData);
-    if (data.EqualsLiteral(kPrefMmsDefaultServiceId)) {
-      mMmsDefaultServiceId = getDefaultServiceId(kPrefMmsDefaultServiceId);
-    } else if (data.EqualsLiteral(kPrefSmsDefaultServiceId)) {
-      mSmsDefaultServiceId = getDefaultServiceId(kPrefSmsDefaultServiceId);
-    }
-    return NS_OK;
-  }
-
-  MOZ_ASSERT(false, "SmsIPCService got unexpected topic!");
-  return NS_ERROR_UNEXPECTED;
-}
-
-/*
- * Implementation of nsISmsService.
- */
-
-NS_IMETHODIMP
-SmsIPCService::GetSmsDefaultServiceId(uint32_t* aServiceId)
-{
-  *aServiceId = mSmsDefaultServiceId;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsIPCService::GetSegmentInfoForText(const nsAString& aText,
-                                     nsIMobileMessageCallback* aRequest)
-{
-  return SendRequest(GetSegmentInfoForTextRequest(nsString(aText)),
-                                                  aRequest);
-}
-
-NS_IMETHODIMP
-SmsIPCService::GetSmscAddress(uint32_t aServiceId,
-                              nsIMobileMessageCallback* aRequest)
-{
-  return SendRequest(GetSmscAddressRequest(aServiceId), aRequest);
-}
-
-
-NS_IMETHODIMP
-SmsIPCService::SetSmscAddress(uint32_t aServiceId,
-                              const nsAString& aNumber,
-                              uint32_t aTypeOfNumber,
-                              uint32_t aNumberPlanIdentification,
-                              nsIMobileMessageCallback* aRequest)
-{
-  return SendRequest(SetSmscAddressRequest(aServiceId,
-                                           nsString(aNumber),
-                                           aTypeOfNumber,
-                                           aNumberPlanIdentification),
-                     aRequest);
-}
-
-NS_IMETHODIMP
-SmsIPCService::Send(uint32_t aServiceId,
-                    const nsAString& aNumber,
-                    const nsAString& aMessage,
-                    bool aSilent,
-                    nsIMobileMessageCallback* aRequest)
-{
-  return SendRequest(SendMessageRequest(SendSmsMessageRequest(aServiceId,
-                                                              nsString(aNumber),
-                                                              nsString(aMessage),
-                                                              aSilent)),
-                     aRequest);
-}
-
-NS_IMETHODIMP
-SmsIPCService::AddSilentNumber(const nsAString& aNumber)
-{
-  PSmsChild* smsChild = GetSmsChild();
-  NS_ENSURE_TRUE(smsChild, NS_ERROR_FAILURE);
-
-  smsChild->SendAddSilentNumber(nsString(aNumber));
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsIPCService::RemoveSilentNumber(const nsAString& aNumber)
-{
-  PSmsChild* smsChild = GetSmsChild();
-  NS_ENSURE_TRUE(smsChild, NS_ERROR_FAILURE);
-
-  smsChild->SendRemoveSilentNumber(nsString(aNumber));
-  return NS_OK;
-}
-
-/*
- * Implementation of nsIMobileMessageDatabaseService.
- */
-NS_IMETHODIMP
-SmsIPCService::GetMessageMoz(int32_t aMessageId,
-                             nsIMobileMessageCallback* aRequest)
-{
-  return SendRequest(GetMessageRequest(aMessageId), aRequest);
-}
-
-NS_IMETHODIMP
-SmsIPCService::DeleteMessage(int32_t *aMessageIds, uint32_t aSize,
-                             nsIMobileMessageCallback* aRequest)
-{
-  DeleteMessageRequest data;
-  data.messageIds().AppendElements(aMessageIds, aSize);
-  return SendRequest(data, aRequest);
-}
-
-NS_IMETHODIMP
-SmsIPCService::CreateMessageCursor(bool aHasStartDate,
-                                   uint64_t aStartDate,
-                                   bool aHasEndDate,
-                                   uint64_t aEndDate,
-                                   const char16_t** aNumbers,
-                                   uint32_t aNumbersCount,
-                                   const nsAString& aDelivery,
-                                   bool aHasRead,
-                                   bool aRead,
-                                   bool aHasThreadId,
-                                   uint64_t aThreadId,
-                                   bool aReverse,
-                                   nsIMobileMessageCursorCallback* aCursorCallback,
-                                   nsICursorContinueCallback** aResult)
-{
-  SmsFilterData data;
-
-  data.hasStartDate() = aHasStartDate;
-  data.startDate() = aStartDate;
-  data.hasEndDate() = aHasEndDate;
-  data.endDate() = aEndDate;
-
-  if (aNumbersCount && aNumbers) {
-    nsTArray<nsString>& numbers = data.numbers();
-    uint32_t index;
-
-    for (index = 0; index < aNumbersCount; index++) {
-      numbers.AppendElement(aNumbers[index]);
-    }
-  }
-
-  data.delivery() = aDelivery;
-  data.hasRead() = aHasRead;
-  data.read() = aRead;
-  data.hasThreadId() = aHasThreadId;
-  data.threadId() = aThreadId;
-
-  return SendCursorRequest(CreateMessageCursorRequest(data, aReverse),
-                           aCursorCallback, aResult);
-}
-
-NS_IMETHODIMP
-SmsIPCService::MarkMessageRead(int32_t aMessageId,
-                               bool aValue,
-                               bool aSendReadReport,
-                               nsIMobileMessageCallback* aRequest)
-{
-  return SendRequest(MarkMessageReadRequest(aMessageId, aValue, aSendReadReport), aRequest);
-}
-
-NS_IMETHODIMP
-SmsIPCService::CreateThreadCursor(nsIMobileMessageCursorCallback* aCursorCallback,
-                                  nsICursorContinueCallback** aResult)
-{
-  return SendCursorRequest(CreateThreadCursorRequest(), aCursorCallback,
-                           aResult);
-}
-
-bool
-GetSendMmsMessageRequestFromParams(uint32_t aServiceId,
-                                   const JS::Value& aParam,
-                                   SendMmsMessageRequest& request) {
-  if (aParam.isUndefined() || aParam.isNull() || !aParam.isObject()) {
-    return false;
-  }
-
-  mozilla::AutoJSContext cx;
-  JS::Rooted<JS::Value> param(cx, aParam);
-  RootedDictionary<MmsParameters> params(cx);
-  if (!params.Init(cx, param)) {
-    return false;
-  }
-
-  // SendMobileMessageRequest.receivers
-  if (!params.mReceivers.WasPassed()) {
-    return false;
-  }
-  request.receivers().AppendElements(params.mReceivers.Value());
-
-  // SendMobileMessageRequest.attachments
-  mozilla::dom::ContentChild* cc = mozilla::dom::ContentChild::GetSingleton();
-
-  if (!params.mAttachments.WasPassed()) {
-    return false;
-  }
-
-  for (uint32_t i = 0; i < params.mAttachments.Value().Length(); i++) {
-    mozilla::dom::MmsAttachment& attachment = params.mAttachments.Value()[i];
-    MmsAttachmentData mmsAttachment;
-    mmsAttachment.id().Assign(attachment.mId);
-    mmsAttachment.location().Assign(attachment.mLocation);
-    mmsAttachment.contentChild() = cc->GetOrCreateActorForBlob(attachment.mContent);
-    if (!mmsAttachment.contentChild()) {
-      return false;
-    }
-    request.attachments().AppendElement(mmsAttachment);
-  }
-
-  request.smil() = params.mSmil;
-  request.subject() = params.mSubject;
-
-  // Set service ID.
-  request.serviceId() = aServiceId;
-
-  return true;
-}
-
-/*
- * Implementation of nsIMmsService.
- */
-
-NS_IMETHODIMP
-SmsIPCService::GetMmsDefaultServiceId(uint32_t* aServiceId)
-{
-  *aServiceId = mMmsDefaultServiceId;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SmsIPCService::Send(uint32_t aServiceId,
-                    JS::Handle<JS::Value> aParameters,
-                    nsIMobileMessageCallback *aRequest)
-{
-  SendMmsMessageRequest req;
-  if (!GetSendMmsMessageRequestFromParams(aServiceId, aParameters, req)) {
-    return NS_ERROR_INVALID_ARG;
-  }
-  return SendRequest(SendMessageRequest(req), aRequest);
-}
-
-NS_IMETHODIMP
-SmsIPCService::Retrieve(int32_t aId, nsIMobileMessageCallback *aRequest)
-{
-  return SendRequest(RetrieveMessageRequest(aId), aRequest);
-}
-
-NS_IMETHODIMP
-SmsIPCService::SendReadReport(const nsAString & messageID,
-                              const nsAString & toAddress,
-                              const nsAString & iccId)
-{
-  NS_ERROR("We should not be here!");
-  return NS_OK;
-}
deleted file mode 100644
--- a/dom/mobilemessage/ipc/SmsIPCService.h
+++ /dev/null
@@ -1,49 +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_mobilemessage_SmsIPCService_h
-#define mozilla_dom_mobilemessage_SmsIPCService_h
-
-#include "nsISmsService.h"
-#include "nsIMmsService.h"
-#include "nsIMobileMessageDatabaseService.h"
-#include "nsIObserver.h"
-#include "mozilla/Attributes.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-class SmsIPCService final : public nsISmsService
-                          , public nsIMmsService
-                          , public nsIMobileMessageDatabaseService
-                          , public nsIObserver
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSISMSSERVICE
-  NS_DECL_NSIMMSSERVICE
-  NS_DECL_NSIMOBILEMESSAGEDATABASESERVICE
-  NS_DECL_NSIOBSERVER
-
-  static already_AddRefed<SmsIPCService>
-  GetSingleton();
-
-private:
-  SmsIPCService();
-
-  // final suppresses -Werror,-Wdelete-non-virtual-dtor
-  ~SmsIPCService();
-
-  uint32_t mMmsDefaultServiceId;
-  uint32_t mSmsDefaultServiceId;
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_SmsIPCService_h
deleted file mode 100644
--- a/dom/mobilemessage/ipc/SmsParent.cpp
+++ /dev/null
@@ -1,967 +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 "SmsParent.h"
-
-#include "nsISmsService.h"
-#include "nsIMmsService.h"
-#include "nsIObserverService.h"
-#include "mozilla/Services.h"
-#include "nsISmsMessage.h"
-#include "nsIMmsMessage.h"
-#include "mozilla/Unused.h"
-#include "SmsMessageInternal.h"
-#include "MmsMessageInternal.h"
-#include "nsIMobileMessageDatabaseService.h"
-#include "MobileMessageThreadInternal.h"
-#include "mozilla/dom/ipc/BlobParent.h"
-#include "mozilla/dom/ContentParent.h"
-#include "mozilla/dom/File.h"
-#include "mozilla/dom/ToJSValue.h"
-#include "mozilla/dom/mobilemessage/Constants.h" // For MessageType
-#include "mozilla/UniquePtr.h"
-#include "nsContentUtils.h"
-#include "nsTArrayHelpers.h"
-#include "xpcpublic.h"
-#include "nsServiceManagerUtils.h"
-#include "DeletedMessageInfo.h"
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-static JSObject*
-MmsAttachmentDataToJSObject(JSContext* aContext,
-                            const MmsAttachmentData& aAttachment)
-{
-  JS::Rooted<JSObject*> obj(aContext, JS_NewPlainObject(aContext));
-  NS_ENSURE_TRUE(obj, nullptr);
-
-  JS::Rooted<JSString*> idStr(aContext, JS_NewUCStringCopyN(aContext,
-                                                            aAttachment.id().get(),
-                                                            aAttachment.id().Length()));
-  NS_ENSURE_TRUE(idStr, nullptr);
-  if (!JS_DefineProperty(aContext, obj, "id", idStr, 0)) {
-    return nullptr;
-  }
-
-  JS::Rooted<JSString*> locStr(aContext, JS_NewUCStringCopyN(aContext,
-                                                             aAttachment.location().get(),
-                                                             aAttachment.location().Length()));
-  NS_ENSURE_TRUE(locStr, nullptr);
-  if (!JS_DefineProperty(aContext, obj, "location", locStr, 0)) {
-    return nullptr;
-  }
-
-  RefPtr<BlobImpl> blobImpl = static_cast<BlobParent*>(aAttachment.contentParent())->GetBlobImpl();
-
-  // RefPtr<File> needs to go out of scope before toObjectOrNull() is
-  // called because the static analysis thinks dereferencing XPCOM objects
-  // can GC (because in some cases it can!), and a return statement with a
-  // JSObject* type means that JSObject* is on the stack as a raw pointer
-  // while destructors are running.
-  JS::Rooted<JS::Value> content(aContext);
-  {
-    nsIGlobalObject *global = xpc::NativeGlobal(JS::CurrentGlobalOrNull(aContext));
-    MOZ_ASSERT(global);
-
-    RefPtr<Blob> blob = Blob::Create(global, blobImpl);
-    if (!ToJSValue(aContext, blob, &content)) {
-      return nullptr;
-    }
-  }
-
-  if (!JS_DefineProperty(aContext, obj, "content", content, 0)) {
-    return nullptr;
-  }
-
-  return obj;
-}
-
-static bool
-GetParamsFromSendMmsMessageRequest(JSContext* aCx,
-                                   const SendMmsMessageRequest& aRequest,
-                                   JS::Value* aParam)
-{
-  JS::Rooted<JSObject*> paramsObj(aCx, JS_NewPlainObject(aCx));
-  NS_ENSURE_TRUE(paramsObj, false);
-
-  // smil
-  JS::Rooted<JSString*> smilStr(aCx, JS_NewUCStringCopyN(aCx,
-                                                         aRequest.smil().get(),
-                                                         aRequest.smil().Length()));
-  NS_ENSURE_TRUE(smilStr, false);
-  if(!JS_DefineProperty(aCx, paramsObj, "smil", smilStr, 0)) {
-    return false;
-  }
-
-  // subject
-  JS::Rooted<JSString*> subjectStr(aCx, JS_NewUCStringCopyN(aCx,
-                                                            aRequest.subject().get(),
-                                                            aRequest.subject().Length()));
-  NS_ENSURE_TRUE(subjectStr, false);
-  if(!JS_DefineProperty(aCx, paramsObj, "subject", subjectStr, 0)) {
-    return false;
-  }
-
-  // receivers
-  JS::Rooted<JSObject*> receiverArray(aCx);
-  if (NS_FAILED(nsTArrayToJSArray(aCx, aRequest.receivers(), &receiverArray)))
-  {
-    return false;
-  }
-  if (!JS_DefineProperty(aCx, paramsObj, "receivers", receiverArray, 0)) {
-    return false;
-  }
-
-  // attachments
-  JS::Rooted<JSObject*> attachmentArray(aCx, JS_NewArrayObject(aCx,
-                                                               aRequest.attachments().Length()));
-  for (uint32_t i = 0; i < aRequest.attachments().Length(); i++) {
-    JS::Rooted<JSObject*> obj(aCx,
-      MmsAttachmentDataToJSObject(aCx, aRequest.attachments().ElementAt(i)));
-    NS_ENSURE_TRUE(obj, false);
-    if (!JS_DefineElement(aCx, attachmentArray, i, obj, JSPROP_ENUMERATE)) {
-      return false;
-    }
-  }
-
-  if (!JS_DefineProperty(aCx, paramsObj, "attachments", attachmentArray, 0)) {
-    return false;
-  }
-
-  aParam->setObject(*paramsObj);
-  return true;
-}
-
-static bool
-GetMobileMessageDataFromMessage(ContentParent* aParent,
-                                nsISupports *aMsg,
-                                MobileMessageData &aData)
-{
-  if (!aMsg) {
-    NS_WARNING("Invalid message to convert!");
-    return false;
-  }
-
-  nsCOMPtr<nsIMmsMessage> mmsMsg = do_QueryInterface(aMsg);
-  if (mmsMsg) {
-    if (!aParent) {
-      NS_ERROR("Invalid ContentParent to convert MMS Message!");
-      return false;
-    }
-    MmsMessageData data;
-    if (!static_cast<MmsMessageInternal*>(mmsMsg.get())->GetData(aParent, data)) {
-      return false;
-    }
-    aData = data;
-    return true;
-  }
-
-  nsCOMPtr<nsISmsMessage> smsMsg = do_QueryInterface(aMsg);
-  if (smsMsg) {
-    aData = static_cast<SmsMessageInternal*>(smsMsg.get())->GetData();
-    return true;
-  }
-
-  NS_WARNING("Cannot get MobileMessageData");
-  return false;
-}
-
-NS_IMPL_ISUPPORTS(SmsParent, nsIObserver)
-
-SmsParent::SmsParent()
-{
-  MOZ_COUNT_CTOR(SmsParent);
-  nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
-  if (!obs) {
-    return;
-  }
-
-  obs->AddObserver(this, kSmsReceivedObserverTopic, false);
-  obs->AddObserver(this, kSmsRetrievingObserverTopic, false);
-  obs->AddObserver(this, kSmsSendingObserverTopic, false);
-  obs->AddObserver(this, kSmsSentObserverTopic, false);
-  obs->AddObserver(this, kSmsFailedObserverTopic, false);
-  obs->AddObserver(this, kSmsDeliverySuccessObserverTopic, false);
-  obs->AddObserver(this, kSmsDeliveryErrorObserverTopic, false);
-  obs->AddObserver(this, kSilentSmsReceivedObserverTopic, false);
-  obs->AddObserver(this, kSmsReadSuccessObserverTopic, false);
-  obs->AddObserver(this, kSmsReadErrorObserverTopic, false);
-  obs->AddObserver(this, kSmsDeletedObserverTopic, false);
-}
-
-void
-SmsParent::ActorDestroy(ActorDestroyReason why)
-{
-  nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
-  if (!obs) {
-    return;
-  }
-
-  obs->RemoveObserver(this, kSmsReceivedObserverTopic);
-  obs->RemoveObserver(this, kSmsRetrievingObserverTopic);
-  obs->RemoveObserver(this, kSmsSendingObserverTopic);
-  obs->RemoveObserver(this, kSmsSentObserverTopic);
-  obs->RemoveObserver(this, kSmsFailedObserverTopic);
-  obs->RemoveObserver(this, kSmsDeliverySuccessObserverTopic);
-  obs->RemoveObserver(this, kSmsDeliveryErrorObserverTopic);
-  obs->RemoveObserver(this, kSilentSmsReceivedObserverTopic);
-  obs->RemoveObserver(this, kSmsReadSuccessObserverTopic);
-  obs->RemoveObserver(this, kSmsReadErrorObserverTopic);
-  obs->RemoveObserver(this, kSmsDeletedObserverTopic);
-}
-
-NS_IMETHODIMP
-SmsParent::Observe(nsISupports* aSubject, const char* aTopic,
-                   const char16_t* aData)
-{
-  ContentParent *parent = static_cast<ContentParent*>(Manager());
-
-  if (!strcmp(aTopic, kSmsReceivedObserverTopic)) {
-    MobileMessageData msgData;
-    if (!GetMobileMessageDataFromMessage(parent, aSubject, msgData)) {
-      NS_ERROR("Got a 'sms-received' topic without a valid message!");
-      return NS_OK;
-    }
-
-    Unused << SendNotifyReceivedMessage(msgData);
-    return NS_OK;
-  }
-
-  if (!strcmp(aTopic, kSmsRetrievingObserverTopic)) {
-    MobileMessageData msgData;
-    if (!GetMobileMessageDataFromMessage(parent, aSubject, msgData)) {
-      NS_ERROR("Got a 'sms-retrieving' topic without a valid message!");
-      return NS_OK;
-    }
-
-    Unused << SendNotifyRetrievingMessage(msgData);
-    return NS_OK;
-  }
-
-  if (!strcmp(aTopic, kSmsSendingObserverTopic)) {
-    MobileMessageData msgData;
-    if (!GetMobileMessageDataFromMessage(parent, aSubject, msgData)) {
-      NS_ERROR("Got a 'sms-sending' topic without a valid message!");
-      return NS_OK;
-    }
-
-    Unused << SendNotifySendingMessage(msgData);
-    return NS_OK;
-  }
-
-  if (!strcmp(aTopic, kSmsSentObserverTopic)) {
-    MobileMessageData msgData;
-    if (!GetMobileMessageDataFromMessage(parent, aSubject, msgData)) {
-      NS_ERROR("Got a 'sms-sent' topic without a valid message!");
-      return NS_OK;
-    }
-
-    Unused << SendNotifySentMessage(msgData);
-    return NS_OK;
-  }
-
-  if (!strcmp(aTopic, kSmsFailedObserverTopic)) {
-    MobileMessageData msgData;
-    if (!GetMobileMessageDataFromMessage(parent, aSubject, msgData)) {
-      NS_ERROR("Got a 'sms-failed' topic without a valid message!");
-      return NS_OK;
-    }
-
-    Unused << SendNotifyFailedMessage(msgData);
-    return NS_OK;
-  }
-
-  if (!strcmp(aTopic, kSmsDeliverySuccessObserverTopic)) {
-    MobileMessageData msgData;
-    if (!GetMobileMessageDataFromMessage(parent, aSubject, msgData)) {
-      NS_ERROR("Got a 'sms-sending' topic without a valid message!");
-      return NS_OK;
-    }
-
-    Unused << SendNotifyDeliverySuccessMessage(msgData);
-    return NS_OK;
-  }
-
-  if (!strcmp(aTopic, kSmsDeliveryErrorObserverTopic)) {
-    MobileMessageData msgData;
-    if (!GetMobileMessageDataFromMessage(parent, aSubject, msgData)) {
-      NS_ERROR("Got a 'sms-delivery-error' topic without a valid message!");
-      return NS_OK;
-    }
-
-    Unused << SendNotifyDeliveryErrorMessage(msgData);
-    return NS_OK;
-  }
-
-  if (!strcmp(aTopic, kSilentSmsReceivedObserverTopic)) {
-    nsCOMPtr<nsISmsMessage> smsMsg = do_QueryInterface(aSubject);
-    if (!smsMsg) {
-      return NS_OK;
-    }
-
-    nsString sender;
-    if (NS_FAILED(smsMsg->GetSender(sender)) ||
-        !mSilentNumbers.Contains(sender)) {
-      return NS_OK;
-    }
-
-    MobileMessageData msgData =
-      static_cast<SmsMessageInternal*>(smsMsg.get())->GetData();
-    Unused << SendNotifyReceivedSilentMessage(msgData);
-    return NS_OK;
-  }
-
-  if (!strcmp(aTopic, kSmsReadSuccessObserverTopic)) {
-    MobileMessageData msgData;
-    if (!GetMobileMessageDataFromMessage(parent, aSubject, msgData)) {
-      NS_ERROR("Got a 'sms-read-success' topic without a valid message!");
-      return NS_OK;
-    }
-
-    Unused << SendNotifyReadSuccessMessage(msgData);
-    return NS_OK;
-  }
-
-  if (!strcmp(aTopic, kSmsReadErrorObserverTopic)) {
-    MobileMessageData msgData;
-    if (!GetMobileMessageDataFromMessage(parent, aSubject, msgData)) {
-      NS_ERROR("Got a 'sms-read-error' topic without a valid message!");
-      return NS_OK;
-    }
-
-    Unused << SendNotifyReadErrorMessage(msgData);
-    return NS_OK;
-  }
-
-  if (!strcmp(aTopic, kSmsDeletedObserverTopic)) {
-    nsCOMPtr<nsIDeletedMessageInfo> deletedInfo = do_QueryInterface(aSubject);
-    if (!deletedInfo) {
-      NS_ERROR("Got a 'sms-deleted' topic without a valid message!");
-      return NS_OK;
-    }
-
-    Unused << SendNotifyDeletedMessageInfo(
-      static_cast<DeletedMessageInfo*>(deletedInfo.get())->GetData());
-    return NS_OK;
-  }
-
-  return NS_OK;
-}
-
-bool
-SmsParent::RecvAddSilentNumber(const nsString& aNumber)
-{
-  if (mSilentNumbers.Contains(aNumber)) {
-    return true;
-  }
-
-  nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
-  NS_ENSURE_TRUE(smsService, true);
-
-  nsresult rv = smsService->AddSilentNumber(aNumber);
-  if (NS_SUCCEEDED(rv)) {
-    mSilentNumbers.AppendElement(aNumber);
-  }
-
-  return true;
-}
-
-bool
-SmsParent::RecvRemoveSilentNumber(const nsString& aNumber)
-{
-  if (!mSilentNumbers.Contains(aNumber)) {
-    return true;
-  }
-
-  nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
-  NS_ENSURE_TRUE(smsService, true);
-
-  nsresult rv = smsService->RemoveSilentNumber(aNumber);
-  if (NS_SUCCEEDED(rv)) {
-    mSilentNumbers.RemoveElement(aNumber);
-  }
-
-  return true;
-}
-
-bool
-SmsParent::RecvPSmsRequestConstructor(PSmsRequestParent* aActor,
-                                      const IPCSmsRequest& aRequest)
-{
-  SmsRequestParent* actor = static_cast<SmsRequestParent*>(aActor);
-
-  switch (aRequest.type()) {
-    case IPCSmsRequest::TSendMessageRequest:
-      return actor->DoRequest(aRequest.get_SendMessageRequest());
-    case IPCSmsRequest::TRetrieveMessageRequest:
-      return actor->DoRequest(aRequest.get_RetrieveMessageRequest());
-    case IPCSmsRequest::TGetMessageRequest:
-      return actor->DoRequest(aRequest.get_GetMessageRequest());
-    case IPCSmsRequest::TDeleteMessageRequest:
-      return actor->DoRequest(aRequest.get_DeleteMessageRequest());
-    case IPCSmsRequest::TMarkMessageReadRequest:
-      return actor->DoRequest(aRequest.get_MarkMessageReadRequest());
-    case IPCSmsRequest::TGetSegmentInfoForTextRequest:
-      return actor->DoRequest(aRequest.get_GetSegmentInfoForTextRequest());
-    case IPCSmsRequest::TGetSmscAddressRequest:
-      return actor->DoRequest(aRequest.get_GetSmscAddressRequest());
-    case IPCSmsRequest::TSetSmscAddressRequest:
-      return actor->DoRequest(aRequest.get_SetSmscAddressRequest());
-    default:
-      MOZ_CRASH("Unknown type!");
-  }
-
-  return false;
-}
-
-PSmsRequestParent*
-SmsParent::AllocPSmsRequestParent(const IPCSmsRequest& aRequest)
-{
-  SmsRequestParent* actor = new SmsRequestParent();
-  // Add an extra ref for IPDL. Will be released in
-  // SmsParent::DeallocPSmsRequestParent().
-  actor->AddRef();
-
-  return actor;
-}
-
-bool
-SmsParent::DeallocPSmsRequestParent(PSmsRequestParent* aActor)
-{
-  // SmsRequestParent is refcounted, must not be freed manually.
-  static_cast<SmsRequestParent*>(aActor)->Release();
-  return true;
-}
-
-bool
-SmsParent::RecvPMobileMessageCursorConstructor(PMobileMessageCursorParent* aActor,
-                                               const IPCMobileMessageCursor& aRequest)
-{
-  MobileMessageCursorParent* actor =
-    static_cast<MobileMessageCursorParent*>(aActor);
-
-  switch (aRequest.type()) {
-    case IPCMobileMessageCursor::TCreateMessageCursorRequest:
-      return actor->DoRequest(aRequest.get_CreateMessageCursorRequest());
-    case IPCMobileMessageCursor::TCreateThreadCursorRequest:
-      return actor->DoRequest(aRequest.get_CreateThreadCursorRequest());
-    default:
-      MOZ_CRASH("Unknown type!");
-  }
-
-  return false;
-}
-
-PMobileMessageCursorParent*
-SmsParent::AllocPMobileMessageCursorParent(const IPCMobileMessageCursor& aRequest)
-{
-  MobileMessageCursorParent* actor = new MobileMessageCursorParent();
-  // Add an extra ref for IPDL. Will be released in
-  // SmsParent::DeallocPMobileMessageCursorParent().
-  actor->AddRef();
-
-  return actor;
-}
-
-bool
-SmsParent::DeallocPMobileMessageCursorParent(PMobileMessageCursorParent* aActor)
-{
-  // MobileMessageCursorParent is refcounted, must not be freed manually.
-  static_cast<MobileMessageCursorParent*>(aActor)->Release();
-  return true;
-}
-
-/*******************************************************************************
- * SmsRequestParent
- ******************************************************************************/
-
-NS_IMPL_ISUPPORTS(SmsRequestParent, nsIMobileMessageCallback)
-
-void
-SmsRequestParent::ActorDestroy(ActorDestroyReason aWhy)
-{
-  mActorDestroyed = true;
-}
-
-bool
-SmsRequestParent::DoRequest(const SendMessageRequest& aRequest)
-{
-  switch(aRequest.type()) {
-  case SendMessageRequest::TSendSmsMessageRequest: {
-      nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
-      NS_ENSURE_TRUE(smsService, true);
-
-      const SendSmsMessageRequest &req = aRequest.get_SendSmsMessageRequest();
-      smsService->Send(req.serviceId(), req.number(), req.message(),
-                       req.silent(), this);
-    }
-    break;
-  case SendMessageRequest::TSendMmsMessageRequest: {
-      nsCOMPtr<nsIMmsService> mmsService = do_GetService(MMS_SERVICE_CONTRACTID);
-      NS_ENSURE_TRUE(mmsService, true);
-
-      // There are cases (see bug 981202) where this is called with no JS on the
-      // stack. And since mmsService might be JS-Implemented, we need to pass a
-      // jsval to ::Send. Only system code should be looking at the result here,
-      // so we just create it in the System-Principaled Junk Scope.
-      AutoJSContext cx;
-      JSAutoCompartment ac(cx, xpc::PrivilegedJunkScope());
-      JS::Rooted<JS::Value> params(cx);
-      const SendMmsMessageRequest &req = aRequest.get_SendMmsMessageRequest();
-      if (!GetParamsFromSendMmsMessageRequest(cx,
-                                              req,
-                                              params.address())) {
-        NS_WARNING("SmsRequestParent: Fail to build MMS params.");
-        return true;
-      }
-      mmsService->Send(req.serviceId(), params, this);
-    }
-    break;
-  default:
-    MOZ_CRASH("Unknown type of SendMessageRequest!");
-  }
-  return true;
-}
-
-bool
-SmsRequestParent::DoRequest(const RetrieveMessageRequest& aRequest)
-{
-  nsresult rv = NS_ERROR_FAILURE;
-
-  nsCOMPtr<nsIMmsService> mmsService = do_GetService(MMS_SERVICE_CONTRACTID);
-  if (mmsService) {
-    rv = mmsService->Retrieve(aRequest.messageId(), this);
-  }
-
-  if (NS_FAILED(rv)) {
-    return NS_SUCCEEDED(NotifyGetMessageFailed(nsIMobileMessageCallback::INTERNAL_ERROR));
-  }
-
-  return true;
-}
-
-bool
-SmsRequestParent::DoRequest(const GetMessageRequest& aRequest)
-{
-  nsresult rv = NS_ERROR_FAILURE;
-
-  nsCOMPtr<nsIMobileMessageDatabaseService> dbService =
-    do_GetService(MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
-  if (dbService) {
-    rv = dbService->GetMessageMoz(aRequest.messageId(), this);
-  }
-
-  if (NS_FAILED(rv)) {
-    return NS_SUCCEEDED(NotifyGetMessageFailed(nsIMobileMessageCallback::INTERNAL_ERROR));
-  }
-
-  return true;
-}
-
-bool
-SmsRequestParent::DoRequest(const GetSmscAddressRequest& aRequest)
-{
-  nsresult rv = NS_ERROR_FAILURE;
-
-  nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
-  if (smsService) {
-    rv = smsService->GetSmscAddress(aRequest.serviceId(), this);
-  }
-
-  if (NS_FAILED(rv)) {
-    return NS_SUCCEEDED(NotifyGetSmscAddressFailed(nsIMobileMessageCallback::INTERNAL_ERROR));
-  }
-
-  return true;
-}
-
-bool
-SmsRequestParent::DoRequest(const SetSmscAddressRequest& aRequest)
-{
-  nsresult rv = NS_ERROR_FAILURE;
-
-  nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
-  if (smsService) {
-    rv = smsService->SetSmscAddress(aRequest.serviceId(),
-                                    aRequest.number(),
-                                    aRequest.typeOfNumber(),
-                                    aRequest.numberPlanIdentification(),
-                                    this);
-  } else {
-    return NS_SUCCEEDED(NotifySetSmscAddressFailed(nsIMobileMessageCallback::INTERNAL_ERROR));
-  }
-
-  if (NS_FAILED(rv)) {
-    return NS_SUCCEEDED(NotifySetSmscAddressFailed(nsIMobileMessageCallback::INTERNAL_ERROR));
-  }
-
-  return true;
-}
-
-bool
-SmsRequestParent::DoRequest(const DeleteMessageRequest& aRequest)
-{
-  nsresult rv = NS_ERROR_FAILURE;
-
-  nsCOMPtr<nsIMobileMessageDatabaseService> dbService =
-    do_GetService(MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
-  if (dbService) {
-    const InfallibleTArray<int32_t>& messageIds = aRequest.messageIds();
-    rv = dbService->DeleteMessage(const_cast<int32_t *>(messageIds.Elements()),
-                                  messageIds.Length(), this);
-  }
-
-  if (NS_FAILED(rv)) {
-    return NS_SUCCEEDED(NotifyDeleteMessageFailed(nsIMobileMessageCallback::INTERNAL_ERROR));
-  }
-
-  return true;
-}
-
-bool
-SmsRequestParent::DoRequest(const MarkMessageReadRequest& aRequest)
-{
-  nsresult rv = NS_ERROR_FAILURE;
-
-  nsCOMPtr<nsIMobileMessageDatabaseService> dbService =
-    do_GetService(MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
-  if (dbService) {
-    rv = dbService->MarkMessageRead(aRequest.messageId(), aRequest.value(),
-                                    aRequest.sendReadReport(), this);
-  }
-
-  if (NS_FAILED(rv)) {
-    return NS_SUCCEEDED(NotifyMarkMessageReadFailed(nsIMobileMessageCallback::INTERNAL_ERROR));
-  }
-
-  return true;
-}
-
-bool
-SmsRequestParent::DoRequest(const GetSegmentInfoForTextRequest& aRequest)
-{
-  nsresult rv = NS_ERROR_FAILURE;
-
-  nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
-  if (smsService) {
-    rv = smsService->GetSegmentInfoForText(aRequest.text(), this);
-  }
-
-  if (NS_FAILED(rv)) {
-    return NS_SUCCEEDED(NotifyGetSegmentInfoForTextFailed(
-                          nsIMobileMessageCallback::INTERNAL_ERROR));
-  }
-
-  return true;
-}
-
-nsresult
-SmsRequestParent::SendReply(const MessageReply& aReply)
-{
-  // The child process could die before this asynchronous notification, in which
-  // case ActorDestroy() was called and mActorDestroyed is set to true. Return
-  // an error here to avoid sending a message to the dead process.
-  NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
-  return Send__delete__(this, aReply) ? NS_OK : NS_ERROR_FAILURE;
-}
-
-// nsIMobileMessageCallback
-
-NS_IMETHODIMP
-SmsRequestParent::NotifyMessageSent(nsISupports *aMessage)
-{
-  NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
-  ContentParent *parent = static_cast<ContentParent*>(Manager()->Manager());
-  MobileMessageData data;
-  if (GetMobileMessageDataFromMessage(parent, aMessage, data)) {
-    return SendReply(ReplyMessageSend(data));
-  }
-
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifySendMessageFailed(int32_t aError, nsISupports *aMessage)
-{
-  NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
-  ContentParent *parent = static_cast<ContentParent*>(Manager()->Manager());
-  MobileMessageData data;
-  if (!GetMobileMessageDataFromMessage(parent, aMessage, data)) {
-    return SendReply(ReplyMessageSendFail(aError, OptionalMobileMessageData(void_t())));
-  }
-
-  return SendReply(ReplyMessageSendFail(aError, OptionalMobileMessageData(data)));
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifyMessageGot(nsISupports *aMessage)
-{
-  NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
-  ContentParent *parent = static_cast<ContentParent*>(Manager()->Manager());
-  MobileMessageData data;
-  if (GetMobileMessageDataFromMessage(parent, aMessage, data)) {
-    return SendReply(ReplyGetMessage(data));
-  }
-
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifyGetMessageFailed(int32_t aError)
-{
-  return SendReply(ReplyGetMessageFail(aError));
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifyMessageDeleted(bool *aDeleted, uint32_t aSize)
-{
-  ReplyMessageDelete data;
-  data.deleted().AppendElements(aDeleted, aSize);
-  return SendReply(data);
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifyDeleteMessageFailed(int32_t aError)
-{
-  return SendReply(ReplyMessageDeleteFail(aError));
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifyMessageMarkedRead(bool aRead)
-{
-  return SendReply(ReplyMarkeMessageRead(aRead));
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifyMarkMessageReadFailed(int32_t aError)
-{
-  return SendReply(ReplyMarkeMessageReadFail(aError));
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifySegmentInfoForTextGot(int32_t aSegments,
-                                              int32_t aCharsPerSegment,
-                                              int32_t aCharsAvailableInLastSegment)
-{
-  return SendReply(ReplyGetSegmentInfoForText(aSegments,
-                                              aCharsPerSegment,
-                                              aCharsAvailableInLastSegment));
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifyGetSegmentInfoForTextFailed(int32_t aError)
-{
-  return SendReply(ReplyGetSegmentInfoForTextFail(aError));
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifyGetSmscAddress(const nsAString& aSmscAddress,
-                                       uint32_t aTypeOfNumber,
-                                       uint32_t aNumberPlanIdentification)
-{
-  return SendReply(ReplyGetSmscAddress(nsString(aSmscAddress),
-                                       aTypeOfNumber,
-                                       aNumberPlanIdentification));
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifyGetSmscAddressFailed(int32_t aError)
-{
-  return SendReply(ReplyGetSmscAddressFail(aError));
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifySetSmscAddress()
-{
-  return SendReply(ReplySetSmscAddress());
-}
-
-NS_IMETHODIMP
-SmsRequestParent::NotifySetSmscAddressFailed(int32_t aError)
-{
-  return SendReply(ReplySetSmscAddressFail(aError));
-}
-
-/*******************************************************************************
- * MobileMessageCursorParent
- ******************************************************************************/
-
-NS_IMPL_ISUPPORTS(MobileMessageCursorParent, nsIMobileMessageCursorCallback)
-
-void
-MobileMessageCursorParent::ActorDestroy(ActorDestroyReason aWhy)
-{
-  // Two possible scenarios here:
-  // 1) When parent fails to SendNotifyResult() in NotifyCursorResult(), it's
-  //    destroyed without nulling out mContinueCallback.
-  // 2) When parent dies normally, mContinueCallback should have been cleared in
-  //    NotifyCursorError(), but just ensure this again.
-  mContinueCallback = nullptr;
-}
-
-bool
-MobileMessageCursorParent::RecvContinue()
-{
-  MOZ_ASSERT(mContinueCallback);
-
-  if (NS_FAILED(mContinueCallback->HandleContinue())) {
-    return NS_SUCCEEDED(NotifyCursorError(nsIMobileMessageCallback::INTERNAL_ERROR));
-  }
-
-  return true;
-}
-
-bool
-MobileMessageCursorParent::DoRequest(const CreateMessageCursorRequest& aRequest)
-{
-  nsresult rv = NS_ERROR_FAILURE;
-
-  nsCOMPtr<nsIMobileMessageDatabaseService> dbService =
-    do_GetService(MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
-  if (dbService) {
-    const SmsFilterData& filter = aRequest.filter();
-
-    const nsTArray<nsString>& numbers = filter.numbers();
-    UniquePtr<const char16_t*[]> ptrNumbers;
-    uint32_t numbersCount = numbers.Length();
-    if (numbersCount) {
-      uint32_t index;
-
-      ptrNumbers = MakeUnique<const char16_t*[]>(numbersCount);
-      for (index = 0; index < numbersCount; index++) {
-        ptrNumbers[index] = numbers[index].get();
-      }
-    }
-
-    rv = dbService->CreateMessageCursor(filter.hasStartDate(),
-                                        filter.startDate(),
-                                        filter.hasEndDate(),
-                                        filter.endDate(),
-                                        ptrNumbers.get(), numbersCount,
-                                        filter.delivery(),
-                                        filter.hasRead(),
-                                        filter.read(),
-                                        filter.hasThreadId(),
-                                        filter.threadId(),
-                                        aRequest.reverse(),
-                                        this,
-                                        getter_AddRefs(mContinueCallback));
-  }
-
-  if (NS_FAILED(rv)) {
-    return NS_SUCCEEDED(NotifyCursorError(nsIMobileMessageCallback::INTERNAL_ERROR));
-  }
-
-  return true;
-}
-
-bool
-MobileMessageCursorParent::DoRequest(const CreateThreadCursorRequest& aRequest)
-{
-  nsresult rv = NS_ERROR_FAILURE;
-
-  nsCOMPtr<nsIMobileMessageDatabaseService> dbService =
-    do_GetService(MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
-  if (dbService) {
-    rv = dbService->CreateThreadCursor(this,
-                                       getter_AddRefs(mContinueCallback));
-  }
-
-  if (NS_FAILED(rv)) {
-    return NS_SUCCEEDED(NotifyCursorError(nsIMobileMessageCallback::INTERNAL_ERROR));
-  }
-
-  return true;
-}
-
-// nsIMobileMessageCursorCallback
-
-NS_IMETHODIMP
-MobileMessageCursorParent::NotifyCursorError(int32_t aError)
-{
-  // The child process could die before this asynchronous notification, in which
-  // case ActorDestroy() was called and mContinueCallback is now null. Return an
-  // error here to avoid sending a message to the dead process.
-  NS_ENSURE_TRUE(mContinueCallback, NS_ERROR_FAILURE);
-
-  mContinueCallback = nullptr;
-
-  return Send__delete__(this, aError) ? NS_OK : NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-MobileMessageCursorParent::NotifyCursorResult(nsISupports** aResults,
-                                              uint32_t aSize)
-{
-  MOZ_ASSERT(aResults && *aResults && aSize);
-
-  // The child process could die before this asynchronous notification, in which
-  // case ActorDestroy() was called and mContinueCallback is now null. Return an
-  // error here to avoid sending a message to the dead process.
-  NS_ENSURE_TRUE(mContinueCallback, NS_ERROR_FAILURE);
-
-  nsCOMPtr<nsIMobileMessageThread> iThread =
-    do_QueryInterface(aResults[0]);
-  if (iThread) {
-    nsTArray<ThreadData> threads;
-
-    for (uint32_t i = 0; i < aSize; i++) {
-      nsCOMPtr<nsIMobileMessageThread> iThread =
-        do_QueryInterface(aResults[i]);
-      NS_ENSURE_TRUE(iThread, NS_ERROR_FAILURE);
-
-      MobileMessageThreadInternal* thread =
-        static_cast<MobileMessageThreadInternal*>(iThread.get());
-      threads.AppendElement(thread->GetData());
-    }
-
-    return SendNotifyResult(MobileMessageCursorData(ThreadArrayData(threads)))
-      ? NS_OK : NS_ERROR_FAILURE;
-  }
-
-  ContentParent* parent = static_cast<ContentParent*>(Manager()->Manager());
-  nsTArray<MobileMessageData> messages;
-  for (uint32_t i = 0; i < aSize; i++) {
-    nsCOMPtr<nsISmsMessage> sms = do_QueryInterface(aResults[i]);
-    if (sms) {
-      messages.AppendElement(
-        static_cast<SmsMessageInternal*>(sms.get())->GetData());
-      continue;
-    }
-
-    nsCOMPtr<nsIMmsMessage> mms = do_QueryInterface(aResults[i]);
-    if (mms) {
-      MmsMessageData mmsData;
-      NS_ENSURE_TRUE(
-        static_cast<MmsMessageInternal*>(mms.get())->GetData(parent, mmsData),
-        NS_ERROR_FAILURE
-      );
-      messages.AppendElement(mmsData);
-      continue;
-    }
-
-    return NS_ERROR_FAILURE;
-  }
-
-  return SendNotifyResult(MobileMessageCursorData(MobileMessageArrayData(messages)))
-    ? NS_OK : NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-MobileMessageCursorParent::NotifyCursorDone()
-{
-  return NotifyCursorError(nsIMobileMessageCallback::SUCCESS_NO_ERROR);
-}
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/mobilemessage/ipc/SmsParent.h
+++ /dev/null
@@ -1,167 +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_mobilemessage_SmsParent_h
-#define mozilla_dom_mobilemessage_SmsParent_h
-
-#include "mozilla/dom/mobilemessage/PSmsParent.h"
-#include "mozilla/dom/mobilemessage/PSmsRequestParent.h"
-#include "mozilla/dom/mobilemessage/PMobileMessageCursorParent.h"
-#include "nsIDOMDOMCursor.h"
-#include "nsIMobileMessageCallback.h"
-#include "nsIMobileMessageCursorCallback.h"
-#include "nsIObserver.h"
-
-namespace mozilla {
-namespace dom {
-
-class ContentParent;
-
-namespace mobilemessage {
-
-class SmsParent : public PSmsParent
-                , public nsIObserver
-{
-  friend class mozilla::dom::ContentParent;
-
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIOBSERVER
-
-protected:
-  virtual bool
-  RecvAddSilentNumber(const nsString& aNumber) override;
-
-  virtual bool
-  RecvRemoveSilentNumber(const nsString& aNumber) override;
-
-  SmsParent();
-  virtual ~SmsParent()
-  {
-    MOZ_COUNT_DTOR(SmsParent);
-  }
-
-  virtual void
-  ActorDestroy(ActorDestroyReason aWhy) override;
-
-  virtual bool
-  RecvPSmsRequestConstructor(PSmsRequestParent* aActor,
-                             const IPCSmsRequest& aRequest) override;
-
-  virtual PSmsRequestParent*
-  AllocPSmsRequestParent(const IPCSmsRequest& aRequest) override;
-
-  virtual bool
-  DeallocPSmsRequestParent(PSmsRequestParent* aActor) override;
-
-  virtual bool
-  RecvPMobileMessageCursorConstructor(PMobileMessageCursorParent* aActor,
-                                      const IPCMobileMessageCursor& aCursor) override;
-
-  virtual PMobileMessageCursorParent*
-  AllocPMobileMessageCursorParent(const IPCMobileMessageCursor& aCursor) override;
-
-  virtual bool
-  DeallocPMobileMessageCursorParent(PMobileMessageCursorParent* aActor) override;
-
-private:
-  nsTArray<nsString> mSilentNumbers;
-};
-
-class SmsRequestParent : public PSmsRequestParent
-                       , public nsIMobileMessageCallback
-{
-  friend class SmsParent;
-
-  bool mActorDestroyed;
-
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIMOBILEMESSAGECALLBACK
-
-protected:
-  SmsRequestParent()
-    : mActorDestroyed(false)
-  {
-    MOZ_COUNT_CTOR(SmsRequestParent);
-  }
-
-  virtual ~SmsRequestParent()
-  {
-    MOZ_COUNT_DTOR(SmsRequestParent);
-  }
-
-  virtual void
-  ActorDestroy(ActorDestroyReason aWhy) override;
-
-  bool
-  DoRequest(const SendMessageRequest& aRequest);
-
-  bool
-  DoRequest(const RetrieveMessageRequest& aRequest);
-
-  bool
-  DoRequest(const GetMessageRequest& aRequest);
-
-  bool
-  DoRequest(const DeleteMessageRequest& aRequest);
-
-  bool
-  DoRequest(const MarkMessageReadRequest& aRequest);
-
-  bool
-  DoRequest(const GetSegmentInfoForTextRequest& aRequest);
-
-  bool
-  DoRequest(const GetSmscAddressRequest& aRequest);
-
-  bool
-  DoRequest(const SetSmscAddressRequest& aRequest);
-
-  nsresult
-  SendReply(const MessageReply& aReply);
-};
-
-class MobileMessageCursorParent : public PMobileMessageCursorParent
-                                , public nsIMobileMessageCursorCallback
-{
-  friend class SmsParent;
-
-  nsCOMPtr<nsICursorContinueCallback> mContinueCallback;
-
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIMOBILEMESSAGECURSORCALLBACK
-
-protected:
-  MobileMessageCursorParent()
-  {
-    MOZ_COUNT_CTOR(MobileMessageCursorParent);
-  }
-
-  virtual ~MobileMessageCursorParent()
-  {
-    MOZ_COUNT_DTOR(MobileMessageCursorParent);
-  }
-
-  virtual void
-  ActorDestroy(ActorDestroyReason aWhy) override;
-
-  virtual bool
-  RecvContinue() override;
-
-  bool
-  DoRequest(const CreateMessageCursorRequest& aRequest);
-
-  bool
-  DoRequest(const CreateThreadCursorRequest& aRequest);
-};
-
-} // namespace mobilemessage
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_mobilemessage_SmsParent_h
deleted file mode 100644
--- a/dom/mobilemessage/ipc/SmsTypes.ipdlh
+++ /dev/null
@@ -1,127 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* vim: set 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/. */
-
-include protocol PBlob;
-
-using DeliveryState from "mozilla/dom/mobilemessage/Types.h";
-using DeliveryStatus from "mozilla/dom/mobilemessage/Types.h";
-using MessageClass from "mozilla/dom/mobilemessage/Types.h";
-using ReadStatus from "mozilla/dom/mobilemessage/Types.h";
-using ReadState from "mozilla/dom/mobilemessage/Types.h";
-using MessageType from "mozilla/dom/mobilemessage/Types.h";
-
-namespace mozilla {
-namespace dom {
-namespace mobilemessage {
-
-struct SmsMessageData
-{
-  int32_t        id;
-  uint64_t       threadId;
-  nsString       iccId;
-  DeliveryState  delivery;
-  DeliveryStatus deliveryStatus;
-  nsString       sender;
-  nsString       receiver;
-  nsString       body;
-  MessageClass   messageClass;
-  uint64_t       timestamp;         // ms since epoch.
-  uint64_t       sentTimestamp;     // ms since epoch.
-  uint64_t       deliveryTimestamp; // ms since epoch.
-  bool           read;
-};
-
-struct MmsAttachmentData
-{
-  nsString id;
-  nsString location;
-  PBlob content;
-};
-
-struct MmsDeliveryInfoData
-{
-  nsString        receiver;
-  DeliveryStatus  deliveryStatus;
-  uint64_t        deliveryTimestamp;
-  ReadStatus      readStatus;
-  uint64_t        readTimestamp;
-};
-
-struct MmsMessageData
-{
-  int32_t               id;
-  uint64_t              threadId;
-  nsString              iccId;
-  DeliveryState         delivery;
-  MmsDeliveryInfoData[] deliveryInfo;
-  nsString              sender;
-  nsString[]            receivers;
-  uint64_t              timestamp;     // ms since epoch.
-  uint64_t              sentTimestamp; // ms since epoch.
-  bool                  read;
-  nsString              subject;
-  nsString              smil;
-  MmsAttachmentData[]   attachments;
-  uint64_t              expiryDate;    // ms since epoch.
-  bool                  readReportRequested;
-};
-
-union MobileMessageData
-{
-  MmsMessageData;
-  SmsMessageData;
-};
-
-struct SmsFilterData
-{
-  bool          hasStartDate;
-  uint64_t      startDate;
-  bool          hasEndDate;
-  uint64_t      endDate;
-  nsString[]    numbers;
-  nsString      delivery;
-  bool          hasRead;
-  bool          read;
-  bool          hasThreadId;
-  uint64_t      threadId;
-};
-
-struct ThreadData
-{
-  uint64_t    id;
-  nsString[]  participants;
-  uint64_t    timestamp;
-  nsString    lastMessageSubject;
-  nsString    body;
-  uint64_t    unreadCount;
-  MessageType lastMessageType;
-};
-
-struct MobileMessageArrayData
-{
-  MobileMessageData[] messages;
-};
-
-struct ThreadArrayData
-{
-  ThreadData[] threads;
-};
-
-union MobileMessageCursorData
-{
-  MobileMessageArrayData;
-  ThreadArrayData;
-};
-
-struct DeletedMessageInfoData
-{
-  int32_t[] deletedMessageIds;
-  uint64_t[] deletedThreadIds;
-};
-
-}
-}
-}
deleted file mode 100644
--- a/dom/mobilemessage/moz.build
+++ /dev/null
@@ -1,91 +0,0 @@
-# -*- Mode: python; 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/.
-
-DIRS += ['interfaces']
-
-MOCHITEST_CHROME_MANIFESTS += ['tests/mochitest/chrome.ini']
-XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
-
-EXPORTS.mozilla.dom.mobilemessage += [
-    'Constants.h',            # Required by almost all cpp files
-    'ipc/SmsChild.h',
-    'ipc/SmsParent.h',
-    'Types.h',                # Required by IPDL SmsTypes.h
-]
-
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android' and CONFIG['MOZ_WEBSMS_BACKEND']:
-    SOURCES += [
-        'android/MobileMessageDatabaseService.cpp',
-        'android/SmsManager.cpp',
-        'android/SmsService.cpp',
-    ]
-elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' and CONFIG['MOZ_B2G_RIL']:
-    EXTRA_JS_MODULES += [
-        'gonk/mms_consts.js',
-        'gonk/MmsPduHelper.jsm',
-        'gonk/MobileMessageDB.jsm',
-        'gonk/SmsSegmentHelper.jsm',
-        'gonk/wap_consts.js',
-        'gonk/WspPduHelper.jsm',
-    ]
-    EXTRA_COMPONENTS += [
-        'gonk/MmsService.js',
-        'gonk/MmsService.manifest',
-        'gonk/MobileMessageDatabaseService.js',
-        'gonk/MobileMessageDatabaseService.manifest',
-    ]
-    if not CONFIG['DISABLE_MOZ_RIL_GEOLOC']:
-        EXTRA_COMPONENTS += [
-            'gonk/SmsService.js',
-            'gonk/SmsService.manifest',
-        ]
-
-EXPORTS.mozilla.dom += [
-    'DOMMobileMessageError.h',
-    'MmsMessage.h',
-    'MobileMessageManager.h',
-    'MobileMessageThread.h',
-    'SmsMessage.h',
-]
-
-UNIFIED_SOURCES += [
-    'Assertions.cpp',
-    'Constants.cpp',
-    'DeletedMessageInfo.cpp',
-    'DOMMobileMessageError.cpp',
-    'ipc/SmsChild.cpp',
-    'ipc/SmsIPCService.cpp',
-    'ipc/SmsParent.cpp',
-    'MmsMessage.cpp',
-    'MmsMessageInternal.cpp',
-    'MobileMessageCallback.cpp',
-    'MobileMessageCursorCallback.cpp',
-    'MobileMessageManager.cpp',
-    'MobileMessageService.cpp',
-    'MobileMessageThread.cpp',
-    'MobileMessageThreadInternal.cpp',
-    'SmsMessage.cpp',
-    'SmsMessageInternal.cpp',
-]
-
-IPDL_SOURCES += [
-    'ipc/PMobileMessageCursor.ipdl',
-    'ipc/PSms.ipdl',
-    'ipc/PSmsRequest.ipdl',
-    'ipc/SmsTypes.ipdlh',
-]
-
-LOCAL_INCLUDES += [
-    '/dom/base',
-    '/widget/android',
-]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FINAL_LIBRARY = 'xul'
-
-if CONFIG['GNU_CXX']:
-    CXXFLAGS += ['-Wno-error=shadow']
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/head.js
+++ /dev/null
@@ -1,722 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const {Cc: Cc, Ci: Ci, Cr: Cr, Cu: Cu} = SpecialPowers;
-
-// Emulate Promise.jsm semantics.
-Promise.defer = function() { return new Deferred(); }
-function Deferred()  {
-  this.promise = new Promise(function(resolve, reject) {
-    this.resolve = resolve;
-    this.reject = reject;
-  }.bind(this));
-  Object.freeze(this);
-}
-
-/**
- * Push a list of preference settings. Never reject.
- *
- * Fulfill params: (none)
- *
- * @param aPrefs
- *        An JS object.  For example:
- *
- *          {'set': [['foo.bar', 2], ['magic.pref', 'baz']],
- *           'clear': [['clear.this'], ['also.this']] };
- *
- * @return A deferred promise.
- */
-function pushPrefEnv(aPrefs) {
-  let deferred = Promise.defer();
-
-  SpecialPowers.pushPrefEnv(aPrefs, function() {
-    ok(true, "preferences pushed: " + JSON.stringify(aPrefs));
-    deferred.resolve();
-  });
-
-  return deferred.promise;
-}
-
-/**
- * Push required permissions and test if |navigator.mozMobileMessage| exists.
- * Resolve if it does, reject otherwise.
- *
- * Fulfill params:
- *   manager -- an reference to navigator.mozMobileMessage.
- *
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
-var manager;
-function ensureMobileMessage() {
-  let deferred = Promise.defer();
-
-  let permissions = [{
-    "type": "sms",
-    "allow": 1,
-    "context": document,
-  }];
-  SpecialPowers.pushPermissions(permissions, function() {
-    ok(true, "permissions pushed: " + JSON.stringify(permissions));
-
-    manager = window.navigator.mozMobileMessage;
-    if (manager) {
-      log("navigator.mozMobileMessage is instance of " + manager.constructor);
-    } else {
-      log("navigator.mozMobileMessage is undefined.");
-    }
-
-    if (manager instanceof MozMobileMessageManager) {
-      deferred.resolve(manager);
-    } else {
-      deferred.reject();
-    }
-  });
-
-  return deferred.promise;
-}
-
-/**
- * Push required permissions and test if |navigator.mozMobileConnections| exists.
- * Resolve if it does, reject otherwise.
- *
- * Fulfill params:
- *   manager -- an reference to navigator.mozMobileConnections.
- *
- * Reject params: (none)
- *
- * @param aServiceId [optional]
- *        A numeric DSDS service id. Default: 0.
- *
- * @return A deferred promise.
- */
-var mobileConnection;
-function ensureMobileConnection(aServiceId) {
-  return new Promise(function(resolve, reject) {
-    let permissions = [{
-      "type": "mobileconnection",
-      "allow": 1,
-      "context": document,
-    }];
-    SpecialPowers.pushPermissions(permissions, function() {
-      ok(true, "permissions pushed: " + JSON.stringify(permissions));
-
-      let serviceId = aServiceId || 0;
-      mobileConnection = window.navigator.mozMobileConnections[serviceId];
-      if (mobileConnection) {
-        log("navigator.mozMobileConnections[" + serviceId + "] is instance of " +
-            mobileConnection.constructor);
-      } else {
-        log("navigator.mozMobileConnections[" + serviceId + "] is undefined");
-      }
-
-      if (mobileConnection instanceof MozMobileConnection) {
-        resolve(mobileConnection);
-      } else {
-        reject();
-      }
-    });
-  });
-}
-
-/**
- * Wait for one named MobileMessageManager event.
- *
- * Resolve if that named event occurs.  Never reject.
- *
- * Fulfill params: the DOMEvent passed.
- *
- * @param aEventName
- *        A string event name.
- * @param aMatchFunc [optional]
- *        An additional callback function to match the interested event
- *        before removing the listener and going to resolve the promise.
- *
- * @return A deferred promise.
- */
-function waitForManagerEvent(aEventName, aMatchFunc) {
-  let deferred = Promise.defer();
-
-  manager.addEventListener(aEventName, function onevent(aEvent) {
-    if (aMatchFunc && !aMatchFunc(aEvent)) {
-      ok(true, "MobileMessageManager event '" + aEventName + "' got" +
-               " but is not interested.");
-      return;
-    }
-
-    ok(true, "MobileMessageManager event '" + aEventName + "' got.");
-    manager.removeEventListener(aEventName, onevent);
-    deferred.resolve(aEvent);
-  });
-
-  return deferred.promise;
-}
-
-/**
- * Send a SMS message to a single receiver.  Resolve if it succeeds, reject
- * otherwise.
- *
- * Fulfill params:
- *   message -- the sent SmsMessage.
- *
- * Reject params:
- *   error -- a DOMError.
- *
- * @param aReceiver the address of the receiver.
- * @param aText the text body of the message.
- *
- * @return A deferred promise.
- */
-function sendSmsWithSuccess(aReceiver, aText) {
-  return manager.send(aReceiver, aText);
-}
-
-/**
- * Send a SMS message to a single receiver.
- * Resolve if it fails, reject otherwise.
- *
- * Fulfill params:
- *   {
- *     message,  -- the failed MmsMessage
- *     error,    -- error of the send request
- *   }
- *
- * Reject params: (none)
- *
- * @param aReceiver the address of the receiver.
- * @param aText the text body of the message.
- *
- * @return A deferred promise.
- */
-function sendSmsWithFailure(aReceiver, aText) {
-  let promises = [];
-  promises.push(waitForManagerEvent("failed")
-    .then((aEvent) => { return aEvent.message; }));
-  promises.push(manager.send(aReceiver, aText)
-    .then((aResult) => { throw aResult; },
-          (aError) => { return aError; }));
-
-  return Promise.all(promises)
-    .then((aResults) => { return { message: aResults[0],
-                                   error: aResults[1] }; });
-}
-
-/**
- * Send a MMS message with specified parameters.  Resolve if it fails, reject
- * otherwise.
- *
- * Fulfill params:
- *   {
- *     message,  -- the failed MmsMessage
- *     error,    -- error of the send request
- *   }
- *
- * Reject params: (none)
- *
- * @param aMmsParameters a MmsParameters instance.
- *
- * @param aSendParameters a MmsSendParameters instance.
- *
- * @return A deferred promise.
- */
-function sendMmsWithFailure(aMmsParameters, aSendParameters) {
-  let promises = [];
-  promises.push(waitForManagerEvent("failed")
-    .then((aEvent) => { return aEvent.message; }));
-  promises.push(manager.sendMMS(aMmsParameters, aSendParameters)
-    .then((aResult) => { throw aResult; },
-          (aError) => { return aError; }));
-
-  return Promise.all(promises)
-    .then((aResults) => { return { message: aResults[0],
-                                   error: aResults[1] }; });
-}
-
-/**
- * Retrieve message by message id.
- *
- * Fulfill params: SmsMessage
- * Reject params:
- *   event -- a DOMEvent
- *
- * @param aId
- *        A numeric message id.
- *
- * @return A deferred promise.
- */
-function getMessage(aId) {
-  return manager.getMessage(aId);
-}
-
-/**
- * Retrieve messages from database.
- *
- * Fulfill params:
- *   messages -- an array of {Sms,Mms}Message instances.
- *
- * Reject params:
- *   event -- a DOMEvent
- *
- * @param aFilter [optional]
- *        A MobileMessageFilter object.
- * @param aReverse [optional]
- *        A boolean value indicating whether the order of the message should be
- *        reversed. Default: false.
- *
- * @return A deferred promise.
- */
-function getMessages(aFilter, aReverse) {
-  let deferred = Promise.defer();
-
-  let messages = [];
-  let cursor = manager.getMessages(aFilter, aReverse || false);
-  cursor.onsuccess = function(aEvent) {
-    if (cursor.result) {
-      messages.push(cursor.result);
-      cursor.continue();
-      return;
-    }
-
-    deferred.resolve(messages);
-  };
-  cursor.onerror = deferred.reject.bind(deferred);
-
-  return deferred.promise;
-}
-
-/**
- * Retrieve all messages from database.
- *
- * Fulfill params:
- *   messages -- an array of {Sms,Mms}Message instances.
- *
- * Reject params:
- *   event -- a DOMEvent
- *
- * @return A deferred promise.
- */
-function getAllMessages() {
-  return getMessages(null, false);
-}
-
-/**
- * Retrieve all threads from database.
- *
- * Fulfill params:
- *   threads -- an array of MozMobileMessageThread instances.
- *
- * Reject params:
- *   event -- a DOMEvent
- *
- * @return A deferred promise.
- */
-function getAllThreads() {
-  let deferred = Promise.defer();
-
-  let threads = [];
-  let cursor = manager.getThreads();
-  cursor.onsuccess = function(aEvent) {
-    if (cursor.result) {
-      threads.push(cursor.result);
-      cursor.continue();
-      return;
-    }
-
-    deferred.resolve(threads);
-  };
-  cursor.onerror = deferred.reject.bind(deferred);
-
-  return deferred.promise;
-}
-
-/**
- * Retrieve a single specified thread from database.
- *
- * Fulfill params:
- *   thread -- a MozMobileMessageThread instance.
- *
- * Reject params:
- *   event -- a DOMEvent if an error occurs in the retrieving process, or
- *            undefined if there's no such thread.
- *
- * @aThreadId a numeric value identifying the target thread.
- *
- * @return A deferred promise.
- */
-function getThreadById(aThreadId) {
-  return getAllThreads()
-    .then(function(aThreads) {
-      for (let thread of aThreads) {
-        if (thread.id === aThreadId) {
-          return thread;
-        }
-      }
-      throw undefined;
-    });
-}
-
-/**
- * Delete messages specified from database.
- *
- * Fulfill params:
- *   result -- an array of boolean values indicating whether delesion was
- *             actually performed on the message record with corresponding id.
- *
- * Reject params:
- *   event -- a DOMEvent.
- *
- * @aMessageId an array of numeric values identifying the target messages.
- *
- * @return An empty array if nothing to be deleted; otherwise, a deferred promise.
- */
-function deleteMessagesById(aMessageIds) {
-  if (!aMessageIds.length) {
-    ok(true, "no message to be deleted");
-    return [];
-  }
-
-  let promises = [];
-  promises.push(waitForManagerEvent("deleted"));
-  promises.push(manager.delete(aMessageIds));
-
-  return Promise.all(promises)
-    .then((aResults) => {
-      return { deletedInfo: aResults[0],
-               deletedFlags: aResults[1] };
-    });
-}
-
-/**
- * Delete messages specified from database.
- *
- * Fulfill params:
- *   result -- an array of boolean values indicating whether delesion was
- *             actually performed on the message record with corresponding id.
- *
- * Reject params:
- *   event -- a DOMEvent.
- *
- * @aMessages an array of {Sms,Mms}Message instances.
- *
- * @return A deferred promise.
- */
-function deleteMessages(aMessages) {
-  let ids = messagesToIds(aMessages);
-  return deleteMessagesById(ids);
-}
-
-/**
- * Delete all messages from database.
- *
- * Fulfill params:
- *   ids -- an array of numeric values identifying those deleted
- *          {Sms,Mms}Messages.
- *
- * Reject params:
- *   event -- a DOMEvent.
- *
- * @return A deferred promise.
- */
-function deleteAllMessages() {
-  return getAllMessages().then(deleteMessages);
-}
-
-var pendingEmulatorCmdCount = 0;
-
-/**
- * Send emulator command with safe guard.
- *
- * We should only call |finish()| after all emulator command transactions
- * end, so here comes with the pending counter.  Resolve when the emulator
- * gives positive response, and reject otherwise.
- *
- * Fulfill params:
- *   result -- an array of emulator response lines.
- *
- * Reject params:
- *   result -- an array of emulator response lines.
- *
- * @return A deferred promise.
- */
-function runEmulatorCmdSafe(aCommand) {
-  let deferred = Promise.defer();
-
-  ++pendingEmulatorCmdCount;
-  runEmulatorCmd(aCommand, function(aResult) {
-    --pendingEmulatorCmdCount;
-
-    ok(true, "Emulator response: " + JSON.stringify(aResult));
-    if (Array.isArray(aResult) && aResult[0] === "OK") {
-      deferred.resolve(aResult);
-    } else {
-      deferred.reject(aResult);
-    }
-  });
-
-  return deferred.promise;
-}
-
-/**
- * Send simple text SMS to emulator.
- *
- * Fulfill params:
- *   result -- an array of emulator response lines.
- *
- * Reject params:
- *   result -- an array of emulator response lines.
- *
- * @param aFrom
- *        A string-typed from address.
- * @param aText
- *        A string-typed message body.
- *
- * @return A deferred promise.
- */
-function sendTextSmsToEmulator(aFrom, aText) {
-  let command = "sms send " + aFrom + " " + aText;
-  return runEmulatorCmdSafe(command);
-}
-
-/**
- * Send simple text SMS to emulator and wait for a received event.
- *
- * Fulfill params: SmsMessage
- * Reject params: (none)
- *
- * @param aFrom
- *        A string-typed from address.
- * @param aText
- *        A string-typed message body.
- *
- * @return A deferred promise.
- */
-function sendTextSmsToEmulatorAndWait(aFrom, aText) {
-  let promises = [];
-  promises.push(waitForManagerEvent("received"));
-  promises.push(sendTextSmsToEmulator(aFrom, aText));
-  return Promise.all(promises).then(aResults => aResults[0].message);
-}
-
-/**
- * Send raw SMS TPDU to emulator.
- *
- * @param: aPdu
- *         A hex string representing the whole SMS T-PDU.
- *
- * Fulfill params:
- *   result -- an array of emulator response lines.
- *
- * Reject params:
- *   result -- an array of emulator response lines.
- *
- * @return A deferred promise.
- */
-function sendRawSmsToEmulator(aPdu) {
-  let command = "sms pdu " + aPdu;
-  return runEmulatorCmdSafe(command);
-}
-
-/**
- * Send multiple raw SMS TPDU to emulator and wait
- *
- * @param: aPdus
- *         A array of hex strings. Each represents a SMS T-PDU.
- *
- * Fulfill params:
- *   result -- array of resolved Promise, where
- *             result[0].message representing the received message.
- *             result[1-n] represents the response of sent emulator command.
- *
- * Reject params:
- *   result -- an array of emulator response lines.
- *
- * @return A deferred promise.
- */
-function sendMultipleRawSmsToEmulatorAndWait(aPdus) {
-  let promises = [];
-
-  promises.push(waitForManagerEvent("received"));
-  for (let pdu of aPdus) {
-    promises.push(sendRawSmsToEmulator(pdu));
-  }
-
-  return Promise.all(promises);
-}
-
-/**
- * Set voice state and wait for state change.
- *
- * @param aState
- *        "unregistered", "searching", "denied", "roaming", or "home".
- *
- * @return A deferred promise.
- */
-function setEmulatorVoiceStateAndWait(aState) {
-  let promises = [];
-  promises.push(new Promise(function(resolve, reject) {
-    mobileConnection.addEventListener("voicechange", function onevent(aEvent) {
-      log("voicechange: connected=" + mobileConnection.voice.connected);
-      mobileConnection.removeEventListener("voicechange", onevent);
-      resolve(aEvent);
-    })
-  }));
-
-  promises.push(runEmulatorCmdSafe("gsm voice " + aState));
-  return Promise.all(promises);
-}
-
-/**
- * Create a new array of id attribute of input messages.
- *
- * @param aMessages an array of {Sms,Mms}Message instances.
- *
- * @return an array of numeric values.
- */
-function messagesToIds(aMessages) {
-  let ids = [];
-  for (let message of aMessages) {
-    ids.push(message.id);
-  }
-  return ids;
-}
-
-/**
- * Convenient function to compare two SMS messages.
- */
-function compareSmsMessage(aFrom, aTo) {
-  const FIELDS = ["id", "threadId", "iccId", "body", "delivery",
-                  "deliveryStatus", "read", "receiver", "sender",
-                  "messageClass", "timestamp", "deliveryTimestamp",
-                  "sentTimestamp"];
-
-  for (let field of FIELDS) {
-    is(aFrom[field], aTo[field], "message." + field);
-  }
-}
-
-/**
- * Wait for pending emulator transactions and call |finish()|.
- */
-function cleanUp() {
-  ok(true, ":: CLEANING UP ::");
-
-  waitFor(finish, function() {
-    return pendingEmulatorCmdCount === 0;
-  });
-}
-
-/**
- * Basic test routine helper for mobile message tests.
- *
- * This helper does nothing but clean-ups.
- *
- * @param aTestCaseMain
- *        A function that takes no parameter.
- */
-function startTestBase(aTestCaseMain) {
-  Promise.resolve()
-         .then(aTestCaseMain)
-         .then(cleanUp, function() {
-           ok(false, 'promise rejects during test.');
-           cleanUp();
-         });
-}
-
-/**
- * Common test routine helper for mobile message tests.
- *
- * This function ensures global |manager| variable is available during the
- * process and performs clean-ups as well.
- *
- * @param aTestCaseMain
- *        A function that takes no parameter.
- */
-function startTestCommon(aTestCaseMain) {
-  startTestBase(function() {
-    return ensureMobileMessage()
-      .then(deleteAllMessages)
-      .then(aTestCaseMain)
-      .then(deleteAllMessages);
-  });
-}
-
-/**
- * Helper to run the test case only needed in Multi-SIM environment.
- *
- * @param  aTest
- *         A function which will be invoked w/o parameter.
- * @return a Promise object.
- */
-function runIfMultiSIM(aTest) {
-  let numRIL;
-  try {
-    numRIL = SpecialPowers.getIntPref("ril.numRadioInterfaces");
-  } catch (ex) {
-    numRIL = 1;  // Pref not set.
-  }
-
-  if (numRIL > 1) {
-    return aTest();
-  } else {
-    log("Not a Multi-SIM environment. Test is skipped.");
-    return Promise.resolve();
-  }
-}
-
-/**
- * Helper to enable/disable connection radio state.
- *
- * @param  aConnection
- *         connection to enable / disable
- * @param  aEnabled
- *         True to enable the radio.
- * @return a Promise object.
- */
-function setRadioEnabled(aConnection, aEnabled) {
-  log("setRadioEnabled to " + aEnabled);
-
-  let deferred = Promise.defer();
-  let finalState = (aEnabled) ? "enabled" : "disabled";
-  if (aConnection.radioState == finalState) {
-    return deferred.resolve(aConnection);
-  }
-
-  aConnection.onradiostatechange = function() {
-    log("Received 'radiostatechange', radioState: " + aConnection.radioState);
-
-    if (aConnection.radioState == finalState) {
-      deferred.resolve(aConnection);
-      aConnection.onradiostatechange = null;
-    }
-  };
-
-  let req = aConnection.setRadioEnabled(aEnabled);
-
-  req.onsuccess = function() {
-    log("setRadioEnabled success");
-  };
-
-  req.onerror = function() {
-    ok(false, "setRadioEnabled should not fail");
-    deferred.reject();
-  };
-
-  return deferred.promise;
-}
-
-/**
- * Helper to enable/disable all connections radio state.
- *
- * @param  aEnabled
- *         True to enable the radio.
- * @return a Promise object.
- */
-function setAllRadioEnabled(aEnabled) {
-  let promises = []
-  for (let i = 0; i < window.navigator.mozMobileConnections.length; ++i) {
-    promises.push(ensureMobileConnection(i)
-      .then((connection) => setRadioEnabled(connection, aEnabled)));
-  }
-  return Promise.all(promises);
-}
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/manifest.ini
+++ /dev/null
@@ -1,53 +0,0 @@
-[DEFAULT]
-run-if = buildapp == 'b2g'
-
-;[test_between_emulators.py]
-[test_bug814761.js]
-[test_decode_spanish_fallback.js]
-[test_emulator_loopback.js]
-[test_error_of_mms_manual_retrieval.js]
-[test_error_of_mms_send.js]
-[test_error_of_sms_send.js]
-[test_filter_date.js]
-[test_filter_mixed.js]
-[test_filter_number.js]
-[test_filter_read.js]
-[test_filter_received.js]
-[test_filter_sent.js]
-[test_filter_unread.js]
-[test_getmessage.js]
-[test_getmessage_notfound.js]
-[test_getmessages.js]
-[test_getsegmentinfofortext.js]
-[test_getthreads.js]
-[test_incoming_delete.js]
-[test_incoming.js]
-[test_incoming_max_segments.js]
-[test_invalid_address.js]
-[test_mark_msg_read_error.js]
-[test_mark_msg_read.js]
-[test_massive_incoming_delete.js]
-[test_message_classes.js]
-[test_mmdb_foreachmatchedmmsdeliveryinfo.js]
-[test_mmdb_full_storage.js]
-[test_mmdb_new.js]
-[test_mmdb_ports_in_cdma_wappush.js]
-[test_mmdb_setmessagedeliverybyid_sms.js]
-[test_mmdb_upgradeSchema_22.js]
-[test_mmdb_upgradeSchema_current_structure.js]
-[test_mmsmessage_attachments.js]
-[test_mobilemessage_dsds_default_service_id.js]
-[test_mt_sms_concatenation.js]
-[test_ondeleted_event.js]
-[test_outgoing_delete.js]
-[test_outgoing.js]
-[test_outgoing_max_segments.js]
-[test_outgoing_unstable_voice_connection.js]
-[test_phone_number_normalization.js]
-[test_replace_short_message_type.js]
-[test_segment_info.js]
-[test_smsc_address.js]
-[test_strict_7bit_encoding.js]
-[test_thread_subject.js]
-[test_update_gsm_nl_on_mcc_chanages.js]
-[test_update_thread_record_in_delete.js]
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/mmdb_head.js
+++ /dev/null
@@ -1,404 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_CONTEXT = "chrome";
-
-var Promise = Cu.import("resource://gre/modules/Promise.jsm").Promise;
-
-/**
- * Name space for MobileMessageDB.jsm.  Only initialized after first call to
- * newMobileMessageDB.
- */
-var MMDB;
-
-/**
- * Create a new MobileMessageDB instance.
- *
- * @return A MobileMessageDB instance.
- */
-function newMobileMessageDB() {
-  if (!MMDB) {
-    MMDB = Cu.import("resource://gre/modules/MobileMessageDB.jsm", {});
-    is(typeof MMDB.MobileMessageDB, "function", "MMDB.MobileMessageDB");
-  }
-
-  let mmdb = new MMDB.MobileMessageDB();
-  ok(mmdb, "MobileMessageDB instance");
-  return mmdb;
-}
-
-/**
- * Initialize a MobileMessageDB.  Resolve if initialized with success, reject
- * otherwise.
- *
- * Fulfill params: a MobileMessageDB instance.
- * Reject params: a MobileMessageDB instance.
- *
- * @param aMmdb
- *        A MobileMessageDB instance.
- * @param aDbName
- *        A string name for that database.
- * @param aDbVersion
- *        The version that MobileMessageDB should upgrade to. 0 for the lastest
- *        version.
- *
- * @return A deferred promise.
- */
-function initMobileMessageDB(aMmdb, aDbName, aDbVersion) {
-  let deferred = Promise.defer();
-
-  aMmdb.init(aDbName, aDbVersion, function(aError) {
-    if (aError) {
-      deferred.reject(aMmdb);
-    } else {
-      deferred.resolve(aMmdb);
-    }
-  });
-
-  return deferred.promise;
-}
-
-/**
- * Close a MobileMessageDB.
- *
- * @param aMmdb
- *        A MobileMessageDB instance.
- *
- * @return The passed MobileMessageDB instance.
- */
-function closeMobileMessageDB(aMmdb) {
-  aMmdb.close();
-  return aMmdb;
-}
-
-/**
- * Utility function for calling MMDB methods that takes either a
- * nsIGonkMobileMessageDatabaseCallback or a
- * nsIGonkMobileMessageDatabaseRecordCallback.
- *
- * Resolve when the target method notifies us with a successful result code;
- * reject otherwise. In either case, the arguments passed are packed into an
- * array and propagated to next action.
- *
- * Fulfill params: an array whose elements are the arguments of the original
- *                 callback.
- * Reject params: same as fulfill params.
- *
- * @param aMmdb
- *        A MobileMessageDB instance.
- * @param aMethodName
- *        A string name for that target method.
- * @param ...
- *        Extra arguments to pass to that target method. The last callback
- *        argument should always be excluded.
- *
- * @return A deferred promise.
- */
-function callMmdbMethod(aMmdb, aMethodName) {
-  let deferred = Promise.defer();
-
-  let args = Array.slice(arguments, 2);
-  args.push({
-    notify: function(aRv) {
-      if (!Components.isSuccessCode(aRv)) {
-        ok(true, aMethodName + " returns a unsuccessful code: " + aRv);
-        deferred.reject(Array.slice(arguments));
-      } else {
-        ok(true, aMethodName + " returns a successful code: " + aRv);
-        deferred.resolve(Array.slice(arguments));
-      }
-    }
-  });
-  aMmdb[aMethodName].apply(aMmdb, args);
-
-  return deferred.promise;
-}
-
-/**
- * A convenient function for calling |mmdb.saveSendingMessage(...)|.
- *
- * Fulfill params: [<Cr.NS_ERROR_FOO>, <DOM message>].
- * Reject params: same as fulfill params.
- *
- * @return A deferred promise.
- */
-function saveSendingMessage(aMmdb, aMessage) {
-  return callMmdbMethod(aMmdb, "saveSendingMessage", aMessage);
-}
-
-/**
- * A convenient function for calling |mmdb.saveReceivedMessage(...)|.
- *
- * Fulfill params: [<Cr.NS_ERROR_FOO>, <DOM message>].
- * Reject params: same as fulfill params.
- *
- * @return A deferred promise.
- */
-function saveReceivedMessage(aMmdb, aMessage) {
-  return callMmdbMethod(aMmdb, "saveReceivedMessage", aMessage);
-}
-
-/**
- * A convenient function for calling |mmdb.setMessageDeliveryByMessageId(...)|.
- *
- * Fulfill params: [<Cr.NS_ERROR_FOO>, <DOM message>].
- * Reject params: same as fulfill params.
- *
- * @return A deferred promise.
- */
-function setMessageDeliveryByMessageId(aMmdb, aMessageId, aReceiver, aDelivery,
-                                       aDeliveryStatus, aEnvelopeId) {
-  return callMmdbMethod(aMmdb, "setMessageDeliveryByMessageId", aMessageId,
-                        aReceiver, aDelivery, aDeliveryStatus, aEnvelopeId);
-}
-
-/**
- * A convenient function for calling
- * |mmdb.setMessageDeliveryStatusByEnvelopeId(...)|.
- *
- * Fulfill params: [<Cr.NS_ERROR_FOO>, <DOM message>].
- * Reject params: same as fulfill params.
- *
- * @return A deferred promise.
- */
-function setMessageDeliveryStatusByEnvelopeId(aMmdb, aEnvelopeId, aReceiver,
-                                              aDeliveryStatus) {
-  return callMmdbMethod(aMmdb, "setMessageDeliveryStatusByEnvelopeId",
-                        aMmdb, aEnvelopeId, aReceiver, aDeliveryStatus);
-}
-
-/**
- * A convenient function for calling
- * |mmdb.setMessageReadStatusByEnvelopeId(...)|.
- *
- * Fulfill params: [<Cr.NS_ERROR_FOO>, <DOM message>].
- * Reject params: same as fulfill params.
- *
- * @return A deferred promise.
- */
-function setMessageReadStatusByEnvelopeId(aMmdb, aEnvelopeId, aReceiver,
-                                          aReadStatus) {
-  return callMmdbMethod(aMmdb, "setMessageReadStatusByEnvelopeId",
-                        aEnvelopeId, aReceiver, aReadStatus);
-}
-
-/**
- * A convenient function for calling
- * |mmdb.getMessageRecordByTransactionId(...)|.
- *
- * Fulfill params: [<Cr.NS_ERROR_FOO>, <DB Record>, <DOM message>].
- * Reject params: same as fulfill params.
- *
- * @return A deferred promise.
- */
-function getMessageRecordByTransactionId(aMmdb, aTransactionId) {
-  return callMmdbMethod(aMmdb, "getMessageRecordByTransactionId",
-                        aTransactionId);
-}
-
-/**
- * A convenient function for calling |mmdb.getMessageRecordById(...)|.
- *
- * Fulfill params: [<Cr.NS_ERROR_FOO>, <DB Record>, <DOM message>].
- * Reject params: same as fulfill params.
- *
- * @return A deferred promise.
- */
-function getMessageRecordById(aMmdb, aMessageId) {
-  return callMmdbMethod(aMmdb, "getMessageRecordById", aMessageId);
-}
-
-/**
- * A convenient function for calling |mmdb.markMessageRead(...)|.
- *
- * Fulfill params: Ci.nsIMobileMessageCallback.FOO.
- * Reject params: same as fulfill params.
- *
- * @return A deferred promise.
- */
-function markMessageRead(aMmdb, aMessageId, aRead) {
-  let deferred = Promise.defer();
-
-  aMmdb.markMessageRead(aMessageId, aRead, false, {
-    notifyMarkMessageReadFailed: function(aRv) {
-      ok(true, "markMessageRead returns a unsuccessful code: " + aRv);
-      deferred.reject(aRv);
-    },
-
-    notifyMessageMarkedRead: function(aRead) {
-      ok(true, "markMessageRead returns a successful code: " + Cr.NS_OK);
-      deferred.resolve(Ci.nsIMobileMessageCallback.SUCCESS_NO_ERROR);
-    }
-  });
-
-  return deferred.promise;
-}
-
-/**
- * A convenient function for calling |mmdb.deleteMessage(...)|.
- *
- * Fulfill params: array of deleted flags.
- * Reject params: Ci.nsIMobileMessageCallback.FOO.
- *
- * @return A deferred promise.
- */
-function deleteMessage(aMmdb, aMessageIds, aLength) {
-  let deferred = Promise.defer();
-
-  aMmdb.deleteMessage(aMessageIds, aLength, {
-    notifyDeleteMessageFailed: function(aRv) {
-      ok(true, "deleteMessage returns a unsuccessful code: " + aRv);
-      deferred.reject(aRv);
-    },
-
-    notifyMessageDeleted: function(aDeleted, aLength) {
-      ok(true, "deleteMessage successfully!");
-      deferred.resolve(aDeleted);
-    }
-  });
-
-  return deferred.promise;
-}
-
-/**
- * A convenient function for calling |mmdb.saveSmsSegment(...)|.
- *
- * Fulfill params: [<Cr.NS_ERROR_FOO>, <completeMessage>].
- * Reject params: same as fulfill params.
- *
- * @return A deferred promise.
- */
-function saveSmsSegment(aMmdb, aSmsSegment) {
-  return callMmdbMethod(aMmdb, "saveSmsSegment", aSmsSegment);
-}
-
-/**
- * Utility function for calling cursor-based MMDB methods.
- *
- * Resolve when the target method notifies us with |notifyCursorDone|,
- * reject otherwise.
- *
- * Fulfill params: [<Ci.nsIMobileMessageCallback.FOO>, [<DOM message/thread>]]
- * Reject params: same as fulfill params.
- *
- * @param aMmdb
- *        A MobileMessageDB instance.
- * @param aMethodName
- *        A string name for that target method.
- * @param ...
- *        Extra arguments to pass to that target method. The last callback
- *        argument should always be excluded.
- *
- * @return A deferred promise.
- */
-function createMmdbCursor(aMmdb, aMethodName) {
-  let deferred = Promise.defer();
-
-  let cursor;
-  let results = [];
-  let args = Array.slice(arguments, 2);
-  args.push({
-    notifyCursorError: function(aRv) {
-      ok(true, "notifyCursorError: " + aRv);
-      deferred.reject([aRv, results]);
-    },
-
-    notifyCursorResult: function(aResults, aSize) {
-      ok(true, "notifyCursorResult: " + aResults.map(function(aElement) { return aElement.id; }));
-      results = results.concat(aResults);
-      cursor.handleContinue();
-    },
-
-    notifyCursorDone: function() {
-      ok(true, "notifyCursorDone");
-      deferred.resolve([Ci.nsIMobileMessageCallback.SUCCESS_NO_ERROR, results]);
-    }
-  });
-
-  cursor = aMmdb[aMethodName].apply(aMmdb, args);
-
-  return deferred.promise;
-}
-
-/**
- * A convenient function for calling |mmdb.createMessageCursor(...)|.
- *
- * Fulfill params: [<Ci.nsIMobileMessageCallback.FOO>, [<DOM message>]].
- * Reject params: same as fulfill params.
- *
- * @return A deferred promise.
- */
-function createMessageCursor(aMmdb, aStartDate = null, aEndDate = null,
-                             aNumbers = null, aDelivery = null, aRead = null,
-                             aThreadId = null, aReverse = false) {
-  return createMmdbCursor(aMmdb, "createMessageCursor",
-                          aStartDate !== null,
-                          aStartDate || 0,
-                          aEndDate !== null,
-                          aEndDate || 0,
-                          aNumbers || null,
-                          aNumbers && aNumbers.length || 0,
-                          aDelivery || null,
-                          aRead !== null,
-                          aRead || false,
-                          aThreadId !== null,
-                          aThreadId || 0,
-                          aReverse || false);
-}
-
-/**
- * A convenient function for calling |mmdb.createThreadCursor(...)|.
- *
- * Fulfill params: [<Ci.nsIMobileMessageCallback.FOO>, [<DOM thread>]].
- * Reject params: same as fulfill params.
- *
- * @return A deferred promise.
- */
-function createThreadCursor(aMmdb) {
-  return createMmdbCursor(aMmdb, "createThreadCursor");
-}
-
-// A reference to a nsIUUIDGenerator service.
-var _uuidGenerator;
-
-/**
- * Generate a new UUID.
- *
- * @return A UUID string.
- */
-function newUUID() {
-  if (!_uuidGenerator) {
-    _uuidGenerator = Cc["@mozilla.org/uuid-generator;1"]
-                     .getService(Ci.nsIUUIDGenerator);
-    ok(_uuidGenerator, "uuidGenerator");
-  }
-
-  return _uuidGenerator.generateUUID().toString();
-}
-
-/**
- * Flush permission settings and call |finish()|.
- */
-function cleanUp() {
-  // Use ok here so that we have at least one test run.
-  ok(true, "permissions flushed");
-
-  finish();
-}
-
-/**
- * Basic test routine helper for mobile message tests.
- *
- * This helper does nothing but clean-ups.
- *
- * @param aTestCaseMain
- *        A function that takes no parameter.
- */
-function startTestBase(aTestCaseMain) {
-  Promise.resolve()
-    .then(aTestCaseMain)
-    .then(null, function() {
-      ok(false, 'promise rejects during test.');
-    })
-    .then(cleanUp);
-}
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_between_emulators.py
+++ /dev/null
@@ -1,43 +0,0 @@
-from marionette_test import *
-
-
-class SMSTest(MarionetteTestCase):
-
-    @unittest.expectedFailure
-    def test_sms_between_emulators(self):
-        # Tests always have one emulator available as self.marionette; we'll
-        # use this for the receiving emulator.  We'll also launch a second
-        # emulator to use as the sender.
-        sender = self.get_new_emulator()
-        receiver = self.marionette
-
-        self.set_up_test_page(sender, "test.html", ["sms"])
-        self.set_up_test_page(receiver, "test.html", ["sms"])
-
-        # Setup the event listsener on the receiver, which should store
-        # a global variable when an SMS is received.
-        message = 'hello world!'
-        self.assertTrue(receiver.execute_script("return window.navigator.mozMobileMessage != null;"))
-        receiver.execute_script("""
-global.smsreceived = null;
-window.navigator.mozMobileMessage.addEventListener("received", function(e) {
-    global.smsreceived = e.message.body;
-});
-""", new_sandbox=False)
-
-        # Send the SMS from the sender.
-        sender.execute_script("""
-window.navigator.mozMobileMessage.send("%d", "%s");
-""" % (receiver.emulator.port, message))
-
-        # On the receiver, wait up to 10s for an SMS to be received, by 
-        # checking the value of the global var that the listener will change.
-        receiver.set_script_timeout(0) # TODO no timeout for now since the test fails
-        received = receiver.execute_async_script("""
-        waitFor(function () {
-            marionetteScriptFinished(global.smsreceived);
-        }, function () {
-            return global.smsreceived
-        });
-        """, new_sandbox=False)
-        self.assertEqual(received, message)
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_bug814761.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-SpecialPowers.addPermission("sms", true, document);
-
-var manager = window.navigator.mozMobileMessage;
-ok(manager instanceof MozMobileMessageManager,
-   "manager is instance of " + manager.constructor);
-
-// Note: 378 chars and below is fine, but 379 and above will cause the issue.
-// Sending first message works, but second one we get emulator callback but
-// the actual SMS is never received, so script will timeout waiting for the
-// onreceived event. Also note that a single larger message (i.e. 1600
-// characters) works; so it is not a compounded send limit.
-var fromNumber = "5551110000";
-var msgLength = 379;
-var msgText = new Array(msgLength + 1).join('a');
-
-var pendingEmulatorCmdCount = 0;
-function sendSmsToEmulator(from, text) {
-  ++pendingEmulatorCmdCount;
-
-  let cmd = "sms send " + from + " " + text;
-  runEmulatorCmd(cmd, function(result) {
-    --pendingEmulatorCmdCount;
-
-    is(result[0], "OK", "Emulator response");
-  });
-}
-
-function firstIncomingSms() {
-  simulateIncomingSms(secondIncomingSms);
-}
-
-function secondIncomingSms() {
-  simulateIncomingSms(cleanUp);
-}
-
-function simulateIncomingSms(nextFunction) {
-  log("Simulating incoming multipart SMS (" + msgText.length
-      + " chars total).");
-
-  manager.onreceived = function onreceived(event) {
-    log("Received 'onreceived' event.");
-    manager.onreceived = null;
-
-    let incomingSms = event.message;
-    ok(incomingSms, "incoming sms");
-    is(incomingSms.body, msgText, "msg body");
-
-    window.setTimeout(nextFunction, 0);
-  };
-
-  sendSmsToEmulator(fromNumber, msgText);
-}
-
-function cleanUp() {
-  if (pendingEmulatorCmdCount) {
-    window.setTimeout(cleanUp, 100);
-    return;
-  }
-
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-}
-
-// Start the test
-firstIncomingSms();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_decode_spanish_fallback.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const PDU_SMSC_NONE = "00"; // no SMSC Address
-
-// |  TP-RP|TP-UDHI| TP-SRI|     Unused    | TP-MMS|     TP-MTI    |
-// |   0   |   1   |   0   |   0   |   0   |   0   |   0   |   0   | => 0x40
-const PDU_FIRST_OCTET = "40";
-
-// |   | <= TON => | <=== NOI ===> |
-// | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | => 0xa8
-const PDU_OA = "0AA89021436587";  // 0912345678
-
-const PDU_PID_NORMAL = "00";
-const PDU_DCS_GSM_7BIT = "00";
-const PDU_TIMESTAMP = "51302151740020"; // 2015/3/12 15:47:00 UTC+8
-
-// ==> | <========== G ==========> |
-// | 1 | 1 | 0 | 0 | 0 | 1 | 1 | 1 |  => 0xc7
-// ======> | <========== S =========
-// | 0 | 1 | 1 | 0 | 1 | 0 | 0 | 1 |  => 0x69
-// |<=padding=>| <========== M =====
-// | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 |  => 0x13
-const PDU_UD_GSM = "C76913";
-
-const IE_USE_SPANISH_LOCKING_SHIFT_TABLE = "250102";
-const IE_USE_SPANISH_SINGLE_SHIFT_TABLE = "240102";
-const PDU_UDHL = "06";
-
-const PDU_UDL = "0B"; // UDH occupies 7 octets = 8 septets, plus 3 septets data.
-
-const PDU = PDU_SMSC_NONE + PDU_FIRST_OCTET + PDU_OA + PDU_PID_NORMAL
-  + PDU_DCS_GSM_7BIT + PDU_TIMESTAMP + PDU_UDL + PDU_UDHL
-  + IE_USE_SPANISH_LOCKING_SHIFT_TABLE + IE_USE_SPANISH_SINGLE_SHIFT_TABLE
-  + PDU_UD_GSM;
-
-function verifyMessage(aMessage) {
-  is(aMessage.body, "GSM", "SmsMessage body");
-}
-
-/**
- * Test and verify that user data encoded in GSM default alphabet can be
- * correctly decoded with Spanish locking shift table. See bug 1138841.
- */
-startTestCommon(function testCaseMain() {
-  return Promise.resolve()
-    .then(() => sendMultipleRawSmsToEmulatorAndWait([PDU]))
-    .then(results => verifyMessage(results[0].message));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_emulator_loopback.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const SELF = "5554";
-
-function randomString16() {
-  return Math.random().toString(36).substr(2, 16);
-}
-
-function times(str, n) {
-  return (new Array(n + 1)).join(str);
-}
-
-function test(aBody) {
-  let promises = [];
-
-  promises.push(waitForManagerEvent('received')
-    .then(function(aEvent) {
-      let message = aEvent.message;
-      is(message.body, aBody, "message.body");
-    }));
-
-  promises.push(sendSmsWithSuccess(SELF, aBody));
-
-  return Promise.all(promises);
-}
-
-const TEST_DATA = [
-  // Random alphanumeric string of 16 characters.
-  randomString16(),
-  // Long long text message for multipart messages.
-  times(randomString16(), 100),
-
-  // UCS2 string for the first sentence of "The Cooing", Classic of Poetry.
-  "\u95dc\u95dc\u96ce\u9ce9\uff0c\u5728\u6cb3\u4e4b\u6d32\u3002",
-  // Long long UCS2 text message for multipart messages.
-  times("\u95dc\u95dc\u96ce\u9ce9\uff0c\u5728\u6cb3\u4e4b\u6d32\u3002", 100),
-
-  // Test case from Bug 809553
-  "zertuuuppzuzyeueieieyeieoeiejeheejrueufjfjfjjfjfkxifjfjfufjjfjfufujdjduxxjdu"
-  + "djdjdjdudhdjdhdjdbddhbfjfjxbuwjdjdudjddjdhdhdvdyudusjdudhdjjfjdvdudbddjdbd"
-  + "usjfbjdfudjdhdjbzuuzyzehdjjdjwybwudjvwywuxjdbfudsbwuwbwjdjdbwywhdbddudbdjd"
-  + "uejdhdudbdduwjdbjddudjdjdjdudjdbdjdhdhdjjdjbxudjdbxufjudbdjhdjdisjsjzusbzh"
-  + "xbdudksksuqjgdjdb jeudi jeudis duhebevzcevevsvs DVD suscite eh du d des jv"
-  + " y b Dj. Du  wh. Hu Deb wh. Du web h w show d DVD h w v.  Th\u00e9 \u00e9c"
-  + "hec d whdvdj. Wh d'h\u00f4tel DVD. IMAX eusjw ii ce",
-
-  // Android Emulator specific problems:
-  // 1) wrong default 7Bit alphabet character for "Ň"(U+0147).
-  "\u0147",
-  // 2) problem in decoding strings encoded with GSM 7Bit Alphabets and
-  // containing characters on extension tables.
-  "\u20ac****",
-];
-
-startTestBase(function testCaseMain() {
-  return ensureMobileMessage()
-    .then(function() {
-      let promise = Promise.resolve();
-
-      for (let i = 0; i < TEST_DATA.length; i++) {
-        let text = TEST_DATA[i];
-        promise = promise.then(() => test(text));
-      }
-
-      return promise;
-    });
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_error_of_mms_manual_retrieval.js
+++ /dev/null
@@ -1,218 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-// We apply "chrome" context to be more flexible to
-// specify the content of M-Notification.ind such as iccId
-// for different kinds of testing.
-MARIONETTE_CONTEXT = "chrome";
-
-Cu.import("resource://gre/modules/Promise.jsm");
-
-var MMS = {};
-Cu.import("resource://gre/modules/MmsPduHelper.jsm", MMS);
-
-var gMobileMessageDatabaseService =
-  Cc["@mozilla.org/mobilemessage/gonkmobilemessagedatabaseservice;1"]
-    .getService(Ci.nsIGonkMobileMessageDatabaseService);
-
-var gUuidGenerator =
-  Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
-
-var gMmsService =
-  Cc["@mozilla.org/mms/gonkmmsservice;1"].getService(Ci.nsIMmsService);
-
-var gMobileConnectionService =
-  Cc["@mozilla.org/mobileconnection/mobileconnectionservice;1"]
-    .getService(Ci.nsIMobileConnectionService);
-
-var gIccService =
-  Cc["@mozilla.org/icc/gonkiccservice;1"].getService(Ci.nsIIccService);
-
-function saveMmsNotification() {
-  log("saveMmsNotification()");
-  let tid = gUuidGenerator.generateUUID().toString();
-  tid = tid.substr(1, tid.length - 2); // strip parentheses {}.
-
-  let headers = {};
-  headers["x-mms-message-type"] = MMS.MMS_PDU_TYPE_NOTIFICATION_IND;
-  headers["x-mms-transaction-id"] = tid;
-  headers["x-mms-mms-version"] = MMS.MMS_VERSION;
-  headers["x-mms-message-class"] = "personal";
-  headers["x-mms-message-size"] = 255;
-  headers["x-mms-expiry"] = 24 * 60 * 60;
-  headers["x-mms-content-location"] = "http://192.168.0.1/mms.cgi" + "?tid=" + tid;
-  let notification = {
-    headers: headers,
-    type: "mms",
-    delivery: "not-downloaded",
-    deliveryStatus: "manual",
-    timestamp: Date.now(),
-    receivers: [],
-    phoneNumber: "+0987654321",
-    iccId: "01234567899876543210"
-  };
-
-  let deferred = Promise.defer();
-
-  gMobileMessageDatabaseService
-    .saveReceivedMessage(notification, function(aRv, aDomMessage) {
-      log("saveReceivedMessage(): " + aRv);
-      if (Components.isSuccessCode(aRv)) {
-        deferred.resolve(aDomMessage.QueryInterface(Ci.nsIMmsMessage));
-      } else {
-        deferred.reject();
-      }
-    });
-
-  return deferred.promise;
-}
-
-function deleteMessagesById(aIds) {
-  log("deleteMessagesById()");
-  let deferred = Promise.defer();
-  let request = {
-    notifyDeleteMessageFailed: function(aRv) {
-      log("notifyDeleteMessageFailed()");
-      deferred.reject();
-    },
-    notifyMessageDeleted: function(aDeleted, aLength) {
-      log("notifyMessageDeleted()");
-      deferred.resolve();
-    },
-  };
-  gMobileMessageDatabaseService
-    .deleteMessage(aIds, aIds.length, request);
-
-  return deferred.promise;
-}
-
-function verifyErrorCause(aResponse, aCause) {
-  is(aResponse, aCause, "Test error cause of retrieval.");
-
-  return deleteMessagesById([aResponse.id]);
-}
-
-function retrieveMmsWithFailure(aId) {
-  log("retrieveMmsWithFailure()");
-  let deferred = Promise.defer();
-  let request = {
-    notifyGetMessageFailed: function(aRv) {
-      log("notifyGetMessageFailed()");
-      deferred.resolve(aRv);
-    }
-  };
-  gMmsService.retrieve(aId, request);
-
-  return deferred.promise;
-}
-
-function testRetrieve(aCause) {
-  log("testRetrieve: aCause = " + aCause);
-  return Promise.resolve()
-    .then(saveMmsNotification)
-    .then((message) => retrieveMmsWithFailure(message.id))
-    .then((response) => verifyErrorCause(response, aCause));
-}
-
-function setRadioEnabled(aConnection, aEnabled) {
-  let deferred = Promise.defer();
-  let finalState = (aEnabled) ?
-    Ci.nsIMobileConnection.MOBILE_RADIO_STATE_ENABLED :
-    Ci.nsIMobileConnection.MOBILE_RADIO_STATE_DISABLED;
-
-  if (aConnection.radioState == finalState) {
-    return deferred.resolve(aConnection);
-  }
-  let listener = {
-    QueryInterface: XPCOMUtils.generateQI([Ci.nsIMobileConnectionListener]),
-    notifyVoiceChanged: function() {},
-    notifyDataChanged: function() {},
-    notifyDataError: function(message) {},
-    notifyCFStateChanged: function(action, reason, number, timeSeconds, serviceClass) {},
-    notifyEmergencyCbModeChanged: function(active, timeoutMs) {},
-    notifyOtaStatusChanged: function(status) {},
-    notifyRadioStateChanged: function() {
-      log("setRadioEnabled state changed to " + aConnection.radioState);
-      if (aConnection.radioState == finalState) {
-        aConnection.unregisterListener(listener);
-        deferred.resolve(aConnection);
-      }
-    },
-    notifyClirModeChanged: function(mode) {},
-    notifyLastKnownNetworkChanged: function() {},
-    notifyLastKnownHomeNetworkChanged: function() {},
-    notifyNetworkSelectionModeChanged: function() {},
-    notifyDeviceIdentitiesChanged: function() {}
-  };
-  let callback = {
-    QueryInterface: XPCOMUtils.generateQI([Ci.nsIMobileConnectionCallback]),
-    notifySuccess() {},
-    notifySuccessWithBoolean(result) {},
-    notifyGetNetworksSuccess(count, networks) {},
-    notifyGetCallForwardingSuccess(count, results) {},
-    notifyGetCallBarringSuccess(program, enabled, serviceClass) {},
-    notifyGetCallWaitingSuccess(serviceClass) {},
-    notifyGetClirStatusSuccess(n, m) {},
-    notifyGetPreferredNetworkTypeSuccess(type) {},
-    notifyGetRoamingPreferenceSuccess(mode) {},
-    notifyError(name) {
-      log("setRadioEnabled reject");
-      aConnection.unregisterListener(listener);
-      deferred.reject();
-    }
-  };
-  aConnection.registerListener(listener);
-  aConnection.setRadioEnabled(aEnabled, callback);
-  return deferred.promise;
-}
-
-function setAllRadioEnabled(aEnabled) {
-  log("setAllRadioEnabled connection number = " +
-    gMobileConnectionService.numItems);
-
-  let promises = [];
-  for (let i = 0; i < gMobileConnectionService.numItems; ++i) {
-    promises.push(setRadioEnabled(
-      gMobileConnectionService.getItemByServiceId(i), aEnabled));
-  }
-  return Promise.all(promises);
-}
-
-function waitIccReady(aIcc) {
-  let deferred = Promise.defer();
-  if (aIcc.cardState == Ci.nsIIcc.CARD_STATE_READY) {
-    return deferred.resolve(aIcc);
-  }
-  let listener = {
-    QueryInterface: XPCOMUtils.generateQI([Ci.nsIIccListener]),
-    notifyStkCommand(aStkProactiveCmd) {},
-    notifyStkSessionEnd() {},
-    notifyCardStateChanged() {
-      if (aIcc.cardState == Ci.nsIIcc.CARD_STATE_READY) {
-        aIcc.unregisterListener(listener);
-        deferred.resolve(aIcc);
-      }
-    },
-    notifyIccInfoChanged() {}
-  };
-  aIcc.registerListener(listener);
-  return deferred.promise;
-}
-
-function waitAllIccReady() {
-  let promises = [];
-  for (let i = 0; i < gMobileConnectionService.numItems; ++i) {
-    let icc = gIccService.getIccByServiceId(i);
-    promises.push(waitIccReady(icc));
-  }
-  return Promise.all(promises);
-}
-
-setAllRadioEnabled(false)
-  .then(() => testRetrieve(Ci.nsIMobileMessageCallback.RADIO_DISABLED_ERROR))
-  .then(() => setAllRadioEnabled(true))
-  .then(() => waitAllIccReady())
-  .then(() => testRetrieve(Ci.nsIMobileMessageCallback.SIM_NOT_MATCHED_ERROR))
-  .then(finish);
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_error_of_mms_send.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-function testSendFailed(aCause, aServiceId) {
-  log("testSendFailed, aCause: " + aCause + ", aServiceId: " + aServiceId);
-  let sendParameters;
-
-  if (aServiceId) {
-    sendParameters = { serviceId: aServiceId };
-  }
-
-  let testSubject = "Test";
-  let testReceivers = ["+0987654321"];
-
-  let mmsParameters = { subject: testSubject,
-                        receivers: testReceivers,
-                        attachments: [] };
-
-  return sendMmsWithFailure(mmsParameters, sendParameters)
-    .then((result) => {
-      is(result.error.name, aCause, "Checking failure cause.");
-
-      let domMessage = result.error.data;
-      is(domMessage.id, result.message.id, "Checking message id.");
-      is(domMessage.subject, testSubject, "Checking subject.");
-      is(domMessage.receivers.length, testReceivers.length, "Checking no. of receivers.");
-      for (let i = 0; i < testReceivers.length; i++) {
-        is(domMessage.receivers[i], testReceivers[i], "Checking receiver address.");
-      }
-
-      let deliveryInfo = domMessage.deliveryInfo;
-      is(deliveryInfo.length, testReceivers.length, "Checking no. of deliveryInfo.");
-      for (let i = 0; i < deliveryInfo.length; i++) {
-        is(deliveryInfo[i].receiver, testReceivers[i], "Checking receiver address.");
-        is(deliveryInfo[i].deliveryStatus, "error", "Checking deliveryStatus.");
-      }
-    });
-}
-
-startTestCommon(function testCaseMain() {
-  return Promise.resolve()
-    .then(() => setAllRadioEnabled(false))
-    .then(() => testSendFailed("RadioDisabledError"), 0)
-    .then(() => setAllRadioEnabled(true))
-    .then(() => runIfMultiSIM(
-                  () => testSendFailed("NonActiveSimCardError", 1)));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_error_of_sms_send.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-function testSendFailed(aCause) {
-  log("testSendFailed, aCause: " + aCause);
-
-  let testReceiver = "+0987654321";
-  let testMessage = "quick fox jump over the lazy dog";
-
-  return sendSmsWithFailure(testReceiver, testMessage)
-    .then((result) => {
-      is(result.error.name, aCause, "Checking failure cause.");
-
-      let domMessage = result.error.data;
-      is(domMessage.id, result.message.id, "Checking message id.");
-      is(domMessage.receiver, testReceiver, "Checking receiver address.");
-      is(domMessage.body, testMessage, "Checking message body.");
-      is(domMessage.delivery, "error", "Checking delivery.");
-      is(domMessage.deliveryStatus, "error", "Checking deliveryStatus.");
-    });
-}
-
-startTestCommon(function testCaseMain() {
-  return ensureMobileConnection()
-    .then(() => setRadioEnabled(mobileConnection, false))
-    .then(() => testSendFailed("RadioDisabledError"))
-    .then(() => setRadioEnabled(mobileConnection, true));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_filter_date.js
+++ /dev/null
@@ -1,119 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const NUMBER_OF_MESSAGES = 10;
-const REMOTE = "5552229797";
-
-function simulateIncomingSms() {
-  let promise = Promise.resolve();
-  let messages = [];
-
-  for (let i = 0; i < NUMBER_OF_MESSAGES; i++) {
-    let text = "Incoming SMS number " + i;
-    promise = promise.then(() => sendTextSmsToEmulatorAndWait(REMOTE, text))
-      .then(function(aMessage) {
-        messages.push(aMessage);
-        return messages;
-      });
-  }
-
-  return promise;
-}
-
-function test(aStartDate, aEndDate, aExpectedMessages) {
-  let filter = {};
-  if (aStartDate !== null) {
-    filter.startDate = aStartDate;
-  }
-  if (aEndDate !== null) {
-    filter.endDate = aEndDate;
-  }
-
-  return getMessages(filter, false)
-    .then(function(aFoundMessages) {
-      log("  Found " + aFoundMessages.length + " messages, expected " +
-          aExpectedMessages.length);
-      is(aFoundMessages.length, aExpectedMessages.length, "aFoundMessages.length");
-    });
-}
-
-function reduceMessages(aMessages, aCompare) {
-  return aMessages.reduce(function(results, message) {
-    if (aCompare(message.timestamp)) {
-      results.push(message);
-    }
-    return results;
-  }, []);
-}
-
-startTestCommon(function testCaseMain() {
-  let startTime, endTime;
-  let allMessages;
-
-  return simulateIncomingSms()
-    .then((aMessages) => {
-      allMessages = aMessages;
-      startTime = aMessages[0].timestamp;
-      endTime = aMessages[NUMBER_OF_MESSAGES - 1].timestamp;
-      log("startTime: " + startTime + ", endTime: " + endTime);
-    })
-
-    // Should return all messages.
-    //
-    .then(() => log("Testing [startTime, )"))
-    .then(() => test(startTime, null, allMessages))
-    .then(() => log("Testing (, endTime]"))
-    .then(() => test(null, endTime, allMessages))
-    .then(() => log("Testing [startTime, endTime]"))
-    .then(() => test(startTime, endTime, allMessages))
-
-    // Should return only messages with timestamp <= startTime.
-    //
-    .then(() => log("Testing [, startTime)"))
-    .then(() => test(null, startTime,
-                     reduceMessages(allMessages,
-                                    (function(a, b) {
-                                      return b <= a;
-                                    }).bind(null, startTime))))
-
-    // Should return only messages with timestamp <= startTime + 1.
-    //
-    .then(() => log("Testing [, startTime + 1)"))
-    .then(() => test(null, startTime + 1,
-                     reduceMessages(allMessages,
-                                    (function(a, b) {
-                                      return b <= a;
-                                    }).bind(null, startTime + 1))))
-
-    // Should return only messages with timestamp >= endTime.
-    //
-    .then(() => log("Testing [endTime, )"))
-    .then(() => test(endTime, null,
-                     reduceMessages(allMessages,
-                                    (function(a, b) {
-                                      return b >= a;
-                                    }).bind(null, endTime))))
-
-    // Should return only messages with timestamp >= endTime - 1.
-    //
-    .then(() => log("Testing [endTime - 1, )"))
-    .then(() => test(endTime - 1, null,
-                     reduceMessages(allMessages,
-                                    (function(a, b) {
-                                      return b >= a;
-                                    }).bind(null, endTime - 1))))
-
-    // Should return none.
-    //
-    .then(() => log("Testing [endTime + 1, )"))
-    .then(() => test(endTime + 1, null, []))
-    .then(() => log("Testing [endTime + 1, endTime + 86400000]"))
-    .then(() => test(endTime + 1, endTime + 86400000, []))
-    .then(() => log("Testing (, startTime - 1]"))
-    .then(() => test(null, startTime - 1, []))
-    .then(() => log("Testing [startTime - 86400000, startTime - 1]"))
-    .then(() => test(startTime - 86400000, startTime - 1, []));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_filter_mixed.js
+++ /dev/null
@@ -1,586 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-const SELF = 5554;
-const NUM_THREADS = 10;
-
-SpecialPowers.addPermission("sms", true, document);
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-
-var manager = window.navigator.mozMobileMessage;
-ok(manager instanceof MozMobileMessageManager,
-   "manager is instance of " + manager.constructor);
-
-var pendingEmulatorCmdCount = 0;
-function sendSmsToEmulator(from, text) {
-  ++pendingEmulatorCmdCount;
-
-  let cmd = "sms send " + from + " " + text;
-  runEmulatorCmd(cmd, function(result) {
-    --pendingEmulatorCmdCount;
-
-    is(result[0], "OK", "Emulator response");
-  });
-}
-
-var tasks = {
-  // List of test fuctions. Each of them should call |tasks.next()| when
-  // completed or |tasks.finish()| to jump to the last one.
-  _tasks: [],
-  _nextTaskIndex: 0,
-
-  push: function(func) {
-    this._tasks.push(func);
-  },
-
-  next: function() {
-    let index = this._nextTaskIndex++;
-    let task = this._tasks[index];
-    try {
-      task();
-    } catch (ex) {
-      ok(false, "test task[" + index + "] throws: " + ex);
-      // Run last task as clean up if possible.
-      if (index != this._tasks.length - 1) {
-        this.finish();
-      }
-    }
-  },
-
-  finish: function() {
-    this._tasks[this._tasks.length - 1]();
-  },
-
-  run: function() {
-    this.next();
-  }
-};
-
-function getAllMessages(callback, filter, reverse) {
-  let messages = [];
-  let request = manager.getMessages(filter, reverse || false);
-  request.onsuccess = function(event) {
-    if (request.result) {
-      messages.push(request.result);
-      request.continue();
-      return;
-    }
-
-    window.setTimeout(callback.bind(null, messages), 0);
-  }
-}
-
-function deleteAllMessages(next) {
-  getAllMessages(function deleteAll(messages) {
-    let message = messages.shift();
-    if (!message) {
-      ok(true, "all messages deleted");
-      tasks.next();
-      return;
-    }
-
-    let request = manager.delete(message.id);
-    request.onsuccess = deleteAll.bind(null, messages);
-    request.onerror = function(event) {
-      ok(false, "failed to delete all messages");
-      tasks.finish();
-    }
-  });
-}
-
-function checkSenderOrReceiver(message, number) {
-  return message.sender == number ||
-         message.sender == ("+1" + number) ||
-         message.receiver == number ||
-         message.receiver == ("+1" + number);
-}
-
-tasks.push(deleteAllMessages);
-
-/**
- * Populate MobileMessageDB with messages to being tests. We'll have NUM_THREADS
- * sent and received messages, and NUM_THREADS/2 unread received messages.
- *
- *   send    to   "+15555315550"
- *   receive from "5555315550", count = 1
- *   mark         received as read
- *
- *   send    to   "+15555315551"
- *   receive from "5555315551", count = 2
- *
- *   send    to   "+15555315552"
- *   receive from "5555315552", count = 3
- *   mark         received as read
- *   ...
- *   send    to   "+15555315559"
- *   receive from "5555315559", count = 10
- */
-var threadIds = [];
-tasks.push(function populateMessages() {
-  let count = 0;
-
-  function sendMessage(iter) {
-    let request = manager.send("+1555531555" + iter, "Nice to meet you");
-    request.onsuccess = function onRequestSuccess(event) {
-      manager.addEventListener("received", onReceived);
-
-      threadIds.push(request.result.threadId);
-
-      sendSmsToEmulator("555531555" + iter, "Nice to meet you, too");
-    }
-    request.onerror = function onRequestError(event) {
-      tasks.finish();
-    }
-  }
-
-  function onReceived(event) {
-    manager.removeEventListener("received", onReceived);
-
-    if (event.message.threadId != threadIds[threadIds.length - 1]) {
-      ok(false, "Thread IDs of sent and received message mismatch.");
-      tasks.finish();
-      return;
-    }
-
-    ++count;
-    if (count % 2) {
-      let request = manager.markMessageRead(event.message.id, true);
-      request.onsuccess = function onRequestSuccess(event) {
-        if (count < NUM_THREADS) {
-          sendMessage(count);
-        } else {
-          tasks.next();
-        }
-      }
-      request.onerror = function onRequestError(event) {
-        tasks.finish();
-      }
-    } else if (count < NUM_THREADS) {
-      sendMessage(count);
-    } else {
-      tasks.next();
-    }
-  }
-
-  sendMessage(count);
-});
-
-var INVALID_NUMBER = "12345";
-var INVALID_NUMBER2 = "6789";
-
-var INVALID_THREAD_ID;
-tasks.push(function assignInvalidThreadID() {
-  INVALID_THREAD_ID = threadIds[threadIds.length - 1] + 1;
-  log("Set INVALID_THREAD_ID to be " + INVALID_THREAD_ID);
-  tasks.next();
-});
-
-tasks.push(function testDeliveryAndNumber() {
-  log("Checking delivery == sent && number == 5555315550");
-  let filter = {
-    delivery: "sent",
-    numbers: ["5555315550"],
-  };
-  getAllMessages(function(messages) {
-    // Only { delivery: "sent", receiver: "+15555315550", read: true }
-    is(messages.length, 1, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      is(message.delivery, filter.delivery, "message delivery");
-      if (!checkSenderOrReceiver(message, filter.numbers[0])) {
-        ok(false, "message sender or receiver number");
-      }
-    }
-
-    getAllMessages(function(messages_r) {
-      is(messages.length, messages_r.length, "message count");
-      for (let i = 0; i < messages_r.length; i++) {
-        is(messages_r[i].id, messages[messages.length - 1 - i].id, "message id");
-      }
-
-      tasks.next();
-    }, filter, true);
-  }, filter);
-});
-
-tasks.push(function testDeliveryAndNumberNotFound() {
-  log("Checking delivery == sent && number == INVALID_NUMBER");
-  let filter = {
-    delivery: "sent",
-    numbers: [INVALID_NUMBER],
-  };
-  getAllMessages(function(messages) {
-    is(messages.length, 0, "message count");
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testDeliveryAndRead() {
-  log("Checking delivery == received && read == true");
-  let filter = {
-    delivery: "received",
-    read: true,
-  }
-  getAllMessages(function(messages) {
-    // { delivery: "received", sender: "5555315550", read: true },
-    // { delivery: "received", sender: "5555315552", read: true },
-    // { delivery: "received", sender: "5555315554", read: true },
-    // { delivery: "received", sender: "5555315556", read: true },
-    // { delivery: "received", sender: "5555315558", read: true },
-    is(messages.length, NUM_THREADS / 2, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      is(message.delivery, filter.delivery, "message delivery");
-      is(message.read, filter.read, "message read");
-    }
-
-    getAllMessages(function(messages_r) {
-      is(messages.length, messages_r.length, "message count");
-      for (let i = 0; i < messages_r.length; i++) {
-        is(messages_r[i].id, messages[messages.length - 1 - i].id, "message id");
-      }
-
-      tasks.next();
-    }, filter, true);
-  }, filter);
-});
-
-tasks.push(function testDeliveryAndReadNotFound() {
-  log("Checking delivery == sent && read == false");
-  let filter = {
-    delivery: "sent",
-    read: false,
-  };
-  getAllMessages(function(messages) {
-    is(messages.length, 0, "message count");
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testDeliveryAndThreadId() {
-  log("Checking delivery == received && threadId == " + threadIds[0]);
-  let filter = {
-    delivery: "sent",
-    threadId: threadIds[0],
-  };
-  getAllMessages(function(messages) {
-    // { delivery: "sent", receiver: "+15555315550", threadId: threadIds[0]}
-    is(messages.length, 1, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      is(message.delivery, filter.delivery, "message delivery");
-      is(message.threadId, filter.threadId, "message threadId");
-    }
-
-    getAllMessages(function(messages_r) {
-      is(messages.length, messages_r.length, "message count");
-      for (let i = 0; i < messages_r.length; i++) {
-        is(messages_r[i].id, messages[messages.length - 1 - i].id, "message id");
-      }
-
-      tasks.next();
-    }, filter, true);
-  }, filter);
-});
-
-tasks.push(function testDeliveryAndThreadIdNotFound() {
-  log("Checking delivery == sent && threadId == INVALID_THREAD_ID");
-  let filter = {
-    delivery: "sent",
-    threadId: INVALID_THREAD_ID,
-  };
-  getAllMessages(function(messages) {
-    is(messages.length, 0, "message count");
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testNumberAndRead() {
-  log("Checking number == 5555315550 && read == true");
-  let filter = {
-    numbers: ["5555315550"],
-    read: true,
-  };
-  getAllMessages(function(messages) {
-    // { delivery: "sent",     receiver: "+15555315550", read: true }
-    // { delivery: "received", sender: "5555315550",     read: true }
-    is(messages.length, 2, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      if (!checkSenderOrReceiver(message, filter.numbers[0])) {
-        ok(false, "message sender or receiver number");
-      }
-      is(message.read, filter.read, "message read");
-    }
-
-    getAllMessages(function(messages_r) {
-      is(messages.length, messages_r.length, "message count");
-      for (let i = 0; i < messages_r.length; i++) {
-        is(messages_r[i].id, messages[messages.length - 1 - i].id, "message id");
-      }
-
-      tasks.next();
-    }, filter, true);
-  }, filter);
-});
-
-tasks.push(function testNumberAndReadNotFound() {
-  log("Checking number == INVALID_NUMBER && read == true");
-  let filter = {
-    numbers: [INVALID_NUMBER],
-    read: true,
-  };
-  getAllMessages(function(messages) {
-    is(messages.length, 0, "message count");
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testNumberAndThreadId() {
-  log("Checking number == 5555315550 && threadId == " + threadIds[0]);
-  let filter = {
-    numbers: ["5555315550"],
-    threadId: threadIds[0],
-  };
-  getAllMessages(function(messages) {
-    // { delivery: "sent",     receiver: "+15555315550", read: true }
-    // { delivery: "received", sender: "5555315550",     read: true }
-    is(messages.length, 2, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      if (!checkSenderOrReceiver(message, filter.numbers[0])) {
-        ok(false, "message sender or receiver number");
-      }
-      is(message.threadId, filter.threadId, "message threadId");
-    }
-
-    getAllMessages(function(messages_r) {
-      is(messages.length, messages_r.length, "message count");
-      for (let i = 0; i < messages_r.length; i++) {
-        is(messages_r[i].id, messages[messages.length - 1 - i].id, "message id");
-      }
-
-      tasks.next();
-    }, filter, true);
-  }, filter);
-});
-
-tasks.push(function testNumberAndThreadIdNotFound() {
-  log("Checking number == INVALID_NUMBER && threadId == INVALID_THREAD_ID");
-  let filter = {
-    numbers: [INVALID_NUMBER],
-    threadId: INVALID_THREAD_ID,
-  };
-  getAllMessages(function(messages) {
-    is(messages.length, 0, "message count");
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testMultipleNumbers() {
-  log("Checking number == 5555315550 || number == 5555315551");
-  let filter = {
-    numbers: ["5555315550", "5555315551"],
-  };
-  getAllMessages(function(messages) {
-    // { delivery: "sent",     receiver: "+15555315550", read: true }
-    // { delivery: "received", sender: "5555315550",     read: true }
-    // { delivery: "sent",     receiver: "+15555315551", read: true }
-    // { delivery: "received", sender: "5555315551",     read: false }
-    is(messages.length, 4, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      if (!(checkSenderOrReceiver(message, filter.numbers[0]) ||
-            checkSenderOrReceiver(message, filter.numbers[1]))) {
-        ok(false, "message sender or receiver number");
-      }
-    }
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testMultipleNumbersNotFound() {
-  log("Checking number == INVALID_NUMBER || number == INVALID_NUMBER2");
-  let filter = {
-    numbers: [INVALID_NUMBER, INVALID_NUMBER2],
-  };
-  getAllMessages(function(messages) {
-    is(messages.length, 0, "message count");
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testDeliveryAndMultipleNumbers() {
-  log("Checking delivery == sent && (number == 5555315550 || number == 5555315551)");
-  let filter = {
-    delivery: "sent",
-    numbers: ["5555315550", "5555315551"],
-  };
-  getAllMessages(function(messages) {
-    // { delivery: "sent", receiver: "+15555315550", read: true }
-    // { delivery: "sent", receiver: "+15555315551", read: true }
-    is(messages.length, 2, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      is(message.delivery, filter.delivery, "message delivery");
-      if (!(checkSenderOrReceiver(message, filter.numbers[0]) ||
-            checkSenderOrReceiver(message, filter.numbers[1]))) {
-        ok(false, "message sender or receiver number");
-      }
-    }
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testMultipleNumbersAndRead() {
-  log("Checking (number == 5555315550 || number == 5555315551) && read == true");
-  let filter = {
-    numbers: ["5555315550", "5555315551"],
-    read: true,
-  };
-  getAllMessages(function(messages) {
-    // { delivery: "sent",     receiver: "+15555315550", read: true }
-    // { delivery: "received", sender: "5555315550",     read: true }
-    // { delivery: "sent",     receiver: "+15555315551", read: true }
-    is(messages.length, 3, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      is(message.read, filter.read, "message read");
-      if (!(checkSenderOrReceiver(message, filter.numbers[0]) ||
-            checkSenderOrReceiver(message, filter.numbers[1]))) {
-        ok(false, "message sender or receiver number");
-      }
-    }
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testMultipleNumbersAndThreadId() {
-  log("Checking (number == 5555315550 || number == 5555315551) && threadId == " + threadIds[0]);
-  let filter = {
-    numbers: ["5555315550", "5555315551"],
-    threadId: threadIds[0],
-  };
-  getAllMessages(function(messages) {
-    // { delivery: "sent",     receiver: "+15555315550", read: true }
-    // { delivery: "received", sender: "5555315550",     read: true }
-    is(messages.length, 2, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      is(message.threadId, filter.threadId, "message threadId");
-      if (!(checkSenderOrReceiver(message, filter.numbers[0]) ||
-            checkSenderOrReceiver(message, filter.numbers[1]))) {
-        ok(false, "message sender or receiver number");
-      }
-    }
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testNationalNumber() {
-  log("Checking number = 5555315550");
-  let filter = {
-    numbers: ["5555315550"],
-  };
-  getAllMessages(function(messages) {
-    // { delivery: "sent",     receiver: "+15555315550", read: true }
-    // { delivery: "received", sender: "5555315550",     read: true }
-    is(messages.length, 2, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      if (!checkSenderOrReceiver(message, filter.numbers[0])) {
-        ok(false, "message sender or receiver number");
-      }
-    }
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testInternationalNumber() {
-  log("Checking number = +15555315550");
-  let filter = {
-    numbers: ["+15555315550"],
-  };
-  getAllMessages(function(messages) {
-    // { delivery: "sent",     receiver: "+15555315550", read: true }
-    // { delivery: "received", sender: "5555315550",     read: true }
-    is(messages.length, 2, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      if (!checkSenderOrReceiver(message, "5555315550")) {
-        ok(false, "message sender or receiver number");
-      }
-    }
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(function testReadAndThreadId() {
-  log("Checking read == true && threadId == " + threadIds[0]);
-  let filter = {
-    read: true,
-    threadId: threadIds[0],
-  };
-  getAllMessages(function(messages) {
-    // { delivery: "sent",     receiver: "+15555315550", read: true }
-    // { delivery: "received", sender: "5555315550",     read: true }
-    is(messages.length, 2, "message count");
-    for (let i = 0; i < messages.length; i++) {
-      let message = messages[i];
-      is(message.read, filter.read, "message read");
-      is(message.threadId, filter.threadId, "message threadId");
-    }
-
-    getAllMessages(function(messages_r) {
-      is(messages.length, messages_r.length, "message count");
-      for (let i = 0; i < messages_r.length; i++) {
-        is(messages_r[i].id, messages[messages.length - 1 - i].id, "message id");
-      }
-
-      tasks.next();
-    }, filter, true);
-  }, filter);
-});
-
-tasks.push(function testReadAndThreadIdNotFound() {
-  log("Checking read == true && threadId == INVALID_THREAD_ID");
-  let filter = {
-    read: true,
-    threadId: INVALID_THREAD_ID,
-  };
-  getAllMessages(function(messages) {
-    is(messages.length, 0, "message count");
-
-    tasks.next();
-  }, filter);
-});
-
-tasks.push(deleteAllMessages);
-
-// WARNING: All tasks should be pushed before this!!!
-tasks.push(function cleanUp() {
-  if (pendingEmulatorCmdCount) {
-    window.setTimeout(cleanUp, 100);
-    return;
-  }
-
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-});
-
-tasks.run();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_filter_number.js
+++ /dev/null
@@ -1,100 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const REMOTE_NATIONAL_NUMBER = "552522555";
-const REMOTE_INTERNATIONAL_NUMBER = "+1" + REMOTE_NATIONAL_NUMBER;
-
-const TEXT_1 = "Nice to meet you";
-const TEXT_2 = "Nice to meet you, too";
-
-// Have a long long subject causes the send fails, so we don't need
-// networking here.
-const MMS_MAX_LENGTH_SUBJECT = 40;
-function genMmsSubject(sep) {
-  return "Hello " + (new Array(MMS_MAX_LENGTH_SUBJECT).join(sep)) + " World!";
-}
-
-function genFailingMms(aReceivers) {
-  return {
-    receivers: aReceivers,
-    subject: genMmsSubject(' '),
-    attachments: [],
-  };
-}
-
-function checkMessage(aNeedle, aValidNumbers) {
-  log("  Verifying " + aNeedle);
-
-  let filter = { numbers: [aNeedle] };
-  return getMessages(filter)
-    .then(function(messages) {
-      // Check the messages are sent to/received from aValidNumbers.
-      is(messages.length, aValidNumbers.length, "messages.length");
-
-      for (let message of messages) {
-        let number;
-        if (message.type == "sms") {
-          number = (message.delivery === "received") ? message.sender
-                                                     : message.receiver;
-        } else {
-          number = message.receivers[0];
-        }
-
-        let index = aValidNumbers.indexOf(number);
-        ok(index >= 0, "message.number");
-        aValidNumbers.splice(index, 1); // Remove from aValidNumbers.
-      }
-
-      is(aValidNumbers.length, 0, "aValidNumbers.length");
-    });
-}
-
-startTestCommon(function testCaseMain() {
-  return Promise.resolve()
-
-    // SMS, MO:international, MT:national
-    .then(() => sendSmsWithSuccess(REMOTE_INTERNATIONAL_NUMBER + '1', TEXT_1))
-    .then(() => sendTextSmsToEmulator(REMOTE_NATIONAL_NUMBER + '1', TEXT_2))
-    // SMS, MO:national, MT:international
-    .then(() => sendSmsWithSuccess(REMOTE_NATIONAL_NUMBER + '2', TEXT_1))
-    .then(() => sendTextSmsToEmulator(REMOTE_INTERNATIONAL_NUMBER + '2', TEXT_2))
-    // MMS, international
-    .then(() => sendMmsWithFailure(genFailingMms([REMOTE_INTERNATIONAL_NUMBER + '3'])))
-    // MMS, national
-    .then(() => sendMmsWithFailure(genFailingMms([REMOTE_NATIONAL_NUMBER + '3'])))
-    // SMS, MO:international, MT:national, ambiguous number.
-    .then(() => sendSmsWithSuccess(REMOTE_INTERNATIONAL_NUMBER + '4', TEXT_1))
-    .then(() => sendTextSmsToEmulator(REMOTE_NATIONAL_NUMBER + '4', TEXT_2))
-    .then(() => sendMmsWithFailure(genFailingMms(["jkalbcjklg"])))
-    .then(() => sendMmsWithFailure(genFailingMms(["jk.alb.cjk.lg"])))
-    // MMS, email
-    .then(() => sendMmsWithFailure(genFailingMms(["jk@alb.cjk.lg"])))
-    // MMS, IPv4
-    .then(() => sendMmsWithFailure(genFailingMms(["55.252.255.54"])))
-    // MMS, IPv6
-    .then(() => sendMmsWithFailure(genFailingMms(["5:5:2:5:2:2:55:54"])))
-
-    .then(() => checkMessage(REMOTE_INTERNATIONAL_NUMBER + '1',
-                             [ REMOTE_INTERNATIONAL_NUMBER + '1',
-                               REMOTE_NATIONAL_NUMBER + '1' ]))
-    .then(() => checkMessage(REMOTE_NATIONAL_NUMBER + '2',
-                             [ REMOTE_NATIONAL_NUMBER + '2',
-                               REMOTE_INTERNATIONAL_NUMBER + '2' ]))
-    .then(() => checkMessage(REMOTE_INTERNATIONAL_NUMBER + '3',
-                             [ REMOTE_INTERNATIONAL_NUMBER + '3',
-                               REMOTE_NATIONAL_NUMBER + '3' ]))
-    .then(() => checkMessage(REMOTE_NATIONAL_NUMBER + '3',
-                             [ REMOTE_NATIONAL_NUMBER + '3',
-                               REMOTE_INTERNATIONAL_NUMBER + '3' ]))
-    .then(() => checkMessage(REMOTE_NATIONAL_NUMBER + '4',
-                             [ REMOTE_NATIONAL_NUMBER + '4',
-                               REMOTE_INTERNATIONAL_NUMBER + '4',
-                               "jkalbcjklg",
-                               "jk.alb.cjk.lg" ]))
-    .then(() => checkMessage("jk@alb.cjk.lg", ["jk@alb.cjk.lg"]))
-    .then(() => checkMessage("55.252.255.54", ["55.252.255.54"]))
-    .then(() => checkMessage("5:5:2:5:2:2:55:54", ["5:5:2:5:2:2:55:54"]))
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_filter_read.js
+++ /dev/null
@@ -1,224 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.addPermission("sms", true, document);
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-
-var manager = window.navigator.mozMobileMessage;
-var numberMsgs = 10;
-var smsList = new Array();
-
-function verifyInitialState() {
-  log("Verifying initial state.");
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-  // Ensure test is starting clean with no existing sms messages
-  deleteAllMsgs(simulateIncomingSms);
-}
-
-function deleteAllMsgs(nextFunction) {
-  let msgList = new Array();
-
-  let cursor = manager.getMessages();
-  ok(cursor instanceof DOMCursor,
-      "cursor is instanceof " + cursor.constructor);
-
-  cursor.onsuccess = function(event) {
-    // Check if message was found
-    if (cursor.result) {
-      msgList.push(cursor.result.id);
-      // Now get next message in the list
-      cursor.continue();
-    } else {
-      // No (more) messages found
-      if (msgList.length) {
-        log("Found " + msgList.length + " SMS messages to delete.");
-        deleteMsgs(msgList, nextFunction);
-      } else {
-        log("No SMS messages found.");
-        nextFunction();
-      }
-    }
-  };
-
-  cursor.onerror = function(event) {
-    log("Received 'onerror' event.");
-    ok(event.target.error, "domerror obj");
-    log("manager.getMessages error: " + event.target.error.name);
-    ok(false,"Could not get SMS messages");
-    cleanUp();
-  };
-}
-
-function deleteMsgs(msgList, nextFunction) {
-  let smsId = msgList.shift();
-
-  log("Deleting SMS (id: " + smsId + ").");
-  let request = manager.delete(smsId);
-  ok(request instanceof DOMRequest,
-      "request is instanceof " + request.constructor);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if (event.target.result) {
-      // Message deleted, continue until none are left
-      if (msgList.length) {
-        deleteMsgs(msgList, nextFunction);
-      } else {
-        log("Finished deleting SMS messages.");
-        nextFunction();
-      }
-    } else {
-      log("SMS delete failed.");
-      ok(false,"manager.delete request returned false");
-      cleanUp();
-    }
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.delete request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function simulateIncomingSms() {
-  let text = "Incoming SMS number " + (smsList.length + 1);
-  let remoteNumber = "5552229797";
-
-  log("Simulating incoming SMS number " + (smsList.length + 1) + " of "
-      + numberMsgs + ".");
-
-  // Simulate incoming sms sent from remoteNumber to our emulator
-  rcvdEmulatorCallback = false;
-  runEmulatorCmd("sms send " + remoteNumber + " " + text, function(result) {
-    is(result[0], "OK", "emulator callback");
-    rcvdEmulatorCallback = true;
-  });
-}
-
-// Callback for incoming sms
-manager.onreceived = function onreceived(event) {
-  log("Received 'onreceived' sms event.");
-  let incomingSms = event.message;
-  log("Received SMS (id: " + incomingSms.id + ").");
-
-  // Add newly received message to array of received msgs
-  smsList.push(incomingSms);
-
-  // Wait for emulator to catch up before continuing
-  waitFor(nextRep,function() {
-    return(rcvdEmulatorCallback);
-  });
-};
-
-function nextRep() {
-  if (smsList.length < numberMsgs) {
-    simulateIncomingSms();
-  } else {
-    // Marking all messages except first as read
-    // Can remove first one from smsList array
-    smsList.shift();
-    markMsgRead(smsList.slice(0));
-  }
-}
-
-function markMsgRead(smsMsgs) {  
-  nextSms = smsMsgs.shift();
-  log("Marking SMS (id: " + nextSms.id + ") as read.");
-  let request = manager.markMessageRead(nextSms.id, true);
-  ok(request instanceof DOMRequest,
-      "request is instanceof " + request.constructor);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if (event.target.result) {
-      // Message marked as read, continue until none are left
-      if (smsMsgs.length) {
-        markMsgRead(smsMsgs);
-      } else {
-        // Done, now test the filter
-        getMsgs();
-      }
-    } else {
-      log("SMS markMessageRead failed.");
-      ok(false,"manager.markMessageRead request returned false");
-      cleanUp();
-    }
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.markMessageRead request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function getMsgs() {
-  let foundSmsList = new Array();
-
-  // Set filter for read messages
-  let filter = { read: true };
-
-  log("Getting the read SMS messages.");
-  let cursor = manager.getMessages(filter, false);
-  ok(cursor instanceof DOMCursor,
-      "cursor is instanceof " + cursor.constructor);
-
-  cursor.onsuccess = function(event) {
-    log("Received 'onsuccess' event.");
-
-    if (cursor.result) {
-      // Another message found
-      log("Got SMS (id: " + cursor.result.id + ").");
-      // Store found message
-      foundSmsList.push(cursor.result);
-      // Now get next message in the list
-      cursor.continue();
-    } else {
-      // No more messages; ensure correct number found
-      if (foundSmsList.length == smsList.length) {
-        log("SMS getMessages returned " + foundSmsList.length +
-            " messages as expected.");
-        verifyFoundMsgs(foundSmsList);
-      } else {
-        log("SMS getMessages returned " + foundSmsList.length +
-            " messages, but expected " + smsList.length + ".");
-        ok(false, "Incorrect number of messages returned by manager.getMessages");
-        deleteAllMsgs(cleanUp);
-      }
-    }
-  };
-
-  cursor.onerror = function(event) {
-    log("Received 'onerror' event.");
-    ok(event.target.error, "domerror obj");
-    log("manager.getMessages error: " + event.target.error.name);
-    ok(false,"Could not get SMS messages");
-    cleanUp();
-  };
-}
-
-function verifyFoundMsgs(foundSmsList) {
-  for (var x = 0; x < foundSmsList.length; x++) {
-    is(foundSmsList[x].id, smsList[x].id, "id");
-    is(foundSmsList[x].read, true, "read");
-  }
-  deleteAllMsgs(cleanUp);
-}
-
-function cleanUp() {
-  manager.onreceived = null;
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-}
-
-// Start the test
-verifyInitialState();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_filter_received.js
+++ /dev/null
@@ -1,236 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.addPermission("sms", true, document);
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-
-var manager = window.navigator.mozMobileMessage;
-var numberMsgs = 10;
-var smsList = new Array();
-
-function verifyInitialState() {
-  log("Verifying initial state.");
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-  // Ensure test is starting clean with no existing sms messages
-  deleteAllMsgs(simulateIncomingSms);
-}
-
-function deleteAllMsgs(nextFunction) {
-  let msgList = new Array();
-
-  let cursor = manager.getMessages();
-  ok(cursor instanceof DOMCursor,
-      "cursor is instanceof " + cursor.constructor);
-
-  cursor.onsuccess = function(event) {
-    // Check if message was found
-    if (cursor.result) {
-      msgList.push(cursor.result.id);
-      // Now get next message in the list
-      cursor.continue();
-    } else {
-      // No (more) messages found
-      if (msgList.length) {
-        log("Found " + msgList.length + " SMS messages to delete.");
-        deleteMsgs(msgList, nextFunction);
-      } else {
-        log("No SMS messages found.");
-        nextFunction();
-      }
-    }
-  };
-
-  cursor.onerror = function(event) {
-    log("Received 'onerror' event.");
-    ok(event.target.error, "domerror obj");
-    log("manager.getMessages error: " + event.target.error.name);
-    ok(false,"Could not get SMS messages");
-    cleanUp();
-  };
-}
-
-function deleteMsgs(msgList, nextFunction) {
-  let smsId = msgList.shift();
-
-  log("Deleting SMS (id: " + smsId + ").");
-  let request = manager.delete(smsId);
-  ok(request instanceof DOMRequest,
-      "request is instanceof " + request.constructor);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if (event.target.result) {
-      // Message deleted, continue until none are left
-      if (msgList.length) {
-        deleteMsgs(msgList, nextFunction);
-      } else {
-        log("Finished deleting SMS messages.");
-        nextFunction();
-      }
-    } else {
-      log("SMS delete failed.");
-      ok(false,"manager.delete request returned false");
-      cleanUp();
-    }
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.delete request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function simulateIncomingSms() {
-  let text = "Incoming SMS number " + (smsList.length + 1);
-  let remoteNumber = "5552229797";
-
-  log("Simulating incoming SMS number " + (smsList.length + 1) + " of "
-      + (numberMsgs - 1) + ".");
-
-  // Simulate incoming sms sent from remoteNumber to our emulator
-  rcvdEmulatorCallback = false;
-  runEmulatorCmd("sms send " + remoteNumber + " " + text, function(result) {
-    is(result[0], "OK", "emulator callback");
-    rcvdEmulatorCallback = true;
-  });
-}
-
-// Callback for incoming sms
-manager.onreceived = function onreceived(event) {
-  log("Received 'onreceived' sms event.");
-  let incomingSms = event.message;
-  log("Received SMS (id: " + incomingSms.id + ").");
-
-  smsList.push(incomingSms);
-
-  // Wait for emulator to catch up before continuing
-  waitFor(nextRep,function() {
-    return(rcvdEmulatorCallback);
-  });
-};
-
-function nextRep() {
-  if (smsList.length < (numberMsgs - 1)) {
-    simulateIncomingSms();
-  } else {
-    // Now send one message also so the filter won't find all
-    sendSms();
-  }
-}
-
-function sendSms() {  
-  let gotSmsSent = false;
-  let gotRequestSuccess = false;
-  let remoteNumber = "5557779999";
-  let text = "Outgoing SMS brought to you by Firefox OS!";
-
-  log("Sending an SMS.");
-
-  manager.onsent = function(event) {
-    log("Received 'onsent' event.");
-    gotSmsSent = true;
-    let sentSms = event.message;
-    log("Sent SMS (id: " + sentSms.id + ").");
-    is(sentSms.delivery, "sent", "delivery");
-    if (gotSmsSent && gotRequestSuccess) {
-      // Test the filter
-      getMsgs();
-    }
-  };
-
-  let request = manager.send(remoteNumber, text);
-  ok(request instanceof DOMRequest,
-      "request is instanceof " + request.constructor);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if(event.target.result) {
-      gotRequestSuccess = true;
-      if (gotSmsSent && gotRequestSuccess) {
-        // Test the filter
-        getMsgs(); 
-      }
-    } else {
-      log("smsrequest returned false for manager.send");
-      ok(false,"SMS send failed");
-      cleanUp();
-    }
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.send request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function getMsgs() {
-  let foundSmsList = new Array();
-
-  // Set filter for received messages
-  let filter = { delivery: "received" };
-
-  log("Getting the received SMS messages.");
-  let cursor = manager.getMessages(filter, false);
-  ok(cursor instanceof DOMCursor,
-      "cursor is instanceof " + cursor.constructor);
-
-  cursor.onsuccess = function(event) {
-    log("Received 'onsuccess' event.");
-
-    if (cursor.result) {
-      // Another message found
-      log("Got SMS (id: " + cursor.result.id + ").");
-      // Store found message
-      foundSmsList.push(cursor.result);
-      // Now get next message in the list
-      cursor.continue();
-    } else {
-      // No more messages; ensure correct number found
-      if (foundSmsList.length == smsList.length) {
-        log("SMS getMessages returned " + foundSmsList.length +
-            " messages as expected.");
-        verifyFoundMsgs(foundSmsList);
-      } else {
-        log("SMS getMessages returned " + foundSmsList.length +
-            " messages, but expected " + smsList.length + ".");
-        ok(false, "Incorrect number of messages returned by manager.getMessages");
-        deleteAllMsgs(cleanUp);
-      }
-    }
-  };
-
-  cursor.onerror = function(event) {
-    log("Received 'onerror' event.");
-    ok(event.target.error, "domerror obj");
-    log("manager.getMessages error: " + event.target.error.name);
-    ok(false,"Could not get SMS messages");
-    cleanUp();
-  };
-}
-
-function verifyFoundMsgs(foundSmsList) {
-  for (var x = 0; x < foundSmsList.length; x++) {
-    is(foundSmsList[x].id, smsList[x].id, "id");
-    is(foundSmsList[x].delivery, "received", "delivery");
-  }
-  deleteAllMsgs(cleanUp);
-}
-
-function cleanUp() {
-  manager.onreceived = null;
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-}
-
-// Start the test
-verifyInitialState();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_filter_sent.js
+++ /dev/null
@@ -1,233 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.addPermission("sms", true, document);
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-
-var manager = window.navigator.mozMobileMessage;
-var numberMsgs = 10;
-var smsList = new Array();
-
-function verifyInitialState() {
-  log("Verifying initial state.");
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-  // Ensure test is starting clean with no existing sms messages
-  deleteAllMsgs(sendSms);
-}
-
-function deleteAllMsgs(nextFunction) {
-  let msgList = new Array();
-
-  let cursor = manager.getMessages();
-  ok(cursor instanceof DOMCursor,
-      "cursor is instanceof " + cursor.constructor);
-
-  cursor.onsuccess = function(event) {
-    // Check if message was found
-    if (cursor.result) {
-      msgList.push(cursor.result.id);
-      // Now get next message in the list
-      cursor.continue();
-    } else {
-      // No (more) messages found
-      if (msgList.length) {
-        log("Found " + msgList.length + " SMS messages to delete.");
-        deleteMsgs(msgList, nextFunction);
-      } else {
-        log("No SMS messages found.");
-        nextFunction();
-      }
-    }
-  };
-
-  cursor.onerror = function(event) {
-    log("Received 'onerror' event.");
-    ok(event.target.error, "domerror obj");
-    log("manager.getMessages error: " + event.target.error.name);
-    ok(false,"Could not get SMS messages");
-    cleanUp();
-  };
-}
-
-function deleteMsgs(msgList, nextFunction) {
-  let smsId = msgList.shift();
-
-  log("Deleting SMS (id: " + smsId + ").");
-  let request = manager.delete(smsId);
-  ok(request instanceof DOMRequest,
-      "request is instanceof " + request.constructor);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if (event.target.result) {
-      // Message deleted, continue until none are left
-      if (msgList.length) {
-        deleteMsgs(msgList, nextFunction);
-      } else {
-        log("Finished deleting SMS messages.");
-        nextFunction();
-      }
-    } else {
-      log("SMS delete failed.");
-      ok(false,"manager.delete request returned false");
-      cleanUp();
-    }
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.delete request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function sendSms() {  
-  let gotSmsSent = false;
-  let gotRequestSuccess = false;
-  let remoteNumber = "5557779999";
-  let text = "Outgoing SMS brought to you by Firefox OS!";
-
-  log("Sending SMS " + (smsList.length + 1) + " of "
-      + (numberMsgs - 1) + ".");
-
-  manager.onsent = function(event) {
-    log("Received 'onsent' event.");
-    gotSmsSent = true;
-    let sentSms = event.message;
-    log("Sent SMS (id: " + sentSms.id + ").");
-    is(sentSms.delivery, "sent", "delivery");
-    smsList.push(sentSms);
-    if (gotSmsSent && gotRequestSuccess) {
-      nextRep();
-    }
-  };
-
-  let request = manager.send(remoteNumber, text);
-  ok(request instanceof DOMRequest,
-      "request is instanceof " + request.constructor);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if(event.target.result) {
-      gotRequestSuccess = true;
-      if (gotSmsSent && gotRequestSuccess) {
-        nextRep(); 
-      }
-    } else {
-      log("smsrequest returned false for manager.send");
-      ok(false,"SMS send failed");
-      cleanUp();
-    }
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.send request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function nextRep() {
-  if (smsList.length < (numberMsgs - 1)) {
-    sendSms();
-  } else {
-    // Now receive one message so filter won't find all
-    simulateIncomingSms();
-  }
-}
-
-function simulateIncomingSms() {
-  let text = "Incoming SMS number " + (smsList.length + 1);
-  let remoteNumber = "5552229797";
-
-  log("Simulating incoming SMS.");
-
-  // Simulate incoming sms sent from remoteNumber to our emulator
-  rcvdEmulatorCallback = false;
-  runEmulatorCmd("sms send " + remoteNumber + " " + text, function(result) {
-    is(result[0], "OK", "emulator callback");
-    rcvdEmulatorCallback = true;
-  });
-}
-
-// Callback for incoming sms
-manager.onreceived = function onreceived(event) {
-  log("Received 'onreceived' sms event.");
-  let incomingSms = event.message;
-  log("Received SMS (id: " + incomingSms.id + ").");
-
-  // Wait for emulator to catch up before continuing
-  waitFor(getMsgs,function() {
-    return(rcvdEmulatorCallback);
-  });
-};
-
-function getMsgs() {
-  let foundSmsList = new Array();
-
-  // Set filter for sent messages
-  let filter = { delivery: "sent" };
-
-  log("Getting the sent SMS messages.");
-  let cursor = manager.getMessages(filter, false);
-  ok(cursor instanceof DOMCursor,
-      "cursor is instanceof " + cursor.constructor);
-
-  cursor.onsuccess = function(event) {
-    log("Received 'onsuccess' event.");
-
-    if (cursor.result) {
-      // Another message found
-      log("Got SMS (id: " + cursor.result.id + ").");
-      // Store found message
-      foundSmsList.push(cursor.result);
-      // Now get next message in the list
-      cursor.continue();
-    } else {
-      // No more messages; ensure correct number found
-      if (foundSmsList.length == smsList.length) {
-        log("SMS getMessages returned " + foundSmsList.length +
-            " messages as expected.");
-        verifyFoundMsgs(foundSmsList);
-      } else {
-        log("SMS getMessages returned " + foundSmsList.length +
-            " messages, but expected " + smsList.length + ".");
-        ok(false, "Incorrect number of messages returned by manager.getMessages");
-        deleteAllMsgs(cleanUp);
-      }
-    }
-  };
-
-  cursor.onerror = function(event) {
-    log("Received 'onerror' event.");
-    ok(event.target.error, "domerror obj");
-    log("manager.getMessages error: " + event.target.error.name);
-    ok(false,"Could not get SMS messages");
-    cleanUp();
-  };
-}
-
-function verifyFoundMsgs(foundSmsList) {
-  for (var x = 0; x < foundSmsList.length; x++) {
-    is(foundSmsList[x].id, smsList[x].id, "id");
-    is(foundSmsList[x].delivery, "sent", "delivery");
-  }
-  deleteAllMsgs(cleanUp);
-}
-
-function cleanUp() {
-  manager.onreceived = null;
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-}
-
-// Start the test
-verifyInitialState();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_filter_unread.js
+++ /dev/null
@@ -1,218 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.addPermission("sms", true, document);
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-
-var manager = window.navigator.mozMobileMessage;
-var numberMsgs = 10;
-var smsList = new Array();
-
-function verifyInitialState() {
-  log("Verifying initial state.");
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-  // Ensure test is starting clean with no existing sms messages
-  deleteAllMsgs(simulateIncomingSms);
-}
-
-function deleteAllMsgs(nextFunction) {
-  let msgList = new Array();
-
-  let cursor = manager.getMessages();
-  ok(cursor instanceof DOMCursor,
-      "cursor is instanceof " + cursor.constructor);
-
-  cursor.onsuccess = function(event) {
-    // Check if message was found
-    if (cursor.result) {
-      msgList.push(cursor.result.id);
-      // Now get next message in the list
-      cursor.continue();
-    } else {
-      // No (more) messages found
-      if (msgList.length) {
-        log("Found " + msgList.length + " SMS messages to delete.");
-        deleteMsgs(msgList, nextFunction);
-      } else {
-        log("No SMS messages found.");
-        nextFunction();
-      }
-    }
-  };
-
-  cursor.onerror = function(event) {
-    log("Received 'onerror' event.");
-    ok(event.target.error, "domerror obj");
-    log("manager.getMessages error: " + event.target.error.name);
-    ok(false,"Could not get SMS messages");
-    cleanUp();
-  };
-}
-
-function deleteMsgs(msgList, nextFunction) {
-  let smsId = msgList.shift();
-
-  log("Deleting SMS (id: " + smsId + ").");
-  let request = manager.delete(smsId);
-  ok(request instanceof DOMRequest,
-      "request is instanceof " + request.constructor);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if (event.target.result) {
-      // Message deleted, continue until none are left
-      if (msgList.length) {
-        deleteMsgs(msgList, nextFunction);
-      } else {
-        log("Finished deleting SMS messages.");
-        nextFunction();
-      }
-    } else {
-      log("SMS delete failed.");
-      ok(false,"manager.delete request returned false");
-      cleanUp();
-    }
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.delete request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function simulateIncomingSms() {
-  let text = "Incoming SMS number " + (smsList.length + 1);
-  let remoteNumber = "5552229797";
-
-  log("Simulating incoming SMS number " + (smsList.length + 1) + " of "
-      + numberMsgs + ".");
-
-  // Simulate incoming sms sent from remoteNumber to our emulator
-  rcvdEmulatorCallback = false;
-  runEmulatorCmd("sms send " + remoteNumber + " " + text, function(result) {
-    is(result[0], "OK", "emulator callback");
-    rcvdEmulatorCallback = true;
-  });
-}
-
-// Callback for incoming sms
-manager.onreceived = function onreceived(event) {
-  log("Received 'onreceived' sms event.");
-  let incomingSms = event.message;
-  log("Received SMS (id: " + incomingSms.id + ").");
-
-  // Add newly received message to array of received msgs
-  smsList.push(incomingSms);
-
-  // Wait for emulator to catch up before continuing
-  waitFor(nextRep,function() {
-    return(rcvdEmulatorCallback);
-  });
-};
-
-function nextRep() {
-  if (smsList.length < numberMsgs) {
-    simulateIncomingSms();
-  } else {
-    markMsgRead();
-  }
-}
-
-function markMsgRead() {
-  // Mark first message read so not all will be found by filter
-  log("Marking SMS (id: " + smsList[0].id + ") as read.");
-  let request = manager.markMessageRead(smsList[0].id, true);
-  ok(request instanceof DOMRequest,
-      "request is instanceof " + request.constructor);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if (event.target.result) {
-      // First message was marked read, so remove from expected smsList
-      smsList.shift();
-      // Now test the filter
-      getMsgs();
-    } else {
-      log("SMS markMessageRead failed.");
-      ok(false,"manager.markMessageRead request returned false");
-      cleanUp();
-    }
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.markMessageRead request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function getMsgs() {
-  let foundSmsList = new Array();
-
-  // Set filter for read messages
-  let filter = { read: false };
-
-  log("Getting the unread SMS messages.");
-  let cursor = manager.getMessages(filter, false);
-  ok(cursor instanceof DOMCursor,
-      "cursor is instanceof " + cursor.constructor);
-
-  cursor.onsuccess = function(event) {
-    log("Received 'onsuccess' event.");
-
-    if (cursor.result) {
-      // Another message found
-      log("Got SMS (id: " + cursor.result.id + ").");
-      // Store found message
-      foundSmsList.push(cursor.result);
-      // Now get next message in the list
-      cursor.continue();
-    } else {
-      // No more messages; ensure correct number found
-      if (foundSmsList.length == smsList.length) {
-        log("SMS getMessages returned " + foundSmsList.length +
-            " messages as expected.");
-        verifyFoundMsgs(foundSmsList);
-      } else {
-        log("SMS getMessages returned " + foundSmsList.length +
-            " messages, but expected " + smsList.length + ".");
-        ok(false, "Incorrect number of messages returned by manager.getMessages");
-        deleteAllMsgs(cleanUp);
-      }
-    }
-  };
-
-  cursor.onerror = function(event) {
-    log("Received 'onerror' event.");
-    ok(event.target.error, "domerror obj");
-    log("manager.getMessages error: " + event.target.error.name);
-    ok(false,"Could not get SMS messages");
-    cleanUp();
-  };
-}
-
-function verifyFoundMsgs(foundSmsList) {
-  for (var x = 0; x < foundSmsList.length; x++) {
-    is(foundSmsList[x].id, smsList[x].id, "id");
-    is(foundSmsList[x].read, false, "read");
-  }
-  deleteAllMsgs(cleanUp);
-}
-
-function cleanUp() {
-  manager.onreceived = null;
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-}
-
-// Start the test
-verifyInitialState();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_getmessage.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const REMOTE = "5559997777"; // the remote number
-const EMULATOR = "15555215554"; // the emulator's number
-
-const IN_TEXT = "Incoming SMS message. Mozilla Firefox OS!";
-const OUT_TEXT = "Outgoing SMS message. Mozilla Firefox OS!";
-
-startTestBase(function testCaseMain() {
-  let incomingSms, outgoingSms;
-
-  return ensureMobileMessage()
-
-    .then(() => sendTextSmsToEmulatorAndWait(REMOTE, IN_TEXT))
-    .then((aMessage) => { incomingSms = aMessage; })
-
-    .then(() => sendSmsWithSuccess(REMOTE, OUT_TEXT))
-    .then((aMessage) => { outgoingSms = aMessage; })
-
-    .then(() => getMessage(incomingSms.id))
-    .then((aMessage) => compareSmsMessage(aMessage, incomingSms))
-
-    .then(() => getMessage(outgoingSms.id))
-    .then((aMessage) => compareSmsMessage(aMessage, outgoingSms))
-
-    .then(deleteAllMessages);
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_getmessage_notfound.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const TEXT = "Incoming SMS message. Mozilla Firefox OS!";
-const REMOTE = "5559997777";
-
-function getNonExistentMsg(aId) {
-  log("Attempting to get non-existent message (id: " + aId + ").");
-
-  return getMessage(aId)
-    .then(function onresolve() {
-      ok(false, "request succeeded when tried to get non-existent sms");
-    }, function onreject(aError) {
-      ok(aError, "DOMError");
-      is(aError.name, "NotFoundError", "error.name");
-    });
-}
-
-function getMsgInvalidId(aId) {
-  log("Attempting to get sms with invalid id (id: " + aId + ").");
-
-  return getMessage(aId)
-    .then(function onresolve() {
-      ok(false, "request succeeded when tried to get message with " +
-                "invalid id (id: " + aId + ").");
-    }, function onreject(aError) {
-      ok(aError, "DOMError");
-      is(aError.name, "NotFoundError", "error.name");
-    });
-}
-
-startTestBase(function testCaseMain() {
-  let lastMessageId;
-
-  return ensureMobileMessage()
-
-    .then(() => sendTextSmsToEmulatorAndWait(REMOTE, TEXT))
-    .then((aMessage) => { lastMessageId = aMessage.id; })
-
-    .then(() => getNonExistentMsg(lastMessageId + 1))
-    .then(() => getMsgInvalidId(-1))
-    .then(() => getMsgInvalidId(0))
-
-    .then(deleteAllMessages);
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_getmessages.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const NUMBER_OF_MESSAGES = 10;
-const REMOTE = "5552229797";
-
-function simulateIncomingSms() {
-  let promise = Promise.resolve();
-  let messages = [];
-
-  for (let i = 0; i< NUMBER_OF_MESSAGES; i++) {
-    let text = "Incoming SMS number " + i;
-    promise = promise.then(() => sendTextSmsToEmulatorAndWait(REMOTE, text))
-      .then(function(aMessage) {
-        messages.push(aMessage);
-        return messages;
-      });
-  }
-
-  return promise;
-}
-
-function verifyFoundMsgs(foundSmsList, smsList) {
-  for (let x = 0; x < NUMBER_OF_MESSAGES; x++) {
-    compareSmsMessage(foundSmsList[x], smsList[x]);
-  }
-
-  log("Content in all of the returned SMS messages is correct.");
-}
-
-startTestCommon(function testCaseMain() {
-  let incomingMessages;
-
-  return simulateIncomingSms()
-    .then((aMessages) => { incomingMessages = aMessages; })
-
-    .then(() => getMessages(null, false))
-    .then((aFoundMessages) => verifyFoundMsgs(aFoundMessages, incomingMessages))
-
-    .then(() => getMessages(null, true))
-    .then((aFoundMessages) => verifyFoundMsgs(aFoundMessages,
-                                              incomingMessages.slice().reverse()));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_getsegmentinfofortext.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-// Copied from dom/system/gonk/ril_consts.js.
-const PDU_MAX_USER_DATA_7BIT = 160;
-
-function test(text, segments, charsPerSegment, charsAvailableInLastSegment) {
-  log("Testing '" + text + "' ...");
-
-  let domRequest = manager.getSegmentInfoForText(text);
-  ok(domRequest, "DOMRequest object returned.");
-
-  return domRequest.then(function(aResult) {
-    ok(aResult, "result = " + JSON.stringify(aResult));
-
-    is(aResult.segments, segments, "result.segments");
-    is(aResult.charsPerSegment, charsPerSegment, "result.charsPerSegment");
-    is(aResult.charsAvailableInLastSegment, charsAvailableInLastSegment,
-       "result.charsAvailableInLastSegment");
-  });
-}
-
-startTestCommon(function() {
-  // Ensure we always begin with strict 7bit encoding set to false.
-  return pushPrefEnv({ set: [["dom.sms.strict7BitEncoding", false]] })
-
-    .then(() => test(null,      1, PDU_MAX_USER_DATA_7BIT, (PDU_MAX_USER_DATA_7BIT - "null".length)))
-    .then(() => test(undefined, 1, PDU_MAX_USER_DATA_7BIT, (PDU_MAX_USER_DATA_7BIT - "undefined".length)))
-
-    .then(() => test(0,         1, PDU_MAX_USER_DATA_7BIT, (PDU_MAX_USER_DATA_7BIT - "0".length)))
-    .then(() => test(1.0,       1, PDU_MAX_USER_DATA_7BIT, (PDU_MAX_USER_DATA_7BIT - "1".length)))
-
-    // Testing empty object.  The empty object extends to "[object Object]" and
-    // both '[' and ']' are in default single shift table, so each of them
-    // takes two septets.
-    .then(() => test({},        1, PDU_MAX_USER_DATA_7BIT, (PDU_MAX_USER_DATA_7BIT - (("" + {}).length + 2))))
-
-    .then(function() {
-      let date = new Date();
-      return test(date,         1, PDU_MAX_USER_DATA_7BIT, (PDU_MAX_USER_DATA_7BIT - ("" + date).length));
-    })
-
-    .then(() => test("",        1, PDU_MAX_USER_DATA_7BIT, (PDU_MAX_USER_DATA_7BIT - "".length)));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_getthreads.js
+++ /dev/null
@@ -1,182 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 90000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-/**
- * Create messages to be tested.
- *
- * @param aMessages
- *        An array of
- *          { 'incoming': [false|true],
- *            'address': [Phone Number]
- *            'text': [Text Body] };
- *
- * @return A deferred promise.
- */
-function createMessages(aMessages) {
-  let promise = Promise.resolve();
-  aMessages.forEach((aMessage) => {
-    promise = promise.then((aMessage.incoming) ?
-      () => sendTextSmsToEmulatorAndWait(aMessage.address, aMessage.text) :
-      () => sendSmsWithSuccess(aMessage.address, aMessage.text));
-  });
-
-  return promise;
-}
-
-function checkThreads(aMessages, aNotMerged) {
-  return getAllThreads().then((aThreads) => {
-    let threadCount = aThreads.length;
-
-    if (aNotMerged) {
-      // Threads are retrieved in reversed order of 'lastTimestamp'.
-      aThreads.reverse();
-      is(threadCount, aMessages.length, "Number of Threads.");
-      for (let i = 0; i < threadCount; i++) {
-        let thread = aThreads[i];
-        let message = aMessages[i];
-        is(thread.unreadCount, message.incoming ? 1 : 0, "Unread Count.");
-        is(thread.participants.length, 1, "Number of Participants.");
-        is(thread.participants[0], message.address, "Participants.");
-        is(thread.body, message.text, "Thread Body.");
-      }
-
-      return;
-    }
-
-    let lastBody = aMessages[aMessages.length - 1].text;
-    let unreadCount = 0;
-    let mergedThread = aThreads[0];
-    aMessages.forEach((aMessage) => {
-      if (aMessage.incoming) {
-        unreadCount++;
-      }
-    });
-    is(threadCount, 1, "Number of Threads.");
-    is(mergedThread.unreadCount, unreadCount, "Unread Count.");
-    is(mergedThread.participants.length, 1, "Number of Participants.");
-    is(mergedThread.participants[0], aMessages[0].address, "Participants.");
-    // Thread is updated according to the device 'timestamp' of the message record
-    // instead of the one from SMSC, so 'mergedThread.body' is expected to be the
-    // same to the body for the last saved SMS.
-    // See https://hg.mozilla.org/mozilla-central/annotate/436686833af0/dom/mobilemessage/gonk/MobileMessageDB.jsm#l2247
-    is(mergedThread.body, lastBody, "Thread Body.");
-  });
-}
-
-function testGetThreads(aMessages, aNotMerged) {
-  aNotMerged = !!aNotMerged;
-  log("aMessages: " + JSON.stringify(aMessages));
-  log("aNotMerged: " + aNotMerged);
-  return createMessages(aMessages)
-    .then(() => checkThreads(aMessages, aNotMerged))
-    .then(() => deleteAllMessages());
-}
-
-startTestCommon(function testCaseMain() {
-  // [Thread 1]
-  // One message only, body = "thread 1";
-  // All sent message, unreadCount = 0;
-  // One participant only, participants = ["5555211001"].
-  return testGetThreads([{ incoming: false, address: "5555211001", text: "thread 1" }])
-  // [Thread 2]
-  // Two messages, body = "thread 2-2";
-  // All sent message, unreadCount = 0;
-  // One participant with two aliased addresses, participants = ["5555211002"].
-    .then(() => testGetThreads([{ incoming: false, address: "5555211002", text: "thread 2-1" },
-                                { incoming: false, address: "+15555211002", text: "thread 2-2" }]))
-  // [Thread 3]
-  // Two messages, body = "thread 3-2";
-  // All sent message, unreadCount = 0;
-  // One participant with two aliased addresses, participants = ["+15555211003"].
-    .then(() => testGetThreads([{ incoming: false, address: "+15555211003", text: "thread 3-1" },
-                                { incoming: false, address: "5555211003", text: "thread 3-2" }]))
-  // [Thread 4]
-  // One message only, body = "thread 4";
-  // All received message, unreadCount = 1;
-  // One participant only, participants = ["5555211004"].
-    .then(() => testGetThreads([{ incoming: true, address: "5555211004", text: "thread 4" }]))
-  // [Thread 5]
-  // All received messages, unreadCount = 2;
-  // One participant with two aliased addresses, participants = ["5555211005"].
-    .then(() => testGetThreads([{ incoming: true, address: "5555211005", text: "thread 5-1" },
-                                { incoming: true, address: "+15555211005", text: "thread 5-2" },]))
-  // [Thread 6]
-  // All received messages, unreadCount = 2;
-  // One participant with two aliased addresses, participants = ["+15555211006"].
-    .then(() => testGetThreads([{ incoming: true, address: "+15555211006", text: "thread 6-1" },
-                                { incoming: true, address: "5555211006", text: "thread 6-2" }]))
-  // [Thread 7]
-  // 2 sent and then 2 received messages, unreadCount = 2;
-  // One participant with two aliased addresses, participants = ["5555211007"].
-    .then(() => testGetThreads([{ incoming: false, address: "5555211007", text: "thread 7-1" },
-                                { incoming: false, address: "+15555211007", text: "thread 7-2" },
-                                { incoming: true, address: "5555211007", text: "thread 7-3" },
-                                { incoming: true, address: "+15555211007", text: "thread 7-4" }]))
-  // [Thread 8]
-  // 2 received and then 2 sent messages, unreadCount = 2;
-  // One participant with two aliased addresses, participants = ["5555211008"].
-    .then(() => testGetThreads([{ incoming: true, address: "5555211008", text: "thread 8-1" },
-                                { incoming: true, address: "+15555211008", text: "thread 8-2" },
-                                { incoming: false, address: "5555211008", text: "thread 8-3" },
-                                { incoming: false, address: "+15555211008", text: "thread 8-4" }]))
-  // [Thread 9]
-  // Three sent message, unreadCount = 0;
-  // One participant with three aliased addresses, participants = ["+15555211009"].
-    .then(() => testGetThreads([{ incoming: false, address: "+15555211009", text: "thread 9-1" },
-                                { incoming: false, address: "01115555211009", text: "thread 9-2" },
-                                { incoming: false, address: "5555211009", text: "thread 9-3" }]))
-  // [Thread 10]
-  // Three sent message, unreadCount = 0;
-  // One participant with three aliased addresses, participants = ["+15555211010"].
-    .then(() => testGetThreads([{ incoming: false, address: "+15555211010", text: "thread 10-1" },
-                                { incoming: false, address: "5555211010", text: "thread 10-2" },
-                                { incoming: false, address: "01115555211010", text: "thread 10-3" }]))
-  // [Thread 11]
-  // Three sent message, unreadCount = 0;
-  // One participant with three aliased addresses, participants = ["01115555211011"].
-    .then(() => testGetThreads([{ incoming: false, address: "01115555211011", text: "thread 11-1" },
-                                { incoming: false, address: "5555211011", text: "thread 11-2" },
-                                { incoming: false, address: "+15555211011", text: "thread 11-3" }]))
-  // [Thread 12]
-  // Three sent message, unreadCount = 0;
-  // One participant with three aliased addresses, participants = ["01115555211012"].
-    .then(() => testGetThreads([{ incoming: false, address: "01115555211012", text: "thread 12-1" },
-                                { incoming: false, address: "+15555211012", text: "thread 12-2" },
-                                { incoming: false, address: "5555211012", text: "thread 12-3" }]))
-  // [Thread 13]
-  // Three sent message, unreadCount = 0;
-  // One participant with three aliased addresses, participants = ["5555211013"].
-    .then(() => testGetThreads([{ incoming: false, address: "5555211013", text: "thread 13-1" },
-                                { incoming: false, address: "+15555211013", text: "thread 13-2" },
-                                { incoming: false, address: "01115555211013", text: "thread 13-3" }]))
-  // [Thread 14]
-  // Three sent message, unreadCount = 0;
-  // One participant with three aliased addresses, participants = ["5555211014"].
-    .then(() => testGetThreads([{ incoming: false, address: "5555211014", text: "thread 14-1" },
-                                { incoming: false, address: "01115555211014", text: "thread 14-2" },
-                                { incoming: false, address: "+15555211014", text: "thread 14-3" }]))
-  // [Thread 15]
-  // One sent message, unreadCount = 0;
-  // One participant but might be merged to 555211015, participants = ["5555211015"].
-  // [Thread 16]
-  // One sent message, unreadCount = 0;
-  // One participant but might be merged to 5555211015, participants = ["555211015"].
-    .then(() => testGetThreads([{ incoming: false, address: "5555211015", text: "thread 15-1" },
-                                { incoming: false, address: "555211015", text: "thread 16-1" }],
-                                true))
-  // [Thread 17]
-  // Brazil number format: +55-aa-nnnnnnnn. (2-digit area code and 8-digit number)
-  // Two sent messages, unreadCount = 0;
-  // One participant with two aliased addresses, participants = ["+551155211017"].
-    .then(() => testGetThreads([{ incoming: false, address: "+551155211017", text: "thread 17-1" },
-                                { incoming: false, address: "1155211017", text: "thread 17-2" }]))
-  // [Thread 18]
-  // Brazil number format: +55-aa-nnnnnnnn. (2-digit area code and 8-digit number)
-  // All sent messages, unreadCount = 0;
-  // One participant with two aliased addresses, participants = ["1155211018"].
-    .then(() => testGetThreads([{ incoming: false, address: "1155211018", text: "thread 18-1" },
-                                { incoming: false, address: "+551155211018", text: "thread 18-2" }]));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_incoming.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const SENDER = "5555552368"; // the remote number
-const RECEIVER = "15555215554"; // the emulator's number
-
-const SHORT_BODY = "Hello SMS world!";
-const LONG_BODY = new Array(17).join(SHORT_BODY);
-ok(LONG_BODY.length > 160, "LONG_BODY.length");
-
-function checkMessage(aMessage, aBody) {
-  ok(aMessage instanceof SmsMessage, "Message is instanceof SmsMessage");
-
-  is(aMessage.type, "sms", "message.type");
-  ok(aMessage.id, "message.id");
-  ok(aMessage.threadId, "message.threadId");
-  ok(aMessage.iccId, "message.iccId");
-  is(aMessage.delivery, "received", "message.delivery");
-  is(aMessage.deliveryStatus, "success", "message.deliveryStatus");
-  is(aMessage.sender, SENDER, "message.sender");
-  is(aMessage.receiver, RECEIVER, "message.receiver");
-  is(aMessage.body, aBody, "message.body");
-  is(aMessage.messageClass, "normal", "message.messageClass");
-  ok(aMessage.timestamp, "message.timestamp");
-  is(aMessage.deliveryTimestamp, 0, "message.deliveryTimestamp");
-  ok(aMessage.sentTimestamp, "message.sentTimestamp");
-  is(aMessage.read, false, "message.read");
-};
-
-function test(aBody) {
-  return sendTextSmsToEmulatorAndWait(SENDER, aBody)
-    .then((aMessage) => checkMessage(aMessage, aBody));
-}
-
-startTestBase(function testCaseMain() {
-  return ensureMobileMessage()
-    .then(() => test(SHORT_BODY))
-    .then(() => test(LONG_BODY));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_incoming_delete.js
+++ /dev/null
@@ -1,138 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-SpecialPowers.addPermission("sms", true, document);
-
-const SENDER = "5555552368"; // the remote number
-const RECEIVER = "15555215554"; // the emulator's number
-
-var manager = window.navigator.mozMobileMessage;
-var msgText = "Mozilla Firefox OS!";
-
-function verifyInitialState() {
-  log("Verifying initial state.");
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-  simulateIncomingSms();  
-}
-
-function simulateIncomingSms() {
-  log("Simulating incoming SMS.");
-
-  manager.onreceived = function onreceived(event) {
-    log("Received 'onreceived' event.");
-    let incomingSms = event.message;
-    ok(incomingSms, "incoming sms");
-    ok(incomingSms.id, "sms id");
-    log("Received SMS (id: " + incomingSms.id + ").");
-    ok(incomingSms.threadId, "thread id");
-    is(incomingSms.body, msgText, "msg body");
-    is(incomingSms.delivery, "received", "delivery");
-    is(incomingSms.deliveryStatus, "success", "deliveryStatus");
-    is(incomingSms.read, false, "read");
-    is(incomingSms.receiver, RECEIVER, "receiver");
-    is(incomingSms.sender, SENDER, "sender");
-    is(incomingSms.messageClass, "normal", "messageClass");
-    is(incomingSms.deliveryTimestamp, 0, "deliveryTimestamp is 0");
-
-    verifySmsExists(incomingSms);
-  };
-  runEmulatorCmd("sms send " + SENDER + " " + msgText, function(result) {
-    is(result[0], "OK", "emulator output");
-  });
-}
-
-function verifySmsExists(incomingSms) {
-  log("Getting SMS (id: " + incomingSms.id + ").");
-  let requestRet = manager.getMessage(incomingSms.id);
-  ok(requestRet, "smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    ok(event.target.result, "smsrequest event.target.result");
-    let foundSms = event.target.result;
-    is(foundSms.id, incomingSms.id, "found SMS id matches");
-    is(foundSms.threadId, incomingSms.threadId, "found SMS thread id matches");
-    is(foundSms.body, msgText, "found SMS msg text matches");
-    is(foundSms.delivery, "received", "delivery");
-    is(foundSms.deliveryStatus, "success", "deliveryStatus");
-    is(foundSms.read, false, "read");
-    is(foundSms.receiver, RECEIVER, "receiver");
-    is(foundSms.sender, SENDER, "sender");
-    is(foundSms.messageClass, "normal", "messageClass");
-    log("Got SMS (id: " + foundSms.id + ") as expected.");
-    deleteSms(incomingSms);
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    is(event.target.error.name, "NotFoundError", "error returned");
-    log("Could not get SMS (id: " + incomingSms.id + ") but should have.");
-    ok(false,"SMS was not found");
-    cleanUp();
-  };
-}
-
-function deleteSms(smsMsgObj){
-  log("Deleting SMS (id: " + smsMsgObj.id + ") using smsmsg obj parameter.");
-  let requestRet = manager.delete(smsMsgObj);
-  ok(requestRet,"smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if(event.target.result){
-      verifySmsDeleted(smsMsgObj.id);
-    } else {
-      log("smsrequest returned false for manager.delete");
-      ok(false,"SMS delete failed");
-      cleanUp();
-    }
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.delete request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function verifySmsDeleted(smsId) {
-  log("Getting SMS (id: " + smsId + ").");
-  let requestRet = manager.getMessage(smsId);
-  ok(requestRet, "smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    ok(event.target.result, "smsrequest event.target.result");
-    let foundSms = event.target.result;
-    is(foundSms.id, smsId, "found SMS id matches");
-    is(foundSms.body, msgText, "found SMS msg text matches");
-    log("Got SMS (id: " + foundSms.id + ") but should not have.");
-    ok(false, "SMS was not deleted");
-    cleanUp();
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    is(event.target.error.name, "NotFoundError", "error returned");
-    log("Could not get SMS (id: " + smsId + ") as expected.");
-    cleanUp();
-  };
-}
-
-function cleanUp() {
-  manager.onreceived = null;
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-}
-
-// Start the test
-verifyInitialState();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_incoming_max_segments.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-SpecialPowers.addPermission("sms", true, document);
-
-var manager = window.navigator.mozMobileMessage;
-// https://developer.mozilla.org/en-US/docs/DOM/SmsManager
-var maxCharsPerSms = 160;
-var maxSegments = 10; // 10 message segments concatenated into 1 multipart SMS
-
-const REMOTE = "5551234567"; // the remote number
-const EMULATOR = "15555215554"; // the emulator's number
-
-function verifyInitialState() {
-  log("Verifying initial state.");
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-  simulateIncomingSms();
-}
-
-function simulateIncomingSms() {
-  let msgText = "";
-
-  // Build the message text
-  msgText = new Array((maxCharsPerSms * maxSegments) + 1).join('a');
-  log("Simulating incoming multipart SMS (" + msgText.length +
-      " chars total).");
-
-  manager.onreceived = function onreceived(event) {
-    manager.onreceived = null;
-    log("Received 'onreceived' event.");
-
-    let incomingSms = event.message;
-    ok(incomingSms, "incoming sms");
-    ok(incomingSms.id, "sms id");
-    log("Received SMS (id: " + incomingSms.id + ").");
-    ok(incomingSms.threadId, "thread id");
-    is(incomingSms.body.length, msgText.length, "msg body length");
-    is(incomingSms.body, msgText, "msg body");
-    is(incomingSms.delivery, "received", "delivery");
-    is(incomingSms.read, false, "read");
-    is(incomingSms.receiver, EMULATOR, "receiver");
-    is(incomingSms.sender, REMOTE, "sender");
-    is(incomingSms.deliveryTimestamp, 0, "deliveryTimestamp is 0");
-
-    verifySmsExists(incomingSms);
-  };
-  runEmulatorCmd("sms send " + REMOTE + " " + msgText, function(result) {
-    is(result[0], "OK", "emulator output");
-  });
-}
-
-function verifySmsExists(incomingSms) {
-  log("Getting SMS (id: " + incomingSms.id + ").");
-  let requestRet = manager.getMessage(incomingSms.id);
-  ok(requestRet, "smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    ok(event.target.result, "smsrequest event.target.result");
-    let foundSms = event.target.result;
-    is(foundSms.id, incomingSms.id, "found SMS id matches");
-    is(foundSms.body.length, incomingSms.body.length, "SMS text length");
-    is(foundSms.body, incomingSms.body, "found SMS msg text matches");
-    log("Got SMS (id: " + foundSms.id + ") as expected.");
-    deleteSms(incomingSms);
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    is(event.target.error.name, "NotFoundError", "error returned");
-    log("Could not get SMS (id: " + incomingSms.id + ") but should have.");
-    ok(false, "SMS was not found");
-    cleanUp();
-  };
-}
-
-function deleteSms(smsMsgObj){
-  log("Deleting SMS (id: " + smsMsgObj.id + ") using smsmsg obj parameter.");
-  let requestRet = manager.delete(smsMsgObj);
-  ok(requestRet, "smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if (event.target.result) {
-      cleanUp();
-    } else {
-      log("smsrequest returned false for manager.delete");
-      ok(false, "SMS delete failed");
-      cleanUp();
-    }
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.delete request returned unexpected error: " +
-              event.target.error.name);
-    cleanUp();
-  };
-}
-
-function cleanUp() {
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-}
-
-// Start the test
-verifyInitialState();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_invalid_address.js
+++ /dev/null
@@ -1,140 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-const MMS_MAX_LENGTH_SUBJECT = 40;
-
-SpecialPowers.addPermission("sms", true, document);
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-
-var tasks = {
-  // List of test fuctions. Each of them should call |tasks.next()| when
-  // completed or |tasks.finish()| to jump to the last one.
-  _tasks: [],
-  _nextTaskIndex: 0,
-
-  push: function(func) {
-    this._tasks.push(func);
-  },
-
-  next: function() {
-    let index = this._nextTaskIndex++;
-    let task = this._tasks[index];
-    try {
-      task();
-    } catch (ex) {
-      ok(false, "test task[" + index + "] throws: " + ex);
-      // Run last task as clean up if possible.
-      if (index != this._tasks.length - 1) {
-        this.finish();
-      }
-    }
-  },
-
-  finish: function() {
-    this._tasks[this._tasks.length - 1]();
-  },
-
-  run: function() {
-    this.next();
-  }
-};
-
-var manager;
-
-function getAllMessages(callback, filter, reverse) {
-  let messages = [];
-  let request = manager.getMessages(filter, reverse || false);
-  request.onsuccess = function(event) {
-    if (request.result) {
-      messages.push(request.result);
-      request.continue();
-      return;
-    }
-
-    window.setTimeout(callback.bind(null, messages), 0);
-  }
-}
-
-function deleteAllMessages() {
-  getAllMessages(function deleteAll(messages) {
-    let message = messages.shift();
-    if (!message) {
-      ok(true, "all messages deleted");
-      tasks.next();
-      return;
-    }
-
-    let request = manager.delete(message.id);
-    request.onsuccess = deleteAll.bind(null, messages);
-    request.onerror = function(event) {
-      ok(false, "failed to delete all messages");
-      tasks.finish();
-    }
-  });
-}
-
-function testInvalidAddressForSMS(aInvalidAddr)  {
-  log("manager.send(...) should get 'InvalidAddressError' error " +
-      "when attempting to send SMS to: " + aInvalidAddr);
-
-  let request = manager.send(aInvalidAddr, "Test");
-
-  request.onerror = function(event) {
-    log("Received 'onerror' DOMRequest event.");
-    let error = event.target.error;
-    ok(error instanceof DOMError, "should be a valid DOMError object");
-    ok(error.name === "InvalidAddressError", "should be 'InvalidAddressError'");
-    tasks.next();
-  };
-}
-
-function testInvalidAddressForMMS(aInvalidAddrs)  {
-  log("manager.sendMMS(...) should get 'InvalidAddressError' error " +
-      "when attempting to send MMS to: " + aInvalidAddrs);
-
-  let request = manager.sendMMS({
-    subject: "Test",
-    receivers: aInvalidAddrs,
-    attachments: [],
-  });
-
-  request.onerror = function(event) {
-    log("Received 'onerror' DOMRequest event.");
-    let error = event.target.error;
-    ok(error instanceof DOMError, "should be a valid DOMError object");
-    ok(error.name === "InvalidAddressError", "should be 'InvalidAddressError'");
-    tasks.next();
-  };
-}
-
-tasks.push(function() {
-  log("Verifying initial state.");
-
-  manager = window.navigator.mozMobileMessage;
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-
-  tasks.next();
-});
-
-// Test sending SMS to invalid addresses.
-tasks.push(testInvalidAddressForSMS.bind(this, "&%&"));
-tasks.push(testInvalidAddressForSMS.bind(this, ""));
-
-// Test sending MMS to invalid addresses.
-tasks.push(testInvalidAddressForMMS.bind(this, ["&%&"]));
-tasks.push(testInvalidAddressForMMS.bind(this, [""]));
-tasks.push(testInvalidAddressForMMS.bind(this, ["123", "&%&", "456"]));
-
-tasks.push(deleteAllMessages);
-
-// WARNING: All tasks should be pushed before this!!!
-tasks.push(function cleanUp() {
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-});
-
-tasks.run();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mark_msg_read.js
+++ /dev/null
@@ -1,228 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.addPermission("sms", true, document);
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-
-var manager = window.navigator.mozMobileMessage;
-var smsList = new Array();
-
-function verifyInitialState() {
-  log("Verifying initial state.");
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-  simulateIncomingSms();
-}
-
-function simulateIncomingSms() {
-  let text = "Incoming SMS courtesy of Firefox OS";
-  let remoteNumber = "5557779999";
-
-  log("Simulating incoming SMS.");
-
-  // Simulate incoming SMS sent from remoteNumber to our emulator
-  rcvdEmulatorCallback = false;
-  runEmulatorCmd("sms send " + remoteNumber + " " + text, function(result) {
-    is(result[0], "OK", "emulator callback");
-    rcvdEmulatorCallback = true;
-  });
-}
-
-// Callback for incoming SMS
-manager.onreceived = function onreceived(event) {
-  log("Received 'onreceived' sms event.");
-  let incomingSms = event.message;
-  log("Received SMS (id: " + incomingSms.id + ").");
-  is(incomingSms.read, false, "incoming message read");
-  log("SMS read attribute: " + incomingSms.read + ".");
-
-  // Add newly received message id to array of msgs
-  smsList.push(incomingSms.id);
-
-  // Wait for emulator to catch up before continuing
-  waitFor(sendSms, function() {
-    return(rcvdEmulatorCallback);
-  });
-};
-
-function sendSms() {
-  let gotSmsSent = false;
-  let gotRequestSuccess = false;
-  let remoteNumber = "5557779999";
-  let text = "Mo Mo Mo Zilla Zilla Zilla!";
-
-  log("Sending an SMS.");
-
-  manager.onsent = function(event) {
-    log("Received 'onsent' event.");
-    gotSmsSent = true;
-    let sentSms = event.message;
-    log("Sent SMS (id: " + sentSms.id + ").");
-    is(sentSms.read, true, "sent sms read");
-    log("SMS read attribute: " + sentSms.read + ".");
-
-    // Add newly received message id to array of msgs
-    smsList.push(sentSms.id);
-
-    if (gotSmsSent && gotRequestSuccess) {
-      test1();
-    }
-  };
-
-  let request = manager.send(remoteNumber, text);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if(event.target.result) {
-      gotRequestSuccess = true;
-      if (gotSmsSent && gotRequestSuccess) {
-        test1();
-      }
-    } else {
-      log("smsrequest returned false for manager.send");
-      ok(false, "SMS send failed");
-      deleteMsgs();
-    }
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.send request returned unexpected error: "
-        + event.target.error.name );
-    deleteMsgs();
-  };
-}
-
-function markMessageAndVerify(smsId, readBool, nextFunction) {
-  let request = manager.markMessageRead(smsId, readBool);
-  ok(request instanceof DOMRequest,
-      "request is instanceof " + request.constructor);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-
-    // Success from MarkMessageRead, the result should match what we set
-    is(event.target.result, readBool, "result matches what was set");
-
-    // Message marked read/unread, now verify
-    log("Getting SMS message (id: " + smsId + ").");
-    let requestRet = manager.getMessage(smsId);
-    ok(requestRet, "smsrequest obj returned");
-
-    requestRet.onsuccess = function(event) {
-      log("Received 'onsuccess' smsrequest event.");
-      ok(event.target.result, "smsrequest event.target.result");
-      let foundSms = event.target.result;
-      is(foundSms.id, smsId, "SMS id matches");
-      log("SMS read attribute: " + foundSms.read + ".");
-      let text = readBool ? "read" : "unread";
-      if (foundSms.read == readBool) {
-        ok(true, "marked sms " + text);
-      } else {
-        ok(false, "marking sms " + text + " didn't work");
-        log("Expected SMS (id: " + foundSms.id + ") to be marked " + text
-            + " but it is not.");
-      }
-      nextFunction();
-    };
-
-    requestRet.onerror = function(event) {
-      log("Received 'onerror' smsrequest event.");
-      ok(event.target.error, "domerror obj");
-      is(event.target.error.name, "NotFoundError", "error returned");
-      log("Could not get SMS (id: " + outSmsId + ") but should have.");
-      ok(false, "Could not get SMS");
-      deleteMsgs();
-    };
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.markMessageRead request returned unexpected error: "
-        + event.target.error.name );
-    nextFunction();
-  };
-}
-
-function test1() {
-  rcvdSms = smsList[0];
-  log("Test 1: Marking received SMS (id: " + rcvdSms + ") read.");
-  markMessageAndVerify(rcvdSms, true, test2);
-}
-
-function test2() {
-  rcvdSms = smsList[0];
-  log("Test 2: Marking received SMS (id: " + rcvdSms + ") unread.");
-  markMessageAndVerify(rcvdSms, false, test3);
-}
-
-function test3() {
-  sentSms = smsList[1];
-  log("Test 3: Marking sent SMS (id: " + sentSms + ") unread.");
-  markMessageAndVerify(sentSms, false, test4);
-}
-
-function test4() {
-  sentSms = smsList[1];
-  log("Test 4: Marking sent SMS (id: " + sentSms + ") read.");
-  markMessageAndVerify(sentSms, true, test5);
-}
-
-function test5() {
-  sentSms = smsList[1];
-  log("Test 5: Marking an already read SMS (id: " + sentSms + ") read.");
-  markMessageAndVerify(sentSms, true, test6);
-}
-
-function test6() {
-  rcvdSms = smsList[0];
-  log("Test 6: Marking an already unread SMS (id: " + rcvdSms + ") unread.");
-  markMessageAndVerify(rcvdSms, false, deleteMsgs);
-}
-
-function deleteMsgs() {
-  let smsId = smsList.shift();
-
-  log("Deleting SMS (id: " + smsId + ").");
-  let request = manager.delete(smsId);
-  ok(request instanceof DOMRequest,
-      "request is instanceof " + request.constructor);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if (event.target.result) {
-      // Message deleted, continue until none are left
-      if (smsList.length) {
-        deleteMsgs();
-      } else {
-        cleanUp();
-      }
-    } else {
-      log("SMS delete failed.");
-      ok(false, "manager.delete request returned false");
-      cleanUp();
-    }
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.delete request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function cleanUp() {
-  manager.onreceived = null;
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-}
-
-// Start the test
-verifyInitialState();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mark_msg_read_error.js
+++ /dev/null
@@ -1,116 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.addPermission("sms", true, document);
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-
-var manager = window.navigator.mozMobileMessage;
-var smsId;
-
-function verifyInitialState() {
-  log("Verifying initial state.");
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-  simulateIncomingSms();
-}
-
-function simulateIncomingSms() {
-  let text = "Incoming SMS courtesy of Firefox OS";
-  let remoteNumber = "5557779999";
-
-  log("Simulating incoming SMS.");
-
-  // Simulate incoming SMS sent from remoteNumber to our emulator
-  rcvdEmulatorCallback = false;
-  runEmulatorCmd("sms send " + remoteNumber + " " + text, function(result) {
-    is(result[0], "OK", "emulator callback");
-    rcvdEmulatorCallback = true;
-  });
-}
-
-// Callback for incoming SMS
-manager.onreceived = function onreceived(event) {
-  log("Received 'onreceived' sms event.");
-  let incomingSms = event.message;
-  log("Received SMS (id: " + incomingSms.id + ").");
-  is(incomingSms.read, false, "incoming message read");
-  smsId = incomingSms.id;
-
-  // Wait for emulator to catch up before continuing
-  waitFor(test1, function() {
-    return(rcvdEmulatorCallback);
-  });
-};
-
-function markMsgError(invalidId, readBool, nextFunction) {
-  let requestRet = manager.markMessageRead(invalidId, readBool);
-  ok(requestRet, "smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event, but expected error.");
-    ok(false, "Smsrequest should have returned error but did not");
-    nextFunction();
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    is(event.target.error.name, "NotFoundError", "error returned");
-    nextFunction();
-  };
-}
-
-function test1() {
-  // Mark message read for a message that doesn't exist, expect error
-  let msgIdNoExist = smsId + 1;
-  log("Attempting to mark non-existent sms (id: " + msgIdNoExist
-      + ") read, expect error.");
-  markMsgError(msgIdNoExist, true, test2);
-}
-
-function test2() {
-  // Mark message read using invalid SMS id, expect error
-  invalidId = -1;
-  log("Attempting to mark sms unread using an invalid id (id: " + invalidId
-      + "), expect error.");
-  markMsgError(invalidId, false, deleteMsg);
-}
-
-function deleteMsg() {
-  log("Deleting SMS (id: " + smsId + ").");
-  let request = manager.delete(smsId);
-  ok(request instanceof DOMRequest,
-      "request is instanceof " + request.constructor);
-
-  request.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if (event.target.result) {
-      // Message deleted
-      cleanUp();
-    } else {
-      log("SMS delete failed.");
-      ok(false,"manager.delete request returned false");
-      cleanUp();
-    }
-  };
-
-  request.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.delete request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function cleanUp() {
-  manager.onreceived = null;
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-}
-
-// Start the test
-verifyInitialState();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_massive_incoming_delete.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 90000;
-MARIONETTE_HEAD_JS = "head.js";
-
-const SENDER = "5555552368"; // the remote number
-const RECEIVER = "15555215554"; // the emulator's number
-const MSG_TEXT = "Mozilla Firefox OS!";
-const SMS_NUMBER = 100;
-
-var SmsList = [];
-
-function sendAllSms() {
-  log("Send " + SMS_NUMBER + " SMS");
-
-  let promises = [];
-
-  // Wait for all "received" event are received.
-  promises.push(waitForManagerEvent("received", function(aEvent) {
-    let message = aEvent.message;
-    log("Received 'onreceived' event.");
-    ok(message, "incoming sms");
-    ok(message.id, "sms id");
-    log("Received SMS (id: " + message.id + ").");
-    ok(message.threadId, "thread id");
-    is(message.body, MSG_TEXT, "msg body");
-    is(message.delivery, "received", "delivery");
-    is(message.deliveryStatus, "success", "deliveryStatus");
-    is(message.read, false, "read");
-    is(message.receiver, RECEIVER, "receiver");
-    is(message.sender, SENDER, "sender");
-    is(message.messageClass, "normal", "messageClass");
-    is(message.deliveryTimestamp, 0, "deliveryTimestamp is 0");
-    SmsList.push(message);
-    return SmsList.length === SMS_NUMBER;
-  }));
-
-  // Generate massive incoming message.
-  for (let i = 0; i < SMS_NUMBER; i++) {
-    promises.push(sendTextSmsToEmulator(SENDER, MSG_TEXT));
-  }
-
-  return Promise.all(promises);
-}
-
-function deleteAllSms() {
-  log("Deleting SMS: " + JSON.stringify(SmsList));
-
-  let deleteStart = Date.now();
-  return deleteMessages(SmsList)
-    .then(() => {
-      let deleteDone = Date.now();
-      log("Delete " + SmsList.length + " SMS takes " +
-          (deleteDone - deleteStart) + " ms.");
-    })
-    // Verify SMS Deleted
-    .then(() => {
-      let promises = [];
-
-      for (let i = 0; i < SmsList.length; i++) {
-        let smsId = SmsList[i].id;
-        promises.push(getMessage(smsId)
-          .then((aMessageInDB) => {
-            log("Got SMS (id: " + aMessageInDB.id + ") but should not have.");
-            ok(false, "SMS (id: " + aMessageInDB.id + ") was not deleted");
-          }, (aError) => {
-            log("Could not get SMS (id: " + smsId + ") as expected.");
-            is(aError.name, "NotFoundError", "error returned");
-          }));
-      }
-
-      return Promise.all(promises);
-    });
-}
-
-// Start the test
-startTestCommon(function testCaseMain() {
-  return sendAllSms()
-    .then(() => deleteAllSms());
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_message_classes.js
+++ /dev/null
@@ -1,260 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-const PDU_SMSC = "00"; // No SMSC Address
-const PDU_FIRST_OCTET = "00"; // RP:no, UDHI:no, SRI:no, MMS:no, MTI:SMS-DELIVER
-const PDU_SENDER = "0191F1"; // +1
-const PDU_PID_NORMAL = "00";
-const PDU_PID_ANSI_136_R_DATA = "7C";
-const PDU_PID_USIM_DATA_DOWNLOAD = "7F";
-const PDU_TIMESTAMP = "00101000000000"; // 2000/01/01
-const PDU_UDL = "01";
-const PDU_UD = "41";
-
-const SENT_TIMESTAMP = Date.UTC(2000, 0, 1); // Must be equal to PDU_TIMESTAMP.
-
-SpecialPowers.addPermission("sms", true, document);
-
-var manager = window.navigator.mozMobileMessage;
-ok(manager instanceof MozMobileMessageManager,
-   "manager is instance of " + manager.constructor);
-
-var pendingEmulatorCmdCount = 0;
-function sendSmsPduToEmulator(pdu) {
-  ++pendingEmulatorCmdCount;
-
-  let cmd = "sms pdu " + pdu;
-  runEmulatorCmd(cmd, function(result) {
-    --pendingEmulatorCmdCount;
-
-    is(result[0], "OK", "Emulator response");
-  });
-}
-
-function checkMessage(message, id, threadId, messageClass) {
-  ok(message instanceof SmsMessage,
-     "message is instanceof " + message.constructor);
-  if (id == null) {
-    ok(message.id > 0, "message.id");
-  } else {
-    is(message.id, id, "message.id");
-  }
-  if (threadId == null) {
-    ok(message.threadId > 0, "message.threadId");
-  } else {
-    is(message.threadId, threadId, "message.threadId");
-  }
-  is(message.delivery, "received", "message.delivery");
-  is(message.deliveryStatus, "success", "message.deliveryStatus");
-  is(message.sender, "+1", "message.sender");
-  is(message.body, "A", "message.body");
-  is(message.messageClass, messageClass, "message.messageClass");
-  is(message.deliveryTimestamp, 0, "deliveryTimestamp is 0");
-  is(message.read, false, "message.read");
-}
-
-function test_message_class_0() {
-  let allDCSs = [
-    "10", // General Group: 00xx
-    "50", // Automatica Deletion Group: 01xx
-    "F0"  // (no name) Group: 1111
-  ];
-
-  function do_test(dcsIndex) {
-    manager.addEventListener("received", function onReceived(event) {
-      manager.removeEventListener("received", onReceived);
-
-      let message = event.message;
-      checkMessage(message, -1, 0, "class-0");
-      ok(event.message.timestamp >= timeBeforeSend,
-         "Message's timestamp should be greater then the timetamp of sending");
-      ok(event.message.timestamp <= Date.now(),
-         "Message's timestamp should be lesser than the timestamp of now");
-      is(event.message.sentTimestamp, SENT_TIMESTAMP,
-         "Message's sentTimestamp should be equal to SENT_TIMESTAMP");
-
-      // Make sure the message is not stored.
-      let cursor = manager.getMessages();
-      cursor.onsuccess = function onsuccess() {
-        if (cursor.result) {
-          // Here we check whether there is any message of the same sender.
-          isnot(cursor.result.sender, message.sender, "cursor.result.sender");
-
-          cursor.continue();
-          return;
-        }
-
-        // All messages checked. Done.
-        ++dcsIndex;
-        if (dcsIndex >= allDCSs.length) {
-          window.setTimeout(test_message_class_1, 0);
-        } else {
-          window.setTimeout(do_test.bind(null, dcsIndex), 0);
-        }
-      };
-      cursor.onerror = function onerror() {
-        ok(false, "Can't fetch messages from SMS database");
-      };
-    });
-
-    let dcs = allDCSs[dcsIndex];
-    log("  Testing DCS " + dcs);
-    let pdu = PDU_SMSC + PDU_FIRST_OCTET + PDU_SENDER + PDU_PID_NORMAL +
-              dcs + PDU_TIMESTAMP + PDU_UDL + PDU_UD;
-    let timeBeforeSend = Date.now();
-    sendSmsPduToEmulator(pdu);
-  }
-
-  log("Checking Message Class 0");
-  do_test(0);
-}
-
-function doTestMessageClassGeneric(allDCSs, messageClass, next) {
-  function do_test(dcsIndex) {
-    manager.addEventListener("received", function onReceived(event) {
-      manager.removeEventListener("received", onReceived);
-
-      // Make sure we can correctly receive the message
-      checkMessage(event.message, null, null, messageClass);
-      ok(event.message.timestamp >= timeBeforeSend,
-         "Message's timestamp should be greater then the timetamp of sending");
-      ok(event.message.timestamp <= Date.now(),
-         "Message's timestamp should be lesser than the timestamp of now");
-      is(event.message.sentTimestamp, SENT_TIMESTAMP,
-         "Message's sentTimestamp should be equal to SENT_TIMESTAMP");
-
-      ++dcsIndex;
-      if (dcsIndex >= allDCSs.length) {
-        window.setTimeout(next, 0);
-      } else {
-        window.setTimeout(do_test.bind(null, dcsIndex), 0);
-      }
-    });
-
-    let dcs = allDCSs[dcsIndex];
-    log("  Testing DCS " + dcs);
-    let pdu = PDU_SMSC + PDU_FIRST_OCTET + PDU_SENDER + PDU_PID_NORMAL +
-              dcs + PDU_TIMESTAMP + PDU_UDL + PDU_UD;
-
-    let timeBeforeSend = Date.now();
-    sendSmsPduToEmulator(pdu);
-  }
-
-  do_test(0);
-}
-
-function test_message_class_1() {
-  let allDCSs = [
-    "11", // General Group: 00xx
-    "51", // Automatica Deletion Group: 01xx
-    "F1"  // (no name) Group: 1111
-  ];
-
-  log("Checking Message Class 1");
-  doTestMessageClassGeneric(allDCSs, "class-1", test_message_class_2);
-}
-
-function test_message_class_2() {
-  let allDCSs = [
-    "12", // General Group: 00xx
-    "52", // Automatica Deletion Group: 01xx
-    "F2"  // (no name) Group: 1111
-  ];
-
-  let allPIDs = [
-    PDU_PID_NORMAL,
-    PDU_PID_ANSI_136_R_DATA,
-    PDU_PID_USIM_DATA_DOWNLOAD
-  ];
-
-  function do_test_dcs(dcsIndex) {
-    function do_test_pid(pidIndex) {
-      function onReceived(event) {
-        if (pidIndex == 0) {
-          // Make sure we can correctly receive the message
-          checkMessage(event.message, null, null, "class-2");
-          ok(event.message.timestamp >= timeBeforeSend,
-             "Message's timestamp should be greater then the timetamp of sending");
-          ok(event.message.timestamp <= Date.now(),
-             "Message's timestamp should be lesser than the timestamp of now");
-          is(event.message.sentTimestamp, SENT_TIMESTAMP,
-             "Message's sentTimestamp should be equal to SENT_TIMESTAMP");
-
-          next();
-          return;
-        }
-
-        // TODO: Bug 792798 - B2G SMS: develop test cases for Message Class 2
-        // Since we have "data download via SMS Point-to-Point" service enabled
-        // but no working implementation in emulator SIM, all class 2 messages
-        // bug normal ones should goto `dataDownloadViaSMSPP()` and we should
-        // not receive the message in content page.
-        ok(false, "SMS-PP messages shouldn't be sent to content");
-      }
-
-      function next() {
-        manager.removeEventListener("received", onReceived);
-
-        ++pidIndex;
-        if (pidIndex >= allPIDs.length) {
-          ++dcsIndex;
-          if (dcsIndex >= allDCSs.length) {
-            window.setTimeout(test_message_class_3, 0);
-          } else {
-            window.setTimeout(do_test_dcs.bind(null, dcsIndex), 0);
-          }
-        } else {
-          window.setTimeout(do_test_pid.bind(null, pidIndex), 0);
-        }
-      }
-
-      manager.addEventListener("received", onReceived);
-
-      if (pidIndex != 0) {
-        // Wait for three seconds to ensure we don't receive the message.
-        window.setTimeout(next, 3000);
-      }
-
-      let pid = allPIDs[pidIndex];
-      log("    Testing PID " + pid);
-
-      let pdu = PDU_SMSC + PDU_FIRST_OCTET + PDU_SENDER + pid + dcs +
-                PDU_TIMESTAMP + PDU_UDL + PDU_UD;
-      let timeBeforeSend = Date.now();
-      sendSmsPduToEmulator(pdu);
-    }
-
-    let dcs = allDCSs[dcsIndex];
-    log("  Testing DCS " + dcs);
-
-    do_test_pid(0);
-  }
-
-  log("Checking Message Class 2");
-  do_test_dcs(0);
-}
-
-function test_message_class_3() {
-  let allDCSs = [
-    "13", // General Group: 00xx
-    "53", // Automatica Deletion Group: 01xx
-    "F3"  // (no name) Group: 1111
-  ];
-
-  log("Checking Message Class 3");
-  doTestMessageClassGeneric(allDCSs, "class-3", cleanUp);
-}
-
-function cleanUp() {
-  if (pendingEmulatorCmdCount) {
-    window.setTimeout(cleanUp, 100);
-    return;
-  }
-
-  SpecialPowers.removePermission("sms", document);
-  finish();
-}
-
-test_message_class_0();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mmdb_foreachmatchedmmsdeliveryinfo.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'mmdb_head.js';
-
-const DBNAME = "test_mmdb_foreachmatchedmmsdeliveryinfo:" + newUUID();
-
-const PHONE_0 = "+15555215500";
-const PHONE_1 = "+15555215501";
-const PHONE_2 = "+15555215502";
-const PHONE_2_NET = "5555215502";
-const PHONE_3 = "+15555215503";
-const PHONE_3_NET = "5555215503";
-const EMAIL_1 = "foo@bar.com";
-var deliveryInfo = [
-  { receiver: PHONE_1 },
-  { receiver: PHONE_2 },
-  { receiver: PHONE_1 },
-  { receiver: PHONE_2_NET },
-  { receiver: PHONE_3_NET },
-  { receiver: EMAIL_1 },
-  { receiver: PHONE_3 },
-];
-
-function clearTraversed(aDeliveryInfo) {
-  for (let element of aDeliveryInfo) {
-    delete element.traversed;
-  }
-}
-
-function doTest(aMmdb, aNeedle, aVerifyFunc, aCount) {
-  log("  '" + aNeedle + "': " + aCount);
-
-  clearTraversed(deliveryInfo);
-
-  let count = 0;
-  aMmdb.forEachMatchedMmsDeliveryInfo(deliveryInfo, aNeedle, function(aElement) {
-    ok(true, "checking " + aElement.receiver);
-    ok(!aElement.hasOwnProperty("traversed"), "element.traversed");
-    aVerifyFunc(aElement);
-
-    aElement.traversed = true;
-    ++count;
-  });
-  is(count, aCount, "matched count");
-}
-
-function testNotFound(aMmdb) {
-  log("Testing unavailable");
-
-  doTest(aMmdb, PHONE_0, function(aElement) {
-    ok(false, "Should never have a match");
-  }, 0);
-}
-
-function testDirectMatch(aMmdb) {
-  log("Testing direct matching");
-
-  for (let needle of [PHONE_1, EMAIL_1]) {
-    let count = deliveryInfo.reduce(function(aCount, aElement) {
-      return aElement.receiver == needle ? aCount + 1 : aCount;
-    }, 0);
-    doTest(aMmdb, needle, function(aElement) {
-      is(aElement.receiver, needle, "element.receiver");
-    }, count);
-  }
-}
-
-function testPhoneMatch(aMmdb) {
-  log("Testing phone matching");
-
-  let verifyFunc = function(aValid, aElement) {
-    ok(aValid.indexOf(aElement.receiver) >= 0, "element.receiver");
-  };
-
-  let matchingGroups = [
-    [PHONE_2, PHONE_2_NET],
-    [PHONE_3, PHONE_3_NET],
-  ];
-  for (let group of matchingGroups) {
-    for (let item of group) {
-      doTest(aMmdb, item, verifyFunc.bind(null, group), group.length);
-    }
-  }
-}
-
-startTestBase(function testCaseMain() {
-  let mmdb = newMobileMessageDB();
-  return initMobileMessageDB(mmdb, DBNAME, 0)
-    .then(() => testNotFound(mmdb))
-    .then(() => testDirectMatch(mmdb))
-    .then(() => testPhoneMatch(mmdb))
-    .then(() => closeMobileMessageDB(mmdb));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mmdb_full_storage.js
+++ /dev/null
@@ -1,195 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'mmdb_head.js';
-
-const DBNAME = "test_mmdb_full_storage:" + newUUID();
-
-function newSavableMessage(aSender, aReceiver) {
-  return {
-    type: "sms",
-    sender: aSender ? aSender : "+0987654321",
-    receiver: aReceiver? aReceiver : "+1234567890",
-    body: "quick fox jump over the lazy dog",
-    deliveryStatusRequested: false,
-    messageClass: "normal",
-    timestamp: Date.now(),
-    iccId: "1029384756"
-  };
-}
-
-function setStorageFull(aFull) {
-  SpecialPowers.notifyObserversInParentProcess(null,
-                                               "disk-space-watcher",
-                                               aFull ? "full" : "free");
-}
-
-function isFileNoDeviceSpaceError(aErrorResult) {
-  is(aErrorResult, Cr.NS_ERROR_FILE_NO_DEVICE_SPACE, "Database error code");
-}
-
-function isCallbackStorageFullError(aErrorCode) {
-  is(aErrorCode, Ci.nsIMobileMessageCallback.STORAGE_FULL_ERROR,
-     "nsIMobileMessageCallback error code");
-}
-
-function testSaveSendingMessage(aMmdb) {
-  log("testSaveSendingMessage()");
-
-  setStorageFull(true);
-  return saveSendingMessage(aMmdb, newSavableMessage())
-    // Resolved/rejected results are both [<Cr.NS_ERROR_FOO>, <DOM message>],
-    // and we need only the error code in both cases.
-    .then((aValue) => aValue[0],
-          (aValue) => aValue[0])
-    .then(isFileNoDeviceSpaceError)
-    .then(() => setStorageFull(false));
-}
-
-function testSaveReceivedMessage(aMmdb) {
-  log("testSaveReceivedMessage()");
-
-  setStorageFull(true);
-  return saveReceivedMessage(aMmdb, newSavableMessage())
-    // Resolved/rejected results are both [<Cr.NS_ERROR_FOO>, <DOM message>],
-    // and we need only the error code in both cases.
-    .then((aValue) => aValue[0],
-          (aValue) => aValue[0])
-    .then(isFileNoDeviceSpaceError)
-    .then(() => setStorageFull(false));
-}
-
-function testGetMessageRecordById(aMmdb) {
-  log("testGetMessageRecordById()");
-
-  setStorageFull(false);
-  return saveReceivedMessage(aMmdb, newSavableMessage())
-    // Resolved result is [<Cr.NS_ERROR_FOO>, <DOM message>],
-    .then(function(aValue) {
-      let domMessage = aValue[1];
-
-      setStorageFull(true);
-      return getMessageRecordById(aMmdb, domMessage.id)
-        .then(() => setStorageFull(false));
-    });
-}
-
-function testMarkMessageRead(aMmdb) {
-  log("testMarkMessageRead()");
-
-  setStorageFull(false);
-  return saveReceivedMessage(aMmdb, newSavableMessage())
-    // Resolved/rejected results are both [<Cr.NS_ERROR_FOO>, <DOM message>].
-    .then(function(aValue) {
-      let domMessage = aValue[1];
-
-      setStorageFull(true);
-      return markMessageRead(aMmdb, domMessage.id, true)
-        .then(null, (aValue) => aValue)
-        .then(isCallbackStorageFullError)
-        .then(() => setStorageFull(false));
-    });
-}
-
-function testDeleteMessage(aMmdb) {
-  log("testDeleteMessage()");
-
-  // Note:
-  // Due to thread-based design in MobileMessageDB and transaction-based design
-  // in indexedDB, There are 2 restrictions to delete a message when storage full
-  // in the following condition:
-  // If the deletion won't remove all the messages in a thead and
-  // 1. the last message of the thread or
-  // 2. an unread message
-  // are to be deleted.
-  //
-  // This will trigger an update of the thread's subject, message body,
-  // unread count, etc but update operation is restricted when storage is full.
-
-  let testAddress = "1111111111";
-  let savedMsgIds = [];
-  let promises = [];
-  let numOfTestMessages = 5;
-
-  setStorageFull(false);
-  // Save several unread messages to the same thread then delete them.
-  for (let i = 0; i < numOfTestMessages; i++) {
-    promises.push(saveReceivedMessage(aMmdb, newSavableMessage(testAddress))
-      .then((aValue) => { savedMsgIds.push(aValue[1].id); }));
-  }
-
-  return Promise.all(promises)
-    .then(() => setStorageFull(true))
-
-    // Failure is expected when deleting the last one.
-    .then(() => deleteMessage(aMmdb, [savedMsgIds[numOfTestMessages - 1]], 1))
-    .then(null, (aValue) => aValue)
-    .then(isCallbackStorageFullError)
-
-    // Failure is expected when deleting an unread message.
-    .then(() => deleteMessage(aMmdb, [savedMsgIds[0]], 1))
-    .then(null, (aValue) => aValue)
-    .then(isCallbackStorageFullError)
-
-    // Delete all messages in the thread.
-    .then(() => deleteMessage(aMmdb, savedMsgIds, savedMsgIds.length))
-
-    .then(() => setStorageFull(false));
-}
-
-function testSaveSmsSegment(aMmdb) {
-  log("testSaveSmsSegment()");
-
-  let smsSegment = {
-    sender: "+0987654321",
-    encoding: 0x00, // GSM 7bit alphabet
-    iccId: "1029384756",
-    segmentRef: 0,
-    segmentSeq: 1,
-    segmentMaxSeq: 3,
-    body: "quick fox jump over the lazy dog"
-  }
-
-  setStorageFull(true);
-  return saveSmsSegment(aMmdb, smsSegment)
-    // Resolved/rejected results are both [<Cr.NS_ERROR_FOO>, <completeMessage>],
-    // and we need only the error code in both cases.
-    .then((aValue) => aValue[0],
-          (aValue) => aValue[0])
-    .then(isFileNoDeviceSpaceError)
-    .then(() => setStorageFull(false));
-}
-
-function testCreateMessageCursor(aMmdb) {
-  log("testCreateMessageCursor()");
-
-  setStorageFull(true);
-  return createMessageCursor(aMmdb)
-    .then(() => setStorageFull(false));
-}
-
-function testCreateThreadCursor(aMmdb) {
-  log("testCreateThreadCursor()");
-
-  setStorageFull(true);
-  return createThreadCursor(aMmdb)
-    .then(() => setStorageFull(false));
-}
-
-startTestBase(function testCaseMain() {
-
-  let mmdb = newMobileMessageDB();
-  return initMobileMessageDB(mmdb, DBNAME, 0)
-
-    .then(() => testSaveSendingMessage(mmdb))
-    .then(() => testSaveReceivedMessage(mmdb))
-    .then(() => testGetMessageRecordById(mmdb))
-    .then(() => testMarkMessageRead(mmdb))
-    .then(() => testDeleteMessage(mmdb))
-    .then(() => testSaveSmsSegment(mmdb))
-    .then(() => testCreateMessageCursor(mmdb))
-    .then(() => testCreateThreadCursor(mmdb))
-
-    .then(() => closeMobileMessageDB(mmdb));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mmdb_new.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'mmdb_head.js';
-
-const DBNAME = "test_mmdb_new:" + newUUID();
-var dbVersion = 0;
-
-function check(aMmdb) {
-  is(aMmdb.dbName, DBNAME, "dbName");
-  if (!dbVersion) {
-    ok(aMmdb.dbVersion, "dbVersion");
-    dbVersion = aMmdb.dbVersion;
-  } else {
-    is(aMmdb.dbVersion, dbVersion, "dbVersion");
-  }
-}
-
-startTestBase(function testCaseMain() {
-  log("Test init MobileMessageDB");
-
-  let mmdb = newMobileMessageDB();
-  return initMobileMessageDB(mmdb, DBNAME, dbVersion)
-    .then(() => check(mmdb))
-    .then(() => closeMobileMessageDB(mmdb))
-    .then(() => check(mmdb))
-
-    .then(function() {
-      log("Test re-init and close.");
-      return initMobileMessageDB(mmdb, DBNAME, dbVersion);
-    })
-    .then(() => check(mmdb))
-    .then(() => closeMobileMessageDB(mmdb))
-    .then(() => check(mmdb));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mmdb_ports_in_cdma_wappush.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'mmdb_head.js';
-
-const DBNAME = "test_mmdb_ports_in_cdma_wappush:" + newUUID();
-
-const TEST_PDU = [
-  {
-    sender: "+0987654321",
-    iccId: "1029384756",
-    segmentRef: 0,
-    segmentSeq: 1, // 1st segment
-    segmentMaxSeq: 2,
-    encoding: 0x04, // 8-bit encoding
-    data: [0, 1, 2],
-    teleservice: 0x1004, // PDU_CDMA_MSG_TELESERIVCIE_ID_WAP
-    // Port numbers are only provided in 1st segment from CDMA SMS PDUs.
-    originatorPort: 9200, // WDP_PORT_PUSH (server-side)
-    destinationPort: 2948 // WDP_PORT_PUSH (client-side)
-  },
-  {
-    sender: "+0987654321",
-    iccId: "1029384756",
-    segmentRef: 0,
-    segmentSeq: 2, // 2nd segment
-    segmentMaxSeq: 2,
-    encoding: 0x04, // 8-bit encoding
-    data: [3, 4, 5],
-    teleservice: 0x1004, // PDU_CDMA_MSG_TELESERIVCIE_ID_WAP
-    // Port numbers are only provided in 1st segment from CDMA SMS PDUs.
-    originatorPort: Ci.nsIGonkSmsService.SMS_APPLICATION_PORT_INVALID,
-    destinationPort: Ci.nsIGonkSmsService.SMS_APPLICATION_PORT_INVALID
-  }
-];
-
-function testSaveCdmaWapPush(aMmdb, aReverse) {
-  log("testSaveCdmaWapPush(), aReverse: " + aReverse);
-
-  let testPDUs = aReverse ? Array.from(TEST_PDU).reverse() : TEST_PDU;
-  let lengthOfFullData = 0;
-  let promises = [];
-
-  for (let pdu of testPDUs) {
-    lengthOfFullData += pdu.data.length;
-    promises.push(saveSmsSegment(aMmdb, pdu));
-  };
-
-  return Promise.all(promises)
-    .then((aResults) => {
-      // Complete message shall be returned after 2 segments are saved.
-      let completeMsg = aResults[1][1];
-
-      is(completeMsg.originatorPort, TEST_PDU[0].originatorPort, "originatorPort");
-      is(completeMsg.destinationPort, TEST_PDU[0].destinationPort, "destinationPort");
-
-      is(completeMsg.fullData.length, lengthOfFullData, "fullData.length");
-      for (let i = 0; i < lengthOfFullData; i++) {
-        is(completeMsg.fullData[i], i, "completeMsg.fullData[" + i + "]");
-      }
-    });
-}
-
-startTestBase(function testCaseMain() {
-
-  let mmdb = newMobileMessageDB();
-  return initMobileMessageDB(mmdb, DBNAME, 0)
-
-    .then(() => testSaveCdmaWapPush(mmdb, false))
-    .then(() => testSaveCdmaWapPush(mmdb, true))
-
-    .then(() => closeMobileMessageDB(mmdb));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mmdb_setmessagedeliverybyid_sms.js
+++ /dev/null
@@ -1,134 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'mmdb_head.js';
-
-const DBNAME = "test_mmdb_setmessagedeliverybyid_sms:" + newUUID();
-
-const RECEIVER = "+1234567890";
-const TEXT = "The quick brown fox jumps over the lazy dog.";
-
-const MESSAGE_STORE_NAME = "sms";
-
-const DELIVERY_SENDING = "sending";
-const DELIVERY_SENT = "sent";
-const DELIVERY_RECEIVED = "received";
-const DELIVERY_NOT_DOWNLOADED = "not-downloaded";
-const DELIVERY_ERROR = "error";
-
-const DELIVERY_STATUS_NOT_APPLICABLE = "not-applicable";
-const DELIVERY_STATUS_SUCCESS = "success";
-const DELIVERY_STATUS_PENDING = "pending";
-const DELIVERY_STATUS_ERROR = "error";
-
-function verify(aMmdb, aMessageId, aDelivery, aDeliveryStatus, aRv, aDomMessage) {
-  log("  Verify(" + aMessageId + ", " + aDelivery + ", " + aDeliveryStatus + ")");
-
-  ok(Components.isSuccessCode(aRv), "Components.isSuccessCode(" + aRv + ")");
-  ok(aDomMessage, "DOM message validity");
-  is(aDomMessage.delivery, aDelivery, "message.delivery");
-  is(aDomMessage.deliveryStatus, aDeliveryStatus, "message.deliveryStatus");
-
-  let deferred = Promise.defer();
-
-  // Verify deliveryIndex, sentTimestamp and deliveryTimestamp
-  aMmdb.newTxn("readonly", function(aError, aTransaction, aMessageStore) {
-    let messageRecord;
-    aTransaction.oncomplete = function() {
-      ok(true, "transaction complete");
-
-      is(messageRecord.deliveryIndex[0], aDelivery,
-         "messageRecord.deliveryIndex[0]");
-      is(messageRecord.deliveryIndex[1], messageRecord.timestamp,
-         "messageRecord.deliveryIndex[1]");
-      if (aDelivery == DELIVERY_SENT) {
-        ok(messageRecord.sentTimestamp >= messageRecord.timestamp,
-           "messageRecord.sentTimestamp");
-      }
-      if (aDeliveryStatus == DELIVERY_STATUS_SUCCESS) {
-        ok(messageRecord.deliveryTimestamp >= messageRecord.timestamp,
-           "messageRecord.deliveryTimestamp");
-      }
-
-      deferred.resolve(aMmdb);
-    };
-
-    aMessageStore.get(aMessageId).onsuccess = function(event) {
-      messageRecord = event.target.result;
-      ok(true, "Got messageRecord " + messageRecord.id);
-    };
-  }, [MESSAGE_STORE_NAME]);
-
-  return deferred.promise;
-}
-
-function test(aTitle, aMmdb, aDeliveryStatusRequested, aParamArray) {
-  log(aTitle);
-
-  let message = {
-    type: "sms",
-    sender: null,
-    timestamp: Date.now(),
-    deliveryStatusRequested: aDeliveryStatusRequested,
-    receiver: RECEIVER,
-    iccId: null,
-    body: TEXT,
-  };
-  return saveSendingMessage(aMmdb, message)
-    .then(function(aValues) {
-      let [resultCode, domMessage] = aValues;
-      let promise =
-        verify(aMmdb, domMessage.id, DELIVERY_SENDING,
-               (aDeliveryStatusRequested ? DELIVERY_STATUS_PENDING
-                                         : DELIVERY_STATUS_NOT_APPLICABLE),
-               resultCode, domMessage);
-      while (aParamArray.length) {
-        let params = aParamArray.shift();
-        let v = verify.bind(null, aMmdb, domMessage.id, params[2], params[3]);
-        promise = promise
-          .then(() => {
-            log("  Set to " + params[0] + ":" + params[1]);
-            return setMessageDeliveryByMessageId(aMmdb, domMessage.id, null,
-                                                 params[0], params[1], null);
-          })
-          .then((aValues) => v(aValues[0], aValues[1]));
-      }
-
-      return promise;
-    });
-}
-
-startTestBase(function testCaseMain() {
-  return initMobileMessageDB(newMobileMessageDB(), DBNAME, 0)
-    .then((aMmdb) => test("Simulate send failed without delivery report requisition",
-                          aMmdb, false, [
-      [DELIVERY_ERROR, DELIVERY_STATUS_ERROR,
-       DELIVERY_ERROR, DELIVERY_STATUS_ERROR],
-    ]))
-    .then((aMmdb) => test("Simulate send failed with delivery report requisition",
-                          aMmdb, true, [
-      [DELIVERY_ERROR, DELIVERY_STATUS_ERROR,
-       DELIVERY_ERROR, DELIVERY_STATUS_ERROR],
-    ]))
-    .then((aMmdb) => test("Simulate sent without delivery report requisition",
-                          aMmdb, false, [
-      [DELIVERY_SENT, null,
-       DELIVERY_SENT, DELIVERY_STATUS_NOT_APPLICABLE],
-    ]))
-    .then((aMmdb) => test("Simulate sent with delivery report success",
-                          aMmdb, true, [
-      [DELIVERY_SENT, null,
-       DELIVERY_SENT, DELIVERY_STATUS_PENDING],
-      [null, DELIVERY_STATUS_SUCCESS,
-       DELIVERY_SENT, DELIVERY_STATUS_SUCCESS],
-    ]))
-    .then((aMmdb) => test("Simulate sent with delivery report error",
-                          aMmdb, true, [
-      [DELIVERY_SENT, null,
-       DELIVERY_SENT, DELIVERY_STATUS_PENDING],
-      [null, DELIVERY_ERROR,
-       DELIVERY_SENT, DELIVERY_ERROR],
-    ]))
-    .then(closeMobileMessageDB);
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mmdb_upgradeSchema_22.js
+++ /dev/null
@@ -1,738 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'mmdb_head.js';
-
-Cu.import("resource://gre/modules/PhoneNumberUtils.jsm");
-
-var RIL = {};
-Cu.import("resource://gre/modules/ril_consts.js", RIL);
-
-var MMS = {};
-Cu.import("resource://gre/modules/MmsPduHelper.jsm", MMS);
-
-const DBNAME = "test_mmdb_upgradeSchema_22:" + newUUID();
-
-const MESSAGE_STORE_NAME = "sms";
-const THREAD_STORE_NAME = "thread";
-const PARTICIPANT_STORE_NAME = "participant";
-
-const DEBUG = false;
-
-const READ_WRITE = "readwrite";
-
-const DELIVERY_SENDING = "sending";
-const DELIVERY_SENT = "sent";
-const DELIVERY_RECEIVED = "received";
-const DELIVERY_NOT_DOWNLOADED = "not-downloaded";
-const DELIVERY_ERROR = "error";
-
-const DELIVERY_STATUS_NOT_APPLICABLE = "not-applicable";
-const DELIVERY_STATUS_SUCCESS = "success";
-const DELIVERY_STATUS_PENDING = "pending";
-const DELIVERY_STATUS_ERROR = "error";
-
-const MESSAGE_CLASS_NORMAL = "normal";
-
-const FILTER_READ_UNREAD = 0;
-const FILTER_READ_READ = 1;
-
-const DISABLE_MMS_GROUPING_FOR_RECEIVING = true;
-
-var LEGACY = {
-  saveRecord: function(aMessageRecord, aAddresses, aCallback) {
-    if (DEBUG) debug("Going to store " + JSON.stringify(aMessageRecord));
-
-    let self = this;
-    this.newTxn(READ_WRITE, function(error, txn, stores) {
-      let notifyResult = function(aRv, aMessageRecord) {
-        if (!aCallback) {
-          return;
-        }
-        let domMessage =
-          aMessageRecord && self.createDomMessageFromRecord(aMessageRecord);
-        aCallback.notify(aRv, domMessage);
-      };
-
-      if (error) {
-        notifyResult(error, null);
-        return;
-      }
-
-      txn.oncomplete = function oncomplete(event) {
-        if (aMessageRecord.id > self.lastMessageId) {
-          self.lastMessageId = aMessageRecord.id;
-        }
-        notifyResult(Cr.NS_OK, aMessageRecord);
-      };
-      txn.onabort = function onabort(event) {
-        // TODO bug 832140 check event.target.errorCode
-        notifyResult(Cr.NS_ERROR_FAILURE, null);
-      };
-
-      let messageStore = stores[0];
-      let participantStore = stores[1];
-      let threadStore = stores[2];
-      LEGACY.replaceShortMessageOnSave.call(self, txn, messageStore,
-                                            participantStore, threadStore,
-                                            aMessageRecord, aAddresses);
-    }, [MESSAGE_STORE_NAME, PARTICIPANT_STORE_NAME, THREAD_STORE_NAME]);
-  },
-
-  replaceShortMessageOnSave: function(aTransaction, aMessageStore,
-                                      aParticipantStore, aThreadStore,
-                                      aMessageRecord, aAddresses) {
-    let isReplaceTypePid = (aMessageRecord.pid) &&
-                           ((aMessageRecord.pid >= RIL.PDU_PID_REPLACE_SHORT_MESSAGE_TYPE_1 &&
-                             aMessageRecord.pid <= RIL.PDU_PID_REPLACE_SHORT_MESSAGE_TYPE_7) ||
-                            aMessageRecord.pid == RIL.PDU_PID_RETURN_CALL_MESSAGE);
-
-    if (aMessageRecord.type != "sms" ||
-        aMessageRecord.delivery != DELIVERY_RECEIVED ||
-        !isReplaceTypePid) {
-      LEGACY.realSaveRecord.call(this, aTransaction, aMessageStore,
-                                 aParticipantStore, aThreadStore,
-                                 aMessageRecord, aAddresses);
-      return;
-    }
-
-    // 3GPP TS 23.040 subclause 9.2.3.9 "TP-Protocol-Identifier (TP-PID)":
-    //
-    //   ... the MS shall check the originating address and replace any
-    //   existing stored message having the same Protocol Identifier code
-    //   and originating address with the new short message and other
-    //   parameter values. If there is no message to be replaced, the MS
-    //   shall store the message in the normal way. ... it is recommended
-    //   that the SC address should not be checked by the MS."
-    let self = this;
-    this.findParticipantRecordByPlmnAddress(aParticipantStore,
-                                            aMessageRecord.sender, false,
-                                            function(participantRecord) {
-      if (!participantRecord) {
-        LEGACY.realSaveRecord.call(self, aTransaction, aMessageStore,
-                                   aParticipantStore, aThreadStore,
-                                   aMessageRecord, aAddresses);
-        return;
-      }
-
-      let participantId = participantRecord.id;
-      let range = IDBKeyRange.bound([participantId, 0], [participantId, ""]);
-      let request = aMessageStore.index("participantIds").openCursor(range);
-      request.onsuccess = function onsuccess(event) {
-        let cursor = event.target.result;
-        if (!cursor) {
-          LEGACY.realSaveRecord.call(self, aTransaction, aMessageStore,
-                                     aParticipantStore, aThreadStore,
-                                     aMessageRecord, aAddresses);
-          return;
-        }
-
-        // A message record with same participantId found.
-        // Verify matching criteria.
-        let foundMessageRecord = cursor.value;
-        if (foundMessageRecord.type != "sms" ||
-            foundMessageRecord.sender != aMessageRecord.sender ||
-            foundMessageRecord.pid != aMessageRecord.pid) {
-          cursor.continue();
-          return;
-        }
-
-        // Match! Now replace that found message record with current one.
-        aMessageRecord.id = foundMessageRecord.id;
-        LEGACY.realSaveRecord.call(self, aTransaction, aMessageStore,
-                                   aParticipantStore, aThreadStore,
-                                   aMessageRecord, aAddresses);
-      };
-    });
-  },
-
-  realSaveRecord: function(aTransaction, aMessageStore, aParticipantStore,
-                           aThreadStore, aMessageRecord, aAddresses) {
-    let self = this;
-    this.findThreadRecordByPlmnAddresses(aThreadStore, aParticipantStore,
-                                         aAddresses, true,
-                                         function(threadRecord, participantIds) {
-      if (!participantIds) {
-        aTransaction.abort();
-        return;
-      }
-
-      let isOverriding = (aMessageRecord.id !== undefined);
-      if (!isOverriding) {
-        // |self.lastMessageId| is only updated in |txn.oncomplete|.
-        aMessageRecord.id = self.lastMessageId + 1;
-      }
-
-      let timestamp = aMessageRecord.timestamp;
-      let insertMessageRecord = function(threadId) {
-        // Setup threadId & threadIdIndex.
-        aMessageRecord.threadId = threadId;
-        aMessageRecord.threadIdIndex = [threadId, timestamp];
-        // Setup participantIdsIndex.
-        aMessageRecord.participantIdsIndex = [];
-        for (let id of participantIds) {
-          aMessageRecord.participantIdsIndex.push([id, timestamp]);
-        }
-
-        if (!isOverriding) {
-          // Really add to message store.
-          aMessageStore.put(aMessageRecord);
-          return;
-        }
-
-        // If we're going to override an old message, we need to update the
-        // info of the original thread containing the overridden message.
-        // To get the original thread ID and read status of the overridden
-        // message record, we need to retrieve it before overriding it.
-        aMessageStore.get(aMessageRecord.id).onsuccess = function(event) {
-          let oldMessageRecord = event.target.result;
-          aMessageStore.put(aMessageRecord);
-          if (oldMessageRecord) {
-            self.updateThreadByMessageChange(aMessageStore,
-                                             aThreadStore,
-                                             oldMessageRecord.threadId,
-                                             [aMessageRecord.id],
-                                             oldMessageRecord.read ? 0 : 1,
-                                             null);
-          }
-        };
-      };
-
-      if (threadRecord) {
-        let needsUpdate = false;
-
-        if (threadRecord.lastTimestamp <= timestamp) {
-          let lastMessageSubject;
-          if (aMessageRecord.type == "mms") {
-            lastMessageSubject = aMessageRecord.headers.subject;
-          }
-          threadRecord.lastMessageSubject = lastMessageSubject || null;
-          threadRecord.lastTimestamp = timestamp;
-          threadRecord.body = aMessageRecord.body;
-          threadRecord.lastMessageId = aMessageRecord.id;
-          threadRecord.lastMessageType = aMessageRecord.type;
-          needsUpdate = true;
-        }
-
-        if (!aMessageRecord.read) {
-          threadRecord.unreadCount++;
-          needsUpdate = true;
-        }
-
-        if (needsUpdate) {
-          aThreadStore.put(threadRecord);
-        }
-
-        insertMessageRecord(threadRecord.id);
-        return;
-      }
-
-      let lastMessageSubject;
-      if (aMessageRecord.type == "mms") {
-        lastMessageSubject = aMessageRecord.headers.subject;
-      }
-
-      threadRecord = {
-        participantIds: participantIds,
-        participantAddresses: aAddresses,
-        lastMessageId: aMessageRecord.id,
-        lastTimestamp: timestamp,
-        lastMessageSubject: lastMessageSubject || null,
-        body: aMessageRecord.body,
-        unreadCount: aMessageRecord.read ? 0 : 1,
-        lastMessageType: aMessageRecord.type,
-      };
-      aThreadStore.add(threadRecord).onsuccess = function(event) {
-        let threadId = event.target.result;
-        insertMessageRecord(threadId);
-      };
-    });
-  },
-
-  fillReceivedMmsThreadParticipants: function(aMessage, threadParticipants) {
-    let receivers = aMessage.receivers;
-    // If we don't want to disable the MMS grouping for receiving, we need to
-    // add the receivers (excluding the user's own number) to the participants
-    // for creating the thread. Some cases might be investigated as below:
-    //
-    // 1. receivers.length == 0
-    //    This usually happens when receiving an MMS notification indication
-    //    which doesn't carry any receivers.
-    // 2. receivers.length == 1
-    //    If the receivers contain single phone number, we don't need to
-    //    add it into participants because we know that number is our own.
-    // 3. receivers.length >= 2
-    //    If the receivers contain multiple phone numbers, we need to add all
-    //    of them but not the user's own number into participants.
-    if (DISABLE_MMS_GROUPING_FOR_RECEIVING || receivers.length < 2) {
-      return;
-    }
-    let isSuccess = false;
-    let slicedReceivers = receivers.slice();
-    if (aMessage.msisdn) {
-      let found = slicedReceivers.indexOf(aMessage.msisdn);
-      if (found !== -1) {
-        isSuccess = true;
-        slicedReceivers.splice(found, 1);
-      }
-    }
-
-    if (!isSuccess) {
-      // For some SIMs we cannot retrieve the vaild MSISDN (i.e. the user's
-      // own phone number), so we cannot correcly exclude the user's own
-      // number from the receivers, thus wrongly building the thread index.
-      if (DEBUG) debug("Error! Cannot strip out user's own phone number!");
-    }
-
-    threadParticipants = threadParticipants.concat(slicedReceivers);
-  },
-
-  saveReceivedMessage: function(aMessage, aCallback) {
-    if ((aMessage.type != "sms" && aMessage.type != "mms") ||
-        (aMessage.type == "sms" && (aMessage.messageClass == undefined ||
-                                    aMessage.sender == undefined)) ||
-        (aMessage.type == "mms" && (aMessage.delivery == undefined ||
-                                    aMessage.deliveryStatus == undefined ||
-                                    !Array.isArray(aMessage.receivers))) ||
-        aMessage.timestamp == undefined) {
-      if (aCallback) {
-        aCallback.notify(Cr.NS_ERROR_FAILURE, null);
-      }
-      return;
-    }
-
-    let threadParticipants;
-    if (aMessage.type == "mms") {
-      if (aMessage.headers.from) {
-        aMessage.sender = aMessage.headers.from.address;
-      } else {
-        aMessage.sender = "anonymous";
-      }
-
-      threadParticipants = [aMessage.sender];
-      LEGACY.fillReceivedMmsThreadParticipants.call(this, aMessage,
-                                                    threadParticipants);
-    } else { // SMS
-      threadParticipants = [aMessage.sender];
-    }
-
-    let timestamp = aMessage.timestamp;
-
-    // Adding needed indexes and extra attributes for internal use.
-    // threadIdIndex & participantIdsIndex are filled in saveRecord().
-    aMessage.readIndex = [FILTER_READ_UNREAD, timestamp];
-    aMessage.read = FILTER_READ_UNREAD;
-
-    // If |sentTimestamp| is not specified, use 0 as default.
-    if (aMessage.sentTimestamp == undefined) {
-      aMessage.sentTimestamp = 0;
-    }
-
-    if (aMessage.type == "mms") {
-      aMessage.transactionIdIndex = aMessage.headers["x-mms-transaction-id"];
-      aMessage.isReadReportSent = false;
-
-      // As a receiver, we don't need to care about the delivery status of
-      // others, so we put a single element with self's phone number in the
-      // |deliveryInfo| array.
-      aMessage.deliveryInfo = [{
-        receiver: aMessage.phoneNumber,
-        deliveryStatus: aMessage.deliveryStatus,
-        deliveryTimestamp: 0,
-        readStatus: MMS.DOM_READ_STATUS_NOT_APPLICABLE,
-        readTimestamp: 0,
-      }];
-
-      delete aMessage.deliveryStatus;
-    }
-
-    if (aMessage.type == "sms") {
-      aMessage.delivery = DELIVERY_RECEIVED;
-      aMessage.deliveryStatus = DELIVERY_STATUS_SUCCESS;
-      aMessage.deliveryTimestamp = 0;
-
-      if (aMessage.pid == undefined) {
-        aMessage.pid = RIL.PDU_PID_DEFAULT;
-      }
-    }
-    aMessage.deliveryIndex = [aMessage.delivery, timestamp];
-
-    LEGACY.saveRecord.call(this, aMessage, threadParticipants, aCallback);
-  },
-
-  saveSendingMessage: function(aMessage, aCallback) {
-    if ((aMessage.type != "sms" && aMessage.type != "mms") ||
-        (aMessage.type == "sms" && aMessage.receiver == undefined) ||
-        (aMessage.type == "mms" && !Array.isArray(aMessage.receivers)) ||
-        aMessage.deliveryStatusRequested == undefined ||
-        aMessage.timestamp == undefined) {
-      if (aCallback) {
-        aCallback.notify(Cr.NS_ERROR_FAILURE, null);
-      }
-      return;
-    }
-
-    // Set |aMessage.deliveryStatus|. Note that for MMS record
-    // it must be an array of strings; For SMS, it's a string.
-    let deliveryStatus = aMessage.deliveryStatusRequested
-                       ? DELIVERY_STATUS_PENDING
-                       : DELIVERY_STATUS_NOT_APPLICABLE;
-    if (aMessage.type == "sms") {
-      aMessage.deliveryStatus = deliveryStatus;
-      // If |deliveryTimestamp| is not specified, use 0 as default.
-      if (aMessage.deliveryTimestamp == undefined) {
-        aMessage.deliveryTimestamp = 0;
-      }
-    } else if (aMessage.type == "mms") {
-      let receivers = aMessage.receivers
-      if (!Array.isArray(receivers)) {
-        if (DEBUG) {
-          debug("Need receivers for MMS. Fail to save the sending message.");
-        }
-        if (aCallback) {
-          aCallback.notify(Cr.NS_ERROR_FAILURE, null);
-        }
-        return;
-      }
-      let readStatus = aMessage.headers["x-mms-read-report"]
-                     ? MMS.DOM_READ_STATUS_PENDING
-                     : MMS.DOM_READ_STATUS_NOT_APPLICABLE;
-      aMessage.deliveryInfo = [];
-      for (let i = 0; i < receivers.length; i++) {
-        aMessage.deliveryInfo.push({
-          receiver: receivers[i],
-          deliveryStatus: deliveryStatus,
-          deliveryTimestamp: 0,
-          readStatus: readStatus,
-          readTimestamp: 0,
-        });
-      }
-    }
-
-    let timestamp = aMessage.timestamp;
-
-    // Adding needed indexes and extra attributes for internal use.
-    // threadIdIndex & participantIdsIndex are filled in saveRecord().
-    aMessage.deliveryIndex = [DELIVERY_SENDING, timestamp];
-    aMessage.readIndex = [FILTER_READ_READ, timestamp];
-    aMessage.delivery = DELIVERY_SENDING;
-    aMessage.messageClass = MESSAGE_CLASS_NORMAL;
-    aMessage.read = FILTER_READ_READ;
-
-    // |sentTimestamp| is not available when the message is still sedning.
-    aMessage.sentTimestamp = 0;
-
-    let addresses;
-    if (aMessage.type == "sms") {
-      addresses = [aMessage.receiver];
-    } else if (aMessage.type == "mms") {
-      addresses = aMessage.receivers;
-    }
-    LEGACY.saveRecord.call(this, aMessage, addresses, aCallback);
-  },
-};
-
-function callMmdbMethodLegacy(aMmdb, aMethodName) {
-  let deferred = Promise.defer();
-
-  let args = Array.slice(arguments, 2);
-  args.push({
-    notify: function(aRv) {
-      if (!Components.isSuccessCode(aRv)) {
-        ok(true, aMethodName + " returns a unsuccessful code: " + aRv);
-        deferred.reject(Array.slice(arguments));
-      } else {
-        ok(true, aMethodName + " returns a successful code: " + aRv);
-        deferred.resolve(Array.slice(arguments));
-      }
-    }
-  });
-  LEGACY[aMethodName].apply(aMmdb, args);
-
-  return deferred.promise;
-}
-
-function saveSendingMessageLegacy(aMmdb, aMessage) {
-  return callMmdbMethodLegacy(aMmdb, "saveSendingMessage", aMessage);
-}
-
-function saveReceivedMessageLegacy(aMmdb, aMessage) {
-  return callMmdbMethodLegacy(aMmdb, "saveReceivedMessage", aMessage);
-}
-
-// Have a long long subject causes the send fails, so we don't need
-// networking here.
-const MMS_MAX_LENGTH_SUBJECT = 40;
-function genMmsSubject(sep) {
-  return "Hello " + (new Array(MMS_MAX_LENGTH_SUBJECT).join(sep)) + " World!";
-}
-
-function generateMms(aSender, aReceivers, aDelivery) {
-  let message = {
-    headers: {},
-    type: "mms",
-    timestamp: Date.now(),
-    receivers: aReceivers,
-    subject: genMmsSubject(' '),
-    attachments: [],
-  };
-
-  message.headers.subject = message.subject;
-  message.headers.to = [];
-  for (let i = 0; i < aReceivers.length; i++) {
-    let receiver = aReceivers[i];
-    let entry = { type: MMS.Address.resolveType(receiver) };
-    if (entry.type == "PLMN") {
-      entry.address = PhoneNumberUtils.normalize(receiver, false);
-    } else {
-      entry.address = receiver;
-    }
-    ok(true, "MMS to address '" + receiver +"' resolved as type " + entry.type);
-    message.headers.to.push(entry);
-  }
-  if (aSender) {
-    message.headers.from = {
-      address: aSender,
-      type: MMS.Address.resolveType(aSender)
-    };
-    ok(true, "MMS from address '" + aSender +"' resolved as type " +
-       message.headers.from.type);
-  }
-
-  if ((aDelivery === DELIVERY_RECEIVED) ||
-      (aDelivery === DELIVERY_NOT_DOWNLOADED)) {
-    message.delivery = aDelivery;
-    message.deliveryStatus = DELIVERY_STATUS_SUCCESS;
-  } else {
-    message.deliveryStatusRequested = false;
-  }
-
-  return message;
-}
-
-function generateSms(aSender, aReceiver, aDelivery) {
-  let message = {
-    type: "sms",
-    sender: aSender,
-    timestamp: Date.now(),
-    receiver: aReceiver,
-    body: "The snow grows white on the mountain tonight.",
-  };
-
-  if (aDelivery === DELIVERY_RECEIVED) {
-    message.messageClass = MESSAGE_CLASS_NORMAL;
-  } else {
-    message.deliveryStatusRequested = false;
-  }
-
-  return message;
-}
-
-function matchArray(lhs, rhs) {
-  if (rhs.length != lhs.length) {
-    return false;
-  }
-
-  for (let k = 0; k < lhs.length; k++) {
-    if (lhs[k] != rhs[k]) {
-      return false;
-    }
-  }
-
-  return true;
-}
-
-const TEST_ADDRESSES = [
-  "+15525225554",      // MMS, TYPE=PLMN
-  "5525225554",        // MMS, TYPE=PLMN
-  "jkalbcjklg",        // MMS, TYPE=PLMN, because of PhoneNumberNormalizer
-  "jk.alb.cjk.lg",     // MMS, TYPE=PLMN, because of PhoneNumberNormalizer
-  "j:k:a:l:b:c:jk:lg", // MMS, TYPE=PLMN, because of PhoneNumberNormalizer
-  "55.252.255.54",     // MMS, TYPE=IPv4
-  "5:5:2:5:2:2:55:54", // MMS, TYPE=IPv6
-  "jk@alb.cjk.lg",     // MMS, TYPE=email
-  "___"                // MMS, TYPE=Others
-];
-
-function populateDatabase(aMmdb) {
-  log("Populating database:");
-
-  let promise = Promise.resolve()
-
-    // We're generating other messages that would be identified as the same
-    // participant with "+15525225554".
-    .then(() => saveReceivedMessageLegacy(
-      aMmdb, generateSms("+15525225554", null, DELIVERY_RECEIVED)))
-
-    // SMS, national number.
-    .then(() => saveReceivedMessageLegacy(
-      aMmdb, generateSms("5525225554", null, DELIVERY_RECEIVED)));
-
-  for (let i = 0; i < TEST_ADDRESSES.length; i++) {
-    let address = TEST_ADDRESSES[i];
-    promise = promise.then(() => saveReceivedMessageLegacy(
-      aMmdb, generateMms(address, ["a"], DELIVERY_RECEIVED)));
-  }
-
-  // Permutation of TEST_ADDRESSES.
-  for (let i = 0; i < TEST_ADDRESSES.length; i++) {
-    for (let j = i + 1; j < TEST_ADDRESSES.length; j++) {
-      let addr_i = TEST_ADDRESSES[i], addr_j = TEST_ADDRESSES[j];
-      promise = promise.then(() => saveSendingMessageLegacy(
-        aMmdb, generateMms(null, [addr_i, addr_j], DELIVERY_SENDING)));
-    }
-  }
-
-  // At this time, we have 3 threads, whose |participants| are:
-  // ["+15525225554"], ["___"], and ["+15525225554", "___"].  The number of each
-  // thread are [ (2 + 8 + 8 * 7 / 2), 1, 8 ] = [ 38, 1, 8 ].
-
-  return promise;
-}
-
-function doVerifyDatabase(aMmdb, aExpected) {
-  // 1) retrieve all threads.
-  return createThreadCursor(aMmdb)
-    .then(function(aValues) {
-      let [errorCode, domThreads] = aValues;
-      is(errorCode, 0, "errorCode");
-      is(domThreads.length, aExpected.length, "domThreads.length");
-
-      let numMessagesInThread = [];
-      let totalMessages = 0;
-
-      for (let i = 0; i < domThreads.length; i++) {
-        let domThread = domThreads[i];
-        log("  thread<" + domThread.id + "> : " + domThread.participants);
-
-        let index = (function() {
-          let rhs = domThread.participants;
-          for (let j = 0; j < aExpected.length; j++) {
-            let lhs = aExpected[j].participants;
-            if (matchArray(lhs, rhs)) {
-              return j;
-            }
-          }
-        })();
-        // 2) make sure all retrieved threads are in expected array.
-        ok(index >= 0, "validity of domThread.participants");
-
-        // 3) fill out numMessagesInThread, which is a <thread id> =>
-        // <num messages> map.
-        numMessagesInThread[domThread.id] = aExpected[index].messages;
-        totalMessages += aExpected[index].messages
-
-        aExpected.splice(index, 1);
-      }
-
-      // 4) make sure no thread is missing by checking |aExpected.length == 0|.
-      is(aExpected.length, 0, "remaining unmatched threads");
-
-      // 5) retrieve all messages.
-      return createMessageCursor(aMmdb)
-        .then(function(aValues) {
-          let [errorCode, domMessages] = aValues;
-          is(errorCode, 0, "errorCode");
-          // 6) check total number of messages.
-          is(domMessages.length, totalMessages, "domMessages.length");
-
-          for (let i = 0; i < domMessages.length; i++) {
-            let domMessage = domMessages[i];
-            // 7) make sure message thread id is valid by checking
-            //    |numMessagesInThread[domMessage.threadId] != null|.
-            ok(numMessagesInThread[domMessage.threadId] != null,
-               "domMessage.threadId");
-
-            // 8) for each message, reduce
-            // |numMessagesInThread[domMessage.threadId]| by 1.
-            --numMessagesInThread[domMessage.threadId];
-            ok(true, "numMessagesInThread[" + domMessage.threadId + "] = " +
-                     numMessagesInThread[domMessage.threadId]);
-          }
-
-          // 9) check if |numMessagesInThread| is now an array of all zeros.
-          for (let i = 0; i < domThreads.length; i++) {
-            let domThread = domThreads[i];
-            is(numMessagesInThread[domThread.id], 0,
-               "numMessagesInThread[" + domThread.id + "]");
-          }
-        });
-    });
-}
-
-function verifyDatabaseBeforeUpgrade(aMmdb) {
-  log("Before updateSchema22:");
-  return doVerifyDatabase(aMmdb, [{
-    participants: ["+15525225554"],
-    messages: 38 // 2 + (9 - 1) + (9 - 1) * ( 9 - 1 - 1) / 2
-  }, {
-    participants: ["___"],
-    messages: 1
-  }, {
-    participants: ["+15525225554", "___"],
-    messages: 8
-  }]);
-}
-
-function verifyDatabaseAfterUpgrade(aMmdb) {
-  log("After updateSchema22:");
-  return doVerifyDatabase(aMmdb, [{
-    participants: ["+15525225554"],
-    messages: 17 // 2 + 5 + 5 * (5 - 1) / 2
-  }, {
-    participants: ["55.252.255.54"],
-    messages: 1
-  }, {
-    participants: ["5:5:2:5:2:2:55:54"],
-    messages: 1
-  }, {
-    participants: ["jk@alb.cjk.lg"],
-    messages: 1
-  }, {
-    participants: ["___"],
-    messages: 1
-  }, {
-    participants: ["+15525225554", "55.252.255.54"],
-    messages: 5
-  }, {
-    participants: ["+15525225554", "5:5:2:5:2:2:55:54"],
-    messages: 5
-  }, {
-    participants: ["+15525225554", "jk@alb.cjk.lg"],
-    messages: 5
-  }, {
-    participants: ["+15525225554", "___"],
-    messages: 5
-  }, {
-    participants: ["55.252.255.54", "5:5:2:5:2:2:55:54"],
-    messages: 1
-  }, {
-    participants: ["55.252.255.54", "jk@alb.cjk.lg"],
-    messages: 1
-  }, {
-    participants: ["55.252.255.54", "___"],
-    messages: 1
-  }, {
-    participants: ["5:5:2:5:2:2:55:54", "jk@alb.cjk.lg"],
-    messages: 1
-  }, {
-    participants: ["5:5:2:5:2:2:55:54", "___"],
-    messages: 1
-  }, {
-    participants: ["jk@alb.cjk.lg", "___"],
-    messages: 1
-  }]);
-}
-
-startTestBase(function testCaseMain() {
-  let mmdb = newMobileMessageDB();
-  return initMobileMessageDB(mmdb, DBNAME, 22)
-    .then(() => populateDatabase(mmdb))
-    .then(() => verifyDatabaseBeforeUpgrade(mmdb))
-    .then(() => closeMobileMessageDB(mmdb))
-
-    .then(() => initMobileMessageDB(mmdb, DBNAME, 23))
-    .then(() => verifyDatabaseAfterUpgrade(mmdb))
-    .then(() => closeMobileMessageDB(mmdb));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mmdb_upgradeSchema_current_structure.js
+++ /dev/null
@@ -1,171 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'mmdb_head.js';
-
-const DBNAME = "test_mmdb_upgradeSchema_current_structure:" + newUUID();
-
-const LAYOUT = {
-  sms: {
-    keyPath: "id",
-    autoIncrement: false,
-    indice: {
-      delivery: {
-        keyPath: "deliveryIndex",
-        multiEntry: false,
-        unique: false,
-      },
-
-      envelopeId: {
-        keyPath: "envelopeIdIndex",
-        multiEntry: false,
-        unique: true,
-      },
-
-      participantIds: {
-        keyPath: "participantIdsIndex",
-        multiEntry: true,
-        unique: false,
-      },
-
-      read: {
-        keyPath: "readIndex",
-        multiEntry: false,
-        unique: false,
-      },
-
-      threadId: {
-        keyPath: "threadIdIndex",
-        multiEntry: false,
-        unique: false,
-      },
-
-      timestamp: {
-        keyPath: "timestamp",
-        multiEntry: false,
-        unique: false,
-      },
-
-      transactionId: {
-        keyPath: "transactionIdIndex",
-        multiEntry: false,
-        unique: true,
-      }
-    },
-  },
-
-  thread: {
-    keyPath: "id",
-    autoIncrement: true,
-    indice: {
-      lastTimestamp: {
-        keyPath: "lastTimestamp",
-        multiEntry: false,
-        unique: false,
-      },
-
-      participantIds: {
-        keyPath: "participantIds",
-        multiEntry: false,
-        unique: false,
-      }
-    },
-  },
-
-  participant: {
-    keyPath: "id",
-    autoIncrement: true,
-    indice: {
-      addresses: {
-        keyPath: "addresses",
-        multiEntry: true,
-        unique: false,
-      }
-    },
-  },
-
-  "sms-segment": {
-    keyPath: "id",
-    autoIncrement: true,
-    indice: {
-      hash: {
-        keyPath: "hash",
-        multiEntry: false,
-        unique: true,
-      }
-    },
-  }
-};
-
-function verifyIndex(aIndex, aIndexLayout) {
-  log("  Verifying index '" + aIndex.name + "'");
-
-  is(aIndex.keyPath, aIndexLayout.keyPath, "aIndex.keyPath");
-  is(aIndex.multiEntry, aIndexLayout.multiEntry, "aIndex.multiEntry");
-  is(aIndex.unique, aIndexLayout.unique, "aIndex.unique");
-}
-
-function verifyStore(aObjectStore, aStoreLayout) {
-  log("Verifying object store '" + aObjectStore.name + "'");
-
-  is(aObjectStore.keyPath, aStoreLayout.keyPath, "aObjectStore.keyPath");
-  is(aObjectStore.autoIncrement, aStoreLayout.autoIncrement,
-     "aObjectStore.autoIncrement");
-
-  let expectedIndexNames = Object.keys(aStoreLayout.indice);
-  for (let i = 0; i < aObjectStore.indexNames.length; i++) {
-    let indexName = aObjectStore.indexNames.item(i);
-
-    let index = expectedIndexNames.indexOf(indexName);
-    ok(index >= 0, "Index name '" + indexName + "' validity");
-    expectedIndexNames.splice(index, 1);
-
-    verifyIndex(aObjectStore.index(indexName), aStoreLayout.indice[indexName]);
-  }
-
-  // All index names should have been verified and leaves expectedIndexNames an
-  // empty array.
-  is(expectedIndexNames.length, 0, "Extra indice: " + expectedIndexNames);
-}
-
-function verifyDatabase(aMmdb) {
-  let deferred = Promise.defer();
-
-  let expectedStoreNames = Object.keys(LAYOUT);
-  aMmdb.newTxn("readonly", function(aError, aTransaction, aObjectStores) {
-    if (!Array.isArray(aObjectStores)) {
-      // When we have only one object store open, aObjectStores is an instance
-      // of IDBObjectStore.  Push it to an array for convenience here.
-      aObjectStores = [aObjectStores];
-    }
-
-    is(aObjectStores.length, expectedStoreNames.length,
-       "expected number of object stores");
-
-    let slicedStoreNames = expectedStoreNames.slice();
-    for (let i = 0; i < aObjectStores.length; i++) {
-      let objectStore = aObjectStores[i];
-
-      let index = slicedStoreNames.indexOf(objectStore.name);
-      ok(index >= 0, "objectStore.name '" + objectStore.name + "' validity");
-      slicedStoreNames.splice(index, 1);
-
-      verifyStore(objectStore, LAYOUT[objectStore.name]);
-    }
-
-    // All store names should have been verified and leaves slicedStoreNames an
-    // empty array.
-    is(slicedStoreNames.length, 0, "Extra object stores: " + slicedStoreNames);
-
-    deferred.resolve(aMmdb);
-  }, expectedStoreNames);
-
-  return deferred.promise;
-}
-
-startTestBase(function testCaseMain() {
-  return initMobileMessageDB(newMobileMessageDB(), DBNAME, 0)
-    .then(verifyDatabase)
-    .then(closeMobileMessageDB);
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mmsmessage_attachments.js
+++ /dev/null
@@ -1,119 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-const MMS_MAX_LENGTH_SUBJECT = 40;
-
-SpecialPowers.addPermission("sms", true, document);
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-
-var tasks = {
-  // List of test fuctions. Each of them should call |tasks.next()| when
-  // completed or |tasks.finish()| to jump to the last one.
-  _tasks: [],
-  _nextTaskIndex: 0,
-
-  push: function(func) {
-    this._tasks.push(func);
-  },
-
-  next: function() {
-    let index = this._nextTaskIndex++;
-    let task = this._tasks[index];
-    try {
-      task();
-    } catch (ex) {
-      ok(false, "test task[" + index + "] throws: " + ex);
-      // Run last task as clean up if possible.
-      if (index != this._tasks.length - 1) {
-        this.finish();
-      }
-    }
-  },
-
-  finish: function() {
-    this._tasks[this._tasks.length - 1]();
-  },
-
-  run: function() {
-    this.next();
-  }
-};
-
-var manager;
-
-function getAllMessages(callback, filter, reverse) {
-  let messages = [];
-  let request = manager.getMessages(filter, reverse || false);
-  request.onsuccess = function(event) {
-    if (request.result) {
-      messages.push(request.result);
-      request.continue();
-      return;
-    }
-
-    window.setTimeout(callback.bind(null, messages), 0);
-  }
-}
-
-function deleteAllMessages() {
-  getAllMessages(function deleteAll(messages) {
-    let message = messages.shift();
-    if (!message) {
-      ok(true, "all messages deleted");
-      tasks.next();
-      return;
-    }
-
-    let request = manager.delete(message.id);
-    request.onsuccess = deleteAll.bind(null, messages);
-    request.onerror = function(event) {
-      ok(false, "failed to delete all messages");
-      tasks.finish();
-    }
-  });
-}
-
-tasks.push(function() {
-  log("Verifying initial state.");
-
-  manager = window.navigator.mozMobileMessage;
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-
-  tasks.next();
-});
-
-tasks.push(function() {
-  log("MmsMessage.attachments should be an empty array.");
-
-  manager.onfailed = function(event) {
-    manager.onfailed = null;
-
-    let message = event.message;
-    ok(Array.isArray(message.attachments) && message.attachments.length === 0,
-       "message.attachments should be an empty array.");
-
-    tasks.next();
-  };
-
-  // Have a long long subject causes the send fails, so we don't need
-  // networking here.
-  manager.sendMMS({
-    subject: new Array(MMS_MAX_LENGTH_SUBJECT + 2).join("a"),
-    receivers: ["1", "2"],
-    attachments: [],
-  });
-});
-
-tasks.push(deleteAllMessages);
-
-// WARNING: All tasks should be pushed before this!!!
-tasks.push(function cleanUp() {
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-});
-
-tasks.run();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mobilemessage_dsds_default_service_id.js
+++ /dev/null
@@ -1,130 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_CONTEXT = "chrome";
-
-Cu.import("resource://gre/modules/Promise.jsm");
-
-const MMS_SERVICE_CONTRACTID = "@mozilla.org/mms/mmsservice;1";
-const SMS_SERVICE_CONTRACTID = "@mozilla.org/sms/smsservice;1";
-
-const PREF_RIL_NUM_RADIO_INTERFACES = "ril.numRadioInterfaces";
-const PREF_MMS_DEFAULT_SERVICE_ID = "dom.mms.defaultServiceId";
-const PREF_SMS_DEFAULT_SERVICE_ID = "dom.sms.defaultServiceId";
-
-function setPrefAndVerify(prefKey, setVal, service, attrName, expectedVal, deferred) {
-  log("  Set '" + prefKey + "' to " + setVal);
-  Services.prefs.setIntPref(prefKey, setVal);
-  let prefVal = Services.prefs.getIntPref(prefKey);
-  is(prefVal, setVal, "'" + prefKey + "' set to " + setVal);
-
-  window.setTimeout(function() {
-    let defaultVal = service[attrName];
-    is(defaultVal, expectedVal, attrName);
-
-    deferred.resolve(service);
-  }, 0);
-}
-
-function getNumRadioInterfaces() {
-  let deferred = Promise.defer();
-
-  window.setTimeout(function() {
-    let numRil = Services.prefs.getIntPref(PREF_RIL_NUM_RADIO_INTERFACES);
-    log("numRil = " + numRil);
-
-    deferred.resolve(numRil);
-  }, 0);
-
-  return deferred.promise;
-}
-
-function getService(contractId, ifaceName) {
-  let deferred = Promise.defer();
-
-  window.setTimeout(function() {
-    log("Getting service for " + ifaceName);
-    let service = Cc[contractId].getService(Ci[ifaceName]);
-    ok(service, "service.constructor is " + service.constructor);
-
-    deferred.resolve(service);
-  }, 0);
-
-  return deferred.promise;
-}
-
-function checkInitialEquality(attrName, prefKey, service) {
-  let deferred = Promise.defer();
-
-  log("  Checking initial value for '" + prefKey + "'");
-  let origPrefVal = Services.prefs.getIntPref(prefKey);
-  ok(isFinite(origPrefVal), "default '" + prefKey + "' value");
-
-  window.setTimeout(function() {
-    let defaultVal = service[attrName];
-    is(defaultVal, origPrefVal, attrName);
-
-    deferred.resolve(service);
-  }, 0);
-
-  return deferred.promise;
-}
-
-function checkSetToNegtiveValue(attrName, prefKey, service) {
-  let deferred = Promise.defer();
-
-  // Set to -1 and verify defaultVal == 0.
-  setPrefAndVerify(prefKey, -1, service, attrName, 0, deferred);
-
-  return deferred.promise;
-}
-
-function checkSetToOverflowedValue(attrName, prefKey, numRil, service) {
-  let deferred = Promise.defer();
-
-  // Set to larger-equal than numRil and verify defaultVal == 0.
-  setPrefAndVerify(prefKey, numRil, service, attrName, 0, deferred);
-
-  return deferred.promise;
-}
-
-function checkValueChange(attrName, prefKey, numRil, service) {
-  let deferred = Promise.defer();
-
-  if (numRil > 1) {
-    // Set to (numRil - 1) and verify defaultVal equals.
-    setPrefAndVerify(prefKey, numRil - 1, service, attrName, numRil - 1, deferred);
-  } else {
-    window.setTimeout(function() {
-      deferred.resolve(service);
-    }, 0);
-  }
-
-  return deferred.promise;
-}
-
-function verify(contractId, ifaceName, attrName, prefKey, numRil) {
-  let deferred = Promise.defer();
-
-  getService(contractId, ifaceName)
-    .then(checkInitialEquality.bind(null, attrName, prefKey))
-    .then(checkSetToNegtiveValue.bind(null, attrName, prefKey))
-    .then(checkSetToOverflowedValue.bind(null, attrName, prefKey, numRil))
-    .then(checkValueChange.bind(null, attrName, prefKey, numRil))
-    .then(function() {
-      // Reset.
-      Services.prefs.clearUserPref(prefKey);
-
-      deferred.resolve(numRil);
-    });
-
-  return deferred.promise;
-}
-
-getNumRadioInterfaces()
-  .then(verify.bind(null, MMS_SERVICE_CONTRACTID, "nsIMmsService",
-                    "mmsDefaultServiceId", PREF_MMS_DEFAULT_SERVICE_ID))
-  .then(verify.bind(null, SMS_SERVICE_CONTRACTID, "nsISmsService",
-                    "smsDefaultServiceId", PREF_SMS_DEFAULT_SERVICE_ID))
-  .then(finish);
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_mt_sms_concatenation.js
+++ /dev/null
@@ -1,151 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const PDU_SMSC_NONE = "00"; // no SMSC Address
-
-const PDU_FIRST_OCTET = "40"; // RP:no, UDHI:yes, SRI:no, MMS:no, MTI:SMS-DELIVER
-
-const PDU_SENDER = "0A912143658709"; // +1234567890
-const SENDER = "+1234567890";
-
-const PDU_PID_NORMAL = "00";
-
-const PDU_DCS_NORMAL_UCS2 = "08";
-const PDU_DCS_CLASS0_UCS2 = "18";
-const PDU_DCS_NORMAL_8BIT = "04";
-const PDU_DCS_CLASS0_8BIT = "14";
-
-const PDU_TIMESTAMP = "00101000000000"; // 2000/01/01
-
-function byteValueToHexString(aValue) {
-  let str = Number(aValue).toString(16).toUpperCase();
-  return str.length == 1 ? "0" + str : str;
-}
-
-var ref_num = 0;
-function buildTextPdus(aDcs, aInsertDuplication = false) {
-  ref_num++;
-
-  let IEI_CONCATE_1 = "0003" + byteValueToHexString(ref_num) + "0301";
-  let IEI_CONCATE_2 = "0003" + byteValueToHexString(ref_num) + "0302";
-  let IEI_CONCATE_3 = "0003" + byteValueToHexString(ref_num) + "0303";
-  let PDU_UDL = "08"; // UDHL(1) + UDH(5) + UCS2 Char (2)
-  let PDU_UDHL = "05";
-
-  let PDU_UD_A = "0041"; // "A"
-  let PDU_UD_B = "0042"; // "B"
-  let PDU_UD_C = "0043"; // "C"
-
-  let PDU_COMMON = PDU_SMSC_NONE + PDU_FIRST_OCTET + PDU_SENDER +
-    PDU_PID_NORMAL + aDcs + PDU_TIMESTAMP + PDU_UDL + PDU_UDHL;
-
-  let pdus = [
-    PDU_COMMON + IEI_CONCATE_1 + PDU_UD_A,
-    PDU_COMMON + IEI_CONCATE_2 + PDU_UD_B,
-    PDU_COMMON + IEI_CONCATE_3 + PDU_UD_C
-  ];
-
-  if (aInsertDuplication) {
-    log("Insert Duplicated text PDU");
-    // The 2nd PDU_UD_A is expected to be ignored.
-    pdus.unshift(PDU_COMMON + IEI_CONCATE_1 + PDU_UD_A);
-    // Expected to be replaced with PDU_UD_A;
-    pdus.unshift(PDU_COMMON + IEI_CONCATE_1 + PDU_UD_C);
-  }
-
-  return pdus;
-}
-
-function buildBinaryPdus(aDcs, aInsertDuplication = false) {
-  ref_num++;
-  let IEI_PORT = "05040B8423F0";
-
-  let PDU_DATA1 = "C106316170706C69636174696F6E2F76" +
-                  "6E642E7761702E6D6D732D6D65737361" +
-                  "676500B131302E382E3133302E313800" +
-                  "AF84B4818C82986B4430595538595347" +
-                  "77464E446741416B4876736C58303141" +
-                  "41414141414141008D90890380310096" +
-                  "05EA4D4D53008A808E02024188058103" +
-                  "015F9083687474703A2F2F6D6D732E65";
-
-  let PDU_DATA2 = "6D6F6D652E6E65743A383030322F6B44" +
-                  "3059553859534777464E446741416B48" +
-                  "76736C583031414141414141414100";
-
-  let PDU_COMMON = PDU_SMSC_NONE + PDU_FIRST_OCTET + PDU_SENDER +
-    PDU_PID_NORMAL + aDcs + PDU_TIMESTAMP;
-
-  function construstBinaryUserData(aBinaryData, aSeqNum) {
-    let ieiConcat = "0003" + byteValueToHexString(ref_num) + "02" +
-                    byteValueToHexString(aSeqNum);
-
-    let udh = IEI_PORT + ieiConcat;
-    let udhl = byteValueToHexString(udh.length / 2);
-    let ud = udhl + udh + aBinaryData;
-    let udl = byteValueToHexString(ud.length / 2);
-
-    return udl + ud;
-  }
-
-  let pdus = [
-    PDU_COMMON + construstBinaryUserData(PDU_DATA1, 1),
-    PDU_COMMON + construstBinaryUserData(PDU_DATA2, 2)
-  ];
-
-  if (aInsertDuplication) {
-    log("Insert Duplicated binary PDU");
-    // The 2nd PDU_DATA1 is expected to be ignored.
-    pdus.unshift(PDU_COMMON + construstBinaryUserData(PDU_DATA1, 1));
-    // Expected to be replaced with PDU_DATA1;
-    pdus.unshift(PDU_COMMON + construstBinaryUserData(PDU_DATA2, 1));
-  }
-
-  return pdus;
-}
-
-function verifyTextMessage(aMessage, aMessageClass) {
-  is(aMessage.messageClass, aMessageClass, "SmsMessage class");
-  is(aMessage.sender, SENDER, "SmsMessage sender");
-  is(aMessage.body, "ABC", "SmsMessage body");
-}
-
-function verifyBinaryMessage(aMessage) {
-  is(aMessage.type, "mms", "MmsMessage type");
-  is(aMessage.delivery, "not-downloaded", "MmsMessage delivery");
-
-  // remove duplicated M-Notification.ind for next test.
-  return deleteMessagesById([aMessage.id]);
-}
-
-function testText(aDcs, aClass) {
-  log("testText(): aDcs = " + aDcs + ", aClass = " + aClass);
-  return sendMultipleRawSmsToEmulatorAndWait(buildTextPdus(aDcs))
-    .then((results) => verifyTextMessage(results[0].message, aClass))
-    .then(() => sendMultipleRawSmsToEmulatorAndWait(buildTextPdus(aDcs, true)))
-    .then((results) => verifyTextMessage(results[0].message, aClass));
-}
-
-function testBinary(aDcs) {
-  log("testBinary(): aDcs = " + aDcs);
-  return sendMultipleRawSmsToEmulatorAndWait(buildBinaryPdus(aDcs))
-    .then((results) => verifyBinaryMessage(results[0].message))
-    .then(() => sendMultipleRawSmsToEmulatorAndWait(buildBinaryPdus(aDcs, true)))
-    .then((results) => verifyBinaryMessage(results[0].message));
-}
-
-SpecialPowers.pushPrefEnv(
-  {"set": [["dom.mms.retrieval_mode", "manual"]]},
-  function startTest() {
-    startTestCommon(function testCaseMain() {
-      return Promise.resolve()
-        .then(() => testText(PDU_DCS_NORMAL_UCS2, "normal"))
-        .then(() => testText(PDU_DCS_CLASS0_UCS2, "class-0"))
-        .then(() => testBinary(PDU_DCS_NORMAL_8BIT))
-        .then(() => testBinary(PDU_DCS_CLASS0_8BIT));
-    });
-  }
-);
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_ondeleted_event.js
+++ /dev/null
@@ -1,58 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const DESTINATING_ADDRESS_1 = "0987654321";
-const DESTINATING_ADDRESS_2 = "1234567890";
-const OUT_TEXT = "Outgoing SMS message!";
-
-function verifyDeletedInfo(aDeletedInfo, aMsgIds, aThreadIds) {
-    is(JSON.stringify(aDeletedInfo.deletedMessageIds),
-       JSON.stringify(aMsgIds), 'Check Msg Id.');
-    is(JSON.stringify(aDeletedInfo.deletedThreadIds),
-       JSON.stringify(aThreadIds), 'Check Thread Id.');
-}
-
-function testDeletingMessagesInOneThreadOneByOne() {
-  let sentMessages = [];
-
-  return Promise.resolve()
-  .then(() => sendSmsWithSuccess(DESTINATING_ADDRESS_1, OUT_TEXT))
-  .then((aMessage) => { sentMessages.push(aMessage); })
-  .then(() => sendSmsWithSuccess(DESTINATING_ADDRESS_1, OUT_TEXT))
-  .then((aMessage) => { sentMessages.push(aMessage); })
-  .then(() => deleteMessagesById([sentMessages[0].id]))
-  .then((aResult) => {
-    verifyDeletedInfo(aResult.deletedInfo,
-                      [sentMessages[0].id],
-                      null);
-  })
-  .then(() => deleteMessagesById([sentMessages[1].id]))
-  .then((aResult) => {
-    verifyDeletedInfo(aResult.deletedInfo,
-                      [sentMessages[1].id],
-                      [sentMessages[1].threadId]);
-  });
-}
-
-function testDeletingMessagesInTwoThreadsAtOnce() {
-  let sentMessages = [];
-  return Promise.resolve()
-  .then(() => sendSmsWithSuccess(DESTINATING_ADDRESS_1, OUT_TEXT))
-  .then((aMessage) => { sentMessages.push(aMessage); })
-  .then(() => sendSmsWithSuccess(DESTINATING_ADDRESS_2, OUT_TEXT))
-  .then((aMessage) => { sentMessages.push(aMessage); })
-  .then(() =>
-    deleteMessagesById(sentMessages.map((aMsg) => { return aMsg.id; })))
-  .then((aResult) =>
-    verifyDeletedInfo(aResult.deletedInfo,
-                      sentMessages.map((aMsg) => { return aMsg.id; }),
-                      sentMessages.map((aMsg) => { return aMsg.threadId; })));
-}
-
-startTestCommon(function testCaseMain() {
-  return testDeletingMessagesInOneThreadOneByOne()
-    .then(() => testDeletingMessagesInTwoThreadsAtOnce());
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_outgoing.js
+++ /dev/null
@@ -1,152 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const SENDER = "15555215554"; // the emulator's number
-
-const SHORT_BODY = "Hello SMS world!";
-const LONG_BODY = "Let me not to the marriage of true minds\n"
-                + "Admit impediments. Love is not love\n"
-                + "Which alters when it alteration finds,\n"
-                + "Or bends with the remover to remove:\n\n"
-                + "O, no! it is an ever-fix`ed mark,\n"
-                + "That looks on tempests and is never shaken;\n"
-                + "It is the star to every wand'ring bark,\n"
-                + "Whose worth's unknown, although his heighth be taken.\n\n"
-                + "Love's not Time's fool, though rosy lips and cheeks\n"
-                + "Within his bending sickle's compass come;\n"
-                + "Love alters not with his brief hours and weeks,\n"
-                + "But bears it out even to the edge of doom:\n\n"
-                + "If this be error and upon me proved,\n"
-                + "I never writ, nor no man ever loved. ";
-
-function checkMessage(message, delivery, body) {
-  ok(message, "message is valid");
-  ok(message instanceof SmsMessage,
-     "message is instanceof " + message.constructor);
-
-  is(message.type, "sms", "message.type");
-  ok(message.id, "message.id");
-  ok(message.threadId, "message.threadId");
-  ok(message.iccId, "message.iccId");
-  is(message.delivery, delivery, "message.delivery");
-  is(message.deliveryStatus, "pending", "message.deliveryStatus");
-  is(message.sender, SENDER, "message.sender");
-  ok(message.receiver, "message.receiver");
-  is(message.body, body, "message.body");
-  is(message.messageClass, "normal", "message.messageClass");
-  is(message.read, true, "message.read");
-
-  // TODO: bug 788928 - add test cases for deliverysuccess event.
-  is(message.deliveryTimestamp, 0, "deliveryTimestamp is 0");
-
-  // Test message.sentTimestamp.
-  if (message.delivery == "sending") {
-    ok(message.sentTimestamp == 0, "message.sentTimestamp should be 0");
-  } else if (message.delivery == "sent") {
-    ok(message.sentTimestamp != 0, "message.sentTimestamp shouldn't be 0");
-  }
-}
-
-function isReceiverMatch(aReceiver, aEvent) {
-  // Bug 838542: following check throws an exception and fails this case.
-  // ok(event instanceof MozSmsEvent,
-  //    "event is instanceof " + event.constructor)
-  ok(aEvent, "sending event is valid");
-
-  let message = aEvent.message;
-  return message.receiver === aReceiver;
-}
-
-function doSingleRequest(aRequest, aReceiver, aBody, aNow) {
-  let sendingGot = false, sentGot = false, successGot = false;
-  let sendingMessage;
-  let promises = [];
-
-  promises.push(waitForManagerEvent("sending",
-                                    isReceiverMatch.bind(null, aReceiver))
-    .then(function(aEvent) {
-      log("  onsending event for '" + aReceiver + "' received.");
-
-      sendingMessage = aEvent.message;
-      checkMessage(sendingMessage, "sending", aBody);
-      // timestamp is in seconds.
-      ok(Math.floor(sendingMessage.timestamp / 1000) >= Math.floor(aNow / 1000),
-         "sent timestamp is valid");
-
-      ok(!sendingGot, "sending event should not have been triggered");
-      ok(!sentGot, "sent event should not have been triggered");
-      ok(!successGot, "success event should not have been triggered");
-
-      sendingGot = true;
-    }));
-
-  promises.push(waitForManagerEvent("sent",
-                                    isReceiverMatch.bind(null, aReceiver))
-    .then(function(aEvent) {
-      log("  onsent event for '" + aReceiver + "' received.");
-
-      let message = aEvent.message;
-      checkMessage(message, "sent", aBody);
-      // Should be mostly identical to sendingMessage.
-      is(message.id, sendingMessage.id, "message.id");
-      is(message.receiver, sendingMessage.receiver, "message.receiver");
-      is(message.body, sendingMessage.body, "message.body");
-      is(message.timestamp, sendingMessage.timestamp, "message.timestamp");
-
-      ok(sendingGot, "sending event should have been triggered");
-      ok(!sentGot, "sent event should not have been triggered");
-      ok(successGot, "success event should have been triggered");
-
-      sentGot = true;
-    }));
-
-  promises.push(aRequest.then(function(aResult) {
-    log("  onsuccess event for '" + aReceiver + "' received.");
-
-    checkMessage(aResult, "sent", aBody);
-    // Should be mostly identical to sendingMessage.
-    is(aResult.id, sendingMessage.id, "message.id");
-    is(aResult.receiver, sendingMessage.receiver, "message.receiver");
-    is(aResult.body, sendingMessage.body, "message.body");
-    is(aResult.timestamp, sendingMessage.timestamp, "message.timestamp");
-
-    ok(sendingGot, "sending event should have been triggered");
-    ok(!sentGot, "sent event should not have been triggered");
-    ok(!successGot, "success event should not have been triggered");
-
-    successGot = true;
-  }));
-
-  return Promise.all(promises);
-}
-
-function doSendMessageAndCheckSuccess(receivers, body) {
-  log("Testing sending message(s) to receiver(s): " + JSON.stringify(receivers));
-
-  let now = Date.now();
-
-  let result = manager.send(receivers, body);
-  is(Array.isArray(result), Array.isArray(receivers),
-     "send() returns an array of requests if receivers is an array");
-  if (Array.isArray(receivers)) {
-    is(result.length, receivers.length, "returned array length");
-
-    return Promise.all(result.map(function(request, index) {
-      return doSingleRequest(request, receivers[index], body, now);
-    }));
-  }
-
-  return doSingleRequest(result, receivers, body, now);
-}
-
-startTestBase(function testCaseMain() {
-  return ensureMobileMessage()
-    .then(() => pushPrefEnv({ set: [['dom.sms.strict7BitEncoding', false],
-                                    ['dom.sms.requestStatusReport', true]] }))
-    .then(() => doSendMessageAndCheckSuccess("1", SHORT_BODY))
-    .then(() => doSendMessageAndCheckSuccess("1", LONG_BODY))
-    .then(() => doSendMessageAndCheckSuccess(["1", "2"], SHORT_BODY));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_outgoing_delete.js
+++ /dev/null
@@ -1,163 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-SpecialPowers.setBoolPref("dom.sms.requestStatusReport", true);
-SpecialPowers.addPermission("sms", true, document);
-
-const SENDER = "15555215554"; // the emulator's number
-const RECEIVER = "5551117777"; // the destination number
-
-var manager = window.navigator.mozMobileMessage;
-var msgText = "Mozilla Firefox OS!";
-var gotSmsOnsent = false;
-var gotReqOnsuccess = false;
-
-function verifyInitialState() {
-  log("Verifying initial state.");
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-  sendSms();
-}
-
-function sendSms() {
-  let smsId = 0;
-
-  log("Sending an SMS.");
-  manager.onsent = function(event) {
-    log("Received 'onsent' event.");
-    gotSmsOnsent = true;
-    let sentSms = event.message;
-    ok(sentSms, "outgoing sms");
-    ok(sentSms.id, "sms id");
-    smsId = sentSms.id;
-    log("Sent SMS (id: " + smsId + ").");
-    ok(sentSms.threadId, "thread id");
-    is(sentSms.body, msgText, "msg body");
-    is(sentSms.delivery, "sent", "delivery");
-    is(sentSms.deliveryStatus, "pending", "deliveryStatus");
-    is(sentSms.read, true, "read");
-    is(sentSms.receiver, RECEIVER, "receiver");
-    is(sentSms.sender, SENDER, "sender");
-    is(sentSms.messageClass, "normal", "messageClass");
-    is(sentSms.deliveryTimestamp, 0, "deliveryTimestamp is 0");
-
-    if (gotSmsOnsent && gotReqOnsuccess) { verifySmsExists(smsId); }
-  };
-
-  let requestRet = manager.send(RECEIVER, msgText);
-  ok(requestRet, "smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    gotReqOnsuccess = true;
-    if(event.target.result){
-      if (gotSmsOnsent && gotReqOnsuccess) { verifySmsExists(smsId); }
-    } else {
-      log("smsrequest returned false for manager.send");
-      ok(false,"SMS send failed");
-      cleanUp();
-    }
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.send request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function verifySmsExists(smsId) {
-  log("Getting SMS (id: " + smsId + ").");
-  let requestRet = manager.getMessage(smsId);
-  ok(requestRet, "smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    ok(event.target.result, "smsrequest event.target.result");
-    let foundSms = event.target.result;
-    is(foundSms.id, smsId, "found SMS id matches");
-    is(foundSms.body, msgText, "found SMS msg text matches");
-    is(foundSms.delivery, "sent", "delivery");
-    is(foundSms.read, true, "read");
-    is(foundSms.receiver, RECEIVER, "receiver");
-    is(foundSms.sender, SENDER, "sender");
-    is(foundSms.messageClass, "normal", "messageClass");
-    log("Got SMS (id: " + foundSms.id + ") as expected.");
-    deleteSms(smsId);
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    is(event.target.error.name, "NotFoundError", "error returned");
-    log("Could not get SMS (id: " + smsId + ") but should have.");
-    ok(false,"SMS was not found");
-    cleanUp();
-  };
-}
-
-function deleteSms(smsId){
-  log("Deleting SMS (id: " + smsId + ") using sms id parameter.");
-  let requestRet = manager.delete(smsId);
-  ok(requestRet,"smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if(event.target.result){
-      verifySmsDeleted(smsId);
-    } else {
-      log("smsrequest returned false for manager.delete");
-      ok(false,"SMS delete failed");
-      cleanUp();
-    }
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.delete request returned unexpected error: "
-        + event.target.error.name );
-    cleanUp();
-  };
-}
-
-function verifySmsDeleted(smsId) {
-  log("Getting SMS (id: " + smsId + ").");
-  let requestRet = manager.getMessage(smsId);
-  ok(requestRet, "smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    ok(event.target.result, "smsrequest event.target.result");
-    let foundSms = event.target.result;
-    is(foundSms.id, smsId, "found SMS id matches");
-    is(foundSms.body, msgText, "found SMS msg text matches");
-    log("Got SMS (id: " + foundSms.id + ") but should not have.");
-    ok(false, "SMS was not deleted");
-    cleanUp();
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    is(event.target.error.name, "NotFoundError", "error returned");
-    log("Could not get SMS (id: " + smsId + ") as expected.");
-    cleanUp();
-  };
-}
-
-function cleanUp() {
-  manager.onsent = null;
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  SpecialPowers.clearUserPref("dom.sms.requestStatusReport");
-  finish();
-}
-
-// Start the test
-verifyInitialState();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_outgoing_max_segments.js
+++ /dev/null
@@ -1,132 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-SpecialPowers.addPermission("sms", true, document);
-
-var manager = window.navigator.mozMobileMessage;
-// https://developer.mozilla.org/en-US/docs/DOM/SmsManager
-var maxCharsPerSms = 160;
-var maxSegments = 10; // 10 message segments concatenated into 1 multipart SMS
-
-function verifyInitialState() {
-  log("Verifying initial state.");
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-  sendSms();
-}
-
-function sendSms() {
-  let destNumber = "5551234567";
-  let msgText = "";
-  let gotReqOnSuccess = false;
-  let gotSmsOnSent = false;
-  let sentSms;
-
-  // Build the message text
-  msgText = new Array((maxCharsPerSms * maxSegments) + 1).join('a');
-  log("Sending multipart SMS (" + msgText.length + " chars total).");
-
-  manager.onsent = function(event) {
-    manager.onsent = null;
-    log("Received 'onsent' event.");
-
-    gotSmsOnSent = true;
-    sentSms = event.message;
-    ok(sentSms, "outgoing sms");
-    ok(sentSms.id, "sms id");
-    log("Sent SMS (id: " + sentSms.id + ").");
-    ok(sentSms.threadId, "thread id");
-    is(sentSms.body.length, msgText.length, "text length");
-    is(sentSms.body, msgText, "msg body");
-    is(sentSms.delivery, "sent", "delivery");
-
-    if (gotReqOnSuccess) { verifySmsExists(sentSms); }
-  };
-
-  let requestRet = manager.send(destNumber, msgText);
-  ok(requestRet, "smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    gotReqOnSuccess = true;
-    if (event.target.result) {
-      if (gotSmsOnSent) { verifySmsExists(sentSms); }
-    } else {
-      log("smsrequest returned false for manager.send");
-      ok(false, "SMS send failed");
-      cleanUp();
-    }
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.send request returned unexpected error: " +
-              event.target.error.name);
-    cleanUp();
-  };
-}
-
-function verifySmsExists(sentSms) {
-  log("Getting SMS (id: " + sentSms.id + ").");
-  let requestRet = manager.getMessage(sentSms.id);
-  ok(requestRet, "smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    ok(event.target.result, "smsrequest event.target.result");
-    let foundSms = event.target.result;
-    is(foundSms.id, sentSms.id, "found SMS id matches");
-    is(foundSms.threadId, sentSms.threadId, "found SMS thread id matches");
-    is(foundSms.body.length, sentSms.body.length, "found SMS text length");
-    is(foundSms.body, sentSms.body, "found SMS msg text matches");
-    log("Got SMS (id: " + foundSms.id + ") as expected.");
-    deleteSms(sentSms);
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    is(event.target.error.name, "NotFoundError", "error returned");
-    log("Could not get SMS (id: " + sentSms.id + ") but should have.");
-    ok(false, "SMS was not found");
-    cleanUp();
-  };
-}
-
-function deleteSms(smsMsgObj) {
-  log("Deleting SMS (id: " + smsMsgObj.id + ") using smsmsg obj parameter.");
-  let requestRet = manager.delete(smsMsgObj);
-  ok(requestRet,"smsrequest obj returned");
-
-  requestRet.onsuccess = function(event) {
-    log("Received 'onsuccess' smsrequest event.");
-    if (event.target.result) {
-      cleanUp();
-    } else {
-      log("smsrequest returned false for manager.delete");
-      ok(false, "SMS delete failed");
-      cleanUp();
-    }
-  };
-
-  requestRet.onerror = function(event) {
-    log("Received 'onerror' smsrequest event.");
-    ok(event.target.error, "domerror obj");
-    ok(false, "manager.delete request returned unexpected error: " +
-              event.target.error.name);
-    cleanUp();
-  };
-}
-
-function cleanUp() {
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-}
-
-// Start the test
-verifyInitialState();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_outgoing_unstable_voice_connection.js
+++ /dev/null
@@ -1,184 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const RECEIVER = "15555215555";
-
-// The Book of Mozilla, 15:1
-const MESSAGES = [
-  "The twins of Mammon quarrelled.",
-  "Their warring plunged the world into a new darkness, and the beast abhorred the darkness.",
-  "So it began to move swiftly, and grew more powerful, and went forth and multiplied.",
-  "And the beasts brought fire and light to the darkness."
-];
-
-/**
- * Send messages and verify that corresponding "sending" events are received.
- *
- * @return an array of message IDs.
- */
-function sendMessagesAndVerifySending() {
-  return new Promise(function(resolve, reject) {
-    try {
-      let eventCount = 0;
-      let now = Date.now();
-      let messageIds = [];
-      manager.addEventListener("sending", function onevent(aEvent) {
-        log("onsending event received.");
-
-        let message = aEvent.message;
-        let expectedBody = MESSAGES[eventCount++];
-        messageIds.push(message.id);
-        is(message.delivery, "sending", "message.delivery");
-        is(message.deliveryStatus, "pending", "message.deliveryStatus");
-        is(message.body, expectedBody, "message.body: expected '" + expectedBody
-          + "'' but got '" + message.body + "'");
-
-        // timestamp is in seconds.
-        ok(Math.floor(message.timestamp / 1000) >= Math.floor(now / 1000),
-           "expected " + message.timestamp + " >= " + now);
-
-        // resolve when all messages are appeared "sending"
-        if (eventCount == MESSAGES.length) {
-          manager.removeEventListener("sending", onevent);
-          resolve(messageIds);
-        }
-      });
-
-      // send messages
-      for (let body of MESSAGES) {
-        manager.send(RECEIVER, body);
-      }
-    } catch (err) {
-      log("Error: " + err);
-      reject(err);
-    }
-  });
-}
-
-/**
- * Turn on voice connection, delete specified messages, and verify all the
- * corresponding "sent" / "failed" events are received.
- *
- * @param aMessageIdsToDelete
- *        An array of message ids to delete.
- * @param aExpectedSentMessages
- *        Expected successfully sent messages, ordered.
- * @param aExpectedFailures
- *        Expected number of failures.
- */
-function turnOnVoiceDeleteMessagesAndVerify(aMessageIdsToDelete,
-  aExpectedSentMessages, aExpectedFailures) {
-  let promises = [];
-
-  // Wait for "sent" and "failed" events.
-  promises.push(new Promise(function(resolve, reject) {
-    try {
-      let sentEventCount = 0;
-      let failedEventCount = 0;
-
-      let onSentHandler = function(aEvent) {
-        log("onsent event received.");
-
-        let message = aEvent.message;
-        let expectedBody = aExpectedSentMessages[sentEventCount++];
-        is(message.delivery, "sent", "message.delivery");
-        is(message.receiver, RECEIVER, "message.receiver");
-        is(message.body, expectedBody, "message.body: expected '" + expectedBody
-          + "'' but got '" + message.body + "'");
-
-        tryResolve();
-      }
-
-      let onFailedHandler = function(aEvent) {
-        log("onfailed event received.");
-        failedEventCount++;
-        tryResolve();
-      }
-
-      let tryResolve = function() {
-        log("sentEventCount=" + sentEventCount + "; failedEventCount=" + failedEventCount);
-        if (sentEventCount === aExpectedSentMessages.length &&
-          failedEventCount === aExpectedFailures) {
-          manager.removeEventListener("sent", onSentHandler);
-          manager.removeEventListener("failed", onFailedHandler);
-          resolve();
-        }
-      }
-
-      manager.addEventListener("sent", onSentHandler);
-      manager.addEventListener("failed", onFailedHandler);
-    } catch (err) {
-      log("Error: " + err);
-      reject(err);
-    }
-  }));
-
-  // Delete messages with given ids.
-  promises.push(deleteMessagesById(aMessageIdsToDelete));
-
-  // wait for 3 seconds and turn on voice connection.
-  promises.push(new Promise(function(resolve, reject) {
-      setTimeout(() => resolve(), 3000);
-    }).then(() => setEmulatorVoiceStateAndWait("on")));
-
-  return Promise.all(promises);
-}
-
-/**
- * Send messages on the second SIM and verify success while voice connection
- * on first SIM is disabled.
- *
- * @return an array of message IDs.
- */
-function sendMessagesOnSecondSIM() {
-  return new Promise(function(resolve, reject) {
-    try {
-      let eventCount = 0;
-      let now = Date.now();
-      let messageIds = [];
-      manager.addEventListener("sent", function onevent(aEvent) {
-        log("onsent event received.");
-
-        let message = aEvent.message;
-        let expectedBody = MESSAGES[eventCount++];
-        messageIds.push(message.id);
-        is(message.delivery, "sent", "message.delivery");
-        is(message.receiver, RECEIVER, "message.receiver");
-        is(message.body, expectedBody, "message.body: expected '" + expectedBody
-          + "'' but got '" + message.body + "'");
-
-        // timestamp is in seconds.
-        ok(Math.floor(message.timestamp / 1000) >= Math.floor(now / 1000),
-           "expected " + message.timestamp + " >= " + now);
-
-        // resolve when all messages are appeared "sent"
-        if (eventCount == MESSAGES.length) {
-          manager.removeEventListener("sent", onevent);
-          resolve(messageIds);
-        }
-      });
-
-      // send messages
-      for (let body of MESSAGES) {
-        manager.send(RECEIVER, body, { serviceId: 1 });
-      }
-    } catch (err) {
-      log("Error: " + err);
-      reject(err);
-    }
-  });
-}
-
-startTestCommon(function testCaseMain() {
-  return pushPrefEnv({ set: [['dom.sms.requestStatusReport', true]] })
-    .then(() => ensureMobileConnection())
-    .then(() => setEmulatorVoiceStateAndWait("unregistered"))
-    .then(() => runIfMultiSIM(() => sendMessagesOnSecondSIM()))
-    .then(() => sendMessagesAndVerifySending())
-    // Delete the first message and wait for result.
-    .then((aMessageIds) => turnOnVoiceDeleteMessagesAndVerify([aMessageIds[0]],
-      MESSAGES.slice().splice(1, MESSAGES.length - 1), 1));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_phone_number_normalization.js
+++ /dev/null
@@ -1,136 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-SpecialPowers.addPermission("sms", true, document);
-
-var pendingEmulatorCmdCount = 0;
-function sendSmsToEmulator(from, text) {
-  ++pendingEmulatorCmdCount;
-
-  let cmd = "sms send " + from + " " + text;
-  runEmulatorCmd(cmd, function(result) {
-    --pendingEmulatorCmdCount;
-
-    is(result[0], "OK", "Emulator response");
-  });
-}
-
-var tasks = {
-  // List of test fuctions. Each of them should call |tasks.next()| when
-  // completed or |tasks.finish()| to jump to the last one.
-  _tasks: [],
-  _nextTaskIndex: 0,
-
-  push: function(func) {
-    this._tasks.push(func);
-  },
-
-  next: function() {
-    let index = this._nextTaskIndex++;
-    let task = this._tasks[index];
-    try {
-      task();
-    } catch (ex) {
-      ok(false, "test task[" + index + "] throws: " + ex);
-      // Run last task as clean up if possible.
-      if (index != this._tasks.length - 1) {
-        this.finish();
-      }
-    }
-  },
-
-  finish: function() {
-    this._tasks[this._tasks.length - 1]();
-  },
-
-  run: function() {
-    this.next();
-  }
-};
-
-function getAllMessages(callback, filter, reverse) {
-  let messages = [];
-  let request = manager.getMessages(filter, reverse || false);
-  request.onsuccess = function(event) {
-    if (request.result) {
-      messages.push(request.result);
-      request.continue();
-      return;
-    }
-
-    window.setTimeout(callback.bind(null, messages), 0);
-  }
-}
-
-function deleteAllMessages() {
-  getAllMessages(function deleteAll(messages) {
-    let message = messages.shift();
-    if (!message) {
-      ok(true, "all messages deleted");
-      tasks.next();
-      return;
-    }
-
-    let request = manager.delete(message.id);
-    request.onsuccess = deleteAll.bind(null, messages);
-    request.onerror = function(event) {
-      ok(false, "failed to delete all messages");
-      tasks.finish();
-    }
-  });
-}
-
-function validate(number, normalizedNumber) {
-  log("Checking ('" + number + "', '" + normalizedNumber + "')");
-
-  let sendRequest = manager.send(number, "ping");
-  sendRequest.onsuccess = function onSendSuccess(event) {
-    let sentMessage = event.target.result;
-
-    manager.onreceived = function onreceived(event) {
-      let receivedMessage = event.message;
-      is(sentMessage.threadId, receivedMessage.threadId,
-         "message threadIds are supposed to be matched");
-
-      tasks.next();
-    };
-    sendSmsToEmulator(normalizedNumber, "pong");
-  };
-  sendRequest.onerror = function onSendError(event) {
-    ok(false, "failed to send message.");
-    tasks.finish();
-  };
-}
-
-var manager = window.navigator.mozMobileMessage;
-tasks.push(function() {
-  log("Verifying initial state.");
-  ok(manager instanceof MozMobileMessageManager,
-     "manager is instance of " + manager.constructor);
-  tasks.next();
-});
-
-tasks.push(deleteAllMessages);
-
-tasks.push(validate.bind(null, "+886-9-87-654-321", "+886987654321"));
-tasks.push(validate.bind(null, "+886 9 87654321", "+886987654321"));
-tasks.push(validate.bind(null, "+886(9)87654321", "+886987654321"));
-
-tasks.push(deleteAllMessages);
-
-// WARNING: All tasks should be pushed before this!!!
-tasks.push(function cleanUp() {
-  if (pendingEmulatorCmdCount) {
-    window.setTimeout(cleanUp, 100);
-    return;
-  }
-
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-});
-
-tasks.run();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_replace_short_message_type.js
+++ /dev/null
@@ -1,88 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 240000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const PDU_SMSC_NONE = "00"; // no SMSC Address
-
-const PDU_FIRST_OCTET = "00"; // RP:no, UDHI:no, SRI:no, MMS:no, MTI:SMS-DELIVER
-
-const PDU_SENDER_0 = "0A912143658709"; // +1234567890
-const PDU_SENDER_1 = "0A912143658719"; // +1234567891
-const SENDER_0 = "+1234567890";
-const SENDER_1 = "+1234567891";
-
-const PDU_PID_NORMAL = "00";
-const PDU_PIDS = ["00", "41", "42", "43", "44", "45", "46", "47", "5F"];
-
-const PDU_DCS_NORMAL = "00";
-
-const PDU_TIMESTAMP = "00101000000000"; // 2000/01/01
-
-const PDU_UDL = "01";
-const PDU_UD_A = "41"; // "A"
-const PDU_UD_B = "42"; // "B"
-const BODY_A = "A";
-const BODY_B = "B";
-
-function buildPdu(aSender, aPid, aBody) {
-  return PDU_SMSC_NONE + PDU_FIRST_OCTET + aSender + aPid + PDU_DCS_NORMAL +
-         PDU_TIMESTAMP + PDU_UDL + aBody;
-}
-
-function verifyReplacing(aVictim, aSender, aPid, aCompare) {
-  let readableSender = aSender === PDU_SENDER_0 ? SENDER_0 : SENDER_1;
-  log("  Checking ('" + readableSender + "', '" + aPid + "', '" + BODY_B + "')");
-
-  let pdu = buildPdu(aSender, aPid, PDU_UD_B);
-  ok(true, "Sending " + pdu);
-
-  return sendMultipleRawSmsToEmulatorAndWait([pdu])
-    .then(function(results) {
-      let receivedMsg = results[0].message;
-      is(receivedMsg.sender, readableSender, "SmsMessage sender");
-      is(receivedMsg.body, BODY_B, "SmsMessage body");
-
-      aCompare(receivedMsg.id, aVictim.id, "SmsMessage id");
-    });
-}
-
-function verifyNotReplaced(aVictim, aSender, aPid) {
-  return verifyReplacing(aVictim, aSender, aPid, isnot);
-}
-
-function verifyReplaced(aVictim, aSender, aPid) {
-  return verifyReplacing(aVictim, aSender, aPid, is);
-}
-
-function testPid(aPid) {
-  log("Test message PID '" + aPid + "'");
-
-  return sendMultipleRawSmsToEmulatorAndWait([buildPdu(PDU_SENDER_0, aPid, PDU_UD_A)])
-    .then(function(results) {
-      let receivedMsg = results[0].message;
-      let promise = Promise.resolve();
-
-      for (let pid of PDU_PIDS) {
-        let verify = (aPid !== PDU_PID_NORMAL && pid === aPid)
-                   ? verifyReplaced : verifyNotReplaced;
-        promise =
-          promise.then(verify.bind(null, receivedMsg, PDU_SENDER_0, pid))
-                 .then(verifyNotReplaced.bind(null, receivedMsg,
-                                              PDU_SENDER_1, pid));
-      }
-
-      return promise;
-    });
-}
-
-startTestCommon(function testCaseMain() {
-  let promise = Promise.resolve();
-  for (let pid of PDU_PIDS) {
-    promise = promise.then(testPid.bind(null, pid))
-                     .then(deleteAllMessages);
-  }
-
-  return promise;
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_segment_info.js
+++ /dev/null
@@ -1,124 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const LEN_7BIT = 160;
-const LEN_7BIT_WITH_8BIT_REF = 153;
-const LEN_7BIT_WITH_16BIT_REF = 152;
-const LEN_UCS2 = 70;
-const LEN_UCS2_WITH_8BIT_REF = 67;
-const LEN_UCS2_WITH_16BIT_REF = 66;
-
-function times(str, n) {
-  return (new Array(n + 1)).join(str);
-}
-
-function test(text, segments, charsPerSegment, charsAvailableInLastSegment) {
-  // 'text' may contain non-ascii characters, so we're not going to print it on
-  // Marionette console to avoid breaking it.
-  ok(true, "Testing '" + text + "' ...");
-
-  let domRequest = manager.getSegmentInfoForText(text);
-  ok(domRequest, "DOMRequest object returned.");
-
-  return domRequest.then(function(aResult) {
-    ok(aResult, "result = " + JSON.stringify(aResult));
-
-    is(aResult.segments, segments, "result.segments");
-    is(aResult.charsPerSegment, charsPerSegment, "result.charsPerSegment");
-    is(aResult.charsAvailableInLastSegment, charsAvailableInLastSegment,
-       "result.charsAvailableInLastSegment");
-  });
-}
-
-startTestCommon(function() {
-  // Ensure we always begin with strict 7bit encoding set to false.
-  return pushPrefEnv({ set: [["dom.sms.strict7BitEncoding", false]] })
-
-    // GSM 7Bit Alphabets:
-    //
-    // 'a' is in GSM default locking shift table, so it takes 1 septet.
-    .then(() => test("a",       1, LEN_7BIT, LEN_7BIT - 1))
-    // '\u20ac' is in GSM default single shift table, so it takes 2 septets.
-    .then(() => test("\u20ac",  1, LEN_7BIT, LEN_7BIT - 2))
-    // SP is defined in both locking shift and single shift tables.
-    .then(() => test(" ",       1, LEN_7BIT, LEN_7BIT - 1))
-    // Some combinations.
-    .then(() => test("a\u20ac", 1, LEN_7BIT, LEN_7BIT - 3))
-    .then(() => test("a ",      1, LEN_7BIT, LEN_7BIT - 2))
-    .then(() => test("\u20aca", 1, LEN_7BIT, LEN_7BIT - 3))
-    .then(() => test("\u20ac ", 1, LEN_7BIT, LEN_7BIT - 3))
-    .then(() => test(" \u20ac", 1, LEN_7BIT, LEN_7BIT - 3))
-    .then(() => test(" a",      1, LEN_7BIT, LEN_7BIT - 2))
-
-    // GSM 7Bit Alphabets (multipart):
-    //
-    // Exactly 160 locking shift table chararacters.
-    .then(() => test(times("a", LEN_7BIT), 1, LEN_7BIT, 0))
-    // 161 locking shift table chararacters. We'll have |161 - 153 = 8| septets in
-    // the 2nd segment.
-    .then(() => test(times("a", LEN_7BIT + 1),
-                     2, LEN_7BIT_WITH_8BIT_REF, LEN_7BIT_WITH_8BIT_REF - 8))
-    // |LEN_7BIT_WITH_8BIT_REF * 2| locking shift table chararacters.
-    .then(() => test(times("a", LEN_7BIT_WITH_8BIT_REF * 2),
-                     2, LEN_7BIT_WITH_8BIT_REF, 0))
-    // |LEN_7BIT_WITH_8BIT_REF * 2 + 1| locking shift table chararacters.
-    .then(() => test(times("a", LEN_7BIT_WITH_8BIT_REF * 2 + 1),
-                     3, LEN_7BIT_WITH_8BIT_REF, LEN_7BIT_WITH_8BIT_REF - 1))
-    // Exactly 80 single shift table chararacters.
-    .then(() => test(times("\u20ac", LEN_7BIT / 2), 1, LEN_7BIT, 0))
-    // 81 single shift table chararacters. Because |Math.floor(153 / 2) = 76|, it
-    // should left 5 septets in the 2nd segment.
-    .then(() => test(times("\u20ac", LEN_7BIT / 2 + 1),
-                     2, LEN_7BIT_WITH_8BIT_REF, LEN_7BIT_WITH_8BIT_REF - 10))
-    // |1 + 2 * 76| single shift table chararacters. We have only |153 - 76 * 2 = 1|
-    // space left, but each single shift table character takes 2, so it will be
-    // filled in the 3rd segment.
-    .then(() => test(times("\u20ac", 1 + 2 * Math.floor(LEN_7BIT_WITH_8BIT_REF / 2)),
-                     3, LEN_7BIT_WITH_8BIT_REF, LEN_7BIT_WITH_8BIT_REF - 2))
-    // |2 * 76| single shift table chararacters + 1 locking shift table chararacter.
-    .then(() => test("a" + times("\u20ac", 2 * Math.floor(LEN_7BIT_WITH_8BIT_REF / 2)),
-                     2, LEN_7BIT_WITH_8BIT_REF, 1))
-    .then(() => test(times("\u20ac", 2 * Math.floor(LEN_7BIT_WITH_8BIT_REF / 2)) + "a",
-                     2, LEN_7BIT_WITH_8BIT_REF, 0))
-
-    // UCS2:
-    //
-    // '\u6afb' should be encoded as UCS2.
-    .then(() => test("\u6afb",       1, LEN_UCS2, LEN_UCS2 - 1))
-    // Combination of GSM 7bit alphabets.
-    .then(() => test("\u6afba",      1, LEN_UCS2, LEN_UCS2 - 2))
-    .then(() => test("\u6afb\u20ac", 1, LEN_UCS2, LEN_UCS2 - 2))
-    .then(() => test("\u6afb ",      1, LEN_UCS2, LEN_UCS2 - 2))
-
-    // UCS2 (multipart):
-    //
-    // Exactly 70 UCS2 chararacters.
-    .then(() => test(times("\u6afb", LEN_UCS2), 1, LEN_UCS2, 0))
-    // 71 UCS2 chararacters. We'll have |71 - 67 = 4| chararacters in the 2nd
-    // segment.
-    .then(() => test(times("\u6afb", LEN_UCS2 + 1),
-                     2, LEN_UCS2_WITH_8BIT_REF, LEN_UCS2_WITH_8BIT_REF - 4))
-    // |LEN_UCS2_WITH_8BIT_REF * 2| ucs2 chararacters.
-    .then(() => test(times("\u6afb", LEN_UCS2_WITH_8BIT_REF * 2),
-                     2, LEN_UCS2_WITH_8BIT_REF, 0))
-    // |LEN_7BIT_WITH_8BIT_REF * 2 + 1| ucs2 chararacters.
-    .then(() => test(times("\u6afb", LEN_UCS2_WITH_8BIT_REF * 2 + 1),
-                     3, LEN_UCS2_WITH_8BIT_REF, LEN_UCS2_WITH_8BIT_REF - 1))
-
-    // Strict 7-Bit Encoding:
-    //
-    .then(() => pushPrefEnv({ set: [["dom.sms.strict7BitEncoding", true]] }))
-
-    // Should have no effect on GSM default alphabet characters.
-    .then(() => test("\u0041",       1, LEN_7BIT, LEN_7BIT - 1))
-    // "\u00c0"(À) should be mapped to "\u0041"(A).
-    .then(() => test("\u00c0",       1, LEN_7BIT, LEN_7BIT - 1))
-    // Mixing mapped characters with unmapped ones.
-    .then(() => test("\u00c0\u0041", 1, LEN_7BIT, LEN_7BIT - 2))
-    .then(() => test("\u0041\u00c0", 1, LEN_7BIT, LEN_7BIT - 2))
-    // UCS2 characters should be mapped to '*'.
-    .then(() => test("\u1234",       1, LEN_7BIT, LEN_7BIT - 1));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_smsc_address.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const SMSC_ATT = '+13123149810';
-const SMSC_ATT_TYPO = '+++1312@@@314$$$9,8,1,0';
-const SMSC_ATT_TEXT = '"+13123149810",145';
-const SMSC_O2 = '+447802000332';
-const SMSC_O2_TEXT = '"+447802000332",145';
-const SMSC_DEF = '+123456789';
-const SMSC_DEF_TEXT = '"+123456789",145';
-const SMSC_TON_UNKNOWN = '0407485455'
-const SMSC_TON_UNKNOWN_TEXT = '"0407485455",129';
-
-function verifySmscAddress(smsc, expectedAddr, expectedTon, expectedNpi) {
-  is(smsc.address, expectedAddr);
-  is(smsc.typeOfAddress.typeOfNumber, expectedTon);
-  is(smsc.typeOfAddress.numberPlanIdentification, expectedNpi);
-}
-
-startTestCommon(function testCaseMain() {
-  return Promise.resolve()
-
-    // Bug 1224990, initialization of SMSC in emulator NV item is unstable.
-    // Verify Getter after Setter to prevent intermittent failure.
-
-    // Verify setting AT&T SMSC address.
-    .then(() => manager.setSmscAddress({ address:SMSC_ATT }))
-    .then(() => manager.getSmscAddress())
-    .then((result) =>
-      verifySmscAddress(result, SMSC_ATT, "international", "isdn"))
-
-    // Verify setting O2 SMSC address.
-    .then(() => manager.setSmscAddress({ address:SMSC_O2 }))
-    .then(() => manager.getSmscAddress())
-    .then((result) =>
-      verifySmscAddress(result, SMSC_O2, "international", "isdn"))
-
-    // Verify setting AT&T SMSC address with extra illegal characters.
-    .then(() => manager.setSmscAddress({ address:SMSC_ATT_TYPO }))
-    .then(() => manager.getSmscAddress())
-    .then((result) =>
-      verifySmscAddress(result, SMSC_ATT, "international", "isdn"))
-
-    // Verify setting a SMSC address with TON=unknown.
-    .then(() => manager.setSmscAddress({ address:SMSC_TON_UNKNOWN }))
-    .then(() => manager.getSmscAddress())
-    .then((result) =>
-      verifySmscAddress(result, SMSC_TON_UNKNOWN, "unknown", "isdn"))
-
-    // Verify setting invalid SMSC address.
-    .then(() => manager.setSmscAddress({}))
-    .then(() => Promise.reject("Expect for an error."),
-      (err) => log("Got expected error: " + err))
-    .then(() => manager.setSmscAddress({ address:"" }))
-    .then(() => Promise.reject("Expect for an error."),
-      (err) => log("Got expected error: " + err))
-    .then(() => manager.setSmscAddress({ address:"???" }))
-    .then(() => Promise.reject("Expect for an error."),
-      (err) => log("Got expected error: " + err))
-
-    // Restore to default emulator SMSC address.
-    .then(() => manager.setSmscAddress({ address:SMSC_DEF }))
-    .then(() => manager.getSmscAddress())
-    .then((result) =>
-      verifySmscAddress(result, SMSC_DEF, "international", "isdn"));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_strict_7bit_encoding.js
+++ /dev/null
@@ -1,275 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-// Copied from ril_consts.js. Some entries are commented out in ril_const.js,
-// but we still want to test them here.
-const GSM_SMS_STRICT_7BIT_CHARMAP = {
-  "\u0024": "\u0024", // "$" => "$", already in default alphabet
-  "\u00a5": "\u00a5", // "¥" => "¥", already in default alphabet
-  "\u00c0": "\u0041", // "À" => "A"
-  "\u00c1": "\u0041", // "Á" => "A"
-  "\u00c2": "\u0041", // "Â" => "A"
-  "\u00c3": "\u0041", // "Ã" => "A"
-  "\u00c4": "\u00c4", // "Ä" => "Ä", already in default alphabet
-  "\u00c5": "\u00c5", // "Å" => "Å", already in default alphabet
-  "\u00c6": "\u00c6", // "Æ" => "Æ", already in default alphabet
-  "\u00c7": "\u00c7", // "Ç" => "Ç", already in default alphabet
-  "\u00c8": "\u0045", // "È" => "E"
-  "\u00c9": "\u00c9", // "É" => "É", already in default alphabet
-  "\u00ca": "\u0045", // "Ê" => "E"
-  "\u00cb": "\u0045", // "Ë" => "E"
-  "\u00cc": "\u0049", // "Ì" => "I"
-  "\u00cd": "\u0049", // "Í" => "I"
-  "\u00ce": "\u0049", // "Î" => "I"
-  "\u00cf": "\u0049", // "Ï" => "I"
-  "\u00d1": "\u00d1", // "Ñ" => "Ñ", already in default alphabet
-  "\u00d2": "\u004f", // "Ò" => "O"
-  "\u00d3": "\u004f", // "Ó" => "O"
-  "\u00d4": "\u004f", // "Ô" => "O"
-  "\u00d5": "\u004f", // "Õ" => "O"
-  "\u00d6": "\u00d6", // "Ö" => "Ö", already in default alphabet
-  "\u00d9": "\u0055", // "Ù" => "U"
-  "\u00da": "\u0055", // "Ú" => "U"
-  "\u00db": "\u0055", // "Û" => "U"
-  "\u00dc": "\u00dc", // "Ü" => "Ü", already in default alphabet
-  "\u00df": "\u00df", // "ß" => "ß", already in default alphabet
-  "\u00e0": "\u00e0", // "à" => "à", already in default alphabet
-  "\u00e1": "\u0061", // "á" => "a"
-  "\u00e2": "\u0061", // "â" => "a"
-  "\u00e3": "\u0061", // "ã" => "a"
-  "\u00e4": "\u00e4", // "ä" => "ä", already in default alphabet
-  "\u00e5": "\u00e5", // "å" => "å", already in default alphabet
-  "\u00e6": "\u00e6", // "æ" => "æ", already in default alphabet
-  "\u00e7": "\u00c7", // "ç" => "Ç"
-  "\u00e8": "\u00e8", // "è" => "è", already in default alphabet
-  "\u00e9": "\u00e9", // "é" => "é", already in default alphabet
-  "\u00ea": "\u0065", // "ê" => "e"
-  "\u00eb": "\u0065", // "ë" => "e"
-  "\u00ec": "\u00ec", // "ì" => "ì", already in default alphabet
-  "\u00ed": "\u0069", // "í" => "i"
-  "\u00ee": "\u0069", // "î" => "i"
-  "\u00ef": "\u0069", // "ï" => "i"
-  "\u00f1": "\u00f1", // "ñ" => "ñ", already in default alphabet
-  "\u00f2": "\u00f2", // "ò" => "ò", already in default alphabet
-  "\u00f3": "\u006f", // "ó" => "o"
-  "\u00f4": "\u006f", // "ô" => "o"
-  "\u00f5": "\u006f", // "õ" => "o"
-  "\u00f6": "\u00f6", // "ö" => "ö", already in default alphabet
-  "\u00f8": "\u00f8", // "ø" => "ø", already in default alphabet
-  "\u00f9": "\u00f9", // "ù" => "ù", already in default alphabet
-  "\u00fa": "\u0075", // "ú" => "u"
-  "\u00fb": "\u0075", // "û" => "u"
-  "\u00fc": "\u00fc", // "ü" => "ü", already in default alphabet
-  "\u00fe": "\u0074", // "þ" => "t"
-  "\u0100": "\u0041", // "Ā" => "A"
-  "\u0101": "\u0061", // "ā" => "a"
-  "\u0106": "\u0043", // "Ć" => "C"
-  "\u0107": "\u0063", // "ć" => "c"
-  "\u010c": "\u0043", // "Č" => "C"
-  "\u010d": "\u0063", // "č" => "c"
-  "\u010f": "\u0064", // "ď" => "d"
-  "\u0110": "\u0044", // "Đ" => "D"
-  "\u0111": "\u0064", // "đ" => "d"
-  "\u0112": "\u0045", // "Ē" => "E"
-  "\u0113": "\u0065", // "ē" => "e"
-  "\u0118": "\u0045", // "Ę" => "E"
-  "\u0119": "\u0065", // "ę" => "e"
-  "\u0128": "\u0049", // "Ĩ" => "I"
-  "\u0129": "\u0069", // "ĩ" => "i"
-  "\u012a": "\u0049", // "Ī" => "I"
-  "\u012b": "\u0069", // "ī" => "i"
-  "\u012e": "\u0049", // "Į" => "I"
-  "\u012f": "\u0069", // "į" => "i"
-  "\u0141": "\u004c", // "Ł" => "L"
-  "\u0142": "\u006c", // "ł" => "l"
-  "\u0143": "\u004e", // "Ń" => "N"
-  "\u0144": "\u006e", // "ń" => "n"
-  "\u0147": "\u004e", // "Ň" => "N"
-  "\u0148": "\u006e", // "ň" => "n"
-  "\u014c": "\u004f", // "Ō" => "O"
-  "\u014d": "\u006f", // "ō" => "o"
-  "\u0152": "\u004f", // "Œ" => "O"
-  "\u0153": "\u006f", // "œ" => "o"
-  "\u0158": "\u0052", // "Ř" => "R"
-  "\u0159": "\u0072", // "ř" => "r"
-  "\u0160": "\u0053", // "Š" => "S"
-  "\u0161": "\u0073", // "š" => "s"
-  "\u0165": "\u0074", // "ť" => "t"
-  "\u0168": "\u0055", // "Ū" => "U"
-  "\u0169": "\u0075", // "ū" => "u"
-  "\u016a": "\u0055", // "Ū" => "U"
-  "\u016b": "\u0075", // "ū" => "u"
-  "\u0178": "\u0059", // "Ÿ" => "Y"
-  "\u0179": "\u005a", // "Ź" => "Z"
-  "\u017a": "\u007a", // "ź" => "z"
-  "\u017b": "\u005a", // "Ż" => "Z"
-  "\u017c": "\u007a", // "ż" => "z"
-  "\u017d": "\u005a", // "Ž" => "Z"
-  "\u017e": "\u007a", // "ž" => "z"
-  "\u025b": "\u0045", // "ɛ" => "E"
-  "\u0398": "\u0398", // "Θ" => "Θ", already in default alphabet
-  "\u1e7c": "\u0056", // "Ṽ" => "V"
-  "\u1e7d": "\u0076", // "ṽ" => "v"
-  "\u1ebc": "\u0045", // "Ẽ" => "E"
-  "\u1ebd": "\u0065", // "ẽ" => "e"
-  "\u1ef8": "\u0059", // "Ỹ" => "Y"
-  "\u1ef9": "\u0079", // "ỹ" => "y"
-  "\u20a4": "\u00a3", // "₤" => "£"
-  "\u20ac": "\u20ac", // "€" => "€", already in default alphabet
-};
-
-// Emulator will loop back the outgoing SMS if the phone number equals to its
-// control port, which is 5554 for the first emulator instance.
-const SELF = "5554";
-
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-SpecialPowers.addPermission("sms", true, document);
-
-var manager = window.navigator.mozMobileMessage;
-ok(manager instanceof MozMobileMessageManager,
-   "manager is instance of " + manager.constructor);
-
-var tasks = {
-  // List of test fuctions. Each of them should call |tasks.next()| when
-  // completed or |tasks.finish()| to jump to the last one.
-  _tasks: [],
-  _nextTaskIndex: 0,
-
-  push: function(func) {
-    this._tasks.push(func);
-  },
-
-  next: function() {
-    let index = this._nextTaskIndex++;
-    let task = this._tasks[index];
-    try {
-      task();
-    } catch (ex) {
-      ok(false, "test task[" + index + "] throws: " + ex);
-      // Run last task as clean up if possible.
-      if (index != this._tasks.length - 1) {
-        this.finish();
-      }
-    }
-  },
-
-  finish: function() {
-    this._tasks[this._tasks.length - 1]();
-  },
-
-  run: function() {
-    this.next();
-  }
-};
-
-function testStrict7BitEncodingHelper(sent, received) {
-  // The log message contains unicode and Marionette seems unable to process
-  // it and throws: |UnicodeEncodeError: 'ascii' codec can't encode character
-  // u'\xa5' in position 14: ordinal not in range(128)|.
-  //
-  //log("Testing '" + sent + "' => '" + received + "'");
-
-  let count = 0;
-  function done(step) {
-    count += step;
-    if (count >= 2) {
-      window.setTimeout(tasks.next.bind(tasks), 0);
-    }
-  }
-
-  manager.addEventListener("received", function onReceived(event) {
-    event.target.removeEventListener("received", onReceived);
-
-    let message = event.message;
-    is(message.body, received, "received message.body");
-
-    done(1);
-  });
-
-  let request = manager.send(SELF, sent);
-  request.addEventListener("success", function onRequestSuccess(event) {
-    let message = event.target.result;
-    is(message.body, sent, "sent message.body");
-
-    done(1);
-  });
-  request.addEventListener("error", function onRequestError(event) {
-    ok(false, "Can't send message out!!!");
-    done(2);
-  });
-}
-
-// Bug 877141 - If you send several spaces together in a sms, the other
-//              dipositive receives a "*" for each space.
-//
-// This function is called twice, with strict 7bit encoding enabled or
-// disabled.  Expect the same result in both sent and received text and with
-// either strict 7bit encoding enabled or disabled.
-function testBug877141() {
-  log("Testing bug 877141");
-  let sent = "1 2     3";
-  testStrict7BitEncodingHelper(sent, sent);
-}
-
-tasks.push(function() {
-  log("Testing with dom.sms.strict7BitEncoding enabled");
-  SpecialPowers.setBoolPref("dom.sms.strict7BitEncoding", true);
-  tasks.next();
-});
-
-
-// Test for combined string.
-tasks.push(function() {
-  let sent = "", received = "";
-  for (let c in GSM_SMS_STRICT_7BIT_CHARMAP) {
-    sent += c;
-    received += GSM_SMS_STRICT_7BIT_CHARMAP[c];
-  }
-  testStrict7BitEncodingHelper(sent, received);
-});
-
-// When strict7BitEncoding is enabled, we should replace characters that
-// can't be encoded with GSM 7-Bit alphabets with '*'.
-tasks.push(function() {
-  // "Happy New Year" in Chinese.
-  let sent = "\u65b0\u5e74\u5feb\u6a02", received = "****";
-  testStrict7BitEncodingHelper(sent, received);
-});
-
-tasks.push(testBug877141);
-
-tasks.push(function() {
-  log("Testing with dom.sms.strict7BitEncoding disabled");
-  SpecialPowers.setBoolPref("dom.sms.strict7BitEncoding", false);
-  tasks.next();
-});
-
-// Test for combined string.
-tasks.push(function() {
-  let sent = "";
-  for (let c in GSM_SMS_STRICT_7BIT_CHARMAP) {
-    sent += c;
-  }
-  testStrict7BitEncodingHelper(sent, sent);
-});
-
-tasks.push(function() {
-  // "Happy New Year" in Chinese.
-  let sent = "\u65b0\u5e74\u5feb\u6a02";
-  testStrict7BitEncodingHelper(sent, sent);
-});
-
-tasks.push(testBug877141);
-
-// WARNING: All tasks should be pushed before this!!!
-tasks.push(function cleanUp() {
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  SpecialPowers.clearUserPref("dom.sms.strict7BitEncoding");
-
-  finish();
-});
-
-tasks.run();
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_thread_subject.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const PHONE_NUMBER = "+1234567890";
-
-// Have a long long subject causes the send fails, so we don't need
-// networking here.
-const MMS_MAX_LENGTH_SUBJECT = 40;
-function genMmsSubject(sep) {
-  return "Hello " + (new Array(MMS_MAX_LENGTH_SUBJECT).join(sep)) + " World!";
-}
-
-function testSms(aProgressStr, aText) {
-  log("Testing thread subject: " + aProgressStr);
-
-  return sendSmsWithSuccess(PHONE_NUMBER, aText)
-    .then(function(message) {
-      log("  SMS sent, retrieving thread of id " + message.threadId);
-      return getThreadById(message.threadId);
-    })
-    .then(function(thread) {
-      log("  Got thread.lastMessageSubject = '" + thread.lastMessageSubject + "'");
-      is(thread.lastMessageSubject, "", "thread.lastMessageSubject");
-    });
-}
-
-function testMms(aProgressStr, aSubject) {
-  log("Testing thread subject: " + aProgressStr);
-
-  let mmsParameters = {
-    receivers: [PHONE_NUMBER],
-    subject: aSubject,
-    attachments: [],
-  };
-
-  // We use a long long message subject so it will always fail.
-  return sendMmsWithFailure(mmsParameters)
-    .then(function(result) {
-      log("  MMS sent, retrieving thread of id " + result.message.threadId);
-      return getThreadById(result.message.threadId);
-    })
-    .then(function(thread) {
-      log("  Got thread.lastMessageSubject = '" + thread.lastMessageSubject + "'");
-      is(thread.lastMessageSubject, aSubject, "thread.lastMessageSubject");
-    });
-}
-
-startTestCommon(function testCaseMain() {
-  return testSms("SMS", "text")
-    .then(testMms.bind(null, "SMS..MMS", genMmsSubject(" ")))
-    .then(testSms.bind(null, "SMS..MMS..SMS", "text"))
-    .then(deleteAllMessages)
-    .then(testMms.bind(null, "MMS", genMmsSubject(" ")))
-    .then(testSms.bind(null, "MMS..SMS", "text"))
-    .then(testMms.bind(null, "MMS..SMS..MMS", genMmsSubject(" ")))
-    .then(deleteAllMessages)
-    .then(testSms.bind(null, "SMS", "1"))
-    .then(testSms.bind(null, "SMS..SMS", "2"))
-    .then(testSms.bind(null, "SMS..SMS..SMS", "3"))
-    .then(deleteAllMessages)
-    .then(testMms.bind(null, "MMS", genMmsSubject("a")))
-    .then(testMms.bind(null, "MMS..MMS", genMmsSubject("b")))
-    .then(testMms.bind(null, "MMS..MMS..MMS", genMmsSubject("c")));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_update_gsm_nl_on_mcc_chanages.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const kPrefLastKnownSimMcc = "ril.lastKnownSimMcc";
-
-// "tablespoon" in Turkish. The character 'ç', 'ş' and 'ğ' exist in both Turkish
-// locking and single shift tables, but is not available in either GSM default
-// alphabet or its extension table.
-const MSG_TURKISH = "çorba kaşığı";
-
-// Random sentence taken from Turkish news with 155 characters. It's the longest
-// message which can be encoded as single 7-bit SMS segment (while using UCS-2
-// it will be splitted to 3 segments).
-const MSG_TURKISH_LONG = "Sinan Akçıl-Ebru Şallı cephesinde sular durulmuyor. \
-Çiftin ayrılığına dair yeni iddialar ortaya atıldı. İlk iddiaya göre; Sinan \
-Akçıl, Ebru Şallı'dan 1.5..";
-
-// Random sentence taken from Turkish news with 156 characters, which just
-// exceeds the max length of single 7-bit SMS segment.
-const MSG_TURKISH_MULTI_SEGS = "ABD'de Başkan Barack Obama'nın kendisini \
-Twitter'dan takip ettiğini söyleyen Kam Brock adlı kadının psikiyatri tedavisi \
-görmeye zorlandığı bildirildi. Obama";
-
-function getSegmentInfoForText(aBody) {
-  return new Promise(function(resolve, reject) {
-    let domRequest = manager.getSegmentInfoForText(aBody);
-    domRequest.onsuccess = function() {
-      let segmentInfo = domRequest.result;
-      log("getSegmentInfoForText success: " + JSON.stringify(segmentInfo));
-      resolve(segmentInfo);
-    };
-    domRequest.onerror = function(){
-      log("getSegmentInfoForText error");
-      reject();
-    }
-  });
-}
-
-function verifySegmentInfo(segmentInfo, expectedSegmentInfo, msg) {
-  is(segmentInfo.segments, expectedSegmentInfo.segments, msg);
-  is(segmentInfo.charsPerSegment, expectedSegmentInfo.charsPerSegment, msg);
-  is(segmentInfo.charsAvailableInLastSegment,
-    expectedSegmentInfo.charsAvailableInLastSegment, msg);
-};
-
-/**
- * Since charsPerSegment returned by getSegmentInfoForText should match the
- * actual segment size when sending a message (which is verified in
- * test_ril_worker_sms_sgement_info.js), here we verify the correct table tuples
- * are loaded when MCC changes by comparing the value of charsPerSegment for the
- * same text when applying different mcc values.
- */
-startTestCommon(function testCaseMain() {
-  return Promise.resolve()
-    // Change MCC to US.
-    .then(() => pushPrefEnv({set: [[kPrefLastKnownSimMcc, "310"]]}))
-
-    // US / UCS-2 / short Turkish message.
-    .then(() => getSegmentInfoForText(MSG_TURKISH))
-    .then((segmentInfo) => verifySegmentInfo(segmentInfo,
-      {segments: 1, charsPerSegment: 70,
-        charsAvailableInLastSegment: 70 - MSG_TURKISH.length},
-      "US / UCS-2 / short Turkish message."))
-
-    // US / UCS-2 / long Turkish message.
-    .then(() => getSegmentInfoForText(MSG_TURKISH_LONG))
-    .then((segmentInfo) => verifySegmentInfo(segmentInfo,
-      {segments: 3, charsPerSegment: 67,
-        charsAvailableInLastSegment: 67 - MSG_TURKISH_LONG.length % 67},
-      "US / UCS-2 / long Turkish message."))
-
-    // Change MCC to Turkey.
-    .then(() => pushPrefEnv({set: [[kPrefLastKnownSimMcc, "286"]]}))
-
-    // Turkey / GSM 7 bits / short Turkish message.
-    .then(() => getSegmentInfoForText(MSG_TURKISH))
-    .then((segmentInfo) => verifySegmentInfo(segmentInfo,
-      {segments: 1, charsPerSegment: 155,
-        charsAvailableInLastSegment: 155 - MSG_TURKISH.length},
-      "Turkey / GSM 7 bits / short Turkish message."))
-
-    // Turkey; GSM 7 bits; longest single segment Turkish message.
-    .then(() => getSegmentInfoForText(MSG_TURKISH_LONG))
-    .then((segmentInfo) => verifySegmentInfo(segmentInfo,
-      {segments: 1, charsPerSegment: 155, charsAvailableInLastSegment: 0},
-      "Turkey / GSM 7 bits / longest single segment Turkish message."))
-
-    // Turkey; GSM 7 bits; shortest dual segments Turkish message.
-    .then(() => getSegmentInfoForText(MSG_TURKISH_MULTI_SEGS))
-    .then((segmentInfo) => verifySegmentInfo(segmentInfo,
-      {segments: 2, charsPerSegment: 149,
-        charsAvailableInLastSegment: 149 - MSG_TURKISH_MULTI_SEGS.length % 149},
-      "Turkey / GSM 7 bits / shortest dual segments Turkish message."));
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/marionette/test_update_thread_record_in_delete.js
+++ /dev/null
@@ -1,230 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-
-const FROM = "09123456789";
-const PREFIX = "msg_";
-const MSGS = 3;
-
-SpecialPowers.addPermission("sms", true, document);
-SpecialPowers.setBoolPref("dom.sms.enabled", true);
-
-var manager = window.navigator.mozMobileMessage;
-ok(manager instanceof MozMobileMessageManager,
-   "manager is instance of " + manager.constructor);
-
-var pendingEmulatorCmdCount = 0;
-function sendSmsToEmulator(from, text) {
-  ++pendingEmulatorCmdCount;
-
-  let cmd = "sms send " + from + " " + text;
-  runEmulatorCmd(cmd, function(result) {
-    --pendingEmulatorCmdCount;
-
-    is(result[0], "OK", "Emulator response");
-  });
-}
-
-var tasks = {
-  // List of test fuctions. Each of them should call |tasks.next()| when
-  // completed or |tasks.finish()| to jump to the last one.
-  _tasks: [],
-  _nextTaskIndex: 0,
-
-  push: function(func) {
-    this._tasks.push(func);
-  },
-
-  next: function() {
-    let index = this._nextTaskIndex++;
-    let task = this._tasks[index];
-    try {
-      task();
-    } catch (ex) {
-      ok(false, "test task[" + index + "] throws: " + ex);
-      // Run last task as clean up if possible.
-      if (index != this._tasks.length - 1) {
-        this.finish();
-      }
-    }
-  },
-
-  finish: function() {
-    this._tasks[this._tasks.length - 1]();
-  },
-
-  run: function() {
-    this.next();
-  }
-};
-
-function getAllMessages(callback, filter, reverse) {
-  let messages = [];
-  let cursor = manager.getMessages(filter, reverse || false);
-  cursor.onsuccess = function(event) {
-    if (!this.done) {
-      messages.push(this.result);
-      this.continue();
-      return;
-    }
-
-    window.setTimeout(callback.bind(null, messages), 0);
-  }
-}
-
-function getAllThreads(callback) {
-  let threads = [];
-  let cursor = manager.getThreads();
-  cursor.onsuccess = function(event) {
-    if (!this.done) {
-      threads.push(this.result);
-      this.continue();
-      return;
-    }
-
-    window.setTimeout(callback.bind(null, threads), 0);
-  }
-}
-
-function deleteAllMessages() {
-  getAllMessages(function deleteAll(messages) {
-    let message = messages.shift();
-    if (!message) {
-      ok(true, "all messages deleted");
-      tasks.next();
-      return;
-    }
-
-    let request = manager.delete(message.id);
-    request.onsuccess = deleteAll.bind(null, messages);
-    request.onerror = function(event) {
-      ok(false, "failed to delete all messages");
-      tasks.finish();
-    }
-  });
-}
-
-function checkThread(thread, id, body, unreadCount, timestamp)
-{
-  is(thread.id, id, "Thread ID is set");
-  is(thread.body, body, "Thread subject is set to last message body");
-  is(thread.unreadCount, unreadCount, "Thread unread count");
-  is(JSON.stringify(thread.participants), JSON.stringify([FROM]), "Thread participants");
-  is(thread.timestamp, timestamp, "Thread timestamp is set");
-}
-
-tasks.push(deleteAllMessages);
-
-tasks.push(getAllThreads.bind(null, function(threads) {
-  is(threads.length, 0, "Threads are cleared");
-  tasks.next();
-}));
-
-var gotMessagesCount = 0;
-tasks.push(function() {
-  manager.onreceived = function() {
-    ++gotMessagesCount;
-  };
-  tasks.next();
-});
-
-tasks.push(function() {
-  for (let i = 1; i <= MSGS; i++) {
-    sendSmsToEmulator(FROM, PREFIX + i);
-  }
-  tasks.next();
-});
-
-var allMessages;
-tasks.push(function waitAllMessageReceived() {
-  if (gotMessagesCount != MSGS) {
-    window.setTimeout(waitAllMessageReceived, 100);
-    return;
-  }
-
-  getAllMessages(function(messages) {
-    allMessages = messages;
-    tasks.next();
-  });
-});
-
-
-var originalThread;
-tasks.push(getAllThreads.bind(null, function(threads) {
-  is(threads.length, 1, "Should have only one thread");
-
-  let lastMessage = allMessages[allMessages.length - 1];
-
-  originalThread = threads[0];
-  checkThread(originalThread,
-              originalThread.id,
-              lastMessage.body,
-              allMessages.length,
-              lastMessage.timestamp);
-
-  tasks.next();
-}));
-
-tasks.push(function DeleteFirstMessage() {
-  let request = manager.delete(allMessages[0].id);
-  request.onsuccess = function() {
-    getAllThreads(function(threads) {
-      is(threads.length, 1, "Should have only one thread");
-
-      allMessages = allMessages.slice(1);
-      let lastMessage = allMessages[allMessages.length - 1];
-
-      checkThread(threads[0],
-                  originalThread.id,
-                  lastMessage.body,
-                  allMessages.length,
-                  lastMessage.timestamp);
-
-      tasks.next();
-    });
-  };
-});
-
-tasks.push(function DeleteLastMessage() {
-  let request = manager.delete(allMessages[allMessages.length - 1].id);
-  request.onsuccess = function() {
-    getAllThreads(function(threads) {
-      is(threads.length, 1, "Should have only one thread");
-
-      allMessages = allMessages.slice(0, -1);
-      let lastMessage = allMessages[allMessages.length - 1];
-
-      checkThread(threads[0],
-                  originalThread.id,
-                  lastMessage.body,
-                  allMessages.length,
-                  lastMessage.timestamp);
-
-      tasks.next();
-    });
-  };
-});
-
-tasks.push(deleteAllMessages);
-
-tasks.push(getAllThreads.bind(null, function(threads) {
-  is(threads.length, 0, "Should have deleted all threads");
-  tasks.next();
-}));
-
-// WARNING: All tasks should be pushed before this!!!
-tasks.push(function cleanUp() {
-  if (pendingEmulatorCmdCount) {
-    window.setTimeout(cleanUp, 100);
-    return;
-  }
-
-  manager.onreceived = null;
-
-  SpecialPowers.removePermission("sms", document);
-  SpecialPowers.clearUserPref("dom.sms.enabled");
-  finish();
-});
-
-tasks.run();
deleted file mode 100644
--- a/dom/mobilemessage/tests/mochitest/chrome.ini
+++ /dev/null
@@ -1,2 +0,0 @@
-[test_sms_basics.html]
-skip-if = toolkit == 'android' #Bug 909036
deleted file mode 100644
--- a/dom/mobilemessage/tests/mochitest/test_sms_basics.html
+++ /dev/null
@@ -1,137 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
-  <title>Test for WebSMS</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
-</head>
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-<iframe></iframe>
-</div>
-<pre id="test">
-<script type="application/javascript;version=1.8">
-
-/** Test for WebSMS **/
-
-// webidl interfaces guarded by [AvailableIn=CertifiedApps].
-const WEBIDL_IFACE_WITH_PREFIX = ["SmsEvent", "MmsEvent", "MessageDeletedEvent"];
-const WEBIDL_IFACE = [
-  "DOMMobileMessageError",
-  "MmsMessage",
-  "MobileMessageThread",
-  "SmsMessage",
-];
-
-function checkSmsDisabled() {
-  ok(!('mozMobileMessage' in frames[0].navigator), "navigator.mozMobileMessage should not exist");
-  ok(frames[0].navigator.mozMobileMessage === undefined,
-     "navigator.mozMobileMessage should return undefined");
-}
-
-function checkSmsEnabled() {
-  // Bug 784617: WebSms is disabled on all platforms except Android for the moment.
-  if (navigator.appVersion.indexOf("Android") == -1 && SpecialPowers.Services.appinfo.name != "B2G") {
-    checkSmsDisabled();
-    return;
-  }
-
-  ok('mozMobileMessage' in frames[0].navigator, "navigator.mozMobileMessage should exist");
-  ok(frames[0].navigator.mozMobileMessage, "navigator.mozMobileMessage returns an object");
-  ok(frames[0].navigator.mozMobileMessage instanceof MozMobileMessageManager,
-     "navigator.mozMobileMessage is an MobileMessageManager object");
-}
-
-function checkWebidlInterfaceInWindow() {
-  for (let i = 0; i < WEBIDL_IFACE_WITH_PREFIX.length; i++) {
-    let iface = WEBIDL_IFACE_WITH_PREFIX[i];
-    ok(!(iface in window), iface + " should be prefixed");
-    ok(("Moz" + iface) in window, iface + " should be prefixed");
-  }
-
-  for (let i = 0; i < WEBIDL_IFACE.length; i++) {
-    let iface = WEBIDL_IFACE[i];
-    ok((iface in window), iface + " should be there");
-  }
-}
-
-function checkWebidlInterfaceNotInWindow() {
-  for (let i = 0; i < WEBIDL_IFACE_WITH_PREFIX.length; i++) {
-    let iface = WEBIDL_IFACE_WITH_PREFIX[i];
-    ok(!(iface in window), iface + " should not be there");
-    ok(!(("Moz" + iface) in window), "Moz" + iface + " should not be there");
-  }
-
-  for (let i = 0; i < WEBIDL_IFACE.length; i++) {
-    let iface = WEBIDL_IFACE[i];
-    ok(!(iface in window), iface + " should not be there");
-  }
-}
-
-function test() {
-  checkWebidlInterfaceNotInWindow();
-
-  // If sms is disabled and permission is removed, sms is disabled.
-  SpecialPowers.pushPrefEnv({"set": [["dom.sms.enabled", false]]}, test2);
-}
-
-function test2() {
-  checkSmsDisabled();
-
-  // If sms is enabled and permission is removed, sms is disabled.
-  SpecialPowers.pushPrefEnv({"set": [["dom.sms.enabled", true]]}, test3);
-}
-
-function test3() {
-  checkSmsDisabled();
-
-  // If sms is disabled and permission is granted, sms is disabled.
-  SpecialPowers.pushPrefEnv({"set": [["dom.sms.enabled", false]]}, test4);
-}
-
-function test4() {
-  checkSmsDisabled();
-
-  // Even if sms is enabled and permission is granted, sms is still disabled due
-  // to the webidl check "AvailableIn=CertifiedApps."
-  SpecialPowers.pushPrefEnv({"set": [["dom.sms.enabled", true]]}, test5);
-}
-
-function test5() {
-  checkSmsDisabled();
-
-  var iframeElt = document.getElementsByTagName('iframe')[0];
-  iframeElt.addEventListener("load", function() {
-    iframeElt.removeEventListener("load", arguments.callee);
-    checkSmsEnabled();
-    checkWebidlInterfaceInWindow();
-
-    iframeElt.addEventListener("load", function() {
-      iframeElt.removeEventListener("load", arguments.callee);
-
-      checkSmsDisabled();
-
-      SimpleTest.finish();
-    });
-
-    // Disabling sms takes effect on reload.
-    SpecialPowers.pushPrefEnv({"set": [["dom.sms.enabled", false]]}, function() {
-      frames[0].location.reload();
-    });
-  });
-
-  // Ignore webidl checks, then enabling sms takes effect on reload.
-  SpecialPowers.pushPrefEnv({"set": [["dom.ignore_webidl_scope_checks", true],
-                                     ["dom.sms.enabled", true]]}, function() {
-    frames[0].location.reload();
-  });
-}
-
-SimpleTest.waitForExplicitFinish();
-addLoadEvent(test);
-
-</script>
-</pre>
-</body>
-</html>
deleted file mode 100644
--- a/dom/mobilemessage/tests/xpcshell/header_helpers.js
+++ /dev/null
@@ -1,162 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-
-var subscriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"]
-                        .getService(Ci.mozIJSSubScriptLoader);
-
-/**
- * Test whether specified function throws exception with expected
- * result.
- *
- * @param func
- *        Function to be tested.
- * @param exception
- *        Expected class name of thrown exception. Use null for no throws.
- * @param stack
- *        Optional stack object to be printed. null for Components#stack#caller.
- */
-function do_check_throws(func, result, stack)
-{
-  if (!stack)
-    stack = Components.stack.caller;
-
-  try {
-    func();
-  } catch (ex) {
-    if (ex.name == result) {
-      return;
-    }
-    do_throw("expected result " + result + ", caught " + ex, stack);
-  }
-
-  if (result) {
-    do_throw("expected result " + result + ", none thrown", stack);
-  }
-}
-
-/**
- * Internal test function for comparing results.
- *
- * @param func
- *        A function under test. It should accept an arguement and return the
- *        result.
- * @param data
- *        Input data for `func`.
- * @param expect
- *        Expected result.
- */
-function wsp_test_func(func, data, expect) {
-  let result_str = JSON.stringify(func(data));
-  let expect_str = JSON.stringify(expect);
-  do_check_eq(result_str, expect_str);
-}
-
-/**
- * Test customized WSP PDU decoding.
- *
- * @param func
- *        Decoding func under test. It should return a decoded value if invoked.
- * @param input
- *        Array of octets as test data.
- * @param expect
- *        Expected decoded value, use null if expecting errors instead.
- * @param exception
- *        Expected class name of thrown exception. Use null for no throws.
- */
-function wsp_decode_test_ex(func, input, expect, exception) {
-  let data = {array: input, offset: 0};
-  do_check_throws(wsp_test_func.bind(null, func, data, expect), exception);
-}
-
-/**
- * Test default WSP PDU decoding.
- *
- * @param target
- *        Target decoding object, ie. TextValue.
- * @param input
- *        Array of octets as test data.
- * @param expect
- *        Expected decoded value, use null if expecting errors instead.
- * @param exception
- *        Expected class name of thrown exception. Use null for no throws.
- */
-function wsp_decode_test(target, input, expect, exception) {
-  let func = function decode_func(data) {
-    return target.decode(data);
-  };
-
-  wsp_decode_test_ex(func, input, expect, exception);
-}
-
-/**
- * Test customized WSP PDU encoding.
- *
- * @param func
- *        Encoding func under test. It should return an encoded octet array if
- *        invoked.
- * @param input
- *        An object to be encoded.
- * @param expect
- *        Expected encoded octet array, use null if expecting errors instead.
- * @param exception
- *        Expected class name of thrown exception. Use null for no throws.
- */
-function wsp_encode_test_ex(func, input, expect, exception) {
-  let data = {array: [], offset: 0};
-  do_check_throws(wsp_test_func.bind(null, func.bind(null, data), input,
-                                     expect), exception);
-}
-
-/**
- * Test default WSP PDU encoding.
- *
- * @param target
- *        Target decoding object, ie. TextValue.
- * @param input
- *        An object to be encoded.
- * @param expect
- *        Expected encoded octet array, use null if expecting errors instead.
- * @param exception
- *        Expected class name of thrown exception. Use null for no throws.
- */
-function wsp_encode_test(target, input, expect, exception) {
-  let func = function encode_func(data, input) {
-    target.encode(data, input);
-
-    // Remove extra space consumed during encoding.
-    while (data.array.length > data.offset) {
-      data.array.pop();
-    }
-
-    return data.array;
-  }
-
-  wsp_encode_test_ex(func, input, expect, exception);
-}
-
-/**
- * @param str
- *        A string.
- * @param noAppendNull
- *        True to omit terminating NUL octet. Default false.
- *
- * @return A number array of char codes of characters in `str`.
- */
-function strToCharCodeArray(str, noAppendNull) {
-  let result = [];
-
-  for (let i = 0; i < str.length; i++) {
-    result.push(str.charCodeAt(i));
-  }
-  if (!noAppendNull) {
-    result.push(0);
-  }
-
-  return result;
-}
-
deleted file mode 100644
--- a/dom/mobilemessage/tests/xpcshell/test_mms_pdu_helper.js
+++ /dev/null
@@ -1,1368 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var MMS = {};
-subscriptLoader.loadSubScript("resource://gre/modules/MmsPduHelper.jsm", MMS);
-MMS.debug = do_print;
-
-function run_test() {
-  run_next_test();
-}
-
-//
-// Test target: BooleanValue
-//
-
-//// BooleanValue.decode ////
-
-add_test(function test_BooleanValue_decode() {
-  // Valid codes are 128 and 129. Check boundary conditions 0, 1, 127, 130 and
-  // 255 as well.
-  wsp_decode_test(MMS.BooleanValue, [0], null, "CodeError");
-  wsp_decode_test(MMS.BooleanValue, [1], null, "CodeError");
-  wsp_decode_test(MMS.BooleanValue, [127], null, "CodeError");
-  wsp_decode_test(MMS.BooleanValue, [128], true);
-  wsp_decode_test(MMS.BooleanValue, [129], false);
-  wsp_decode_test(MMS.BooleanValue, [130], null, "CodeError");
-  wsp_decode_test(MMS.BooleanValue, [255], null, "CodeError");
-
-  run_next_test();
-});
-
-//// BooleanValue.encode ////
-
-add_test(function test_BooleanValue_encode() {
-  wsp_encode_test(MMS.BooleanValue, true, [128]);
-  wsp_encode_test(MMS.BooleanValue, false, [129]);
-
-  run_next_test();
-});
-
-//
-// Test target: Address
-//
-
-//// Address.decode ////
-
-add_test(function test_Address_decode() {
-  // Test for PLMN address
-  wsp_decode_test(MMS.Address, strToCharCodeArray("+123.456-789/TYPE=PLMN"),
-                      {address: "+123.456-789", type: "PLMN"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("123456789/TYPE=PLMN"),
-                      {address: "123456789", type: "PLMN"});
-
-  wsp_decode_test(MMS.Address, strToCharCodeArray("a23456789/TYPE=PLMN"),
-                      null, "CodeError");
-  wsp_decode_test(MMS.Address, strToCharCodeArray("++123456789/TYPE=PLMN"),
-                      null, "CodeError");
-
-  // Test for IPv4
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1.2.3.4/TYPE=IPv4"),
-                      {address: "1.2.3.4", type: "IPv4"});
-
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1.2.3.256/TYPE=IPv4"),
-                      null, "CodeError");
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1.2.3.00/TYPE=IPv4"),
-                      null, "CodeError");
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1.2.3.a/TYPE=IPv4"),
-                      null, "CodeError");
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1.2.3/TYPE=IPv4"),
-                      null, "CodeError");
-
-  // Test for IPv6
-  wsp_decode_test(MMS.Address,
-    strToCharCodeArray("1111:AAAA:bbbb:CdEf:1ABC:2cde:3Def:0000/TYPE=IPv6"),
-    {address: "1111:AAAA:bbbb:CdEf:1ABC:2cde:3Def:0000", type: "IPv6"}
-  );
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3:4:5:6:7:8/TYPE=IPv6"),
-                      {address: "1:2:3:4:5:6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3:4:5:6:7::/TYPE=IPv6"),
-                      {address: "1:2:3:4:5:6:7::", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3:4:5:6::/TYPE=IPv6"),
-                      {address: "1:2:3:4:5:6::", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3:4:5::/TYPE=IPv6"),
-                      {address: "1:2:3:4:5::", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3:4::/TYPE=IPv6"),
-                      {address: "1:2:3:4::", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3::/TYPE=IPv6"),
-                      {address: "1:2:3::", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2::/TYPE=IPv6"),
-                      {address: "1:2::", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1::/TYPE=IPv6"),
-                      {address: "1::", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("::/TYPE=IPv6"),
-                      {address: "::", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3:4:5:6::8/TYPE=IPv6"),
-                      {address: "1:2:3:4:5:6::8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3:4:5::8/TYPE=IPv6"),
-                      {address: "1:2:3:4:5::8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3:4::8/TYPE=IPv6"),
-                      {address: "1:2:3:4::8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3::8/TYPE=IPv6"),
-                      {address: "1:2:3::8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2::8/TYPE=IPv6"),
-                      {address: "1:2::8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1::8/TYPE=IPv6"),
-                      {address: "1::8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("::8/TYPE=IPv6"),
-                      {address: "::8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3:4:5::7:8/TYPE=IPv6"),
-                      {address: "1:2:3:4:5::7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3:4::7:8/TYPE=IPv6"),
-                      {address: "1:2:3:4::7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3::7:8/TYPE=IPv6"),
-                      {address: "1:2:3::7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2::7:8/TYPE=IPv6"),
-                      {address: "1:2::7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1::7:8/TYPE=IPv6"),
-                      {address: "1::7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("::7:8/TYPE=IPv6"),
-                      {address: "::7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3:4::6:7:8/TYPE=IPv6"),
-                      {address: "1:2:3:4::6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3::6:7:8/TYPE=IPv6"),
-                      {address: "1:2:3::6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2::6:7:8/TYPE=IPv6"),
-                      {address: "1:2::6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1::6:7:8/TYPE=IPv6"),
-                      {address: "1::6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("::6:7:8/TYPE=IPv6"),
-                      {address: "::6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2:3::5:6:7:8/TYPE=IPv6"),
-                      {address: "1:2:3::5:6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2::5:6:7:8/TYPE=IPv6"),
-                      {address: "1:2::5:6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1::5:6:7:8/TYPE=IPv6"),
-                      {address: "1::5:6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("::5:6:7:8/TYPE=IPv6"),
-                      {address: "::5:6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:2::4:5:6:7:8/TYPE=IPv6"),
-                      {address: "1:2::4:5:6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1::4:5:6:7:8/TYPE=IPv6"),
-                      {address: "1::4:5:6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("::4:5:6:7:8/TYPE=IPv6"),
-                      {address: "::4:5:6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1::3:4:5:6:7:8/TYPE=IPv6"),
-                      {address: "1::3:4:5:6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("::3:4:5:6:7:8/TYPE=IPv6"),
-                      {address: "::3:4:5:6:7:8", type: "IPv6"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("::2:3:4:5:6:7:8/TYPE=IPv6"),
-                      {address: "::2:3:4:5:6:7:8", type: "IPv6"});
-
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1:g:3:4:5:6:7:8/TYPE=IPv6"),
-                      null, "CodeError");
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1::3:4::6:7:8/TYPE=IPv6"),
-                      null, "CodeError");
-
-  // Test for other device-address
-  wsp_decode_test(MMS.Address, strToCharCodeArray("+H-e.1%l_o/TYPE=W0r1d_"),
-                      {address: "+H-e.1%l_o", type: "W0r1d_"});
-
-  wsp_decode_test(MMS.Address, strToCharCodeArray("addr/TYPE=type!"),
-                      null, "CodeError");
-  wsp_decode_test(MMS.Address, strToCharCodeArray("addr!/TYPE=type"),
-                      null, "CodeError");
-
-  // Test for num-shortcode
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1"),
-                      {address: "1", type: "num"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("123"),
-                      {address: "123", type: "num"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("+123"),
-                      {address: "+123", type: "num"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("*123"),
-                      {address: "*123", type: "num"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("#123"),
-                      {address: "#123", type: "num"});
-
-  wsp_decode_test(MMS.Address, strToCharCodeArray("++123"),
-                      null, "CodeError");
-  wsp_decode_test(MMS.Address, strToCharCodeArray("!123"),
-                      null, "CodeError");
-  wsp_decode_test(MMS.Address, strToCharCodeArray("1*23"),
-                      null, "CodeError");
-
-  // Test for alphanum-shortcode
-  wsp_decode_test(MMS.Address, strToCharCodeArray("a"),
-                      {address: "a", type: "alphanum"});
-  wsp_decode_test(MMS.Address, strToCharCodeArray("H0w_D0_Y0u_Turn_Th1s_0n"),
-                      {address: "H0w_D0_Y0u_Turn_Th1s_0n", type: "alphanum"});
-
-  wsp_decode_test(MMS.Address, strToCharCodeArray("abc#"),
-                      null, "CodeError");
-
-  // Test for email address
-  wsp_decode_test(MMS.Address, strToCharCodeArray("Joe User <joe@user.org>"),
-                      {address: "Joe User <joe@user.org>", type: "email"});
-  wsp_decode_test(MMS.Address,
-    strToCharCodeArray("a-z.A-.Z.0-9!#$.%&.'*+./=?^._`{|}~-@a-.zA-Z.0-9!.#$%&'.*+/=?.^_`.{|}~-"),
-    {address: "a-z.A-.Z.0-9!#$.%&.'*+./=?^._`{|}~-@a-.zA-Z.0-9!.#$%&'.*+/=?.^_`.{|}~-", type: "email"}
-  );
-
-  // Test for invalid address
-  wsp_decode_test(MMS.Address, strToCharCodeArray("@@@@@"),
-                  null, "CodeError");
-
-  run_next_test();
-});
-
-//// Address.encode ////
-
-add_test(function test_Address_encode() {
-  // Test for PLMN address
-  wsp_encode_test(MMS.Address, {address: "+123.456-789", type: "PLMN"},
-                  strToCharCodeArray("+123.456-789/TYPE=PLMN"));
-  wsp_encode_test(MMS.Address, {address: "123456789", type: "PLMN"},
-                  strToCharCodeArray("123456789/TYPE=PLMN"));
-
-  wsp_encode_test(MMS.Address, {address: "a23456789", type: "PLMN"},
-                  null, "CodeError");
-  wsp_encode_test(MMS.Address, {address: "++123456789", type: "PLMN"},
-                  null, "CodeError");
-
-  // Test for IPv4
-  wsp_encode_test(MMS.Address, {address: "1.2.3.4", type: "IPv4"},
-                  strToCharCodeArray("1.2.3.4/TYPE=IPv4"));
-
-  wsp_encode_test(MMS.Address, {address: "1.2.3.256", type: "IPv4"},
-                  null, "CodeError");
-  wsp_encode_test(MMS.Address, {address: "1.2.3.00", type: "IPv4"},
-                  null, "CodeError");
-  wsp_encode_test(MMS.Address, {address: "1.2.3.a", type: "IPv4"},
-                  null, "CodeError");
-  wsp_encode_test(MMS.Address, {address: "1.2.3", type: "IPv4"},
-                  null, "CodeError");
-
-  // Test for IPv6
-  wsp_encode_test(MMS.Address,
-    {address: "1111:AAAA:bbbb:CdEf:1ABC:2cde:3Def:0000", type: "IPv6"},
-    strToCharCodeArray("1111:AAAA:bbbb:CdEf:1ABC:2cde:3Def:0000/TYPE=IPv6")
-  );
-  wsp_encode_test(MMS.Address, {address: "1:2:3:4:5:6:7:8", type: "IPv6"},
-                  strToCharCodeArray("1:2:3:4:5:6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3:4:5:6:7::", type: "IPv6"},
-                  strToCharCodeArray("1:2:3:4:5:6:7::/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3:4:5:6::", type: "IPv6"},
-                  strToCharCodeArray("1:2:3:4:5:6::/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3:4:5::", type: "IPv6"},
-                  strToCharCodeArray("1:2:3:4:5::/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3:4::", type: "IPv6"},
-                  strToCharCodeArray("1:2:3:4::/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3::", type: "IPv6"},
-                  strToCharCodeArray("1:2:3::/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2::", type: "IPv6"},
-                  strToCharCodeArray("1:2::/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1::", type: "IPv6"},
-                  strToCharCodeArray("1::/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "::", type: "IPv6"},
-                  strToCharCodeArray("::/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3:4:5:6::8", type: "IPv6"},
-                  strToCharCodeArray("1:2:3:4:5:6::8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3:4:5::8", type: "IPv6"},
-                  strToCharCodeArray("1:2:3:4:5::8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3:4::8", type: "IPv6"},
-                  strToCharCodeArray("1:2:3:4::8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3::8", type: "IPv6"},
-                  strToCharCodeArray("1:2:3::8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2::8", type: "IPv6"},
-                  strToCharCodeArray("1:2::8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1::8", type: "IPv6"},
-                  strToCharCodeArray("1::8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "::8", type: "IPv6"},
-                  strToCharCodeArray("::8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3:4:5::7:8", type: "IPv6"},
-                  strToCharCodeArray("1:2:3:4:5::7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3:4::7:8", type: "IPv6"},
-                  strToCharCodeArray("1:2:3:4::7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3::7:8", type: "IPv6"},
-                  strToCharCodeArray("1:2:3::7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2::7:8", type: "IPv6"},
-                  strToCharCodeArray("1:2::7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1::7:8", type: "IPv6"},
-                  strToCharCodeArray("1::7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "::7:8", type: "IPv6"},
-                  strToCharCodeArray("::7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3:4::6:7:8", type: "IPv6"},
-                  strToCharCodeArray("1:2:3:4::6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3::6:7:8", type: "IPv6"},
-                  strToCharCodeArray("1:2:3::6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2::6:7:8", type: "IPv6"},
-                  strToCharCodeArray("1:2::6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1::6:7:8", type: "IPv6"},
-                  strToCharCodeArray("1::6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "::6:7:8", type: "IPv6"},
-                  strToCharCodeArray("::6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2:3::5:6:7:8", type: "IPv6"},
-                  strToCharCodeArray("1:2:3::5:6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2::5:6:7:8", type: "IPv6"},
-                  strToCharCodeArray("1:2::5:6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1::5:6:7:8", type: "IPv6"},
-                  strToCharCodeArray("1::5:6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "::5:6:7:8", type: "IPv6"},
-                  strToCharCodeArray("::5:6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1:2::4:5:6:7:8", type: "IPv6"},
-                  strToCharCodeArray("1:2::4:5:6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1::4:5:6:7:8", type: "IPv6"},
-                  strToCharCodeArray("1::4:5:6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "::4:5:6:7:8", type: "IPv6"},
-                  strToCharCodeArray("::4:5:6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "1::3:4:5:6:7:8", type: "IPv6"},
-                  strToCharCodeArray("1::3:4:5:6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "::3:4:5:6:7:8", type: "IPv6"},
-                  strToCharCodeArray("::3:4:5:6:7:8/TYPE=IPv6"));
-  wsp_encode_test(MMS.Address, {address: "::2:3:4:5:6:7:8", type: "IPv6"},
-                  strToCharCodeArray("::2:3:4:5:6:7:8/TYPE=IPv6"));
-
-  wsp_encode_test(MMS.Address, {address: "1:g:3:4:5:6:7:8", type: "IPv6"},
-                  null, "CodeError");
-  wsp_encode_test(MMS.Address, {address: "1::3:4:5:6::8", type: "IPv6"},
-                  null, "CodeError");
-
-  // Test for other device-address
-  wsp_encode_test(MMS.Address, {address: "+H-e.1%l_o", type: "W0r1d_"},
-                  strToCharCodeArray("+H-e.1%l_o/TYPE=W0r1d_"));
-
-  wsp_encode_test(MMS.Address, {address: "addr!", type: "type"},
-                  null, "CodeError");
-  wsp_encode_test(MMS.Address, {address: "addr", type: "type!"},
-                  null, "CodeError");
-
-  // Test for num-shortcode
-  wsp_encode_test(MMS.Address, {address: "1", type: "num"},
-                  strToCharCodeArray("1"));
-  wsp_encode_test(MMS.Address, {address: "123", type: "num"},
-                  strToCharCodeArray("123"));
-  wsp_encode_test(MMS.Address, {address: "+123", type: "num"},
-                  strToCharCodeArray("+123"));
-  wsp_encode_test(MMS.Address, {address: "*123", type: "num"},
-                  strToCharCodeArray("*123"));
-  wsp_encode_test(MMS.Address, {address: "#123", type: "num"},
-                  strToCharCodeArray("#123"));
-
-  wsp_encode_test(MMS.Address, {address: "++123", type: "num"},
-                  null, "CodeError");
-  wsp_encode_test(MMS.Address, {address: "!123", type: "num"},
-                  null, "CodeError");
-  wsp_encode_test(MMS.Address, {address: "1#23", type: "num"},
-                  null, "CodeError");
-
-  // Test for alphanum-shortcode
-  wsp_encode_test(MMS.Address, {address: "a", type: "alphanum"},
-                  strToCharCodeArray("a"));
-  wsp_encode_test(MMS.Address, {address: "1", type: "alphanum"},
-                  strToCharCodeArray("1"));
-  wsp_encode_test(MMS.Address, {address: "H0w_D0_Y0u_Turn_Th1s_0n", type: "alphanum"},
-                  strToCharCodeArray("H0w_D0_Y0u_Turn_Th1s_0n"));
-
-  wsp_encode_test(MMS.Address, {address: "abc#", type: "alphanum"},
-                  null, "CodeError");
-
-  // Test for email address
-  wsp_encode_test(MMS.Address, {address: "Joe User <joe@user.org>", type: "email"},
-                  strToCharCodeArray("Joe User <joe@user.org>"));
-  wsp_encode_test(MMS.Address,
-    {address: "a-z.A-.Z.0-9!#$.%&.'*+./=?^._`{|}~-@a-.zA-Z.0-9!.#$%&'.*+/=?.^_`.{|}~-", type: "email"},
-    strToCharCodeArray("a-z.A-.Z.0-9!#$.%&.'*+./=?^._`{|}~-@a-.zA-Z.0-9!.#$%&'.*+/=?.^_`.{|}~-")
-  );
-
-  // Test for invalid address
-  wsp_encode_test(MMS.Address, {address: "a"}, null, "CodeError");
-  wsp_encode_test(MMS.Address, {type: "alphanum"}, null, "CodeError");
-
-  run_next_test();
-});
-
-//// Address.resolveType ////
-
-add_test(function test_Address_encode() {
-  function test(address, type) {
-    do_check_eq(MMS.Address.resolveType(address), type);
-  }
-
-  // Test ambiguous addresses.
-  test("+15525225554",      "PLMN");
-  test("5525225554",        "PLMN");
-  test("jkalbcjklg",        "PLMN");
-  test("jk.alb.cjk.lg",     "PLMN");
-  test("j:k:a:l:b:c:jk:lg", "PLMN");
-  test("55.252.255.54",     "IPv4");
-  test("5:5:2:5:2:2:55:54", "IPv6");
-  test("jk@alb.cjk.lg",     "email");
-  // Test empty address.  This is for received anonymous MMS messages.
-  test("",                  "Others");
-
-  run_next_test();
-});
-
-//
-// Test target: HeaderField
-//
-
-//// HeaderField.decode ////
-
-add_test(function test_HeaderField_decode() {
-  wsp_decode_test(MMS.HeaderField, [65, 0, 66, 0], {name: "a", value: "B"});
-  wsp_decode_test(MMS.HeaderField, [0x80 | 0x27, 128],
-                      {name: "x-mms-stored", value: true});
-
-  run_next_test();
-});
-
-//// HeaderField.encode ////
-
-add_test(function test_HeaderField_encode() {
-  // Test for MmsHeader
-  wsp_encode_test(MMS.HeaderField, {name: "X-Mms-Message-Type",
-                                    value: MMS_PDU_TYPE_SEND_REQ},
-                  [0x80 | 0x0C, MMS_PDU_TYPE_SEND_REQ]);
-  // Test for ApplicationHeader
-  wsp_encode_test(MMS.HeaderField, {name: "a", value: "B"}, [97, 0, 66, 0]);
-
-  run_next_test();
-});
-
-//
-// Test target: MmsHeader
-//
-
-//// MmsHeader.decode ////
-
-add_test(function test_MmsHeader_decode() {
-  wsp_decode_test(MMS.MmsHeader, [0x80 | 0x00], null, "NotWellKnownEncodingError");
-  wsp_decode_test(MMS.MmsHeader, [0x80 | 0x27, 128],
-                      {name: "x-mms-stored", value: true});
-  wsp_decode_test(MMS.MmsHeader, [0x80 | 0x27, 255], null);
-
-  run_next_test();
-});
-
-//// MmsHeader.encode ////
-
-add_test(function test_MmsHeader_encode() {
-  // Test for empty header name:
-  wsp_encode_test(MMS.MmsHeader, {name: undefined, value: null}, null, "CodeError");
-  wsp_encode_test(MMS.MmsHeader, {name: null, value: null}, null, "CodeError");
-  wsp_encode_test(MMS.MmsHeader, {name: "", value: null}, null, "CodeError");
-  // Test for non-well-known header name:
-  wsp_encode_test(MMS.MmsHeader, {name: "X-No-Such-Field", value: null},
-                  null, "NotWellKnownEncodingError");
-  // Test for normal header
-  wsp_encode_test(MMS.MmsHeader, {name: "X-Mms-Message-Type",
-                                  value: MMS_PDU_TYPE_SEND_REQ},
-                  [0x80 | 0x0C, MMS_PDU_TYPE_SEND_REQ]);
-
-  run_next_test();
-});
-
-//
-// Test target: CancelStatusValue
-//
-
-//// CancelStatusValue.decode ////
-
-add_test(function test_CancelStatusValue_decode() {
-  // Valid codes are 128 and 129. Check boundary conditions 0, 1, 127, 130 and
-  // 255 as well.
-  wsp_decode_test(MMS.CancelStatusValue, [0], null, "CodeError");
-  wsp_decode_test(MMS.CancelStatusValue, [1], null, "CodeError");
-  wsp_decode_test(MMS.CancelStatusValue, [127], null, "CodeError");
-  wsp_decode_test(MMS.CancelStatusValue, [128], 128);
-  wsp_decode_test(MMS.CancelStatusValue, [129], 129);
-  wsp_decode_test(MMS.CancelStatusValue, [130], null, "CodeError");
-  wsp_decode_test(MMS.CancelStatusValue, [255], null, "CodeError");
-
-  run_next_test();
-});
-
-//// CancelStatusValue.encode ////
-
-add_test(function test_CancelStatusValue_encode() {
-  // Valid codes are 128 and 129. Check boundary conditions 0, 1, 127, 130 and
-  // 255 as well.
-  wsp_encode_test(MMS.CancelStatusValue, 0, null, "CodeError");
-  wsp_encode_test(MMS.CancelStatusValue, 1, null, "CodeError");
-  wsp_encode_test(MMS.CancelStatusValue, 127, null, "CodeError");
-  wsp_encode_test(MMS.CancelStatusValue, 128, [128]);
-  wsp_encode_test(MMS.CancelStatusValue, 129, [129]);
-  wsp_encode_test(MMS.CancelStatusValue, 130, null, "CodeError");
-  wsp_encode_test(MMS.CancelStatusValue, 255, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: ContentClassValue
-//
-
-//// ContentClassValue.decode ////
-
-add_test(function test_ContentClassValue_decode() {
-  // Valid codes are 128 - 135. Check boundary conditions 0, 1, 127, 136 and
-  // 255 as well.
-  wsp_decode_test(MMS.ContentClassValue, [0], null, "CodeError");
-  wsp_decode_test(MMS.ContentClassValue, [1], null, "CodeError");
-  wsp_decode_test(MMS.ContentClassValue, [127], null, "CodeError");
-  for (let i = 128; i <= 135; i++) {
-    wsp_decode_test(MMS.ContentClassValue, [i], i);
-  }
-  wsp_decode_test(MMS.ContentClassValue, [136], null, "CodeError");
-  wsp_decode_test(MMS.ContentClassValue, [255], null, "CodeError");
-
-  run_next_test();
-});
-
-//// ContentClassValue.encode ////
-
-add_test(function test_ContentClassValue_encode() {
-  // Valid codes are 128 - 135. Check boundary conditions 0, 1, 127, 136 and
-  // 255 as well.
-  wsp_encode_test(MMS.ContentClassValue, 0, null, "CodeError");
-  wsp_encode_test(MMS.ContentClassValue, 1, null, "CodeError");
-  wsp_encode_test(MMS.ContentClassValue, 127, null, "CodeError");
-  for (let i = 128; i <= 135; i++) {
-    wsp_encode_test(MMS.ContentClassValue, i, [i]);
-  }
-  wsp_encode_test(MMS.ContentClassValue, 136, null, "CodeError");
-  wsp_encode_test(MMS.ContentClassValue, 255, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: ContentLocationValue
-//
-
-//// ContentLocationValue.decode ////
-
-add_test(function test_ContentLocationValue_decode() {
-  // Test for MMS_PDU_TYPE_MBOX_DELETE_CONF & MMS_PDU_TYPE_DELETE_CONF
-  function test(type, statusCount, exception) {
-    function decode(data) {
-      let options = {};
-      if (type) {
-        options["x-mms-message-type"] = type;
-      }
-      return MMS.ContentLocationValue.decode(data, options);
-    }
-
-    let uri = "http://no.such.com/path";
-
-    let data = strToCharCodeArray(uri);
-    if (statusCount != null) {
-      data = [data.length + 1, statusCount | 0x80].concat(data);
-    }
-
-    let expected;
-    if (!exception) {
-      expected = {};
-      if (statusCount != null) {
-        expected.statusCount = statusCount;
-      }
-      expected.uri = uri;
-    }
-
-    do_print("data = " + JSON.stringify(data));
-    wsp_decode_test_ex(decode, data, expected, exception);
-  }
-
-  test(null, null, "FatalCodeError");
-  for (let type = MMS_PDU_TYPE_SEND_REQ; type <= MMS_PDU_TYPE_CANCEL_CONF; type++) {
-    if ((type == MMS_PDU_TYPE_MBOX_DELETE_CONF)
-        || (type == MMS_PDU_TYPE_DELETE_CONF)) {
-      test(type, 1, null);
-    } else {
-      test(type, null, null);
-    }
-  }
-
-  run_next_test();
-});
-
-//
-// Test target: ElementDescriptorValue
-//
-
-//// ElementDescriptorValue.decode ////
-
-add_test(function test_ElementDescriptorValue_decode() {
-  wsp_decode_test(MMS.ElementDescriptorValue, [2, 97, 0], {contentReference: "a"});
-  wsp_decode_test(MMS.ElementDescriptorValue, [4, 97, 0, 0x80 | 0x02, 0x80],
-                      {contentReference: "a", params: {type: 0}});
-
-  run_next_test();
-});
-
-//
-// Test target: Parameter
-//
-
-//// Parameter.decodeParameterName ////
-
-add_test(function test_Parameter_decodeParameterName() {
-  wsp_decode_test_ex(function(data) {
-      return MMS.Parameter.decodeParameterName(data);
-    }, [0x80 | 0x02], "type"
-  );
-  wsp_decode_test_ex(function(data) {
-      return MMS.Parameter.decodeParameterName(data);
-    }, strToCharCodeArray("type"), "type"
-  );
-
-  run_next_test();
-});
-
-//// Parameter.decode ////
-
-add_test(function test_Parameter_decode() {
-  wsp_decode_test(MMS.Parameter, [0x80 | 0x02, 0x80 | 0x00], {name: "type", value: 0});
-
-  run_next_test();
-});
-
-//// Parameter.decodeMultiple ////
-
-add_test(function test_Parameter_decodeMultiple() {
-  // FIXME: The following test case falls because Parameter-value decoding of
-  //        "type" parameters utilies WSP.ConstrainedEncoding, which in turn
-  //        utilies WSP.TextString, and TextString is not matual exclusive to
-  //        each other.
-  //wsp_decode_test_ex(function(data) {
-  //    return MMS.Parameter.decodeMultiple(data, data.array.length);
-  //  }, [0x80 | 0x02, 0x80 | 0x00].concat(strToCharCodeArray("good")).concat([0x80 | 0x01]),
-  //  {type: 0, good: 1}
-  //);
-
-  run_next_test();
-});
-
-//// Parameter.encode ////
-
-add_test(function test_Parameter_encode() {
-  // Test for invalid parameter value
-  wsp_encode_test(MMS.Parameter, null, null, "CodeError");
-  wsp_encode_test(MMS.Parameter, undefined, null, "CodeError");
-  wsp_encode_test(MMS.Parameter, {}, null, "CodeError");
-  // Test for case-insensitive parameter name
-  wsp_encode_test(MMS.Parameter, {name: "TYPE", value: 0}, [130, 128]);
-  wsp_encode_test(MMS.Parameter, {name: "type", value: 0}, [130, 128]);
-  // Test for non-well-known parameter name
-  wsp_encode_test(MMS.Parameter, {name: "name", value: 0}, [110, 97, 109, 101, 0, 128]);
-  // Test for constrained encoding value
-  wsp_encode_test(MMS.Parameter, {name: "type", value: "0"}, [130, 48, 0]);
-
-  run_next_test();
-});
-
-//
-// Test target: EncodedStringValue
-//
-
-//// EncodedStringValue.decode ////
-
-add_test(function test_EncodedStringValue_decode() {
-  // Test for normal TextString
-  wsp_decode_test(MMS.EncodedStringValue, strToCharCodeArray("Hello"), "Hello");
-  // Test for non-well-known charset
-  wsp_decode_test(MMS.EncodedStringValue, [1, 0x80], null, "NotWellKnownEncodingError");
-  // Test for utf-8
-  let entry = MMS.WSP.WSP_WELL_KNOWN_CHARSETS["utf-8"];
-  // "Mozilla" in full width.
-  let str = "\uff2d\uff4f\uff5a\uff49\uff4c\uff4c\uff41";
-
-  let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
-             .createInstance(Ci.nsIScriptableUnicodeConverter);
-  conv.charset = entry.converter;
-
-  let raw = conv.convertToByteArray(str).concat([0]);
-  wsp_decode_test(MMS.EncodedStringValue,
-                  [raw.length + 2, 0x80 | entry.number, 127].concat(raw), str);
-
-  entry = MMS.WSP.WSP_WELL_KNOWN_CHARSETS["utf-16"];
-  // "Mozilla" in full width.
-  str = "\u004d\u006F\u007A\u0069\u006C\u006C\u0061";
-
-  conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
-         .createInstance(Ci.nsIScriptableUnicodeConverter);
-  conv.charset = entry.converter;
-
-  raw = conv.convertToByteArray(str).concat([0]);
-  wsp_decode_test(MMS.EncodedStringValue,
-                  [raw.length + 3, 2, 3, 247].concat(raw), str);
-
-  run_next_test();
-});
-
-//// EncodedStringValue.encode ////
-
-add_test(function test_EncodedStringValue_encode() {
-  // Test for normal TextString
-  wsp_encode_test(MMS.EncodedStringValue, "Hello", strToCharCodeArray("Hello"));
-
-  // Test for utf-8
-  let entry = MMS.WSP.WSP_WELL_KNOWN_CHARSETS["utf-8"];
-  // "Mozilla" in full width.
-  let str = "\uff2d\uff4f\uff5a\uff49\uff4c\uff4c\uff41";
-
-  let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
-             .createInstance(Ci.nsIScriptableUnicodeConverter);
-  conv.charset = entry.converter;
-
-  let raw = conv.convertToByteArray(str).concat([0]);
-  wsp_encode_test(MMS.EncodedStringValue, str,
-                  [raw.length + 2, 0x80 | entry.number, 127].concat(raw));
-
-  // MMS.EncodedStringValue encodes non us-ascii characters (128 ~ 255)
-  // (e.g., 'Ñ' or 'ü') by the utf-8 encoding. Otherwise, for us-ascii
-  // characters (0 ~ 127), still use the normal TextString encoding.
-
-  // "Ñü" in full width.
-  str = "\u00d1\u00fc";
-  raw = conv.convertToByteArray(str).concat([0]);
-  wsp_encode_test(MMS.EncodedStringValue, str,
-                  [raw.length + 2, 0x80 | entry.number, 127].concat(raw));
-
-  run_next_test();
-});
-
-//
-// Test target: ExpiryValue
-//
-
-//// ExpiryValue.decode ////
-
-add_test(function test_ExpiryValue_decode() {
-  // Test for Absolute-token Date-value
-  wsp_decode_test(MMS.ExpiryValue, [3, 128, 1, 0x80], new Date(0x80 * 1000));
-  // Test for Relative-token Delta-seconds-value
-  wsp_decode_test(MMS.ExpiryValue, [2, 129, 0x80], 0);
-
-  run_next_test();
-});
-
-//// ExpiryValue.encode ////
-
-add_test(function test_ExpiryValue_encode() {
-  // Test for Absolute-token Date-value
-  wsp_encode_test(MMS.ExpiryValue, new Date(0x80 * 1000), [3, 128, 1, 0x80]);
-  // Test for Relative-token Delta-seconds-value
-  wsp_encode_test(MMS.ExpiryValue, 0, [2, 129, 0x80]);
-
-  run_next_test();
-});
-
-//
-// Test target: PreviouslySentByValue
-//
-
-//// PreviouslySentByValue.decode ////
-
-add_test(function test_PreviouslySentByValue_decode() {
-  wsp_decode_test(MMS.PreviouslySentByValue, [3, 0x80 | 0x03, 65, 0],
-                      {forwardedCount: 3, originator: {address: "A",
-                                                       type: "alphanum"}});
-
-  run_next_test();
-});
-
-//
-// Test target: PreviouslySentDateValue
-//
-
-//// PreviouslySentDateValue.decode ////
-
-add_test(function test_PreviouslySentDateValue_decode() {
-  wsp_decode_test(MMS.PreviouslySentDateValue, [3, 0x80 | 0x03, 1, 4],
-                      {forwardedCount: 3, timestamp: new Date(4 * 1000)});
-
-  run_next_test();
-});
-
-//
-// Test target: FromValue
-//
-
-//// FromValue.decode ////
-
-add_test(function test_FromValue_decode() {
-  // Test for Insert-address-token:
-  wsp_decode_test(MMS.FromValue, [1, 129], null);
-  // Test for Address-present-token:
-  let addr = strToCharCodeArray("+123/TYPE=PLMN");
-  wsp_decode_test(MMS.FromValue, [addr.length + 1, 128].concat(addr),
-                      {address: "+123", type: "PLMN"});
-
-  run_next_test();
-});
-
-//// FromValue.encode ////
-
-add_test(function test_FromValue_encode() {
-  // Test for Insert-address-token:
-  wsp_encode_test(MMS.FromValue, null, [1, 129]);
-  // Test for Address-present-token:
-  let addr = strToCharCodeArray("+123/TYPE=PLMN");
-  wsp_encode_test(MMS.FromValue, {address: "+123", type: "PLMN"},
-                  [addr.length + 1, 128].concat(addr));
-
-  run_next_test();
-});
-
-//
-// Test target: MessageClassValue
-//
-
-//// MessageClassValue.decodeClassIdentifier ////
-
-add_test(function test_MessageClassValue_decodeClassIdentifier() {
-  const IDs = ["personal", "advertisement", "informational", "auto"];
-
-  function test(i, error) {
-    let id = IDs[i - 128];
-    wsp_decode_test_ex(function(data) {
-        return MMS.MessageClassValue.decodeClassIdentifier(data);
-      }, [i], (error ? null : id), error);
-  }
-
-  // Valid codes are 128 - 131. Check boundary conditions 0, 1, 127, 132 and
-  // 255 as well.
-  test(0, "CodeError");
-  test(1, "CodeError");
-  test(127, "CodeError");
-  for (let i = 128; i <= 131; i++) {
-    test(i, null);
-  }
-  test(132, "CodeError");
-  test(255, "CodeError");
-
-  run_next_test();
-});
-
-//// MessageClassValue.decode ////
-
-add_test(function test_MessageClassValue_decode() {
-  wsp_decode_test(MMS.MessageClassValue, [65, 0], "A");
-  wsp_decode_test(MMS.MessageClassValue, [128], "personal");
-
-  run_next_test();
-});
-
-//// MessageClassValue.encode ////
-
-add_test(function test_MessageClassValue_encode() {
-  wsp_encode_test(MMS.MessageClassValue, "personal", [128]);
-  wsp_encode_test(MMS.MessageClassValue, "advertisement", [129]);
-  wsp_encode_test(MMS.MessageClassValue, "informational", [130]);
-  wsp_encode_test(MMS.MessageClassValue, "auto", [131]);
-  wsp_encode_test(MMS.MessageClassValue, "A", [65, 0]);
-
-  run_next_test();
-});
-
-//
-// Test target: MessageTypeValue
-//
-
-//// MessageTypeValue.decode ////
-
-add_test(function test_MessageTypeValue_decode() {
-  // Valid codes are 128 - 151. Check boundary conditions 0, 1, 127, 152 and
-  // 255 as well.
-  wsp_decode_test(MMS.MessageTypeValue, [0], null, "CodeError");
-  wsp_decode_test(MMS.MessageTypeValue, [1], null, "CodeError");
-  wsp_decode_test(MMS.MessageTypeValue, [127], null, "CodeError");
-  for (let i = 128; i <= 151; i++) {
-    wsp_decode_test(MMS.MessageTypeValue, [i], i);
-  }
-  wsp_decode_test(MMS.MessageTypeValue, [152], null, "CodeError");
-  wsp_decode_test(MMS.MessageTypeValue, [255], null, "CodeError");
-
-  run_next_test();
-});
-
-//// MessageTypeValue.encode ////
-
-add_test(function test_MessageTypeValue_encode() {
-  // Valid codes are 128 - 151. Check boundary conditions 0, 1, 127, 152 and
-  // 255 as well.
-  wsp_encode_test(MMS.MessageTypeValue, 0, null, "CodeError");
-  wsp_encode_test(MMS.MessageTypeValue, 1, null, "CodeError");
-  wsp_encode_test(MMS.MessageTypeValue, 127, null, "CodeError");
-  for (let i = 128; i <= 151; i++) {
-    wsp_encode_test(MMS.MessageTypeValue, i, [i]);
-  }
-  wsp_encode_test(MMS.MessageTypeValue, 152, null, "CodeError");
-  wsp_encode_test(MMS.MessageTypeValue, 255, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: MmFlagsValue
-//
-
-//// MmFlagsValue.decode ////
-
-add_test(function test_MmFlagsValue_decode() {
-  // Valid codes are 128 - 130. Check boundary conditions 0, 1, 127, 131 and
-  // 255 as well.
-  wsp_decode_test(MMS.MmFlagsValue, [3, 0, 65, 0], null, "CodeError");
-  wsp_decode_test(MMS.MmFlagsValue, [3, 1, 65, 0], null, "CodeError");
-  wsp_decode_test(MMS.MmFlagsValue, [3, 127, 65, 0], null, "CodeError");
-  for (let i = 128; i <= 130; i++) {
-    wsp_decode_test(MMS.MmFlagsValue, [3, i, 65, 0], {type: i, text: "A"});
-  }
-  wsp_decode_test(MMS.MmFlagsValue, [3, 131, 65, 0], null, "CodeError");
-  wsp_decode_test(MMS.MmFlagsValue, [3, 255, 65, 0], null, "CodeError");
-
-  run_next_test();
-});
-
-//// MmFlagsValue.encode ////
-
-add_test(function test_MmFlagsValue_encode() {
-  // Valid codes are 128 - 130. Check boundary conditions 0, 1, 127, 131 and
-  // 255 as well.
-  wsp_encode_test(MMS.MmFlagsValue, {type: 0, text: "A"}, null, "CodeError");
-  wsp_encode_test(MMS.MmFlagsValue, {type: 1, text: "A"}, null, "CodeError");
-  wsp_encode_test(MMS.MmFlagsValue, {type: 127, text: "A"}, null, "CodeError");
-  for (let i = 128; i <= 130; i++) {
-    wsp_encode_test(MMS.MmFlagsValue, {type: i, text: "A"}, [3, i, 65, 0]);
-  }
-  wsp_encode_test(MMS.MmFlagsValue, {type: 131, text: "A"}, null, "CodeError");
-  wsp_encode_test(MMS.MmFlagsValue, {type: 255, text: "A"}, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: MmStateValue
-//
-
-//// MmStateValue.decode ////
-
-add_test(function test_MmStateValue_decode() {
-  // Valid codes are 128 - 132. Check boundary conditions 0, 1, 127, 133 and
-  // 255 as well.
-  wsp_decode_test(MMS.MmStateValue, [0], null, "CodeError");
-  wsp_decode_test(MMS.MmStateValue, [1], null, "CodeError");
-  wsp_decode_test(MMS.MmStateValue, [127], null, "CodeError");
-  for (let i = 128; i <= 132; i++) {
-    wsp_decode_test(MMS.MmStateValue, [i], i);
-  }
-  wsp_decode_test(MMS.MmStateValue, [133], null, "CodeError");
-  wsp_decode_test(MMS.MmStateValue, [255], null, "CodeError");
-
-  run_next_test();
-});
-
-//// MmStateValue.encode ////
-
-add_test(function test_MmStateValue_encode() {
-  // Valid codes are 128 - 132. Check boundary conditions 0, 1, 127, 133 and
-  // 255 as well.
-  wsp_encode_test(MMS.MmStateValue, 0, null, "CodeError");
-  wsp_encode_test(MMS.MmStateValue, 1, null, "CodeError");
-  wsp_encode_test(MMS.MmStateValue, 127, null, "CodeError");
-  for (let i = 128; i <= 132; i++) {
-    wsp_encode_test(MMS.MmStateValue, i, [i]);
-  }
-  wsp_encode_test(MMS.MmStateValue, 133, null, "CodeError");
-  wsp_encode_test(MMS.MmStateValue, 255, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: PriorityValue
-//
-
-//// PriorityValue.decode ////
-
-add_test(function test_PriorityValue_decode() {
-  // Valid codes are 128 - 130. Check boundary conditions 0, 1, 127, 131 and
-  // 255 as well.
-  wsp_decode_test(MMS.PriorityValue, [0], null, "CodeError");
-  wsp_decode_test(MMS.PriorityValue, [1], null, "CodeError");
-  wsp_decode_test(MMS.PriorityValue, [127], null, "CodeError");
-  for (let i = 128; i <= 130; i++) {
-    wsp_decode_test(MMS.PriorityValue, [i], i);
-  }
-  wsp_decode_test(MMS.PriorityValue, [131], null, "CodeError");
-  wsp_decode_test(MMS.PriorityValue, [255], null, "CodeError");
-
-  run_next_test();
-});
-
-//// PriorityValue.encode ////
-
-add_test(function test_PriorityValue_encode() {
-  // Valid codes are 128 - 130. Check boundary conditions 0, 1, 127, 131 and
-  // 255 as well.
-  wsp_encode_test(MMS.PriorityValue, 0, null, "CodeError");
-  wsp_encode_test(MMS.PriorityValue, 1, null, "CodeError");
-  wsp_encode_test(MMS.PriorityValue, 127, null, "CodeError");
-  for (let i = 128; i <= 130; i++) {
-    wsp_encode_test(MMS.PriorityValue, i, [i]);
-  }
-  wsp_encode_test(MMS.PriorityValue, 131, null, "CodeError");
-  wsp_encode_test(MMS.PriorityValue, 255, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: ReadStatusValue
-//
-
-//// ReadStatusValue.decode ////
-
-add_test(function test_ReadStatusValue_decode() {
-  // Valid codes are 128, 129. Check boundary conditions 0, 1, 127, 130 and
-  // 255 as well.
-  wsp_decode_test(MMS.ReadStatusValue, [0], null, "CodeError");
-  wsp_decode_test(MMS.ReadStatusValue, [1], null, "CodeError");
-  wsp_decode_test(MMS.ReadStatusValue, [127], null, "CodeError");
-  wsp_decode_test(MMS.ReadStatusValue, [128], 128);
-  wsp_decode_test(MMS.ReadStatusValue, [129], 129);
-  wsp_decode_test(MMS.ReadStatusValue, [130], null, "CodeError");
-  wsp_decode_test(MMS.ReadStatusValue, [255], null, "CodeError");
-
-  run_next_test();
-});
-
-//// ReadStatusValue.encode ////
-
-add_test(function test_ReadStatusValue_encode() {
-  // Valid codes are 128, 129. Check boundary conditions 0, 1, 127, 130 and
-  // 255 as well.
-  wsp_encode_test(MMS.ReadStatusValue, 0, null, "CodeError");
-  wsp_encode_test(MMS.ReadStatusValue, 1, null, "CodeError");
-  wsp_encode_test(MMS.ReadStatusValue, 127, null, "CodeError");
-  wsp_encode_test(MMS.ReadStatusValue, 128, [128]);
-  wsp_encode_test(MMS.ReadStatusValue, 129, [129]);
-  wsp_encode_test(MMS.ReadStatusValue, 130, null, "CodeError");
-  wsp_encode_test(MMS.ReadStatusValue, 255, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: RecommendedRetrievalModeValue
-//
-
-//// RecommendedRetrievalModeValue.decode ////
-
-add_test(function test_RecommendedRetrievalModeValue_decode() {
-  // Valid codes is 128. Check boundary conditions 0, 1, 127, 130 and 255 as
-  // well.
-  wsp_decode_test(MMS.RecommendedRetrievalModeValue, [0], null, "CodeError");
-  wsp_decode_test(MMS.RecommendedRetrievalModeValue, [1], null, "CodeError");
-  wsp_decode_test(MMS.RecommendedRetrievalModeValue, [127], null, "CodeError");
-  wsp_decode_test(MMS.RecommendedRetrievalModeValue, [128], 128);
-  wsp_decode_test(MMS.RecommendedRetrievalModeValue, [129], null, "CodeError");
-  wsp_decode_test(MMS.RecommendedRetrievalModeValue, [255], null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: ReplyChargingValue
-//
-
-//// ReplyChargingValue.decode ////
-
-add_test(function test_ReplyChargingValue_decode() {
-  // Valid codes are 128 - 131. Check boundary conditions 0, 1, 127, 132 and
-  // 255 as well.
-  wsp_decode_test(MMS.ReplyChargingValue, [0], null, "CodeError");
-  wsp_decode_test(MMS.ReplyChargingValue, [1], null, "CodeError");
-  wsp_decode_test(MMS.ReplyChargingValue, [127], null, "CodeError");
-  for (let i = 128; i <= 131; i++) {
-    wsp_decode_test(MMS.ReplyChargingValue, [i], i);
-  }
-  wsp_decode_test(MMS.ReplyChargingValue, [132], null, "CodeError");
-  wsp_decode_test(MMS.ReplyChargingValue, [255], null, "CodeError");
-
-  run_next_test();
-});
-
-//// ReplyChargingValue.encode ////
-
-add_test(function test_ReplyChargingValue_encode() {
-  // Valid codes are 128 - 131. Check boundary conditions 0, 1, 127, 132 and
-  // 255 as well.
-  wsp_encode_test(MMS.ReplyChargingValue, 0, null, "CodeError");
-  wsp_encode_test(MMS.ReplyChargingValue, 1, null, "CodeError");
-  wsp_encode_test(MMS.ReplyChargingValue, 127, null, "CodeError");
-  for (let i = 128; i <= 131; i++) {
-    wsp_encode_test(MMS.ReplyChargingValue, i, [i]);
-  }
-  wsp_encode_test(MMS.ReplyChargingValue, 132, null, "CodeError");
-  wsp_encode_test(MMS.ReplyChargingValue, 255, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: ResponseText
-//
-
-//// ResponseText.decode ////
-
-add_test(function test_ResponseText_decode() {
-  // Test for MMS_PDU_TYPE_MBOX_DELETE_CONF & MMS_PDU_TYPE_DELETE_CONF
-  wsp_decode_test_ex(function(data) {
-      data.array[0] = data.array.length - 1;
-
-      let options = {};
-      options["x-mms-message-type"] = MMS_PDU_TYPE_MBOX_DELETE_CONF;
-      return MMS.ResponseText.decode(data, options);
-    }, [0, 0x80 | 0x00].concat(strToCharCodeArray("http://no.such.com/path")),
-    {statusCount: 0, text: "http://no.such.com/path"}
-  );
-  wsp_decode_test_ex(function(data) {
-      data.array[0] = data.array.length - 1;
-
-      let options = {};
-      options["x-mms-message-type"] = MMS_PDU_TYPE_DELETE_CONF;
-      return MMS.ResponseText.decode(data, options);
-    }, [0, 0x80 | 0x00].concat(strToCharCodeArray("http://no.such.com/path")),
-    {statusCount: 0, text: "http://no.such.com/path"}
-  );
-  // Test for other situations
-  wsp_decode_test_ex(function(data) {
-      let options = {};
-      options["x-mms-message-type"] = MMS_PDU_TYPE_SEND_REQ;
-      return MMS.ResponseText.decode(data, options);
-    }, strToCharCodeArray("http://no.such.com/path"),
-    {text: "http://no.such.com/path"}
-  );
-
-  run_next_test();
-});
-
-//
-// Test target: RetrieveStatusValue
-//
-
-//// RetrieveStatusValue.decode ////
-
-add_test(function test_RetrieveStatusValue_decode() {
-  // Valid codes are 128, 192 - 255. Check boundary conditions 0, 1, 127, 129,
-  // and 191 as well.
-  wsp_decode_test(MMS.RetrieveStatusValue, [0],
-                  MMS_PDU_ERROR_PERMANENT_FAILURE);
-  wsp_decode_test(MMS.RetrieveStatusValue, [1],
-                  MMS_PDU_ERROR_PERMANENT_FAILURE);
-  wsp_decode_test(MMS.RetrieveStatusValue, [127],
-                  MMS_PDU_ERROR_PERMANENT_FAILURE);
-
-  wsp_decode_test(MMS.RetrieveStatusValue, [128], MMS_PDU_ERROR_OK);
-
-  wsp_decode_test(MMS.RetrieveStatusValue, [129],
-                  MMS_PDU_ERROR_PERMANENT_FAILURE);
-  wsp_decode_test(MMS.RetrieveStatusValue, [191],
-                  MMS_PDU_ERROR_PERMANENT_FAILURE);
-  for (let i = 192; i < 256; i++) {
-    wsp_decode_test(MMS.RetrieveStatusValue, [i], i);
-  }
-
-  run_next_test();
-});
-
-//
-// Test target: SenderVisibilityValue
-//
-
-//// SenderVisibilityValue.decode ////
-
-add_test(function test_SenderVisibilityValue_decode() {
-  // Valid codes are 128, 129. Check boundary conditions 0, 1, 127, 130 and
-  // 255 as well.
-  wsp_decode_test(MMS.SenderVisibilityValue, [0], null, "CodeError");
-  wsp_decode_test(MMS.SenderVisibilityValue, [1], null, "CodeError");
-  wsp_decode_test(MMS.SenderVisibilityValue, [127], null, "CodeError");
-  wsp_decode_test(MMS.SenderVisibilityValue, [128], 128);
-  wsp_decode_test(MMS.SenderVisibilityValue, [129], 129);
-  wsp_decode_test(MMS.SenderVisibilityValue, [130], null, "CodeError");
-  wsp_decode_test(MMS.SenderVisibilityValue, [255], null, "CodeError");
-
-  run_next_test();
-});
-
-//// SenderVisibilityValue.encode ////
-
-add_test(function test_SenderVisibilityValue_encode() {
-  // Valid codes are 128, 129. Check boundary conditions 0, 1, 127, 130 and
-  // 255 as well.
-  wsp_encode_test(MMS.SenderVisibilityValue, 0, null, "CodeError");
-  wsp_encode_test(MMS.SenderVisibilityValue, 1, null, "CodeError");
-  wsp_encode_test(MMS.SenderVisibilityValue, 127, null, "CodeError");
-  wsp_encode_test(MMS.SenderVisibilityValue, 128, [128]);
-  wsp_encode_test(MMS.SenderVisibilityValue, 129, [129]);
-  wsp_encode_test(MMS.SenderVisibilityValue, 130, null, "CodeError");
-  wsp_encode_test(MMS.SenderVisibilityValue, 255, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: StatusValue
-//
-
-//// StatusValue.decode ////
-
-add_test(function test_StatusValue_decode() {
-  // Valid codes are 128 - 135. Check boundary conditions 0, 1, 127, 136 and
-  // 255 as well.
-  wsp_decode_test(MMS.StatusValue, [0], null, "CodeError");
-  wsp_decode_test(MMS.StatusValue, [1], null, "CodeError");
-  wsp_decode_test(MMS.StatusValue, [127], null, "CodeError");
-  for (let i = 128; i <= 135; i++) {
-    wsp_decode_test(MMS.StatusValue, [i], i);
-  }
-  wsp_decode_test(MMS.StatusValue, [136], null, "CodeError");
-  wsp_decode_test(MMS.StatusValue, [255], null, "CodeError");
-
-  run_next_test();
-});
-
-//// StatusValue.encode ////
-
-add_test(function test_StatusValue_encode() {
-  // Valid codes are 128 - 135. Check boundary conditions 0, 1, 127, 136 and
-  // 255 as well.
-  wsp_encode_test(MMS.StatusValue, 0, null, "CodeError");
-  wsp_encode_test(MMS.StatusValue, 1, null, "CodeError");
-  wsp_encode_test(MMS.StatusValue, 127, null, "CodeError");
-  for (let i = 128; i <= 135; i++) {
-    wsp_encode_test(MMS.StatusValue, i, [i]);
-  }
-  wsp_encode_test(MMS.StatusValue, 136, null, "CodeError");
-  wsp_encode_test(MMS.StatusValue, 255, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: PduHelper
-//
-
-//// PduHelper.parseHeaders ////
-
-add_test(function test_PduHelper_parseHeaders() {
-  function parse(input, expect, exception) {
-    let data = {array: input, offset: 0};
-    do_check_throws(wsp_test_func.bind(null, MMS.PduHelper.parseHeaders, data, expect),
-                    exception);
-  }
-
-  // Parse ends with Content-Type
-  let expect = {};
-  expect["x-mms-mms-version"] = MMS_VERSION_1_3;
-  expect["content-type"] = {
-    media: "application/vnd.wap.multipart.related",
-    params: null,
-  };
-  parse([0x80 | 0x0D, 0x80 | MMS_VERSION_1_3,   // X-Mms-Mms-Version: 1.3
-         0x80 | 0x04, 0x80 | 0x33,          // Content-Type: application/vnd.wap.multipart.related
-         0x80 | 0x0C, MMS_PDU_TYPE_SEND_REQ // X-Mms-Message-Type: M-Send.req
-        ], expect);
-
-  // Parse header fields with multiple entries
-  expect = {
-    to: [
-      { address: "+123", type: "PLMN" },
-      { address: "+456", type: "num" },
-    ],
-  };
-  expect["content-type"] = {
-    media: "application/vnd.wap.multipart.related",
-    params: null,
-  };
-  parse(Array.concat([0x80 | 0x17]).concat(strToCharCodeArray("+123/TYPE=PLMN"))
-             .concat([0x80 | 0x17]).concat(strToCharCodeArray("+456"))
-             .concat([0x80 | 0x04, 0x80 | 0x33]),
-        expect);
-
-  run_next_test();
-});
-
-//// PduHelper.encodeHeader ////
-
-add_test(function test_PduHelper_encodeHeader() {
-  function func(name, data, headers) {
-    MMS.PduHelper.encodeHeader(data, headers, name);
-
-    // Remove extra space consumed during encoding.
-    while (data.array.length > data.offset) {
-      data.array.pop();
-    }
-
-    return data.array;
-  }
-
-  // Encode header fields with multiple entries
-  let headers = {
-    to: [
-      { address: "+123", type: "PLMN" },
-      { address: "+456", type: "num" },
-    ],
-  };
-  wsp_encode_test_ex(func.bind(null, "to"), headers,
-                     Array.concat([0x80 | 0x17]).concat(strToCharCodeArray("+123/TYPE=PLMN"))
-                          .concat([0x80 | 0x17]).concat(strToCharCodeArray("+456")));
-
-  run_next_test();
-});
-
-//// PduHelper.encodeHeaderIfExists ////
-
-add_test(function test_PduHelper_encodeHeaderIfExists() {
-  function func(name, data, headers) {
-    MMS.PduHelper.encodeHeaderIfExists(data, headers, name);
-
-    // Remove extra space consumed during encoding.
-    while (data.array.length > data.offset) {
-      data.array.pop();
-    }
-
-    return data.array;
-  }
-
-  wsp_encode_test_ex(func.bind(null, "to"), {}, []);
-
-  run_next_test();
-});
-
-//// PduHelper.encodeHeaders ////
-
-add_test(function test_PduHelper_encodeHeaders() {
-  function func(data, headers) {
-    MMS.PduHelper.encodeHeaders(data, headers);
-
-    // Remove extra space consumed during encoding.
-    while (data.array.length > data.offset) {
-      data.array.pop();
-    }
-
-    return data.array;
-  }
-
-  let headers = {};
-  headers["x-mms-message-type"] = MMS_PDU_TYPE_SEND_REQ;
-  headers["x-mms-mms-version"] = MMS_VERSION_1_3;
-  headers["x-mms-transaction-id"] = "asdf";
-  headers["to"] = { address: "+123", type: "PLMN" };
-  headers["content-type"] = {
-    media: "application/vnd.wap.multipart.related",
-  };
-  wsp_encode_test_ex(func, headers,
-                     Array.concat([0x80 | 0x0C, MMS_PDU_TYPE_SEND_REQ])
-                          .concat([0x80 | 0x18]).concat(strToCharCodeArray(headers["x-mms-transaction-id"]))
-                          .concat([0x80 | 0x0D, 0x80 | MMS_VERSION_1_3])
-                          .concat([0x80 | 0x17]).concat(strToCharCodeArray("+123/TYPE=PLMN"))
-                          .concat([0x80 | 0x04, 0x80 | 0x33]));
-
-  run_next_test();
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/xpcshell/test_mms_service.js
+++ /dev/null
@@ -1,139 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function newMmsTransactionHelper() {
-  let MMS_Service = {};
-  subscriptLoader.loadSubScript("resource://gre/components/MmsService.js", MMS_Service);
-  MMS_Service.debug = do_print;
-  return MMS_Service.gMmsTransactionHelper;
-}
-var CallFunc = newMmsTransactionHelper();
-function run_test() {
-  run_next_test();
-}
-
-//
-// Test target: checkMaxValuesParameters
-//
-
-//// Test Long Subject field ////
-//// @see OMA-ETS-MMS_CON-V1_3-20080128-C 5.1.1.1.10 MMS-1.3-con-171 ////
-
-add_test(function test_LongSubjectField() {
-  let msg = {};
-  msg.headers = {};
-  // Test for normal TextString
-  msg.headers["subject"] = "abcdefghijklmnopqrstuvwxyz0123456789/-+@?";
-  do_check_eq(CallFunc.checkMaxValuesParameters(msg), false);
-
-  run_next_test();
-});
-
-//// Test recipient field length
-
-add_test(function test_LongRecipientField() {
-  let msg = {};
-  msg.headers = {};
-  msg.headers["to"] = [
-    { address:
-      "abcdefghijklmnopqrstuvwxyz0123456789/-+@?" +
-      "abcdefghijklmnopqrstuvwxyz0123456789/-+@?" +
-      "abcdefghijklmnopqrstuvwxyz0123456789/-+@?" +
-      "abcdefghijklmnopqrstuvwxyz0123456789/-+@?" +
-      "abcdefghijklmnopqrstuvwxyz0123456789/-+@?" +
-      "abcdefghijklmnopqrstuvwxyz0123456789/-+@?" +
-      "abcdefghijklmnopqrstuvwxyz0123456789/-+@?" +
-      "abcdefghijklmnopqrstuvwxyz",
-      type: "PLMN" },
-  ];
-  do_check_eq(CallFunc.checkMaxValuesParameters(msg), false);
-
-  run_next_test();
-});
-
-
-add_test(function test_checkMaxValuesParameters() {
-  let msg = {};
-  msg.headers = {};
-  msg.headers["cc"] = [
-    { address: "+789", type: "PLMN" },
-    { address: "+119", type: "num" },
-    { address: "Joe2 User " +
-               "<abcdefghijklmnopqrstuvwxyz0123456789" +
-               "abcdefghijklmnopqrstuvwxyz0123456789@" +
-               "abcdefghijklmnopqrstuvwxyz0123456789" +
-               "abcdefghijklmnopqrstuvwxyz0123456789." +
-               "abcdefghijklmnopqrstuvwxyz0123456789" +
-               "abcdefghijklmnopqrstuvwxyz0123456789" +
-               "abcdefghijklmnopqrstuvwxyz0123456789->"
-      , type: "email" },
-  ];
-  do_check_eq(CallFunc.checkMaxValuesParameters(msg), false);
-
-  run_next_test();
-});
-
-//// Test total recipient count over 20
-
-add_test(function test_TotalRecipientCount() {
-  let msg = {};
-  msg.headers = {};
-  do_check_eq(CallFunc.checkMaxValuesParameters(msg), false);
-
-  msg.headers["to"] = [
-    { address: "+123", type: "PLMN" },
-    { address: "+456", type: "num" },
-    { address: "Joe User <joe@user.org>", type: "email" },
-    { address: "+123", type: "PLMN" },
-    { address: "+456", type: "num" },
-    { address: "Joe User <joe@user.org>", type: "email" },
-    { address: "+123", type: "PLMN" },
-  ];
-  msg.headers["cc"] = [
-    { address: "+789", type: "PLMN" },
-    { address: "+119", type: "num" },
-    { address: "Joe2 User <joe2@user.org>", type: "email" },
-    { address: "+789", type: "PLMN" },
-    { address: "+119", type: "num" },
-    { address: "Joe2 User <joe2@user.org>", type: "email" },
-    { address: "+789", type: "PLMN" },
-  ];
-  msg.headers["bcc"] = [
-    { address: "+110", type: "num" },
-    { address: "Joe3 User <joe2@user.org>", type: "email" },
-    { address: "Joe2 User <joe2@user.org>", type: "email" },
-    { address: "+789", type: "PLMN" },
-    { address: "+119", type: "num" },
-    { address: "Joe2 User <joe2@user.org>", type: "email" },
-    { address: "+789", type: "PLMN" },
-  ];
-  do_check_eq(CallFunc.checkMaxValuesParameters(msg), false);
-
-  run_next_test();
-});
-
-////Test name parameter in content-type field of multi-parts
-
-add_test(function test_NameParameterInContentType() {
-  let msg = {};
-  msg.headers = {};
-  msg.headers["to"] = [
-                       { address: "Joe User <joe@user.org>", type: "email" },
-                      ];
-  let params = {};
-  params["name"] = "abcdefghijklmnopqrstuvwxyz0123456789/-+@?";
-  let headers = {};
-  headers["content-type"] = {
-    media: null,
-    params: params,
-  };
-  msg.parts = new Array(1);
-  msg.parts[0] = {
-    index: 0,
-    headers: headers,
-    content: null,
-  };
-  do_check_eq(CallFunc.checkMaxValuesParameters(msg), false);
-
-  run_next_test();
-});
\ No newline at end of file
deleted file mode 100644
--- a/dom/mobilemessage/tests/xpcshell/test_sms_segment_helper.js
+++ /dev/null
@@ -1,192 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "gSmsSegmentHelper", function() {
-  let ns = {};
-  Cu.import("resource://gre/modules/SmsSegmentHelper.jsm", ns);
-  return ns.SmsSegmentHelper;
-});
-
-const ESCAPE = "\uffff";
-const RESCTL = "\ufffe";
-const SP = " ";
-
-function run_test() {
-  run_next_test();
-}
-
-/**
- * Verify SmsSegmentHelper#calculateUserDataLength handles national language
- * selection correctly.
- */
-add_test(function test_SmsSegmentHelper_calculateUserDataLength() {
-  function test_calc(str, expected, enabledGsmTableTuples, strict7BitEncoding) {
-    gSmsSegmentHelper.enabledGsmTableTuples = enabledGsmTableTuples;
-    let options = gSmsSegmentHelper.calculateUserDataLength(str, strict7BitEncoding);
-
-    do_check_eq(expected[0], options.dcs);
-    do_check_eq(expected[1], options.encodedFullBodyLength);
-    do_check_eq(expected[2], options.userDataHeaderLength);
-    do_check_eq(expected[3], options.langIndex);
-    do_check_eq(expected[4], options.langShiftIndex);
-  }
-
-  // Test UCS fallback
-  // - No any default enabled nl tables
-  test_calc("A", [PDU_DCS_MSG_CODING_16BITS_ALPHABET, 2, 0,], []);
-  // - Character not defined in enabled nl tables.
-  //   ("\u4e00" -> '一' is one in Chinese).
-  test_calc("\u4e00", [PDU_DCS_MSG_CODING_16BITS_ALPHABET, 2, 0,], [[2, 2]]);
-
-  // With GSM default nl tables
-  test_calc("A", [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 1, 0, 0, 0], [[0, 0]]);
-  // - SP is defined in both locking/single shift tables, should be directly
-  //   encoded.
-  test_calc(SP, [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 1, 0, 0, 0], [[0, 0]]);
-  // - '^' is only defined in single shift table, should be encoded as
-  //   <escape>^.
-  test_calc("^", [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 2, 0, 0, 0], [[0, 0]]);
-
-  // Test userDataHeaderLength calculation
-  // - Header contains both IEIs
-  test_calc("A", [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 1, 6, 1, 1], [[1, 1]]);
-  // - Header contains only locking shift table IEI
-  test_calc("A", [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 1, 3, 1, 0], [[1, 0]]);
-  // - Header contains only single shift table IEI
-  test_calc("^", [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 2, 3, 0, 1], [[0, 1]]);
-
-  // Test minimum cost nl tables selection
-  // - '\u00e7' -> 'ç' is defined in Turkish locking shift table
-  test_calc("\u00e7", [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 1, 3, 1, 0], [[1, 0], [2, 0]]);
-  test_calc("\u00e7", [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 1, 3, 1, 0], [[2, 0], [1, 0]]);
-  // - '\u09fa' -> '৺' is defined in Bengali single shift table
-  test_calc("\u09fa", [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 2, 6, 2, 4], [[2, 0], [2, 4]]);
-  test_calc("\u09fa", [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 2, 6, 2, 4], [[2, 4], [2, 0]]);
-  // - '\u00e7' -> 'ç' is defined in both Turkish locking shift table and
-  // Spanish single shift table.
-  test_calc("\u00e7", [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 1, 3, 1, 0], [[1, 0], [2, 2]]);
-  test_calc("\u00e7", [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 1, 3, 1, 0], [[2, 2], [1, 0]]);
-
-  // Test Bug 733981
-  // - Case 1, headerLen is in octets, not septets. "\\" is defined in default
-  //   single shift table and Portuguese locking shift table. The original code
-  //   will add headerLen 7(octets), which should be 8(septets), to calculated
-  //   cost and gets 14, which should be 15 in total for the first run. As for
-  //   the second run, it will be undoubtedly 14 in total. With correct fix,
-  //   the best choice should be the second one.
-  test_calc("\\\\\\\\\\\\\\",
-            [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 14, 0, 0, 0], [[3, 1], [0, 0]]);
-  // - Case 2, possible early return non-best choice. The original code will
-  //   get total cost 6 in the first run and returns immediately. With correct
-  //   fix, the best choice should be the second one.
-  test_calc(ESCAPE + ESCAPE + ESCAPE + ESCAPE + ESCAPE + "\\",
-            [PDU_DCS_MSG_CODING_7BITS_ALPHABET, 2, 0, 0, 0], [[3, 0], [0, 0]]);
-
-  // Test Bug 790192: support strict GSM SMS 7-Bit encoding
-  let str = "", gsmLen = 0, udhl = 0;
-  for (let c in GSM_SMS_STRICT_7BIT_CHARMAP) {
-    str += c;
-    if (PDU_NL_LOCKING_SHIFT_TABLES.indexOf(GSM_SMS_STRICT_7BIT_CHARMAP[c])) {
-      gsmLen += 1;
-    } else {
-      gsmLen += 2;
-    }
-  }
-  if (str.length > PDU_MAX_USER_DATA_UCS2) {
-    udhl = 5;
-  }
-  test_calc(str, [PDU_DCS_MSG_CODING_7BITS_ALPHABET, gsmLen, 0, 0, 0], [[0, 0]], true);
-  test_calc(str, [PDU_DCS_MSG_CODING_16BITS_ALPHABET, str.length * 2, udhl], [[0, 0]]);
-
-  run_next_test();
-});
-
-function generateStringOfLength(str, length) {
-  while (str.length < length) {
-    if (str.length < (length / 2)) {
-      str = str + str;
-    } else {
-      str = str + str.substr(0, length - str.length);
-    }
-  }
-
-  return str;
-}
-
-/**
- * Verify SmsSegmentHelper#calculateUserDataLength7Bit multipart handling.
- */
-add_test(function test_SmsSegmentHelper_calculateUserDataLength7Bit_multipart() {
-  function test_calc(str, expected) {
-    let options = gSmsSegmentHelper.calculateUserDataLength7Bit(str);
-
-    do_check_eq(expected[0], options.encodedFullBodyLength);
-    do_check_eq(expected[1], options.userDataHeaderLength);
-    do_check_eq(expected[2], options.segmentMaxSeq);
-  }
-
-  test_calc(generateStringOfLength("A", PDU_MAX_USER_DATA_7BIT),
-            [PDU_MAX_USER_DATA_7BIT, 0, 1]);
-  test_calc(generateStringOfLength("A", PDU_MAX_USER_DATA_7BIT + 1),
-            [PDU_MAX_USER_DATA_7BIT + 1, 5, 2]);
-
-  run_next_test();
-});
-
-/**
- * Verify SmsSegmentHelper#fragmentText().
- */
-add_test(function test_SmsSegmentHelper_fragmentText7Bit() {
-  function test_calc(str, strict7BitEncoding, expectedSegments) {
-    expectedSegments = expectedSegments || 1;
-    let options = gSmsSegmentHelper.fragmentText(str, null, strict7BitEncoding);
-    do_check_eq(expectedSegments, options.segments.length);
-  }
-
-  // 7-Bit
-
-  // Boundary checks
-  test_calc(generateStringOfLength("A", PDU_MAX_USER_DATA_7BIT), false);
-  test_calc(generateStringOfLength("A", PDU_MAX_USER_DATA_7BIT), true);
-  test_calc(generateStringOfLength("A", PDU_MAX_USER_DATA_7BIT + 1), false, 2);
-  test_calc(generateStringOfLength("A", PDU_MAX_USER_DATA_7BIT + 1), true, 2);
-
-  // Escaped character
-  test_calc(generateStringOfLength("{", PDU_MAX_USER_DATA_7BIT / 2), false);
-  test_calc(generateStringOfLength("{", PDU_MAX_USER_DATA_7BIT / 2 + 1), false, 2);
-  // Escaped character cannot be separated
-  test_calc(generateStringOfLength("{", (PDU_MAX_USER_DATA_7BIT - 7) * 2 / 2), false, 3);
-
-  // Test headerLen, 7 = Math.ceil(6 * 8 / 7), 6 = headerLen + 1
-  test_calc(generateStringOfLength("A", PDU_MAX_USER_DATA_7BIT - 7));
-  test_calc(generateStringOfLength("A", (PDU_MAX_USER_DATA_7BIT - 7) * 2), false, 2);
-  test_calc(generateStringOfLength("A", (PDU_MAX_USER_DATA_7BIT - 7) * 3), false, 3);
-
-  // UCS-2
-
-  // Boundary checks
-  test_calc(generateStringOfLength("\ua2db", PDU_MAX_USER_DATA_UCS2));
-  test_calc(generateStringOfLength("\ua2db", PDU_MAX_USER_DATA_UCS2), true);
-  test_calc(generateStringOfLength("\ua2db", PDU_MAX_USER_DATA_UCS2 + 1), false, 2);
-  // Bug 816082: when strict GSM SMS 7-Bit encoding is enabled, replace unicode
-  // chars with '*'.
-  test_calc(generateStringOfLength("\ua2db", PDU_MAX_USER_DATA_UCS2 + 1), true, 1);
-
-  // UCS2 character cannot be separated
-  gSmsSegmentHelper.segmentRef16Bit = true;
-  test_calc(generateStringOfLength("\ua2db", (PDU_MAX_USER_DATA_UCS2 * 2 - 7) * 2 / 2), false, 3);
-  gSmsSegmentHelper.segmentRef16Bit = false;
-
-  // Test Bug 790192: support strict GSM SMS 7-Bit encoding
-  for (let c in GSM_SMS_STRICT_7BIT_CHARMAP) {
-    test_calc(generateStringOfLength(c, PDU_MAX_USER_DATA_7BIT), false, 3);
-    test_calc(generateStringOfLength(c, PDU_MAX_USER_DATA_7BIT), true);
-    test_calc(generateStringOfLength(c, PDU_MAX_USER_DATA_UCS2), false);
-  }
-
-  run_next_test();
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/xpcshell/test_smsservice_createsmsmessage.js
+++ /dev/null
@@ -1,234 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const ICC_ID = "123456789";
-
-function do_check_throws(f, result, stack) {
-  if (!stack) {
-    stack = Components.stack.caller;
-  }
-
-  try {
-    f();
-  } catch (exc) {
-    if (exc.result == result)
-      return;
-    do_throw("expected result " + result + ", caught " + exc, stack);
-  }
-  do_throw("expected result " + result + ", none thrown", stack);
-}
-
-var gMobileMessageService = Cc["@mozilla.org/mobilemessage/mobilemessageservice;1"]
-                            .getService(Ci.nsIMobileMessageService);
-function newMessage() {
-  return gMobileMessageService.createSmsMessage.apply(gMobileMessageService, arguments);
-}
-
-function run_test() {
-  run_next_test();
-}
-
-/**
- * Ensure an SmsMessage object created has sensible initial values.
- */
-add_test(function test_interface() {
-  let sms = newMessage(null, null, ICC_ID, "sent", "success", null, null, null,
-                       "normal", Date.now(), Date.now(), Date.now(), true);
-  do_check_true(sms instanceof Ci.nsISmsMessage);
-  do_check_eq(sms.id, 0);
-  do_check_eq(sms.threadId, 0);
-  do_check_eq(sms.iccId, ICC_ID);
-  do_check_eq(sms.delivery, "sent");
-  do_check_eq(sms.deliveryStatus, "success");
-  do_check_eq(sms.receiver, null);
-  do_check_eq(sms.sender, null);
-  do_check_eq(sms.body, null);
-  do_check_eq(sms.messageClass, "normal");
-  do_check_true(sms.read);
-  run_next_test();
-});
-
-/**
- * Test if ICC ID is null when it's not available.
- */
-add_test(function test_icc_id_not_available() {
-  let sms = newMessage(null, null, null, "sent", "success", null, null, null,
-                       "normal", Date.now(), Date.now(), Date.now(), true);
-  do_check_true(sms instanceof Ci.nsISmsMessage);
-  do_check_eq(sms.id, 0);
-  do_check_eq(sms.threadId, 0);
-  do_check_eq(sms.iccId, null);
-  do_check_eq(sms.delivery, "sent");
-  do_check_eq(sms.deliveryStatus, "success");
-  do_check_eq(sms.receiver, null);
-  do_check_eq(sms.sender, null);
-  do_check_eq(sms.body, null);
-  do_check_eq(sms.messageClass, "normal");
-  do_check_true(sms.read);
-  run_next_test();
-});
-
-/**
- * Verify that attributes are read-only.
- */
-add_test(function test_readonly_attributes() {
-  let sms = newMessage(null, null, ICC_ID, "sent", "success", null, null, null,
-                       "normal", Date.now(), Date.now(), Date.now(), true);
-
-  sms.id = 1;
-  do_check_eq(sms.id, 0);
-
-  sms.threadId = 1;
-  do_check_eq(sms.threadId, 0);
-
-  sms.iccId = "987654321";
-  do_check_eq(sms.iccId, ICC_ID);
-
-  sms.delivery = "received";
-  do_check_eq(sms.delivery, "sent");
-
-  sms.deliveryStatus = "pending";
-  do_check_eq(sms.deliveryStatus, "success");
-
-  sms.receiver = "a receiver";
-  do_check_eq(sms.receiver, null);
-
-  sms.sender = "a sender";
-  do_check_eq(sms.sender, null);
-
-  sms.body = "a body";
-  do_check_eq(sms.body, null);
-
-  sms.messageClass = "class-0";
-  do_check_eq(sms.messageClass, "normal");
-
-  let oldTimestamp = sms.timestamp;
-  sms.timestamp = Date.now();
-  do_check_eq(sms.timestamp, oldTimestamp);
-
-  let oldSentTimestamp = sms.sentTimestamp;
-  sms.sentTimestamp = Date.now();
-  do_check_eq(sms.sentTimestamp, oldSentTimestamp);
-
-  let oldDeliveryTimestamp = sms.deliveryTimestamp;
-  sms.deliveryTimestamp = Date.now();
-  do_check_eq(sms.deliveryTimestamp, oldDeliveryTimestamp);
-
-  sms.read = false;
-  do_check_true(sms.read);
-
-  run_next_test();
-});
-
-/**
- * Test supplying the timestamp as a number of milliseconds.
- */
-add_test(function test_timestamp_number() {
-  let ts = Date.now();
-  let sms = newMessage(42, 1, ICC_ID, "sent", "success", "the sender", "the receiver",
-                       "the body", "normal", ts, ts, ts, true);
-  do_check_eq(sms.id, 42);
-  do_check_eq(sms.threadId, 1);
-  do_check_eq(sms.iccId, ICC_ID);
-  do_check_eq(sms.delivery, "sent");
-  do_check_eq(sms.deliveryStatus, "success");
-  do_check_eq(sms.sender, "the sender");
-  do_check_eq(sms.receiver, "the receiver");
-  do_check_eq(sms.body, "the body");
-  do_check_eq(sms.messageClass, "normal");
-  do_check_eq(sms.timestamp, ts);
-  do_check_eq(sms.sentTimestamp, ts);
-  do_check_eq(sms.deliveryTimestamp, ts);
-  do_check_true(sms.read);
-  run_next_test();
-});
-
-/**
- * Test supplying the timestamp as a Date object, which will be automatically
- * casted to unsigned long long.
- */
-add_test(function test_timestamp_date() {
-  let date = new Date();
-  let sms = newMessage(42, 1, ICC_ID, "sent", "success", "the sender", "the receiver",
-                       "the body", "normal", date, date, date, true);
-  do_check_eq(sms.id, 42);
-  do_check_eq(sms.threadId, 1);
-  do_check_eq(sms.iccId, ICC_ID);
-  do_check_eq(sms.delivery, "sent");
-  do_check_eq(sms.deliveryStatus, "success");
-  do_check_eq(sms.sender, "the sender");
-  do_check_eq(sms.receiver, "the receiver");
-  do_check_eq(sms.body, "the body");
-  do_check_eq(sms.messageClass, "normal");
-  do_check_eq(sms.timestamp, date.getTime());
-  do_check_eq(sms.sentTimestamp, date.getTime());
-  do_check_eq(sms.deliveryTimestamp, date.getTime());
-  do_check_true(sms.read);
-  run_next_test();
-});
-
-/**
- * Test that an invalid delivery string is not accepted.
- */
-add_test(function test_invalid_delivery_string() {
-  do_check_throws(function() {
-    newMessage(42, 1, ICC_ID, "this is invalid", "pending", "the sender",
-               "the receiver", "the body", "normal", Date.now(), 0, 0, true);
-  }, Cr.NS_ERROR_INVALID_ARG);
-  run_next_test();
-});
-
-/**
- * Test that a number is not accepted for the 'delivery' argument.
- */
-add_test(function test_invalid_delivery_string() {
-  do_check_throws(function() {
-    newMessage(42, 1, ICC_ID, 1, "pending", "the sender", "the receiver", "the body",
-               "normal", Date.now(), 0, 0, true);
-  }, Cr.NS_ERROR_INVALID_ARG);
-  run_next_test();
-});
-
-/**
- * Test that an invalid delivery status string is not accepted.
- */
-add_test(function test_invalid_delivery_status_string() {
-  do_check_throws(function() {
-    newMessage(42, 1, ICC_ID, "sent", "this is invalid", "the sender", "the receiver",
-               "the body", "normal", Date.now(), Date.now(), 0, true);
-  }, Cr.NS_ERROR_INVALID_ARG);
-  run_next_test();
-});
-
-/**
- * Test that a number is not accepted for the 'deliveryStatus' argument.
- */
-add_test(function test_invalid_delivery_status_string() {
-  do_check_throws(function() {
-    newMessage(42, 1, ICC_ID, "sent", 1, "the sender", "the receiver", "the body",
-               "normal", Date.now(), Date.now(), 0, true);
-  }, Cr.NS_ERROR_INVALID_ARG);
-  run_next_test();
-});
-
-/**
- * Test that an invalid message class string is not accepted.
- */
-add_test(function test_invalid_message_class_string() {
-  do_check_throws(function() {
-    newMessage(42, 1, ICC_ID, "sent", "success", "the sender", "the receiver",
-               "the body", "this is invalid", Date.now(), Date.now(), Date.now(), true);
-  }, Cr.NS_ERROR_INVALID_ARG);
-  run_next_test();
-});
-
-/**
- * Test that a number is not accepted for the 'messageClass' argument.
- */
-add_test(function test_invalid_message_class_string() {
-  do_check_throws(function() {
-    newMessage(42, 1, ICC_ID, "sent", "success", "the sender", "the receiver",
-               "the body", 1, Date.now(), Date.now(), Date.now(), true);
-  }, Cr.NS_ERROR_INVALID_ARG);
-  run_next_test();
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/xpcshell/test_wsp_pdu_helper.js
+++ /dev/null
@@ -1,559 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var WSP = {};
-subscriptLoader.loadSubScript("resource://gre/modules/WspPduHelper.jsm", WSP);
-WSP.debug = do_print;
-
-function run_test() {
-  run_next_test();
-}
-
-//
-// Test target: skipValue()
-//
-
-add_test(function test_skipValue() {
-  function func(data) {
-    return WSP.skipValue(data);
-  }
-
-  // Test for zero-valued first octet:
-  wsp_decode_test_ex(func, [0], null);
-  // Test first octet < 31
-  wsp_decode_test_ex(func, [1, 2], [2]);
-  // Test first octet = 31
-  wsp_decode_test_ex(func, [31, 0], null);
-  wsp_decode_test_ex(func, [31, 1, 2], [2]);
-  // Test first octet <= 127
-  wsp_decode_test_ex(func, strToCharCodeArray("Hello world!"), "Hello world!");
-  // Test first octet >= 128
-  wsp_decode_test_ex(func, [0x80 | 0x01], 0x01);
-
-  run_next_test();
-});
-
-//
-// Test target: ConstrainedEncoding
-//
-
-//// ConstrainedEncoding.decode ////
-
-add_test(function test_ConstrainedEncoding_decode() {
-  wsp_decode_test(WSP.ConstrainedEncoding, [0x80], 0);
-  wsp_decode_test(WSP.ConstrainedEncoding, [32, 0], " ");
-
-  run_next_test();
-});
-
-//// ConstrainedEncoding.encode ////
-
-add_test(function test_ConstrainedEncoding_encode() {
-  wsp_encode_test(WSP.ConstrainedEncoding, 0, [0x80 | 0]);
-  wsp_encode_test(WSP.ConstrainedEncoding, "A", [65, 0]);
-
-  run_next_test();
-});
-
-//
-// Test target: ValueLength
-//
-
-//// ValueLength.decode ////
-
-add_test(function test_ValueLength_decode() {
-  for (let i = 0; i < 256; i++) {
-    if (i < 31) {
-      wsp_decode_test(WSP.ValueLength, [i, 0x8F, 0x7F], i);
-    } else if (i == 31) {
-      wsp_decode_test(WSP.ValueLength, [i, 0x8F, 0x7F], 0x7FF);
-    } else {
-      wsp_decode_test(WSP.ValueLength, [i, 0x8F, 0x7F], null, "CodeError");
-    }
-  }
-
-  run_next_test();
-});
-
-//// ValueLength.encode ////
-
-add_test(function test_ValueLength_encode() {
-  for (let i = 0; i < 256; i++) {
-    if (i < 31) {
-      wsp_encode_test(WSP.ValueLength, i, [i]);
-    } else if (i < 128) {
-      wsp_encode_test(WSP.ValueLength, i, [31, i]);
-    } else {
-      wsp_encode_test(WSP.ValueLength, i, [31, (0x80 | (i / 128)), i % 128]);
-    }
-  }
-
-  run_next_test();
-});
-
-//
-// Test target: NoValue
-//
-
-//// NoValue.decode ////
-
-add_test(function test_NoValue_decode() {
-  wsp_decode_test(WSP.NoValue, [0], null);
-  for (let i = 1; i < 256; i++) {
-    wsp_decode_test(WSP.NoValue, [i], null, "CodeError");
-  }
-
-  run_next_test();
-});
-
-//// NoValue.encode ////
-
-add_test(function test_NoValue_encode() {
-  wsp_encode_test(WSP.NoValue, undefined, [0]);
-  wsp_encode_test(WSP.NoValue, null, [0]);
-  wsp_encode_test(WSP.NoValue, 0, null, "CodeError");
-  wsp_encode_test(WSP.NoValue, "", null, "CodeError");
-  wsp_encode_test(WSP.NoValue, [], null, "CodeError");
-  wsp_encode_test(WSP.NoValue, {}, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: DateValue
-//
-
-//// DateValue.decode ////
-
-add_test(function test_DateValue_decode() {
-  wsp_decode_test(WSP.DateValue, [0, 0], null, "CodeError");
-  wsp_decode_test(WSP.DateValue, [1, 0x80], new Date(0x80 * 1000));
-  wsp_decode_test(WSP.DateValue, [31], null, "CodeError");
-
-  run_next_test();
-});
-
-//// DateValue.encode ////
-
-add_test(function test_DateValue_encode() {
-  wsp_encode_test(WSP.DateValue, new Date(0x80 * 1000), [1, 0x80]);
-
-  run_next_test();
-});
-
-//
-// Test target: DeltaSecondsValue
-//
-// DeltaSecondsValue is only an alias of IntegerValue.
-
-//
-// Test target: QValue
-//
-
-//// QValue.decode ////
-
-add_test(function test_QValue_decode() {
-  wsp_decode_test(WSP.QValue, [0], null, "CodeError");
-  wsp_decode_test(WSP.QValue, [1], 0);
-  wsp_decode_test(WSP.QValue, [100], 0.99);
-  wsp_decode_test(WSP.QValue, [101], 0.001);
-  wsp_decode_test(WSP.QValue, [0x88, 0x4B], 0.999);
-  wsp_decode_test(WSP.QValue, [0x88, 0x4C], null, "CodeError");
-
-  run_next_test();
-});
-
-//// QValue.encode ////
-
-add_test(function test_QValue_encode() {
-  wsp_encode_test(WSP.QValue, 0, [1]);
-  wsp_encode_test(WSP.QValue, 0.99, [100]);
-  wsp_encode_test(WSP.QValue, 0.001, [101]);
-  wsp_encode_test(WSP.QValue, 0.999, [0x88, 0x4B]);
-  wsp_encode_test(WSP.QValue, 1, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: VersionValue
-//
-
-//// VersionValue.decode ////
-
-add_test(function test_VersionValue_decode() {
-  for (let major = 1; major < 8; major++) {
-    let version = (major << 4) | 0x0F;
-    wsp_decode_test(WSP.VersionValue, [0x80 | version], version);
-    wsp_decode_test(WSP.VersionValue, [major + 0x30, 0], version);
-
-    for (let minor = 0; minor < 15; minor++) {
-      version = (major << 4) | minor;
-      wsp_decode_test(WSP.VersionValue, [0x80 | version], version);
-      if (minor >= 10) {
-        wsp_decode_test(WSP.VersionValue, [major + 0x30, 0x2E, 0x31, (minor - 10) + 0x30, 0], version);
-      } else {
-        wsp_decode_test(WSP.VersionValue, [major + 0x30, 0x2E, minor + 0x30, 0], version);
-      }
-    }
-  }
-
-  run_next_test();
-});
-
-//// VersionValue.encode ////
-
-add_test(function test_VersionValue_encode() {
-  for (let major = 1; major < 8; major++) {
-    let version = (major << 4) | 0x0F;
-    wsp_encode_test(WSP.VersionValue, version, [0x80 | version]);
-
-    for (let minor = 0; minor < 15; minor++) {
-      version = (major << 4) | minor;
-      wsp_encode_test(WSP.VersionValue, version, [0x80 | version]);
-    }
-  }
-
-  run_next_test();
-});
-
-//
-// Test target: UriValue
-//
-
-//// UriValue.decode ////
-
-add_test(function test_UriValue_decode() {
-  wsp_decode_test(WSP.UriValue, [97], null, "RangeError");
-  wsp_decode_test(WSP.UriValue, [0], "");
-  wsp_decode_test(WSP.UriValue, [65, 0], "A");
-
-  run_next_test();
-});
-
-//
-// Test target: TypeValue
-//
-
-//// TypeValue.decode ////
-
-add_test(function test_TypeValue_decode() {
-  // Test for string-typed return value from ConstrainedEncoding
-  wsp_decode_test(WSP.TypeValue, [65, 0], "a");
-  // Test for number-typed return value from ConstrainedEncoding
-  wsp_decode_test(WSP.TypeValue, [0x33 | 0x80],
-                  "application/vnd.wap.multipart.related");
-  wsp_decode_test(WSP.TypeValue, [0x1d | 0x80], "image/gif");
-  // Test for NotWellKnownEncodingError
-  wsp_decode_test(WSP.TypeValue, [0x59 | 0x80], null, "NotWellKnownEncodingError");
-
-  run_next_test();
-});
-
-//// TypeValue.encode ////
-
-add_test(function test_TypeValue_encode() {
-  wsp_encode_test(WSP.TypeValue, "no/such.type",
-                  [110, 111, 47, 115, 117, 99, 104, 46, 116, 121, 112, 101, 0]);
-  wsp_encode_test(WSP.TypeValue, "application/vnd.wap.multipart.related",
-                  [0x33 | 0x80]);
-  wsp_encode_test(WSP.TypeValue, "image/gif",
-                  [0x1d | 0x80]);
-
-  run_next_test();
-});
-
-//
-// Test target: AcceptCharsetValue
-//
-
-//// AcceptCharsetValue.decode ////
-
-add_test(function test_AcceptCharsetValue_decode() {
-  wsp_decode_test(WSP.AcceptCharsetValue, [0xFF], null, "CodeError");
-  // Test for Any-Charset
-  wsp_decode_test(WSP.AcceptCharsetValue, [128], {charset: "*"});
-  // Test for Constrained-Charset
-  wsp_decode_test(WSP.AcceptCharsetValue, [65, 0], {charset: "A"});
-  let entry = WSP.WSP_WELL_KNOWN_CHARSETS["utf-8"];
-  wsp_decode_test(WSP.AcceptCharsetValue, [entry.number | 0x80], {charset: entry.name});
-
-  // Test for Accept-Charset-General-Form
-  wsp_decode_test(WSP.AcceptCharsetValue, [1, 128], {charset: "*"});
-  entry = WSP.WSP_WELL_KNOWN_CHARSETS["utf-8"];
-  wsp_decode_test(WSP.AcceptCharsetValue, [2, 1, entry.number], {charset: entry.name});
-  wsp_decode_test(WSP.AcceptCharsetValue, [1, entry.number | 0x80], {charset: entry.name});
-  wsp_decode_test(WSP.AcceptCharsetValue, [3, 65, 0, 100], {charset: "A", q: 0.99});
-
-  run_next_test();
-});
-
-//// AcceptCharsetValue.encodeAnyCharset ////
-
-add_test(function test_AcceptCharsetValue_encodeAnyCharset() {
-  function func(data, input) {
-    WSP.AcceptCharsetValue.encodeAnyCharset(data, input);
-    return data.array;
-  }
-
-  wsp_encode_test_ex(func, null, [0x80]);
-  wsp_encode_test_ex(func, undefined, [0x80]);
-  wsp_encode_test_ex(func, {}, [0x80]);
-  wsp_encode_test_ex(func, {charset: null}, [0x80]);
-  wsp_encode_test_ex(func, {charset: "*"}, [0x80]);
-  wsp_encode_test_ex(func, {charset: "en"}, null, "CodeError");
-
-  run_next_test();
-});
-
-//
-// Test target: WellKnownCharset
-//
-
-//// WellKnownCharset.decode ////
-
-add_test(function test_WellKnownCharset_decode() {
-  wsp_decode_test(WSP.WellKnownCharset, [0xFF], null, "NotWellKnownEncodingError");
-  // Test for Any-Charset
-  wsp_decode_test(WSP.WellKnownCharset, [128], {charset: "*"});
-  // Test for number-typed return value from IntegerValue
-  wsp_decode_test(WSP.WellKnownCharset, [1, 3], {charset: "us-ascii"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 4], {charset: "iso-8859-1"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 5], {charset: "iso-8859-2"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 6], {charset: "iso-8859-3"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 7], {charset: "iso-8859-4"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 8], {charset: "iso-8859-5"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 9], {charset: "iso-8859-6"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 10], {charset: "iso-8859-7"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 11], {charset: "iso-8859-8"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 12], {charset: "iso-8859-9"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 13], {charset: "iso-8859-10"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 17], {charset: "shift_jis"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 18], {charset: "euc-jp"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 37], {charset: "iso-2022-kr"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 38], {charset: "euc-kr"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 39], {charset: "iso-2022-jp"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 40], {charset: "iso-2022-jp-2"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 81], {charset: "iso-8859-6-e"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 82], {charset: "iso-8859-6-i"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 84], {charset: "iso-8859-8-e"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 85], {charset: "iso-8859-8-i"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 1000], {charset: "iso-10646-ucs-2"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 1015], {charset: "utf-16"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 2025], {charset: "gb2312"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 2026], {charset: "big5"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 2084], {charset: "koi8-r"});
-  wsp_decode_test(WSP.WellKnownCharset, [1, 2252], {charset: "windows-1252"});
-  wsp_decode_test(WSP.WellKnownCharset, [2, 3, 247], {charset: "utf-16"});
-  // Test for array-typed return value from IntegerValue
-  wsp_decode_test(WSP.WellKnownCharset, [7, 0, 0, 0, 0, 0, 0, 0, 3], null, "CodeError");
-
-  run_next_test();
-});
-
-//// WellKnownCharset.encode ////
-
-add_test(function test_WellKnownCharset_encode() {
-  // Test for Any-charset
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "*"}, [0x80]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "us-ascii"}, [128 + 3]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-1"}, [128 + 4]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-2"}, [128 + 5]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-3"}, [128 + 6]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-4"}, [128 + 7]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-5"}, [128 + 8]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-6"}, [128 + 9]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-7"}, [128 + 10]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-8"}, [128 + 11]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-9"}, [128 + 12]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-10"}, [128 + 13]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "shift_jis"}, [128 + 17]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "euc-jp"}, [128 + 18]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-2022-kr"}, [128 + 37]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "euc-kr"}, [128 + 38]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-2022-jp"}, [128 + 39]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-2022-jp-2"}, [128 + 40]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-6-e"}, [128 + 81]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-6-i"}, [128 + 82]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-8-e"}, [128 + 84]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-8859-8-i"}, [128 + 85]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "UTF-8"}, [128 + 106]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "iso-10646-ucs-2"}, [2, 0x3, 0xe8]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "UTF-16"}, [2, 0x3, 0xf7]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "gb2312"}, [2, 0x7, 0xe9]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "big5"}, [2, 0x7, 0xea]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "koi8-r"}, [2, 0x8, 0x24]);
-  wsp_encode_test(WSP.WellKnownCharset, {charset: "windows-1252"}, [2, 0x8, 0xcc]);
-
-  run_next_test();
-});
-
-//
-// Test target: ContentTypeValue
-//
-
-//// ContentTypeValue.decodeConstrainedMedia ////
-
-add_test(function test_ContentTypeValue_decodeConstrainedMedia() {
-  function func(data) {
-    return WSP.ContentTypeValue.decodeConstrainedMedia(data);
-  }
-
-  // Test for string-typed return value from ConstrainedEncoding
-  wsp_decode_test_ex(func, [65, 0], {media: "a", params: null});
-  // Test for number-typed return value from ConstrainedEncoding
-  for (let ix = 0; ix <WSP.WSP_WELL_KNOWN_CONTENT_TYPES.length ; ++ix) {
-    wsp_decode_test_ex(func, [WSP.WSP_WELL_KNOWN_CONTENT_TYPES[ix].number | 0x80],
-      {media: WSP.WSP_WELL_KNOWN_CONTENT_TYPES[ix].value, params: null});
-  }
-  // Test for NotWellKnownEncodingError
-  wsp_decode_test_ex(func, [0x59 | 0x80], null, "NotWellKnownEncodingError");
-
-  run_next_test();
-});
-
-//// ContentTypeValue.decodeMedia ////
-
-add_test(function test_ContentTypeValue_decodeMedia() {
-  function func(data) {
-    return WSP.ContentTypeValue.decodeMedia(data);
-  }
-
-  // Test for NullTerminatedTexts
-  wsp_decode_test_ex(func, [65, 0], "a");
-  // Test for IntegerValue
-  wsp_decode_test_ex(func, [0x3E | 0x80], "application/vnd.wap.mms-message");
-  wsp_decode_test_ex(func, [0x59 | 0x80], null, "NotWellKnownEncodingError");
-
-  run_next_test();
-});
-
-//// ContentTypeValue.decodeMediaType ////
-
-add_test(function test_ContentTypeValue_decodeMediaType() {
-  wsp_decode_test_ex(function(data) {
-      return WSP.ContentTypeValue.decodeMediaType(data, 1);
-    }, [0x3E | 0x80],
-    {media: "application/vnd.wap.mms-message", params: null}
-  );
-  wsp_decode_test_ex(function(data) {
-      return WSP.ContentTypeValue.decodeMediaType(data, 14);
-    }, [0x3E | 0x80, 1, 0x0A, 60, 115, 109, 105, 108, 62, 0, 65, 0, 66, 0],
-    {media: "application/vnd.wap.mms-message", params: {start: "<smil>", a: "B"}}
-  );
-
-  run_next_test();
-});
-
-//// ContentTypeValue.decodeContentGeneralForm ////
-
-add_test(function test_ContentTypeValue_decodeContentGeneralForm() {
-  wsp_decode_test_ex(function(data) {
-      return WSP.ContentTypeValue.decodeContentGeneralForm(data);
-    }, [14, 0x3E | 0x80, 1, 0x0A, 60, 115, 109, 105, 108, 62, 0, 65, 0, 66, 0],
-    {media: "application/vnd.wap.mms-message", params: {start: "<smil>", a: "B"}}
-  );
-
-  run_next_test();
-});
-
-//// ContentTypeValue.decode ////
-
-add_test(function test_ContentTypeValue_decode() {
-  wsp_decode_test(WSP.ContentTypeValue,
-    [14, 0x3E | 0x80, 1, 0x0A, 60, 115, 109, 105, 108, 62, 0, 65, 0, 66, 0],
-    {media: "application/vnd.wap.mms-message", params: {start: "<smil>", a: "B"}}
-  );
-
-  wsp_decode_test(WSP.ContentTypeValue, [0x33 | 0x80],
-    {media: "application/vnd.wap.multipart.related", params: null}
-  );
-
-  run_next_test();
-});
-
-//// ContentTypeValue.encodeConstrainedMedia ////
-
-add_test(function test_ContentTypeValue_encodeConstrainedMedia() {
-  function func(data, input) {
-    WSP.ContentTypeValue.encodeConstrainedMedia(data, input);
-    return data.array;
-  }
-
-  // Test media type with additional parameters.
-  wsp_encode_test_ex(func, {media: "a", params: [{a: "b"}]}, null, "CodeError");
-  wsp_encode_test_ex(func, {media: "no/such.type"},
-                     [110, 111, 47, 115, 117, 99, 104, 46, 116, 121, 112, 101, 0]);
-  for (let ix = 0; ix <WSP.WSP_WELL_KNOWN_CONTENT_TYPES.length ; ++ix) {
-    wsp_encode_test_ex(func, {media: WSP.WSP_WELL_KNOWN_CONTENT_TYPES[ix].value},
-    [WSP.WSP_WELL_KNOWN_CONTENT_TYPES[ix].number | 0x80]);
-  }
-  wsp_encode_test_ex(func, {media: "TexT/X-hdml"}, [0x04 | 0x80]);
-  wsp_encode_test_ex(func, {media: "appLication/*"}, [0x10 | 0x80]);
-
-  run_next_test();
-});
-
-//// ContentTypeValue.encodeMediaType ////
-
-add_test(function test_ContentTypeValue_encodeMediaType() {
-  function func(data, input) {
-    WSP.ContentTypeValue.encodeMediaType(data, input);
-    return data.array;
-  }
-
-  wsp_encode_test_ex(func, {media: "no/such.type"},
-                     [110, 111, 47, 115, 117, 99, 104, 46, 116, 121, 112, 101, 0]);
-  wsp_encode_test_ex(func, {media: "application/vnd.wap.multipart.related"},
-                     [0x33 | 0x80]);
-  wsp_encode_test_ex(func, {media: "a", params: {b: "c", q: 0}},
-                     [97, 0, 98, 0, 99, 0, 128, 1]);
-
-  run_next_test();
-});
-
-//// ContentTypeValue.encodeContentGeneralForm ////
-
-add_test(function test_ContentTypeValue_encodeContentGeneralForm() {
-  function func(data, input) {
-    WSP.ContentTypeValue.encodeContentGeneralForm(data, input);
-    return data.array;
-  }
-
-  wsp_encode_test_ex(func, {media: "a", params: {b: "c", q: 0}},
-                     [8, 97, 0, 98, 0, 99, 0, 128, 1]);
-
-  run_next_test();
-});
-
-//// ContentTypeValue.encode ////
-
-add_test(function test_ContentTypeValue_encode() {
-  wsp_encode_test(WSP.ContentTypeValue, {media: "no/such.type"},
-                  [110, 111, 47, 115, 117, 99, 104, 46, 116, 121, 112, 101, 0]);
-  wsp_encode_test(WSP.ContentTypeValue,
-                  {media: "application/vnd.wap.multipart.related"},
-                  [0x33 | 0x80]);
-  wsp_encode_test(WSP.ContentTypeValue, {media: "a", params: {b: "c", q: 0}},
-                  [8, 97, 0, 98, 0, 99, 0, 128, 1]);
-
-  run_next_test();
-});
-
-//
-// Test target: ApplicationIdValue
-//
-
-//// ApplicationIdValue.decode ////
-
-add_test(function test_ApplicationIdValue_decode() {
-  wsp_decode_test(WSP.ApplicationIdValue, [0], "");
-  wsp_decode_test(WSP.ApplicationIdValue, [65, 0], "A");
-  wsp_decode_test(WSP.ApplicationIdValue, [97, 0], "a");
-  let entry = WSP.OMNA_PUSH_APPLICATION_IDS["x-wap-application:mms.ua"];
-  wsp_decode_test(WSP.ApplicationIdValue, [entry.number | 0x80], entry.urn);
-  wsp_decode_test(WSP.ApplicationIdValue, [1, entry.number], entry.urn);
-  wsp_decode_test(WSP.ApplicationIdValue, [0xFF], null, "NotWellKnownEncodingError");
-
-  run_next_test();
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/xpcshell/test_wsp_pdu_helper_header.js
+++ /dev/null
@@ -1,221 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var WSP = {};
-subscriptLoader.loadSubScript("resource://gre/modules/WspPduHelper.jsm", WSP);
-WSP.debug = do_print;
-
-function run_test() {
-  run_next_test();
-}
-
-//
-// Test target: ensureHeader
-//
-
-add_test(function test_ensureHeader() {
-  do_check_throws(function() {
-      WSP.ensureHeader({}, "no-such-property");
-    }, "FatalCodeError"
-  );
-
-  run_next_test();
-});
-
-//
-// Test target: Header
-//
-
-//// Header.decode ////
-
-add_test(function test_Header_decode() {
-  wsp_decode_test(WSP.Header, [0x34 | 0x80, 0x80], {name: "push-flag", value: 0});
-  wsp_decode_test(WSP.Header, [65, 0, 66, 0], {name: "a", value: "B"});
-
-  run_next_test();
-});
-
-//
-// Test target: WellKnownHeader
-//
-
-//// WellKnownHeader.decode ////
-
-add_test(function test_WellKnownHeader_decode() {
-  wsp_decode_test(WSP.WellKnownHeader, [0xFF], null, "NotWellKnownEncodingError");
-  let entry = WSP.WSP_HEADER_FIELDS["push-flag"];
-
-  // Test for Short-Integer
-  wsp_decode_test(WSP.WellKnownHeader, [entry.number | 0x80, 0x80],
-                      {name: entry.name, value: 0});
-  // Test for NoValue
-  wsp_decode_test(WSP.WellKnownHeader, [entry.number | 0x80, 0],
-                      {name: entry.name, value: null});
-  // Test for TokenText
-  wsp_decode_test(WSP.WellKnownHeader, [entry.number | 0x80, 65, 0],
-                      {name: entry.name, value: "A"});
-  // Test for QuotedString
-  wsp_decode_test(WSP.WellKnownHeader, [entry.number | 0x80, 34, 128, 0],
-                      {name: entry.name, value: String.fromCharCode(128)});
-  // Test for skipValue
-  wsp_decode_test(WSP.WellKnownHeader, [entry.number | 0x80, 2, 0, 0], null);
-
-  run_next_test();
-});
-
-//
-// Test target: ApplicationHeader
-//
-
-//// ApplicationHeader.decode ////
-
-add_test(function test_ApplicationHeader_decode() {
-  wsp_decode_test(WSP.ApplicationHeader, [5, 0, 66, 0], null, "CodeError");
-  wsp_decode_test(WSP.ApplicationHeader, [65, 0, 66, 0], {name: "a", value: "B"});
-  // Test for skipValue
-  wsp_decode_test(WSP.ApplicationHeader, [65, 0, 2, 0, 0], null);
-
-  run_next_test();
-});
-
-//// ApplicationHeader.encode ////
-
-add_test(function test_ApplicationHeader_encode() {
-  // Test invalid header name string:
-  wsp_encode_test(WSP.ApplicationHeader, {name: undefined, value: "asdf"}, null, "CodeError");
-  wsp_encode_test(WSP.ApplicationHeader, {name: null, value: "asdf"}, null, "CodeError");
-  wsp_encode_test(WSP.ApplicationHeader, {name: "", value: "asdf"}, null, "CodeError");
-  wsp_encode_test(WSP.ApplicationHeader, {name: "a b", value: "asdf"}, null, "CodeError");
-  // Test value string:
-  wsp_encode_test(WSP.ApplicationHeader, {name: "asdf", value: undefined},
-                  strToCharCodeArray("asdf").concat([0]));
-  wsp_encode_test(WSP.ApplicationHeader, {name: "asdf", value: null},
-                  strToCharCodeArray("asdf").concat([0]));
-  wsp_encode_test(WSP.ApplicationHeader, {name: "asdf", value: ""},
-                  strToCharCodeArray("asdf").concat([0]));
-  wsp_encode_test(WSP.ApplicationHeader, {name: "asdf", value: "fdsa"},
-                  strToCharCodeArray("asdf").concat(strToCharCodeArray("fdsa")));
-
-  run_next_test();
-});
-
-//
-// Test target: FieldName
-//
-
-//// FieldName.decode ////
-
-add_test(function test_FieldName_decode() {
-  wsp_decode_test(WSP.FieldName, [0], "");
-  wsp_decode_test(WSP.FieldName, [65, 0], "a");
-  wsp_decode_test(WSP.FieldName, [97, 0], "a");
-  let entry = WSP.WSP_HEADER_FIELDS["content-length"];
-  wsp_decode_test(WSP.FieldName, [entry.number | 0x80], entry.name);
-  wsp_decode_test(WSP.FieldName, [0xFF], null, "NotWellKnownEncodingError");
-
-  run_next_test();
-});
-
-//// FieldName.encode ////
-
-add_test(function test_FieldName_encode() {
-  wsp_encode_test(WSP.FieldName, "", [0]);
-  wsp_encode_test(WSP.FieldName, "date", [0x92]);
-
-  run_next_test();
-});
-
-//
-// Test target: PduHelper
-//
-
-//// PduHelper.parseHeaders ////
-
-add_test(function test_PduHelper_parseHeaders() {
-  wsp_decode_test_ex(function(data) {
-      return WSP.PduHelper.parseHeaders(data, data.array.length);
-    }, [0x80 | 0x05, 2, 0x23, 0x28, 0x80 | 0x2F, 0x80 | 0x04],
-    {"age": 9000, "x-wap-application-id": "x-wap-application:mms.ua"}
-  );
-
-  run_next_test();
-});
-
-//// PduHelper.decodeStringContent ////
-
-add_test(function StringContent_decode() {
-  //Test for utf-8
-  let entry = WSP.WSP_WELL_KNOWN_CHARSETS["utf-8"];
-
-  // "Mozilla" in full width.
-  let str = "\uff2d\uff4f\uff5a\uff49\uff4c\uff4c\uff41";
-
-  let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
-             .createInstance(Ci.nsIScriptableUnicodeConverter);
-  conv.charset = entry.converter;
-
-  let raw = conv.convertToByteArray(str);
-  let data = {array: raw, offset: 0};
-  let octetArray = WSP.Octet.decodeMultiple(data, data.array.length);
-  wsp_decode_test_ex(function(data) {
-      return WSP.PduHelper.decodeStringContent(data.array, "utf-8");
-    }, octetArray, str);
-
-  entry = WSP.WSP_WELL_KNOWN_CHARSETS["utf-16"];
-  // "Mozilla" in full width.
-  str = "\u004d\u006F\u007A\u0069\u006C\u006C\u0061";
-
-  conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
-         .createInstance(Ci.nsIScriptableUnicodeConverter);
-  conv.charset = entry.converter;
-
-  raw = conv.convertToByteArray(str);
-  data = {array: raw, offset: 0};
-  octetArray = WSP.Octet.decodeMultiple(data, data.array.length);
-  wsp_decode_test_ex(function(data) {
-      return WSP.PduHelper.decodeStringContent(data.array, "utf-16");
-    }, raw, str);
-
-  run_next_test();
-});
-
-//// PduHelper.composeMultiPart ////
-
-add_test(function test_PduHelper_composeMultiPart() {
-  let multiStream = Components.classes["@mozilla.org/io/multiplex-input-stream;1"]
-                    .createInstance(Ci.nsIMultiplexInputStream);
-  let uint8Array = new Uint8Array(5);
-  uint8Array[0] = 0x00;
-  uint8Array[1] = 0x01;
-  uint8Array[2] = 0x02;
-  uint8Array[3] = 0x03;
-  uint8Array[4] = 0x04;
-
-  let parts = [
-      {
-        content: "content",
-        headers: {
-            "content-type": {
-                media: "text/plain",
-                params: {}
-            }
-        }
-      },
-      {
-        content: uint8Array,
-        headers: {
-            "content-type": {
-                media: "text/plain",
-                params: {}
-            }
-        }
-      }
-    ];
-
-  let beforeCompose = JSON.stringify(parts);
-  WSP.PduHelper.composeMultiPart(multiStream, parts);
-  let afterCompose = JSON.stringify(parts);
-
-  do_check_eq(beforeCompose, afterCompose);
-  run_next_test();
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/xpcshell/test_wsp_pdu_helper_numeric.js
+++ /dev/null
@@ -1,240 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var WSP = {};
-subscriptLoader.loadSubScript("resource://gre/modules/WspPduHelper.jsm", WSP);
-WSP.debug = do_print;
-
-function run_test() {
-  run_next_test();
-}
-
-//
-// Test target: Octet
-//
-
-//// Octet.decode ////
-
-add_test(function test_Octet_decode() {
-  wsp_decode_test(WSP.Octet, [1], 1);
-  wsp_decode_test(WSP.Octet, [], null, "RangeError");
-
-  run_next_test();
-});
-
-//// Octet.decodeMultiple ////
-
-add_test(function test_Octet_decodeMultiple() {
-  wsp_decode_test_ex(function(data) {
-      return WSP.Octet.decodeMultiple(data, 3);
-    }, [0, 1, 2], [0, 1, 2], null
-  );
-  wsp_decode_test_ex(function(data) {
-      return WSP.Octet.decodeMultiple(data, 3);
-    }, new Uint8Array([0, 1, 2]), new Uint8Array([0, 1, 2]), null
-  );
-  wsp_decode_test_ex(function(data) {
-      return WSP.Octet.decodeMultiple(data, 4);
-    }, [0, 1, 2], null, "RangeError"
-  );
-
-  run_next_test();
-});
-
-//// Octet.decodeEqualTo ////
-
-add_test(function test_Octet_decodeEqualTo() {
-  wsp_decode_test_ex(function(data) {
-      return WSP.Octet.decodeEqualTo(data, 1);
-    }, [1], 1, null
-  );
-  wsp_decode_test_ex(function(data) {
-      return WSP.Octet.decodeEqualTo(data, 2);
-    }, [1], null, "CodeError"
-  );
-  wsp_decode_test_ex(function(data) {
-      return WSP.Octet.decodeEqualTo(data, 2);
-    }, [], null, "RangeError"
-  );
-
-  run_next_test();
-});
-
-//// Octet.encode ////
-
-add_test(function test_Octet_encode() {
-  for (let i = 0; i < 256; i++) {
-    wsp_encode_test(WSP.Octet, i, [i]);
-  }
-
-  run_next_test();
-});
-
-//// Octet.encodeMultiple ////
-
-add_test(function test_Octet_encodeMultiple() {
-  wsp_encode_test_ex(function(data, input) {
-    WSP.Octet.encodeMultiple(data, input);
-    return data.array;
-  }, [0, 1, 2, 3], [0, 1, 2, 3]);
-
-  run_next_test();
-});
-
-//
-// Test target: ShortInteger
-//
-
-//// ShortInteger.decode ////
-
-add_test(function test_ShortInteger_decode() {
-  for (let i = 0; i < 256; i++) {
-    if (i & 0x80) {
-      wsp_decode_test(WSP.ShortInteger, [i], i & 0x7F);
-    } else {
-      wsp_decode_test(WSP.ShortInteger, [i], null, "CodeError");
-    }
-  }
-
-  run_next_test();
-});
-
-//// ShortInteger.encode ////
-
-add_test(function test_ShortInteger_encode() {
-  for (let i = 0; i < 256; i++) {
-    if (i & 0x80) {
-      wsp_encode_test(WSP.ShortInteger, i, null, "CodeError");
-    } else {
-      wsp_encode_test(WSP.ShortInteger, i, [0x80 | i]);
-    }
-  }
-
-  run_next_test();
-});
-
-//
-// Test target: LongInteger
-//
-
-//// LongInteger.decode ////
-
-function LongInteger_decode_testcases(target) {
-  // Test LongInteger of zero octet
-  wsp_decode_test(target, [0, 0], null, "CodeError");
-  wsp_decode_test(target, [1, 0x80], 0x80);
-  wsp_decode_test(target, [2, 0x80, 2], 0x8002);
-  wsp_decode_test(target, [3, 0x80, 2, 3], 0x800203);
-  wsp_decode_test(target, [4, 0x80, 2, 3, 4], 0x80020304);
-  wsp_decode_test(target, [5, 0x80, 2, 3, 4, 5], 0x8002030405);
-  wsp_decode_test(target, [6, 0x80, 2, 3, 4, 5, 6], 0x800203040506);
-  // Test LongInteger of more than 6 octets
-  wsp_decode_test(target, [7, 0x80, 2, 3, 4, 5, 6, 7], [0x80, 2, 3, 4, 5, 6, 7]);
-  // Test LongInteger of more than 30 octets
-  wsp_decode_test(target, [31], null, "CodeError");
-}
-add_test(function test_LongInteger_decode() {
-  LongInteger_decode_testcases(WSP.LongInteger);
-
-  run_next_test();
-});
-
-//// LongInteger.encode ////
-
-function LongInteger_encode_testcases(target) {
-  wsp_encode_test(target, 0x80,           [1, 0x80]);
-  wsp_encode_test(target, 0x8002,         [2, 0x80, 2]);
-  wsp_encode_test(target, 0x800203,       [3, 0x80, 2, 3]);
-  wsp_encode_test(target, 0x80020304,     [4, 0x80, 2, 3, 4]);
-  wsp_encode_test(target, 0x8002030405,   [5, 0x80, 2, 3, 4, 5]);
-  wsp_encode_test(target, 0x800203040506, [6, 0x80, 2, 3, 4, 5, 6]);
-  // Test LongInteger of more than 6 octets
-  wsp_encode_test(target, 0x1000000000000, null, "CodeError");
-  // Test input empty array
-  wsp_encode_test(target, [], null, "CodeError");
-  // Test input octets array of length 1..30
-  let array = [];
-  for (let i = 1; i <= 30; i++) {
-    array.push(i);
-    wsp_encode_test(target, array, [i].concat(array));
-  }
-  // Test input octets array of 31 elements.
-  array.push(31);
-  wsp_encode_test(target, array, null, "CodeError");
-}
-add_test(function test_LongInteger_encode() {
-  wsp_encode_test(WSP.LongInteger, 0, [1, 0]);
-
-  LongInteger_encode_testcases(WSP.LongInteger);
-
-  run_next_test();
-});
-
-//
-// Test target: UintVar
-//
-
-//// UintVar.decode ////
-
-add_test(function test_UintVar_decode() {
-  wsp_decode_test(WSP.UintVar, [0x80], null, "RangeError");
-  // Test up to max 53 bits integer
-  wsp_decode_test(WSP.UintVar, [0x7F], 0x7F);
-  wsp_decode_test(WSP.UintVar, [0xFF, 0x7F], 0x3FFF);
-  wsp_decode_test(WSP.UintVar, [0xFF, 0xFF, 0x7F], 0x1FFFFF);
-  wsp_decode_test(WSP.UintVar, [0xFF, 0xFF, 0xFF, 0x7F], 0xFFFFFFF);
-  wsp_decode_test(WSP.UintVar, [0xFF, 0xFF, 0xFF, 0xFF, 0x7F], 0x7FFFFFFFF);
-  wsp_decode_test(WSP.UintVar, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F], 0x3FFFFFFFFFF);
-  wsp_decode_test(WSP.UintVar, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F], 0x1FFFFFFFFFFFF);
-  wsp_decode_test(WSP.UintVar, [0x8F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F], 0x1FFFFFFFFFFFFF);
-  wsp_decode_test(WSP.UintVar, [0x01, 0x02], 1);
-  wsp_decode_test(WSP.UintVar, [0x80, 0x01, 0x02], 1);
-  wsp_decode_test(WSP.UintVar, [0x80, 0x80, 0x80, 0x01, 0x2], 1);
-
-  run_next_test();
-});
-
-//// UintVar.encode ////
-
-add_test(function test_UintVar_encode() {
-  // Test up to max 53 bits integer
-  wsp_encode_test(WSP.UintVar, 0, [0]);
-  wsp_encode_test(WSP.UintVar, 0x7F, [0x7F]);
-  wsp_encode_test(WSP.UintVar, 0x3FFF, [0xFF, 0x7F]);
-  wsp_encode_test(WSP.UintVar, 0x1FFFFF, [0xFF, 0xFF, 0x7F]);
-  wsp_encode_test(WSP.UintVar, 0xFFFFFFF, [0xFF, 0xFF, 0xFF, 0x7F]);
-  wsp_encode_test(WSP.UintVar, 0x7FFFFFFFF, [0xFF, 0xFF, 0xFF, 0xFF, 0x7F]);
-  wsp_encode_test(WSP.UintVar, 0x3FFFFFFFFFF, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F]);
-  wsp_encode_test(WSP.UintVar, 0x1FFFFFFFFFFFF, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F]);
-  wsp_encode_test(WSP.UintVar, 0x1FFFFFFFFFFFFF, [0x8F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F]);
-
-  run_next_test();
-});
-
-//
-// Test target: IntegerValue
-//
-
-//// IntegerValue.decode ////
-
-add_test(function test_IntegerValue_decode() {
-  for (let i = 128; i < 256; i++) {
-    wsp_decode_test(WSP.IntegerValue, [i], i & 0x7F);
-  }
-
-  LongInteger_decode_testcases(WSP.IntegerValue);
-
-  run_next_test();
-});
-
-//// IntegerValue.decode ////
-
-add_test(function test_IntegerValue_encode() {
-  for (let i = 0; i < 128; i++) {
-    wsp_encode_test(WSP.IntegerValue, i, [0x80 | i]);
-  }
-
-  LongInteger_encode_testcases(WSP.IntegerValue);
-
-  run_next_test();
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/xpcshell/test_wsp_pdu_helper_parameter.js
+++ /dev/null
@@ -1,132 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var WSP = {};
-subscriptLoader.loadSubScript("resource://gre/modules/WspPduHelper.jsm", WSP);
-WSP.debug = do_print;
-
-function run_test() {
-  run_next_test();
-}
-
-//
-// Test target: Parameter
-//
-
-//// Parameter.decodeTypedParameter ////
-
-add_test(function test_Parameter_decodeTypedParameter() {
-  function func(data) {
-    return WSP.Parameter.decodeTypedParameter(data);
-  }
-
-  // Test for array-typed return value from IntegerValue
-  wsp_decode_test_ex(func, [7, 0, 0, 0, 0, 0, 0, 0], null, "CodeError");
-  // Test for number-typed return value from IntegerValue
-  wsp_decode_test_ex(func, [1, 0, 0], {name: "q", value: null});
-  // Test for NotWellKnownEncodingError
-  wsp_decode_test_ex(func, [1, 0xFF], null, "NotWellKnownEncodingError");
-  // Test for parameter specific decoder
-  wsp_decode_test_ex(func, [1, 0, 100], {name: "q", value: 0.99});
-  // Test for TextValue
-  wsp_decode_test_ex(func, [1, 0x10, 48, 46, 57, 57, 0],
-                     {name: "secure", value: "0.99"});
-  // Test for TextString
-  wsp_decode_test_ex(func, [1, 0x0A, 60, 115, 109, 105, 108, 62, 0],
-                     {name: "start", value: "<smil>"});
-  // Test for skipValue
-  wsp_decode_test_ex(func, [1, 0x0A, 128], null);
-
-  run_next_test();
-});
-
-//// Parameter.decodeUntypedParameter ////
-
-add_test(function test_Parameter_decodeUntypedParameter() {
-  function func (data) {
-    return WSP.Parameter.decodeUntypedParameter(data);
-  }
-
-  wsp_decode_test_ex(func, [1], null, "CodeError");
-  wsp_decode_test_ex(func, [65, 0, 0], {name: "a", value: null});
-  // Test for IntegerValue
-  wsp_decode_test_ex(func, [65, 0, 1, 0], {name: "a", value: 0});
-  // Test for TextValue
-  wsp_decode_test_ex(func, [65, 0, 66, 0], {name: "a", value: "B"});
-
-  run_next_test();
-});
-
-//// Parameter.decode ////
-
-add_test(function test_Parameter_decode() {
-  wsp_decode_test(WSP.Parameter, [1, 0x0A, 60, 115, 109, 105, 108, 62, 0],
-                  {name: "start", value: "<smil>"});
-  wsp_decode_test(WSP.Parameter, [65, 0, 66, 0], {name: "a", value: "B"});
-
-  run_next_test();
-});
-
-//// Parameter.decodeMultiple ////
-
-add_test(function test_Parameter_decodeMultiple() {
-  wsp_decode_test_ex(function(data) {
-      return WSP.Parameter.decodeMultiple(data, 13);
-    }, [1, 0x0A, 60, 115, 109, 105, 108, 62, 0, 65, 0, 66, 0], {start: "<smil>", a: "B"}
-  );
-
-  run_next_test();
-});
-
-//// Parameter.encodeTypedParameter ////
-
-add_test(function test_Parameter_encodeTypedParameter() {
-  function func(data, input) {
-    WSP.Parameter.encodeTypedParameter(data, input);
-    return data.array;
-  }
-
-  // Test for NotWellKnownEncodingError
-  wsp_encode_test_ex(func, {name: "xxx", value: 0}, null, "NotWellKnownEncodingError");
-  wsp_encode_test_ex(func, {name: "q", value: 0}, [0x80, 1]);
-  wsp_encode_test_ex(func, {name: "name", value: "A"}, [0x85, 65, 0]);
-
-  run_next_test();
-});
-
-//// Parameter.encodeUntypedParameter ////
-
-add_test(function test_Parameter_encodeUntypedParameter() {
-  function func(data, input) {
-    WSP.Parameter.encodeUntypedParameter(data, input);
-    return data.array;
-  }
-
-  wsp_encode_test_ex(func, {name: "q", value: 0}, [113, 0, 0x80]);
-  wsp_encode_test_ex(func, {name: "name", value: "A"}, [110, 97, 109, 101, 0, 65, 0]);
-
-  run_next_test();
-});
-
-//// Parameter.encodeMultiple ////
-
-add_test(function test_Parameter_encodeMultiple() {
-  function func(data, input) {
-    WSP.Parameter.encodeMultiple(data, input);
-    return data.array;
-  }
-
-  wsp_encode_test_ex(func, {q: 0, n: "A"}, [0x80, 1, 110, 0, 65, 0]);
-
-  run_next_test();
-});
-
-//// Parameter.encode ////
-
-add_test(function test_Parameter_encode() {
-
-  wsp_encode_test(WSP.Parameter, {name: "q", value: 0}, [0x80, 1]);
-  wsp_encode_test(WSP.Parameter, {name: "n", value: "A"}, [110, 0, 65, 0]);
-
-  run_next_test();
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/xpcshell/test_wsp_pdu_helper_text.js
+++ /dev/null
@@ -1,241 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var WSP = {};
-subscriptLoader.loadSubScript("resource://gre/modules/WspPduHelper.jsm", WSP);
-WSP.debug = do_print;
-
-function run_test() {
-  run_next_test();
-}
-
-//
-// Test target: Text
-//
-
-//// Text.decode ////
-
-add_test(function test_Text_decode() {
-  for (let i = 0; i < 256; i++) {
-    if (i == 0) {
-      wsp_decode_test(WSP.Text, [0], null, "NullCharError");
-    } else if ((i < WSP.CTLS) || (i == WSP.DEL)) {
-      wsp_decode_test(WSP.Text, [i], null, "CodeError");
-    } else {
-      wsp_decode_test(WSP.Text, [i], String.fromCharCode(i));
-    }
-  }
-  // Test \r\n(SP|HT)* sequence:
-  wsp_decode_test(WSP.Text, strToCharCodeArray("\r\n \t \t \t", true), " ");
-  wsp_decode_test(WSP.Text, strToCharCodeArray("\r\n \t \t \t"), " ");
-  wsp_decode_test(WSP.Text, strToCharCodeArray("\r\n \t \t \tA"), " ");
-
-  run_next_test();
-});
-
-//// Text.encode ////
-
-add_test(function test_Text_encode() {
-  for (let i = 0; i < 256; i++) {
-    if ((i < WSP.CTLS) || (i == WSP.DEL)) {
-      wsp_encode_test(WSP.Text, String.fromCharCode(i), null, "CodeError");
-    } else {
-      wsp_encode_test(WSP.Text, String.fromCharCode(i), [i]);
-    }
-  }
-
-  run_next_test();
-});
-
-//
-// Test target: NullTerminatedTexts
-//
-
-//// NullTerminatedTexts.decode ////
-
-add_test(function test_NullTerminatedTexts_decode() {
-  // Test incompleted string:
-  wsp_decode_test(WSP.NullTerminatedTexts, strToCharCodeArray(" ", true), null, "RangeError");
-  // Test control char:
-  wsp_decode_test(WSP.NullTerminatedTexts, strToCharCodeArray(" \n"), null, "CodeError");
-  // Test normal string:
-  wsp_decode_test(WSP.NullTerminatedTexts, strToCharCodeArray(""), "");
-  wsp_decode_test(WSP.NullTerminatedTexts, strToCharCodeArray("oops"), "oops");
-  // Test \r\n(SP|HT)* sequence:
-  wsp_decode_test(WSP.NullTerminatedTexts, strToCharCodeArray("A\r\n \t \t \tB"), "A B");
-
-  run_next_test();
-});
-
-//// NullTerminatedTexts.encode ////
-
-add_test(function test_NullTerminatedTexts_encode() {
-  wsp_encode_test(WSP.NullTerminatedTexts, "", [0]);
-  wsp_encode_test(WSP.NullTerminatedTexts, "Hello, World!",
-                  strToCharCodeArray("Hello, World!"));
-
-  run_next_test();
-});
-
-//
-// Test target: Token
-//
-
-var TOKEN_SEPS = "()<>@,;:\\\"/[]?={} \t";
-
-//// Token.decode ////
-
-add_test(function test_Token_decode() {
-  for (let i = 0; i < 256; i++) {
-    if (i == 0) {
-      wsp_decode_test(WSP.Token, [i], null, "NullCharError");
-    } else if ((i < WSP.CTLS) || (i >= WSP.ASCIIS)
-        || (TOKEN_SEPS.indexOf(String.fromCharCode(i)) >= 0)) {
-      wsp_decode_test(WSP.Token, [i], null, "CodeError");
-    } else {
-      wsp_decode_test(WSP.Token, [i], String.fromCharCode(i));
-    }
-  }
-
-  run_next_test();
-});
-
-//// Token.encode ////
-
-add_test(function test_Token_encode() {
-  for (let i = 0; i < 256; i++) {
-    if ((i < WSP.CTLS) || (i >= WSP.ASCIIS)
-        || (TOKEN_SEPS.indexOf(String.fromCharCode(i)) >= 0)) {
-      wsp_encode_test(WSP.Token, String.fromCharCode(i), null, "CodeError");
-    } else {
-      wsp_encode_test(WSP.Token, String.fromCharCode(i), [i]);
-    }
-  }
-
-  run_next_test();
-});
-
-//
-// Test target: URIC
-//
-
-//// URIC.decode ////
-
-add_test(function test_URIC_decode() {
-  let uric = "!#$%&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMN"
-             + "OPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~";
-  for (let i = 0; i < 256; i++) {
-    if (i == 0) {
-      wsp_decode_test(WSP.URIC, [i], null, "NullCharError");
-    } else if (uric.indexOf(String.fromCharCode(i)) >= 0) {
-      wsp_decode_test(WSP.URIC, [i], String.fromCharCode(i));
-    } else {
-      wsp_decode_test(WSP.URIC, [i], null, "CodeError");
-    }
-  }
-
-  run_next_test();
-});
-
-//
-// Test target: TextString
-//
-
-//// TextString.decode ////
-
-add_test(function test_TextString_decode() {
-  // Test quoted string
-  wsp_decode_test(WSP.TextString, [127, 128, 0], String.fromCharCode(128));
-  // Test illegal quoted string
-  wsp_decode_test(WSP.TextString, [127, 32, 0], null, "CodeError");
-  // Test illegal unquoted string
-  wsp_decode_test(WSP.TextString, [128, 0], null, "CodeError");
-  // Test normal string
-  wsp_decode_test(WSP.TextString, [32, 0], " ");
-
-  run_next_test();
-});
-
-//// TextString.encode ////
-
-add_test(function test_TextString_encode() {
-  // Test quoted string
-  wsp_encode_test(WSP.TextString, String.fromCharCode(128), [127, 128, 0]);
-  // Test normal string
-  wsp_encode_test(WSP.TextString, "Mozilla", strToCharCodeArray("Mozilla"));
-
-  run_next_test();
-});
-
-//
-// Test target: TokenText
-//
-
-//// TokenText.decode ////
-
-add_test(function test_TokenText_decode() {
-  wsp_decode_test(WSP.TokenText, [65], null, "RangeError");
-  wsp_decode_test(WSP.TokenText, [0], "");
-  wsp_decode_test(WSP.TokenText, [65, 0], "A");
-
-  run_next_test();
-});
-
-//// TokenText.encode ////
-
-add_test(function test_TokenText_encode() {
-  wsp_encode_test(WSP.TokenText, "B2G", strToCharCodeArray("B2G"));
-
-  run_next_test();
-});
-
-//
-// Test target: QuotedString
-//
-
-//// QuotedString.decode ////
-
-add_test(function test_QuotedString_decode() {
-  // Test non-quoted string
-  wsp_decode_test(WSP.QuotedString, [32, 0], null, "CodeError");
-  // Test incompleted string
-  wsp_decode_test(WSP.QuotedString, [34, 32], null, "RangeError");
-  wsp_decode_test(WSP.QuotedString, [34, 32, 0], " ");
-
-  run_next_test();
-});
-
-//// QuotedString.encode ////
-
-add_test(function test_QuotedString_encode() {
-  wsp_encode_test(WSP.QuotedString, "B2G", [34].concat(strToCharCodeArray("B2G")));
-
-  run_next_test();
-});
-
-//
-// Test target: TextValue
-//
-
-//// TextValue.decode ////
-
-add_test(function test_TextValue_decode() {
-  wsp_decode_test(WSP.TextValue, [0], null);
-  wsp_decode_test(WSP.TextValue, [65, 0], "A");
-  wsp_decode_test(WSP.TextValue, [32, 0], null, "CodeError");
-  wsp_decode_test(WSP.TextValue, [34, 32, 0], " ");
-
-  run_next_test();
-});
-
-//// TextValue.encode ////
-
-add_test(function test_TextValue_encode() {
-  wsp_encode_test(WSP.TextValue, undefined, [0]);
-  wsp_encode_test(WSP.TextValue, null, [0]);
-  wsp_encode_test(WSP.TextValue, "", [0]);
-  wsp_encode_test(WSP.TextValue, "A", [65, 0]);
-  wsp_encode_test(WSP.TextValue, "\x80", [34, 128, 0]);
-
-  run_next_test();
-});
deleted file mode 100644
--- a/dom/mobilemessage/tests/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,21 +0,0 @@
-[DEFAULT]
-head = header_helpers.js
-tail =
-
-[test_smsservice_createsmsmessage.js]
-[test_wsp_pdu_helper.js]
-skip-if = toolkit != "gonk"
-[test_wsp_pdu_helper_header.js]
-skip-if = toolkit != "gonk"
-[test_wsp_pdu_helper_numeric.js]
-skip-if = toolkit != "gonk"
-[test_wsp_pdu_helper_parameter.js]
-skip-if = toolkit != "gonk"
-[test_wsp_pdu_helper_text.js]
-skip-if = toolkit != "gonk"
-[test_mms_pdu_helper.js]
-skip-if = toolkit != "gonk"
-[test_mms_service.js]
-skip-if = toolkit != "gonk"
-[test_sms_segment_helper.js]
-skip-if = toolkit != "gonk"
--- a/dom/moz.build
+++ b/dom/moz.build
@@ -73,17 +73,16 @@ DIRS += [
     'offline',
     'power',
     'push',
     'quota',
     'security',
     'settings',
     'storage',
     'svg',
-    'mobilemessage',
     'time',
     'locales',
     'network',
     'permission',
     'plugins/base',
     'plugins/ipc',
     'indexedDB',
     'system',
--- a/dom/permission/moz.build
+++ b/dom/permission/moz.build
@@ -32,17 +32,14 @@ XPCSHELL_TESTS_MANIFESTS += ['tests/unit
 MOCHITEST_MANIFESTS += ['tests/mochitest.ini']
 
 if CONFIG['MOZ_B2G_RIL']:
     MOCHITEST_MANIFESTS += ['tests/mochitest-ril.ini']
 
 if CONFIG['MOZ_B2G_BT']:
     MOCHITEST_MANIFESTS += ['tests/mochitest-bt.ini']
 
-if CONFIG['MOZ_WEBSMS_BACKEND']:
-    MOCHITEST_MANIFESTS += ['tests/mochitest-websms.ini']
-
 if CONFIG['MOZ_TIME_MANAGER']:
     MOCHITEST_MANIFESTS += ['tests/mochitest-time.ini']
 
 FINAL_LIBRARY = 'xul'
 
 include('/ipc/chromium/chromium-config.mozbuild')
deleted file mode 100644
--- a/dom/permission/tests/mochitest-websms.ini
+++ /dev/null
@@ -1,1 +0,0 @@
-[test_sms.html]
deleted file mode 100644
--- a/dom/permission/tests/test_sms.html
+++ /dev/null
@@ -1,33 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=815105
--->
-<head>
-  <meta charset="utf-8">
-  <title>Test for Bug 815105 </title>
-  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=815105">Mozilla Bug 815105 </a>
-<p id="display"></p>
-<div id="content" style="display: none"></div>
-<pre id="test">
-<script type="application/javascript;version=1.8" src="file_framework.js"></script>
-<script type="application/javascript;version=1.8">
-var gData = [
-  {
-    perm: ["sms"],
-    needParentPerm: true,
-    obj: "mozMobileMessage",
-    webidl: "MozMobileMessageManager",
-    settings: [["dom.sms.enabled", true],
-               ["dom.ignore_webidl_scope_checks", true]],
-  },
-]
-</script>
-</pre>
-</body>
-</html>
-
deleted file mode 100644
--- a/dom/webidl/DOMMobileMessageError.webidl
+++ /dev/null
@@ -1,11 +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/.
- */
-
-[Pref="dom.sms.enabled",
- ChromeOnly]
-interface DOMMobileMessageError : DOMError {
-  readonly attribute (SmsMessage or MmsMessage) data;
-};
deleted file mode 100644
--- a/dom/webidl/MmsMessage.webidl
+++ /dev/null
@@ -1,101 +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 MmsDeliveryInfo {
-  DOMString? receiver = null;
-  DOMString? deliveryStatus = null;
-  DOMTimeStamp deliveryTimestamp = 0; // 0 if not available (e.g.,
-                                      // |delivery| = "received" or not yet delivered).
-  DOMString? readStatus = null;
-  DOMTimeStamp readTimestamp = 0; // 0 if not available (e.g.,
-                                  // |delivery| = "received" or not yet read).
-};
-
-[Pref="dom.sms.enabled",
- ChromeOnly]
-interface MmsMessage {
-  /**
-   * |type| is always "mms".
-   */
-  readonly attribute DOMString type;
-
-  /**
-   * The id of the message record in the database.
-   */
-  readonly attribute long id;
-
-  /**
-   * The Thread id this message belonging to.
-   */
-  readonly attribute unsigned long long threadId;
-
-  /**
-   * Integrated Circuit Card Identifier.
-   *
-   * Will be null if ICC is not available.
-   */
-  readonly attribute DOMString iccId;
-
-  /**
-   * Should be "not-downloaded", "received", "sending", "sent" or "error".
-   */
-  readonly attribute DOMString delivery;
-
-  [Cached, Pure]
-  readonly attribute sequence<MmsDeliveryInfo> deliveryInfo;
-
-  /**
-   * The sender's address.
-   */
-  readonly attribute DOMString sender;
-
-  /**
-   * The addreses of the receivers.
-   */
-  [Cached, Pure]
-  readonly attribute sequence<DOMString> receivers;
-
-  /**
-   * Device timestamp when message is either sent or received.
-   */
-  readonly attribute DOMTimeStamp timestamp;
-
-  /**
-   * The timestamp from MMSC when |delivery| is |received|.
-   */
-  readonly attribute DOMTimeStamp sentTimestamp;
-
-  /**
-   * The read status of this message.
-   */
-  readonly attribute boolean read;
-
-  /**
-   * The subject of this message.
-   */
-  readonly attribute DOMString subject;
-
-  /**
-   * The SMIL document of this message.
-   */
-  readonly attribute DOMString smil;
-
-  /**
-   * The attachments of this message.
-   */
-  [Cached, Pure]
-  readonly attribute sequence<MmsAttachment> attachments;
-
-  /**
-   * Expiry date for an MMS to be retrieved.
-   */
-  readonly attribute DOMTimeStamp expiryDate;
-
-  /**
-   * The flag to indicate that a read report is requested by the sender or not.
-   */
-  readonly attribute boolean readReportRequested;
-};
deleted file mode 100644
--- a/dom/webidl/MobileMessageThread.webidl
+++ /dev/null
@@ -1,45 +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/.
- */
-
-[Pref="dom.sms.enabled",
- ChromeOnly]
-interface MobileMessageThread {
-  /**
-   * Unique identity of the thread.
-   */
-  readonly attribute unsigned long long id;
-
-  /**
-   * Last (MMS) message subject.
-   */
-  readonly attribute DOMString lastMessageSubject;
-
-  /**
-   * Message body of the last message in the thread.
-   */
-  readonly attribute DOMString body;
-
-  /**
-   * Total unread messages in the thread.
-   */
-  readonly attribute unsigned long long unreadCount;
-
-  /**
-   * Participant addresses of the thread.
-   */
-  [Cached, Pure]
-  readonly attribute sequence<DOMString> participants;
-
-  /**
-   * Timestamp of the last message in the thread.
-   */
-  readonly attribute DOMTimeStamp timestamp;
-
-  /**
-   * Message type of the last message in the thread.
-   */
-  readonly attribute DOMString lastMessageType;
-};
deleted file mode 100644
--- a/dom/webidl/MozMessageDeletedEvent.webidl
+++ /dev/null
@@ -1,22 +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/.
- */
-
-[Pref="dom.sms.enabled",
- ChromeOnly,
- Constructor(DOMString type, optional MozMessageDeletedEventInit eventInitDict)]
-interface MozMessageDeletedEvent : Event
-{
-  // Array of deleted message ids.
-  [Cached, Constant] readonly attribute sequence<long>? deletedMessageIds;
-  // Array of deleted thread ids.
-  [Cached, Constant] readonly attribute sequence<unsigned long long>? deletedThreadIds;
-};
-
-dictionary MozMessageDeletedEventInit : EventInit
-{
-  sequence<long>? deletedMessageIds = null;
-  sequence<unsigned long long>? deletedThreadIds = null;
-};
deleted file mode 100644
--- a/dom/webidl/MozMmsEvent.webidl
+++ /dev/null
@@ -1,18 +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/.
- */
-
-[Pref="dom.sms.enabled",
- ChromeOnly,
- Constructor(DOMString type, optional MozMmsEventInit eventInitDict)]
-interface MozMmsEvent : Event
-{
-  readonly attribute MmsMessage? message;
-};
-
-dictionary MozMmsEventInit : EventInit
-{
-  MmsMessage? message = null;
-};
deleted file mode 100644
--- a/dom/webidl/MozMobileMessageManager.webidl
+++ /dev/null
@@ -1,221 +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 SmsSegmentInfo {
-  /**
-   * The number of total segments for the input string. The value is always
-   * larger-equal than 1.
-   */
-  long segments = 0;
-
-  /**
-   * The number of characters available per segment. The value is always
-   * larger-equal than 1.
-   */
-  long charsPerSegment = 0;
-
-  /**
-   * The maximum number of available characters in the last segment. The value
-   * is always larger-equal than 0.
-   */
-  long charsAvailableInLastSegment = 0;
-};
-
-dictionary MmsAttachment {
-  DOMString? id = null;
-  DOMString? location = null;
-  Blob? content = null;
-};
-
-dictionary MmsParameters {
-  sequence<DOMString> receivers;
-  DOMString? subject = null;
-  DOMString? smil = null;
-  sequence<MmsAttachment> attachments;
-};
-
-dictionary SmsSendParameters {
-  unsigned long serviceId; // The ID of the RIL service which needs to be
-                           // specified under the multi-sim scenario.
-};
-
-dictionary MmsSendParameters {
-  unsigned long serviceId; // The ID of the RIL service which needs to be
-                           // specified under the multi-sim scenario.
-};
-
-enum MobileMessageFilterDelivery { "sent", "received" };
-
-dictionary MobileMessageFilter
-{
-  // Close lower bound range for filtering by the message timestamp.
-  // Time in milliseconds since Epoch.
-  [EnforceRange] DOMTimeStamp? startDate = null;
-
-  // Close upper bound range for filtering by the message timestamp.
-  // Time in milliseconds since Epoch.
-  [EnforceRange] DOMTimeStamp? endDate = null;
-
-  // An array of string message participant addresses that any of which
-  // appears or matches a message's sendor or recipients addresses.
-  sequence<DOMString>? numbers = null;
-
-  MobileMessageFilterDelivery? delivery = null;
-
-  // Filtering by whether a message has been read or not.
-  boolean? read = null;
-
-  // Filtering by a message's threadId attribute.
-  [EnforceRange] unsigned long long? threadId = null;
-};
-
-/**
- * TON defined in |Table 10.5.118: Called party BCD number| of 3GPP TS 24.008.
- * It's used in SM-RL originator / destination address element as defined in
- * |8.2.5.2 Destination address element| of 3GPP TS 24.011.
- */
-enum TypeOfNumber { "unknown", "international", "national", "network-specific",
-  "dedicated-access-short-code" };
-
-/**
- * NPI defined in |Table 10.5.118: Called party BCD number| of 3GPP TS 24.008.
- * It's used in SM-RL originator / destination address element as defined in
- * |8.2.5.2 Destination address element| of 3GPP TS 24.011.
- */
-enum NumberPlanIdentification { "unknown", "isdn", "data", "telex", "national",
-  "private" };
-
-/**
- * Type of address used in SmscAddress.
- *
- * As described in |3.1 Parameters Definitions| of 3GPP TS 27.005, the default
- * value of <tosca> should be 129 (typeOfNumber=unknown,
- * numberPlanIdentification=isdn) if the number does not begin with '+'.
- *
- * |setSmscAddress| updates typeOfNumber to international automatically if the
- * given number begins with '+'.
- */
-dictionary TypeOfAddress {
-  TypeOfNumber typeOfNumber = "unknown";
-  NumberPlanIdentification numberPlanIdentification = "isdn";
-};
-
-/**
- * SMSC address.
- */
-dictionary SmscAddress {
-  DOMString address;
-  TypeOfAddress typeOfAddress;
-};
-
-[Pref="dom.sms.enabled",
- ChromeOnly]
-interface MozMobileMessageManager : EventTarget
-{
-  [Throws]
-  DOMRequest getSegmentInfoForText(DOMString text);
-
-  /**
-   * Send SMS.
-   *
-   * @param number
-   *        Either a DOMString (only one number) or an array of numbers.
-   * @param text
-   *        The text message to be sent.
-   * @param sendParameters
-   *        A SmsSendParameters object.
-   *
-   * @return
-   *        A DOMRequest object indicating the sending result if one number
-   *        has been passed; an array of DOMRequest objects otherwise.
-   */
-  [Throws]
-  DOMRequest send(DOMString number,
-                  DOMString text,
-                  optional SmsSendParameters sendParameters);
-  [Throws]
-  sequence<DOMRequest> send(sequence<DOMString> numbers,
-                            DOMString text,
-                            optional SmsSendParameters sendParameters);
-
-  /**
-   * Send MMS.
-   *
-   * @param parameters
-   *        A MmsParameters object.
-   * @param sendParameters
-   *        A MmsSendParameters object.
-   *
-   * @return
-   *        A DOMRequest object indicating the sending result.
-   */
-  [Throws]
-  DOMRequest sendMMS(optional MmsParameters parameters,
-                     optional MmsSendParameters sendParameters);
-
-  [Throws]
-  DOMRequest getMessage(long id);
-
-  // The parameter can be either a message id, or a {Mms,Sms}Message, or an
-  // array of {Mms,Sms}Message objects.
-  [Throws]
-  DOMRequest delete(long id);
-  [Throws]
-  DOMRequest delete(SmsMessage message);
-  [Throws]
-  DOMRequest delete(MmsMessage message);
-  [Throws]
-  DOMRequest delete(sequence<(long or SmsMessage or MmsMessage)> params);
-
-  // Iterates through {Mms,Sms}Message.
-  [Throws]
-  DOMCursor getMessages(optional MobileMessageFilter filter,
-                        optional boolean reverse = false);
-
-  [Throws]
-  DOMRequest markMessageRead(long id,
-                             boolean read,
-                             optional boolean sendReadReport = false);
-
-  // Iterates through MobileMessageThread.
-  [Throws]
-  DOMCursor getThreads();
-
-  [Throws]
-  DOMRequest retrieveMMS(long id);
-  [Throws]
-  DOMRequest retrieveMMS(MmsMessage message);
-
-  [Throws]
-  Promise<SmscAddress> getSmscAddress(optional unsigned long serviceId);
-
-  /**
-   * Set the SMSC address.
-   *
-   * @param smscAddress
-   *        SMSC address to use.
-   *        Reject if smscAddress.address does not present.
-   * @param serviceId (optional)
-   *        The ID of the RIL service which needs to be specified under
-   *        the multi-sim scenario.
-   * @return a Promise
-   *         Resolve if success. Otherwise, reject with error cause.
-   */
-  [NewObject]
-  Promise<void> setSmscAddress(optional SmscAddress smscAddress,
-                               optional unsigned long serviceId);
-
-  attribute EventHandler onreceived;
-  attribute EventHandler onretrieving;
-  attribute EventHandler onsending;
-  attribute EventHandler onsent;
-  attribute EventHandler onfailed;
-  attribute EventHandler ondeliverysuccess;
-  attribute EventHandler ondeliveryerror;
-  attribute EventHandler onreadsuccess;
-  attribute EventHandler onreaderror;
-  attribute EventHandler ondeleted;
-};
deleted file mode 100644
--- a/dom/webidl/MozSmsEvent.webidl
+++ /dev/null
@@ -1,18 +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/.
- */
-
-[Pref="dom.sms.enabled",
- ChromeOnly,
- Constructor(DOMString type, optional MozSmsEventInit eventInitDict)]
-interface MozSmsEvent : Event
-{
-  readonly attribute SmsMessage? message;
-};
-
-dictionary MozSmsEventInit : EventInit
-{
-  SmsMessage? message = null;
-};
--- a/dom/webidl/Navigator.webidl
+++ b/dom/webidl/Navigator.webidl
@@ -252,23 +252,16 @@ partial interface Navigator {
 };
 
 // nsIDOMNavigatorDesktopNotification
 partial interface Navigator {
   [Throws, Pref="notification.feature.enabled", UnsafeInPrerendering]
   readonly attribute DesktopNotificationCenter mozNotification;
 };
 
-#ifdef MOZ_WEBSMS_BACKEND
-partial interface Navigator {
-  [ChromeOnly, Pref="dom.sms.enabled"]
-  readonly attribute MozMobileMessageManager? mozMobileMessage;
-};
-#endif
-
 // NetworkInformation
 partial interface Navigator {
   [Throws, Pref="dom.netinfo.enabled"]
   readonly attribute NetworkInformation connection;
 };
 
 #ifdef MOZ_B2G_RIL
 partial interface Navigator {
deleted file mode 100644
--- a/dom/webidl/SmsMessage.webidl
+++ /dev/null
@@ -1,88 +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/.
- */
-
-[Pref="dom.sms.enabled",
- ChromeOnly]
-interface SmsMessage {
-  /**
-   * |type| is always "sms".
-   */
-  readonly attribute DOMString type;
-
-  /**
-   * The id of the message record in the database.
-   */
-  readonly attribute long id;
-
-  /**
-   * The Thread id this message belonging to.
-   */
-  readonly attribute unsigned long long threadId;
-
-  /**
-   * Integrated Circuit Card Identifier.
-   *
-   * Will be null if ICC is not available.
-   */
-  readonly attribute DOMString iccId;
-
-  /**
-   * Should be "received", "sending", "sent" or "error".
-   */
-  readonly attribute DOMString delivery;
-
-  /**
-   * Possible delivery status values for above delivery states are:
-   *
-   * "received": "success"
-   * "sending" : "pending", or "not-applicable" if the message was sent without
-   *             status report requisition.
-   * "sent"    : "pending", "success", "error", or "not-applicable"
-   *             if the message was sent without status report requisition.
-   * "error"   : "error"
-   */
-  readonly attribute DOMString deliveryStatus;
-
-  /**
-   * The sender's address.
-   */
-  readonly attribute DOMString sender;
-
-  /**
-   * The receiver's address.
-   */
-  readonly attribute DOMString receiver;
-
-  /**
-   * Text body of the message.
-   */
-  readonly attribute DOMString body;
-
-  /**
-   * Should be "normal", "class-0", "class-1", "class-2" or "class-3".
-   */
-  readonly attribute DOMString messageClass;
-
-  /**
-   * Device timestamp when message is either sent or received.
-   */
-  readonly attribute DOMTimeStamp timestamp;
-
-  /**
-   * The timestamp from SMSC when |delivery| is |received|.
-   */
-  readonly attribute DOMTimeStamp sentTimestamp;
-
-  /**
-   * The delivery timestamp when |deliveryStatus| is updated to |success|.
-   */
-  readonly attribute DOMTimeStamp deliveryTimestamp;
-
-  /**
-   * The read status of this message.
-   */
-  readonly attribute boolean read;
-};
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -120,17 +120,16 @@ WEBIDL_FILES = [
     'DocumentTimeline.webidl',
     'DocumentType.webidl',
     'DOMCursor.webidl',
     'DOMError.webidl',
     'DOMException.webidl',
     'DOMImplementation.webidl',
     'DominatorTree.webidl',
     'DOMMatrix.webidl',
-    'DOMMobileMessageError.webidl',
     'DOMParser.webidl',
     'DOMPoint.webidl',
     'DOMQuad.webidl',
     'DOMRect.webidl',
     'DOMRectList.webidl',
     'DOMRequest.webidl',
     'DOMStringList.webidl',
     'DOMStringMap.webidl',
@@ -319,28 +318,25 @@ WEBIDL_FILES = [
     'MediaTrackSupportedConstraints.webidl',
     'MenuBoxObject.webidl',
     'MessageChannel.webidl',
     'MessageEvent.webidl',
     'MessagePort.webidl',
     'MimeType.webidl',
     'MimeTypeArray.webidl',
     'MMICall.webidl',
-    'MmsMessage.webidl',
-    'MobileMessageThread.webidl',
     'MouseEvent.webidl',
     'MouseScrollEvent.webidl',
     'MozIcc.webidl',
     'MozIccInfo.webidl',
     'MozIccManager.webidl',
     'MozMobileCellInfo.webidl',
     'MozMobileConnection.webidl',
     'MozMobileConnectionArray.webidl',
     'MozMobileConnectionInfo.webidl',
-    'MozMobileMessageManager.webidl',
     'MozMobileNetworkInfo.webidl',
     'MozPowerManager.webidl',
     'MozSelfSupport.webidl',
     'MozTetheringManager.webidl',
     'MozTimeManager.webidl',
     'MozWakeLock.webidl',
     'MutationEvent.webidl',
     'MutationObserver.webidl',
@@ -420,17 +416,16 @@ WEBIDL_FILES = [
     'ServiceWorkerMessageEvent.webidl',
     'ServiceWorkerRegistration.webidl',
     'SettingChangeNotification.webidl',
     'SettingsManager.webidl',
     'ShadowRoot.webidl',
     'SharedWorker.webidl',
     'SharedWorkerGlobalScope.webidl',
     'SimpleGestureEvent.webidl',
-    'SmsMessage.webidl',
     'SocketCommon.webidl',
     'SourceBuffer.webidl',
     'SourceBufferList.webidl',
     'StereoPannerNode.webidl',
     'Storage.webidl',
     'StorageEvent.webidl',
     'StorageManager.webidl',
     'StorageType.webidl',
@@ -777,22 +772,19 @@ GENERATED_EVENTS_WEBIDL_FILES = [
     'HiddenPluginEvent.webidl',
     'IccChangeEvent.webidl',
     'ImageCaptureErrorEvent.webidl',
     'MediaStreamEvent.webidl',
     'MediaStreamTrackEvent.webidl',
     'MozClirModeEvent.webidl',
     'MozContactChangeEvent.webidl',
     'MozEmergencyCbModeEvent.webidl',
-    'MozMessageDeletedEvent.webidl',
-    'MozMmsEvent.webidl',
     'MozOtaStatusEvent.webidl',
     'MozSettingsEvent.webidl',
     'MozSettingsTransactionEvent.webidl',
-    'MozSmsEvent.webidl',
     'MozStkCommandEvent.webidl',
     'PageTransitionEvent.webidl',
     'PerformanceEntryEvent.webidl',
     'PluginCrashedEvent.webidl',
     'PopStateEvent.webidl',
     'PopupBlockedEvent.webidl',
     'PresentationConnectionAvailableEvent.webidl',
     'PresentationConnectionClosedEvent.webidl',
--- a/layout/build/nsLayoutModule.cpp
+++ b/layout/build/nsLayoutModule.cpp
@@ -193,21 +193,17 @@ NS_NewXULTreeBuilder(nsISupports* aOuter
 static void Shutdown();
 
 #include "nsGeolocation.h"
 #include "nsDeviceSensors.h"
 #include "mozilla/dom/nsContentSecurityManager.h"
 #include "mozilla/dom/nsCSPService.h"
 #include "mozilla/dom/nsCSPContext.h"
 #include "nsIIccService.h"
-#include "nsISmsService.h"
-#include "nsIMmsService.h"
 #include "nsIMobileConnectionService.h"
-#include "nsIMobileMessageService.h"
-#include "nsIMobileMessageDatabaseService.h"
 #include "nsIPowerManagerService.h"
 #include "nsIMediaManager.h"
 #include "mozilla/dom/nsMixedContentBlocker.h"
 
 #include "AudioChannelService.h"
 #include "mozilla/net/WebSocketEventService.h"
 
 #include "mozilla/dom/FlyWebService.h"
@@ -336,23 +332,17 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(AudioChan
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDeviceSensors)
 
 #ifndef MOZ_WIDGET_GONK
 #if defined(ANDROID)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsHapticFeedback)
 #endif
 #endif
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(ThirdPartyUtil, Init)
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsISmsService, NS_CreateSmsService)
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIIccService, NS_CreateIccService)
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIMmsService, NS_CreateMmsService)
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIMobileMessageService,
-                                         NS_CreateMobileMessageService)
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIMobileMessageDatabaseService,
-                                         NS_CreateMobileMessageDatabaseService)
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIPowerManagerService,
                                          PowerManagerService::GetInstance)
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsITimeService,
                                          TimeService::GetInstance)
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIStreamingProtocolControllerService,
                                          StreamingProtocolControllerService::GetInstance)
 
 #ifdef MOZ_WIDGET_GONK
@@ -801,21 +791,17 @@ NS_DEFINE_NAMED_CID(NS_HAPTICFEEDBACK_CI
 #endif
 #ifndef DISABLE_MOZ_RIL_GEOLOC
 #ifdef MOZ_WIDGET_GONK
 NS_DEFINE_NAMED_CID(GONK_GPS_GEOLOCATION_PROVIDER_CID);
 #endif
 #endif
 NS_DEFINE_NAMED_CID(TELEPHONY_SERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_MOBILE_CONNECTION_SERVICE_CID);
-NS_DEFINE_NAMED_CID(SMS_SERVICE_CID);
 NS_DEFINE_NAMED_CID(ICC_SERVICE_CID);
-NS_DEFINE_NAMED_CID(MMS_SERVICE_CID);
-NS_DEFINE_NAMED_CID(MOBILE_MESSAGE_SERVICE_CID);
-NS_DEFINE_NAMED_CID(MOBILE_MESSAGE_DATABASE_SERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_POWERMANAGERSERVICE_CID);
 NS_DEFINE_NAMED_CID(OSFILECONSTANTSSERVICE_CID);
 NS_DEFINE_NAMED_CID(UDPSOCKETCHILD_CID);
 NS_DEFINE_NAMED_CID(NS_TIMESERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_MEDIASTREAMCONTROLLERSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_MEDIAMANAGERSERVICE_CID);
 #ifdef MOZ_WEBSPEECH_TEST_BACKEND
 NS_DEFINE_NAMED_CID(NS_FAKE_SPEECH_RECOGNITION_SERVICE_CID);
@@ -1098,21 +1084,17 @@ static const mozilla::Module::CIDEntry k
   { &kNS_DEVICE_SENSORS_CID, false, nullptr, nsDeviceSensorsConstructor },
 #ifndef MOZ_WIDGET_GONK
 #if defined(ANDROID)
   { &kNS_HAPTICFEEDBACK_CID, false, nullptr, nsHapticFeedbackConstructor },
 #endif
 #endif
   { &kTHIRDPARTYUTIL_CID, false, nullptr, ThirdPartyUtilConstructor },
   { &kNS_STRUCTUREDCLONECONTAINER_CID, false, nullptr, nsStructuredCloneContainerConstructor },
-  { &kSMS_SERVICE_CID, false, nullptr, nsISmsServiceConstructor },
   { &kICC_SERVICE_CID, false, nullptr, nsIIccServiceConstructor },
-  { &kMMS_SERVICE_CID, false, nullptr, nsIMmsServiceConstructor },
-  { &kMOBILE_MESSAGE_SERVICE_CID, false, nullptr, nsIMobileMessageServiceConstructor },
-  { &kMOBILE_MESSAGE_DATABASE_SERVICE_CID, false, nullptr, nsIMobileMessageDatabaseServiceConstructor },
   { &kNS_POWERMANAGERSERVICE_CID, false, nullptr, nsIPowerManagerServiceConstructor, Module::ALLOW_IN_GPU_PROCESS },
   { &kOSFILECONSTANTSSERVICE_CID, true, nullptr, OSFileConstantsServiceConstructor },
   { &kUDPSOCKETCHILD_CID, false, nullptr, UDPSocketChildConstructor },
   { &kGECKO_MEDIA_PLUGIN_SERVICE_CID, true, nullptr, GeckoMediaPluginServiceConstructor },
   { &kNS_TIMESERVICE_CID, false, nullptr, nsITimeServiceConstructor },
   { &kNS_MEDIASTREAMCONTROLLERSERVICE_CID, false, nullptr, nsIStreamingProtocolControllerServiceConstructor },
 #if defined(MOZ_WIDGET_GONK) && !defined(DISABLE_MOZ_RIL_GEOLOC)
   { &kGONK_GPS_GEOLOCATION_PROVIDER_CID, false, nullptr, nsIGeolocationProviderConstructor },
@@ -1256,21 +1238,17 @@ static const mozilla::Module::ContractID
   { NS_DEVICE_SENSORS_CONTRACTID, &kNS_DEVICE_SENSORS_CID },
 #ifndef MOZ_WIDGET_GONK
 #if defined(ANDROID)
   { "@mozilla.org/widget/hapticfeedback;1", &kNS_HAPTICFEEDBACK_CID },
 #endif
 #endif
   { THIRDPARTYUTIL_CONTRACTID, &kTHIRDPARTYUTIL_CID },
   { NS_STRUCTUREDCLONECONTAINER_CONTRACTID, &kNS_STRUCTUREDCLONECONTAINER_CID },
-  { SMS_SERVICE_CONTRACTID, &kSMS_SERVICE_CID },
   { ICC_SERVICE_CONTRACTID, &kICC_SERVICE_CID },
-  { MMS_SERVICE_CONTRACTID, &kMMS_SERVICE_CID },
-  { MOBILE_MESSAGE_SERVICE_CONTRACTID, &kMOBILE_MESSAGE_SERVICE_CID },
-  { MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID, &kMOBILE_MESSAGE_DATABASE_SERVICE_CID },
   { POWERMANAGERSERVICE_CONTRACTID, &kNS_POWERMANAGERSERVICE_CID, Module::ALLOW_IN_GPU_PROCESS },
   { OSFILECONSTANTSSERVICE_CONTRACTID, &kOSFILECONSTANTSSERVICE_CID },
   { "@mozilla.org/udp-socket-child;1", &kUDPSOCKETCHILD_CID },
   { TIMESERVICE_CONTRACTID, &kNS_TIMESERVICE_CID },
   { MEDIASTREAMCONTROLLERSERVICE_CONTRACTID, &kNS_MEDIASTREAMCONTROLLERSERVICE_CID },
 #if defined(MOZ_WIDGET_GONK) && !defined(DISABLE_MOZ_RIL_GEOLOC)
   { GONK_GPS_GEOLOCATION_PROVIDER_CONTRACTID, &kGONK_GPS_GEOLOCATION_PROVIDER_CID },
 #endif
--- a/mobile/android/base/AppConstants.java.in
+++ b/mobile/android/base/AppConstants.java.in
@@ -217,23 +217,16 @@ public class AppConstants {
 
     public static final boolean MOZ_UPDATER =
 //#ifdef MOZ_UPDATER
     true;
 //#else
     false;
 //#endif
 
-    public static final boolean MOZ_WEBSMS_BACKEND =
-//#ifdef MOZ_WEBSMS_BACKEND
-    true;
-//#else
-    false;
-//#endif
-
     // Android Beam is only supported on API14+, so we don't even bother building
     // it if this APK doesn't include API14 support.
     public static final boolean MOZ_ANDROID_BEAM =
 //#ifdef MOZ_ANDROID_BEAM
     true;
 //#else
     false;
 //#endif
--- a/mobile/android/base/FennecManifest_permissions.xml.in
+++ b/mobile/android/base/FennecManifest_permissions.xml.in
@@ -32,25 +32,16 @@
     <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/>
     <uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS"/>
 
     <uses-permission android:name="android.permission.WAKE_LOCK"/>
     <uses-permission android:name="android.permission.VIBRATE"/>
 #ifdef MOZ_ANDROID_DOWNLOADS_INTEGRATION
     <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
 #endif
-#ifdef MOZ_WEBSMS_BACKEND
-    <!-- WebSMS -->
-    <uses-permission android:name="android.permission.SEND_SMS"/>
-    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
-    <uses-permission android:name="android.permission.WRITE_SMS"/>
-    <uses-permission android:name="android.permission.READ_SMS"/>
-
-    <uses-feature android:name="android.hardware.telephony"/>
-#endif
 
     <uses-feature android:name="android.hardware.location" android:required="false"/>
     <uses-feature android:name="android.hardware.location.gps" android:required="false"/>
     <uses-feature android:name="android.hardware.touchscreen"/>
 
     <!-- Tab Queue -->
     <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
 
--- a/mobile/android/base/geckoview.ddf
+++ b/mobile/android/base/geckoview.ddf
@@ -33,17 +33,16 @@ show allResults
   org.mozilla.gecko.GeckoThread \
   org.mozilla.gecko.GeckoView \
   org.mozilla.gecko.GlobalHistory \
   org.mozilla.gecko.InputMethods \
   org.mozilla.gecko.NSSBridge \
   org.mozilla.gecko.NotificationClient \
   org.mozilla.gecko.NotificationHandler \
   org.mozilla.gecko.PrefsHelper \
-  org.mozilla.gecko.SmsManager \
   org.mozilla.gecko.SysInfo \
   org.mozilla.gecko.TouchEventInterceptor \
   org.mozilla.gecko.ZoomConstraints
 
 [middle] = \
   org.mozilla.gecko.prompts.* \
   org.mozilla.gecko.FormAssistPopup \
   org.mozilla.gecko.GeckoActivity \
--- a/mobile/android/base/java/org/mozilla/gecko/BrowserApp.java
+++ b/mobile/android/base/java/org/mozilla/gecko/BrowserApp.java
@@ -1514,23 +1514,16 @@ public class BrowserApp extends GeckoApp
         if (mFormAssistPopup != null)
             mFormAssistPopup.destroy();
         if (mTextSelection != null)
             mTextSelection.destroy();
         NotificationHelper.destroy();
         IntentHelper.destroy();
         GeckoNetworkManager.destroy();
 
-        if (SmsManager.isEnabled()) {
-            SmsManager.getInstance().stop();
-            if (isFinishing()) {
-                SmsManager.getInstance().shutdown();
-            }
-        }
-
         super.onDestroy();
 
         if (!isFinishing()) {
             // GeckoApp was not intentionally destroyed, so keep our process alive.
             return;
         }
 
         // Wait for Gecko to handle our pause event sent in onPause.
--- a/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java
+++ b/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java
@@ -1604,20 +1604,16 @@ public abstract class GeckoApp
             // Copy extras.
             settingsIntent.putExtras(intent.getUnsafe());
             startActivity(settingsIntent);
         }
 
         //app state callbacks
         mAppStateListeners = new LinkedList<GeckoAppShell.AppStateListener>();
 
-        if (SmsManager.isEnabled()) {
-            SmsManager.getInstance().start();
-        }
-
         mPromptService = new PromptService(this);
 
         // Trigger the completion of the telemetry timer that wraps activity startup,
         // then grab the duration to give to FHR.
         mJavaUiStartupTimer.stop();
         final long javaDuration = mJavaUiStartupTimer.getElapsed();
 
         ThreadUtils.getBackgroundHandler().postDelayed(new Runnable() {
--- a/mobile/android/base/moz.build
+++ b/mobile/android/base/moz.build
@@ -235,17 +235,16 @@ gvjar.sources += [geckoview_source_dir +
     'GeckoEditableListener.java',
     'GeckoHalDefines.java',
     'GeckoInputConnection.java',
     'GeckoNetworkManager.java',
     'GeckoProfile.java',
     'GeckoProfileDirectories.java',
     'GeckoScreenOrientation.java',
     'GeckoSharedPrefs.java',
-    'GeckoSmsManager.java',
     'GeckoThread.java',
     'GeckoView.java',
     'GeckoViewChrome.java',
     'GeckoViewContent.java',
     'GeckoViewFragment.java',
     'gfx/BitmapUtils.java',
     'gfx/BufferedImage.java',
     'gfx/BufferedImageGLInfo.java',
@@ -273,17 +272,16 @@ gvjar.sources += [geckoview_source_dir +
     'InputConnectionListener.java',
     'InputMethods.java',
     'NotificationListener.java',
     'NSSBridge.java',
     'permissions/PermissionBlock.java',
     'permissions/Permissions.java',
     'permissions/PermissionsHelper.java',
     'PrefsHelper.java',
-    'SmsManager.java',
     'sqlite/ByteBufferInputStream.java',
     'sqlite/MatrixBlobCursor.java',
     'sqlite/SQLiteBridge.java',
     'sqlite/SQLiteBridgeException.java',
     'TouchEventInterceptor.java',
 ]]
 
 gvjar.sources += [geckoview_thirdparty_source_dir + f for f in [
--- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java
+++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java
@@ -1990,97 +1990,16 @@ public class GeckoAppShell
         geckoInterface.setUriTitle(uri, title);
     }
 
     @WrapForJNI(calledFrom = "gecko")
     private static void hideProgressDialog() {
         // unused stub
     }
 
-    /*
-     * WebSMS related methods.
-     */
-    public static void sendMessage(String aNumber, String aMessage, int aRequestId, boolean aShouldNotify) {
-        if (!SmsManager.isEnabled()) {
-            return;
-        }
-
-        SmsManager.getInstance().send(aNumber, aMessage, aRequestId, aShouldNotify);
-    }
-
-    @WrapForJNI(calledFrom = "gecko")
-    private static void sendMessage(String aNumber, String aMessage, int aRequestId) {
-        sendMessage(aNumber, aMessage, aRequestId, /* shouldNotify */ true);
-    }
-
-    @WrapForJNI(calledFrom = "gecko")
-    private static void getMessage(int aMessageId, int aRequestId) {
-        if (!SmsManager.isEnabled()) {
-            return;
-        }
-
-        SmsManager.getInstance().getMessage(aMessageId, aRequestId);
-    }
-
-    @WrapForJNI(calledFrom = "gecko")
-    private static void deleteMessage(int aMessageId, int aRequestId) {
-        if (!SmsManager.isEnabled()) {
-            return;
-        }
-
-        SmsManager.getInstance().deleteMessage(aMessageId, aRequestId);
-    }
-
-    @WrapForJNI(calledFrom = "gecko")
-    private static void markMessageRead(int aMessageId, boolean aValue, boolean aSendReadReport, int aRequestId) {
-        if (!SmsManager.isEnabled()) {
-            return;
-        }
-
-        SmsManager.getInstance().markMessageRead(aMessageId, aValue, aSendReadReport, aRequestId);
-    }
-
-    @WrapForJNI(calledFrom = "gecko")
-    private static void createMessageCursor(long aStartDate, long aEndDate, String[] aNumbers, int aNumbersCount, String aDelivery, boolean aHasRead, boolean aRead, boolean aHasThreadId, long aThreadId, boolean aReverse, int aRequestId) {
-        if (!SmsManager.isEnabled()) {
-            return;
-        }
-
-        SmsManager.getInstance().createMessageCursor(aStartDate, aEndDate, aNumbers, aNumbersCount, aDelivery, aHasRead, aRead, aHasThreadId, aThreadId, aReverse, aRequestId);
-    }
-
-    @WrapForJNI(calledFrom = "gecko")
-    private static void getNextMessage(int aRequestId) {
-        if (!SmsManager.isEnabled()) {
-            return;
-        }
-
-        SmsManager.getInstance().getNextMessage(aRequestId);
-    }
-
-    @WrapForJNI(calledFrom = "gecko")
-    private static void createThreadCursor(int aRequestId) {
-        Log.i("GeckoAppShell", "CreateThreadCursorWrapper!");
-
-        if (!SmsManager.isEnabled()) {
-            return;
-        }
-
-        SmsManager.getInstance().createThreadCursor(aRequestId);
-    }
-
-    @WrapForJNI(calledFrom = "gecko")
-    private static void getNextThread(int aRequestId) {
-        if (!SmsManager.isEnabled()) {
-            return;
-        }
-
-        SmsManager.getInstance().getNextThread(aRequestId);
-    }
-
     /* Called by JNI from AndroidBridge, and by reflection from tests/BaseTest.java.in */
     @WrapForJNI(calledFrom = "gecko")
     @RobocopTarget
     public static boolean isTablet() {
         return HardwareUtils.isTablet();
     }
 
     private static boolean sImeWasEnabledOnLastResize = false;
deleted file mode 100644
--- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoSmsManager.java
+++ /dev/null
@@ -1,1244 +0,0 @@
-/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
- * 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/. */
-
-package org.mozilla.gecko;
-
-import org.mozilla.gecko.annotation.WrapForJNI;
-
-import android.app.Activity;
-import android.app.PendingIntent;
-import android.content.BroadcastReceiver;
-import android.content.ContentResolver;
-import android.content.ContentUris;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.database.Cursor;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.provider.Telephony;
-import android.telephony.SmsManager;
-import android.telephony.SmsMessage;
-import android.util.Log;
-
-import static android.telephony.SmsMessage.MessageClass;
-import static org.mozilla.gecko.SmsManager.ISmsManager;
-
-import java.util.ArrayList;
-import java.util.Formatter;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * The envelope class contains all information that are needed to keep track of
- * a sent SMS.
- */
-class Envelope
-{
-  enum SubParts {
-    SENT_PART,
-    DELIVERED_PART
-  }
-
-  protected int       mId;
-  protected int       mMessageId;
-  protected long      mMessageTimestamp;
-
-  /**
-   * Number of sent/delivered remaining parts.
-   * @note The array has much slots as SubParts items.
-   */
-  protected int[]     mRemainingParts;
-
-  /**
-   * Whether sending/delivering is currently failing.
-   * @note The array has much slots as SubParts items.
-   */
-  protected boolean[] mFailing;
-
-  /**
-   * Error type (only for sent).
-   */
-  protected int       mError;
-
-  public Envelope(int aId, int aParts) {
-    mId = aId;
-    mMessageId = -1;
-    mError = GeckoSmsManager.kNoError;
-
-    int size = SubParts.values().length;
-    mRemainingParts = new int[size];
-    mFailing = new boolean[size];
-
-    for (int i = 0; i < size; ++i) {
-      mRemainingParts[i] = aParts;
-      mFailing[i] = false;
-    }
-  }
-
-  public void decreaseRemainingParts(SubParts aType) {
-    --mRemainingParts[aType.ordinal()];
-
-    if (mRemainingParts[SubParts.SENT_PART.ordinal()] >
-        mRemainingParts[SubParts.DELIVERED_PART.ordinal()]) {
-      Log.e("GeckoSmsManager", "Delivered more parts than we sent!?");
-    }
-  }
-
-  public boolean arePartsRemaining(SubParts aType) {
-    return mRemainingParts[aType.ordinal()] != 0;
-  }
-
-  public void markAsFailed(SubParts aType) {
-    mFailing[aType.ordinal()] = true;
-  }
-
-  public boolean isFailing(SubParts aType) {
-    return mFailing[aType.ordinal()];
-  }
-
-  public int getMessageId() {
-    return mMessageId;
-  }
-
-  public void setMessageId(int aMessageId) {
-    mMessageId = aMessageId;
-  }
-
-  public long getMessageTimestamp() {
-    return mMessageTimestamp;
-  }
-
-  public void setMessageTimestamp(long aMessageTimestamp) {
-    mMessageTimestamp = aMessageTimestamp;
-  }
-
-  public int getError() {
-    return mError;
-  }
-
-  public void setError(int aError) {
-    mError = aError;
-  }
-}
-
-/**
- * Postman class is a singleton that manages Envelope instances.
- */
-class Postman
-{
-  public static final int kUnknownEnvelopeId = -1;
-
-  private static final Postman sInstance = new Postman();
-
-  private final ArrayList<Envelope> mEnvelopes = new ArrayList<>(1);
-
-  private Postman() {}
-
-  public static Postman getInstance() {
-    return sInstance;
-  }
-
-  public int createEnvelope(int aParts) {
-    /*
-     * We are going to create the envelope in the first empty slot in the array
-     * list. If there is no empty slot, we create a new one.
-     */
-    int size = mEnvelopes.size();
-
-    for (int i = 0; i < size; ++i) {
-      if (mEnvelopes.get(i) == null) {
-        mEnvelopes.set(i, new Envelope(i, aParts));
-        return i;
-      }
-    }
-
-    mEnvelopes.add(new Envelope(size, aParts));
-    return size;
-  }
-
-  public Envelope getEnvelope(int aId) {
-    if (aId < 0 || mEnvelopes.size() <= aId) {
-      Log.e("GeckoSmsManager", "Trying to get an unknown Envelope!");
-      return null;
-    }
-
-    Envelope envelope = mEnvelopes.get(aId);
-    if (envelope == null) {
-      Log.e("GeckoSmsManager", "Trying to get an empty Envelope!");
-    }
-
-    return envelope;
-  }
-
-  public void destroyEnvelope(int aId) {
-    if (aId < 0 || mEnvelopes.size() <= aId) {
-      Log.e("GeckoSmsManager", "Trying to destroy an unknown Envelope!");
-      return;
-    }
-
-    if (mEnvelopes.set(aId, null) == null) {
-      Log.e("GeckoSmsManager", "Trying to destroy an empty Envelope!");
-    }
-  }
-}
-
-class SmsIOThread extends HandlerThread {
-  private final static SmsIOThread sInstance = new SmsIOThread();
-
-  private Handler mHandler;
-
-  public static SmsIOThread getInstance() {
-    return sInstance;
-  }
-
-  SmsIOThread() {
-    super("SmsIOThread");
-  }
-
-  @Override
-  public void start() {
-    super.start();
-    mHandler = new Handler(getLooper());
-  }
-
-  public boolean execute(Runnable r) {
-    return mHandler.post(r);
-  }
-}
-
-class MessagesListManager
-{
-  private static final MessagesListManager sInstance = new MessagesListManager();
-
-  public static MessagesListManager getInstance() {
-    return sInstance;
-  }
-
-  private final HashMap<Integer, Cursor> mCursors = new HashMap<>();
-
-  public void add(int id, Cursor aCursor) {
-    if (mCursors.containsKey(id)) {
-      Log.e("GeckoSmsManager", "Trying to overwrite cursor!");
-      return;
-    }
-
-    mCursors.put(id, aCursor);
-  }
-
-  public Cursor get(int aId) {
-    if (!mCursors.containsKey(aId)) {
-      Log.e("GeckoSmsManager", "Cursor doesn't exist!");
-      return null;
-    }
-
-    return mCursors.get(aId);
-  }
-
-  public void remove(int aId) {
-    if (!mCursors.containsKey(aId)) {
-      Log.e("GeckoSmsManager", "Cursor doesn't exist!");
-      return;
-    }
-
-    mCursors.remove(aId);
-  }
-
-  public void clear() {
-    Set<Map.Entry<Integer, Cursor>> entries = mCursors.entrySet();
-    Iterator<Map.Entry<Integer, Cursor>> it = entries.iterator();
-    while (it.hasNext()) {
-      it.next().getValue().close();
-    }
-
-    mCursors.clear();
-  }
-}
-
-public class GeckoSmsManager
-  extends BroadcastReceiver
-  implements ISmsManager
-{
-  public final static String ACTION_SMS_SENT      = "org.mozilla.gecko.SMS_SENT";
-  public final static String ACTION_SMS_DELIVERED = "org.mozilla.gecko.SMS_DELIVERED";
-
-  /*
-   * Make sure that the following error codes are in sync with |ErrorType| in:
-   * dom/mobilemessage/interfaces/nsIMobileMessageCallback.idl
-   * The error codes are owned by the DOM.
-   */
-  public final static int kNoError               = 0;
-  public final static int kNoSignalError         = 1;
-  public final static int kNotFoundError         = 2;
-  public final static int kUnknownError          = 3;
-  public final static int kInternalError         = 4;
-  public final static int kNoSimCardError        = 5;
-  public final static int kRadioDisabledError    = 6;
-  public final static int kInvalidAddressError   = 7;
-  public final static int kFdnCheckError         = 8;
-  public final static int kNonActiveSimCardError = 9;
-  public final static int kStorageFullError      = 10;
-  public final static int kSimNotMatchedError    = 11;
-  public final static int kNetworkProblemsError = 12;
-  public final static int kGeneralProblemsError = 13;
-  public final static int kServiceNotAvailableError      = 14;
-  public final static int kMessageTooLongForNetworkError = 15;
-  public final static int kServiceNotSupportedError      = 16;
-  public final static int kRetryRequiredError   = 17;
-
-  private final static int kMaxMessageSize    = 160;
-
-  private final static Uri kSmsContentUri        = Telephony.Sms.Inbox.CONTENT_URI;
-  private final static Uri kSmsSentContentUri    = Telephony.Sms.Sent.CONTENT_URI;
-  private final static Uri kSmsThreadsContentUri = Telephony.Sms.Conversations.CONTENT_URI;
-
-  private final static int kSmsTypeInbox      = Telephony.Sms.MESSAGE_TYPE_INBOX;
-  private final static int kSmsTypeSentbox    = Telephony.Sms.MESSAGE_TYPE_SENT;
-
-  /*
-   * Keep the following state codes in syng with |DeliveryState| in:
-   * dom/mobilemessage/Types.h
-   */
-  private final static int kDeliveryStateSent          = 0;
-  private final static int kDeliveryStateReceived      = 1;
-  private final static int kDeliveryStateSending       = 2;
-  private final static int kDeliveryStateError         = 3;
-  private final static int kDeliveryStateUnknown       = 4;
-  private final static int kDeliveryStateNotDownloaded = 5;
-  private final static int kDeliveryStateEndGuard      = 6;
-
-  /*
-   * Keep the following status codes in sync with |DeliveryStatus| in:
-   * dom/mobilemessage/Types.h
-   */
-  private final static int kDeliveryStatusNotApplicable = 0;
-  private final static int kDeliveryStatusSuccess       = 1;
-  private final static int kDeliveryStatusPending       = 2;
-  private final static int kDeliveryStatusError         = 3;
-
-  /*
-   * Keep the following values in sync with |MessageClass| in:
-   * dom/mobilemessage/Types.h
-   */
-  private final static int kMessageClassNormal  = 0;
-  private final static int kMessageClassClass0  = 1;
-  private final static int kMessageClassClass1  = 2;
-  private final static int kMessageClassClass2  = 3;
-  private final static int kMessageClassClass3  = 4;
-
-  private final static String[] kRequiredMessageRows = { "_id", "address", "body", "date", "type", "status", "read", "thread_id" };
-  private final static String[] kRequiredMessageRowsForThread = { "_id", "address", "body", "read", "subject", "date" };
-  private final static String[] kThreadProjection = { "thread_id" };
-
-  // Used to generate monotonically increasing GUIDs.
-  private static final AtomicInteger pendingIntentGuid = new AtomicInteger(Integer.MIN_VALUE);
-
-  // The maximum value of a 32 bit signed integer. Used to enforce a limit on ids.
-  private static final long UNSIGNED_INTEGER_MAX_VALUE = Integer.MAX_VALUE * 2L + 1L;
-
-  public GeckoSmsManager() {
-    if (SmsIOThread.getInstance().getState() == Thread.State.NEW) {
-      SmsIOThread.getInstance().start();
-    }
-  }
-
-  private boolean isDefaultSmsApp(Context context) {
-    String myPackageName = context.getPackageName();
-    return Telephony.Sms.getDefaultSmsPackage(context).equals(myPackageName);
-  }
-
-  @Override
-  public void start() {
-    IntentFilter smsFilter = new IntentFilter();
-    smsFilter.addAction(Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
-    smsFilter.addAction(ACTION_SMS_SENT);
-    smsFilter.addAction(ACTION_SMS_DELIVERED);
-
-    GeckoAppShell.getContext().registerReceiver(this, smsFilter);
-  }
-
-  /**
-   * Build up the SMS message body from the SmsMessage array of received SMS
-   *
-   * @param msgs The SmsMessage array of the received SMS
-   * @return The text message body
-   */
-  private static String buildMessageBodyFromPdus(SmsMessage[] msgs) {
-    if (msgs.length == 1) {
-      // There is only one part, so grab the body directly.
-      return replaceFormFeeds(msgs[0].getDisplayMessageBody());
-    } else {
-      // Build up the body from the parts.
-      StringBuilder body = new StringBuilder();
-      for (SmsMessage msg : msgs) {
-        // getDisplayMessageBody() can NPE if mWrappedMessage inside is null.
-        body.append(msg.getDisplayMessageBody());
-      }
-      return replaceFormFeeds(body.toString());
-    }
-  }
-
-  // Some providers send formfeeds in their messages. Convert those formfeeds to newlines.
-  private static String replaceFormFeeds(String s) {
-    return s == null ? "" : s.replace('\f', '\n');
-  }
-
-  @Override
-  public void onReceive(Context context, Intent intent) {
-    if (intent.getAction().equals(Telephony.Sms.Intents.SMS_DELIVER_ACTION) ||
-        intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
-      // If we're the default SMS, ignore SMS_RECEIVED intents since we'll handle
-      // the SMS_DELIVER intent instead.
-      if (isDefaultSmsApp(GeckoAppShell.getContext()) && intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
-        return;
-      }
-
-      // TODO: Try to find the receiver number to be able to populate
-      //       SmsMessage.receiver.
-      SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
-      if (messages == null || messages.length == 0) {
-        return;
-      }
-
-      SmsMessage sms = messages[0];
-      String body = buildMessageBodyFromPdus(messages);
-      long timestamp = System.currentTimeMillis();
-
-      int id = 0;
-      // We only need to save the message if we're the default SMS app
-      if (intent.getAction().equals(Telephony.Sms.Intents.SMS_DELIVER_ACTION)) {
-        id = saveReceivedMessage(context,
-                               sms.getDisplayOriginatingAddress(),
-                               body,
-                               sms.getTimestampMillis(),
-                               timestamp,
-                               sms.getPseudoSubject());
-      }
-
-      notifySmsReceived(id,
-                        sms.getDisplayOriginatingAddress(),
-                        body,
-                        getGeckoMessageClass(sms.getMessageClass()),
-                        sms.getTimestampMillis(),
-                        timestamp);
-
-      return;
-    }
-
-    if (intent.getAction().equals(ACTION_SMS_SENT) ||
-        intent.getAction().equals(ACTION_SMS_DELIVERED)) {
-      Bundle bundle = intent.getExtras();
-
-      if (bundle == null || !bundle.containsKey("envelopeId") ||
-          !bundle.containsKey("number") || !bundle.containsKey("message") ||
-          !bundle.containsKey("requestId")) {
-        Log.e("GeckoSmsManager", "Got an invalid ACTION_SMS_SENT/ACTION_SMS_DELIVERED!");
-        return;
-      }
-
-      int envelopeId = bundle.getInt("envelopeId");
-      Postman postman = Postman.getInstance();
-
-      Envelope envelope = postman.getEnvelope(envelopeId);
-      if (envelope == null) {
-        Log.e("GeckoSmsManager", "Got an invalid envelope id (or Envelope has been destroyed)!");
-        return;
-      }
-
-      Envelope.SubParts part = intent.getAction().equals(ACTION_SMS_SENT)
-                                 ? Envelope.SubParts.SENT_PART
-                                 : Envelope.SubParts.DELIVERED_PART;
-      envelope.decreaseRemainingParts(part);
-
-
-      if (getResultCode() != Activity.RESULT_OK) {
-        switch (getResultCode()) {
-          case SmsManager.RESULT_ERROR_NULL_PDU:
-            envelope.setError(kInternalError);
-            break;
-          case SmsManager.RESULT_ERROR_NO_SERVICE:
-          case SmsManager.RESULT_ERROR_RADIO_OFF:
-            envelope.setError(kNoSignalError);
-            break;
-          case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
-          default:
-            envelope.setError(kUnknownError);
-            break;
-        }
-        envelope.markAsFailed(part);
-        Log.i("GeckoSmsManager", "SMS part sending failed!");
-      }
-
-      if (envelope.arePartsRemaining(part)) {
-        return;
-      }
-
-      if (envelope.isFailing(part)) {
-        if (part == Envelope.SubParts.SENT_PART) {
-          if (bundle.getBoolean("shouldNotify")) {
-            notifySmsSendFailed(envelope.getError(), bundle.getInt("requestId"));
-          }
-          Log.i("GeckoSmsManager", "SMS sending failed!");
-        } else {
-          notifySmsDelivery(envelope.getMessageId(),
-                            kDeliveryStatusError,
-                            bundle.getString("number"),
-                            bundle.getString("message"),
-                            envelope.getMessageTimestamp());
-          Log.i("GeckoSmsManager", "SMS delivery failed!");
-        }
-      } else {
-        if (part == Envelope.SubParts.SENT_PART) {
-          String number = bundle.getString("number");
-          String message = bundle.getString("message");
-          long timestamp = System.currentTimeMillis();
-
-          // save message only if we're default SMS app, otherwise sendTextMessage does it for us
-          int id = 0;
-          if (isDefaultSmsApp(GeckoAppShell.getContext())) {
-            id = saveSentMessage(number, message, timestamp);
-          }
-
-          if (bundle.getBoolean("shouldNotify")) {
-            notifySmsSent(id, number, message, timestamp, bundle.getInt("requestId"));
-          }
-
-          envelope.setMessageId(id);
-          envelope.setMessageTimestamp(timestamp);
-
-          Log.i("GeckoSmsManager", "SMS sending was successful!");
-        } else {
-          Uri id = ContentUris.withAppendedId(kSmsContentUri, envelope.getMessageId());
-          updateMessageStatus(id, Telephony.Sms.STATUS_COMPLETE);
-
-          notifySmsDelivery(envelope.getMessageId(),
-                            kDeliveryStatusSuccess,
-                            bundle.getString("number"),
-                            bundle.getString("message"),
-                            envelope.getMessageTimestamp());
-          Log.i("GeckoSmsManager", "SMS successfully delivered!");
-        }
-      }
-
-      // Destroy the envelope object only if the SMS has been sent and delivered.
-      if (!envelope.arePartsRemaining(Envelope.SubParts.SENT_PART) &&
-          !envelope.arePartsRemaining(Envelope.SubParts.DELIVERED_PART)) {
-        postman.destroyEnvelope(envelopeId);
-      }
-    }
-  }
-
-  @Override
-  public void send(String aNumber, String aMessage, int aRequestId, boolean aShouldNotify) {
-    int envelopeId = Postman.kUnknownEnvelopeId;
-
-    try {
-      SmsManager sm = SmsManager.getDefault();
-
-      Intent sentIntent = new Intent(GeckoAppShell.getContext(), GeckoSmsManager.class);
-      sentIntent.setAction(ACTION_SMS_SENT);
-      Intent deliveredIntent = new Intent(GeckoAppShell.getContext(), GeckoSmsManager.class);
-      deliveredIntent.setAction(ACTION_SMS_DELIVERED);
-
-      Bundle bundle = new Bundle();
-      bundle.putString("number", aNumber);
-      bundle.putString("message", aMessage);
-      bundle.putInt("requestId", aRequestId);
-      bundle.putBoolean("shouldNotify", aShouldNotify);
-
-      if (aMessage.length() <= kMaxMessageSize) {
-        envelopeId = Postman.getInstance().createEnvelope(1);
-        bundle.putInt("envelopeId", envelopeId);
-
-        sentIntent.putExtras(bundle);
-        deliveredIntent.putExtras(bundle);
-
-        /*
-         * There are a few things to know about getBroadcast and pending intents:
-         * - the pending intents are in a shared pool maintained by the system;
-         * - each pending intent is identified by a token;
-         * - when a new pending intent is created, if it has the same token as
-         *   another intent in the pool, one of them has to be removed.
-         *
-         * To prevent having a hard time because of this situation, we give a
-         * unique id to all pending intents we are creating. This unique id is
-         * generated by GetPendingIntentUID().
-         */
-        PendingIntent sentPendingIntent =
-          PendingIntent.getBroadcast(GeckoAppShell.getContext(),
-                                     pendingIntentGuid.incrementAndGet(), sentIntent,
-                                     PendingIntent.FLAG_CANCEL_CURRENT);
-
-        PendingIntent deliveredPendingIntent =
-          PendingIntent.getBroadcast(GeckoAppShell.getContext(),
-                                     pendingIntentGuid.incrementAndGet(), deliveredIntent,
-                                     PendingIntent.FLAG_CANCEL_CURRENT);
-
-        sm.sendTextMessage(aNumber, null, aMessage,
-                           sentPendingIntent, deliveredPendingIntent);
-      } else {
-        ArrayList<String> parts = sm.divideMessage(aMessage);
-        envelopeId = Postman.getInstance().createEnvelope(parts.size());
-        bundle.putInt("envelopeId", envelopeId);
-
-        sentIntent.putExtras(bundle);
-        deliveredIntent.putExtras(bundle);
-
-        ArrayList<PendingIntent> sentPendingIntents =
-          new ArrayList<PendingIntent>(parts.size());
-        ArrayList<PendingIntent> deliveredPendingIntents =
-          new ArrayList<PendingIntent>(parts.size());
-
-        for (int i = 0; i < parts.size(); ++i) {
-          sentPendingIntents.add(
-            PendingIntent.getBroadcast(GeckoAppShell.getContext(),
-                                       pendingIntentGuid.incrementAndGet(), sentIntent,
-                                       PendingIntent.FLAG_CANCEL_CURRENT)
-          );
-
-          deliveredPendingIntents.add(
-            PendingIntent.getBroadcast(GeckoAppShell.getContext(),
-                                       pendingIntentGuid.incrementAndGet(), deliveredIntent,
-                                       PendingIntent.FLAG_CANCEL_CURRENT)
-          );
-        }
-
-        sm.sendMultipartTextMessage(aNumber, null, parts, sentPendingIntents,
-                                    deliveredPendingIntents);
-      }
-    } catch (Exception e) {
-      Log.e("GeckoSmsManager", "Failed to send an SMS: ", e);
-
-      if (envelopeId != Postman.kUnknownEnvelopeId) {
-        Postman.getInstance().destroyEnvelope(envelopeId);
-      }
-
-      notifySmsSendFailed(kUnknownError, aRequestId);
-    }
-  }
-
-  public int saveSentMessage(String aRecipient, String aBody, long aDate) {
-    try {
-      ContentValues values = new ContentValues();
-      values.put(Telephony.Sms.ADDRESS, aRecipient);
-      values.put(Telephony.Sms.BODY, aBody);
-      values.put(Telephony.Sms.DATE, aDate);
-      // Always 'PENDING' because we always request status report.
-      values.put(Telephony.Sms.STATUS, Telephony.Sms.STATUS_PENDING);
-      values.put(Telephony.Sms.SEEN, 0);
-      values.put(Telephony.Sms.READ, 0);
-
-      ContentResolver cr = GeckoAppShell.getContext().getContentResolver();
-      Uri uri = cr.insert(kSmsSentContentUri, values);
-
-      long id = ContentUris.parseId(uri);
-
-      // The DOM API takes a 32bits unsigned int for the id. It's unlikely that
-      // we happen to need more than that but it doesn't cost to check.
-      if (id > UNSIGNED_INTEGER_MAX_VALUE) {
-        throw new IdTooHighException();
-      }
-
-      return (int)id;
-    } catch (IdTooHighException e) {
-      Log.e("GeckoSmsManager", "The id we received is higher than the higher allowed value.");
-      return -1;
-    } catch (Exception e) {
-      Log.e("GeckoSmsManager", "Something went wrong when trying to write a sent message", e);
-      return -1;
-    }
-  }
-
-  public void updateMessageStatus(Uri aId, int aStatus) {
-    ContentValues values = new ContentValues(1);
-    values.put(Telephony.Sms.STATUS, aStatus);
-
-    ContentResolver cr = GeckoAppShell.getContext().getContentResolver();
-    if (cr.update(aId, values, null, null) != 1) {
-      Log.i("GeckoSmsManager", "Failed to update message status!");
-    }
-  }
-
-  public int saveReceivedMessage(Context aContext, String aSender, String aBody, long aDateSent, long aDate, String aSubject) {
-    ContentValues values = new ContentValues();
-    values.put(Telephony.Sms.Inbox.ADDRESS, aSender);
-    values.put(Telephony.Sms.Inbox.BODY, aBody);
-    values.put(Telephony.Sms.Inbox.DATE_SENT, aDateSent);
-    values.put(Telephony.Sms.Inbox.DATE, aDate);
-    values.put(Telephony.Sms.Inbox.STATUS, Telephony.Sms.STATUS_COMPLETE);
-    values.put(Telephony.Sms.Inbox.READ, 0);
-    values.put(Telephony.Sms.Inbox.SEEN, 0);
-
-    ContentResolver cr = aContext.getContentResolver();
-    Uri uri = cr.insert(kSmsContentUri, values);
-
-    long id = ContentUris.parseId(uri);
-
-    // The DOM API takes a 32bits unsigned int for the id. It's unlikely that
-    // we happen to need more than that but it doesn't cost to check.
-    if (id > UNSIGNED_INTEGER_MAX_VALUE) {
-      Log.i("GeckoSmsManager", "The id we received is higher than the higher allowed value.");
-      return -1;
-    }
-
-    return (int)id;
-  }
-
-  @Override
-  public void getMessage(int aMessageId, int aRequestId) {
-    class GetMessageRunnable implements Runnable {
-      private final int mMessageId;
-      private final int mRequestId;
-
-      GetMessageRunnable(int aMessageId, int aRequestId) {
-        mMessageId = aMessageId;
-        mRequestId = aRequestId;
-      }
-
-      @Override
-      public void run() {
-        Cursor cursor = null;
-
-        try {
-          ContentResolver cr = GeckoAppShell.getContext().getContentResolver();
-          Uri message = ContentUris.withAppendedId(kSmsContentUri, mMessageId);
-
-          cursor = cr.query(message, kRequiredMessageRows, null, null, null);
-          if (cursor == null || cursor.getCount() == 0) {
-            throw new NotFoundException();
-          }
-
-          if (cursor.getCount() != 1) {
-            throw new TooManyResultsException();
-          }
-
-          cursor.moveToFirst();
-
-          if (cursor.getInt(cursor.getColumnIndex("_id")) != mMessageId) {
-            throw new UnmatchingIdException();
-          }
-
-          int type = cursor.getInt(cursor.getColumnIndex("type"));
-          int deliveryStatus;
-          String sender = "";
-          String receiver = "";
-
-          if (type == kSmsTypeInbox) {
-            deliveryStatus = kDeliveryStatusSuccess;
-            sender = cursor.getString(cursor.getColumnIndex("address"));
-          } else if (type == kSmsTypeSentbox) {
-            deliveryStatus = getGeckoDeliveryStatus(cursor.getInt(cursor.getColumnIndex("status")));
-            receiver = cursor.getString(cursor.getColumnIndex("address"));
-          } else {
-            throw new InvalidTypeException();
-          }
-
-          boolean read = cursor.getInt(cursor.getColumnIndex("read")) != 0;
-
-          notifyGetSms(cursor.getInt(cursor.getColumnIndex("_id")),
-                       deliveryStatus,
-                       receiver, sender,
-                       cursor.getString(cursor.getColumnIndex("body")),
-                       cursor.getLong(cursor.getColumnIndex("date")),
-                       read,
-                       mRequestId);
-        } catch (NotFoundException e) {
-          Log.i("GeckoSmsManager", "Message id " + mMessageId + " not found");
-          notifyGetSmsFailed(kNotFoundError, mRequestId);
-        } catch (UnmatchingIdException e) {
-          Log.e("GeckoSmsManager", "Requested message id (" + mMessageId +
-                                   ") is different from the one we got.");
-          notifyGetSmsFailed(kUnknownError, mRequestId);
-        } catch (TooManyResultsException e) {
-          Log.e("GeckoSmsManager", "Get too many results for id " + mMessageId);
-          notifyGetSmsFailed(kUnknownError, mRequestId);
-        } catch (InvalidTypeException e) {
-          Log.i("GeckoSmsManager", "Message has an invalid type, we ignore it.");
-          notifyGetSmsFailed(kNotFoundError, mRequestId);
-        } catch (Exception e) {
-          Log.e("GeckoSmsManager", "Error while trying to get message", e);
-          notifyGetSmsFailed(kUnknownError, mRequestId);
-        } finally {
-          if (cursor != null) {
-            cursor.close();
-          }
-        }
-      }
-    }
-
-    if (!SmsIOThread.getInstance().execute(new GetMessageRunnable(aMessageId, aRequestId))) {
-      Log.e("GeckoSmsManager", "Failed to add GetMessageRunnable to the SmsIOThread");
-      notifyGetSmsFailed(kUnknownError, aRequestId);
-    }
-  }
-
-  @Override
-  public void deleteMessage(int aMessageId, int aRequestId) {
-    class DeleteMessageRunnable implements Runnable {
-      private final int mMessageId;
-      private final int mRequestId;
-
-      DeleteMessageRunnable(int aMessageId, int aRequestId) {
-        mMessageId = aMessageId;
-        mRequestId = aRequestId;
-      }
-
-      @Override
-      public void run() {
-        try {
-          ContentResolver cr = GeckoAppShell.getContext().getContentResolver();
-          Uri message = ContentUris.withAppendedId(kSmsContentUri, mMessageId);
-
-          int count = cr.delete(message, null, null);
-
-          if (count > 1) {
-            throw new TooManyResultsException();
-          }
-
-          notifySmsDeleted(count == 1, mRequestId);
-        } catch (TooManyResultsException e) {
-          Log.e("GeckoSmsManager", "Delete more than one message?", e);
-          notifySmsDeleteFailed(kUnknownError, mRequestId);
-        } catch (Exception e) {
-          Log.e("GeckoSmsManager", "Error while trying to delete a message", e);
-          notifySmsDeleteFailed(kUnknownError, mRequestId);
-        }
-      }
-    }
-
-    if (!SmsIOThread.getInstance().execute(new DeleteMessageRunnable(aMessageId, aRequestId))) {
-      Log.e("GeckoSmsManager", "Failed to add GetMessageRunnable to the SmsIOThread");
-      notifySmsDeleteFailed(kUnknownError, aRequestId);
-    }
-  }
-
-  private void getMessageFromCursorAndNotify(Cursor aCursor, int aRequestId) throws Exception {
-    int type = aCursor.getInt(aCursor.getColumnIndex("type"));
-    int deliveryStatus = kDeliveryStateUnknown;
-    String sender = "";
-    String receiver = "";
-
-    if (type == kSmsTypeInbox) {
-      deliveryStatus = kDeliveryStatusSuccess;
-      sender = aCursor.getString(aCursor.getColumnIndex("address"));
-    } else if (type == kSmsTypeSentbox) {
-      deliveryStatus = getGeckoDeliveryStatus(aCursor.getInt(aCursor.getColumnIndex("status")));
-      receiver = aCursor.getString(aCursor.getColumnIndex("address"));
-    } else {
-      throw new Exception("Shouldn't ever get a message here that's not from inbox or sentbox");
-    }
-
-    boolean read = aCursor.getInt(aCursor.getColumnIndex("read")) != 0;
-
-    notifyMessageCursorResult(aCursor.getInt(aCursor.getColumnIndex("_id")),
-                              deliveryStatus,
-                              receiver, sender,
-                              aCursor.getString(aCursor.getColumnIndex("body")),
-                              aCursor.getLong(aCursor.getColumnIndex("date")),
-                              aCursor.getLong(aCursor.getColumnIndex("thread_id")),
-                              read,
-                              aRequestId);
-  }
-
-  @Override
-  public void markMessageRead(int aMessageId, boolean aValue, boolean aSendReadReport, int aRequestId) {
-    class MarkMessageReadRunnable implements Runnable {
-      private final int mMessageId;
-      private final boolean mValue;
-      private final int mRequestId;
-
-      MarkMessageReadRunnable(int aMessageId, boolean aValue, int aRequestId) {
-        mMessageId = aMessageId;
-        mValue = aValue;
-        mRequestId = aRequestId;
-      }
-
-      @Override
-      public void run() {
-        try {
-          ContentResolver cr = GeckoAppShell.getContext().getContentResolver();
-          Uri message = ContentUris.withAppendedId(kSmsContentUri, mMessageId);
-
-          ContentValues updatedProps = new ContentValues();
-          updatedProps.put("read", mValue);
-
-          int count = cr.update(message, updatedProps, null, null);
-
-          notifySmsMarkedAsRead(count == 1, mRequestId);
-        } catch (Exception e) {
-          Log.e("GeckoSmsManager", "Error while trying to mark message as read: " + e);
-          notifySmsMarkAsReadFailed(kUnknownError, mRequestId);
-        }
-      }
-    }
-
-    if (aSendReadReport == true) {
-      Log.w("GeckoSmsManager", "Android SmsManager doesn't suport read receipts for SMS.");
-    }
-
-    if (!SmsIOThread.getInstance().execute(new MarkMessageReadRunnable(aMessageId, aValue, aRequestId))) {
-      Log.e("GeckoSmsManager", "Failed to add MarkMessageReadRunnable to the SmsIOThread");
-      notifySmsMarkAsReadFailed(kUnknownError, aRequestId);
-    }
-  }
-
-  @Override
-  public void createMessageCursor(long aStartDate, long aEndDate, String[] aNumbers, int aNumbersCount, String aDelivery, boolean aHasRead, boolean aRead, boolean aHasThreadId, long aThreadId, boolean aReverse, int aRequestId) {
-    class CreateMessageCursorRunnable implements Runnable {
-      private final long     mStartDate;
-      private final long     mEndDate;
-      private final String[] mNumbers;
-      private final int      mNumbersCount;
-      private final String   mDelivery;
-      private final boolean  mHasThreadId;
-      private final long     mThreadId;
-      private final boolean  mReverse;
-      private final int      mRequestId;
-
-      CreateMessageCursorRunnable(long aStartDate, long aEndDate, String[] aNumbers, int aNumbersCount, String aDelivery, boolean aHasRead, boolean aRead, boolean aHasThreadId, long aThreadId, boolean aReverse, int aRequestId) {
-        mStartDate = aStartDate;
-        mEndDate = aEndDate;
-        mNumbers = aNumbers;
-        mNumbersCount = aNumbersCount;
-        mDelivery = aDelivery;
-        mHasThreadId = aHasThreadId;
-        mThreadId = aThreadId;
-        mReverse = aReverse;
-        mRequestId = aRequestId;
-      }
-
-      @Override
-      public void run() {
-        Cursor cursor = null;
-        boolean closeCursor = true;
-
-        try {
-          StringBuilder restrictions = new StringBuilder();
-          Formatter formatter = new Formatter(restrictions);
-
-          if (mStartDate >= 0) {
-            formatter.format("date >= '%d' AND ", mStartDate);
-          }
-
-          if (mEndDate >= 0) {
-            formatter.format("date <= '%d' AND ", mEndDate);
-          }
-
-          if (mNumbersCount > 0) {
-            formatter.format("address IN ('%s'", mNumbers[0]);
-
-            for (int i = 1; i < mNumbersCount; ++i) {
-              formatter.format(", '%s'", mNumbers[i]);
-            }
-
-            formatter.format(") AND ");
-          }
-
-          if (mDelivery == null || mDelivery.isEmpty()) {
-            formatter.format("type IN ('%d', '%d') AND ", kSmsTypeSentbox, kSmsTypeInbox);
-          } else if (mDelivery.equals("sent")) {
-            formatter.format("type = '%d' AND ", kSmsTypeSentbox);
-          } else if (mDelivery.equals("received")) {
-            formatter.format("type = '%d' AND ", kSmsTypeInbox);
-          } else {
-            throw new Exception("Unexpected delivery state: " + mDelivery);
-          }
-
-          if (mHasThreadId) {
-            formatter.format("thread_id = '%d' AND ", mThreadId);
-          }
-
-          // Final 'AND 1' is a no-op so we don't have to special case the last
-          // condition.
-          formatter.format("1");
-
-          ContentResolver cr = GeckoAppShell.getContext().getContentResolver();
-          cursor = cr.query(kSmsContentUri,
-                            kRequiredMessageRows,
-                            restrictions.toString(),
-                            null,
-                            mReverse ? "date DESC" : "date ASC");
-
-          if (cursor.getCount() == 0) {
-            notifyCursorDone(mRequestId);
-            return;
-          }
-
-          MessagesListManager.getInstance().add(mRequestId, cursor);
-
-          cursor.moveToFirst();
-          getMessageFromCursorAndNotify(cursor, mRequestId);
-          closeCursor = false;
-        } catch (Exception e) {
-          Log.e("GeckoSmsManager", "Error while trying to create a message list cursor", e);
-          notifyCursorError(kUnknownError, mRequestId);
-        } finally {
-          if (closeCursor && cursor != null) {
-            cursor.close();
-          }
-        }
-      }
-    }
-
-    if (!SmsIOThread.getInstance().execute(new CreateMessageCursorRunnable(aStartDate, aEndDate, aNumbers, aNumbersCount, aDelivery, aHasRead, aRead, aHasThreadId, aThreadId, aReverse, aRequestId))) {
-      Log.e("GeckoSmsManager", "Failed to add CreateMessageCursorRunnable to the SmsIOThread");
-      notifyCursorError(kUnknownError, aRequestId);
-    }
-  }
-
-  @Override
-  public void getNextMessage(int aRequestId) {
-    class GetNextMessageRunnable implements Runnable {
-      private final int mRequestId;
-
-      GetNextMessageRunnable(int aRequestId) {
-        mRequestId = aRequestId;
-      }
-
-      @Override
-      public void run() {
-        Cursor cursor = null;
-        boolean closeCursor = true;
-        try {
-          cursor = MessagesListManager.getInstance().get(mRequestId);
-
-          if (!cursor.moveToNext()) {
-            MessagesListManager.getInstance().remove(mRequestId);
-            notifyCursorDone(mRequestId);
-            return;
-          }
-
-          getMessageFromCursorAndNotify(cursor, mRequestId);
-          closeCursor = false;
-        } catch (Exception e) {
-          Log.e("GeckoSmsManager", "Error while trying to get the next message of a list", e);
-          notifyCursorError(kUnknownError, mRequestId);
-        } finally {
-          if (closeCursor) {
-            cursor.close();
-          }
-        }
-      }
-    }
-
-    if (!SmsIOThread.getInstance().execute(new GetNextMessageRunnable(aRequestId))) {
-      Log.e("GeckoSmsManager", "Failed to add GetNextMessageRunnable to the SmsIOThread");
-      notifyCursorError(kUnknownError, aRequestId);
-    }
-  }
-
-  private void getThreadFromCursorAndNotify(Cursor aCursor, int aRequestId) throws Exception {
-    ContentResolver cr = GeckoAppShell.getContext().getContentResolver();
-
-    long id = aCursor.getLong(aCursor.getColumnIndex("thread_id"));
-    Cursor msgCursor = cr.query(kSmsContentUri,
-                                kRequiredMessageRowsForThread,
-                                "thread_id = " + id,
-                                null,
-                                "date DESC");
-
-    if (msgCursor == null || msgCursor.getCount() == 0) {
-      throw new Exception("Empty thread " + id);
-    }
-
-    msgCursor.moveToFirst();
-
-    String lastMessageSubject = msgCursor.getString(msgCursor.getColumnIndex("subject"));
-    String body = msgCursor.getString(msgCursor.getColumnIndex("body"));
-    long timestamp = msgCursor.getLong(msgCursor.getColumnIndex("date"));
-
-    HashSet<String> participants = new HashSet<>();
-    do {
-      String p = msgCursor.getString(msgCursor.getColumnIndex("address"));
-      participants.add(p);
-    } while (msgCursor.moveToNext());
-
-    //TODO: handle MMS
-    String lastMessageType = "sms";
-
-    msgCursor = cr.query(kSmsContentUri,
-                         kRequiredMessageRowsForThread,
-                         "thread_id = " + id + " AND read = 0",
-                         null,
-                         null);
-
-    if (msgCursor == null) {
-      Log.e("GeckoSmsManager", "We should never get here, should have errored before");
-      throw new Exception("Empty thread " + id);
-    }
-
-    long unreadCount = msgCursor.getCount();
-
-    notifyThreadCursorResult(id, lastMessageSubject, body, unreadCount, participants.toArray(), timestamp, lastMessageType, aRequestId);
-  }
-
-  @Override
-  public void createThreadCursor(int aRequestId) {
-    class CreateThreadCursorRunnable implements Runnable {
-      private final int mRequestId;
-
-      CreateThreadCursorRunnable(int aRequestId) {
-        mRequestId = aRequestId;
-      }
-
-      @Override
-      public void run() {
-        try {
-          ContentResolver cr = GeckoAppShell.getContext().getContentResolver();
-          Cursor cursor = cr.query(kSmsThreadsContentUri,
-                                   kThreadProjection,
-                                   null,
-                                   null,
-                                   "date DESC");
-          if (cursor == null || !cursor.moveToFirst()) {
-            notifyCursorDone(mRequestId);
-            return;
-          }
-
-          MessagesListManager.getInstance().add(mRequestId, cursor);
-
-          getThreadFromCursorAndNotify(cursor, mRequestId);
-        } catch (Exception e) {
-          Log.e("GeckoSmsManager", "Error while trying to create thread cursor: " + e);
-          notifyCursorError(kUnknownError, mRequestId);
-        }
-      }
-    }
-
-    if (!SmsIOThread.getInstance().execute(new CreateThreadCursorRunnable(aRequestId))) {
-      Log.e("GeckoSmsManager", "Failed to add CreateThreadCursorRunnable to the SmsIOThread");
-      notifyCursorError(kUnknownError, aRequestId);
-    }
-  }
-
-  @Override
-  public void getNextThread(int aRequestId) {
-    class GetNextThreadRunnable implements Runnable {
-      private final int mRequestId;
-
-      GetNextThreadRunnable(int aRequestId) {
-        mRequestId = aRequestId;
-      }
-
-      @Override
-      public void run() {
-        try {
-          Cursor cursor = MessagesListManager.getInstance().get(mRequestId);
-
-          if (!cursor.moveToNext()) {
-            MessagesListManager.getInstance().remove(mRequestId);
-            notifyCursorDone(mRequestId);
-            return;
-          }
-
-          getThreadFromCursorAndNotify(cursor, mRequestId);
-        } catch (Exception e) {
-          Log.e("GeckoSmsManager", "Error while trying to create thread cursor: " + e);
-          notifyCursorError(kUnknownError, mRequestId);
-        }
-      }
-    }
-
-    if (!SmsIOThread.getInstance().execute(new GetNextThreadRunnable(aRequestId))) {
-      Log.e("GeckoSmsManager", "Failed to add GetNextThreadRunnable to the SmsIOThread");
-      notifyCursorError(kUnknownError, aRequestId);
-    }
-  }
-
-  @Override
-  public void stop() {
-    GeckoAppShell.getContext().unregisterReceiver(this);
-  }
-
-  @Override
-  public void shutdown() {
-    SmsIOThread.getInstance().interrupt();
-    MessagesListManager.getInstance().clear();
-  }
-
-  private int getGeckoDeliveryStatus(int aDeliveryStatus) {
-    if (aDeliveryStatus == Telephony.Sms.STATUS_NONE) {
-      return kDeliveryStatusNotApplicable;
-    }
-    if (aDeliveryStatus >= Telephony.Sms.STATUS_FAILED) {
-      return kDeliveryStatusError;
-    }
-    if (aDeliveryStatus >= Telephony.Sms.STATUS_PENDING) {
-      return kDeliveryStatusPending;
-    }
-    return kDeliveryStatusSuccess;
-  }
-
-  private int getGeckoMessageClass(MessageClass aMessageClass) {
-    switch (aMessageClass) {
-      case CLASS_0:
-        return kMessageClassClass0;
-      case CLASS_1:
-        return kMessageClassClass1;
-      case CLASS_2:
-        return kMessageClassClass2;
-      case CLASS_3:
-        return kMessageClassClass3;
-      default:
-        return kMessageClassNormal;
-    }
-  }
-
-  static class IdTooHighException extends Exception {
-    private static final long serialVersionUID = 29935575131092050L;
-  }
-
-  static class InvalidTypeException extends Exception {
-    private static final long serialVersionUID = 47436856832535912L;
-  }
-
-  static class NotFoundException extends Exception {
-    private static final long serialVersionUID = 1940676816633984L;
-  }
-
-  static class TooManyResultsException extends Exception {
-    private static final long serialVersionUID = 51883196784325305L;
-  }
-
-  static class UnmatchingIdException extends Exception {
-    private static final long serialVersionUID = 158467542575633280L;
-  }
-
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  public static native void notifySmsReceived(int aId, String aSender, String aBody, int aMessageClass, long aSentTimestamp, long aTimestamp);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifySmsSent(int aId, String aReceiver, String aBody, long aTimestamp, int aRequestId);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifySmsDelivery(int aId, int aDeliveryStatus, String aReceiver, String aBody, long aTimestamp);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifySmsSendFailed(int aError, int aRequestId);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifyGetSms(int aId, int aDeliveryStatus, String aReceiver, String aSender, String aBody, long aTimestamp, boolean aRead, int aRequestId);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifyGetSmsFailed(int aError, int aRequestId);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifySmsDeleted(boolean aDeleted, int aRequestId);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifySmsDeleteFailed(int aError, int aRequestId);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifySmsMarkedAsRead(boolean aMarkedAsRead, int aRequestId);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifySmsMarkAsReadFailed(int aError, int aRequestId);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifyCursorError(int aError, int aRequestId);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifyThreadCursorResult(long aId, String aLastMessageSubject, String aBody, long aUnreadCount, Object[] aParticipants, long aTimestamp, String aLastMessageType, int aRequestId);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifyMessageCursorResult(int aMessageId, int aDeliveryStatus, String aReceiver, String aSender, String aBody, long aTimestamp, long aThreadId, boolean aRead, int aRequestId);
-  @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-  private static native void notifyCursorDone(int aRequestId);
-}
deleted file mode 100644
--- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/SmsManager.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
- * 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/. */
-
-package org.mozilla.gecko;
-
-public class SmsManager {
-    private static final ISmsManager sInstance;
-    static {
-        if (AppConstants.MOZ_WEBSMS_BACKEND) {
-            sInstance = new GeckoSmsManager();
-        } else {
-            sInstance = null;
-        }
-    }
-
-    public static ISmsManager getInstance() {
-        return sInstance;
-    }
-
-    public static boolean isEnabled() {
-        return AppConstants.MOZ_WEBSMS_BACKEND;
-    }
-
-    public interface ISmsManager {
-        void start();
-        void stop();
-        void shutdown();
-
-        void send(String aNumber, String aMessage, int aRequestId, boolean aShouldNotify);
-        void getMessage(int aMessageId, int aRequestId);
-        void deleteMessage(int aMessageId, int aRequestId);
-        void markMessageRead(int aMessageId, boolean aValue, boolean aSendReadReport, int aRequestId);
-        void createMessageCursor(long aStartDate, long aEndDate, String[] aNumbers, int aNumbersCount, String aDelivery, boolean aHasRead, boolean aRead, boolean aHasThreadId, long aThreadId, boolean aReverse, int aRequestId);
-        void createThreadCursor(int aRequestId);
-        void getNextThread(int aRequestId);
-        void getNextMessage(int aRequestId);
-    }
-}
-
--- a/modules/libpref/init/all.js
+++ b/modules/libpref/init/all.js
@@ -4730,32 +4730,16 @@ pref("layout.animated-image-layers.enabl
 
 pref("dom.vibrator.enabled", true);
 pref("dom.vibrator.max_vibrate_ms", 10000);
 pref("dom.vibrator.max_vibrate_list_len", 128);
 
 // Battery API
 pref("dom.battery.enabled", true);
 
-// WebSMS
-pref("dom.sms.enabled", false);
-// Enable Latin characters replacement with corresponding ones in GSM SMS
-// 7-bit default alphabet.
-pref("dom.sms.strict7BitEncoding", false);
-pref("dom.sms.requestStatusReport", true);
-// Numeric default service id for SMS API calls with |serviceId| parameter
-// omitted.
-pref("dom.sms.defaultServiceId", 0);
-// MobileMessage GetMessages/GetThreads read ahead aggressiveness.
-//
-// positive: finite read-ahead entries,
-// 0: don't read ahead unless explicitly requested, (default)
-// negative: read ahead all IDs if possible.
-pref("dom.sms.maxReadAheadEntries", 0);
-
 // Push
 
 pref("dom.push.enabled", false);
 
 pref("dom.push.loglevel", "error");
 
 pref("dom.push.serverURL", "wss://push.services.mozilla.com/");
 pref("dom.push.userAgentID", "");
--- a/testing/marionette/harness/marionette/tests/webapi-tests.ini
+++ b/testing/marionette/harness/marionette/tests/webapi-tests.ini
@@ -1,12 +1,11 @@
 [include:../../../../../dom/bluetooth/tests/marionette/manifest.ini]
 [include:../../../../../dom/telephony/test/marionette/manifest.ini]
 [include:../../../../../dom/battery/test/marionette/manifest.ini]
-[include:../../../../../dom/mobilemessage/tests/marionette/manifest.ini]
 [include:../../../../../dom/mobileconnection/tests/marionette/manifest.ini]
 [include:../../../../../dom/system/gonk/tests/marionette/manifest.ini]
 [include:../../../../../dom/icc/tests/marionette/manifest.ini]
 [include:../../../../../dom/system/tests/marionette/manifest.ini]
 [include:../../../../../dom/nfc/tests/marionette/manifest.ini]
 skip-if = android_version > '15' # Bug 1203072
 [include:../../../../../dom/events/test/marionette/manifest.ini]
 [include:../../../../../dom/wifi/test/marionette/manifest.ini]
--- a/toolkit/moz.configure
+++ b/toolkit/moz.configure
@@ -609,32 +609,16 @@ option('--enable-webspeechtestbackend', 
 
 @depends_if('--enable-webspeechtestbackend')
 def webspeech_test_backend(value):
     return True
 
 set_config('MOZ_WEBSPEECH_TEST_BACKEND', webspeech_test_backend)
 set_define('MOZ_WEBSPEECH_TEST_BACKEND', webspeech_test_backend)
 
-# WebSMS
-# ==============================================================
-@depends(build_project, '--help')
-def websms_default(build_project, _):
-    return build_project in ('b2g', 'b2g/graphene')
-
-option('--enable-websms-backend', default=websms_default,
-       help='Enable WebSMS backend')
-
-@depends_if('--enable-websms-backend')
-def websms_backend(value):
-    return True
-
-set_config('MOZ_WEBSMS_BACKEND', websms_backend)
-set_define('MOZ_WEBSMS_BACKEND', websms_backend)
-
 # Enable IPDL's "expensive" unit tests
 # ==============================================================
 option('--enable-ipdl-tests', help='Enable expensive IPDL tests')
 
 set_config('MOZ_IPDL_TESTS',
            depends_if('--enable-ipdl-tests')(lambda _: True))
 
 include('nss.configure')
--- a/widget/android/AndroidBridge.cpp
+++ b/widget/android/AndroidBridge.cpp
@@ -20,17 +20,16 @@
 #include "AndroidBridgeUtilities.h"
 #include "nsAlertsUtils.h"
 #include "nsAppShell.h"
 #include "nsOSHelperAppService.h"
 #include "nsWindow.h"
 #include "mozilla/Preferences.h"
 #include "nsThreadUtils.h"
 #include "nsIThreadManager.h"
-#include "mozilla/dom/mobilemessage/PSms.h"
 #include "gfxPlatform.h"
 #include "gfxContext.h"
 #include "mozilla/gfx/2D.h"
 #include "gfxUtils.h"
 #include "nsPresContext.h"
 #include "nsIDocShell.h"
 #include "nsPIDOMWindow.h"
 #include "mozilla/dom/ScreenOrientation.h"
@@ -167,22 +166,16 @@ AndroidBridge::AndroidBridge()
             jEnv, jEnv->GetObjectClass(mMessageQueue.Get()));
     // mMessageQueueNext must not be null
     mMessageQueueNext = GetMethodID(
             jEnv, msgQueueClass.Get(), "next", "()Landroid/os/Message;");
     // mMessageQueueMessages may be null (e.g. due to proguard optimization)
     mMessageQueueMessages = jEnv->GetFieldID(
             msgQueueClass.Get(), "mMessages", "Landroid/os/Message;");
 
-#ifdef MOZ_WEBSMS_BACKEND
-    AutoJNIClass smsMessage(jEnv, "android/telephony/SmsMessage");
-    mAndroidSmsMessageClass = smsMessage.getGlobalRef();
-    jCalculateLength = smsMessage.getStaticMethod("calculateLength", "(Ljava/lang/CharSequence;Z)[I");
-#endif
-
     AutoJNIClass string(jEnv, "java/lang/String");
     jStringClass = string.getGlobalRef();
 
     if (!GetStaticIntField("android/os/Build$VERSION", "SDK_INT", &mAPIVersion, jEnv)) {
         ALOG_BRIDGE("Failed to find API version");
     }
 
     AutoJNIClass channels(jEnv, "java/nio/channels/Channels");
@@ -674,287 +667,16 @@ void
 AndroidBridge::HandleGeckoMessage(JSContext* cx, JS::HandleObject object)
 {
     ALOG_BRIDGE("%s", __PRETTY_FUNCTION__);
 
     auto message = widget::CreateNativeJSContainer(cx, object);
     GeckoAppShell::HandleGeckoMessage(message);
 }
 
-nsresult
-AndroidBridge::GetSegmentInfoForText(const nsAString& aText,
-                                     nsIMobileMessageCallback* aRequest)
-{
-#ifndef MOZ_WEBSMS_BACKEND
-    return NS_ERROR_FAILURE;
-#else
-    ALOG_BRIDGE("AndroidBridge::GetSegmentInfoForText");
-
-    int32_t segments, charsPerSegment, charsAvailableInLastSegment;
-
-    JNIEnv* const env = jni::GetGeckoThreadEnv();
-
-    AutoLocalJNIFrame jniFrame(env, 2);
-    jstring jText = NewJavaString(&jniFrame, aText);
-    jobject obj = env->CallStaticObjectMethod(mAndroidSmsMessageClass,
-                                              jCalculateLength, jText, JNI_FALSE);
-    if (jniFrame.CheckForException())
-        return NS_ERROR_FAILURE;
-
-    jintArray arr = static_cast<jintArray>(obj);
-    if (!arr || env->GetArrayLength(arr) != 4)
-        return NS_ERROR_FAILURE;
-
-    jint* info = env->GetIntArrayElements(arr, JNI_FALSE);
-
-    segments = info[0]; // msgCount
-    charsPerSegment = info[2]; // codeUnitsRemaining
-    // segmentChars = (codeUnitCount + codeUnitsRemaining) / msgCount
-    charsAvailableInLastSegment = (info[1] + info[2]) / info[0];
-
-    env->ReleaseIntArrayElements(arr, info, JNI_ABORT);
-
-    // TODO Bug 908598 - Should properly use |QueueSmsRequest(...)| to queue up
-    // the nsIMobileMessageCallback just like other functions.
-    return aRequest->NotifySegmentInfoForTextGot(segments,
-                                                 charsPerSegment,
-                                                 charsAvailableInLastSegment);
-#endif
-}
-
-void
-AndroidBridge::SendMessage(const nsAString& aNumber,
-                           const nsAString& aMessage,
-                           nsIMobileMessageCallback* aRequest)
-{
-    ALOG_BRIDGE("AndroidBridge::SendMessage");
-
-    uint32_t requestId;
-    if (!QueueSmsRequest(aRequest, &requestId))
-        return;
-
-    GeckoAppShell::SendMessage(aNumber, aMessage, requestId);
-}
-
-void
-AndroidBridge::GetMessage(int32_t aMessageId, nsIMobileMessageCallback* aRequest)
-{
-    ALOG_BRIDGE("AndroidBridge::GetMessage");
-
-    uint32_t requestId;
-    if (!QueueSmsRequest(aRequest, &requestId))
-        return;
-
-    GeckoAppShell::GetMessage(aMessageId, requestId);
-}
-
-void
-AndroidBridge::DeleteMessage(int32_t aMessageId, nsIMobileMessageCallback* aRequest)
-{
-    ALOG_BRIDGE("AndroidBridge::DeleteMessage");
-
-    uint32_t requestId;
-    if (!QueueSmsRequest(aRequest, &requestId))
-        return;
-
-    GeckoAppShell::DeleteMessage(aMessageId, requestId);
-}
-
-void
-AndroidBridge::MarkMessageRead(int32_t aMessageId,
-                               bool aValue,
-                               bool aSendReadReport,
-                               nsIMobileMessageCallback* aRequest)
-{
-    ALOG_BRIDGE("AndroidBridge::MarkMessageRead");
-
-    uint32_t requestId;
-    if (!QueueSmsRequest(aRequest, &requestId)) {
-        return;
-    }
-
-    GeckoAppShell::MarkMessageRead(aMessageId,
-                                   aValue,
-                                   aSendReadReport,
-                                   requestId);
-}
-
-NS_IMPL_ISUPPORTS0(MessageCursorContinueCallback)
-
-NS_IMETHODIMP
-MessageCursorContinueCallback::HandleContinue()
-{
-    GeckoAppShell::GetNextMessage(mRequestId);
-    return NS_OK;
-}
-
-already_AddRefed<nsICursorContinueCallback>
-AndroidBridge::CreateMessageCursor(bool aHasStartDate,
-                                   uint64_t aStartDate,
-                                   bool aHasEndDate,
-                                   uint64_t aEndDate,
-                                   const char16_t** aNumbers,
-                                   uint32_t aNumbersCount,
-                                   const nsAString& aDelivery,
-                                   bool aHasRead,
-                                   bool aRead,
-                                   bool aHasThreadId,
-                                   uint64_t aThreadId,
-                                   bool aReverse,
-                                   nsIMobileMessageCursorCallback* aRequest)
-{
-    ALOG_BRIDGE("AndroidBridge::CreateMessageCursor");
-
-    JNIEnv* const env = jni::GetGeckoThreadEnv();
-
-    uint32_t requestId;
-    if (!QueueSmsCursorRequest(aRequest, &requestId))
-        return nullptr;
-
-    AutoLocalJNIFrame jniFrame(env, 2);
-
-    jobjectArray numbers =
-        (jobjectArray)env->NewObjectArray(aNumbersCount,
-                                          jStringClass,
-                                          NewJavaString(&jniFrame, EmptyString()));
-
-    for (uint32_t i = 0; i < aNumbersCount; ++i) {
-        jstring elem = NewJavaString(&jniFrame, nsDependentString(aNumbers[i]));
-        env->SetObjectArrayElement(numbers, i, elem);
-        env->DeleteLocalRef(elem);
-    }
-
-    int64_t startDate = aHasStartDate ? aStartDate : -1;
-    int64_t endDate = aHasEndDate ? aEndDate : -1;
-    GeckoAppShell::CreateMessageCursor(startDate, endDate,
-                                       ObjectArray::Ref::From(numbers),
-                                       aNumbersCount,
-                                       aDelivery,
-                                       aHasRead, aRead,
-                                       aHasThreadId, aThreadId,
-                                       aReverse,
-                                       requestId);
-
-    nsCOMPtr<nsICursorContinueCallback> callback = 
-       new MessageCursorContinueCallback(requestId);
-    return callback.forget();
-}
-
-NS_IMPL_ISUPPORTS0(ThreadCursorContinueCallback)
-
-NS_IMETHODIMP
-ThreadCursorContinueCallback::HandleContinue()
-{
-    GeckoAppShell::GetNextThread(mRequestId);
-    return NS_OK;
-}
-
-already_AddRefed<nsICursorContinueCallback>
-AndroidBridge::CreateThreadCursor(nsIMobileMessageCursorCallback* aRequest)
-{
-    ALOG_BRIDGE("AndroidBridge::CreateThreadCursor");
-
-    uint32_t requestId;
-    if (!QueueSmsCursorRequest(aRequest, &requestId)) {
-        return nullptr;
-    }
-
-    GeckoAppShell::CreateThreadCursor(requestId);
-
-    nsCOMPtr<nsICursorContinueCallback> callback =
-        new ThreadCursorContinueCallback(requestId);
-    return callback.forget();
-}
-
-bool
-AndroidBridge::QueueSmsRequest(nsIMobileMessageCallback* aRequest, uint32_t* aRequestIdOut)
-{
-    MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!");
-    MOZ_ASSERT(aRequest && aRequestIdOut);
-
-    const uint32_t length = mSmsRequests.Length();
-    for (uint32_t i = 0; i < length; i++) {
-        if (!(mSmsRequests)[i]) {
-            (mSmsRequests)[i] = aRequest;
-            *aRequestIdOut = i;
-            return true;
-        }
-    }
-
-    mSmsRequests.AppendElement(aRequest);
-
-    // After AppendElement(), previous `length` points to the new tail element.
-    *aRequestIdOut = length;
-    return true;
-}
-
-already_AddRefed<nsIMobileMessageCallback>
-AndroidBridge::DequeueSmsRequest(uint32_t aRequestId)
-{
-    MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!");
-
-    MOZ_ASSERT(aRequestId < mSmsRequests.Length());
-    if (aRequestId >= mSmsRequests.Length()) {
-        return nullptr;
-    }
-
-    return mSmsRequests[aRequestId].forget();
-}
-
-bool
-AndroidBridge::QueueSmsCursorRequest(nsIMobileMessageCursorCallback* aRequest,
-                                     uint32_t* aRequestIdOut)
-{
-    MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!");
-    MOZ_ASSERT(aRequest && aRequestIdOut);
-
-    const uint32_t length = mSmsCursorRequests.Length();
-    for (uint32_t i = 0; i < length; i++) {
-        if (!(mSmsCursorRequests)[i]) {
-            (mSmsCursorRequests)[i] = aRequest;
-            *aRequestIdOut = i;
-            return true;
-        }
-    }
-
-    mSmsCursorRequests.AppendElement(aRequest);
-
-    // After AppendElement(), previous `length` points to the new tail element.
-    *aRequestIdOut = length;
-    return true;
-}
-
-nsCOMPtr<nsIMobileMessageCursorCallback>
-AndroidBridge::GetSmsCursorRequest(uint32_t aRequestId)
-{
-    MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!");
-
-    MOZ_ASSERT(aRequestId < mSmsCursorRequests.Length());
-    if (aRequestId >= mSmsCursorRequests.Length()) {
-        return nullptr;
-    }
-
-    // TODO: remove on final dequeue
-    return mSmsCursorRequests[aRequestId];
-}
-
-already_AddRefed<nsIMobileMessageCursorCallback>
-AndroidBridge::DequeueSmsCursorRequest(uint32_t aRequestId)
-{
-    MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!");
-
-    MOZ_ASSERT(aRequestId < mSmsCursorRequests.Length());
-    if (aRequestId >= mSmsCursorRequests.Length()) {
-        return nullptr;
-    }
-
-    // TODO: remove on final dequeue
-    return mSmsCursorRequests[aRequestId].forget();
-}
-
 void
 AndroidBridge::GetCurrentNetworkInformation(hal::NetworkInformation* aNetworkInfo)
 {
     ALOG_BRIDGE("AndroidBridge::GetCurrentNetworkInformation");
 
     // To prevent calling too many methods through JNI, the Java method returns
     // an array of double even if we actually want an integer, a boolean, and an integer.
 
--- a/widget/android/AndroidBridge.h
+++ b/widget/android/AndroidBridge.h
@@ -19,18 +19,16 @@
 #include "GeneratedJNIWrappers.h"
 
 #include "nsIMutableArray.h"
 #include "nsIMIMEInfo.h"
 #include "nsColor.h"
 #include "gfxRect.h"
 
 #include "nsIAndroidBridge.h"
-#include "nsIMobileMessageCallback.h"
-#include "nsIMobileMessageCursorCallback.h"
 #include "nsIDOMDOMCursor.h"
 
 #include "mozilla/Likely.h"
 #include "mozilla/Mutex.h"
 #include "mozilla/Types.h"
 #include "mozilla/gfx/Point.h"
 #include "mozilla/jni/Utils.h"
 #include "nsIObserver.h"
@@ -55,56 +53,32 @@ namespace mozilla {
 class AutoLocalJNIFrame;
 class Runnable;
 
 namespace hal {
 class BatteryInformation;
 class NetworkInformation;
 } // namespace hal
 
-namespace dom {
-namespace mobilemessage {
-class SmsFilterData;
-} // namespace mobilemessage
-} // namespace dom
-
 // The order and number of the members in this structure must correspond
 // to the attrsAppearance array in GeckoAppShell.getSystemColors()
 typedef struct AndroidSystemColors {
     nscolor textColorPrimary;
     nscolor textColorPrimaryInverse;
     nscolor textColorSecondary;
     nscolor textColorSecondaryInverse;
     nscolor textColorTertiary;
     nscolor textColorTertiaryInverse;
     nscolor textColorHighlight;
     nscolor colorForeground;
     nscolor colorBackground;
     nscolor panelColorForeground;
     nscolor panelColorBackground;
 } AndroidSystemColors;
 
-class ThreadCursorContinueCallback : public nsICursorContinueCallback
-{
-public:
-    NS_DECL_ISUPPORTS
-    NS_DECL_NSICURSORCONTINUECALLBACK
-
-    ThreadCursorContinueCallback(int aRequestId)
-        : mRequestId(aRequestId)
-    {
-    }
-private:
-    virtual ~ThreadCursorContinueCallback()
-    {
-    }
-
-    int mRequestId;
-};
-
 class MessageCursorContinueCallback : public nsICursorContinueCallback
 {
 public:
     NS_DECL_ISUPPORTS
     NS_DECL_NSICURSORCONTINUECALLBACK
 
     MessageCursorContinueCallback(int aRequestId)
         : mRequestId(aRequestId)
@@ -182,46 +156,16 @@ public:
     // caller is responsible for ensuring this doesn't leak by calling
     // DeleteGlobalRef() when the context is no longer needed.
     jobject GetGlobalContextRef(void);
 
     void HandleGeckoMessage(JSContext* cx, JS::HandleObject message);
 
     void GetCurrentBatteryInformation(hal::BatteryInformation* aBatteryInfo);
 
-    nsresult GetSegmentInfoForText(const nsAString& aText,
-                                   nsIMobileMessageCallback* aRequest);
-    void SendMessage(const nsAString& aNumber, const nsAString& aText,
-                     nsIMobileMessageCallback* aRequest);
-    void GetMessage(int32_t aMessageId, nsIMobileMessageCallback* aRequest);
-    void DeleteMessage(int32_t aMessageId, nsIMobileMessageCallback* aRequest);
-    void MarkMessageRead(int32_t aMessageId,
-                         bool aValue,
-                         bool aSendReadReport,
-                         nsIMobileMessageCallback* aRequest);
-    already_AddRefed<nsICursorContinueCallback>
-    CreateMessageCursor(bool aHasStartDate,
-                        uint64_t aStartDate,
-                        bool aHasEndDate,
-                        uint64_t aEndDate,
-                        const char16_t** aNumbers,
-                        uint32_t aNumbersCount,
-                        const nsAString& aDelivery,
-                        bool aHasRead,
-                        bool aRead,
-                        bool aHasThreadId,
-                        uint64_t aThreadId,
-                        bool aReverse,
-                        nsIMobileMessageCursorCallback* aRequest);
-    already_AddRefed<nsICursorContinueCallback>
-    CreateThreadCursor(nsIMobileMessageCursorCallback* aRequest);
-    already_AddRefed<nsIMobileMessageCallback> DequeueSmsRequest(uint32_t aRequestId);
-    nsCOMPtr<nsIMobileMessageCursorCallback> GetSmsCursorRequest(uint32_t aRequestId);
-    already_AddRefed<nsIMobileMessageCursorCallback> DequeueSmsCursorRequest(uint32_t aRequestId);
-
     void GetCurrentNetworkInformation(hal::NetworkInformation* aNetworkInfo);
 
     // These methods don't use a ScreenOrientation because it's an
     // enum and that would require including the header which requires
     // include IPC headers which requires including basictypes.h which
     // requires a lot of changes...
     uint32_t GetScreenOrientation();
     uint16_t GetScreenAngle();
@@ -259,30 +203,22 @@ public:
     static nsresult InputStreamRead(jni::Object::Param obj, char *aBuf, uint32_t aCount, uint32_t *aRead);
 
     static nsresult GetExternalPublicDirectory(const nsAString& aType, nsAString& aPath);
 
 protected:
     static nsDataHashtable<nsStringHashKey, nsString> sStoragePaths;
 
     static AndroidBridge* sBridge;
-    nsTArray<nsCOMPtr<nsIMobileMessageCallback>> mSmsRequests;
-    nsTArray<nsCOMPtr<nsIMobileMessageCursorCallback>> mSmsCursorRequests;
-
-    // the android.telephony.SmsMessage class
-    jclass mAndroidSmsMessageClass;
 
     AndroidBridge();
     ~AndroidBridge();
 
     int mAPIVersion;
 
-    bool QueueSmsRequest(nsIMobileMessageCallback* aRequest, uint32_t* aRequestIdOut);
-    bool QueueSmsCursorRequest(nsIMobileMessageCursorCallback* aRequest, uint32_t* aRequestIdOut);
-
     // intput stream
     jclass jReadableByteChannel;
     jclass jChannels;
     jmethodID jChannelCreate;
     jmethodID jByteBufferRead;
 
     jclass jInputStream;
     jmethodID jClose;
--- a/widget/android/GeneratedJNINatives.h
+++ b/widget/android/GeneratedJNINatives.h
@@ -197,83 +197,16 @@ template<class Impl>
 const JNINativeMethod GeckoScreenOrientation::Natives<Impl>::methods[] = {
 
     mozilla::jni::MakeNativeMethod<GeckoScreenOrientation::OnOrientationChange_t>(
             mozilla::jni::NativeStub<GeckoScreenOrientation::OnOrientationChange_t, Impl>
             ::template Wrap<&Impl::OnOrientationChange>)
 };
 
 template<class Impl>
-class GeckoSmsManager::Natives : public mozilla::jni::NativeImpl<GeckoSmsManager, Impl>
-{
-public:
-    static const JNINativeMethod methods[14];
-};
-
-template<class Impl>
-const JNINativeMethod GeckoSmsManager::Natives<Impl>::methods[] = {
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifyCursorDone_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifyCursorDone_t, Impl>
-            ::template Wrap<&Impl::NotifyCursorDone>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifyCursorError_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifyCursorError_t, Impl>
-            ::template Wrap<&Impl::NotifyCursorError>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifyGetSms_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifyGetSms_t, Impl>
-            ::template Wrap<&Impl::NotifyGetSms>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifyGetSmsFailed_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifyGetSmsFailed_t, Impl>
-            ::template Wrap<&Impl::NotifyGetSmsFailed>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifyMessageCursorResult_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifyMessageCursorResult_t, Impl>
-            ::template Wrap<&Impl::NotifyMessageCursorResult>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifySmsDeleteFailed_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifySmsDeleteFailed_t, Impl>
-            ::template Wrap<&Impl::NotifySmsDeleteFailed>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifySmsDeleted_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifySmsDeleted_t, Impl>
-            ::template Wrap<&Impl::NotifySmsDeleted>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifySmsDelivery_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifySmsDelivery_t, Impl>
-            ::template Wrap<&Impl::NotifySmsDelivery>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifySmsMarkAsReadFailed_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifySmsMarkAsReadFailed_t, Impl>
-            ::template Wrap<&Impl::NotifySmsMarkAsReadFailed>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifySmsMarkedAsRead_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifySmsMarkedAsRead_t, Impl>
-            ::template Wrap<&Impl::NotifySmsMarkedAsRead>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifySmsReceived_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifySmsReceived_t, Impl>
-            ::template Wrap<&Impl::NotifySmsReceived>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifySmsSendFailed_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifySmsSendFailed_t, Impl>
-            ::template Wrap<&Impl::NotifySmsSendFailed>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifySmsSent_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifySmsSent_t, Impl>
-            ::template Wrap<&Impl::NotifySmsSent>),
-
-    mozilla::jni::MakeNativeMethod<GeckoSmsManager::NotifyThreadCursorResult_t>(
-            mozilla::jni::NativeStub<GeckoSmsManager::NotifyThreadCursorResult_t, Impl>
-            ::template Wrap<&Impl::NotifyThreadCursorResult>)
-};
-
-template<class Impl>
 class GeckoThread::Natives : public mozilla::jni::NativeImpl<GeckoThread, Impl>
 {
 public:
     static const JNINativeMethod methods[6];
 };
 
 template<class Impl>
 const JNINativeMethod GeckoThread::Natives<Impl>::methods[] = {
--- a/widget/android/GeneratedJNIWrappers.cpp
+++ b/widget/android/GeneratedJNIWrappers.cpp
@@ -106,48 +106,24 @@ auto GeckoAppShell::ConnectionGetMimeTyp
 constexpr char GeckoAppShell::CreateInputStream_t::name[];
 constexpr char GeckoAppShell::CreateInputStream_t::signature[];
 
 auto GeckoAppShell::CreateInputStream(mozilla::jni::Object::Param a0) -> mozilla::jni::Object::LocalRef
 {
     return mozilla::jni::Method<CreateInputStream_t>::Call(GeckoAppShell::Context(), nullptr, a0);
 }
 
-constexpr char GeckoAppShell::CreateMessageCursor_t::name[];
-constexpr char GeckoAppShell::CreateMessageCursor_t::signature[];
-
-auto GeckoAppShell::CreateMessageCursor(int64_t a0, int64_t a1, mozilla::jni::ObjectArray::Param a2, int32_t a3, mozilla::jni::String::Param a4, bool a5, bool a6, bool a7, int64_t a8, bool a9, int32_t a10) -> void
-{
-    return mozilla::jni::Method<CreateMessageCursor_t>::Call(GeckoAppShell::Context(), nullptr, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
-}
-
 constexpr char GeckoAppShell::CreateShortcut_t::name[];
 constexpr char GeckoAppShell::CreateShortcut_t::signature[];
 
 auto GeckoAppShell::CreateShortcut(mozilla::jni::String::Param a0, mozilla::jni::String::Param a1) -> void
 {
     return mozilla::jni::Method<CreateShortcut_t>::Call(GeckoAppShell::Context(), nullptr, a0, a1);
 }
 
-constexpr char GeckoAppShell::CreateThreadCursor_t::name[];
-constexpr char GeckoAppShell::CreateThreadCursor_t::signature[];
-
-auto GeckoAppShell::CreateThreadCursor(int32_t a0) -> void
-{
-    return mozilla::jni::Method<CreateThreadCursor_t>::Call(GeckoAppShell::Context(), nullptr, a0);
-}
-
-constexpr char GeckoAppShell::DeleteMessage_t::name[];
-constexpr char GeckoAppShell::DeleteMessage_t::signature[];
-
-auto GeckoAppShell::DeleteMessage(int32_t a0, int32_t a1) -> void
-{
-    return mozilla::jni::Method<DeleteMessage_t>::Call(GeckoAppShell::Context(), nullptr, a0, a1);
-}
-
 constexpr char GeckoAppShell::DisableAlarm_t::name[];
 constexpr char GeckoAppShell::DisableAlarm_t::signature[];
 
 auto GeckoAppShell::DisableAlarm() -> void
 {
     return mozilla::jni::Method<DisableAlarm_t>::Call(GeckoAppShell::Context(), nullptr);
 }
 
@@ -354,56 +330,32 @@ auto GeckoAppShell::GetIconForExtension(
 constexpr char GeckoAppShell::GetMaxTouchPoints_t::name[];
 constexpr char GeckoAppShell::GetMaxTouchPoints_t::signature[];
 
 auto GeckoAppShell::GetMaxTouchPoints() -> int32_t
 {
     return mozilla::jni::Method<GetMaxTouchPoints_t>::Call(GeckoAppShell::Context(), nullptr);
 }
 
-constexpr char GeckoAppShell::GetMessage_t::name[];
-constexpr char GeckoAppShell::GetMessage_t::signature[];
-
-auto GeckoAppShell::GetMessage(int32_t a0, int32_t a1) -> void
-{
-    return mozilla::jni::Method<GetMessage_t>::Call(GeckoAppShell::Context(), nullptr, a0, a1);
-}
-
 constexpr char GeckoAppShell::GetMimeTypeFromExtensions_t::name[];
 constexpr char GeckoAppShell::GetMimeTypeFromExtensions_t::signature[];
 
 auto GeckoAppShell::GetMimeTypeFromExtensions(mozilla::jni::String::Param a0) -> mozilla::jni::String::LocalRef
 {
     return mozilla::jni::Method<GetMimeTypeFromExtensions_t>::Call(GeckoAppShell::Context(), nullptr, a0);
 }
 
 constexpr char GeckoAppShell::GetNetworkLinkType_t::name[];
 constexpr char GeckoAppShell::GetNetworkLinkType_t::signature[];
 
 auto GeckoAppShell::GetNetworkLinkType() -> int32_t
 {
     return mozilla::jni::Method<GetNetworkLinkType_t>::Call(GeckoAppShell::Context(), nullptr);
 }
 
-constexpr char GeckoAppShell::GetNextMessage_t::name[];
-constexpr char GeckoAppShell::GetNextMessage_t::signature[];
-
-auto GeckoAppShell::GetNextMessage(int32_t a0) -> void
-{
-    return mozilla::jni::Method<GetNextMessage_t>::Call(GeckoAppShell::Context(), nullptr, a0);
-}
-
-constexpr char GeckoAppShell::GetNextThread_t::name[];
-constexpr char GeckoAppShell::GetNextThread_t::signature[];
-
-auto GeckoAppShell::GetNextThread(int32_t a0) -> void
-{
-    return mozilla::jni::Method<GetNextThread_t>::Call(GeckoAppShell::Context(), nullptr, a0);
-}
-
 constexpr char GeckoAppShell::GetProxyForURI_t::name[];
 constexpr char GeckoAppShell::GetProxyForURI_t::signature[];
 
 auto GeckoAppShell::GetProxyForURI(mozilla::jni::String::Param a0, mozilla::jni::String::Param a1, mozilla::jni::String::Param a2, int32_t a3) -> mozilla::jni::String::LocalRef
 {
     return mozilla::jni::Method<GetProxyForURI_t>::Call(GeckoAppShell::Context(), nullptr, a0, a1, a2, a3);
 }
 
@@ -530,24 +482,16 @@ auto GeckoAppShell::LoadPluginClass(mozi
 constexpr char GeckoAppShell::LockScreenOrientation_t::name[];
 constexpr char GeckoAppShell::LockScreenOrientation_t::signature[];
 
 auto GeckoAppShell::LockScreenOrientation(int32_t a0) -> void
 {
     return mozilla::jni::Method<LockScreenOrientation_t>::Call(GeckoAppShell::Context(), nullptr, a0);
 }
 
-constexpr char GeckoAppShell::MarkMessageRead_t::name[];
-constexpr char GeckoAppShell::MarkMessageRead_t::signature[];
-
-auto GeckoAppShell::MarkMessageRead(int32_t a0, bool a1, bool a2, int32_t a3) -> void
-{
-    return mozilla::jni::Method<MarkMessageRead_t>::Call(GeckoAppShell::Context(), nullptr, a0, a1, a2, a3);
-}
-
 constexpr char GeckoAppShell::MarkURIVisited_t::name[];
 constexpr char GeckoAppShell::MarkURIVisited_t::signature[];
 
 auto GeckoAppShell::MarkURIVisited(mozilla::jni::String::Param a0) -> void
 {
     return mozilla::jni::Method<MarkURIVisited_t>::Call(GeckoAppShell::Context(), nullptr, a0);
 }
 
@@ -615,24 +559,16 @@ constexpr char GeckoAppShell::ReportJava
 constexpr char GeckoAppShell::ScheduleRestart_t::name[];
 constexpr char GeckoAppShell::ScheduleRestart_t::signature[];
 
 auto GeckoAppShell::ScheduleRestart() -> void
 {
     return mozilla::jni::Method<ScheduleRestart_t>::Call(GeckoAppShell::Context(), nullptr);
 }
 
-constexpr char GeckoAppShell::SendMessage_t::name[];
-constexpr char GeckoAppShell::SendMessage_t::signature[];
-
-auto GeckoAppShell::SendMessage(mozilla::jni::String::Param a0, mozilla::jni::String::Param a1, int32_t a2) -> void
-{
-    return mozilla::jni::Method<SendMessage_t>::Call(GeckoAppShell::Context(), nullptr, a0, a1, a2);
-}
-
 constexpr char GeckoAppShell::SetAlarm_t::name[];
 constexpr char GeckoAppShell::SetAlarm_t::signature[];
 
 auto GeckoAppShell::SetAlarm(int32_t a0, int32_t a1) -> bool
 {
     return mozilla::jni::Method<SetAlarm_t>::Call(GeckoAppShell::Context(), nullptr, a0, a1);
 }
 
@@ -827,61 +763,16 @@ constexpr char GeckoNetworkManager::OnSt
 constexpr char GeckoNetworkManager::OnStatusChanged_t::signature[];
 
 const char GeckoScreenOrientation::name[] =
         "org/mozilla/gecko/GeckoScreenOrientation";
 
 constexpr char GeckoScreenOrientation::OnOrientationChange_t::name[];
 constexpr char GeckoScreenOrientation::OnOrientationChange_t::signature[];
 
-const char GeckoSmsManager::name[] =
-        "org/mozilla/gecko/GeckoSmsManager";
-
-constexpr char GeckoSmsManager::NotifyCursorDone_t::name[];
-constexpr char GeckoSmsManager::NotifyCursorDone_t::signature[];
-
-constexpr char GeckoSmsManager::NotifyCursorError_t::name[];
-constexpr char GeckoSmsManager::NotifyCursorError_t::signature[];
-
-constexpr char GeckoSmsManager::NotifyGetSms_t::name[];
-constexpr char GeckoSmsManager::NotifyGetSms_t::signature[];
-
-constexpr char GeckoSmsManager::NotifyGetSmsFailed_t::name[];
-constexpr char GeckoSmsManager::NotifyGetSmsFailed_t::signature[];
-
-constexpr char GeckoSmsManager::NotifyMessageCursorResult_t::name[];
-constexpr char GeckoSmsManager::NotifyMessageCursorResult_t::signature[];
-
-constexpr char GeckoSmsManager::NotifySmsDeleteFailed_t::name[];
-constexpr char GeckoSmsManager::NotifySmsDeleteFailed_t::signature[];
-
-constexpr char GeckoSmsManager::NotifySmsDeleted_t::name[];
-constexpr char GeckoSmsManager::NotifySmsDeleted_t::signature[];
-
-constexpr char GeckoSmsManager::NotifySmsDelivery_t::name[];
-constexpr char GeckoSmsManager::NotifySmsDelivery_t::signature[];
-
-constexpr char GeckoSmsManager::NotifySmsMarkAsReadFailed_t::name[];
-constexpr char GeckoSmsManager::NotifySmsMarkAsReadFailed_t::signature[];
-
-constexpr char GeckoSmsManager::NotifySmsMarkedAsRead_t::name[];
-constexpr char GeckoSmsManager::NotifySmsMarkedAsRead_t::signature[];
-
-constexpr char GeckoSmsManager::NotifySmsReceived_t::name[];
-constexpr char GeckoSmsManager::NotifySmsReceived_t::signature[];
-
-constexpr char GeckoSmsManager::NotifySmsSendFailed_t::name[];
-constexpr char GeckoSmsManager::NotifySmsSendFailed_t::signature[];
-
-constexpr char GeckoSmsManager::NotifySmsSent_t::name[];
-constexpr char GeckoSmsManager::NotifySmsSent_t::signature[];
-
-constexpr char GeckoSmsManager::NotifyThreadCursorResult_t::name[];
-constexpr char GeckoSmsManager::NotifyThreadCursorResult_t::signature[];
-
 const char GeckoThread::name[] =
         "org/mozilla/gecko/GeckoThread";
 
 constexpr char GeckoThread::CheckAndSetState_t::name[];
 constexpr char GeckoThread::CheckAndSetState_t::signature[];
 
 auto GeckoThread::CheckAndSetState(mozilla::jni::Object::Param a0, mozilla::jni::Object::Param a1) -> bool
 {
--- a/widget/android/GeneratedJNIWrappers.h
+++ b/widget/android/GeneratedJNIWrappers.h
@@ -316,46 +316,16 @@ public:
         static const mozilla::jni::CallingThread callingThread =
                 mozilla::jni::CallingThread::ANY;
         static const mozilla::jni::DispatchTarget dispatchTarget =
                 mozilla::jni::DispatchTarget::CURRENT;
     };
 
     static auto CreateInputStream(mozilla::jni::Object::Param) -> mozilla::jni::Object::LocalRef;
 
-    struct CreateMessageCursor_t {
-        typedef GeckoAppShell Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int64_t,
-                int64_t,
-                mozilla::jni::ObjectArray::Param,
-                int32_t,
-                mozilla::jni::String::Param,
-                bool,
-                bool,
-                bool,
-                int64_t,
-                bool,
-                int32_t> Args;
-        static constexpr char name[] = "createMessageCursor";
-        static constexpr char signature[] =
-                "(JJ[Ljava/lang/String;ILjava/lang/String;ZZZJZI)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::GECKO;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::CURRENT;
-    };
-
-    static auto CreateMessageCursor(int64_t, int64_t, mozilla::jni::ObjectArray::Param, int32_t, mozilla::jni::String::Param, bool, bool, bool, int64_t, bool, int32_t) -> void;
-
     struct CreateShortcut_t {
         typedef GeckoAppShell Owner;
         typedef void ReturnType;
         typedef void SetterType;
         typedef mozilla::jni::Args<
                 mozilla::jni::String::Param,
                 mozilla::jni::String::Param> Args;
         static constexpr char name[] = "createShortcut";
@@ -367,57 +337,16 @@ public:
         static const mozilla::jni::CallingThread callingThread =
                 mozilla::jni::CallingThread::GECKO;
         static const mozilla::jni::DispatchTarget dispatchTarget =
                 mozilla::jni::DispatchTarget::CURRENT;
     };
 
     static auto CreateShortcut(mozilla::jni::String::Param, mozilla::jni::String::Param) -> void;
 
-    struct CreateThreadCursor_t {
-        typedef GeckoAppShell Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t> Args;
-        static constexpr char name[] = "createThreadCursor";
-        static constexpr char signature[] =
-                "(I)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::GECKO;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::CURRENT;
-    };
-
-    static auto CreateThreadCursor(int32_t) -> void;
-
-    struct DeleteMessage_t {
-        typedef GeckoAppShell Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                int32_t> Args;
-        static constexpr char name[] = "deleteMessage";
-        static constexpr char signature[] =
-                "(II)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::GECKO;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::CURRENT;
-    };
-
-    static auto DeleteMessage(int32_t, int32_t) -> void;
-
     struct DisableAlarm_t {
         typedef GeckoAppShell Owner;
         typedef void ReturnType;
         typedef void SetterType;
         typedef mozilla::jni::Args<> Args;
         static constexpr char name[] = "disableAlarm";
         static constexpr char signature[] =
                 "()V";
@@ -935,37 +864,16 @@ public:
         static const mozilla::jni::CallingThread callingThread =
                 mozilla::jni::CallingThread::GECKO;
         static const mozilla::jni::DispatchTarget dispatchTarget =
                 mozilla::jni::DispatchTarget::CURRENT;
     };
 
     static auto GetMaxTouchPoints() -> int32_t;
 
-    struct GetMessage_t {
-        typedef GeckoAppShell Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                int32_t> Args;
-        static constexpr char name[] = "getMessage";
-        static constexpr char signature[] =
-                "(II)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::GECKO;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::CURRENT;
-    };
-
-    static auto GetMessage(int32_t, int32_t) -> void;
-
     struct GetMimeTypeFromExtensions_t {
         typedef GeckoAppShell Owner;
         typedef mozilla::jni::String::LocalRef ReturnType;
         typedef mozilla::jni::String::Param SetterType;
         typedef mozilla::jni::Args<
                 mozilla::jni::String::Param> Args;
         static constexpr char name[] = "getMimeTypeFromExtensions";
         static constexpr char signature[] =
@@ -995,56 +903,16 @@ public:
         static const mozilla::jni::CallingThread callingThread =
                 mozilla::jni::CallingThread::GECKO;
         static const mozilla::jni::DispatchTarget dispatchTarget =
                 mozilla::jni::DispatchTarget::CURRENT;
     };
 
     static auto GetNetworkLinkType() -> int32_t;
 
-    struct GetNextMessage_t {
-        typedef GeckoAppShell Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t> Args;
-        static constexpr char name[] = "getNextMessage";
-        static constexpr char signature[] =
-                "(I)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::GECKO;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::CURRENT;
-    };
-
-    static auto GetNextMessage(int32_t) -> void;
-
-    struct GetNextThread_t {
-        typedef GeckoAppShell Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t> Args;
-        static constexpr char name[] = "getNextThread";
-        static constexpr char signature[] =
-                "(I)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::GECKO;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::CURRENT;
-    };
-
-    static auto GetNextThread(int32_t) -> void;
-
     struct GetProxyForURI_t {
         typedef GeckoAppShell Owner;
         typedef mozilla::jni::String::LocalRef ReturnType;
         typedef mozilla::jni::String::Param SetterType;
         typedef mozilla::jni::Args<
                 mozilla::jni::String::Param,
                 mozilla::jni::String::Param,
                 mozilla::jni::String::Param,
@@ -1371,39 +1239,16 @@ public:
         static const mozilla::jni::CallingThread callingThread =
                 mozilla::jni::CallingThread::GECKO;
         static const mozilla::jni::DispatchTarget dispatchTarget =
                 mozilla::jni::DispatchTarget::CURRENT;
     };
 
     static auto LockScreenOrientation(int32_t) -> void;
 
-    struct MarkMessageRead_t {
-        typedef GeckoAppShell Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                bool,
-                bool,
-                int32_t> Args;
-        static constexpr char name[] = "markMessageRead";
-        static constexpr char signature[] =
-                "(IZZI)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::GECKO;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::CURRENT;
-    };
-
-    static auto MarkMessageRead(int32_t, bool, bool, int32_t) -> void;
-
     struct MarkURIVisited_t {
         typedef GeckoAppShell Owner;
         typedef void ReturnType;
         typedef void SetterType;
         typedef mozilla::jni::Args<
                 mozilla::jni::String::Param> Args;
         static constexpr char name[] = "markUriVisited";
         static constexpr char signature[] =
@@ -1680,38 +1525,16 @@ public:
         static const mozilla::jni::CallingThread callingThread =
                 mozilla::jni::CallingThread::GECKO;
         static const mozilla::jni::DispatchTarget dispatchTarget =
                 mozilla::jni::DispatchTarget::CURRENT;
     };
 
     static auto ScheduleRestart() -> void;
 
-    struct SendMessage_t {
-        typedef GeckoAppShell Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                mozilla::jni::String::Param,
-                mozilla::jni::String::Param,
-                int32_t> Args;
-        static constexpr char name[] = "sendMessage";
-        static constexpr char signature[] =
-                "(Ljava/lang/String;Ljava/lang/String;I)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::GECKO;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::CURRENT;
-    };
-
-    static auto SendMessage(mozilla::jni::String::Param, mozilla::jni::String::Param, int32_t) -> void;
-
     struct SetAlarm_t {
         typedef GeckoAppShell Owner;
         typedef bool ReturnType;
         typedef bool SetterType;
         typedef mozilla::jni::Args<
                 int32_t,
                 int32_t> Args;
         static constexpr char name[] = "setAlarm";
@@ -2450,323 +2273,16 @@ public:
     };
 
     static const mozilla::jni::CallingThread callingThread =
             mozilla::jni::CallingThread::ANY;
 
     template<class Impl> class Natives;
 };
 
-class GeckoSmsManager : public mozilla::jni::ObjectBase<GeckoSmsManager>
-{
-public:
-    static const char name[];
-
-    explicit GeckoSmsManager(const Context& ctx) : ObjectBase<GeckoSmsManager>(ctx) {}
-
-    struct NotifyCursorDone_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t> Args;
-        static constexpr char name[] = "notifyCursorDone";
-        static constexpr char signature[] =
-                "(I)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifyCursorError_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                int32_t> Args;
-        static constexpr char name[] = "notifyCursorError";
-        static constexpr char signature[] =
-                "(II)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifyGetSms_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                int32_t,
-                mozilla::jni::String::Param,
-                mozilla::jni::String::Param,
-                mozilla::jni::String::Param,
-                int64_t,
-                bool,
-                int32_t> Args;
-        static constexpr char name[] = "notifyGetSms";
-        static constexpr char signature[] =
-                "(IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;JZI)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifyGetSmsFailed_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                int32_t> Args;
-        static constexpr char name[] = "notifyGetSmsFailed";
-        static constexpr char signature[] =
-                "(II)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifyMessageCursorResult_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                int32_t,
-                mozilla::jni::String::Param,
-                mozilla::jni::String::Param,
-                mozilla::jni::String::Param,
-                int64_t,
-                int64_t,
-                bool,
-                int32_t> Args;
-        static constexpr char name[] = "notifyMessageCursorResult";
-        static constexpr char signature[] =
-                "(IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;JJZI)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifySmsDeleteFailed_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                int32_t> Args;
-        static constexpr char name[] = "notifySmsDeleteFailed";
-        static constexpr char signature[] =
-                "(II)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifySmsDeleted_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                bool,
-                int32_t> Args;
-        static constexpr char name[] = "notifySmsDeleted";
-        static constexpr char signature[] =
-                "(ZI)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifySmsDelivery_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                int32_t,
-                mozilla::jni::String::Param,
-                mozilla::jni::String::Param,
-                int64_t> Args;
-        static constexpr char name[] = "notifySmsDelivery";
-        static constexpr char signature[] =
-                "(IILjava/lang/String;Ljava/lang/String;J)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifySmsMarkAsReadFailed_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                int32_t> Args;
-        static constexpr char name[] = "notifySmsMarkAsReadFailed";
-        static constexpr char signature[] =
-                "(II)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifySmsMarkedAsRead_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                bool,
-                int32_t> Args;
-        static constexpr char name[] = "notifySmsMarkedAsRead";
-        static constexpr char signature[] =
-                "(ZI)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifySmsReceived_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                mozilla::jni::String::Param,
-                mozilla::jni::String::Param,
-                int32_t,
-                int64_t,
-                int64_t> Args;
-        static constexpr char name[] = "notifySmsReceived";
-        static constexpr char signature[] =
-                "(ILjava/lang/String;Ljava/lang/String;IJJ)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifySmsSendFailed_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                int32_t> Args;
-        static constexpr char name[] = "notifySmsSendFailed";
-        static constexpr char signature[] =
-                "(II)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifySmsSent_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int32_t,
-                mozilla::jni::String::Param,
-                mozilla::jni::String::Param,
-                int64_t,
-                int32_t> Args;
-        static constexpr char name[] = "notifySmsSent";
-        static constexpr char signature[] =
-                "(ILjava/lang/String;Ljava/lang/String;JI)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    struct NotifyThreadCursorResult_t {
-        typedef GeckoSmsManager Owner;
-        typedef void ReturnType;
-        typedef void SetterType;
-        typedef mozilla::jni::Args<
-                int64_t,
-                mozilla::jni::String::Param,
-                mozilla::jni::String::Param,
-                int64_t,
-                mozilla::jni::ObjectArray::Param,
-                int64_t,
-                mozilla::jni::String::Param,
-                int32_t> Args;
-        static constexpr char name[] = "notifyThreadCursorResult";
-        static constexpr char signature[] =
-                "(JLjava/lang/String;Ljava/lang/String;J[Ljava/lang/Object;JLjava/lang/String;I)V";
-        static const bool isStatic = true;
-        static const mozilla::jni::ExceptionMode exceptionMode =
-                mozilla::jni::ExceptionMode::ABORT;
-        static const mozilla::jni::CallingThread callingThread =
-                mozilla::jni::CallingThread::UI;
-        static const mozilla::jni::DispatchTarget dispatchTarget =
-                mozilla::jni::DispatchTarget::GECKO;
-    };
-
-    static const mozilla::jni::CallingThread callingThread =
-            mozilla::jni::CallingThread::UI;
-
-    template<class Impl> class Natives;
-};
-
 class GeckoThread : public mozilla::jni::ObjectBase<GeckoThread>
 {
 public:
     static const char name[];
 
     explicit GeckoThread(const Context& ctx) : ObjectBase<GeckoThread>(ctx) {}
 
     class State;