Merge mozilla-central and inbound; CLOSED TREE
authorEd Morley <emorley@mozilla.com>
Fri, 07 Mar 2014 15:07:22 +0000
changeset 189757 2f3539fc3c685025b346d5ec550801a619b9544d
parent 189665 36c081b72fd8801fc6c697aee1684362ccde551d (current diff)
parent 189756 7e787cc4649e09ddb02af25815bb0211ddd9c9f3 (diff)
child 189758 1293344f5eb678c30a353663e0627e3928fff757
push id3503
push userraliiev@mozilla.com
push dateMon, 28 Apr 2014 18:51:11 +0000
treeherdermozilla-beta@c95ac01e332e [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone30.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge mozilla-central and inbound; CLOSED TREE
dom/icc/interfaces/SimToolKit.idl
js/xpconnect/src/dictionary_helper_gen.conf
js/xpconnect/src/dictionary_helper_gen.py
--- a/accessible/tests/mochitest/hittest/a11y.ini
+++ b/accessible/tests/mochitest/hittest/a11y.ini
@@ -1,13 +1,11 @@
 [DEFAULT]
 support-files = zoom_tree.xul
 
 [test_browser.html]
 [test_canvas_hitregion.html]
-# Disabled everywhere because of failures. It appears this test has
-# never executed since its inception.
-skip-if = true || (os == "android" || appname == "b2g")
+skip-if = (os == "android" || appname == "b2g")
 [test_general.html]
 [test_menu.xul]
 [test_zoom.html]
 [test_zoom_text.html]
 [test_zoom_tree.xul]
--- a/accessible/tests/mochitest/hittest/test_canvas_hitregion.html
+++ b/accessible/tests/mochitest/hittest/test_canvas_hitregion.html
@@ -38,17 +38,17 @@
       if (document.activeElement == element)
         context.drawFocusIfNeeded(element);
       context.addHitRegion({control: element});
       context.restore();
     }
 
     function doTest()
     {
-      getNode("hittest").scrollIntoView(true);
+      getNode("hitcanvas").scrollIntoView(true);
 
       var context = document.getElementById("hitcanvas").getContext('2d');
       redrawCheckbox(context, document.getElementById('hitcheck'), 20, 40);
 
       var hitcanvas = getAccessible("hitcanvas");
       var hitcheck = getAccessible("hitcheck");
 
       var [hitX, hitY, hitWidth, hitHeight] = getBounds(hitcanvas);
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -869,16 +869,24 @@ pref("osfile.reset_worker_delay", 5000);
 // more often than the default value (100).
 pref("apz.asyncscroll.throttle", 40);
 pref("apz.pan_repaint_interval", 16);
 
 // Maximum fling velocity in px/ms.  Slower devices may need to reduce this
 // to avoid checkerboarding.  Note, float value must be set as a string.
 pref("apz.max_velocity_pixels_per_ms", "6.0");
 
+// Tweak default displayport values to reduce the risk of running out of
+// memory when zooming in
+pref("apz.x_skate_size_multiplier", "1.25");
+pref("apz.y_skate_size_multiplier", "1.5");
+pref("apz.x_stationary_size_multiplier", "1.5");
+pref("apz.y_stationary_size_multiplier", "1.8");
+pref("apz.enlarge_displayport_when_clipped", true);
+
 // This preference allows FirefoxOS apps (and content, I think) to force
 // the use of software (instead of hardware accelerated) 2D canvases by
 // creating a context like this:
 //
 //   canvas.getContext('2d', { willReadFrequently: true })
 //
 // Using a software canvas can save memory when JS calls getImageData()
 // on the canvas frequently. See bug 884226.
--- a/b2g/app/ua-update.json.in
+++ b/b2g/app/ua-update.json.in
@@ -90,48 +90,36 @@
   // bug 828422, publico.es
   "publico.es": "\\(Mobile#(Android; Mobile",
   // bug 828425, mercadolibre.com.ve
   "mercadolibre.com.ve": "\\(Mobile#(Android; Mobile",
   // bug 828439, movistar.com.ve
   "movistar.com.ve": "\\(Mobile#(Android; Mobile",
   // bug 828445, bumeran.com.ve
   "bumeran.com.ve": "\\(Mobile#(Android; Mobile",
-  // bug 843112, movil.bankinter.es
-  "movil.bankinter.es": "\\(Mobile#(Android; Mobile",
   // bug 843114, einforma.com
   "einforma.com": "\\(Mobile#(Android; Mobile",
-  // bug 843119, askthebuilder.com
-  "askthebuilder.com": "\\(Mobile#(Android; Mobile",
-  // bug 843121, tor.com
-  "tor.com": "\\(Mobile#(Android; Mobile",
   // bug 843126, es.playstation.com
   "es.playstation.com": "Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19",
   // bug 843129, 11870.com
   "11870.com": "\\(Mobile#(Android; Mobile",
   // bug 843200, iphonejuegosgratis.com
   "iphonejuegosgratis.com": "\\(Mobile#(Android; Mobile",
   // bug 843132, comunio.es
   "comunio.es": "\\(Mobile#(Android; Mobile",
-  // bug 843139, consumersearch.com
-  "consumersearch.com": "\\(Mobile#(Android; Mobile",
-  // bug 843141, foodily.com
-  "foodily.com": "\\(Mobile#(Android; Mobile",
   // bug 843151, citibank.com
   "citibank.com": "\\(Mobile#(Android; Mobile",
   // bug 843153, games.com
   "games.com": "\\(Mobile#(Android; Mobile",
   // bug 843160, ehow.com
   "ehow.com": "\\(Mobile#(Android; Mobile",
   // bug 843165, virginatlantic.com
   "virginatlantic.com": "\\(Mobile#(Android; Mobile",
   // bug 843172, zimbio.com
   "zimbio.com": "\\(Mobile#(Android; Mobile",
-  // bug 843178, txt2nite.com
-  "txt2nite.com": "\\(Mobile#(Android; Mobile",
   // bug 843181, slashgear.com
   "slashgear.com": "\\(Mobile#(Android; Mobile",
   // bug 843186, chevrolet.com
   "chevrolet.com": "\\(Mobile#(Android; Mobile",
   // bug 866577, 3g.qq.com
   "3g.qq.com": "\\(Mobile#(Android; Mobile",
   // bug 878222, arukereso.hu
   "arukereso.hu": "\\(Mobile#(Android; Mobile",
--- a/browser/components/shell/src/nsWindowsShellService.cpp
+++ b/browser/components/shell/src/nsWindowsShellService.cpp
@@ -761,27 +761,20 @@ WriteBitmap(nsIFile* aFile, imgIContaine
   nsRefPtr<gfxImageSurface> thebesImageSurface =
     thebesSurface->GetAsReadableARGB32ImageSurface();
   NS_ENSURE_TRUE(thebesImageSurface, NS_ERROR_FAILURE);
 
   RefPtr<DataSourceSurface> dataSurface =
     thebesImageSurface->CopyToB8G8R8A8DataSourceSurface();
   NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
 
-  DataSourceSurface::MappedSurface map;
-  dataSurface->Map(DataSourceSurface::MapType::READ, &map);
-  if (!map.mData) {
-    return NS_ERROR_FAILURE;
-  }
-
   int32_t width = dataSurface->GetSize().width;
   int32_t height = dataSurface->GetSize().height;
   int32_t bytesPerPixel = 4 * sizeof(uint8_t);
   uint32_t bytesPerRow = bytesPerPixel * width;
-  uint32_t length = map.mStride * height;
 
   // initialize these bitmap structs which we will later
   // serialize directly to the head of the bitmap file
   BITMAPINFOHEADER bmi;
   bmi.biSize = sizeof(BITMAPINFOHEADER);
   bmi.biWidth = width;
   bmi.biHeight = height;
   bmi.biPlanes = 1;
@@ -800,43 +793,50 @@ WriteBitmap(nsIFile* aFile, imgIContaine
   bf.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
   bf.bfSize = bf.bfOffBits + bmi.biSizeImage;
 
   // get a file output stream
   nsCOMPtr<nsIOutputStream> stream;
   rv = NS_NewLocalFileOutputStream(getter_AddRefs(stream), aFile);
   NS_ENSURE_SUCCESS(rv, rv);
 
+  DataSourceSurface::MappedSurface map;
+  if (!dataSurface->Map(DataSourceSurface::MapType::READ, &map)) {
+    return NS_ERROR_FAILURE;
+  }
+
   // write the bitmap headers and rgb pixel data to the file
   rv = NS_ERROR_FAILURE;
   if (stream) {
     uint32_t written;
     stream->Write((const char*)&bf, sizeof(BITMAPFILEHEADER), &written);
     if (written == sizeof(BITMAPFILEHEADER)) {
       stream->Write((const char*)&bmi, sizeof(BITMAPINFOHEADER), &written);
       if (written == sizeof(BITMAPINFOHEADER)) {
         // write out the image data backwards because the desktop won't
         // show bitmaps with negative heights for top-to-bottom
-        uint32_t i = length;
+        uint32_t i = map.mStride * height;
         do {
           i -= map.mStride;
           stream->Write(((const char*)map.mData) + i, bytesPerRow, &written);
           if (written == bytesPerRow) {
             rv = NS_OK;
           } else {
             rv = NS_ERROR_FAILURE;
             break;
           }
         } while (i != 0);
       }
     }
 
     stream->Close();
   }
 
+  dataSurface->Unmap();
+
   return rv;
 }
 
 NS_IMETHODIMP
 nsWindowsShellService::SetDesktopBackground(nsIDOMElement* aElement, 
                                             int32_t aPosition)
 {
   nsresult rv;
--- a/configure.in
+++ b/configure.in
@@ -3930,17 +3930,17 @@ MOZ_WEBSMS_BACKEND=
 MOZ_ANDROID_BEAM=
 MOZ_ANDROID_SYNTHAPKS=
 ACCESSIBILITY=1
 MOZ_TIME_MANAGER=
 MOZ_PAY=
 MOZ_AUDIO_CHANNEL_MANAGER=
 NSS_NO_LIBPKIX=
 MOZ_CONTENT_SANDBOX=
-MOZ_CONTENT_SANDBOX_REPORTER=
+MOZ_CONTENT_SANDBOX_REPORTER=1
 JSGC_USE_EXACT_ROOTING=
 
 case "$target_os" in
     mingw*)
         NS_ENABLE_TSF=1
         AC_DEFINE(NS_ENABLE_TSF)
         ;;
 esac
@@ -8000,17 +8000,17 @@ dnl Skia
 dnl ========================================================
 if test "$MOZ_ENABLE_SKIA"; then
   AC_DEFINE(MOZ_ENABLE_SKIA)
   AC_DEFINE(USE_SKIA)
   if test "${MOZ_WIDGET_TOOLKIT}" = "android" -o x"$MOZ_WIDGET_TOOLKIT" = x"gonk"; then
     AC_DEFINE(SK_BUILD_FOR_ANDROID_NDK)
   fi
 
-  if test "${CPU_ARCH}" != "ppc" -a "${CPU_ARCH}" != "ppc64"; then
+  if test "${CPU_ARCH}" != "ppc" -a "${CPU_ARCH}" != "ppc64" -a "${CPU_ARCH}" != "sparc" ; then
     MOZ_ENABLE_SKIA_GPU=1
     AC_DEFINE(USE_SKIA_GPU)
     AC_SUBST(MOZ_ENABLE_SKIA_GPU)
   fi
 fi
 AC_SUBST(MOZ_ENABLE_SKIA)
 
 dnl ========================================================
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -176,17 +176,16 @@
 #include "mozilla/dom/Comment.h"
 #include "nsTextNode.h"
 #include "mozilla/dom/Link.h"
 #include "mozilla/dom/HTMLElementBinding.h"
 #include "mozilla/dom/SVGElementBinding.h"
 #include "nsXULAppAPI.h"
 #include "mozilla/dom/Touch.h"
 #include "mozilla/dom/TouchEvent.h"
-#include "DictionaryHelpers.h"
 #include "GeneratedEvents.h"
 
 #include "mozilla/Preferences.h"
 
 #include "imgILoader.h"
 #include "imgRequestProxy.h"
 #include "nsWrapperCacheInlines.h"
 #include "nsSandboxFlags.h"
--- a/content/media/webspeech/recognition/nsIDOMSpeechRecognitionEvent.idl
+++ b/content/media/webspeech/recognition/nsIDOMSpeechRecognitionEvent.idl
@@ -24,15 +24,8 @@ interface nsIDOMSpeechRecognitionEvent :
                                                in DOMString interpretation,
                                                in nsIDOMDocument emma);
 
     readonly attribute unsigned long resultIndex;
     readonly attribute nsISupports results;
     readonly attribute DOMString interpretation;
     readonly attribute nsIDOMDocument emma;
 };
-
-dictionary SpeechRecognitionEventInit : EventInit {
-    unsigned long resultIndex;
-    nsISupports results;
-    DOMString interpretation;
-    nsIDOMDocument emma;
-};
--- a/content/media/webspeech/synth/nsIDOMSpeechSynthesisEvent.idl
+++ b/content/media/webspeech/synth/nsIDOMSpeechSynthesisEvent.idl
@@ -20,14 +20,8 @@ interface nsIDOMSpeechSynthesisEvent : n
                                            in unsigned long aCharIndex,
                                            in float aElapsedTime,
                                            in DOMString aName);
 
   readonly attribute unsigned long charIndex;
   readonly attribute float elapsedTime;
   readonly attribute DOMString name;
 };
-
-dictionary SpeechSynthesisEventInit : EventInit {
-  unsigned long charIndex;
-  float elapsedTime;
-  DOMString name;
-};
--- a/db/sqlite3/src/moz.build
+++ b/db/sqlite3/src/moz.build
@@ -37,16 +37,22 @@ else:
 for var in ('SQLITE_SECURE_DELETE', 'SQLITE_THREADSAFE', 'SQLITE_CORE',
             'SQLITE_ENABLE_FTS3', 'SQLITE_ENABLE_UNLOCK_NOTIFY'):
     DEFINES[var] = 1
 
 DEFINES['SQLITE_DEFAULT_PAGE_SIZE'] = 32768
 DEFINES['SQLITE_MAX_DEFAULT_PAGE_SIZE'] = 32768
 DEFINES['SQLITE_MAX_SCHEMA_RETRY'] = 25
 
+# -DSQLITE_WIN32_GETVERSIONEX=0 avoids using deprecated functions.
+# SQLite will just assume we are running on NT kinds of Windows. That's fine
+# because we don't support Win9x.
+if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
+    DEFINES['SQLITE_WIN32_GETVERSIONEX'] = 0
+
 # -DSQLITE_ENABLE_LOCKING_STYLE=1 to help with AFP folders
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
     DEFINES['SQLITE_ENABLE_LOCKING_STYLE'] = 1
 
 # Turn on SQLite's assertions in debug builds.
 if CONFIG['MOZ_DEBUG']:
     DEFINES['SQLITE_DEBUG'] = 1
 
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -716,29 +716,18 @@ static const char js_strict_option_str[]
 #ifdef DEBUG
 static const char js_strict_debug_option_str[] = JS_OPTIONS_DOT_STR "strict.debug";
 #endif
 static const char js_werror_option_str[] = JS_OPTIONS_DOT_STR "werror";
 #ifdef JS_GC_ZEAL
 static const char js_zeal_option_str[]        = JS_OPTIONS_DOT_STR "gczeal";
 static const char js_zeal_frequency_str[]     = JS_OPTIONS_DOT_STR "gczeal.frequency";
 #endif
-static const char js_typeinfer_content_str[]  = JS_OPTIONS_DOT_STR "typeinference.content";
-static const char js_typeinfer_chrome_str[]   = JS_OPTIONS_DOT_STR "typeinference.chrome";
 static const char js_memlog_option_str[]      = JS_OPTIONS_DOT_STR "mem.log";
 static const char js_memnotify_option_str[]   = JS_OPTIONS_DOT_STR "mem.notify";
-static const char js_asmjs_content_str[]      = JS_OPTIONS_DOT_STR "asmjs";
-static const char js_baselinejit_content_str[] = JS_OPTIONS_DOT_STR "baselinejit.content";
-static const char js_baselinejit_chrome_str[]  = JS_OPTIONS_DOT_STR "baselinejit.chrome";
-static const char js_baselinejit_eager_str[]  = JS_OPTIONS_DOT_STR "baselinejit.unsafe_eager_compilation";
-static const char js_ion_content_str[]        = JS_OPTIONS_DOT_STR "ion.content";
-static const char js_ion_chrome_str[]         = JS_OPTIONS_DOT_STR "ion.chrome";
-static const char js_ion_eager_str[]          = JS_OPTIONS_DOT_STR "ion.unsafe_eager_compilation";
-static const char js_parallel_parsing_str[]   = JS_OPTIONS_DOT_STR "parallel_parsing";
-static const char js_ion_parallel_compilation_str[] = JS_OPTIONS_DOT_STR "ion.parallel_compilation";
 
 void
 nsJSContext::JSOptionChangedCallback(const char *pref, void *data)
 {
   nsJSContext *context = reinterpret_cast<nsJSContext *>(data);
   JSContext *cx = context->mContext;
 
   sPostGCEventsToConsole = Preferences::GetBool(js_memlog_option_str);
@@ -751,69 +740,27 @@ nsJSContext::JSOptionChangedCallback(con
   // So ask for the member directly instead.
   nsIScriptGlobalObject *global = context->GetGlobalObjectRef();
 
   // XXX should we check for sysprin instead of a chrome window, to make
   // XXX components be covered by the chrome pref instead of the content one?
   nsCOMPtr<nsIDOMWindow> contentWindow(do_QueryInterface(global));
   nsCOMPtr<nsIDOMChromeWindow> chromeWindow(do_QueryInterface(global));
 
-  bool useTypeInference = Preferences::GetBool((chromeWindow || !contentWindow) ?
-                                               js_typeinfer_chrome_str :
-                                               js_typeinfer_content_str);
-  bool useBaselineJIT = Preferences::GetBool((chromeWindow || !contentWindow) ?
-                                               js_baselinejit_chrome_str :
-                                               js_baselinejit_content_str);
-  bool useBaselineJITEager = Preferences::GetBool(js_baselinejit_eager_str);
-  bool useIon = Preferences::GetBool((chromeWindow || !contentWindow) ?
-                                               js_ion_chrome_str :
-                                               js_ion_content_str);
-  bool useIonEager = Preferences::GetBool(js_ion_eager_str);
-  bool useAsmJS = Preferences::GetBool(js_asmjs_content_str);
-  bool parallelParsing = Preferences::GetBool(js_parallel_parsing_str);
-  bool parallelIonCompilation = Preferences::GetBool(js_ion_parallel_compilation_str);
-  nsCOMPtr<nsIXULRuntime> xr = do_GetService(XULRUNTIME_SERVICE_CONTRACTID);
-  if (xr) {
-    bool safeMode = false;
-    xr->GetInSafeMode(&safeMode);
-    if (safeMode) {
-      useTypeInference = false;
-      useBaselineJIT = false;
-      useBaselineJITEager = false;
-      useIon = false;
-      useIonEager = false;
-      useAsmJS = false;
-    }
-  }
-
-  JS::ContextOptionsRef(cx).setTypeInference(useTypeInference)
-                           .setBaseline(useBaselineJIT)
-                           .setIon(useIon)
-                           .setAsmJS(useAsmJS);
-
 #ifdef DEBUG
   // In debug builds, warnings are enabled in chrome context if
   // javascript.options.strict.debug is true
   if (Preferences::GetBool(js_strict_debug_option_str) &&
       (chromeWindow || !contentWindow)) {
     JS::ContextOptionsRef(cx).setExtraWarnings(true);
   }
 #endif
 
   JS::ContextOptionsRef(cx).setWerror(Preferences::GetBool(js_werror_option_str));
 
-  ::JS_SetParallelParsingEnabled(context->mContext, parallelParsing);
-  ::JS_SetParallelIonCompilationEnabled(context->mContext, parallelIonCompilation);
-
-  ::JS_SetGlobalJitCompilerOption(context->mContext, JSJITCOMPILER_BASELINE_USECOUNT_TRIGGER,
-                                  (useBaselineJITEager ? 0 : -1));
-
-  ::JS_SetGlobalJitCompilerOption(context->mContext, JSJITCOMPILER_ION_USECOUNT_TRIGGER,
-                                  (useIonEager ? 0 : -1));
-
 #ifdef JS_GC_ZEAL
   int32_t zeal = Preferences::GetInt(js_zeal_option_str, -1);
   int32_t frequency = Preferences::GetInt(js_zeal_frequency_str, JS_DEFAULT_ZEAL_FREQ);
   if (zeal >= 0)
     ::JS_SetGCZeal(context->mContext, (uint8_t)zeal, frequency);
 #endif
 }
 
--- a/dom/camera/DOMCameraControl.cpp
+++ b/dom/camera/DOMCameraControl.cpp
@@ -19,27 +19,25 @@
 #include "nsIObserverService.h"
 #include "nsIDOMDeviceStorage.h"
 #include "nsIDOMEventListener.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsXULAppAPI.h"
 #include "DOMCameraManager.h"
 #include "DOMCameraCapabilities.h"
 #include "CameraCommon.h"
-#include "DictionaryHelpers.h"
 #include "nsGlobalWindow.h"
 #include "CameraPreviewMediaStream.h"
 #include "mozilla/dom/CameraControlBinding.h"
 #include "mozilla/dom/CameraManagerBinding.h"
 #include "mozilla/dom/CameraCapabilitiesBinding.h"
 #include "mozilla/dom/BindingUtils.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
-using namespace mozilla::idl;
 using namespace mozilla::ipc;
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMCameraControl)
   NS_INTERFACE_MAP_ENTRY(nsISupports)
   NS_INTERFACE_MAP_ENTRY(nsIDOMMediaStream)
 NS_INTERFACE_MAP_END_INHERITING(DOMMediaStream)
 
 NS_IMPL_ADDREF_INHERITED(nsDOMCameraControl, DOMMediaStream)
--- a/dom/camera/DOMCameraManager.cpp
+++ b/dom/camera/DOMCameraManager.cpp
@@ -6,17 +6,16 @@
 #include "nsDebug.h"
 #include "jsapi.h"
 #include "nsPIDOMWindow.h"
 #include "mozilla/Services.h"
 #include "nsObserverService.h"
 #include "nsIPermissionManager.h"
 #include "DOMCameraControl.h"
 #include "nsDOMClassInfo.h"
-#include "DictionaryHelpers.h"
 #include "CameraCommon.h"
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/dom/CameraManagerBinding.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_1(nsDOMCameraManager, mWindow)
--- a/dom/cellbroadcast/interfaces/nsIDOMMozCellBroadcastEvent.idl
+++ b/dom/cellbroadcast/interfaces/nsIDOMMozCellBroadcastEvent.idl
@@ -12,14 +12,8 @@ interface nsIDOMMozCellBroadcastEvent : 
   //[binaryname(MessageMoz)]
   readonly attribute nsIDOMMozCellBroadcastMessage message;
 
   [noscript] void initMozCellBroadcastEvent(in DOMString aType,
                                             in boolean aCanBubble,
                                             in boolean aCancelable,
                                             in nsIDOMMozCellBroadcastMessage aMessage);
 };
-
-dictionary MozCellBroadcastEventInit : EventInit
-{
-  //[binaryname(MessageMoz)]
-  nsIDOMMozCellBroadcastMessage message;
-};
--- a/dom/devicestorage/nsDeviceStorage.cpp
+++ b/dom/devicestorage/nsDeviceStorage.cpp
@@ -32,17 +32,16 @@
 #include "nsAppDirectoryServiceDefs.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsIDOMFile.h"
 #include "nsDOMBlobBuilder.h"
 #include "nsNetUtil.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsIPrincipal.h"
 #include "nsJSUtils.h"
-#include "DictionaryHelpers.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsXULAppAPI.h"
 #include "TabChild.h"
 #include "DeviceStorageFileDescriptor.h"
 #include "DeviceStorageRequestChild.h"
 #include "nsIDOMDeviceStorageChangeEvent.h"
 #include "nsCRT.h"
--- a/dom/downloads/tests/mochitest.ini
+++ b/dom/downloads/tests/mochitest.ini
@@ -1,9 +1,10 @@
 [DEFAULT]
+skip-if = (buildapp == 'b2g' && toolkit != 'gonk') # b2g-desktop(bug 979446, frequent failures)
 support-files =
   serve_file.sjs
 
 [test_downloads_navigator_object.html]
 [test_downloads_basic.html]
 [test_downloads_large.html]
 [test_downloads_pause_remove.html]
 [test_downloads_pause_resume.html]
--- a/dom/file/ArchiveZipEvent.h
+++ b/dom/file/ArchiveZipEvent.h
@@ -8,18 +8,16 @@
 #define mozilla_dom_file_domarchivezipevent_h__
 
 #include "mozilla/Attributes.h"
 #include "ArchiveEvent.h"
 
 #include "FileCommon.h"
 #include "zipstruct.h"
 
-#include "DictionaryHelpers.h"
-
 BEGIN_FILE_NAMESPACE
 
 /**
  * ArchiveZipItem - ArchiveItem for ArchiveReaderZipEvent
  */
 class ArchiveZipItem : public ArchiveItem
 {
 public:
--- a/dom/filesystem/CreateDirectoryTask.cpp
+++ b/dom/filesystem/CreateDirectoryTask.cpp
@@ -43,17 +43,18 @@ CreateDirectoryTask::CreateDirectoryTask
   MOZ_ASSERT(FileSystemUtils::IsParentProcess(),
              "Only call from parent process!");
   MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
   mTargetRealPath = aParam.realPath();
 }
 
 CreateDirectoryTask::~CreateDirectoryTask()
 {
-  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  MOZ_ASSERT(!mPromise || NS_IsMainThread(),
+             "mPromise should be released on main thread!");
 }
 
 already_AddRefed<Promise>
 CreateDirectoryTask::GetPromise()
 {
   MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
   return nsRefPtr<Promise>(mPromise).forget();
 }
@@ -118,27 +119,30 @@ CreateDirectoryTask::Work()
 }
 
 void
 CreateDirectoryTask::HandlerCallback()
 {
   MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
   nsRefPtr<FileSystemBase> filesystem = do_QueryReferent(mFileSystem);
   if (!filesystem) {
+    mPromise = nullptr;
     return;
   }
 
   if (HasError()) {
     nsRefPtr<DOMError> domError = new DOMError(filesystem->GetWindow(),
       mErrorValue);
     mPromise->MaybeReject(domError);
+    mPromise = nullptr;
     return;
   }
   nsRefPtr<Directory> dir = new Directory(filesystem, mTargetRealPath);
   mPromise->MaybeResolve(dir);
+  mPromise = nullptr;
 }
 
 void
 CreateDirectoryTask::GetPermissionAccessType(nsCString& aAccess) const
 {
   aAccess.AssignLiteral("create");
 }
 
--- a/dom/filesystem/GetFileOrDirectoryTask.cpp
+++ b/dom/filesystem/GetFileOrDirectoryTask.cpp
@@ -48,17 +48,18 @@ GetFileOrDirectoryTask::GetFileOrDirecto
   MOZ_ASSERT(FileSystemUtils::IsParentProcess(),
              "Only call from parent process!");
   MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
   mTargetRealPath = aParam.realPath();
 }
 
 GetFileOrDirectoryTask::~GetFileOrDirectoryTask()
 {
-  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  MOZ_ASSERT(!mPromise || NS_IsMainThread(),
+             "mPromise should be released on main thread!");
 }
 
 already_AddRefed<Promise>
 GetFileOrDirectoryTask::GetPromise()
 {
   MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
   return nsRefPtr<Promise>(mPromise).forget();
 }
@@ -192,33 +193,37 @@ GetFileOrDirectoryTask::Work()
 }
 
 void
 GetFileOrDirectoryTask::HandlerCallback()
 {
   MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
   nsRefPtr<FileSystemBase> filesystem = do_QueryReferent(mFileSystem);
   if (!filesystem) {
+    mPromise = nullptr;
     return;
   }
 
   if (HasError()) {
     nsRefPtr<DOMError> domError = new DOMError(filesystem->GetWindow(),
       mErrorValue);
     mPromise->MaybeReject(domError);
+    mPromise = nullptr;
     return;
   }
 
   if (mIsDirectory) {
     nsRefPtr<Directory> dir = new Directory(filesystem, mTargetRealPath);
     mPromise->MaybeResolve(dir);
+    mPromise = nullptr;
     return;
   }
 
   mPromise->MaybeResolve(mTargetFile);
+  mPromise = nullptr;
 }
 
 void
 GetFileOrDirectoryTask::GetPermissionAccessType(nsCString& aAccess) const
 {
   aAccess.AssignLiteral("read");
 }
 
deleted file mode 100644
--- a/dom/icc/interfaces/SimToolKit.idl
+++ /dev/null
@@ -1,669 +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 "nsIDOMEvent.idl"
-
-interface nsIDOMEvent;
-
-dictionary MozStkTextMessage
-{
-  /**
-   * Text String.
-   *
-   * @see TS 11.14, clause 12.15, Text String.
-   */
-  DOMString text;
-
-  /**
-   * The length of time for which the ME shall display the dialog.
-   *
-   * @see MozStkDuration
-   */
-  jsval duration;
-
-  /**
-   * Indicate this text message is high priority or normal priority.
-   *
-   * @see TS 11.14, clause 12.6, Command Qualifier, Display Text, bit 1.
-   *
-   * High priority text shall be displayed on the screen immediately, except if
-   * there is a conflict of priority level of alerting such as incoming calls
-   * or a low battery warning. In that situation, the resolution is left to
-   * the terminal. If the command is rejected in spite of the high priority,
-   * the terminal shall inform the ICC with resultCode is
-   * TERMINAL_CRNTLY_UNABLE_TO_PROCESS in MozStkResponse.
-   *
-   * true: high priority
-   * false: normal priority
-   */
-  boolean isHighPriority;
-
-  /**
-   * Need to wait for user to clear message or not.
-   *
-   * @see TS 11.14, clause 12.6, Command Qualifier, Display Text, bit 8.
-   *
-   * If this attribute is true, but user doesn't give any input within a period
-   * of time(said 30 secs), the terminal shall inform the ICC with resultCode
-   * is NO_RESPONSE_FROM_USER in MozStkResponse.
-   *
-   * true: Wait for user to clear message.
-   * false: clear message after a delay.
-   */
-  boolean userClear;
-
-  /**
-   * Need to response immediately or not.
-   *
-   * @see TS 11.14, clause 12.43, Immediate response.
-   *
-   * When this attribute is true, the terminal shall immediately send
-   * MozStkResponse with resultCode is OK.
-   *
-   * true: The terminal shall send response immediately.
-   * false: otherwise.
-   */
-  boolean responseNeeded;
-};
-
-dictionary MozStkItem
-{
-  /**
-   * Identifier of item.
-   *
-   * The identifier is a single byte between '01' and 'FF'. Each item shall
-   * have a unique identifier within an Item list.
-   */
-  unsigned short identifier;
-
-  /**
-   * Text string of item.
-   */
-  DOMString text;
-};
-
-dictionary MozStkMenu
-{
-  /**
-   * Array of MozStkItem.
-   *
-   * @see TS 11.14, clause 12.9
-   */
-  jsval items; // MozStkItem[]
-
-  /**
-   * Presentation type, one of TYPE_*.
-   */
-  unsigned short presentationType;
-
-  /**
-   * Title of the menu.
-   */
-  DOMString title;
-
-  /**
-   * Default item identifier of the menu.
-   */
-  unsigned short defaultItem;
-
-  /**
-   * Help information available or not.
-   *
-   * @see TS 11.14, clause 12.6, Command Qualifier, SET UP MENU, bit 8.
-   *
-   * true: help information available.
-   * false: no help information available.
-   */
-  boolean isHelpAvailable;
-
-  /**
-   * List of Next Action Indicators.
-   * Each element should be one of nsIDOMMozIccManager.STK_CMD_*
-   *                            or nsIDOMMozIccManager.STK_NEXT_ACTION_*
-   * If it's STK_NEXT_ACTION_NULL, the terminal should ignore this action
-   * in corresponding item.
-   *
-   * @see TS 11.14, clause 12.24, Items Next Action Indicator.
-   */
-  jsval nextActionList; // unsigned short []
-};
-
-dictionary MozStkInput
-{
-  /**
-   * Text for the ME to display in conjunction with asking the user to respond.
-   */
-  DOMString text;
-
-  /**
-   * The length of time for which the ME shall display the dialog. This field
-   * is used only for GET INKEY.
-   *
-   * @see TS 11.14, clause 11.8, duration, GET INKEY T.C 27.22.4.2.8.4.2
-   */
-  jsval duration;
-
-  /**
-   * Minimum length of response.
-   */
-  unsigned short minLength;
-
-  /**
-   * Maximum length of response.
-   */
-  unsigned short maxLength;
-
-  /**
-   * Text for the ME to display, corresponds to a default text string offered
-   * by the ICC.
-   */
-  DOMString defaultText;
-
-  /**
-   * Input format.
-   *
-   * @see TS 11.14, clause 12.6, Command Qualifier, GET INPUT, bit 1.
-   *
-   * true: Alphabet set.
-   * false: Digits only.
-   */
-  boolean isAlphabet;
-
-  /**
-   * Alphabet encoding.
-   *
-   * @see TS 11.14, clause 12.6, Command Qualifier, GET INPUT, bit 2.
-   *
-   * true: UCS2 alphabet.
-   * false: default SMS alphabet.
-   */
-  boolean isUCS2;
-
-  /**
-   * Visibility of input.
-   *
-   * @see TS 11.14, clause 12.6, Command Qualifier, GET INPUT, bit 3.
-   *
-   * true: User input shall not be revealed in any way.
-   * false: ME may echo user input on the display.
-   */
-  boolean hideInput;
-
-  /**
-   * Yes/No response is requested.
-   *
-   * @see TS 11.14, clause 12.6, Command Qualifier, GET INKEY, bit 3.
-   *
-   * true: Yes/No response is requested, and character sets
-   *       (Alphabet set and UCS2) are disabled.
-   * false: Character sets (Alphabet set and UCS2) are enabled.
-   */
-  boolean isYesNoRequested;
-
-  /**
-   * User input in packed or unpacked format.
-   *
-   * @see TS 11.14, clause 12.6, Command Qualifier, GET INPUT, bit 4.
-   *
-   * true: User input to be in SMS packed format.
-   * false: User input to be in unpacked format.
-   */
-  boolean isPacked;
-
-  /**
-   * Help information available or not.
-   *
-   * @see TS 11.14, clause 12.6, Command Qualifier, GET INPUT/GET INKEY, bit 8.
-   *
-   * true: help information available.
-   * false: no help information available.
-   */
-  boolean isHelpAvailable;
-};
-
-dictionary MozStkBrowserSetting
-{
-  /**
-   * Confirm message to launch browser.
-   *
-   * @see MozStkTextMessage for the detail specification of
-   *      confirmMessage.
-   */
-  jsval confirmMessage;
-
-  /**
-   * The URL to be opened by browser.
-   */
-  DOMString url;
-
-  /**
-   * One of STK_BROWSER_MODE_*.
-   *
-   * @see nsIDOMMozIccManager.STK_BROWSER_MODE_*
-   */
-  unsigned short mode;
-};
-
-dictionary MozStkSetUpCall
-{
-  /**
-   * The Dialling number.
-   */
-  DOMString address;
-
-  /**
-   * The text message used in user confirmation phase.
-   *
-   * @see MozStkTextMessage for the detail specification of
-   *      confirmMessage.
-   */
-  jsval confirmMessage;
-
-  /**
-   * The text message used in call set up phase.
-   *
-   * @see MozStkTextMessage for the detail specification of
-   *      callMessage.
-   */
-  jsval callMessage;
-
-  /**
-   * The Optional maximum duration for the redial mechanism.
-   * The time elapsed since the first call set-up attempt has exceeded the duration
-   * requested by the UICC, the redial mechanism is terminated.
-   */
-  jsval duration;
-};
-
-dictionary MozStkSetUpEventList
-{
-  /**
-   * The list of events that needs to provide details to ICC when they happen.
-   * When this valus is null, means an indication to remove the existing list
-   * of events in ME.
-   *
-   * @see nsIDOMMozIccManager.STK_EVENT_TYPE_*
-   */
-   jsval eventList; // unsigned short []
-};
-
-dictionary MozStkLocationInfo
-{
-  /**
-   * Mobile Country Code (MCC) of the current serving operator.
-   */
-  unsigned short mcc;
-
-  /**
-   * Mobile Network Code (MNC) of the current serving operator.
-   */
-  unsigned short mnc;
-
-  /**
-   * Mobile Location Area Code (LAC) for the current serving operator.
-   */
-  unsigned short gsmLocationAreaCode;
-
-  /**
-   * Mobile Cell ID for the current serving operator.
-   */
-  unsigned long gsmCellId;
-};
-
-dictionary MozStkDuration
-{
-  /**
-   * Time unit used, should be one of STK_TIME_UNIT_*.
-   */
-  unsigned short timeUnit;
-
-  /**
-   * The length of time required, expressed in timeUnit.
-   */
-  octet timeInterval;
-};
-
-dictionary MozStkPlayTone
-{
-  /**
-   * Text String.
-   */
-  DOMString text;
-
-  /**
-   * One of STK_TONE_TYPE_*.
-   */
-  unsigned short tone;
-
-  /**
-   * The length of time for which the ME shall generate the tone.
-   *
-   * @see MozStkDuration
-   */
-  jsval duration;
-
-  /**
-   * Need to vibrate or not.
-   * true: vibrate alert, if available, with the tone.
-   * false: use of vibrate alert is up to the ME.
-   */
-  boolean isVibrate;
-};
-
-dictionary MozStkProvideLocalInfo
-{
-  /**
-   * Indicate which local information is required.
-   * It shall be one of following:
-   *  - nsIDOMMozIccManager.STK_LOCAL_INFO_LOCATION_INFO
-   *  - nsIDOMMozIccManager.STK_LOCAL_INFO_IMEI
-   *  - nsIDOMMozIccManager.STK_LOCAL_INFO_DATE_TIME_ZONE
-   *  - nsIDOMMozIccManager.STK_LOCAL_INFO_LANGUAGE
-   */
-  unsigned short localInfoType;
-};
-
-dictionary MozStkLocationEvent
-{
-  /**
-   * The type of this event.
-   * It shall be nsIDOMMozIccManager.STK_EVENT_TYPE_LOCATION_STATUS;
-   */
-  unsigned short eventType;
-
-  /**
-   * Indicate current service state of the MS with one of the values listed
-   * below:
-   *  - nsIDOMMozIccManager.STK_SERVICE_STATE_NORMAL
-   *  - nsIDOMMozIccManager.STK_SERVICE_STATE_LIMITED
-   *  - nsIDOMMozIccManager.STK_SERVICE_STATE_UNAVAILABLE
-   */
-  unsigned short locationStatus;
-
-  /**
-   * See MozStkLocationInfo.
-   * This value shall only be provided if the locationStatus indicates
-   * 'STK_SERVICE_STATE_NORMAL'.
-   */
-  jsval locationInfo;
-};
-
-dictionary MozStkTimer
-{
-  /**
-   * Identifier of a timer.
-   */
-  octet timerId;
-
-  /**
-   * Length of time during which the timer has to run.
-   * The resolution of a timer is 1 second.
-   */
-  unsigned long timerValue;
-
-  /**
-   * The action requested from UICC.
-   * It shall be one of below:
-   * - nsIDOMMozIccManager.STK_TIMER_START
-   * - nsIDOMMozIccManager.STK_TIMER_DEACTIVATE
-   * - nsIDOMMozIccManager.STK_TIMER_GET_CURRENT_VALUE
-   */
-  unsigned short timerAction;
-};
-
-dictionary MozStkBipMessage
-{
-  /**
-   * Text String
-   */
-  DOMString text;
-};
-
-dictionary MozStkCommand
-{
-  /**
-   * The number of command issued by ICC. And it is assigned
-   * by ICC may take any hexadecimal value betweean '01' and 'FE'.
-   *
-   * @see TS 11.14, clause 6.5.1
-   */
-  unsigned short commandNumber;
-
-  /**
-   * One of STK_CMD_*
-   */
-  unsigned short typeOfCommand;
-
-  /**
-   * Qualifiers specific to the command.
-   */
-  unsigned short commandQualifier;
-
-  /**
-   * options varies accrording to the typeOfCommand in MozStkCommand.
-   *
-   * When typeOfCommand is
-   * - STK_CMD_DISPLAY_TEXT
-   * - STK_CMD_SET_UP_IDLE_MODE_TEXT
-   * - STK_CMD_SEND_{SS|USSD|SMS|DTMF},
-   * options is MozStkTextMessage.
-   *
-   * When typeOfCommand is
-   * - STK_CMD_SELECT_ITEM
-   * - STK_CMD_SET_UP_MENU
-   * options is MozStkMenu.
-   *
-   * When typeOfCommand is
-   * - STK_CMD_GET_INKEY
-   * - STK_CMD_GET_INPUT,
-   * options is MozStkInput.
-   *
-   * When typeOfCommand is
-   * - STK_CMD_LAUNCH_BROWSER
-   * options is MozStkBrowserSetting.
-   *
-   * When typeOfCommand is
-   * - STK_CMD_SET_UP_CALL
-   * options is MozStkSetUpCall.
-   *
-   * When typeOfCommand is
-   * - STK_CMD_SET_UP_EVENT_LIST
-   * options is MozStkSetUpEventList.
-   *
-   * When typeOfCommand is
-   * - STK_CMD_PLAY_TONE
-   * options is MozStkPlayTone.
-   *
-   * When typeOfCommand is
-   * - STK_CMD_POLL_INTERVAL
-   * options is MozStkDuration.
-   *
-   * When typeOfCommand is
-   * - STK_CMD_PROVIDE_LOCAL_INFO
-   * options is MozStkProvideLocalInfo.
-   *
-   * When typeOfCommand is
-   * - STK_CMD_TIMER_MANAGEMENT
-   * option is MozStkTimer
-   *
-   * When typeOfCommand is
-   * - STK_CMD_OPEN_CHANNEL
-   * - STK_CMD_CLOSE_CHANNEL
-   * - STK_CMD_SEND_DATA
-   * - STK_CMD_RECEIVE_DATA
-   * options is MozStkBipMessage
-   *
-   * When typeOfCommand is
-   * - STK_CMD_POLL_OFF
-   * options is null.
-   *
-   * When typeOfCommand is
-   * - STK_CMD_REFRESH
-   * options is null.
-   */
-  jsval options;
-};
-
-dictionary MozStkResponse
-{
-  /**
-   * One of RESULT_*
-   */
-  unsigned short resultCode;
-
-  /**
-   * The identifier of the item selected by user.
-   *
-   * @see MozStkItem.identifier
-   */
-  unsigned short itemIdentifier;
-
-  /**
-   * User input.
-   */
-  DOMString input;
-
-  /**
-   * YES/NO response.
-   *
-   * @see MozStkInput.isYesNoRequested
-   */
-  boolean isYesNo;
-
-  /**
-   * User has confirmed or rejected the call during STK_CMD_CALL_SET_UP.
-   *
-   * @see RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM
-   *
-   * true: Confirmed by User.
-   * false: Rejected by User.
-   */
-  boolean hasConfirmed;
-
-  /**
-   * The response for STK_CMD_PROVIDE_LOCAL_INFO
-   *
-   * @see MozStkLocalInfo
-   */
-  jsval localInfo;
-
-  /**
-   * The response for STK_CMD_TIMER_MANAGEMENT.
-   * The 'timerValue' is needed if the action of STK_CMD_TIMER_MANAGEMENT is
-   * 'STK_TIMER_DEACTIVATE' or 'STK_TIMER_GET_CURRENT_VALUE'. It shall state
-   * the current value of a timer. And the resolution is 1 second.
-   *
-   * @see MozStkTimer
-   */
-  jsval timer;
-};
-
-dictionary MozStkCallEvent
-{
-  /**
-   * The type of this event.
-   * It shall be one of following:
-   *     - nsIDOMMozIccManager.STK_EVENT_TYPE_MT_CALL,
-   *     - nsIDOMMozIccManager.STK_EVENT_TYPE_CALL_CONNECTED,
-   *     - nsIDOMMozIccManager.STK_EVENT_TYPE_CALL_DISCONNECTED.
-   */
-  unsigned short eventType;
-
-  /**
-   * Remote party number.
-   */
-  DOMString number;
-
-  /**
-   * This field is available in 'STK_EVENT_TYPE_CALL_CONNECTED' and
-   * 'STK_EVENT_TYPE_CALL_DISCONNECTED' events.
-   * For the STK_EVENT_TYPE_CALL_CONNECTED event, setting this to true means the
-   * connection is answered by remote end, that is, this is an outgoing call.
-   * For the STK_EVENT_TYPE_CALL_DISCONNECTED event, setting this to true
-   * indicates the connection is hung up by remote.
-   */
-  boolean isIssuedByRemote;
-
-  /**
-   * This field is available in Call Disconnected event to indicate the cause
-   * of disconnection. The cause string is passed to gaia through the error
-   * listener of nsIDOMCallEvent. Null if there's no error.
-   */
-  DOMString error;
-};
-
-dictionary MozStkLocalInfo
-{
-  /**
-   * IMEI information
-   */
-  DOMString imei;
-
-  /**
-   * Location Information
-   *
-   * @see MozStkLocationInfo.
-   */
-  jsval locationInfo;
-
-  /**
-   * Date information
-   *
-   * @see Date
-   */
-  jsval date;
-
-  /**
-   * Language Information
-   *
-   * @see ISO 639-1, Alpha-2 code
-   */
-  DOMString language;
-};
-
-dictionary MozStkLanguageSelectionEvent
-{
-  /**
-   * The type of this event.
-   * It shall be nsIDOMMozIccManager.STK_EVENT_TYPE_LANGUAGE_SELECTION.
-   */
-  unsigned short eventType;
-
-  /**
-   * Language Information
-   *
-   * @see ISO 639-1, Alpha-2 code
-   *      "de" for German, "en" for English, "zh" for Chinese, etc.
-   */
-  DOMString language;
-};
-
-dictionary MozStkBrowserTerminationEvent
-{
-  /**
-   * The type of this event.
-   * It shall be nsIDOMMozIccManager.STK_EVENT_TYPE_BROWSER_TERMINATION
-   */
-  unsigned short eventType;
-
-  /**
-   * This object shall contain the browser termination cause.
-   * See TZ 102 223 8.51. It shall be one of following:
-   * - nsIDOMMozIccManager.STK_BROWSER_TERMINATION_CAUSE_USER
-   * - nsIDOMMozIccManager.STK_BROWSER_TERMINATION_CAUSE_ERROR
-   */
-  unsigned short terminationCause;
-};
-
-dictionary MozStkGeneralEvent
-{
-  /**
-   * The type of this event, MozStkGeneralEvent can be used for all Stk Event
-   * requires no more parameter than event type, including
-   * nsIDOMMozIccManager.STK_EVENT_TYPE_USER_ACTIVITY.
-   * nsIDOMMozIccManager.STK_EVENT_TYPE_IDLE_SCREEN_AVAILABLE.
-   * HCI Connectivity Event(Not defined in interface yet).
-   */
-  unsigned short eventType;
-};
--- a/dom/icc/interfaces/moz.build
+++ b/dom/icc/interfaces/moz.build
@@ -3,12 +3,11 @@
 # 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 += [
     'nsIDOMIccInfo.idl',
     'nsIDOMIccManager.idl',
     'nsIIccProvider.idl',
-    'SimToolKit.idl',
 ]
 
 XPIDL_MODULE = 'dom_icc'
--- a/dom/indexedDB/IDBDatabase.cpp
+++ b/dom/indexedDB/IDBDatabase.cpp
@@ -3,17 +3,16 @@
 /* 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 "base/basictypes.h"
 
 #include "IDBDatabase.h"
 
-#include "DictionaryHelpers.h"
 #include "mozilla/Mutex.h"
 #include "mozilla/storage.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/DOMStringList.h"
 #include "mozilla/dom/DOMStringListBinding.h"
 #include "mozilla/dom/quota/Client.h"
 #include "mozilla/dom/quota/QuotaManager.h"
 #include "nsJSUtils.h"
--- a/dom/indexedDB/IDBObjectStore.cpp
+++ b/dom/indexedDB/IDBObjectStore.cpp
@@ -34,17 +34,16 @@
 #include "AsyncConnectionHelper.h"
 #include "IDBCursor.h"
 #include "IDBEvents.h"
 #include "IDBFileHandle.h"
 #include "IDBIndex.h"
 #include "IDBKeyRange.h"
 #include "IDBTransaction.h"
 #include "DatabaseInfo.h"
-#include "DictionaryHelpers.h"
 #include "KeyPath.h"
 #include "ProfilerHelpers.h"
 #include "ReportInternalError.h"
 
 #include "ipc/IndexedDBChild.h"
 #include "ipc/IndexedDBParent.h"
 
 #include "IndexedDatabaseInlines.h"
--- a/dom/interfaces/apps/nsIDOMMozApplicationEvent.idl
+++ b/dom/interfaces/apps/nsIDOMMozApplicationEvent.idl
@@ -11,13 +11,8 @@ interface nsIDOMMozApplicationEvent : ns
 {
   readonly attribute mozIDOMApplication application;
 
   [noscript] void initMozApplicationEvent(in DOMString aType,
                                           in boolean aCanBubble,
                                           in boolean aCancelable,
                                           in mozIDOMApplication aApplication);
 };
-
-dictionary MozApplicationEventInit : EventInit
-{
-  mozIDOMApplication application;
-};
--- a/dom/interfaces/devicestorage/nsIDOMDeviceStorageChangeEvent.idl
+++ b/dom/interfaces/devicestorage/nsIDOMDeviceStorageChangeEvent.idl
@@ -13,14 +13,8 @@ interface nsIDOMDeviceStorageChangeEvent
                                                in boolean canBubbleArg,
                                                in boolean cancelableArg,
                                                in DOMString path,
                                                in DOMString reason);
   
   readonly attribute DOMString path;
   readonly attribute DOMString reason;
 };
-
-dictionary DeviceStorageChangeEventInit : EventInit
-{
-  DOMString path;
-  DOMString reason;
-};
--- a/dom/interfaces/events/nsIDOMCloseEvent.idl
+++ b/dom/interfaces/events/nsIDOMCloseEvent.idl
@@ -21,15 +21,8 @@ interface nsIDOMCloseEvent : nsIDOMEvent
 
   void initCloseEvent(in DOMString aType,
                       in boolean aCanBubble,
                       in boolean aCancelable,
                       in boolean aWasClean,
                       in unsigned short aReasonCode,
                       in DOMString aReason);
 };
-
-dictionary CloseEventInit : EventInit
-{
-  boolean wasClean;
-  unsigned short code;
-  DOMString reason;
-};
--- a/dom/interfaces/events/nsIDOMCustomEvent.idl
+++ b/dom/interfaces/events/nsIDOMCustomEvent.idl
@@ -12,13 +12,8 @@ interface nsIDOMCustomEvent : nsIDOMEven
 
   readonly attribute nsIVariant detail;
 
   void initCustomEvent(in DOMString  typeArg, 
                        in boolean    canBubbleArg, 
                        in boolean    cancelableArg, 
                        in nsIVariant detailArg);
 };
-
-dictionary CustomEventInit : EventInit
-{
-  nsIVariant detail;
-};
--- a/dom/interfaces/events/nsIDOMDOMTransactionEvent.idl
+++ b/dom/interfaces/events/nsIDOMDOMTransactionEvent.idl
@@ -12,14 +12,8 @@ interface nsIDOMDOMTransactionEvent : ns
 {
   readonly attribute nsIVariant transactions;
 
   void initDOMTransactionEvent(in DOMString typeArg,
                                in boolean canBubbleArg,
                                in boolean canCancelArg,
                                in nsIVariant transactions);
 };
-
-dictionary DOMTransactionEventInit : EventInit
-{
-  nsIVariant transactions;
-};
-
--- a/dom/interfaces/events/nsIDOMDeviceOrientationEvent.idl
+++ b/dom/interfaces/events/nsIDOMDeviceOrientationEvent.idl
@@ -35,16 +35,8 @@ interface nsIDOMDeviceOrientationEvent :
    *    rolling an aircraft); gamma is in [-90,90).
    */
 
   readonly attribute double alpha;
   readonly attribute double beta;
   readonly attribute double gamma;
   readonly attribute boolean absolute;
 };
-
-dictionary DeviceOrientationEventInit : EventInit
-{
-  double alpha;
-  double beta;
-  double gamma;
-  boolean absolute;
-};
--- a/dom/interfaces/events/nsIDOMElementReplaceEvent.idl
+++ b/dom/interfaces/events/nsIDOMElementReplaceEvent.idl
@@ -12,13 +12,8 @@ interface nsIDOMElementReplaceEvent : ns
 {
   readonly attribute nsIDOMElement upgrade;
 
   void initElementReplaceEvent(in DOMString typeArg,
                                in boolean canBubbleArg,
                                in boolean canCancelArg,
                                in nsIDOMElement upgrade);
 };
-
-dictionary ElementReplaceEventInit : EventInit
-{
-  nsIDOMElement upgrade;
-};
--- a/dom/interfaces/events/nsIDOMEvent.idl
+++ b/dom/interfaces/events/nsIDOMEvent.idl
@@ -210,22 +210,16 @@ interface nsIDOMEvent : nsISupports
   [noscript,notxpcom] void SetTrusted(in boolean aTrusted);
   [notxpcom] void Serialize(in IPCMessagePtr aMsg,
                             in boolean aSerializeInterfaceType);
   [notxpcom] boolean Deserialize(in ConstIPCMessagePtr aMsg, out voidPtr aIter);
   [noscript,notxpcom] void SetOwner(in EventTargetPtr aOwner);
   [notxpcom] DOMEventPtr InternalDOMEvent();
 };
 
-dictionary EventInit
-{
-  boolean bubbles;
-  boolean cancelable;
-};
-
 %{C++
 
 nsresult
 NS_NewDOMEvent(nsIDOMEvent** aInstancePtrResult,
                mozilla::dom::EventTarget* aOwner,
                nsPresContext* aPresContext,
                mozilla::WidgetEvent* aEvent);
 nsresult
--- a/dom/interfaces/events/nsIDOMHashChangeEvent.idl
+++ b/dom/interfaces/events/nsIDOMHashChangeEvent.idl
@@ -12,14 +12,8 @@ interface nsIDOMHashChangeEvent : nsIDOM
   readonly attribute DOMString newURL;
 
   void initHashChangeEvent(in DOMString typeArg,
                            in boolean canBubbleArg,
                            in boolean cancelableArg,
                            in DOMString oldURLArg,
                            in DOMString newURLArg);
 };
-
-dictionary HashChangeEventInit : EventInit
-{
-  DOMString oldURL;
-  DOMString newURL;
-};
--- a/dom/interfaces/events/nsIDOMPageTransitionEvent.idl
+++ b/dom/interfaces/events/nsIDOMPageTransitionEvent.idl
@@ -22,13 +22,8 @@ interface nsIDOMPageTransitionEvent : ns
   readonly attribute boolean persisted;
 
   /* Initialize a new pageshow or pagehide event. */
   void initPageTransitionEvent(in DOMString typeArg,
                                in boolean canBubbleArg,
                                in boolean canCancelArg,
                                in boolean persisted);
 };
-
-dictionary PageTransitionEventInit : EventInit
-{
-  boolean persisted;
-};
--- a/dom/interfaces/events/nsIDOMPopStateEvent.idl
+++ b/dom/interfaces/events/nsIDOMPopStateEvent.idl
@@ -15,13 +15,8 @@ interface nsIDOMPopStateEvent : nsIDOMEv
    */
   readonly attribute nsIVariant state;
 
   void initPopStateEvent(in DOMString typeArg,
                          in boolean canBubbleArg,
                          in boolean cancelableArg,
                          in nsIVariant stateArg);
 };
-
-dictionary PopStateEventInit : EventInit
-{
-  nsIVariant state;
-};
--- a/dom/interfaces/events/nsIDOMPopupBlockedEvent.idl
+++ b/dom/interfaces/events/nsIDOMPopupBlockedEvent.idl
@@ -42,16 +42,8 @@ interface nsIDOMPopupBlockedEvent : nsID
   void initPopupBlockedEvent(in DOMString typeArg,
                              in boolean canBubbleArg,
                              in boolean cancelableArg,
                              in nsIDOMWindow requestingWindow,
                              in nsIURI popupWindowURI,
                              in DOMString popupWindowName,
                              in DOMString popupWindowFeatures);
 };
-
-dictionary PopupBlockedEventInit : EventInit
-{
-  nsIDOMWindow requestingWindow;
-  nsIURI popupWindowURI;
-  DOMString popupWindowFeatures;
-  DOMString popupWindowName;
-};
--- a/dom/interfaces/events/nsIDOMProgressEvent.idl
+++ b/dom/interfaces/events/nsIDOMProgressEvent.idl
@@ -19,14 +19,8 @@ interface nsIDOMProgressEvent : nsIDOMEv
   [noscript]
   void initProgressEvent(in DOMString typeArg,
                          in boolean canBubbleArg,
                          in boolean cancelableArg,
                          in boolean lengthComputableArg,
                          in unsigned long long loadedArg,
                          in unsigned long long totalArg);
 };
-
-dictionary ProgressEventInit : EventInit {
-  boolean lengthComputable;
-  unsigned long long loaded;
-  unsigned long long total;
-};
--- a/dom/interfaces/events/nsIDOMRecordErrorEvent.idl
+++ b/dom/interfaces/events/nsIDOMRecordErrorEvent.idl
@@ -20,12 +20,8 @@ interface nsIDOMRecordErrorEvent : nsIDO
   readonly attribute DOMString name;
 
   [noscript]
   void initRecordErrorEvent(in DOMString aType,
                             in boolean aCanBubble,
                             in boolean aCancelable,
                             in DOMString aName);
 };
-
-dictionary RecordErrorEventInit : EventInit {
-  DOMString name;
-};
--- a/dom/interfaces/events/nsIDOMSmartCardEvent.idl
+++ b/dom/interfaces/events/nsIDOMSmartCardEvent.idl
@@ -14,14 +14,8 @@
 interface nsIDOMSmartCardEvent : nsIDOMEvent
 {
   readonly attribute DOMString   tokenName;
   [noscript] void initSmartCardEvent(in DOMString aTypeArg,
                                      in boolean aCanBubbleArg,
                                      in boolean aCancelableArg,
                                      in DOMString aTokenNAme);
 };
-
-dictionary SmartCardEventInit : EventInit
-{
-  DOMString tokenName;
-};
-
--- a/dom/interfaces/events/nsIDOMStyleRuleChangeEvent.idl
+++ b/dom/interfaces/events/nsIDOMStyleRuleChangeEvent.idl
@@ -14,15 +14,8 @@ interface nsIDOMStyleRuleChangeEvent : n
   readonly attribute nsIDOMCSSStyleSheet stylesheet;
   readonly attribute nsIDOMCSSRule rule;
   [noscript] void initStyleRuleChangeEvent(in DOMString aTypeArg,
                                            in boolean aCanBubbleArg,
                                            in boolean aCancelableArg,
                                            in nsIDOMCSSStyleSheet aStyleSheet,
                                            in nsIDOMCSSRule aRule);
 };
-
-dictionary StyleRuleChangeEventInit : EventInit
-{
-  nsIDOMCSSStyleSheet stylesheet;
-  nsIDOMCSSRule rule;
-};
-
--- a/dom/interfaces/events/nsIDOMStyleSheetApplicableStateChangeEvent.idl
+++ b/dom/interfaces/events/nsIDOMStyleSheetApplicableStateChangeEvent.idl
@@ -13,15 +13,8 @@ interface nsIDOMStyleSheetApplicableStat
   readonly attribute nsIDOMCSSStyleSheet stylesheet;
   readonly attribute boolean applicable;
   [noscript] void initStyleSheetApplicableStateChangeEvent(in DOMString aTypeArg,
                                                            in boolean aCanBubbleArg,
                                                            in boolean aCancelableArg,
                                                            in nsIDOMCSSStyleSheet aStyleSheet,
                                                            in boolean aApplicable);
 };
-
-dictionary StyleSheetApplicableStateChangeEventInit : EventInit
-{
-  nsIDOMCSSStyleSheet stylesheet;
-  boolean applicable;
-};
-
--- a/dom/interfaces/events/nsIDOMStyleSheetChangeEvent.idl
+++ b/dom/interfaces/events/nsIDOMStyleSheetChangeEvent.idl
@@ -13,15 +13,8 @@ interface nsIDOMStyleSheetChangeEvent : 
   readonly attribute nsIDOMCSSStyleSheet stylesheet;
   readonly attribute boolean documentSheet;
   [noscript] void initStyleSheetChangeEvent(in DOMString aTypeArg,
                                             in boolean aCanBubbleArg,
                                             in boolean aCancelableArg,
                                             in nsIDOMCSSStyleSheet aStyleSheet,
                                             in boolean aDocumentSheet);
 };
-
-dictionary StyleSheetChangeEventInit : EventInit
-{
-  nsIDOMCSSStyleSheet stylesheet;
-  boolean documentSheet;
-};
-
--- a/dom/interfaces/settings/nsIDOMMozSettingsEvent.idl
+++ b/dom/interfaces/settings/nsIDOMMozSettingsEvent.idl
@@ -12,14 +12,8 @@ interface nsIDOMMozSettingsEvent : nsIDO
   readonly attribute nsIVariant settingValue;
 
   [noscript] void initMozSettingsEvent(in DOMString aType,
                                        in boolean aCanBubble,
                                        in boolean aCancelable,
                                        in DOMString aSettingName,
                                        in nsIVariant aSettingValue);
 };
-
-dictionary MozSettingsEventInit : EventInit
-{
-  DOMString  settingName;
-  nsIVariant settingValue;
-};
--- a/dom/interfaces/storage/nsIDOMStorageEvent.idl
+++ b/dom/interfaces/storage/nsIDOMStorageEvent.idl
@@ -57,17 +57,8 @@ interface nsIDOMStorageEvent : nsIDOMEve
                         in boolean canBubbleArg, 
                         in boolean cancelableArg, 
                         in DOMString keyArg,
                         in DOMString oldValueArg,
                         in DOMString newValueArg,
                         in DOMString urlArg,
                         in nsIDOMStorage storageAreaArg);
 };
-
-dictionary StorageEventInit : EventInit
-{
-  DOMString? key;
-  DOMString? oldValue;
-  DOMString? newValue;
-  DOMString url;
-  nsIDOMStorage storageArea;
-};
--- a/dom/mobileconnection/interfaces/nsIDOMMobileConnection.idl
+++ b/dom/mobileconnection/interfaces/nsIDOMMobileConnection.idl
@@ -691,87 +691,8 @@ interface nsIDOMMozMobileCFInfo : nsISup
   readonly attribute unsigned short timeSeconds;
 
   /**
    * Service for which the call forward is set up. It should be one of the
    * nsIDOMMozMobileConnection.ICC_SERVICE_CLASS_* values.
    */
   readonly attribute unsigned short serviceClass;
 };
-
-
-dictionary MozCallBarringOption
-{
-  /**
-   * Indicates the program the call is being barred.
-   *
-   * It shall be one of the nsIDOMMozMobileConnection.CALL_BARRING_PROGRAM_*
-   * values.
-   */
-   unsigned short program;
-
-  /**
-   * Enable or disable the call barring program.
-   */
-  boolean enabled;
-
-  /**
-   * Barring password. Use "" if no password specified.
-   */
-  DOMString password;
-
-  /**
-   * Service for which the call barring is set up.
-   *
-   * It shall be one of the nsIDOMMozMobileConnection.ICC_SERVICE_CLASS_*
-   * values.
-   */
-  unsigned short serviceClass;
-};
-
-dictionary DOMMMIResult
-{
-  /**
-   * String key that identifies the service associated with the MMI code
-   * request. The UI is supposed to handle the localization of the strings
-   * associated with this string key.
-   */
-  DOMString serviceCode;
-
-  /**
-   * String key containing the status message of the associated MMI request.
-   * The UI is supposed to handle the localization of the strings associated
-   * with this string key.
-   */
-  DOMString statusMessage;
-
-  /**
-   * Some MMI requests like call forwarding or PIN/PIN2/PUK/PUK2 related
-   * requests provide extra information along with the status message, this
-   * information can be a number, a string key or an array of string keys.
-   */
-  jsval additionalInformation;
-};
-
-dictionary DOMCLIRStatus
-{
-  /**
-   * CLIR parameter 'n': parameter sets the adjustment for outgoing calls.
-   *
-   * 0 Presentation indicator is used according to the subscription of the
-   *   CLIR service (uses subscription default value).
-   * 1 CLIR invocation (restricts CLI presentation).
-   * 2 CLIR suppression (allows CLI presentation).
-   */
-  unsigned short n;
-
-  /**
-   * CLIR parameter 'm': parameter shows the subscriber CLIR service status in
-   *                     the network.
-   * 0 CLIR not provisioned.
-   * 1 CLIR provisioned in permanent mode.
-   * 2 unknown (e.g. no network, etc.).
-   * 3 CLIR temporary mode presentation restricted.
-   *
-   * @see 3GPP TS 27.007 7.7 Defined values
-   */
-  unsigned short m;
-};
--- a/dom/mobilemessage/interfaces/nsIDOMMozMmsEvent.idl
+++ b/dom/mobilemessage/interfaces/nsIDOMMozMmsEvent.idl
@@ -11,13 +11,8 @@ interface nsIDOMMozMmsEvent : nsIDOMEven
 {
   readonly attribute nsIDOMMozMmsMessage message;
 
   [noscript] void initMozMmsEvent(in DOMString aType,
                                   in boolean aCanBubble,
                                   in boolean aCancelable,
                                   in nsIDOMMozMmsMessage aMessage);
 };
-
-dictionary MozMmsEventInit : EventInit
-{
-  nsIDOMMozMmsMessage message;
-};
--- a/dom/mobilemessage/interfaces/nsIDOMMozMmsMessage.idl
+++ b/dom/mobilemessage/interfaces/nsIDOMMozMmsMessage.idl
@@ -2,36 +2,16 @@
  * 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;
 
-// If this is changed, change the WebIDL dictionary as well.
-dictionary MmsAttachment
-{
-  DOMString? id;
-  DOMString? location;
-  nsIDOMBlob content; // If the content blob is a text/plain type, the encoding
-                      // for text should always be "utf-8".
-};
-
-dictionary MmsDeliveryInfo
-{
-  DOMString? receiver;
-  DOMString? deliveryStatus;
-  DOMTimeStamp deliveryTimestamp; // 0 if not available (e.g.,
-                                  // |delivery| = "received" or not yet delivered).
-  DOMString? readStatus;
-  DOMTimeStamp readTimestamp; // 0 if not available (e.g.,
-                              // |delivery| = "received" or not yet read).
-};
-
 [scriptable, builtinclass, uuid(f41d7400-0026-11e3-829d-eb7459c03810)]
 interface nsIDOMMozMmsMessage : nsISupports
 {
   /**
    * |type| is always "mms".
    */
   readonly attribute DOMString type;
 
--- a/dom/mobilemessage/interfaces/nsIDOMMozSmsEvent.idl
+++ b/dom/mobilemessage/interfaces/nsIDOMMozSmsEvent.idl
@@ -11,13 +11,8 @@ interface nsIDOMMozSmsEvent : nsIDOMEven
 {
   readonly attribute nsIDOMMozSmsMessage message;
 
   [noscript] void initMozSmsEvent(in DOMString aType,
                                   in boolean aCanBubble,
                                   in boolean aCancelable,
                                   in nsIDOMMozSmsMessage aMessage);
 };
-
-dictionary MozSmsEventInit : EventInit
-{
-  nsIDOMMozSmsMessage message;
-};
--- a/dom/mobilemessage/interfaces/nsIMobileMessageCallback.idl
+++ b/dom/mobilemessage/interfaces/nsIMobileMessageCallback.idl
@@ -1,24 +1,15 @@
 /* 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"
 #include "nsIDOMSmsSegmentInfo.idl"
 
-dictionary SmsThreadListItem
-{
-  unsigned long long id;
-  DOMString senderOrReceiver;
-  unsigned long long timestamp;
-  DOMString body;
-  unsigned long long unreadCount;
-};
-
 [scriptable, uuid(46cf221e-9886-11e3-8039-171af7a2299e)]
 interface nsIMobileMessageCallback : nsISupports
 {
   /**
    * All SMS related errors.
    * Make sure to keep this list in sync with the list in:
    * embedding/android/GeckoSmsManager.java
    */
--- a/dom/mobilemessage/src/MmsMessage.cpp
+++ b/dom/mobilemessage/src/MmsMessage.cpp
@@ -13,17 +13,16 @@
 #include "nsTArrayHelpers.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/mobilemessage/Constants.h" // For MessageType
 #include "mozilla/dom/mobilemessage/SmsTypes.h"
 #include "nsDOMFile.h"
 #include "nsCxPusher.h"
 #include "MessageUtils.h"
 
-using namespace mozilla::idl;
 using namespace mozilla::dom::mobilemessage;
 
 DOMCI_DATA(MozMmsMessage, mozilla::dom::MmsMessage)
 
 namespace mozilla {
 namespace dom {
 
 NS_INTERFACE_MAP_BEGIN(MmsMessage)
@@ -42,17 +41,17 @@ MmsMessage::MmsMessage(int32_t          
                        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,
+                       const nsTArray<Attachment>&      aAttachments,
                        uint64_t                         aExpiryDate,
                        bool                             aReadReportRequested)
   : mId(aId),
     mThreadId(aThreadId),
     mIccId(aIccId),
     mDelivery(aDelivery),
     mDeliveryInfo(aDeliveryInfo),
     mSender(aSender),
@@ -83,38 +82,38 @@ MmsMessage::MmsMessage(const mobilemessa
   , 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.id = element.id();
-    att.location = element.location();
+    att.mId = element.id();
+    att.mLocation = element.location();
     if (element.contentParent()) {
-      att.content = static_cast<BlobParent*>(element.contentParent())->GetBlob();
+      att.mContent = static_cast<BlobParent*>(element.contentParent())->GetBlob();
     } else if (element.contentChild()) {
-      att.content = static_cast<BlobChild*>(element.contentChild())->GetBlob();
+      att.mContent = static_cast<BlobChild*>(element.contentChild())->GetBlob();
     } 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.receiver|.
-    info.receiver = infoData.receiver();
+    // Prepare |info.mReceiver|.
+    info.mReceiver = infoData.receiver();
 
-    // Prepare |info.deliveryStatus|.
+    // 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;
@@ -129,22 +128,22 @@ MmsMessage::MmsMessage(const mobilemessa
         break;
       case eDeliveryStatus_Manual:
         statusStr = DELIVERY_STATUS_MANUAL;
         break;
       case eDeliveryStatus_EndGuard:
       default:
         MOZ_CRASH("We shouldn't get any other delivery status!");
     }
-    info.deliveryStatus = statusStr;
+    info.mDeliveryStatus = statusStr;
 
-    // Prepare |info.deliveryTimestamp|.
-    info.deliveryTimestamp = infoData.deliveryTimestamp();
+    // Prepare |info.mDeliveryTimestamp|.
+    info.mDeliveryTimestamp = infoData.deliveryTimestamp();
 
-    // Prepare |info.readStatus|.
+    // 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;
@@ -153,20 +152,20 @@ MmsMessage::MmsMessage(const mobilemessa
         break;
       case eReadStatus_Error:
         statusReadString = READ_STATUS_ERROR;
         break;
       case eReadStatus_EndGuard:
       default:
         MOZ_CRASH("We shouldn't get any other read status!");
     }
-    info.readStatus = statusReadString;
+    info.mReadStatus = statusReadString;
 
-    // Prepare |info.readTimestamp|.
-    info.readTimestamp = infoData.readTimestamp();
+    // Prepare |info.mReadTimestamp|.
+    info.mReadTimestamp = infoData.readTimestamp();
 
     mDeliveryInfo.AppendElement(info);
   }
 }
 
 /* static */ nsresult
 MmsMessage::Create(int32_t               aId,
                    uint64_t              aThreadId,
@@ -220,18 +219,19 @@ MmsMessage::Create(int32_t              
   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;
-    nsresult rv = info.Init(aCx, infoJsVal.address());
-    NS_ENSURE_SUCCESS(rv, rv);
+    if (!info.Init(aCx, infoJsVal)) {
+      return NS_ERROR_TYPE_ERR;
+    }
 
     deliveryInfo.AppendElement(info);
   }
 
   // Set |receivers|.
   if (!aReceivers.isObject()) {
     return NS_ERROR_INVALID_ARG;
   }
@@ -269,28 +269,29 @@ MmsMessage::Create(int32_t              
   if (!aAttachments.isObject()) {
     return NS_ERROR_INVALID_ARG;
   }
   JS::Rooted<JSObject*> attachmentsObj(aCx, &aAttachments.toObject());
   if (!JS_IsArrayObject(aCx, attachmentsObj)) {
     return NS_ERROR_INVALID_ARG;
   }
 
-  nsTArray<MmsAttachment> attachments;
+  nsTArray<Attachment> 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;
-    rv = attachment.Init(aCx, attachmentJsVal.address());
-    NS_ENSURE_SUCCESS(rv, rv);
+    if (!attachment.Init(aCx, attachmentJsVal)) {
+      return NS_ERROR_TYPE_ERR;
+    }
 
     attachments.AppendElement(attachment);
   }
 
   // Set |expiryDate|.
   uint64_t expiryDate;
   rv = convertTimeToInt(aCx, aExpiryDate, expiryDate);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -334,66 +335,66 @@ MmsMessage::GetData(ContentParent* aPare
   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.receiver|.
-    infoData.receiver().Assign(info.receiver);
+    // Prepare |infoData.mReceiver|.
+    infoData.receiver().Assign(info.mReceiver);
 
-    // Prepare |infoData.deliveryStatus|.
+    // Prepare |infoData.mDeliveryStatus|.
     DeliveryStatus status;
-    if (info.deliveryStatus.Equals(DELIVERY_STATUS_NOT_APPLICABLE)) {
+    if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_NOT_APPLICABLE)) {
       status = eDeliveryStatus_NotApplicable;
-    } else if (info.deliveryStatus.Equals(DELIVERY_STATUS_SUCCESS)) {
+    } else if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_SUCCESS)) {
       status = eDeliveryStatus_Success;
-    } else if (info.deliveryStatus.Equals(DELIVERY_STATUS_PENDING)) {
+    } else if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_PENDING)) {
       status = eDeliveryStatus_Pending;
-    } else if (info.deliveryStatus.Equals(DELIVERY_STATUS_ERROR)) {
+    } else if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_ERROR)) {
       status = eDeliveryStatus_Error;
-    } else if (info.deliveryStatus.Equals(DELIVERY_STATUS_REJECTED)) {
+    } else if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_REJECTED)) {
       status = eDeliveryStatus_Reject;
-    } else if (info.deliveryStatus.Equals(DELIVERY_STATUS_MANUAL)) {
+    } else if (info.mDeliveryStatus.Equals(DELIVERY_STATUS_MANUAL)) {
       status = eDeliveryStatus_Manual;
     } else {
       return false;
     }
     infoData.deliveryStatus() = status;
 
-    // Prepare |infoData.deliveryTimestamp|.
-    infoData.deliveryTimestamp() = info.deliveryTimestamp;
+    // Prepare |infoData.mDeliveryTimestamp|.
+    infoData.deliveryTimestamp() = info.mDeliveryTimestamp;
 
-    // Prepare |infoData.readStatus|.
+    // Prepare |infoData.mReadStatus|.
     ReadStatus readStatus;
-    if (info.readStatus.Equals(READ_STATUS_NOT_APPLICABLE)) {
+    if (info.mReadStatus.Equals(READ_STATUS_NOT_APPLICABLE)) {
       readStatus = eReadStatus_NotApplicable;
-    } else if (info.readStatus.Equals(READ_STATUS_SUCCESS)) {
+    } else if (info.mReadStatus.Equals(READ_STATUS_SUCCESS)) {
       readStatus = eReadStatus_Success;
-    } else if (info.readStatus.Equals(READ_STATUS_PENDING)) {
+    } else if (info.mReadStatus.Equals(READ_STATUS_PENDING)) {
       readStatus = eReadStatus_Pending;
-    } else if (info.readStatus.Equals(READ_STATUS_ERROR)) {
+    } else if (info.mReadStatus.Equals(READ_STATUS_ERROR)) {
       readStatus = eReadStatus_Error;
     } else {
       return false;
     }
     infoData.readStatus() = readStatus;
 
-    // Prepare |infoData.readTimestamp|.
-    infoData.readTimestamp() = info.readTimestamp;
+    // 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];
+    const Attachment &element = mAttachments[i];
     mma.id().Assign(element.id);
     mma.location().Assign(element.location);
 
     // 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.
     nsDOMFileBase* file = static_cast<nsDOMFileBase*>(element.content.get());
@@ -491,61 +492,61 @@ MmsMessage::GetDeliveryInfo(JSContext* a
 
     JS::Rooted<JSObject*> infoJsObj(
       aCx, JS_NewObject(aCx, nullptr, JS::NullPtr(), JS::NullPtr()));
     NS_ENSURE_TRUE(infoJsObj, NS_ERROR_OUT_OF_MEMORY);
 
     JS::Rooted<JS::Value> tmpJsVal(aCx);
     JSString* tmpJsStr;
 
-    // Get |info.receiver|.
+    // Get |info.mReceiver|.
     tmpJsStr = JS_NewUCStringCopyN(aCx,
-                                   info.receiver.get(),
-                                   info.receiver.Length());
+                                   info.mReceiver.get(),
+                                   info.mReceiver.Length());
     NS_ENSURE_TRUE(tmpJsStr, NS_ERROR_OUT_OF_MEMORY);
 
     tmpJsVal.setString(tmpJsStr);
     if (!JS_DefineProperty(aCx, infoJsObj, "receiver", tmpJsVal,
                            nullptr, nullptr, JSPROP_ENUMERATE)) {
       return NS_ERROR_FAILURE;
     }
 
-    // Get |info.deliveryStatus|.
+    // Get |info.mDeliveryStatus|.
     tmpJsStr = JS_NewUCStringCopyN(aCx,
-                                   info.deliveryStatus.get(),
-                                   info.deliveryStatus.Length());
+                                   info.mDeliveryStatus.get(),
+                                   info.mDeliveryStatus.Length());
     NS_ENSURE_TRUE(tmpJsStr, NS_ERROR_OUT_OF_MEMORY);
 
     tmpJsVal.setString(tmpJsStr);
     if (!JS_DefineProperty(aCx, infoJsObj, "deliveryStatus", tmpJsVal,
                            nullptr, nullptr, JSPROP_ENUMERATE)) {
       return NS_ERROR_FAILURE;
     }
 
-    // Get |info.deliveryTimestamp|.
-    tmpJsVal.setNumber(static_cast<double>(info.deliveryTimestamp));
+    // Get |info.mDeliveryTimestamp|.
+    tmpJsVal.setNumber(static_cast<double>(info.mDeliveryTimestamp));
     if (!JS_DefineProperty(aCx, infoJsObj, "deliveryTimestamp", tmpJsVal,
                            nullptr, nullptr, JSPROP_ENUMERATE)) {
       return NS_ERROR_FAILURE;
     }
 
-    // Get |info.readStatus|.
+    // Get |info.mReadStatus|.
     tmpJsStr = JS_NewUCStringCopyN(aCx,
-                                   info.readStatus.get(),
-                                   info.readStatus.Length());
+                                   info.mReadStatus.get(),
+                                   info.mReadStatus.Length());
     NS_ENSURE_TRUE(tmpJsStr, NS_ERROR_OUT_OF_MEMORY);
 
     tmpJsVal.setString(tmpJsStr);
     if (!JS_DefineProperty(aCx, infoJsObj, "readStatus", tmpJsVal,
                            nullptr, nullptr, JSPROP_ENUMERATE)) {
       return NS_ERROR_FAILURE;
     }
 
-    // Get |info.readTimestamp|.
-    tmpJsVal.setNumber(static_cast<double>(info.readTimestamp));
+    // Get |info.mReadTimestamp|.
+    tmpJsVal.setNumber(static_cast<double>(info.mReadTimestamp));
     if (!JS_DefineProperty(aCx, infoJsObj, "readTimestamp", tmpJsVal,
                            nullptr, nullptr, JSPROP_ENUMERATE)) {
       return NS_ERROR_FAILURE;
     }
 
     if (!JS_SetElement(aCx, deliveryInfo, i, infoJsObj)) {
       return NS_ERROR_FAILURE;
     }
@@ -613,17 +614,17 @@ MmsMessage::GetAttachments(JSContext* aC
 {
   uint32_t length = mAttachments.Length();
 
   JS::Rooted<JSObject*> attachments(
     aCx, JS_NewArrayObject(aCx, length));
   NS_ENSURE_TRUE(attachments, NS_ERROR_OUT_OF_MEMORY);
 
   for (uint32_t i = 0; i < length; ++i) {
-    const MmsAttachment &attachment = mAttachments[i];
+    const Attachment &attachment = mAttachments[i];
 
     JS::Rooted<JSObject*> attachmentObj(
       aCx, JS_NewObject(aCx, nullptr, JS::NullPtr(), JS::NullPtr()));
     NS_ENSURE_TRUE(attachmentObj, NS_ERROR_OUT_OF_MEMORY);
 
     JS::Rooted<JS::Value> tmpJsVal(aCx);
     JSString* tmpJsStr;
 
--- a/dom/mobilemessage/src/MmsMessage.h
+++ b/dom/mobilemessage/src/MmsMessage.h
@@ -4,47 +4,61 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_mobilemessage_MmsMessage_h
 #define mozilla_dom_mobilemessage_MmsMessage_h
 
 #include "nsIDOMMozMmsMessage.h"
 #include "nsString.h"
 #include "mozilla/dom/mobilemessage/Types.h"
+#include "mozilla/dom/MozMmsMessageBinding.h"
 #include "mozilla/Attributes.h"
-#include "DictionaryHelpers.h"
 
 namespace mozilla {
 namespace dom {
 
 namespace mobilemessage {
 class MmsMessageData;
 } // namespace mobilemessage
 
 class ContentParent;
 
 class MmsMessage MOZ_FINAL : public nsIDOMMozMmsMessage
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMMOZMMSMESSAGE
 
+  // If this is changed, change the WebIDL dictionary as well.
+  struct Attachment MOZ_FINAL
+  {
+    nsCOMPtr<nsIDOMBlob> content;
+    nsString id;
+    nsString location;
+
+    explicit Attachment(const MmsAttachment& aAttachment) :
+      content(aAttachment.mContent),
+      id(aAttachment.mId),
+      location(aAttachment.mLocation)
+    {}
+  };
+
   MmsMessage(int32_t                               aId,
              uint64_t                              aThreadId,
              const nsAString&                      aIccId,
              mobilemessage::DeliveryState          aDelivery,
-             const nsTArray<idl::MmsDeliveryInfo>& aDeliveryInfo,
+             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<idl::MmsAttachment>&   aAttachments,
+             const nsTArray<Attachment>&           aAttachments,
              uint64_t                              aExpiryDate,
              bool                                  aReadReportRequested);
 
   MmsMessage(const mobilemessage::MmsMessageData& aData);
 
   static nsresult Create(int32_t               aId,
                          uint64_t              aThreadId,
                          const nsAString&      aIccId,
@@ -67,25 +81,25 @@ public:
                mobilemessage::MmsMessageData& aData);
 
 private:
 
   int32_t                        mId;
   uint64_t                       mThreadId;
   nsString                       mIccId;
   mobilemessage::DeliveryState   mDelivery;
-  nsTArray<idl::MmsDeliveryInfo> mDeliveryInfo;
+  nsTArray<MmsDeliveryInfo>      mDeliveryInfo;
   nsString                       mSender;
   nsTArray<nsString>             mReceivers;
   uint64_t                       mTimestamp;
   uint64_t                       mSentTimestamp;
   bool                           mRead;
   nsString                       mSubject;
   nsString                       mSmil;
-  nsTArray<idl::MmsAttachment>   mAttachments;
+  nsTArray<Attachment>           mAttachments;
   uint64_t                       mExpiryDate;
   bool                           mReadReportRequested;
 };
 
 } // namespace dom
 } // namespace mozilla
 
 #endif // mozilla_dom_mobilemessage_MmsMessage_h
--- a/dom/mobilemessage/src/ipc/SmsIPCService.cpp
+++ b/dom/mobilemessage/src/ipc/SmsIPCService.cpp
@@ -5,17 +5,16 @@
 
 #include "mozilla/dom/ContentChild.h"
 #include "SmsIPCService.h"
 #include "nsXULAppAPI.h"
 #include "mozilla/dom/mobilemessage/SmsChild.h"
 #include "SmsMessage.h"
 #include "SmsFilter.h"
 #include "SmsSegmentInfo.h"
-#include "DictionaryHelpers.h"
 #include "nsJSUtils.h"
 #include "nsCxPusher.h"
 #include "mozilla/dom/MobileMessageManagerBinding.h"
 #include "mozilla/dom/MozMmsMessageBinding.h"
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/Preferences.h"
 #include "nsString.h"
 
--- a/dom/network/interfaces/nsIDOMNetworkStatsManager.idl
+++ b/dom/network/interfaces/nsIDOMNetworkStatsManager.idl
@@ -2,51 +2,29 @@
  * 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 nsIDOMDOMRequest;
 
 /**
- * Provide the detailed options for specifying different kinds of data filtering
- * in getSamples function.
- */
-dictionary NetworkStatsGetOptions
-{
-  /**
-   * App manifest URL is used to filter network stats by app, while service type
-   * is used to filter stats by system service.
-   * Note that, these two options cannot be specified at the same time for now;
-   * others, an NS_ERROR_NOT_IMPLMENTED exception will be thrown.
-   */
-  DOMString appManifestURL;
-  DOMString serviceType;
-};
-
-/**
  * Represents a data interface for which the manager is recording statistics.
  */
 [scriptable, uuid(f540615b-d803-43ff-8200-2a9d145a5645)]
 interface nsIDOMMozNetworkStatsInterface : nsISupports
 {
   readonly attribute long type;
 
   /**
    * Id value is '0' for wifi or the iccid for mobile (SIM).
    */
   readonly attribute DOMString id;
 };
 
-dictionary NetworkStatsAlarmOptions
-{
-  jsval startTime; // Date object
-  jsval data;
-};
-
 [scriptable, builtinclass, uuid(063ebeb2-5c6e-47ae-bdcd-5e6ebdc7a68c)]
 interface nsIDOMMozNetworkStatsAlarm : nsISupports
 {
   readonly attribute unsigned long alarmId;
   readonly attribute nsIDOMMozNetworkStatsInterface network;
   readonly attribute long threshold;
   readonly attribute jsval data;
 };
--- a/dom/src/geolocation/nsGeolocation.h
+++ b/dom/src/geolocation/nsGeolocation.h
@@ -27,17 +27,16 @@
 #include "nsIDOMGeoPositionErrorCallback.h"
 #include "mozilla/dom/GeolocationBinding.h"
 #include "mozilla/dom/PositionErrorBinding.h"
 #include "mozilla/dom/CallbackObject.h"
 
 #include "nsIGeolocationProvider.h"
 #include "nsIContentPermissionPrompt.h"
 #include "nsIDOMWindow.h"
-#include "DictionaryHelpers.h"
 #include "mozilla/Attributes.h"
 
 class nsGeolocationService;
 class nsGeolocationRequest;
 
 namespace mozilla {
 namespace dom {
 class Geolocation;
--- a/dom/voicemail/nsIDOMMozVoicemailEvent.idl
+++ b/dom/voicemail/nsIDOMMozVoicemailEvent.idl
@@ -16,13 +16,8 @@ interface nsIDOMMozVoicemailEvent : nsID
    */
   readonly attribute nsIDOMMozVoicemailStatus status;
 
   [noscript] void initMozVoicemailEvent(in DOMString aType,
                                         in boolean aCanBubble,
                                         in boolean aCancelable,
                                         in nsIDOMMozVoicemailStatus aStatus);
 };
-
-dictionary MozVoicemailEventInit : EventInit
-{
-  nsIDOMMozVoicemailStatus status;
-};
--- a/dom/webidl/MozMmsMessage.webidl
+++ b/dom/webidl/MozMmsMessage.webidl
@@ -1,14 +1,24 @@
 /* -*- 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/.
  */
 
-// If this is changed, change the XPIDL dictionary as well.
+// If this is changed, change the MmsMessage.h structure as well.
 dictionary MmsAttachment {
   DOMString? id = null;
   DOMString? location = null;
   Blob? content = null;
 };
 
+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).
+};
+
 // If we start using MmsParameters here, remove it from DummyBinding.
copy from dom/mobileconnection/interfaces/nsIDOMMobileConnection.idl
copy to dom/webidl/MozMobileConnection.webidl
--- a/dom/mobileconnection/interfaces/nsIDOMMobileConnection.idl
+++ b/dom/webidl/MozMobileConnection.webidl
@@ -1,707 +1,12 @@
 /* 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 "nsIDOMEventTarget.idl"
-
-interface nsIDOMEventListener;
-interface nsIDOMDOMRequest;
-interface nsIDOMMozMobileConnectionInfo;
-interface nsIDOMMozMobileNetworkInfo;
-interface nsIDOMMozMobileCellInfo;
-interface nsIDOMMozMobileCFInfo;
-interface nsIVariant;
-
-[scriptable, builtinclass, uuid(389ad352-4e43-4c1a-85e9-bae745554326)]
-interface nsIDOMMozMobileConnection : nsIDOMEventTarget
-{
-  const long ICC_SERVICE_CLASS_VOICE = (1 << 0);
-  const long ICC_SERVICE_CLASS_DATA = (1 << 1);
-  const long ICC_SERVICE_CLASS_FAX = (1 << 2);
-  const long ICC_SERVICE_CLASS_SMS = (1 << 3);
-  const long ICC_SERVICE_CLASS_DATA_SYNC = (1 << 4);
-  const long ICC_SERVICE_CLASS_DATA_ASYNC = (1 << 5);
-  const long ICC_SERVICE_CLASS_PACKET = (1 << 6);
-  const long ICC_SERVICE_CLASS_PAD = (1 << 7);
-  const long ICC_SERVICE_CLASS_MAX = (1 << 7);
-
-  /**
-   * Call barring program.
-   *
-   * (0) all outgoing.
-   * (1) outgoing international.
-   * (2) outgoing international except to home country.
-   * (3) all incoming.
-   * (4) incoming when roaming outside the home country.
-   */
-  const long CALL_BARRING_PROGRAM_ALL_OUTGOING                       = 0;
-  const long CALL_BARRING_PROGRAM_OUTGOING_INTERNATIONAL             = 1;
-  const long CALL_BARRING_PROGRAM_OUTGOING_INTERNATIONAL_EXCEPT_HOME = 2;
-  const long CALL_BARRING_PROGRAM_ALL_INCOMING                       = 3;
-  const long CALL_BARRING_PROGRAM_INCOMING_ROAMING                   = 4;
-
-  /**
-   * Calling line identification restriction constants.
-   *
-   * @see 3GPP TS 27.007 7.7 Defined values
-   *
-   * (0) Uses subscription default value.
-   * (1) Restricts CLI presentation.
-   * (2) Allows CLI presentation.
-   */
-  const long CLIR_DEFAULT     = 0;
-  const long CLIR_INVOCATION  = 1;
-  const long CLIR_SUPPRESSION = 2;
-
-  /**
-   * These two fields can be accessed by privileged applications with the
-   * 'mobilenetwork' permission.
-   */
-  readonly attribute DOMString lastKnownNetwork;
-  readonly attribute DOMString lastKnownHomeNetwork;
-
-  /**
-   * Information about the voice connection.
-   */
-  readonly attribute nsIDOMMozMobileConnectionInfo voice;
-
-  /**
-   * Information about the data connection.
-   */
-  readonly attribute nsIDOMMozMobileConnectionInfo data;
-
-  /**
-   * Integrated Circuit Card Identifier of the SIM this
-   * mobile connection corresponds to.
-   */
-  readonly attribute DOMString iccId;
-
-  /**
-   * The selection mode of the voice and data networks.
-   *
-   * Possible values: null (unknown), 'automatic', 'manual'
-   */
-  readonly attribute DOMString networkSelectionMode;
-
-  /**
-   * The current radio state.
-   *
-   * Possible values: null (unknown), 'enabling', 'enabled', 'disabling',
-   * 'disabled'
-   */
-  readonly attribute DOMString radioState;
-
-  /**
-   * Array of network types that are supported by this radio.
-   *
-   * Possible values: 'gsm', 'wcdma', 'cdma', 'evdo', 'lte'
-   */
-  readonly attribute nsIVariant supportedNetworkTypes;
-
-  /**
-   * Search for available networks.
-   *
-   * If successful, the request's onsuccess will be called, and the request's
-   * result will be an array of nsIDOMMozMobileNetworkInfo.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * or 'GenericFailure'.
-   */
-  nsIDOMDOMRequest getNetworks();
-
-  /**
-   * Manually selects the passed in network, overriding the radio's current
-   * selection.
-   *
-   * If successful, the request's onsuccess will be called.
-   * Note: If the network was actually changed by this request,
-   * the 'voicechange' and 'datachange' events will also be fired.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'IllegalSIMorME', or 'GenericFailure'
-   */
-  nsIDOMDOMRequest selectNetwork(in nsIDOMMozMobileNetworkInfo network);
-
-  /**
-   * Tell the radio to automatically select a network.
-   *
-   * If successful, the request's onsuccess will be called.
-   * Note: If the network was actually changed by this request, the
-   * 'voicechange' and 'datachange' events will also be fired.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'IllegalSIMorME', or 'GenericFailure'
-   */
-  nsIDOMDOMRequest selectNetworkAutomatically();
-
-  /**
-   * Set preferred network type
-   *
-   * @param type
-   *        DOMString indicates the desired preferred network type.
-   *        Possible values: 'wcdma/gsm', 'gsm', 'wcdma', 'wcdma/gsm-auto',
-   *                         'cdma/evdo', 'cdma', 'evdo', 'wcdma/gsm/cdma/evdo',
-   *                         'lte/cdma/evdo', 'lte/wcdma/gsm',
-   *                         'lte/wcdma/gsm/cdma/evdo' or 'lte'.
-   *
-   * If successful, the request's onsuccess will be called.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'InvalidParameter', 'ModeNotSupported' or 'GenericFailure'
-   *
-   * TODO: param "type" should be a WebIDL enum when this interface is converted
-   *       to WebIDL
-   */
-  nsIDOMDOMRequest setPreferredNetworkType(in DOMString type);
-
-  /**
-   * Query current preferred network type
-   *
-   * If successful, the request's onsuccess will be called. And the request's
-   * result will be a string indicating the current preferred network type.
-   * The value will be either 'wcdma/gsm', 'gsm', 'wcdma', 'wcdma/gsm-auto',
-   * 'cdma/evdo', 'cdma', 'evdo', 'wcdma/gsm/cdma/evdo', 'lte/cdma/evdo',
-   * 'lte/wcdma/gsm', 'lte/wcdma/gsm/cdma/evdo' or 'lte'.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * or 'GenericFailure'
-   */
-  nsIDOMDOMRequest getPreferredNetworkType();
-
-  /**
-   * Set roaming preference
-   *
-   * @param mode
-   *        DOMString indicates the desired roaming preference.
-   *        Possible values: 'home', 'affiliated', or 'any'.
-   *
-   * If successful, the request's onsuccess will be called.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'IllegalSIMorME', 'InvalidParameter', or 'GenericFailure'
-   *
-   * TODO: param "mode" should be a WebIDL enum when this interface is converted
-   *       to WebIDL
-   */
-  nsIDOMDOMRequest setRoamingPreference(in DOMString mode);
-
-  /**
-   * Query current roaming preference
-   *
-   * If successful, the request's onsuccess will be called. And the request's
-   * result will be a string indicating the current roaming preference.
-   * The value will be either 'home', 'affiliated', or 'any'.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'IllegalSIMorME', or 'GenericFailure'
-   */
-  nsIDOMDOMRequest getRoamingPreference();
-
-  /**
-   * Set voice privacy preference.
-   *
-   * @param enabled
-   *        Boolean indicates the preferred voice privacy mode used in voice
-   *        scrambling in CDMA networks. 'True' means the enhanced voice security
-   *        is required.
-   *
-   * If successful, the request's onsuccess will be called.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'IllegalSIMorME', 'InvalidParameter', or 'GenericFailure'
-   */
-  nsIDOMDOMRequest setVoicePrivacyMode(in bool enabled);
-
-  /**
-   * Query current voice privacy mode.
-   *
-   * If successful, the request's onsuccess will be called. And the request's
-   * result will be a boolean indicating the current voice privacy mode.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'IllegalSIMorME', or 'GenericFailure'
-   */
-  nsIDOMDOMRequest getVoicePrivacyMode();
-
-  /**
-   * Send a MMI message.
-   *
-   * @param mmi
-   *        DOMString containing an MMI string that can be associated to a
-   *        USSD request or other RIL functionality.
-   *
-   * @return a nsIDOMDOMRequest
-   *         The request's result will be an object containing information
-   *         about the operation.
-   *
-   * In case that the MMI code requires sending an USSD request, the DOMrequest
-   * 'success' event means that the RIL has successfully processed and sent the
-   * USSD request to the network. The network reply will be reported via
-   * 'onussdreceived' event. If the MMI code is not associated to a USSD but to
-   * other RIL request its result, if one is needed, will be notified via the
-   * returned DOMRequest 'success' or 'error' event.
-   */
-  nsIDOMDOMRequest sendMMI(in DOMString mmi);
-
-  /**
-   * Cancel the current MMI request if one exists.
-   */
-  nsIDOMDOMRequest cancelMMI();
-
-  /**
-   * Configures call forward options.
-   *
-   * @param CFInfo
-   *        An object containing the call forward rule to set.
-   *
-   * If successful, the request's onsuccess will be called.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'IllegalSIMorME', 'InvalidParameter', or 'GenericFailure'
-   */
-  nsIDOMDOMRequest setCallForwardingOption(in nsIDOMMozMobileCFInfo CFInfo);
-
-  /**
-   * Queries current call forward options.
-   *
-   * @param reason
-   *        Indicates the reason the call is being forwarded. It will be either
-   *        unconditional (0), mobile busy (1), no reply (2), not reachable (3),
-   *        all call forwarding (4), or all conditional call forwarding (5).
-   *
-   * If successful, the request's onsuccess will be called, and the request's
-   * result will be an array of nsIDOMMozMobileCFInfo.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'InvalidParameter', or 'GenericFailure'.
-   */
-  nsIDOMDOMRequest getCallForwardingOption(in unsigned short reason);
-
-  /**
-   * Configures call barring option.
-   *
-   * @param option
-   *        An object containing the call barring rule to set.
-   * @see MozCallBarringOption for the detail of info.
-   *
-   * If successful, the request's onsuccess will be called.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'IllegalSIMorME', 'InvalidParameter', or 'GenericFailure'
-   */
-  nsIDOMDOMRequest setCallBarringOption(in jsval option);
-
-  /**
-   * Queries current call barring status.
-   *
-   * @param info
-   *        An object containing the call barring rule to query. No need to
-   *        specify 'enabled' property.
-   * @see MozCallBarringOption for the detail of info.
-   *
-   * If successful, the request's onsuccess will be called, and the request's
-   * result will be an object of MozCallBarringOption with correct 'enabled'
-   * property indicating the status of this rule.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'InvalidParameter', or 'GenericFailure'.
-   */
-  nsIDOMDOMRequest getCallBarringOption(in jsval option);
-
-  /**
-   * Change call barring facility password.
-   *
-   * @param info
-   *        An object containing information about pin and newPin, and,
-   *        this object must have both "pin" and "newPin" attributes
-   *        to change the call barring facility password.
-   *
-   * Example:
-   *
-   *   changeCallBarringPassword({pin: "...",
-   *                              newPin: "..."});
-   */
-  nsIDOMDOMRequest changeCallBarringPassword(in jsval info);
-
-  /**
-   * Configures call waiting options.
-   *
-   * @param enabled
-   *        Value containing the desired call waiting status.
-   *
-   * If successful, the request's onsuccess will be called.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * 'IllegalSIMorME', or 'GenericFailure'
-   */
-  nsIDOMDOMRequest setCallWaitingOption(in bool enabled);
-
-  /**
-   * Queries current call waiting options.
-   *
-   * If successful, the request's onsuccess will be called, and the request's
-   * result will be a boolean indicating the call waiting status.
-   *
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * or 'GenericFailure'.
-   */
-  nsIDOMDOMRequest getCallWaitingOption();
-
-  /**
-   * Enables or disables the presentation of the calling line identity (CLI) to
-   * the called party when originating a call.
-   *
-   * @param clirMode
-   *        Is one of the CLIR_* constants.
-   *
-   * If successful, the request's onsuccess will be called.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   */
-  nsIDOMDOMRequest setCallingLineIdRestriction(in unsigned short clirMode);
-
-  /**
-   * Queries current CLIR status.
-   *
-   * If successful, the request's onsuccess will be called, and the request's
-   * result will be a DOMCLIRStatus dictionary containing CLIR 'n' and 'm'
-   * parameter.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RadioNotAvailable', 'RequestNotSupported',
-   * or 'GenericFailure'.
-   */
-  nsIDOMDOMRequest getCallingLineIdRestriction();
-
-  /**
-   * Exit emergency callback mode.
-   *
-   * If successful, the request's onsuccess will be called.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'RequestNotSupported'  or 'GenericFailure'.
-   */
-  nsIDOMDOMRequest exitEmergencyCbMode();
-
-  /**
-   * Set radio enabled/disabled.
-   *
-   * @param enabled
-   *        True to enable the radio.
-   *
-   * If successful, the request's onsuccess will be called.
-   *
-   * Otherwise, the request's onerror will be called, and the request's error
-   * will be either 'InvalidStateError', 'RadioNotAvailable', or
-   * 'GenericFailure'.
-   *
-   * Note: Request is not available when radioState is null, 'enabling', or
-   *       'disabling'. Calling the function in above conditions will receive
-   *       'InvalidStateError' error.
-   */
-  nsIDOMDOMRequest setRadioEnabled(in boolean enabled);
-
-  /**
-   * The 'voicechange' event is notified whenever the voice connection object
-   * changes.
-   */
-  [implicit_jscontext] attribute jsval onvoicechange;
-
-  /**
-   * The 'datachange' event is notified whenever the data connection object
-   * changes values.
-   */
-  [implicit_jscontext] attribute jsval ondatachange;
-
-  /**
-   * The 'ussdreceived' event is notified whenever a new USSD message is
-   * received.
-   */
-  [implicit_jscontext] attribute jsval onussdreceived;
-
-  /**
-   * The 'dataerror' event is notified whenever the data connection object
-   * receives an error from the RIL
-   */
-  [implicit_jscontext] attribute jsval ondataerror;
-
-  /**
-   * The 'oncfstatechange' event is notified whenever the call forwarding
-   * state changes.
-   */
-  [implicit_jscontext] attribute jsval oncfstatechange;
-
-  /**
-   * The 'emergencycbmodechange' event is notified whenever the emergency
-   * callback mode changes.
-   */
-  [implicit_jscontext] attribute jsval onemergencycbmodechange;
-
-  /**
-   * The 'onotastatuschange' event is notified whenever the ota provision status
-   * changes.
-   */
-  [implicit_jscontext] attribute jsval onotastatuschange;
-
-  /**
-   * The 'oniccchange' event is notified whenever the iccid value
-   * changes.
-   */
-  [implicit_jscontext] attribute jsval oniccchange;
-
-  /**
-   * The 'onradiostatechange' event is notified whenever the radio state
-   * changes.
-   */
-  [implicit_jscontext] attribute jsval onradiostatechange;
-};
-
-[scriptable, uuid(49706beb-a160-40b7-b745-50f62e389a2c)]
-interface nsIDOMMozMobileConnectionInfo : nsISupports
-{
-  /**
-   * State of the connection.
-   *
-   * Possible values: 'notSearching', 'searching', 'denied', 'registered'.
-   * null if the state is unknown.
-   */
-  readonly attribute DOMString state;
-
-  /**
-   * Indicates whether the connection is ready. This may be different
-   */
-  readonly attribute bool connected;
-
-  /**
-   * Indicates whether only emergency calls are possible.
-   *
-   * This flag is only relevant to voice connections and when 'connected' is
-   * false.
-   */
-  readonly attribute bool emergencyCallsOnly;
-
-  /**
-   * Indicates whether the connection is going through a foreign operator
-   * (roaming) or not.
-   */
-  readonly attribute bool roaming;
-
-  /**
-   * Network operator
-   */
-  readonly attribute nsIDOMMozMobileNetworkInfo network;
-
-  /**
-   * Type of connection.
-   *
-   * Possible values: 'gsm', 'cdma', gprs', 'edge', 'umts', 'hsdpa', 'evdo0',
-   * 'evdoa', 'evdob', etc.
-   */
-  readonly attribute DOMString type;
-
-  /**
-   * Signal strength in dBm, or null if no service is available.
-   */
-  readonly attribute jsval signalStrength;
-
-  /**
-   * Signal strength, represented linearly as a number between 0 (weakest
-   * signal) and 100 (full signal).
-   */
-  readonly attribute jsval relSignalStrength;
-
-  /**
-   * Cell location.
-   */
-  readonly attribute nsIDOMMozMobileCellInfo cell;
-
-};
-
-[scriptable, uuid(40018fc7-4c42-47b6-8de6-3591a9c622bc)]
-interface nsIDOMMozMobileNetworkInfo: nsISupports
-{
-  /**
-   * Short name of the network operator
-   */
-  readonly attribute DOMString shortName;
-
-  /**
-   * Long name of the network operator
-   */
-  readonly attribute DOMString longName;
-
-  /**
-   * Mobile Country Code (MCC) of the network operator
-   */
-  readonly attribute DOMString mcc;
-
-  /**
-   * Mobile Network Code (MNC) of the network operator
-   */
-  readonly attribute DOMString mnc;
-
-  /**
-   * State of this network operator.
-   *
-   * Possible values: 'available', 'connected', 'forbidden', or null (unknown)
-   */
-  readonly attribute DOMString state;
-};
-
-[scriptable, uuid(9750b3a7-d913-436e-95d4-7ef2973ec6a1)]
-interface nsIDOMMozMobileCellInfo: nsISupports
-{
-  /**
-   * Mobile Location Area Code (LAC) for GSM/WCDMA networks.
-   *
-   * Possible ranges from 0x0000 to 0xffff.
-   * -1 if the LAC is unknown.
-   */
-  readonly attribute long gsmLocationAreaCode;
-
-  /**
-   * Mobile Cell ID for GSM/WCDMA networks.
-   *
-   * Possible ranges from 0x00000000 to 0xffffffff.
-   * -1 if the cell id is unknown.
-   */
-  readonly attribute long long gsmCellId;
-
-  /**
-   * Base Station ID for CDMA networks.
-   *
-   * Possible ranges from 0 to 65535
-   * -1 if the base station id is unknown.
-   */
-  readonly attribute long cdmaBaseStationId;
-
-  /**
-   * Base Station Latitude for CDMA networks.
-   *
-   * Possible ranges from -1296000 to 1296000.
-   * -2147483648 if the latitude is unknown.
-   *
-   * @see 3GPP2 C.S0005-A v6.0.
-   */
-  readonly attribute long cdmaBaseStationLatitude;
-
-  /**
-   * Base Station Longitude for CDMA networks.
-   *
-   * Possible ranges from -2592000 to 2592000.
-   * -2147483648 if the longitude is unknown.
-   *
-   * @see 3GPP2 C.S0005-A v6.0.
-   */
-  readonly attribute long cdmaBaseStationLongitude;
-
-  /**
-   * System ID for CDMA networks.
-   *
-   * Possible ranges from 0 to 32767.
-   * -1 if the system id is unknown.
-   */
-  readonly attribute long cdmaSystemId;
-
-  /**
-   * Network ID for CDMA networks.
-   *
-   * Possible ranges from 0 to 65535.
-   * -1 if the network id is unknown.
-   */
-  readonly attribute long cdmaNetworkId;
-};
-
-[scriptable, uuid(d1b35ad8-99aa-47cc-ab49-2e72b00e39df)]
-interface nsIDOMMozMobileCFInfo : nsISupports
-{
-  /**
-   * Call forwarding rule status.
-   *
-   * It will be either not active (false), or active (true).
-   *
-   * Note: Unused for setting call forwarding options. It reports
-   *       the status of the rule when getting how the rule is
-   *       configured.
-   *
-   * @see 3GPP TS 27.007 7.11 "status".
-   */
-  readonly attribute bool active;
-
-  const long CALL_FORWARD_ACTION_DISABLE = 0;
-  const long CALL_FORWARD_ACTION_ENABLE = 1;
-  const long CALL_FORWARD_ACTION_QUERY_STATUS = 2;
-  const long CALL_FORWARD_ACTION_REGISTRATION = 3;
-  const long CALL_FORWARD_ACTION_ERASURE = 4;
-
-  /**
-   * Indicates what to do with the rule.
-   *
-   * One of the CALL_FORWARD_ACTION_* constants. It will be either disable (0),
-   * enable (1), query status (2), registration (3), or erasure (4).
-   *
-   * @see 3GPP TS 27.007 7.11 "mode".
-   */
-  readonly attribute unsigned short action;
-
-  const long CALL_FORWARD_REASON_UNCONDITIONAL = 0;
-  const long CALL_FORWARD_REASON_MOBILE_BUSY = 1;
-  const long CALL_FORWARD_REASON_NO_REPLY = 2;
-  const long CALL_FORWARD_REASON_NOT_REACHABLE = 3;
-  const long CALL_FORWARD_REASON_ALL_CALL_FORWARDING = 4;
-  const long CALL_FORWARD_REASON_ALL_CONDITIONAL_CALL_FORWARDING = 5;
-
-  /**
-   * Indicates the reason the call is being forwarded.
-   *
-   * One of the CALL_FORWARD_REASON_* constants. It will be either
-   * unconditional (0), mobile busy (1), no reply (2), not reachable (3),
-   * all call forwarding (4), or all conditional call forwarding (5).
-   *
-   * @see 3GPP TS 27.007 7.11 "reason".
-   */
-  readonly attribute unsigned short reason;
-
-  /**
-   * Phone number of forwarding address.
-   */
-  readonly attribute DOMString number;
-
-  /**
-   * When "no reply" is enabled or queried, this gives the time in
-   * seconds to wait before call is forwarded.
-   */
-  readonly attribute unsigned short timeSeconds;
-
-  /**
-   * Service for which the call forward is set up. It should be one of the
-   * nsIDOMMozMobileConnection.ICC_SERVICE_CLASS_* values.
-   */
-  readonly attribute unsigned short serviceClass;
-};
-
 
 dictionary MozCallBarringOption
 {
   /**
    * Indicates the program the call is being barred.
    *
    * It shall be one of the nsIDOMMozMobileConnection.CALL_BARRING_PROGRAM_*
    * values.
@@ -743,17 +48,17 @@ dictionary DOMMMIResult
    */
   DOMString statusMessage;
 
   /**
    * Some MMI requests like call forwarding or PIN/PIN2/PUK/PUK2 related
    * requests provide extra information along with the status message, this
    * information can be a number, a string key or an array of string keys.
    */
-  jsval additionalInformation;
+  any additionalInformation;
 };
 
 dictionary DOMCLIRStatus
 {
   /**
    * CLIR parameter 'n': parameter sets the adjustment for outgoing calls.
    *
    * 0 Presentation indicator is used according to the subscription of the
copy from dom/network/interfaces/nsIDOMNetworkStatsManager.idl
copy to dom/webidl/MozNetworkStats.webidl
--- a/dom/network/interfaces/nsIDOMNetworkStatsManager.idl
+++ b/dom/webidl/MozNetworkStats.webidl
@@ -1,141 +1,25 @@
 /* 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 nsIDOMDOMRequest;
-
 /**
  * Provide the detailed options for specifying different kinds of data filtering
  * in getSamples function.
  */
 dictionary NetworkStatsGetOptions
 {
   /**
    * App manifest URL is used to filter network stats by app, while service type
    * is used to filter stats by system service.
    * Note that, these two options cannot be specified at the same time for now;
    * others, an NS_ERROR_NOT_IMPLMENTED exception will be thrown.
    */
   DOMString appManifestURL;
   DOMString serviceType;
 };
 
-/**
- * Represents a data interface for which the manager is recording statistics.
- */
-[scriptable, uuid(f540615b-d803-43ff-8200-2a9d145a5645)]
-interface nsIDOMMozNetworkStatsInterface : nsISupports
-{
-  readonly attribute long type;
-
-  /**
-   * Id value is '0' for wifi or the iccid for mobile (SIM).
-   */
-  readonly attribute DOMString id;
-};
-
 dictionary NetworkStatsAlarmOptions
 {
-  jsval startTime; // Date object
-  jsval data;
-};
-
-[scriptable, builtinclass, uuid(063ebeb2-5c6e-47ae-bdcd-5e6ebdc7a68c)]
-interface nsIDOMMozNetworkStatsAlarm : nsISupports
-{
-  readonly attribute unsigned long alarmId;
-  readonly attribute nsIDOMMozNetworkStatsInterface network;
-  readonly attribute long threshold;
-  readonly attribute jsval data;
+  Date startTime;
+  Date data;
 };
-
-[scriptable,  uuid(8a66f4c1-0c25-4a66-9fc5-0106947b91f9)]
-interface nsIDOMMozNetworkStatsManager : nsISupports
-{
-  /**
-   * Constants for known interface types.
-   */
-  const long WIFI = 0;
-  const long MOBILE = 1;
-
-  /**
-   * Find samples between two dates start and end, both included.
-   *
-   * If options is provided, per-app or per-system service usage will be
-   * retrieved; otherwise the target will be overall system usage.
-   *
-   * If success, the request result will be an nsIDOMMozNetworkStats object.
-   */
-  nsIDOMDOMRequest getSamples(in nsIDOMMozNetworkStatsInterface network,
-                              in jsval start,
-                              in jsval end,
-                   [optional] in jsval options /* NetworkStatsGetOptions */);
-
-  /**
-   * Install an alarm on a network. The network must be in the return of
-   * getAvailableNetworks() otherwise an "InvalidNetwork" exception will
-   * be raised.
-   *
-   * When total data usage reaches threshold bytes, a "networkstats-alarm"
-   * system message is sent to the application, where the optional parameter
-   * |data| must be a cloneable object.
-   *
-   * If success, the |result| field of the DOMRequest keeps the alarm Id.
-   */
-  nsIDOMDOMRequest addAlarm(in nsIDOMMozNetworkStatsInterface network,
-                            in long threshold,
-                            [optional] in jsval options /* NetworkStatsAlarmOptions */);
-
-  /**
-   * Obtain all alarms for those networks returned by getAvailableNetworks().
-   * If a network is provided, only retrieves the alarms for that network.
-   * The network must be one of those returned by getAvailebleNetworks() or an
-   * "InvalidNetwork" exception will be raised.
-   *
-   * Each alarm object has the same fields as that in the system message:
-   *  - alarmId
-   *  - network
-   *  - threshold
-   *  - data
-   */
-  nsIDOMDOMRequest getAllAlarms([optional] in nsIDOMMozNetworkStatsInterface network);
-
-  /**
-   * Remove all network alarms. If an |alarmId| is provided, then only that
-   * alarm is removed.
-   */
-  nsIDOMDOMRequest removeAlarms([optional] in long alarmId);
-
-  /**
-   * Remove all stats related with the provided network from DB.
-   */
-  nsIDOMDOMRequest clearStats(in nsIDOMMozNetworkStatsInterface network);
-
-  /**
-   * Remove all stats in the database.
-   */
-  nsIDOMDOMRequest clearAllStats();
-
-  /**
-   * Return available networks that used to be saved in the database.
-   */
-  nsIDOMDOMRequest getAvailableNetworks(); // array of nsIDOMMozNetworkStatsInterface.
-
-  /**
-   * Return available service types that used to be saved in the database.
-   */
-  nsIDOMDOMRequest getAvailableServiceTypes(); // array of string.
-
-  /**
-   * Minimum time in milliseconds between samples stored in the database.
-   */
-  readonly attribute long sampleRate;
-
-  /**
-   * Time in milliseconds recorded by the API until present time. All samples
-   * older than maxStorageAge from now are deleted.
-   */
-  readonly attribute long long maxStorageAge;
-};
--- a/dom/webidl/MozStkCommandEvent.webidl
+++ b/dom/webidl/MozStkCommandEvent.webidl
@@ -10,8 +10,649 @@ interface MozStkCommandEvent : Event
 {
   readonly attribute any command;
 };
 
 dictionary MozStkCommandEventInit : EventInit
 {
   any command = null;
 };
+
+dictionary MozStkTextMessage
+{
+  /**
+   * Text String.
+   *
+   * @see TS 11.14, clause 12.15, Text String.
+   */
+  DOMString text;
+
+  /**
+   * The length of time for which the ME shall display the dialog.
+   */
+  MozStkDuration duration;
+
+  /**
+   * Indicate this text message is high priority or normal priority.
+   *
+   * @see TS 11.14, clause 12.6, Command Qualifier, Display Text, bit 1.
+   *
+   * High priority text shall be displayed on the screen immediately, except if
+   * there is a conflict of priority level of alerting such as incoming calls
+   * or a low battery warning. In that situation, the resolution is left to
+   * the terminal. If the command is rejected in spite of the high priority,
+   * the terminal shall inform the ICC with resultCode is
+   * TERMINAL_CRNTLY_UNABLE_TO_PROCESS in MozStkResponse.
+   *
+   * true: high priority
+   * false: normal priority
+   */
+  boolean isHighPriority;
+
+  /**
+   * Need to wait for user to clear message or not.
+   *
+   * @see TS 11.14, clause 12.6, Command Qualifier, Display Text, bit 8.
+   *
+   * If this attribute is true, but user doesn't give any input within a period
+   * of time(said 30 secs), the terminal shall inform the ICC with resultCode
+   * is NO_RESPONSE_FROM_USER in MozStkResponse.
+   *
+   * true: Wait for user to clear message.
+   * false: clear message after a delay.
+   */
+  boolean userClear;
+
+  /**
+   * Need to response immediately or not.
+   *
+   * @see TS 11.14, clause 12.43, Immediate response.
+   *
+   * When this attribute is true, the terminal shall immediately send
+   * MozStkResponse with resultCode is OK.
+   *
+   * true: The terminal shall send response immediately.
+   * false: otherwise.
+   */
+  boolean responseNeeded;
+};
+
+dictionary MozStkItem
+{
+  /**
+   * Identifier of item.
+   *
+   * The identifier is a single byte between '01' and 'FF'. Each item shall
+   * have a unique identifier within an Item list.
+   */
+  unsigned short identifier;
+
+  /**
+   * Text string of item.
+   */
+  DOMString text;
+};
+
+dictionary MozStkMenu
+{
+  /**
+   * Array of MozStkItem.
+   *
+   * @see TS 11.14, clause 12.9
+   */
+  sequence<MozStkItem> items;
+
+  /**
+   * Presentation type, one of TYPE_*.
+   */
+  unsigned short presentationType;
+
+  /**
+   * Title of the menu.
+   */
+  DOMString title;
+
+  /**
+   * Default item identifier of the menu.
+   */
+  unsigned short defaultItem;
+
+  /**
+   * Help information available or not.
+   *
+   * @see TS 11.14, clause 12.6, Command Qualifier, SET UP MENU, bit 8.
+   *
+   * true: help information available.
+   * false: no help information available.
+   */
+  boolean isHelpAvailable;
+
+  /**
+   * List of Next Action Indicators.
+   * Each element should be one of nsIDOMMozIccManager.STK_CMD_*
+   *                            or nsIDOMMozIccManager.STK_NEXT_ACTION_*
+   * If it's STK_NEXT_ACTION_NULL, the terminal should ignore this action
+   * in corresponding item.
+   *
+   * @see TS 11.14, clause 12.24, Items Next Action Indicator.
+   */
+  sequence<unsigned short> nextActionList;
+};
+
+dictionary MozStkInput
+{
+  /**
+   * Text for the ME to display in conjunction with asking the user to respond.
+   */
+  DOMString text;
+
+  /**
+   * The length of time for which the ME shall display the dialog. This field
+   * is used only for GET INKEY.
+   *
+   * @see TS 11.14, clause 11.8, duration, GET INKEY T.C 27.22.4.2.8.4.2
+   */
+  MozStkDuration duration;
+
+  /**
+   * Minimum length of response.
+   */
+  unsigned short minLength;
+
+  /**
+   * Maximum length of response.
+   */
+  unsigned short maxLength;
+
+  /**
+   * Text for the ME to display, corresponds to a default text string offered
+   * by the ICC.
+   */
+  DOMString defaultText;
+
+  /**
+   * Input format.
+   *
+   * @see TS 11.14, clause 12.6, Command Qualifier, GET INPUT, bit 1.
+   *
+   * true: Alphabet set.
+   * false: Digits only.
+   */
+  boolean isAlphabet;
+
+  /**
+   * Alphabet encoding.
+   *
+   * @see TS 11.14, clause 12.6, Command Qualifier, GET INPUT, bit 2.
+   *
+   * true: UCS2 alphabet.
+   * false: default SMS alphabet.
+   */
+  boolean isUCS2;
+
+  /**
+   * Visibility of input.
+   *
+   * @see TS 11.14, clause 12.6, Command Qualifier, GET INPUT, bit 3.
+   *
+   * true: User input shall not be revealed in any way.
+   * false: ME may echo user input on the display.
+   */
+  boolean hideInput;
+
+  /**
+   * Yes/No response is requested.
+   *
+   * @see TS 11.14, clause 12.6, Command Qualifier, GET INKEY, bit 3.
+   *
+   * true: Yes/No response is requested, and character sets
+   *       (Alphabet set and UCS2) are disabled.
+   * false: Character sets (Alphabet set and UCS2) are enabled.
+   */
+  boolean isYesNoRequested;
+
+  /**
+   * User input in packed or unpacked format.
+   *
+   * @see TS 11.14, clause 12.6, Command Qualifier, GET INPUT, bit 4.
+   *
+   * true: User input to be in SMS packed format.
+   * false: User input to be in unpacked format.
+   */
+  boolean isPacked;
+
+  /**
+   * Help information available or not.
+   *
+   * @see TS 11.14, clause 12.6, Command Qualifier, GET INPUT/GET INKEY, bit 8.
+   *
+   * true: help information available.
+   * false: no help information available.
+   */
+  boolean isHelpAvailable;
+};
+
+dictionary MozStkBrowserSetting
+{
+  /**
+   * Confirm message to launch browser.
+   */
+  MozStkTextMessage confirmMessage;
+
+  /**
+   * The URL to be opened by browser.
+   */
+  DOMString url;
+
+  /**
+   * One of STK_BROWSER_MODE_*.
+   *
+   * @see nsIDOMMozIccManager.STK_BROWSER_MODE_*
+   */
+  unsigned short mode;
+};
+
+dictionary MozStkSetUpCall
+{
+  /**
+   * The Dialling number.
+   */
+  DOMString address;
+
+  /**
+   * The text message used in user confirmation phase.
+   */
+  MozStkTextMessage confirmMessage;
+
+  /**
+   * The text message used in call set up phase.
+   */
+  MozStkTextMessage callMessage;
+
+  /**
+   * The Optional maximum duration for the redial mechanism.
+   * The time elapsed since the first call set-up attempt has exceeded the duration
+   * requested by the UICC, the redial mechanism is terminated.
+   */
+  MozStkDuration duration;
+};
+
+dictionary MozStkSetUpEventList
+{
+  /**
+   * The list of events that needs to provide details to ICC when they happen.
+   * When this valus is null, means an indication to remove the existing list
+   * of events in ME.
+   *
+   * @see nsIDOMMozIccManager.STK_EVENT_TYPE_*
+   */
+   sequence<unsigned short> eventList;
+};
+
+dictionary MozStkLocationInfo
+{
+  /**
+   * Mobile Country Code (MCC) of the current serving operator.
+   */
+  unsigned short mcc;
+
+  /**
+   * Mobile Network Code (MNC) of the current serving operator.
+   */
+  unsigned short mnc;
+
+  /**
+   * Mobile Location Area Code (LAC) for the current serving operator.
+   */
+  unsigned short gsmLocationAreaCode;
+
+  /**
+   * Mobile Cell ID for the current serving operator.
+   */
+  unsigned long gsmCellId;
+};
+
+dictionary MozStkDuration
+{
+  /**
+   * Time unit used, should be one of STK_TIME_UNIT_*.
+   */
+  unsigned short timeUnit;
+
+  /**
+   * The length of time required, expressed in timeUnit.
+   */
+  octet timeInterval;
+};
+
+dictionary MozStkPlayTone
+{
+  /**
+   * Text String.
+   */
+  DOMString text;
+
+  /**
+   * One of STK_TONE_TYPE_*.
+   */
+  unsigned short tone;
+
+  /**
+   * The length of time for which the ME shall generate the tone.
+   */
+  MozStkDuration duration;
+
+  /**
+   * Need to vibrate or not.
+   * true: vibrate alert, if available, with the tone.
+   * false: use of vibrate alert is up to the ME.
+   */
+  boolean isVibrate;
+};
+
+dictionary MozStkProvideLocalInfo
+{
+  /**
+   * Indicate which local information is required.
+   * It shall be one of following:
+   *  - nsIDOMMozIccManager.STK_LOCAL_INFO_LOCATION_INFO
+   *  - nsIDOMMozIccManager.STK_LOCAL_INFO_IMEI
+   *  - nsIDOMMozIccManager.STK_LOCAL_INFO_DATE_TIME_ZONE
+   *  - nsIDOMMozIccManager.STK_LOCAL_INFO_LANGUAGE
+   */
+  unsigned short localInfoType;
+};
+
+dictionary MozStkLocationEvent
+{
+  /**
+   * The type of this event.
+   * It shall be nsIDOMMozIccManager.STK_EVENT_TYPE_LOCATION_STATUS;
+   */
+  unsigned short eventType;
+
+  /**
+   * Indicate current service state of the MS with one of the values listed
+   * below:
+   *  - nsIDOMMozIccManager.STK_SERVICE_STATE_NORMAL
+   *  - nsIDOMMozIccManager.STK_SERVICE_STATE_LIMITED
+   *  - nsIDOMMozIccManager.STK_SERVICE_STATE_UNAVAILABLE
+   */
+  unsigned short locationStatus;
+
+  /**
+   * See MozStkLocationInfo.
+   * This value shall only be provided if the locationStatus indicates
+   * 'STK_SERVICE_STATE_NORMAL'.
+   */
+  MozStkLocationInfo locationInfo;
+};
+
+dictionary MozStkTimer
+{
+  /**
+   * Identifier of a timer.
+   */
+  octet timerId;
+
+  /**
+   * Length of time during which the timer has to run.
+   * The resolution of a timer is 1 second.
+   */
+  unsigned long timerValue;
+
+  /**
+   * The action requested from UICC.
+   * It shall be one of below:
+   * - nsIDOMMozIccManager.STK_TIMER_START
+   * - nsIDOMMozIccManager.STK_TIMER_DEACTIVATE
+   * - nsIDOMMozIccManager.STK_TIMER_GET_CURRENT_VALUE
+   */
+  unsigned short timerAction;
+};
+
+dictionary MozStkBipMessage
+{
+  /**
+   * Text String
+   */
+  DOMString text;
+};
+
+dictionary MozStkCommand
+{
+  /**
+   * The number of command issued by ICC. And it is assigned
+   * by ICC may take any hexadecimal value betweean '01' and 'FE'.
+   *
+   * @see TS 11.14, clause 6.5.1
+   */
+  unsigned short commandNumber;
+
+  /**
+   * One of STK_CMD_*
+   */
+  unsigned short typeOfCommand;
+
+  /**
+   * Qualifiers specific to the command.
+   */
+  unsigned short commandQualifier;
+
+  /**
+   * options varies accrording to the typeOfCommand in MozStkCommand.
+   *
+   * When typeOfCommand is
+   * - STK_CMD_DISPLAY_TEXT
+   * - STK_CMD_SET_UP_IDLE_MODE_TEXT
+   * - STK_CMD_SEND_{SS|USSD|SMS|DTMF},
+   * options is MozStkTextMessage.
+   *
+   * When typeOfCommand is
+   * - STK_CMD_SELECT_ITEM
+   * - STK_CMD_SET_UP_MENU
+   * options is MozStkMenu.
+   *
+   * When typeOfCommand is
+   * - STK_CMD_GET_INKEY
+   * - STK_CMD_GET_INPUT,
+   * options is MozStkInput.
+   *
+   * When typeOfCommand is
+   * - STK_CMD_LAUNCH_BROWSER
+   * options is MozStkBrowserSetting.
+   *
+   * When typeOfCommand is
+   * - STK_CMD_SET_UP_CALL
+   * options is MozStkSetUpCall.
+   *
+   * When typeOfCommand is
+   * - STK_CMD_SET_UP_EVENT_LIST
+   * options is MozStkSetUpEventList.
+   *
+   * When typeOfCommand is
+   * - STK_CMD_PLAY_TONE
+   * options is MozStkPlayTone.
+   *
+   * When typeOfCommand is
+   * - STK_CMD_POLL_INTERVAL
+   * options is MozStkDuration.
+   *
+   * When typeOfCommand is
+   * - STK_CMD_PROVIDE_LOCAL_INFO
+   * options is MozStkProvideLocalInfo.
+   *
+   * When typeOfCommand is
+   * - STK_CMD_TIMER_MANAGEMENT
+   * option is MozStkTimer
+   *
+   * When typeOfCommand is
+   * - STK_CMD_OPEN_CHANNEL
+   * - STK_CMD_CLOSE_CHANNEL
+   * - STK_CMD_SEND_DATA
+   * - STK_CMD_RECEIVE_DATA
+   * options is MozStkBipMessage
+   *
+   * When typeOfCommand is
+   * - STK_CMD_POLL_OFF
+   * options is null.
+   *
+   * When typeOfCommand is
+   * - STK_CMD_REFRESH
+   * options is null.
+   */
+  any options;
+};
+
+dictionary MozStkResponse
+{
+  /**
+   * One of RESULT_*
+   */
+  unsigned short resultCode;
+
+  /**
+   * The identifier of the item selected by user.
+   *
+   * @see MozStkItem.identifier
+   */
+  unsigned short itemIdentifier;
+
+  /**
+   * User input.
+   */
+  DOMString input;
+
+  /**
+   * YES/NO response.
+   *
+   * @see MozStkInput.isYesNoRequested
+   */
+  boolean isYesNo;
+
+  /**
+   * User has confirmed or rejected the call during STK_CMD_CALL_SET_UP.
+   *
+   * @see RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM
+   *
+   * true: Confirmed by User.
+   * false: Rejected by User.
+   */
+  boolean hasConfirmed;
+
+  /**
+   * The response for STK_CMD_PROVIDE_LOCAL_INFO
+   */
+  MozStkLocalInfo localInfo;
+
+  /**
+   * The response for STK_CMD_TIMER_MANAGEMENT.
+   * The 'timerValue' is needed if the action of STK_CMD_TIMER_MANAGEMENT is
+   * 'STK_TIMER_DEACTIVATE' or 'STK_TIMER_GET_CURRENT_VALUE'. It shall state
+   * the current value of a timer. And the resolution is 1 second.
+   */
+  MozStkTimer timer;
+};
+
+dictionary MozStkCallEvent
+{
+  /**
+   * The type of this event.
+   * It shall be one of following:
+   *     - nsIDOMMozIccManager.STK_EVENT_TYPE_MT_CALL,
+   *     - nsIDOMMozIccManager.STK_EVENT_TYPE_CALL_CONNECTED,
+   *     - nsIDOMMozIccManager.STK_EVENT_TYPE_CALL_DISCONNECTED.
+   */
+  unsigned short eventType;
+
+  /**
+   * Remote party number.
+   */
+  DOMString number;
+
+  /**
+   * This field is available in 'STK_EVENT_TYPE_CALL_CONNECTED' and
+   * 'STK_EVENT_TYPE_CALL_DISCONNECTED' events.
+   * For the STK_EVENT_TYPE_CALL_CONNECTED event, setting this to true means the
+   * connection is answered by remote end, that is, this is an outgoing call.
+   * For the STK_EVENT_TYPE_CALL_DISCONNECTED event, setting this to true
+   * indicates the connection is hung up by remote.
+   */
+  boolean isIssuedByRemote;
+
+  /**
+   * This field is available in Call Disconnected event to indicate the cause
+   * of disconnection. The cause string is passed to gaia through the error
+   * listener of nsIDOMCallEvent. Null if there's no error.
+   */
+  DOMString error;
+};
+
+dictionary MozStkLocalInfo
+{
+  /**
+   * IMEI information
+   */
+  DOMString imei;
+
+  /**
+   * Location Information
+   */
+  MozStkLocationInfo locationInfo;
+
+  /**
+   * Date information
+   */
+  Date date;
+
+  /**
+   * Language Information
+   *
+   * @see ISO 639-1, Alpha-2 code
+   */
+  DOMString language;
+};
+
+dictionary MozStkLanguageSelectionEvent
+{
+  /**
+   * The type of this event.
+   * It shall be nsIDOMMozIccManager.STK_EVENT_TYPE_LANGUAGE_SELECTION.
+   */
+  unsigned short eventType;
+
+  /**
+   * Language Information
+   *
+   * @see ISO 639-1, Alpha-2 code
+   *      "de" for German, "en" for English, "zh" for Chinese, etc.
+   */
+  DOMString language;
+};
+
+dictionary MozStkBrowserTerminationEvent
+{
+  /**
+   * The type of this event.
+   * It shall be nsIDOMMozIccManager.STK_EVENT_TYPE_BROWSER_TERMINATION
+   */
+  unsigned short eventType;
+
+  /**
+   * This object shall contain the browser termination cause.
+   * See TZ 102 223 8.51. It shall be one of following:
+   * - nsIDOMMozIccManager.STK_BROWSER_TERMINATION_CAUSE_USER
+   * - nsIDOMMozIccManager.STK_BROWSER_TERMINATION_CAUSE_ERROR
+   */
+  unsigned short terminationCause;
+};
+
+dictionary MozStkGeneralEvent
+{
+  /**
+   * The type of this event, MozStkGeneralEvent can be used for all Stk Event
+   * requires no more parameter than event type, including
+   * nsIDOMMozIccManager.STK_EVENT_TYPE_USER_ACTIVITY.
+   * nsIDOMMozIccManager.STK_EVENT_TYPE_IDLE_SCREEN_AVAILABLE.
+   * HCI Connectivity Event(Not defined in interface yet).
+   */
+  unsigned short eventType;
+};
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -232,17 +232,19 @@ WEBIDL_FILES = [
     'MimeType.webidl',
     'MimeTypeArray.webidl',
     'MobileMessageManager.webidl',
     'MouseEvent.webidl',
     'MouseScrollEvent.webidl',
     'MozActivity.webidl',
     'MozConnection.webidl',
     'MozMmsMessage.webidl',
+    'MozMobileConnection.webidl',
     'MozNamedAttrMap.webidl',
+    'MozNetworkStats.webidl',
     'MozPowerManager.webidl',
     'MozTimeManager.webidl',
     'MozWakeLock.webidl',
     'MutationEvent.webidl',
     'MutationObserver.webidl',
     'NetDashboard.webidl',
     'NetworkOptions.webidl',
     'Node.webidl',
--- a/dom/wifi/nsIDOMMozWifiConnectionInfoEvent.idl
+++ b/dom/wifi/nsIDOMMozWifiConnectionInfoEvent.idl
@@ -38,18 +38,8 @@ interface nsIDOMMozWifiConnectionInfoEve
                                                    in boolean aCanBubble,
                                                    in boolean aCancelable,
                                                    in nsIVariant aNetwork,
                                                    in short signalStrength,
                                                    in short relSignalStrength,
                                                    in long linkSpeed,
                                                    in DOMString ipAddress);
 };
-
-dictionary MozWifiConnectionInfoEventInit : EventInit
-{
-  nsIVariant network;
-  short signalStrength;
-  short relSignalStrength;
-  long linkSpeed;
-  DOMString ipAddress;
-};
-
--- a/dom/wifi/nsIDOMMozWifiP2pStatusChangeEvent.idl
+++ b/dom/wifi/nsIDOMMozWifiP2pStatusChangeEvent.idl
@@ -12,13 +12,8 @@ interface nsIDOMMozWifiP2pStatusChangeEv
    */
   readonly attribute DOMString peerAddress;
 
   [noscript] void initMozWifiP2pStatusChangeEvent(in DOMString aType,
                                                   in boolean aCanBubble,
                                                   in boolean aCancelable,
                                                   in DOMString aPeerAddress);
 };
-
-dictionary MozWifiP2pStatusChangeEventInit : EventInit
-{
-  DOMString peerAddress;
-};
--- a/dom/wifi/nsIDOMMozWifiStatusChangeEvent.idl
+++ b/dom/wifi/nsIDOMMozWifiStatusChangeEvent.idl
@@ -22,14 +22,8 @@ interface nsIDOMMozWifiStatusChangeEvent
     readonly attribute DOMString status;
 
     [noscript] void initMozWifiStatusChangeEvent(in DOMString aType,
                                                  in boolean aCanBubble,
                                                  in boolean aCancelable,
                                                  in nsIVariant aNetwork,
                                                  in DOMString aStatus);
 };
-
-dictionary MozWifiStatusChangeEventInit : EventInit
-{
-  nsIVariant network;
-  DOMString  status;
-};
--- a/dom/workers/RuntimeService.cpp
+++ b/dom/workers/RuntimeService.cpp
@@ -143,17 +143,17 @@ static_assert(MAX_WORKERS_PER_DOMAIN >= 
 #endif
 
 #define PREF_WORKERS_LATEST_JS_VERSION "dom.workers.latestJSVersion"
 
 namespace {
 
 const uint32_t kNoIndex = uint32_t(-1);
 
-const JS::ContextOptions kRequiredJSContextOptions =
+const JS::ContextOptions kRequiredContextOptions =
   JS::ContextOptions().setDontReportUncaught(true)
                       .setNoScriptRval(true);
 
 uint32_t gMaxWorkersPerDomain = MAX_WORKERS_PER_DOMAIN;
 
 // Does not hold an owning reference.
 RuntimeService* gRuntimeService = nullptr;
 
@@ -295,17 +295,17 @@ GenerateSharedWorkerKey(const nsACString
     }
   }
 
   aKey.Append('|');
   aKey.Append(aScriptSpec);
 }
 
 void
-LoadJSContextOptions(const char* aPrefName, void* /* aClosure */)
+LoadRuntimeAndContextOptions(const char* aPrefName, void* /* aClosure */)
 {
   AssertIsOnMainThread();
 
   RuntimeService* rts = RuntimeService::GetService();
   if (!rts && !gRuntimeServiceDuringInit) {
     // May be shutting down, just bail.
     return;
   }
@@ -325,61 +325,57 @@ LoadJSContextOptions(const char* aPrefNa
 
 #ifdef JS_GC_ZEAL
   if (prefName.EqualsLiteral(PREF_JS_OPTIONS_PREFIX PREF_GCZEAL) ||
       prefName.EqualsLiteral(PREF_WORKERS_OPTIONS_PREFIX PREF_GCZEAL)) {
     return;
   }
 #endif
 
+  // Runtime options.
+  JS::RuntimeOptions runtimeOptions;
+  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("asmjs"))) {
+    runtimeOptions.setAsmJS(true);
+  }
+  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("typeinference"))) {
+    runtimeOptions.setTypeInference(true);
+  }
+  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("baselinejit"))) {
+    runtimeOptions.setBaseline(true);
+  }
+  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("ion"))) {
+    runtimeOptions.setIon(true);
+  }
+
   // Common options.
-  JS::ContextOptions commonOptions = kRequiredJSContextOptions;
+  JS::ContextOptions commonContextOptions = kRequiredContextOptions;
   if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("strict"))) {
-    commonOptions.setExtraWarnings(true);
+    commonContextOptions.setExtraWarnings(true);
   }
   if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("werror"))) {
-    commonOptions.setWerror(true);
-  }
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("asmjs"))) {
-    commonOptions.setAsmJS(true);
+    commonContextOptions.setWerror(true);
   }
 
   // Content options.
-  JS::ContextOptions contentOptions = commonOptions;
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("baselinejit.content"))) {
-    contentOptions.setBaseline(true);
-  }
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("ion.content"))) {
-    contentOptions.setIon(true);
-  }
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("typeinference.content"))) {
-    contentOptions.setTypeInference(true);
-  }
+  JS::ContextOptions contentContextOptions = commonContextOptions;
 
   // Chrome options.
-  JS::ContextOptions chromeOptions = commonOptions;
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("baselinejit.chrome"))) {
-    chromeOptions.setBaseline(true);
-  }
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("ion.chrome"))) {
-    chromeOptions.setIon(true);
-  }
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("typeinference.chrome"))) {
-    chromeOptions.setTypeInference(true);
-  }
+  JS::ContextOptions chromeContextOptions = commonContextOptions;
 #ifdef DEBUG
   if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("strict.debug"))) {
-    chromeOptions.setExtraWarnings(true);
+    chromeContextOptions.setExtraWarnings(true);
   }
 #endif
 
-  RuntimeService::SetDefaultJSContextOptions(contentOptions, chromeOptions);
+  RuntimeService::SetDefaultRuntimeAndContextOptions(runtimeOptions,
+                                                     contentContextOptions,
+                                                     chromeContextOptions);
 
   if (rts) {
-    rts->UpdateAllWorkerJSContextOptions();
+    rts->UpdateAllWorkerRuntimeAndContextOptions();
   }
 }
 
 #ifdef JS_GC_ZEAL
 void
 LoadGCZealOptions(const char* /* aPrefName */, void* /* aClosure */)
 {
   AssertIsOnMainThread();
@@ -767,16 +763,18 @@ JSContext*
 CreateJSContextForWorker(WorkerPrivate* aWorkerPrivate, JSRuntime* aRuntime)
 {
   aWorkerPrivate->AssertIsOnWorkerThread();
   NS_ASSERTION(!aWorkerPrivate->GetJSContext(), "Already has a context!");
 
   JSSettings settings;
   aWorkerPrivate->CopyJSSettings(settings);
 
+  JS::RuntimeOptionsRef(aRuntime) = settings.runtimeOptions;
+
   JSSettings::JSGCSettingsArray& gcSettings = settings.gcSettings;
 
   // This is the real place where we set the max memory for the runtime.
   for (uint32_t index = 0; index < ArrayLength(gcSettings); index++) {
     const JSSettings::JSGCSetting& setting = gcSettings[index];
     if (setting.IsSet()) {
       NS_ASSERTION(setting.value, "Can't handle 0 values!");
       JS_SetGCParameter(aRuntime, setting.key, setting.value);
@@ -1610,20 +1608,21 @@ nsresult
 RuntimeService::Init()
 {
   AssertIsOnMainThread();
 
   nsLayoutStatics::AddRef();
 
   // Initialize JSSettings.
   if (!sDefaultJSSettings.gcSettings[0].IsSet()) {
-    sDefaultJSSettings.chrome.contextOptions = kRequiredJSContextOptions;
+    sDefaultJSSettings.runtimeOptions = JS::RuntimeOptions();
+    sDefaultJSSettings.chrome.contextOptions = kRequiredContextOptions;
     sDefaultJSSettings.chrome.maxScriptRuntime = -1;
     sDefaultJSSettings.chrome.compartmentOptions.setVersion(JSVERSION_LATEST);
-    sDefaultJSSettings.content.contextOptions = kRequiredJSContextOptions;
+    sDefaultJSSettings.content.contextOptions = kRequiredContextOptions;
     sDefaultJSSettings.content.maxScriptRuntime = MAX_SCRIPT_RUN_TIME_SEC;
 #ifdef JS_GC_ZEAL
     sDefaultJSSettings.gcZealFrequency = JS_DEFAULT_ZEAL_FREQ;
     sDefaultJSSettings.gcZeal = 0;
 #endif
     SetDefaultJSGCSettings(JSGC_MAX_BYTES, WORKER_DEFAULT_RUNTIME_HEAPSIZE);
     SetDefaultJSGCSettings(JSGC_ALLOCATION_THRESHOLD,
                            WORKER_DEFAULT_ALLOCATION_THRESHOLD);
@@ -1688,23 +1687,23 @@ RuntimeService::Init()
                                         nullptr)) ||
 #endif
 #if DUMP_CONTROLLED_BY_PREF
       NS_FAILED(Preferences::RegisterCallbackAndCall(
                                   WorkerPrefChanged,
                                   PREF_DOM_WINDOW_DUMP_ENABLED,
                                   reinterpret_cast<void *>(WORKERPREF_DUMP))) ||
 #endif
-      NS_FAILED(Preferences::RegisterCallback(LoadJSContextOptions,
+      NS_FAILED(Preferences::RegisterCallback(LoadRuntimeAndContextOptions,
                                               PREF_JS_OPTIONS_PREFIX,
                                               nullptr)) ||
       NS_FAILED(Preferences::RegisterCallbackAndCall(
-                                                    LoadJSContextOptions,
-                                                    PREF_WORKERS_OPTIONS_PREFIX,
-                                                    nullptr)) ||
+                                                   LoadRuntimeAndContextOptions,
+                                                   PREF_WORKERS_OPTIONS_PREFIX,
+                                                   nullptr)) ||
       NS_FAILED(Preferences::RegisterCallbackAndCall(
                                                  JSVersionChanged,
                                                  PREF_WORKERS_LATEST_JS_VERSION,
                                                  nullptr))) {
     NS_WARNING("Failed to register pref callbacks!");
   }
 
   NS_ASSERTION(gRuntimeServiceDuringInit == this, "Should be 'this'!");
@@ -1841,20 +1840,20 @@ RuntimeService::Cleanup()
   }
 
   NS_ASSERTION(!mWindowMap.Count(), "All windows should have been released!");
 
   if (mObserved) {
     if (NS_FAILED(Preferences::UnregisterCallback(JSVersionChanged,
                                                   PREF_WORKERS_LATEST_JS_VERSION,
                                                   nullptr)) ||
-        NS_FAILED(Preferences::UnregisterCallback(LoadJSContextOptions,
+        NS_FAILED(Preferences::UnregisterCallback(LoadRuntimeAndContextOptions,
                                                   PREF_JS_OPTIONS_PREFIX,
                                                   nullptr)) ||
-        NS_FAILED(Preferences::UnregisterCallback(LoadJSContextOptions,
+        NS_FAILED(Preferences::UnregisterCallback(LoadRuntimeAndContextOptions,
                                                   PREF_WORKERS_OPTIONS_PREFIX,
                                                   nullptr)) ||
 #if DUMP_CONTROLLED_BY_PREF
         NS_FAILED(Preferences::UnregisterCallback(
                                   WorkerPrefChanged,
                                   PREF_DOM_WINDOW_DUMP_ENABLED,
                                   reinterpret_cast<void *>(WORKERPREF_DUMP))) ||
 #endif
@@ -2226,19 +2225,20 @@ RuntimeService::NoteIdleThread(WorkerThr
   // Schedule timer.
   MOZ_ALWAYS_TRUE(NS_SUCCEEDED(mIdleThreadTimer->InitWithFuncCallback(
                                                  ShutdownIdleThreads, nullptr,
                                                  IDLE_THREAD_TIMEOUT_SEC * 1000,
                                                  nsITimer::TYPE_ONE_SHOT)));
 }
 
 void
-RuntimeService::UpdateAllWorkerJSContextOptions()
+RuntimeService::UpdateAllWorkerRuntimeAndContextOptions()
 {
-  BROADCAST_ALL_WORKERS(UpdateJSContextOptions,
+  BROADCAST_ALL_WORKERS(UpdateRuntimeAndContextOptions,
+                        sDefaultJSSettings.runtimeOptions,
                         sDefaultJSSettings.content.contextOptions,
                         sDefaultJSSettings.chrome.contextOptions);
 }
 
 void
 RuntimeService::UpdateAllWorkerPreference(WorkerPreference aPref, bool aValue)
 {
   BROADCAST_ALL_WORKERS(UpdatePreference, aPref, aValue);
--- a/dom/workers/RuntimeService.h
+++ b/dom/workers/RuntimeService.h
@@ -169,26 +169,29 @@ public:
   static void
   GetDefaultPreferences(bool aPreferences[WORKERPREF_COUNT])
   {
     AssertIsOnMainThread();
     memcpy(aPreferences, sDefaultPreferences, WORKERPREF_COUNT * sizeof(bool));
   }
 
   static void
-  SetDefaultJSContextOptions(const JS::ContextOptions& aContentOptions,
-                             const JS::ContextOptions& aChromeOptions)
+  SetDefaultRuntimeAndContextOptions(
+                                    const JS::RuntimeOptions& aRuntimeOptions,
+                                    const JS::ContextOptions& aContentCxOptions,
+                                    const JS::ContextOptions& aChromeCxOptions)
   {
     AssertIsOnMainThread();
-    sDefaultJSSettings.content.contextOptions = aContentOptions;
-    sDefaultJSSettings.chrome.contextOptions = aChromeOptions;
+    sDefaultJSSettings.runtimeOptions = aRuntimeOptions;
+    sDefaultJSSettings.content.contextOptions = aContentCxOptions;
+    sDefaultJSSettings.chrome.contextOptions = aChromeCxOptions;
   }
 
   void
-  UpdateAllWorkerJSContextOptions();
+  UpdateAllWorkerRuntimeAndContextOptions();
 
   void
   UpdateAllWorkerPreference(WorkerPreference aPref, bool aValue);
 
   static void
   SetDefaultJSGCSettings(JSGCParamKey aKey, uint32_t aValue)
   {
     AssertIsOnMainThread();
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -1510,35 +1510,42 @@ private:
       mTimer->Cancel();
       mTimer = nullptr;
     }
 
     return true;
   }
 };
 
-class UpdateJSContextOptionsRunnable MOZ_FINAL : public WorkerControlRunnable
+class UpdateRuntimeAndContextOptionsRunnable MOZ_FINAL : public WorkerControlRunnable
 {
-  JS::ContextOptions mContentOptions;
-  JS::ContextOptions mChromeOptions;
+  JS::RuntimeOptions mRuntimeOptions;
+  JS::ContextOptions mContentCxOptions;
+  JS::ContextOptions mChromeCxOptions;
 
 public:
-  UpdateJSContextOptionsRunnable(WorkerPrivate* aWorkerPrivate,
-                                 const JS::ContextOptions& aContentOptions,
-                                 const JS::ContextOptions& aChromeOptions)
+  UpdateRuntimeAndContextOptionsRunnable(
+                                    WorkerPrivate* aWorkerPrivate,
+                                    const JS::RuntimeOptions& aRuntimeOptions,
+                                    const JS::ContextOptions& aContentCxOptions,
+                                    const JS::ContextOptions& aChromeCxOptions)
   : WorkerControlRunnable(aWorkerPrivate, WorkerThreadUnchangedBusyCount),
-    mContentOptions(aContentOptions), mChromeOptions(aChromeOptions)
+    mRuntimeOptions(aRuntimeOptions),
+    mContentCxOptions(aContentCxOptions),
+    mChromeCxOptions(aChromeCxOptions)
   { }
 
 private:
   virtual bool
   WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) MOZ_OVERRIDE
   {
-    aWorkerPrivate->UpdateJSContextOptionsInternal(aCx, mContentOptions,
-                                                   mChromeOptions);
+    aWorkerPrivate->UpdateRuntimeAndContextOptionsInternal(aCx,
+                                                           mRuntimeOptions,
+                                                           mContentCxOptions,
+                                                           mChromeCxOptions);
     return true;
   }
 };
 
 class UpdatePreferenceRunnable MOZ_FINAL : public WorkerControlRunnable
 {
   WorkerPreference mPref;
   bool mValue;
@@ -2838,32 +2845,36 @@ WorkerPrivateParent<Derived>::GetInnerWi
   AssertIsOnMainThread();
   NS_ASSERTION(!mLoadInfo.mWindow || mLoadInfo.mWindow->IsInnerWindow(),
                "Outer window?");
   return mLoadInfo.mWindow ? mLoadInfo.mWindow->WindowID() : 0;
 }
 
 template <class Derived>
 void
-WorkerPrivateParent<Derived>::UpdateJSContextOptions(
-                                      JSContext* aCx,
-                                      const JS::ContextOptions& aContentOptions,
-                                      const JS::ContextOptions& aChromeOptions)
+WorkerPrivateParent<Derived>::UpdateRuntimeAndContextOptions(
+                                    JSContext* aCx,
+                                    const JS::RuntimeOptions& aRuntimeOptions,
+                                    const JS::ContextOptions& aContentCxOptions,
+                                    const JS::ContextOptions& aChromeCxOptions)
 {
   AssertIsOnParentThread();
 
   {
     MutexAutoLock lock(mMutex);
-    mJSSettings.content.contextOptions = aContentOptions;
-    mJSSettings.chrome.contextOptions = aChromeOptions;
-  }
-
-  nsRefPtr<UpdateJSContextOptionsRunnable> runnable =
-    new UpdateJSContextOptionsRunnable(ParentAsWorkerPrivate(), aContentOptions,
-                                       aChromeOptions);
+    mJSSettings.runtimeOptions = aRuntimeOptions;
+    mJSSettings.content.contextOptions = aContentCxOptions;
+    mJSSettings.chrome.contextOptions = aChromeCxOptions;
+  }
+
+  nsRefPtr<UpdateRuntimeAndContextOptionsRunnable> runnable =
+    new UpdateRuntimeAndContextOptionsRunnable(ParentAsWorkerPrivate(),
+                                               aRuntimeOptions,
+                                               aContentCxOptions,
+                                               aChromeCxOptions);
   if (!runnable->Dispatch(aCx)) {
     NS_WARNING("Failed to update worker context options!");
     JS_ClearPendingException(aCx);
   }
 }
 
 template <class Derived>
 void
@@ -5498,27 +5509,31 @@ WorkerPrivate::RescheduleTimeoutTimer(JS
     JS_ReportError(aCx, "Failed to start timer!");
     return false;
   }
 
   return true;
 }
 
 void
-WorkerPrivate::UpdateJSContextOptionsInternal(JSContext* aCx,
-                                              const JS::ContextOptions& aContentOptions,
-                                              const JS::ContextOptions& aChromeOptions)
+WorkerPrivate::UpdateRuntimeAndContextOptionsInternal(
+                                    JSContext* aCx,
+                                    const JS::RuntimeOptions& aRuntimeOptions,
+                                    const JS::ContextOptions& aContentCxOptions,
+                                    const JS::ContextOptions& aChromeCxOptions)
 {
   AssertIsOnWorkerThread();
 
-  JS::ContextOptionsRef(aCx) = IsChromeWorker() ? aChromeOptions : aContentOptions;
+  JS::RuntimeOptionsRef(aCx) = aRuntimeOptions;
+  JS::ContextOptionsRef(aCx) = IsChromeWorker() ? aChromeCxOptions : aContentCxOptions;
 
   for (uint32_t index = 0; index < mChildWorkers.Length(); index++) {
-    mChildWorkers[index]->UpdateJSContextOptions(aCx, aContentOptions,
-                                                 aChromeOptions);
+    mChildWorkers[index]->UpdateRuntimeAndContextOptions(aCx, aRuntimeOptions,
+                                                         aContentCxOptions,
+                                                         aChromeCxOptions);
   }
 }
 
 void
 WorkerPrivate::UpdatePreferenceInternal(JSContext* aCx, WorkerPreference aPref, bool aValue)
 {
   AssertIsOnWorkerThread();
   MOZ_ASSERT(aPref >= 0 && aPref < WORKERPREF_COUNT);
--- a/dom/workers/WorkerPrivate.h
+++ b/dom/workers/WorkerPrivate.h
@@ -384,18 +384,20 @@ public:
                                uint64_t aMessagePortSerial,
                                JSAutoStructuredCloneBuffer&& aBuffer,
                                nsTArray<nsCOMPtr<nsISupports>>& aClonedObjects);
 
   uint64_t
   GetInnerWindowId();
 
   void
-  UpdateJSContextOptions(JSContext* aCx, const JS::ContextOptions& aChromeOptions,
-                         const JS::ContextOptions& aContentOptions);
+  UpdateRuntimeAndContextOptions(JSContext* aCx,
+                                 const JS::RuntimeOptions& aRuntimeOptions,
+                                 const JS::ContextOptions& aContentCxOptions,
+                                 const JS::ContextOptions& aChromeCxOptions);
 
   void
   UpdatePreference(JSContext* aCx, WorkerPreference aPref, bool aValue);
 
   void
   UpdateJSWorkerMemoryParameter(JSContext* aCx, JSGCParamKey key,
                                 uint32_t value);
 
@@ -901,18 +903,21 @@ public:
   void
   CloseHandlerFinished()
   {
     AssertIsOnWorkerThread();
     mCloseHandlerFinished = true;
   }
 
   void
-  UpdateJSContextOptionsInternal(JSContext* aCx, const JS::ContextOptions& aContentOptions,
-                                 const JS::ContextOptions& aChromeOptions);
+  UpdateRuntimeAndContextOptionsInternal(
+                                    JSContext* aCx,
+                                    const JS::RuntimeOptions& aRuntimeOptions,
+                                    const JS::ContextOptions& aContentCxOptions,
+                                    const JS::ContextOptions& aChromeCxOptions);
 
   void
   UpdatePreferenceInternal(JSContext* aCx, WorkerPreference aPref, bool aValue);
 
   void
   UpdateJSWorkerMemoryParameterInternal(JSContext* aCx, JSGCParamKey key, uint32_t aValue);
 
   enum WorkerRanOrNot {
--- a/dom/workers/Workers.h
+++ b/dom/workers/Workers.h
@@ -102,16 +102,17 @@ struct JSSettings
     JSContentChromeSettings()
     : contextOptions(), compartmentOptions(), maxScriptRuntime(0)
     { }
   };
 
   JSContentChromeSettings chrome;
   JSContentChromeSettings content;
   JSGCSettingsArray gcSettings;
+  JS::RuntimeOptions runtimeOptions;
 
 #ifdef JS_GC_ZEAL
   uint8_t gcZeal;
   uint32_t gcZealFrequency;
 #endif
 
   JSSettings()
 #ifdef JS_GC_ZEAL
--- a/gfx/2d/2D.h
+++ b/gfx/2d/2D.h
@@ -342,16 +342,23 @@ class DataSourceSurface : public SourceS
 {
 public:
   MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(DataSourceSurface)
   DataSourceSurface()
     : mIsMapped(false)
   {
   }
 
+#ifdef DEBUG
+  virtual ~DataSourceSurface()
+  {
+    MOZ_ASSERT(!mIsMapped, "Someone forgot to call Unmap()");
+  }
+#endif
+
   struct MappedSurface {
     uint8_t *mData;
     int32_t mStride;
   };
 
   enum MapType {
     READ,
     WRITE,
new file mode 100644
--- /dev/null
+++ b/gfx/2d/DataSurfaceHelpers.cpp
@@ -0,0 +1,86 @@
+/* -*- Mode: C++; tab-width: 20; 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/. */
+
+#include "2D.h"
+#include "DataSurfaceHelpers.h"
+
+namespace mozilla {
+namespace gfx {
+
+void
+ConvertBGRXToBGRA(uint8_t* aData, const IntSize &aSize, int32_t aStride)
+{
+  uint32_t* pixel = reinterpret_cast<uint32_t*>(aData);
+
+  for (int row = 0; row < aSize.height; ++row) {
+    for (int column = 0; column < aSize.width; ++column) {
+#ifdef IS_BIG_ENDIAN
+      pixel[column] |= 0x000000FF;
+#else
+      pixel[column] |= 0xFF000000;
+#endif
+    }
+    pixel += (aStride/4);
+  }
+}
+
+void
+CopySurfaceDataToPackedArray(uint8_t* aSrc, uint8_t* aDst, IntSize aSrcSize,
+                             int32_t aSrcStride, int32_t aBytesPerPixel)
+{
+  MOZ_ASSERT(aBytesPerPixel > 0,
+             "Negative stride for aDst not currently supported");
+
+  int packedStride = aSrcSize.width * aBytesPerPixel;
+
+  if (aSrcStride == packedStride) {
+    // aSrc is already packed, so we can copy with a single memcpy.
+    memcpy(aDst, aSrc, packedStride * aSrcSize.height);
+  } else {
+    // memcpy one row at a time.
+    for (int row = 0; row < aSrcSize.height; ++row) {
+      memcpy(aDst, aSrc, packedStride);
+      aSrc += aSrcStride;
+      aDst += packedStride;
+    }
+  }
+}
+
+uint8_t*
+SurfaceToPackedBGRA(DataSourceSurface *aSurface)
+{
+  SurfaceFormat format = aSurface->GetFormat();
+  if (format != SurfaceFormat::B8G8R8A8 && format != SurfaceFormat::B8G8R8X8) {
+    return nullptr;
+  }
+
+  IntSize size = aSurface->GetSize();
+
+  uint8_t* imageBuffer = new (std::nothrow) uint8_t[size.width * size.height * sizeof(uint32_t)];
+  if (!imageBuffer) {
+    return nullptr;
+  }
+
+  DataSourceSurface::MappedSurface map;
+  if (!aSurface->Map(DataSourceSurface::MapType::READ, &map)) {
+    delete [] imageBuffer;
+    return nullptr;
+  }
+
+  CopySurfaceDataToPackedArray(map.mData, imageBuffer, size,
+                               map.mStride, 4 * sizeof(uint8_t));
+
+  aSurface->Unmap();
+
+  if (format == SurfaceFormat::B8G8R8X8) {
+    // Convert BGRX to BGRA by setting a to 255.
+    ConvertBGRXToBGRA(reinterpret_cast<uint8_t *>(imageBuffer), size, size.width * sizeof(uint32_t));
+  }
+
+  return imageBuffer;
+}
+
+}
+}
--- a/gfx/2d/DataSurfaceHelpers.h
+++ b/gfx/2d/DataSurfaceHelpers.h
@@ -5,71 +5,30 @@
 
 #pragma once
 
 #include "2D.h"
 
 namespace mozilla {
 namespace gfx {
 
-static inline void
-ConvertBGRXToBGRA(uint8_t* aData, const IntSize &aSize, int32_t aStride)
-{
-  uint32_t* pixel = reinterpret_cast<uint32_t*>(aData);
+void
+ConvertBGRXToBGRA(uint8_t* aData, const IntSize &aSize, int32_t aStride);
 
-  for (int row = 0; row < aSize.height; ++row) {
-    for (int column = 0; column < aSize.width; ++column) {
-#ifdef IS_BIG_ENDIAN
-      pixel[column] |= 0x000000FF;
-#else
-      pixel[column] |= 0xFF000000;
-#endif
-    }
-    pixel += (aStride/4);
-  }
-}
+/**
+ * Copy the pixel data from aSrc and pack it into aDst. aSrcSize, aSrcStride
+ * and aBytesPerPixel give the size, stride and bytes per pixel for aSrc's
+ * surface. Callers are responsible for making sure that aDst is big enough to
+ * contain |aSrcSize.width * aSrcSize.height * aBytesPerPixel| bytes.
+ */
+void
+CopySurfaceDataToPackedArray(uint8_t* aSrc, uint8_t* aDst, IntSize aSrcSize,
+                             int32_t aSrcStride, int32_t aBytesPerPixel);
 
 /**
  * Convert aSurface to a packed buffer in BGRA format. The pixel data is
  * returned in a buffer allocated with new uint8_t[].
  */
-inline uint8_t *
-SurfaceToPackedBGRA(DataSourceSurface *aSurface)
-{
-  SurfaceFormat format = aSurface->GetFormat();
-  if (format != SurfaceFormat::B8G8R8A8 && format != SurfaceFormat::B8G8R8X8) {
-    return nullptr;
-  }
-
-  IntSize size = aSurface->GetSize();
-
-  uint8_t* imageBuffer = new (std::nothrow) uint8_t[size.width * size.height * sizeof(uint32_t)];
-  if (!imageBuffer) {
-    return nullptr;
-  }
-
-  size_t stride = aSurface->Stride();
-
-  uint32_t* src = reinterpret_cast<uint32_t*>(aSurface->GetData());
-  uint32_t* dst = reinterpret_cast<uint32_t*>(imageBuffer);
-
-  if (stride == size.width * sizeof(uint32_t)) {
-    // DataSourceSurface is already packed. We can use memcpy.
-    memcpy(dst, src, size.width * size.height * sizeof(uint32_t));
-  } else {
-    for (int row = 0; row < size.height; ++row) {
-      for (int column = 0; column < size.width; ++column) {
-        *dst++ = src[column];
-      }
-      src += (stride/4);
-    }
-  }
-
-  if (format == SurfaceFormat::B8G8R8X8) {
-    // Convert BGRX to BGRA by setting a to 255.
-    ConvertBGRXToBGRA(reinterpret_cast<uint8_t *>(imageBuffer), size, size.width * sizeof(uint32_t));
-  }
-
-  return imageBuffer;
-}
+uint8_t*
+SurfaceToPackedBGRA(DataSourceSurface *aSurface);
 
 }
 }
--- a/gfx/2d/SourceSurfaceD2D1.cpp
+++ b/gfx/2d/SourceSurfaceD2D1.cpp
@@ -162,16 +162,19 @@ DataSourceSurfaceD2D1::Map(MapType aMapT
 
   mIsMapped = true;
   return true;
 }
 
 void
 DataSourceSurfaceD2D1::Unmap()
 {
+  MOZ_ASSERT(mIsMapped);
+
+  mIsMapped = false;
   mBitmap->Unmap();
 }
 
 int32_t
 DataSourceSurfaceD2D1::Stride()
 {
   EnsureMapped();
 
--- a/gfx/2d/SourceSurfaceD2DTarget.cpp
+++ b/gfx/2d/SourceSurfaceD2DTarget.cpp
@@ -268,25 +268,27 @@ DataSourceSurfaceD2DTarget::Map(MapType 
 
   if (FAILED(hr)) {
     gfxWarning() << "Texture map failed with code: " << hr;
     return false;
   }
 
   aMappedSurface->mData = (uint8_t*)map.pData;
   aMappedSurface->mStride = map.RowPitch;
+  mIsMapped = true;
 
   return true;
 }
 
 void
 DataSourceSurfaceD2DTarget::Unmap()
 {
   MOZ_ASSERT(mIsMapped);
 
+  mIsMapped = false;
   mTexture->Unmap(0);
 }
 
 void
 DataSourceSurfaceD2DTarget::EnsureMapped()
 {
   // Do not use GetData() after having used Map!
   MOZ_ASSERT(!mIsMapped);
--- a/gfx/2d/moz.build
+++ b/gfx/2d/moz.build
@@ -97,16 +97,17 @@ if CONFIG['INTEL_ARCHITECTURE']:
         if CONFIG['SOLARIS_SUNPRO_CXX']:
             SOURCES['BlurSSE2.cpp'].flags += ['-xarch=sse2', '-xO4']
             SOURCES['FilterProcessingSSE2.cpp'].flags += ['-xarch=sse2', '-xO4']
             SOURCES['ImageScalingSSE2.cpp'].flags += ['-xarch=sse2', '-xO4']
 
 UNIFIED_SOURCES += [
     'Blur.cpp',
     'DataSourceSurface.cpp',
+    'DataSurfaceHelpers.cpp',
     'DrawEventRecorder.cpp',
     'DrawTargetCairo.cpp',
     'DrawTargetDual.cpp',
     'DrawTargetRecording.cpp',
     'Factory.cpp',
     'FilterNodeSoftware.cpp',
     'FilterProcessing.cpp',
     'FilterProcessingScalar.cpp',
--- a/gfx/gl/GLScreenBuffer.cpp
+++ b/gfx/gl/GLScreenBuffer.cpp
@@ -485,16 +485,17 @@ GLScreenBuffer::Readback(SharedSurface_G
   DataSourceSurface::MappedSurface ms;
   dest->Map(DataSourceSurface::MapType::READ, &ms);
   nsRefPtr<gfxImageSurface> wrappedDest =
     new gfxImageSurface(ms.mData,
                         ThebesIntSize(dest->GetSize()),
                         ms.mStride,
                         SurfaceFormatToImageFormat(dest->GetFormat()));
   DeprecatedReadback(src, wrappedDest);
+  dest->Unmap();
 }
 
 void
 GLScreenBuffer::DeprecatedReadback(SharedSurface_GL* src, gfxImageSurface* dest)
 {
     MOZ_ASSERT(src && dest);
     MOZ_ASSERT(ToIntSize(dest->GetSize()) == src->Size());
     MOZ_ASSERT(dest->Format() == (src->HasAlpha() ? gfxImageFormat::ARGB32
--- a/gfx/ipc/GfxMessageUtils.h
+++ b/gfx/ipc/GfxMessageUtils.h
@@ -614,18 +614,16 @@ struct ParamTraits<mozilla::layers::Fram
     WriteParam(aMsg, aParam.mResolution);
     WriteParam(aMsg, aParam.mCumulativeResolution);
     WriteParam(aMsg, aParam.mZoom);
     WriteParam(aMsg, aParam.mDevPixelsPerCSSPixel);
     WriteParam(aMsg, aParam.mMayHaveTouchListeners);
     WriteParam(aMsg, aParam.mPresShellId);
     WriteParam(aMsg, aParam.mIsRoot);
     WriteParam(aMsg, aParam.mHasScrollgrab);
-    WriteParam(aMsg, aParam.mDisableScrollingX);
-    WriteParam(aMsg, aParam.mDisableScrollingY);
     WriteParam(aMsg, aParam.mUpdateScrollOffset);
     WriteParam(aMsg, aParam.mScrollGeneration);
     WriteParam(aMsg, aParam.mContentDescription);
   }
 
   static bool Read(const Message* aMsg, void** aIter, paramType* aResult)
   {
     return (ReadParam(aMsg, aIter, &aResult->mScrollableRect) &&
@@ -638,18 +636,16 @@ struct ParamTraits<mozilla::layers::Fram
             ReadParam(aMsg, aIter, &aResult->mResolution) &&
             ReadParam(aMsg, aIter, &aResult->mCumulativeResolution) &&
             ReadParam(aMsg, aIter, &aResult->mZoom) &&
             ReadParam(aMsg, aIter, &aResult->mDevPixelsPerCSSPixel) &&
             ReadParam(aMsg, aIter, &aResult->mMayHaveTouchListeners) &&
             ReadParam(aMsg, aIter, &aResult->mPresShellId) &&
             ReadParam(aMsg, aIter, &aResult->mIsRoot) &&
             ReadParam(aMsg, aIter, &aResult->mHasScrollgrab) &&
-            ReadParam(aMsg, aIter, &aResult->mDisableScrollingX) &&
-            ReadParam(aMsg, aIter, &aResult->mDisableScrollingY) &&
             ReadParam(aMsg, aIter, &aResult->mUpdateScrollOffset) &&
             ReadParam(aMsg, aIter, &aResult->mScrollGeneration) &&
             ReadParam(aMsg, aIter, &aResult->mContentDescription));
   }
 };
 
 template<>
 struct ParamTraits<mozilla::layers::TextureFactoryIdentifier>
--- a/gfx/layers/FrameMetrics.h
+++ b/gfx/layers/FrameMetrics.h
@@ -57,18 +57,16 @@ public:
     , mResolution(1)
     , mCumulativeResolution(1)
     , mZoom(1)
     , mDevPixelsPerCSSPixel(1)
     , mPresShellId(-1)
     , mMayHaveTouchListeners(false)
     , mIsRoot(false)
     , mHasScrollgrab(false)
-    , mDisableScrollingX(false)
-    , mDisableScrollingY(false)
     , mUpdateScrollOffset(false)
     , mScrollGeneration(0)
   {}
 
   // Default copy ctor and operator= are fine
 
   bool operator==(const FrameMetrics& aOther) const
   {
@@ -83,18 +81,16 @@ public:
            mScrollableRect.IsEqualEdges(aOther.mScrollableRect) &&
            mResolution == aOther.mResolution &&
            mCumulativeResolution == aOther.mCumulativeResolution &&
            mDevPixelsPerCSSPixel == aOther.mDevPixelsPerCSSPixel &&
            mMayHaveTouchListeners == aOther.mMayHaveTouchListeners &&
            mPresShellId == aOther.mPresShellId &&
            mIsRoot == aOther.mIsRoot &&
            mHasScrollgrab == aOther.mHasScrollgrab &&
-           mDisableScrollingX == aOther.mDisableScrollingX &&
-           mDisableScrollingY == aOther.mDisableScrollingY &&
            mUpdateScrollOffset == aOther.mUpdateScrollOffset;
   }
   bool operator!=(const FrameMetrics& aOther) const
   {
     return !operator==(aOther);
   }
 
   bool IsDefault() const
@@ -299,36 +295,16 @@ public:
 
   // Whether or not this is the root scroll frame for the root content document.
   bool mIsRoot;
 
   // Whether or not this frame is for an element marked 'scrollgrab'.
   bool mHasScrollgrab;
 
 public:
-  bool GetDisableScrollingX() const
-  {
-    return mDisableScrollingX;
-  }
-
-  void SetDisableScrollingX(bool aDisableScrollingX)
-  {
-    mDisableScrollingX = aDisableScrollingX;
-  }
-
-  bool GetDisableScrollingY() const
-  {
-    return mDisableScrollingY;
-  }
-
-  void SetDisableScrollingY(bool aDisableScrollingY)
-  {
-    mDisableScrollingY = aDisableScrollingY;
-  }
-
   void SetScrollOffsetUpdated(uint32_t aScrollGeneration)
   {
     mUpdateScrollOffset = true;
     mScrollGeneration = aScrollGeneration;
   }
 
   bool GetScrollOffsetUpdated() const
   {
@@ -349,21 +325,16 @@ public:
   {
     mContentDescription = aContentDescription;
   }
 
 private:
   // New fields from now on should be made private and old fields should
   // be refactored to be private.
 
-  // Allow disabling scrolling in individual axis to support
-  // |overflow: hidden|.
-  bool mDisableScrollingX;
-  bool mDisableScrollingY;
-
   // Whether mScrollOffset was updated by something other than the APZ code, and
   // if the APZC receiving this metrics should update its local copy.
   bool mUpdateScrollOffset;
   // The scroll generation counter used to acknowledge the scroll offset update.
   uint32_t mScrollGeneration;
 
   // A description of the content element corresponding to this frame.
   // This is empty unless the apz.printtree pref is turned on.
--- a/gfx/layers/GrallocImages.cpp
+++ b/gfx/layers/GrallocImages.cpp
@@ -348,39 +348,45 @@ GrallocImage::GetAsSourceSurface()
     uint8_t* buffer_as_bytes = static_cast<uint8_t*>(buffer);
     ConvertYVU420SPToRGB565(buffer, alignedWidth,
                             buffer_as_bytes + uvOffset, uvStride,
                             mappedSurface.mData,
                             width, height);
 
     surface->Unmap();
     return surface;
-  } else if (format == HAL_PIXEL_FORMAT_YCrCb_420_SP) {
+  }
+
+  if (format == HAL_PIXEL_FORMAT_YCrCb_420_SP) {
     uint32_t uvOffset = height * width;
     ConvertYVU420SPToRGB565(buffer, width,
                             buffer + uvOffset, width,
                             mappedSurface.mData,
                             width, height);
 
     surface->Unmap();
     return surface;
-  } else if (format == HAL_PIXEL_FORMAT_YV12) {
+  }
+
+  if (format == HAL_PIXEL_FORMAT_YV12) {
     gfx::ConvertYCbCrToRGB(mData,
                            surface->GetFormat(),
                            mSize,
                            surface->GetData(),
                            surface->Stride());
+    surface->Unmap();
     return surface;
   }
 
   android::ColorConverter colorConverter((OMX_COLOR_FORMATTYPE)omxFormat,
                                          OMX_COLOR_Format16bitRGB565);
 
   if (!colorConverter.isValid()) {
     NS_WARNING("Invalid color conversion");
+    surface->Unmap();
     return nullptr;
   }
 
   rv = colorConverter.convert(buffer, width, height,
                               0, 0, width - 1, height - 1 /* source crop */,
                               mappedSurface.mData, width, height,
                               0, 0, width - 1, height - 1 /* dest crop */);
 
--- a/gfx/layers/ipc/AsyncPanZoomController.cpp
+++ b/gfx/layers/ipc/AsyncPanZoomController.cpp
@@ -283,21 +283,21 @@ static int gAsyncScrollTimeout = 300;
 static bool gCrossSlideEnabled = false;
 
 /** 
  * Pref that allows or disallows checkerboarding
  */
 static bool gAllowCheckerboarding = true;
 
 /**
- * Pref that enables enlarging of the displayport along one axis when its
- * opposite's scrollable rect is within the composition bounds. That is, we
- * don't need to pad the opposite axis.
+ * Pref that enables enlarging of the displayport along one axis when the
+ * generated displayport's size is beyond that of the scrollable rect on the
+ * opposite axis.
  */
-static bool gEnlargeDisplayPortWhenOnlyScrollable = false;
+static bool gEnlargeDisplayPortWhenClipped = false;
 
 /**
  * Is aAngle within the given threshold of the horizontal axis?
  * @param aAngle an angle in radians in the range [0, pi]
  * @param aThreshold an angle in radians in the range [0, pi/2]
  */
 static bool IsCloseToHorizontal(float aAngle, float aThreshold)
 {
@@ -414,18 +414,18 @@ AsyncPanZoomController::InitializeGlobal
   Preferences::AddFloatVarCache(&gYSkateSizeMultiplier, "apz.y_skate_size_multiplier", gYSkateSizeMultiplier);
   Preferences::AddFloatVarCache(&gXStationarySizeMultiplier, "apz.x_stationary_size_multiplier", gXStationarySizeMultiplier);
   Preferences::AddFloatVarCache(&gYStationarySizeMultiplier, "apz.y_stationary_size_multiplier", gYStationarySizeMultiplier);
   Preferences::AddIntVarCache(&gAsyncScrollThrottleTime, "apz.asyncscroll.throttle", gAsyncScrollThrottleTime);
   Preferences::AddIntVarCache(&gAsyncScrollTimeout, "apz.asyncscroll.timeout", gAsyncScrollTimeout);
   Preferences::AddBoolVarCache(&gCrossSlideEnabled, "apz.cross_slide.enabled", gCrossSlideEnabled);
   Preferences::AddIntVarCache(&gAxisLockMode, "apz.axis_lock_mode", gAxisLockMode);
   Preferences::AddBoolVarCache(&gAllowCheckerboarding, "apz.allow-checkerboarding", gAllowCheckerboarding);
-  Preferences::AddBoolVarCache(&gEnlargeDisplayPortWhenOnlyScrollable, "apz.enlarge_displayport_when_only_scrollable",
-    gEnlargeDisplayPortWhenOnlyScrollable);
+  Preferences::AddBoolVarCache(&gEnlargeDisplayPortWhenClipped, "apz.enlarge_displayport_when_clipped",
+    gEnlargeDisplayPortWhenClipped);
 
   gComputedTimingFunction = new ComputedTimingFunction();
   gComputedTimingFunction->Init(
     nsTimingFunction(NS_STYLE_TRANSITION_TIMING_FUNCTION_EASE));
   ClearOnShutdown(&gComputedTimingFunction);
 }
 
 AsyncPanZoomController::AsyncPanZoomController(uint64_t aLayersId,
@@ -787,17 +787,17 @@ nsEventStatus AsyncPanZoomController::On
 
 nsEventStatus AsyncPanZoomController::OnScaleBegin(const PinchGestureInput& aEvent) {
   APZC_LOG("%p got a scale-begin in state %d\n", this, mState);
 
   if (!TouchActionAllowZoom()) {
     return nsEventStatus_eIgnore;
   }
 
-  if (!AllowZoom()) {
+  if (!mZoomConstraints.mAllowZoom) {
     return nsEventStatus_eConsumeNoDefault;
   }
 
   SetState(PINCHING);
   mLastZoomFocus = aEvent.mFocusPoint - mFrameMetrics.mCompositionBounds.TopLeft();
 
   return nsEventStatus_eConsumeNoDefault;
 }
@@ -947,17 +947,17 @@ nsEventStatus AsyncPanZoomController::On
   return nsEventStatus_eIgnore;
 }
 
 nsEventStatus AsyncPanZoomController::OnSingleTapUp(const TapGestureInput& aEvent) {
   APZC_LOG("%p got a single-tap-up in state %d\n", this, mState);
   nsRefPtr<GeckoContentController> controller = GetGeckoContentController();
   // If mZoomConstraints.mAllowDoubleTapZoom is true we wait for a call to OnSingleTapConfirmed before
   // sending event to content
-  if (controller && !AllowDoubleTapZoom()) {
+  if (controller && !mZoomConstraints.mAllowDoubleTapZoom) {
     int32_t modifiers = WidgetModifiersToDOMModifiers(aEvent.modifiers);
     CSSIntPoint geckoScreenPoint;
     if (ConvertToGecko(aEvent.mPoint, &geckoScreenPoint)) {
       // Because this may be being running as part of APZCTreeManager::ReceiveInputEvent,
       // calling controller->HandleSingleTap directly might mean that content receives
       // the single tap message before the corresponding touch-up. To avoid that we
       // schedule the singletap message to run on the next spin of the event loop.
       // See bug 965381 for the issue this was causing.
@@ -988,17 +988,17 @@ nsEventStatus AsyncPanZoomController::On
   }
   return nsEventStatus_eIgnore;
 }
 
 nsEventStatus AsyncPanZoomController::OnDoubleTap(const TapGestureInput& aEvent) {
   APZC_LOG("%p got a double-tap in state %d\n", this, mState);
   nsRefPtr<GeckoContentController> controller = GetGeckoContentController();
   if (controller) {
-    if (AllowDoubleTapZoom()) {
+    if (mZoomConstraints.mAllowDoubleTapZoom) {
       int32_t modifiers = WidgetModifiersToDOMModifiers(aEvent.modifiers);
       CSSIntPoint geckoScreenPoint;
       if (ConvertToGecko(aEvent.mPoint, &geckoScreenPoint)) {
         controller->HandleDoubleTap(geckoScreenPoint, modifiers, GetGuid());
       }
     }
 
     return nsEventStatus_eConsumeNoDefault;
@@ -1150,21 +1150,19 @@ void AsyncPanZoomController::AttemptScro
     CSSToScreenScale zoom = mFrameMetrics.mZoom;
 
     // Inversely scale the offset by the resolution (when you're zoomed further in,
     // a larger swipe should move you a shorter distance).
     CSSPoint cssDisplacement = displacement / zoom;
 
     CSSPoint cssOverscroll;
     gfx::Point scrollOffset(mX.AdjustDisplacement(cssDisplacement.x,
-                                                  cssOverscroll.x,
-                                                  mFrameMetrics.GetDisableScrollingX()),
+                                                  cssOverscroll.x),
                             mY.AdjustDisplacement(cssDisplacement.y,
-                                                  cssOverscroll.y,
-                                                  mFrameMetrics.GetDisableScrollingY()));
+                                                  cssOverscroll.y));
     overscroll = cssOverscroll * zoom;
 
     if (fabs(scrollOffset.x) > EPSILON || fabs(scrollOffset.y) > EPSILON) {
       ScrollBy(CSSPoint::FromUnknownPoint(scrollOffset));
       ScheduleComposite();
 
       TimeDuration timePaintDelta = mPaintThrottler.TimeSinceLastRequest(GetFrameTime());
       if (timePaintDelta.ToMilliseconds() > gPanRepaintInterval) {
@@ -1250,20 +1248,18 @@ bool FlingAnimation::Sample(FrameMetrics
   CSSPoint overscroll; // overscroll is ignored for flings
   ScreenPoint offset(aDelta.ToMilliseconds() * mX.GetVelocity(),
                      aDelta.ToMilliseconds() * mY.GetVelocity());
 
   // Inversely scale the offset by the resolution (when you're zoomed further in,
   // a larger swipe should move you a shorter distance).
   CSSPoint cssOffset = offset / aFrameMetrics.mZoom;
   aFrameMetrics.mScrollOffset += CSSPoint::FromUnknownPoint(gfx::Point(
-    mX.AdjustDisplacement(cssOffset.x, overscroll.x,
-                          aFrameMetrics.GetDisableScrollingX()),
-    mY.AdjustDisplacement(cssOffset.y, overscroll.y,
-                          aFrameMetrics.GetDisableScrollingY())
+    mX.AdjustDisplacement(cssOffset.x, overscroll.x),
+    mY.AdjustDisplacement(cssOffset.y, overscroll.y)
   ));
 
   return true;
 }
 
 void AsyncPanZoomController::StartAnimation(AsyncPanZoomAnimation* aAnimation)
 {
   ReentrantMonitorAutoEnter lock(mMonitor);
@@ -1296,100 +1292,88 @@ void AsyncPanZoomController::ScaleWithFo
   // We want to adjust the scroll offset such that the CSS point represented by aFocus remains
   // at the same position on the screen before and after the change in zoom. The below code
   // accomplishes this; see https://bugzilla.mozilla.org/show_bug.cgi?id=923431#c6 for an
   // in-depth explanation of how.
   mFrameMetrics.mScrollOffset = (mFrameMetrics.mScrollOffset + aFocus) - (aFocus / aScale);
 }
 
 /**
- * Attempts to enlarge the displayport along a single axis based on the
- * velocity. aOffset and aLength are in/out parameters; they are initially set
- * to the currently visible area and will be transformed to the area we should
- * be drawing to minimize checkerboarding.
+ * Enlarges the displayport along both axes based on the velocity.
+ */
+static CSSSize
+CalculateDisplayPortSize(const CSSRect& aCompositionBounds,
+                         const CSSPoint& aVelocity)
+{
+  float xMultiplier = fabsf(aVelocity.x) < gMinSkateSpeed
+                        ? gXStationarySizeMultiplier
+                        : gXSkateSizeMultiplier;
+  float yMultiplier = fabsf(aVelocity.y) < gMinSkateSpeed
+                        ? gYStationarySizeMultiplier
+                        : gYSkateSizeMultiplier;
+  return CSSSize(aCompositionBounds.width * xMultiplier,
+                 aCompositionBounds.height * yMultiplier);
+}
+
+/**
+ * Attempts to redistribute any area in the displayport that would get clipped
+ * by the scrollable rect, or be inaccessible due to disabled scrolling, to the
+ * other axis, while maintaining total displayport area.
  */
 static void
-EnlargeDisplayPortAlongAxis(float* aOutOffset, float* aOutLength,
-                            double aEstimatedPaintDurationMillis, float aVelocity,
-                            float aStationarySizeMultiplier, float aSkateSizeMultiplier)
+RedistributeDisplayPortExcess(CSSSize& aDisplayPortSize,
+                              const CSSRect& aCompositionBounds,
+                              const CSSRect& aScrollableRect)
 {
-  // Scale up the length using the appropriate multiplier and center the
-  // displayport around the visible area.
-  float multiplier = (fabsf(aVelocity) < gMinSkateSpeed
-                        ? aStationarySizeMultiplier
-                        : aSkateSizeMultiplier);
-  float newLength = (*aOutLength) * multiplier;
-  *aOutOffset -= (newLength - (*aOutLength)) / 2;
-  *aOutLength = newLength;
+  float xSlack = std::max(0.0f, aDisplayPortSize.width - aScrollableRect.width);
+  float ySlack = std::max(0.0f, aDisplayPortSize.height - aScrollableRect.height);
 
-  // Project the displayport out based on the estimated time it will take to paint,
-  // if the gUsePaintDuration flag is set. If not, just use a constant 50ms paint
-  // time. Setting the gVelocityBias pref appropriately can cancel this out if so
-  // desired.
-  double paintFactor = (gUsePaintDuration ? aEstimatedPaintDurationMillis : 50.0);
-  *aOutOffset += (aVelocity * paintFactor * gVelocityBias);
+  if (ySlack > 0) {
+    // Reassign wasted y-axis displayport to the x-axis
+    aDisplayPortSize.height -= ySlack;
+    float xExtra = ySlack * aDisplayPortSize.width / aDisplayPortSize.height;
+    aDisplayPortSize.width += xExtra;
+  } else if (xSlack > 0) {
+    // Reassign wasted x-axis displayport to the y-axis
+    aDisplayPortSize.width -= xSlack;
+    float yExtra = xSlack * aDisplayPortSize.height / aDisplayPortSize.width;
+    aDisplayPortSize.height += yExtra;
+  }
 }
 
 /* static */
 const CSSRect AsyncPanZoomController::CalculatePendingDisplayPort(
   const FrameMetrics& aFrameMetrics,
   const ScreenPoint& aVelocity,
   double aEstimatedPaintDuration)
 {
-  // convert to milliseconds
-  double estimatedPaintDurationMillis = aEstimatedPaintDuration * 1000;
-
   CSSRect compositionBounds = aFrameMetrics.CalculateCompositedRectInCssPixels();
+  CSSPoint velocity = aVelocity / aFrameMetrics.mZoom;
   CSSPoint scrollOffset = aFrameMetrics.mScrollOffset;
-  CSSRect displayPort(scrollOffset, compositionBounds.Size());
-  CSSPoint velocity = aVelocity / aFrameMetrics.mZoom;
-
   CSSRect scrollableRect = aFrameMetrics.GetExpandedScrollableRect();
 
-  float xSkateSizeMultiplier = gXSkateSizeMultiplier,
-        ySkateSizeMultiplier = gYSkateSizeMultiplier;
+  // Calculate the displayport size based on how fast we're moving along each axis.
+  CSSSize displayPortSize = CalculateDisplayPortSize(compositionBounds, velocity);
 
-  if (gEnlargeDisplayPortWhenOnlyScrollable) {
-    // Check if the displayport, without being enlarged, fits tightly inside the
-    // scrollable rect. If so, we're not going to be able to enlarge it, so we
-    // should consider enlarging the opposite axis.
-    if (scrollableRect.width - compositionBounds.width <= EPSILON ||
-        aFrameMetrics.GetDisableScrollingX()) {
-      xSkateSizeMultiplier = 1.f;
-      ySkateSizeMultiplier = gYStationarySizeMultiplier;
-    }
-    // Even if we end up overwriting the previous multipliers, it doesn't
-    // matter, since this frame's scrollable rect fits within its composition
-    // bounds on both axes and we won't be enlarging either displayport axis.
-    if (scrollableRect.height - compositionBounds.height <= EPSILON ||
-        aFrameMetrics.GetDisableScrollingY()) {
-      ySkateSizeMultiplier = 1.f;
-      xSkateSizeMultiplier = gXSkateSizeMultiplier;
-    }
+  if (gEnlargeDisplayPortWhenClipped) {
+    RedistributeDisplayPortExcess(displayPortSize, compositionBounds, scrollableRect);
   }
 
-  // If scrolling is disabled here then our actual velocity is going
-  // to be zero, so treat the displayport accordingly.
-  if (aFrameMetrics.GetDisableScrollingX()) {
-    velocity.x = 0;
-  }
-  if (aFrameMetrics.GetDisableScrollingY()) {
-    velocity.y = 0;
-  }
+  // Offset the displayport, depending on how fast we're moving and the
+  // estimated time it takes to paint, to try to minimise checkerboarding.
+  float estimatedPaintDurationMillis = (float)(aEstimatedPaintDuration * 1000.0);
+  float paintFactor = (gUsePaintDuration ? estimatedPaintDurationMillis : 50.0f);
+  CSSRect displayPort = CSSRect(scrollOffset + (velocity * paintFactor * gVelocityBias),
+                                displayPortSize);
 
-  // Enlarge the displayport along both axes depending on how fast we're moving
-  // on that axis and how long it takes to paint. Apply some heuristics to try
-  // to minimize checkerboarding.
-  EnlargeDisplayPortAlongAxis(&(displayPort.x), &(displayPort.width),
-    estimatedPaintDurationMillis, velocity.x,
-    gXStationarySizeMultiplier, xSkateSizeMultiplier);
-  EnlargeDisplayPortAlongAxis(&(displayPort.y), &(displayPort.height),
-    estimatedPaintDurationMillis, velocity.y,
-    gYStationarySizeMultiplier, ySkateSizeMultiplier);
+  // Re-center the displayport based on its expansion over the composition bounds.
+  displayPort.MoveBy((compositionBounds.width - displayPort.width)/2.0f,
+                     (compositionBounds.height - displayPort.height)/2.0f);
 
+  // Make sure the displayport remains within the scrollable rect.
   displayPort = displayPort.ForceInside(scrollableRect) - scrollOffset;
 
   APZC_LOG_FM(aFrameMetrics,
     "Calculated displayport as (%f %f %f %f) from velocity (%f %f) paint time %f metrics",
     displayPort.x, displayPort.y, displayPort.width, displayPort.height,
     aVelocity.x, aVelocity.y, (float)estimatedPaintDurationMillis);
 
   return displayPort;
@@ -1686,18 +1670,16 @@ void AsyncPanZoomController::NotifyLayer
       mFrameMetrics.mZoom.scale = aLayerMetrics.mZoom.scale;
       mFrameMetrics.mDevPixelsPerCSSPixel.scale = aLayerMetrics.mDevPixelsPerCSSPixel.scale;
     }
     mFrameMetrics.mScrollableRect = aLayerMetrics.mScrollableRect;
     mFrameMetrics.mCompositionBounds = aLayerMetrics.mCompositionBounds;
     mFrameMetrics.mResolution = aLayerMetrics.mResolution;
     mFrameMetrics.mCumulativeResolution = aLayerMetrics.mCumulativeResolution;
     mFrameMetrics.mHasScrollgrab = aLayerMetrics.mHasScrollgrab;
-    mFrameMetrics.SetDisableScrollingX(aLayerMetrics.GetDisableScrollingX());
-    mFrameMetrics.SetDisableScrollingY(aLayerMetrics.GetDisableScrollingY());
 
     // If the layers update was not triggered by our own repaint request, then
     // we want to take the new scroll offset.
     if (aLayerMetrics.GetScrollOffsetUpdated()) {
       APZC_LOG("%p updating scroll offset from (%f, %f) to (%f, %f)\n", this,
         mFrameMetrics.mScrollOffset.x, mFrameMetrics.mScrollOffset.y,
         aLayerMetrics.mScrollOffset.x, aLayerMetrics.mScrollOffset.y);
 
@@ -1941,29 +1923,16 @@ void AsyncPanZoomController::SetState(Pa
 bool AsyncPanZoomController::IsTransformingState(PanZoomState aState) {
   return !(aState == NOTHING || aState == TOUCHING || aState == WAITING_CONTENT_RESPONSE);
 }
 
 bool AsyncPanZoomController::IsPanningState(PanZoomState aState) {
   return (aState == PANNING || aState == PANNING_LOCKED_X || aState == PANNING_LOCKED_Y);
 }
 
-bool AsyncPanZoomController::AllowZoom() {
-  // In addition to looking at the zoom constraints, which comes from the meta
-  // viewport tag, disallow zooming if we are overflow:hidden in either direction.
-  ReentrantMonitorAutoEnter lock(mMonitor);
-  return mZoomConstraints.mAllowZoom
-      && !(mFrameMetrics.GetDisableScrollingX() || mFrameMetrics.GetDisableScrollingY());
-}
-
-bool AsyncPanZoomController::AllowDoubleTapZoom() {
-  ReentrantMonitorAutoEnter lock(mMonitor);
-  return mZoomConstraints.mAllowDoubleTapZoom && AllowZoom();
-}
-
 void AsyncPanZoomController::SetContentResponseTimer() {
   if (!mContentResponseTimeoutTask) {
     mContentResponseTimeoutTask =
       NewRunnableMethod(this, &AsyncPanZoomController::TimeoutContentResponse);
 
     PostDelayedTask(mContentResponseTimeoutTask, gContentResponseTimeout);
   }
 }
--- a/gfx/layers/ipc/AsyncPanZoomController.h
+++ b/gfx/layers/ipc/AsyncPanZoomController.h
@@ -594,19 +594,16 @@ private:
   bool ConvertToGecko(const ScreenPoint& aPoint, CSSIntPoint* aOut);
 
   /**
    * Internal helpers for checking general state of this apzc.
    */
   bool IsTransformingState(PanZoomState aState);
   bool IsPanningState(PanZoomState mState);
 
-  bool AllowZoom();
-  bool AllowDoubleTapZoom();
-
   enum AxisLockMode {
     FREE,     /* No locking at all */
     STANDARD, /* Default axis locking mode that remains locked until pan ends*/
     STICKY,   /* Allow lock to be broken, with hysteresis */
   };
 
   static AxisLockMode GetAxisLockMode();
 
--- a/gfx/layers/ipc/Axis.cpp
+++ b/gfx/layers/ipc/Axis.cpp
@@ -98,29 +98,22 @@ void Axis::UpdateWithTouchAtDevicePoint(
 }
 
 void Axis::StartTouch(int32_t aPos) {
   mStartPos = aPos;
   mPos = aPos;
   mAxisLocked = false;
 }
 
-float Axis::AdjustDisplacement(float aDisplacement, float& aOverscrollAmountOut,
-                               bool aScrollingDisabled) {
+float Axis::AdjustDisplacement(float aDisplacement, float& aOverscrollAmountOut) {
   if (mAxisLocked) {
     aOverscrollAmountOut = 0;
     return 0;
   }
 
-  if (aScrollingDisabled) {
-    // Scrolling is disabled on this axis, stop scrolling.
-    aOverscrollAmountOut = aDisplacement;
-    return 0;
-  }
-
   float displacement = aDisplacement;
 
   // If this displacement will cause an overscroll, throttle it. Can potentially
   // bring it to 0 even if the velocity is high.
   if (DisplacementWillOverscroll(displacement) != OVERSCROLL_NONE) {
     // No need to have a velocity along this axis anymore; it won't take us
     // anywhere, so we're just spinning needlessly.
     mVelocity = 0.0f;
--- a/gfx/layers/ipc/Axis.h
+++ b/gfx/layers/ipc/Axis.h
@@ -71,22 +71,18 @@ public:
 
   /**
    * Takes a requested displacement to the position of this axis, and adjusts it
    * to account for overscroll (which might decrease the displacement; this is
    * to prevent the viewport from overscrolling the page rect), and axis locking
    * (which might prevent any displacement from happening). If overscroll
    * ocurred, its amount is written to |aOverscrollAmountOut|.
    * The adjusted displacement is returned.
-   *
-   * aScrollingDisabled is used to indicate that no scrolling should happen
-   * in this axis. This is used to implement overflow: hidden;
    */
-  float AdjustDisplacement(float aDisplacement, float& aOverscrollAmountOut,
-                           bool aScrollingDisabled);
+  float AdjustDisplacement(float aDisplacement, float& aOverscrollAmountOut);
 
   /**
    * Gets the distance between the starting position of the touch supplied in
    * startTouch() and the current touch from the last
    * updateWithTouchAtDevicePoint().
    */
   float PanDistance();
 
--- a/image/src/imgTools.cpp
+++ b/image/src/imgTools.cpp
@@ -129,32 +129,32 @@ static nsresult EncodeImageData(DataSour
   nsAutoCString encoderCID(
     NS_LITERAL_CSTRING("@mozilla.org/image/encoder;2?type=") + aMimeType);
 
   nsCOMPtr<imgIEncoder> encoder = do_CreateInstance(encoderCID.get());
   if (!encoder)
     return NS_IMAGELIB_ERROR_NO_ENCODER;
 
   DataSourceSurface::MappedSurface map;
-  aDataSurface->Map(DataSourceSurface::MapType::READ, &map);
-  if (!map.mData)
+  if (!aDataSurface->Map(DataSourceSurface::MapType::READ, &map)) {
     return NS_ERROR_FAILURE;
+  }
 
   IntSize size = aDataSurface->GetSize();
   uint32_t dataLength = map.mStride * size.height;
 
   // Encode the bitmap
   nsresult rv = encoder->InitFromData(map.mData,
                                       dataLength,
                                       size.width,
                                       size.height,
                                       map.mStride,
                                       imgIEncoder::INPUT_FORMAT_HOSTARGB,
                                       aOutputOptions);
-
+  aDataSurface->Unmap();
   NS_ENSURE_SUCCESS(rv, rv);
 
   return CallQueryInterface(encoder, aStream);
 }
 
 NS_IMETHODIMP imgTools::EncodeImage(imgIContainer *aContainer,
                                     const nsACString& aMimeType,
                                     const nsAString& aOutputOptions,
@@ -199,32 +199,34 @@ NS_IMETHODIMP imgTools::EncodeScaledImag
   } else if (aScaledHeight == 0) {
     aScaledHeight = frameHeight;
   }
 
   RefPtr<DataSourceSurface> dataSurface =
     Factory::CreateDataSourceSurface(IntSize(aScaledWidth, aScaledHeight),
                                      SurfaceFormat::B8G8R8A8);
   DataSourceSurface::MappedSurface map;
-  dataSurface->Map(DataSourceSurface::MapType::WRITE, &map);
-  if (!map.mData)
+  if (!dataSurface->Map(DataSourceSurface::MapType::WRITE, &map)) {
     return NS_ERROR_FAILURE;
+  }
 
   RefPtr<DrawTarget> dt =
     Factory::CreateDrawTargetForData(BackendType::CAIRO,
                                      map.mData,
                                      dataSurface->GetSize(),
                                      map.mStride,
                                      SurfaceFormat::B8G8R8A8);
   dt->DrawSurface(frame,
                   Rect(0, 0, aScaledWidth, aScaledHeight),
                   Rect(0, 0, frameWidth, frameHeight),
                   DrawSurfaceOptions(),
                   DrawOptions(1.0f, CompositionOp::OP_SOURCE));
 
+  dataSurface->Unmap();
+
   return EncodeImageData(dataSurface, aMimeType, aOutputOptions, aStream);
 }
 
 NS_IMETHODIMP imgTools::EncodeCroppedImage(imgIContainer *aContainer,
                                            const nsACString& aMimeType,
                                            int32_t aOffsetX,
                                            int32_t aOffsetY,
                                            int32_t aWidth,
@@ -262,30 +264,32 @@ NS_IMETHODIMP imgTools::EncodeCroppedIma
   // Check that the given crop rectangle is within image bounds.
   NS_ENSURE_ARG(frameWidth >= aOffsetX + aWidth &&
                 frameHeight >= aOffsetY + aHeight);
 
   RefPtr<DataSourceSurface> dataSurface =
     Factory::CreateDataSourceSurface(IntSize(aWidth, aHeight),
                                      SurfaceFormat::B8G8R8A8);
   DataSourceSurface::MappedSurface map;
-  dataSurface->Map(DataSourceSurface::MapType::WRITE, &map);
-  if (!map.mData)
+  if (!dataSurface->Map(DataSourceSurface::MapType::WRITE, &map)) {
     return NS_ERROR_FAILURE;
+  }
 
   RefPtr<DrawTarget> dt =
     Factory::CreateDrawTargetForData(BackendType::CAIRO,
                                      map.mData,
                                      dataSurface->GetSize(),
                                      map.mStride,
                                      SurfaceFormat::B8G8R8A8);
   dt->CopySurface(frame,
                   IntRect(aOffsetX, aOffsetY, aWidth, aHeight),
                   IntPoint(0, 0));
 
+  dataSurface->Unmap();
+
   return EncodeImageData(dataSurface, aMimeType, aOutputOptions, aStream);
 }
 
 NS_IMETHODIMP imgTools::CreateScriptedObserver(imgIScriptedNotificationObserver* aInner,
                                                imgINotificationObserver** aObserver)
 {
   NS_ADDREF(*aObserver = new ScriptedNotificationObserver(aInner));
   return NS_OK;
--- a/js/jsd/jsd_xpc.cpp
+++ b/js/jsd/jsd_xpc.cpp
@@ -1651,39 +1651,31 @@ jsdContext::GetJSContext(JSContext **_rv
 
 #define JSOPTION_EXTRA_WARNINGS                 JS_BIT(0)
 #define JSOPTION_WERROR                         JS_BIT(1)
 #define JSOPTION_VAROBJFIX                      JS_BIT(2)
 #define JSOPTION_PRIVATE_IS_NSISUPPORTS         JS_BIT(3)
 #define JSOPTION_DONT_REPORT_UNCAUGHT           JS_BIT(8)
 #define JSOPTION_NO_DEFAULT_COMPARTMENT_OBJECT  JS_BIT(11)
 #define JSOPTION_NO_SCRIPT_RVAL                 JS_BIT(12)
-#define JSOPTION_BASELINE                       JS_BIT(14)
-#define JSOPTION_TYPE_INFERENCE                 JS_BIT(16)
 #define JSOPTION_STRICT_MODE                    JS_BIT(17)
-#define JSOPTION_ION                            JS_BIT(18)
-#define JSOPTION_ASMJS                          JS_BIT(19)
 #define JSOPTION_MASK                           JS_BITMASK(20)
 
 NS_IMETHODIMP
 jsdContext::GetOptions(uint32_t *_rval)
 {
     ASSERT_VALID_EPHEMERAL;
     *_rval = (JS::ContextOptionsRef(mJSCx).extraWarnings() ? JSOPTION_EXTRA_WARNINGS : 0)
            | (JS::ContextOptionsRef(mJSCx).werror() ? JSOPTION_WERROR : 0)
            | (JS::ContextOptionsRef(mJSCx).varObjFix() ? JSOPTION_VAROBJFIX : 0)
            | (JS::ContextOptionsRef(mJSCx).privateIsNSISupports() ? JSOPTION_PRIVATE_IS_NSISUPPORTS : 0)
            | (JS::ContextOptionsRef(mJSCx).dontReportUncaught() ? JSOPTION_DONT_REPORT_UNCAUGHT : 0)
            | (JS::ContextOptionsRef(mJSCx).noDefaultCompartmentObject() ? JSOPTION_NO_DEFAULT_COMPARTMENT_OBJECT : 0)
            | (JS::ContextOptionsRef(mJSCx).noScriptRval() ? JSOPTION_NO_SCRIPT_RVAL : 0)
-           | (JS::ContextOptionsRef(mJSCx).strictMode() ? JSOPTION_STRICT_MODE : 0)
-           | (JS::ContextOptionsRef(mJSCx).baseline() ? JSOPTION_BASELINE : 0)
-           | (JS::ContextOptionsRef(mJSCx).typeInference() ? JSOPTION_TYPE_INFERENCE : 0)
-           | (JS::ContextOptionsRef(mJSCx).ion() ? JSOPTION_ION : 0)
-           | (JS::ContextOptionsRef(mJSCx).asmJS() ? JSOPTION_ASMJS : 0);
+           | (JS::ContextOptionsRef(mJSCx).strictMode() ? JSOPTION_STRICT_MODE : 0);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 jsdContext::SetOptions(uint32_t options)
 {
     ASSERT_VALID_EPHEMERAL;
 
@@ -1694,21 +1686,17 @@ jsdContext::SetOptions(uint32_t options)
         return NS_ERROR_ILLEGAL_VALUE;
 
     JS::ContextOptionsRef(mJSCx).setExtraWarnings(options & JSOPTION_EXTRA_WARNINGS)
                                 .setWerror(options & JSOPTION_WERROR)
                                 .setVarObjFix(options & JSOPTION_VAROBJFIX)
                                 .setDontReportUncaught(options & JSOPTION_DONT_REPORT_UNCAUGHT)
                                 .setNoDefaultCompartmentObject(options & JSOPTION_NO_DEFAULT_COMPARTMENT_OBJECT)
                                 .setNoScriptRval(options & JSOPTION_NO_SCRIPT_RVAL)
-                                .setStrictMode(options & JSOPTION_STRICT_MODE)
-                                .setBaseline(options & JSOPTION_BASELINE)
-                                .setTypeInference(options & JSOPTION_TYPE_INFERENCE)
-                                .setIon(options & JSOPTION_ION)
-                                .setAsmJS(options & JSOPTION_ASMJS);
+                                .setStrictMode(options & JSOPTION_STRICT_MODE);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 jsdContext::GetPrivateData(nsISupports **_rval)
 {
     ASSERT_VALID_EPHEMERAL;
     if (JS::ContextOptionsRef(mJSCx).privateIsNSISupports()) 
--- a/js/src/builtin/TestingFunctions.cpp
+++ b/js/src/builtin/TestingFunctions.cpp
@@ -1155,35 +1155,35 @@ SetJitCompilerOption(JSContext *cx, unsi
         ReportUsageError(cx, callee, "First argument does not name a valid option (see jsapi.h).");
         return false;
     }
 
     int32_t number = args[1].toInt32();
     if (number < 0)
         number = -1;
 
-    JS_SetGlobalJitCompilerOption(cx, opt, uint32_t(number));
+    JS_SetGlobalJitCompilerOption(cx->runtime(), opt, uint32_t(number));
 
     args.rval().setUndefined();
     return true;
 }
 
 static bool
 GetJitCompilerOptions(JSContext *cx, unsigned argc, jsval *vp)
 {
     RootedObject info(cx, JS_NewObject(cx, nullptr, JS::NullPtr(), JS::NullPtr()));
     if (!info)
         return false;
 
     RootedValue value(cx);
 
-#define JIT_COMPILER_MATCH(key, string)                         \
-    opt = JSJITCOMPILER_ ## key;                                \
-    value.setInt32(JS_GetGlobalJitCompilerOption(cx, opt));     \
-    if (!JS_SetProperty(cx, info, string, value))               \
+#define JIT_COMPILER_MATCH(key, string)                                \
+    opt = JSJITCOMPILER_ ## key;                                       \
+    value.setInt32(JS_GetGlobalJitCompilerOption(cx->runtime(), opt)); \
+    if (!JS_SetProperty(cx, info, string, value))                      \
         return false;
 
     JSJitCompilerOption opt = JSJITCOMPILER_NOT_AN_OPTION;
     JIT_COMPILER_OPTIONS(JIT_COMPILER_MATCH);
 #undef JIT_COMPILER_MATCH
 
     *vp = ObjectValue(*info);
 
--- a/js/src/gc/RootMarking.cpp
+++ b/js/src/gc/RootMarking.cpp
@@ -57,17 +57,16 @@ MarkExactStackRoot(JSTracer *trc, Rooted
       case THING_ROOT_LAZY_SCRIPT: MarkLazyScriptRoot(trc, (LazyScript **)addr, "exact-lazy-script"); break;
       case THING_ROOT_SHAPE:       MarkShapeRoot(trc, (Shape **)addr, "exact-shape"); break;
       case THING_ROOT_BASE_SHAPE:  MarkBaseShapeRoot(trc, (BaseShape **)addr, "exact-baseshape"); break;
       case THING_ROOT_TYPE:        MarkTypeRoot(trc, (types::Type *)addr, "exact-type"); break;
       case THING_ROOT_TYPE_OBJECT: MarkTypeObjectRoot(trc, (types::TypeObject **)addr, "exact-typeobject"); break;
       case THING_ROOT_JIT_CODE:    MarkJitCodeRoot(trc, (jit::JitCode **)addr, "exact-jitcode"); break;
       case THING_ROOT_VALUE:       MarkValueRoot(trc, (Value *)addr, "exact-value"); break;
       case THING_ROOT_ID:          MarkIdRoot(trc, (jsid *)addr, "exact-id"); break;
-      case THING_ROOT_PROPERTY_ID: MarkIdRoot(trc, &((js::PropertyId *)addr)->asId(), "exact-propertyid"); break;
       case THING_ROOT_BINDINGS:    ((Bindings *)addr)->trace(trc); break;
       case THING_ROOT_PROPERTY_DESCRIPTOR: ((JSPropertyDescriptor *)addr)->trace(trc); break;
       case THING_ROOT_CUSTOM: {
           // 'rooter' is a member within a class containing a vtable. Back up
           // to the vtable and call trace() through it.
           const size_t rooterOffset = offsetof(RootedGeneric<void*>, rooter);
           reinterpret_cast< RootedGeneric<void*>* >(uintptr_t(rooter) - rooterOffset)->trace(trc);
           break;
--- a/js/src/jit/AsmJS.cpp
+++ b/js/src/jit/AsmJS.cpp
@@ -7023,13 +7023,13 @@ js::IsAsmJSCompilationAvailable(JSContex
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     // See EstablishPreconditions.
     bool available = cx->jitSupportsFloatingPoint() &&
                      cx->signalHandlersInstalled() &&
                      cx->gcSystemPageSize() == AsmJSPageSize &&
                      !cx->compartment()->debugMode() &&
-                     cx->compartment()->options().asmJS(cx);
+                     cx->runtime()->options().asmJS();
 
     args.rval().set(BooleanValue(available));
     return true;
 }
--- a/js/src/jit/BaselineJIT.h
+++ b/js/src/jit/BaselineJIT.h
@@ -307,17 +307,17 @@ struct BaselineScript
         JS_ASSERT(bytecodeTypeMapOffset_);
         return reinterpret_cast<uint32_t *>(reinterpret_cast<uint8_t *>(this) + bytecodeTypeMapOffset_);
     }
 };
 
 inline bool
 IsBaselineEnabled(JSContext *cx)
 {
-    return cx->compartment()->options().baseline(cx);
+    return cx->runtime()->options().baseline();
 }
 
 MethodStatus
 CanEnterBaselineMethod(JSContext *cx, RunState &state);
 
 MethodStatus
 CanEnterBaselineAtBranch(JSContext *cx, StackFrame *fp, bool newType);
 
--- a/js/src/jit/Ion.h
+++ b/js/src/jit/Ion.h
@@ -154,18 +154,18 @@ CodeGenerator *CompileBackEnd(MIRGenerat
 
 void AttachFinishedCompilations(JSContext *cx);
 void FinishOffThreadBuilder(IonBuilder *builder);
 void StopAllOffThreadCompilations(JSCompartment *comp);
 
 static inline bool
 IsIonEnabled(JSContext *cx)
 {
-    return cx->compartment()->options().ion(cx) &&
-        cx->compartment()->options().baseline(cx) &&
+    return cx->runtime()->options().ion() &&
+        cx->runtime()->options().baseline() &&
         cx->typeInferenceEnabled();
 }
 
 inline bool
 IsIonInlinablePC(jsbytecode *pc) {
     // CALL, FUNCALL, FUNAPPLY, EVAL, NEW (Normal Callsites)
     // GETPROP, CALLPROP, and LENGTH. (Inlined Getters)
     // SETPROP, SETNAME, SETGNAME (Inlined Setters)
--- a/js/src/jsapi-tests/testFuncCallback.cpp
+++ b/js/src/jsapi-tests/testFuncCallback.cpp
@@ -128,14 +128,14 @@ BEGIN_TEST(testFuncCallback_bug507012)
 // Make sure that the method jit is enabled.
 // We'll probably want to test in all modes.
 virtual
 JSContext *createContext()
 {
     JSContext *cx = JSAPITest::createContext();
     if (!cx)
         return nullptr;
-    JS::ContextOptionsRef(cx).setBaseline(true)
+    JS::RuntimeOptionsRef(cx).setBaseline(true)
                              .setIon(true);
     return cx;
 }
 
 END_TEST(testFuncCallback_bug507012)
--- a/js/src/jsapi-tests/testProfileStrings.cpp
+++ b/js/src/jsapi-tests/testProfileStrings.cpp
@@ -140,17 +140,17 @@ BEGIN_TEST(testProfileStrings_isCalledWi
     }
     return true;
 }
 END_TEST(testProfileStrings_isCalledWithInterpreter)
 
 BEGIN_TEST(testProfileStrings_isCalledWithJIT)
 {
     CHECK(initialize(cx));
-    JS::ContextOptionsRef(cx).setBaseline(true)
+    JS::RuntimeOptionsRef(cx).setBaseline(true)
                              .setIon(true);
 
     EXEC("function g() { var p = new Prof(); p.test_fn(); }");
     EXEC("function f() { g(); }");
     EXEC("function e() { f(); }");
     EXEC("function d() { e(); }");
     EXEC("function c() { d(); }");
     EXEC("function b() { c(); }");
@@ -192,17 +192,17 @@ BEGIN_TEST(testProfileStrings_isCalledWi
     }
     return true;
 }
 END_TEST(testProfileStrings_isCalledWithJIT)
 
 BEGIN_TEST(testProfileStrings_isCalledWhenError)
 {
     CHECK(initialize(cx));
-    JS::ContextOptionsRef(cx).setBaseline(true)
+    JS::RuntimeOptionsRef(cx).setBaseline(true)
                              .setIon(true);
 
     EXEC("function check2() { throw 'a'; }");
 
     reset(cx);
     JS::ContextOptionsRef(cx).setDontReportUncaught(true);
     {
         JS::RootedValue rval(cx);
@@ -217,17 +217,17 @@ BEGIN_TEST(testProfileStrings_isCalledWh
     }
     return true;
 }
 END_TEST(testProfileStrings_isCalledWhenError)
 
 BEGIN_TEST(testProfileStrings_worksWhenEnabledOnTheFly)
 {
     CHECK(initialize(cx));
-    JS::ContextOptionsRef(cx).setBaseline(true)
+    JS::RuntimeOptionsRef(cx).setBaseline(true)
                              .setIon(true);
 
     EXEC("function b(p) { p.test_fn(); }");
     EXEC("function a() { var p = new Prof(); p.enable(); b(p); }");
     reset(cx);
     js::EnableRuntimeProfilingStack(cx->runtime(), false);
     {
         /* enable it in the middle of JS and make sure things check out */
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -876,16 +876,28 @@ JS_StringToVersion(const char *string)
     int i;
 
     for (i = 0; v2smap[i].string; i++)
         if (strcmp(v2smap[i].string, string) == 0)
             return v2smap[i].version;
     return JSVERSION_UNKNOWN;
 }
 
+JS_PUBLIC_API(JS::RuntimeOptions &)
+JS::RuntimeOptionsRef(JSRuntime *rt)
+{
+    return rt->options();
+}
+
+JS_PUBLIC_API(JS::RuntimeOptions &)
+JS::RuntimeOptionsRef(JSContext *cx)
+{
+    return cx->runtime()->options();
+}
+
 JS_PUBLIC_API(JS::ContextOptions &)
 JS::ContextOptionsRef(JSContext *cx)
 {
     return cx->options();
 }
 
 JS_PUBLIC_API(const char *)
 JS_GetImplementationVersion(void)
@@ -2448,46 +2460,16 @@ class AutoHoldZone
   private:
     bool *holdp;
     MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
 } /* anonymous namespace */
 
 bool
-JS::CompartmentOptions::baseline(JSContext *cx) const
-{
-    return baselineOverride_.get(cx->options().baseline());
-}
-
-bool
-JS::CompartmentOptions::typeInference(const ExclusiveContext *cx) const
-{
-    /* Unlike the other options that can be overriden on a per compartment
-     * basis, the default value for the typeInference option is stored on the
-     * compartment's type zone, rather than the current JSContext. Type zones
-     * copy this default value over from the current JSContext when they are
-     * created.
-     */
-    return typeInferenceOverride_.get(cx->compartment()->zone()->types.inferenceEnabled);
-}
-
-bool
-JS::CompartmentOptions::ion(JSContext *cx) const
-{
-    return ionOverride_.get(cx->options().ion());
-}
-
-bool
-JS::CompartmentOptions::asmJS(JSContext *cx) const
-{
-    return asmJSOverride_.get(cx->options().asmJS());
-}
-
-bool
 JS::CompartmentOptions::cloneSingletons(JSContext *cx) const
 {
     return cloneSingletonsOverride_.get(cx->options().cloneSingletons());
 }
 
 JS::CompartmentOptions &
 JS::CompartmentOptions::setZone(ZoneSpecifier spec)
 {
@@ -4457,17 +4439,17 @@ JS::CompileOptions::CompileOptions(JSCon
 {
     this->version = (version != JSVERSION_UNKNOWN) ? version : cx->findVersion();
 
     compileAndGo = false;
     noScriptRval = cx->options().noScriptRval();
     strictOption = cx->options().strictMode();
     extraWarningsOption = cx->options().extraWarnings();
     werrorOption = cx->options().werror();
-    asmJSOption = cx->options().asmJS();
+    asmJSOption = cx->runtime()->options().asmJS();
 }
 
 bool
 JS::CompileOptions::wrap(JSContext *cx, JSCompartment *compartment)
 {
     if (!compartment->wrap(cx, &elementRoot))
         return false;
     if (elementAttributeNameRoot) {
@@ -5955,33 +5937,33 @@ JS_SetGCZeal(JSContext *cx, uint8_t zeal
 JS_PUBLIC_API(void)
 JS_ScheduleGC(JSContext *cx, uint32_t count)
 {
     cx->runtime()->gcNextScheduled = count;
 }
 #endif
 
 JS_PUBLIC_API(void)
-JS_SetParallelParsingEnabled(JSContext *cx, bool enabled)
+JS_SetParallelParsingEnabled(JSRuntime *rt, bool enabled)
 {
 #ifdef JS_ION
-    cx->runtime()->setParallelParsingEnabled(enabled);
+    rt->setParallelParsingEnabled(enabled);
 #endif
 }
 
 JS_PUBLIC_API(void)
-JS_SetParallelIonCompilationEnabled(JSContext *cx, bool enabled)
+JS_SetParallelIonCompilationEnabled(JSRuntime *rt, bool enabled)
 {
 #ifdef JS_ION
-    cx->runtime()->setParallelIonCompilationEnabled(enabled);
+    rt->setParallelIonCompilationEnabled(enabled);
 #endif
 }
 
 JS_PUBLIC_API(void)
-JS_SetGlobalJitCompilerOption(JSContext *cx, JSJitCompilerOption opt, uint32_t value)
+JS_SetGlobalJitCompilerOption(JSRuntime *rt, JSJitCompilerOption opt, uint32_t value)
 {
 #ifdef JS_ION
 
     switch (opt) {
       case JSJITCOMPILER_BASELINE_USECOUNT_TRIGGER:
         if (value == uint32_t(-1)) {
             jit::JitOptions defaultValues;
             value = defaultValues.baselineUsesBeforeCompile;
@@ -5994,51 +5976,51 @@ JS_SetGlobalJitCompilerOption(JSContext 
             break;
         }
         jit::js_JitOptions.setUsesBeforeCompile(value);
         if (value == 0)
             jit::js_JitOptions.setEagerCompilation();
         break;
       case JSJITCOMPILER_ION_ENABLE:
         if (value == 1) {
-            JS::ContextOptionsRef(cx).setIon(true);
+            JS::RuntimeOptionsRef(rt).setIon(true);
             IonSpew(js::jit::IonSpew_Scripts, "Enable ion");
         } else if (value == 0) {
-            JS::ContextOptionsRef(cx).setIon(false);
+            JS::RuntimeOptionsRef(rt).setIon(false);
             IonSpew(js::jit::IonSpew_Scripts, "Disable ion");
         }
         break;
       case JSJITCOMPILER_BASELINE_ENABLE:
         if (value == 1) {
-            JS::ContextOptionsRef(cx).setBaseline(true);
+            JS::RuntimeOptionsRef(rt).setBaseline(true);
             IonSpew(js::jit::IonSpew_BaselineScripts, "Enable baseline");
         } else if (value == 0) {
-            JS::ContextOptionsRef(cx).setBaseline(false);
+            JS::RuntimeOptionsRef(rt).setBaseline(false);
             IonSpew(js::jit::IonSpew_BaselineScripts, "Disable baseline");
         }
         break;
       default:
         break;
     }
 #endif
 }
 
 JS_PUBLIC_API(int)
-JS_GetGlobalJitCompilerOption(JSContext *cx, JSJitCompilerOption opt)
+JS_GetGlobalJitCompilerOption(JSRuntime *rt, JSJitCompilerOption opt)
 {
 #ifdef JS_ION
     switch (opt) {
       case JSJITCOMPILER_BASELINE_USECOUNT_TRIGGER:
         return jit::js_JitOptions.baselineUsesBeforeCompile;
       case JSJITCOMPILER_ION_USECOUNT_TRIGGER:
         return jit::js_JitOptions.forcedDefaultIonUsesBeforeCompile;
       case JSJITCOMPILER_ION_ENABLE:
-        return JS::ContextOptionsRef(cx).ion();
+        return JS::RuntimeOptionsRef(rt).ion();
       case JSJITCOMPILER_BASELINE_ENABLE:
-        return JS::ContextOptionsRef(cx).baseline();
+        return JS::RuntimeOptionsRef(rt).baseline();
       default:
         break;
     }
 #endif
     return 0;
 }
 
 /************************************************************************/
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -1434,31 +1434,90 @@ JS_SetVersionForCompartment(JSCompartmen
 extern JS_PUBLIC_API(const char *)
 JS_VersionToString(JSVersion version);
 
 extern JS_PUBLIC_API(JSVersion)
 JS_StringToVersion(const char *string);
 
 namespace JS {
 
+class JS_PUBLIC_API(RuntimeOptions) {
+  public:
+    RuntimeOptions()
+      : baseline_(false),
+        typeInference_(false),
+        ion_(false),
+        asmJS_(false)
+    {
+    }
+
+    bool baseline() const { return baseline_; }
+    RuntimeOptions &setBaseline(bool flag) {
+        baseline_ = flag;
+        return *this;
+    }
+    RuntimeOptions &toggleBaseline() {
+        baseline_ = !baseline_;
+        return *this;
+    }
+
+    bool typeInference() const { return typeInference_; }
+    RuntimeOptions &setTypeInference(bool flag) {
+        typeInference_ = flag;
+        return *this;
+    }
+    RuntimeOptions &toggleTypeInference() {
+        typeInference_ = !typeInference_;
+        return *this;
+    }
+
+    bool ion() const { return ion_; }
+    RuntimeOptions &setIon(bool flag) {
+        ion_ = flag;
+        return *this;
+    }
+    RuntimeOptions &toggleIon() {
+        ion_ = !ion_;
+        return *this;
+    }
+
+    bool asmJS() const { return asmJS_; }
+    RuntimeOptions &setAsmJS(bool flag) {
+        asmJS_ = flag;
+        return *this;
+    }
+    RuntimeOptions &toggleAsmJS() {
+        asmJS_ = !asmJS_;
+        return *this;
+    }
+
+  private:
+    bool baseline_ : 1;
+    bool typeInference_ : 1;
+    bool ion_ : 1;
+    bool asmJS_ : 1;
+};
+
+JS_PUBLIC_API(RuntimeOptions &)
+RuntimeOptionsRef(JSRuntime *rt);
+
+JS_PUBLIC_API(RuntimeOptions &)
+RuntimeOptionsRef(JSContext *cx);
+
 class JS_PUBLIC_API(ContextOptions) {
   public:
     ContextOptions()
       : extraWarnings_(false),
         werror_(false),
         varObjFix_(false),
         privateIsNSISupports_(false),
         dontReportUncaught_(false),
         noDefaultCompartmentObject_(false),
         noScriptRval_(false),
         strictMode_(false),
-        baseline_(false),
-        typeInference_(false),
-        ion_(false),
-        asmJS_(false),
         cloneSingletons_(false)
     {
     }
 
     bool extraWarnings() const { return extraWarnings_; }
     ContextOptions &setExtraWarnings(bool flag) {
         extraWarnings_ = flag;
         return *this;
@@ -1533,56 +1592,16 @@ class JS_PUBLIC_API(ContextOptions) {
         strictMode_ = flag;
         return *this;
     }
     ContextOptions &toggleStrictMode() {
         strictMode_ = !strictMode_;
         return *this;
     }
 
-    bool baseline() const { return baseline_; }
-    ContextOptions &setBaseline(bool flag) {
-        baseline_ = flag;
-        return *this;
-    }
-    ContextOptions &toggleBaseline() {
-        baseline_ = !baseline_;
-        return *this;
-    }
-
-    bool typeInference() const { return typeInference_; }
-    ContextOptions &setTypeInference(bool flag) {
-        typeInference_ = flag;
-        return *this;
-    }
-    ContextOptions &toggleTypeInference() {
-        typeInference_ = !typeInference_;
-        return *this;
-    }
-
-    bool ion() const { return ion_; }
-    ContextOptions &setIon(bool flag) {
-        ion_ = flag;
-        return *this;
-    }
-    ContextOptions &toggleIon() {
-        ion_ = !ion_;
-        return *this;
-    }
-
-    bool asmJS() const { return asmJS_; }
-    ContextOptions &setAsmJS(bool flag) {
-        asmJS_ = flag;
-        return *this;
-    }
-    ContextOptions &toggleAsmJS() {
-        asmJS_ = !asmJS_;
-        return *this;
-    }
-
     bool cloneSingletons() const { return cloneSingletons_; }
     ContextOptions &setCloneSingletons(bool flag) {
         cloneSingletons_ = flag;
         return *this;
     }
     ContextOptions &toggleCloneSingletons() {
         cloneSingletons_ = !cloneSingletons_;
         return *this;
@@ -1592,20 +1611,16 @@ class JS_PUBLIC_API(ContextOptions) {
     bool extraWarnings_ : 1;
     bool werror_ : 1;
     bool varObjFix_ : 1;
     bool privateIsNSISupports_ : 1;
     bool dontReportUncaught_ : 1;
     bool noDefaultCompartmentObject_ : 1;
     bool noScriptRval_ : 1;
     bool strictMode_ : 1;
-    bool baseline_ : 1;
-    bool typeInference_ : 1;
-    bool ion_ : 1;
-    bool asmJS_ : 1;
     bool cloneSingletons_ : 1;
 };
 
 JS_PUBLIC_API(ContextOptions &)
 ContextOptionsRef(JSContext *cx);
 
 class JS_PUBLIC_API(AutoSaveContextOptions) {
   public:
@@ -2642,28 +2657,16 @@ class JS_PUBLIC_API(CompartmentOptions)
     // allowed if this flag is set.  The invisibleToDebugger flag must also be
     // set for such compartments.
     bool mergeable() const { return mergeable_; }
     CompartmentOptions &setMergeable(bool flag) {
         mergeable_ = flag;
         return *this;
     }
 
-    bool baseline(JSContext *cx) const;
-    Override &baselineOverride() { return baselineOverride_; }
-
-    bool typeInference(const js::ExclusiveContext *cx) const;
-    Override &typeInferenceOverride() { return typeInferenceOverride_; }
-
-    bool ion(JSContext *cx) const;
-    Override &ionOverride() { return ionOverride_; }
-
-    bool asmJS(JSContext *cx) const;
-    Override &asmJSOverride() { return asmJSOverride_; }
-
     bool cloneSingletons(JSContext *cx) const;
     Override &cloneSingletonsOverride() { return cloneSingletonsOverride_; }
 
     void *zonePointer() const {
         JS_ASSERT(uintptr_t(zone_.pointer) > uintptr_t(JS::SystemZone));
         return zone_.pointer;
     }
     ZoneSpecifier zoneSpecifier() const { return zone_.spec; }
@@ -2676,20 +2679,16 @@ class JS_PUBLIC_API(CompartmentOptions)
     bool getSingletonsAsTemplates() const {
         return singletonsAsTemplates_;
     };
 
   private:
     JSVersion version_;
     bool invisibleToDebugger_;
     bool mergeable_;
-    Override baselineOverride_;
-    Override typeInferenceOverride_;
-    Override ionOverride_;
-    Override asmJSOverride_;
     Override cloneSingletonsOverride_;
     union {
         ZoneSpecifier spec;
         void *pointer; // js::Zone* is not exposed in the API.
     } zone_;
 
     // To XDR singletons, we need to ensure that all singletons are all used as
     // templates, by making JSOP_OBJECT return a clone of the JSScript
@@ -4659,20 +4658,20 @@ JS_NewObjectForConstructor(JSContext *cx
 extern JS_PUBLIC_API(void)
 JS_SetGCZeal(JSContext *cx, uint8_t zeal, uint32_t frequency);
 
 extern JS_PUBLIC_API(void)
 JS_ScheduleGC(JSContext *cx, uint32_t count);
 #endif
 
 extern JS_PUBLIC_API(void)
-JS_SetParallelParsingEnabled(JSContext *cx, bool enabled);
+JS_SetParallelParsingEnabled(JSRuntime *rt, bool enabled);
 
 extern JS_PUBLIC_API(void)
-JS_SetParallelIonCompilationEnabled(JSContext *cx, bool enabled);
+JS_SetParallelIonCompilationEnabled(JSRuntime *rt, bool enabled);
 
 #define JIT_COMPILER_OPTIONS(Register)                             \
   Register(BASELINE_USECOUNT_TRIGGER, "baseline.usecount.trigger") \
   Register(ION_USECOUNT_TRIGGER, "ion.usecount.trigger")           \
   Register(ION_ENABLE, "ion.enable")                               \
   Register(BASELINE_ENABLE, "baseline.enable")
 
 typedef enum JSJitCompilerOption {
@@ -4681,19 +4680,19 @@ typedef enum JSJitCompilerOption {
 
     JIT_COMPILER_OPTIONS(JIT_COMPILER_DECLARE)
 #undef JIT_COMPILER_DECLARE
 
     JSJITCOMPILER_NOT_AN_OPTION
 } JSJitCompilerOption;
 
 extern JS_PUBLIC_API(void)
-JS_SetGlobalJitCompilerOption(JSContext *cx, JSJitCompilerOption opt, uint32_t value);
+JS_SetGlobalJitCompilerOption(JSRuntime *rt, JSJitCompilerOption opt, uint32_t value);
 extern JS_PUBLIC_API(int)
-JS_GetGlobalJitCompilerOption(JSContext *cx, JSJitCompilerOption opt);
+JS_GetGlobalJitCompilerOption(JSRuntime *rt, JSJitCompilerOption opt);
 
 /*
  * Convert a uint32_t index into a jsid.
  */
 extern JS_PUBLIC_API(bool)
 JS_IndexToId(JSContext *cx, uint32_t index, JS::MutableHandleId);
 
 /*
--- a/js/src/jscompartment.h
+++ b/js/src/jscompartment.h
@@ -516,17 +516,17 @@ class js::AutoDebugModeInvalidation
     }
 };
 
 namespace js {
 
 inline bool
 ExclusiveContext::typeInferenceEnabled() const
 {
-    return compartment_->options().typeInference(this);
+    return zone()->types.inferenceEnabled;
 }
 
 inline js::Handle<js::GlobalObject*>
 ExclusiveContext::global() const
 {
     /*
      * It's safe to use |unsafeGet()| here because any compartment that is
      * on-stack will be marked automatically, so there's no need for a read
--- a/js/src/jsinfer.cpp
+++ b/js/src/jsinfer.cpp
@@ -1857,17 +1857,17 @@ TypeCompartment::TypeCompartment()
 {
     PodZero(this);
 }
 
 void
 TypeZone::init(JSContext *cx)
 {
     if (!cx ||
-        !cx->options().typeInference() ||
+        !cx->runtime()->options().typeInference() ||
         !cx->runtime()->jitSupportsFloatingPoint)
     {
         return;
     }
 
     inferenceEnabled = true;
 }
 
--- a/js/src/jspubtd.h
+++ b/js/src/jspubtd.h
@@ -277,17 +277,16 @@ enum ThingRootKind
     THING_ROOT_SHAPE,
     THING_ROOT_BASE_SHAPE,
     THING_ROOT_TYPE_OBJECT,
     THING_ROOT_STRING,
     THING_ROOT_JIT_CODE,
     THING_ROOT_SCRIPT,
     THING_ROOT_LAZY_SCRIPT,
     THING_ROOT_ID,
-    THING_ROOT_PROPERTY_ID,
     THING_ROOT_VALUE,
     THING_ROOT_TYPE,
     THING_ROOT_BINDINGS,
     THING_ROOT_PROPERTY_DESCRIPTOR,
     THING_ROOT_CUSTOM,
     THING_ROOT_LIMIT
 };
 
--- a/js/src/jsversion.h
+++ b/js/src/jsversion.h
@@ -36,19 +36,9 @@
 #define JS_HAS_DESTRUCTURING_SHORTHAND  (JS_HAS_DESTRUCTURING == 2)
 
 /*
  * Feature for Object.prototype.__{define,lookup}{G,S}etter__ legacy support;
  * support likely to be made opt-in at some future time.
  */
 #define JS_OLD_GETTER_SETTER_METHODS    1
 
-/* A kill-switch for bug 586842.  Embedders shouldn't touch this! */
-#define JS_USE_NEW_OBJECT_REPRESENTATION 0
-
-#if JS_USE_NEW_OBJECT_REPRESENTATION
-# define JS_NEW_OBJECT_REPRESENTATION_ONLY() ((void)0)
-#else
-# define JS_NEW_OBJECT_REPRESENTATION_ONLY() \
-     MOZ_ASSUME_UNREACHABLE("don't call this!  to be used in the new object representation")
-#endif
-
 #endif /* jsversion_h */
--- a/js/src/shell/js.cpp
+++ b/js/src/shell/js.cpp
@@ -113,21 +113,17 @@ static size_t gMaxStackSize = 128 * size
  * Limit the timeout to 30 minutes to prevent an overflow on platfoms
  * that represent the time internally in microseconds using 32-bit int.
  */
 static double MAX_TIMEOUT_INTERVAL = 1800.0;
 static double gTimeoutInterval = -1.0;
 static volatile bool gTimedOut = false;
 static JS::Value gTimeoutFunc;
 
-static bool enableTypeInference = true;
 static bool enableDisassemblyDumps = false;
-static bool enableIon = true;
-static bool enableBaseline = true;
-static bool enableAsmJS = true;
 
 static bool printTiming = false;
 static const char *jsCacheDir = nullptr;
 static const char *jsCacheAsmJSPath = nullptr;
 static bool jsCachingEnabled = true;
 mozilla::Atomic<bool> jsCacheOpened(false);
 
 static bool
@@ -650,31 +646,32 @@ ResolvePath(JSContext *cx, HandleString 
     return JS_NewStringCopyZ(cx, buffer);
 }
 
 static bool
 Options(JSContext *cx, unsigned argc, jsval *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
-    JS::ContextOptions oldOptions = JS::ContextOptionsRef(cx);
+    JS::RuntimeOptions oldRuntimeOptions = JS::RuntimeOptionsRef(cx);
+    JS::ContextOptions oldContextOptions = JS::ContextOptionsRef(cx);
     for (unsigned i = 0; i < args.length(); i++) {
         JSString *str = JS::ToString(cx, args[i]);
         if (!str)
             return false;
         args[i].setString(str);
 
         JSAutoByteString opt(cx, str);
         if (!opt)
             return false;
 
         if (strcmp(opt.ptr(), "strict") == 0)
             JS::ContextOptionsRef(cx).toggleExtraWarnings();
         else if (strcmp(opt.ptr(), "typeinfer") == 0)
-            JS::ContextOptionsRef(cx).toggleTypeInference();
+            JS::RuntimeOptionsRef(cx).toggleTypeInference();
         else if (strcmp(opt.ptr(), "werror") == 0)
             JS::ContextOptionsRef(cx).toggleWerror();
         else if (strcmp(opt.ptr(), "strict_mode") == 0)
             JS::ContextOptionsRef(cx).toggleStrictMode();
         else {
             char* msg = JS_sprintf_append(nullptr,
                                           "unknown option name '%s'."
                                           " The valid names are strict,"
@@ -688,29 +685,29 @@ Options(JSContext *cx, unsigned argc, js
             JS_ReportError(cx, msg);
             free(msg);
             return false;
         }
     }
 
     char *names = strdup("");
     bool found = false;
-    if (!names && oldOptions.extraWarnings()) {
+    if (!names && oldContextOptions.extraWarnings()) {
         names = JS_sprintf_append(names, "%s%s", found ? "," : "", "strict");
         found = true;
     }
-    if (!names && oldOptions.typeInference()) {
+    if (!names && oldRuntimeOptions.typeInference()) {
         names = JS_sprintf_append(names, "%s%s", found ? "," : "", "typeinfer");
         found = true;
     }
-    if (!names && oldOptions.werror()) {
+    if (!names && oldContextOptions.werror()) {
         names = JS_sprintf_append(names, "%s%s", found ? "," : "", "werror");
         found = true;
     }
-    if (!names && oldOptions.strictMode()) {
+    if (!names && oldContextOptions.strictMode()) {
         names = JS_sprintf_append(names, "%s%s", found ? "," : "", "strict_mode");
         found = true;
     }
     if (!names) {
         JS_ReportOutOfMemory(cx);
         return false;
     }
 
@@ -5505,24 +5502,16 @@ NewContext(JSRuntime *rt)
     JSShellContextData *data = NewContextData();
     if (!data) {
         DestroyContext(cx, false);
         return nullptr;
     }
 
     JS_SetContextPrivate(cx, data);
     JS_SetErrorReporter(cx, my_ErrorReporter);
-    if (enableTypeInference)
-        JS::ContextOptionsRef(cx).toggleTypeInference();
-    if (enableIon)
-        JS::ContextOptionsRef(cx).toggleIon();
-    if (enableBaseline)
-        JS::ContextOptionsRef(cx).toggleBaseline();
-    if (enableAsmJS)
-        JS::ContextOptionsRef(cx).toggleAsmJS();
     return cx;
 }
 
 static void
 DestroyContext(JSContext *cx, bool withGC)
 {
     JSShellContextData *data = GetContextData(cx);
     JS_SetContextPrivate(cx, nullptr);
@@ -5614,202 +5603,37 @@ BindScriptArgs(JSContext *cx, JSObject *
 
     return true;
 }
 
 // This function is currently only called from "#if defined(JS_ION)" chunks,
 // so we're guarding the function definition with an #ifdef, too, to avoid
 // build warning for unused function in non-ion-enabled builds:
 #if defined(JS_ION)
-static int
+static bool
 OptionFailure(const char *option, const char *str)
 {
     fprintf(stderr, "Unrecognized option for %s: %s\n", option, str);
-    return EXIT_FAILURE;
+    return false;
 }
 #endif /* JS_ION */
 
 static int
 ProcessArgs(JSContext *cx, JSObject *obj_, OptionParser *op)
 {
     RootedObject obj(cx, obj_);
 
-    if (op->getBoolOption('c'))
-        compileOnly = true;
-
-    if (op->getBoolOption('w'))
-        reportWarnings = true;
-    else if (op->getBoolOption('W'))
-        reportWarnings = false;
-
     if (op->getBoolOption('s'))
         JS::ContextOptionsRef(cx).toggleExtraWarnings();
 
     if (op->getBoolOption('d')) {
         JS_SetRuntimeDebugMode(JS_GetRuntime(cx), true);
         JS_SetDebugMode(cx, true);
     }
 
-    jsCacheDir = op->getStringOption("js-cache");
-    if (jsCacheDir) {
-        if (op->getBoolOption("js-cache-per-process"))
-            jsCacheDir = JS_smprintf("%s/%u", jsCacheDir, (unsigned)getpid());
-        jsCacheAsmJSPath = JS_smprintf("%s/asmjs.cache", jsCacheDir);
-    }
-
-    if (op->getBoolOption('b'))
-        printTiming = true;
-
-    if (op->getBoolOption('D')) {
-        cx->runtime()->profilingScripts = true;
-        enableDisassemblyDumps = true;
-    }
-
-#ifdef JS_THREADSAFE
-    int32_t threadCount = op->getIntOption("thread-count");
-    if (threadCount >= 0)
-        SetFakeCPUCount(threadCount);
-#endif /* JS_THREADSAFE */
-
-#if defined(JS_ION)
-    if (op->getBoolOption("no-ion")) {
-        enableIon = false;
-        JS::ContextOptionsRef(cx).toggleIon();
-    }
-    if (op->getBoolOption("no-asmjs")) {
-        enableAsmJS = false;
-        JS::ContextOptionsRef(cx).toggleAsmJS();
-    }
-
-    if (op->getBoolOption("no-baseline")) {
-        enableBaseline = false;
-        JS::ContextOptionsRef(cx).toggleBaseline();
-    }
-
-    if (const char *str = op->getStringOption("ion-gvn")) {
-        if (strcmp(str, "off") == 0) {
-            jit::js_JitOptions.disableGvn = true;
-        } else if (strcmp(str, "pessimistic") == 0) {
-            jit::js_JitOptions.forceGvnKind = true;
-            jit::js_JitOptions.forcedGvnKind = jit::GVN_Pessimistic;
-        } else if (strcmp(str, "optimistic") == 0) {
-            jit::js_JitOptions.forceGvnKind = true;
-            jit::js_JitOptions.forcedGvnKind = jit::GVN_Optimistic;
-        } else {
-            return OptionFailure("ion-gvn", str);
-        }
-    }
-
-    if (const char *str = op->getStringOption("ion-licm")) {
-        if (strcmp(str, "on") == 0)
-            jit::js_JitOptions.disableLicm = false;
-        else if (strcmp(str, "off") == 0)
-            jit::js_JitOptions.disableLicm = true;
-        else
-            return OptionFailure("ion-licm", str);
-    }
-
-    if (const char *str = op->getStringOption("ion-edgecase-analysis")) {
-        if (strcmp(str, "on") == 0)
-            jit::js_JitOptions.disableEdgeCaseAnalysis = false;
-        else if (strcmp(str, "off") == 0)
-            jit::js_JitOptions.disableEdgeCaseAnalysis = true;
-        else
-            return OptionFailure("ion-edgecase-analysis", str);
-    }
-
-     if (const char *str = op->getStringOption("ion-range-analysis")) {
-         if (strcmp(str, "on") == 0)
-             jit::js_JitOptions.disableRangeAnalysis = false;
-         else if (strcmp(str, "off") == 0)
-             jit::js_JitOptions.disableRangeAnalysis = true;
-         else
-             return OptionFailure("ion-range-analysis", str);
-     }
-
-    if (op->getBoolOption("ion-check-range-analysis"))
-        jit::js_JitOptions.checkRangeAnalysis = true;
-
-    if (const char *str = op->getStringOption("ion-inlining")) {
-        if (strcmp(str, "on") == 0)
-            jit::js_JitOptions.disableInlining = false;
-        else if (strcmp(str, "off") == 0)
-            jit::js_JitOptions.disableInlining = true;
-        else
-            return OptionFailure("ion-inlining", str);
-    }
-
-    if (const char *str = op->getStringOption("ion-osr")) {
-        if (strcmp(str, "on") == 0)
-            jit::js_JitOptions.osr = true;
-        else if (strcmp(str, "off") == 0)
-            jit::js_JitOptions.osr = false;
-        else
-            return OptionFailure("ion-osr", str);
-    }
-
-    if (const char *str = op->getStringOption("ion-limit-script-size")) {
-        if (strcmp(str, "on") == 0)
-            jit::js_JitOptions.limitScriptSize = true;
-        else if (strcmp(str, "off") == 0)
-            jit::js_JitOptions.limitScriptSize = false;
-        else
-            return OptionFailure("ion-limit-script-size", str);
-    }
-
-    int32_t useCount = op->getIntOption("ion-uses-before-compile");
-    if (useCount >= 0)
-        jit::js_JitOptions.setUsesBeforeCompile(useCount);
-
-    useCount = op->getIntOption("baseline-uses-before-compile");
-    if (useCount >= 0)
-        jit::js_JitOptions.baselineUsesBeforeCompile = useCount;
-
-    if (op->getBoolOption("baseline-eager"))
-        jit::js_JitOptions.baselineUsesBeforeCompile = 0;
-
-    if (const char *str = op->getStringOption("ion-regalloc")) {
-        if (strcmp(str, "lsra") == 0) {
-            jit::js_JitOptions.forceRegisterAllocator = true;
-            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_LSRA;
-        } else if (strcmp(str, "backtracking") == 0) {
-            jit::js_JitOptions.forceRegisterAllocator = true;
-            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_Backtracking;
-        } else if (strcmp(str, "stupid") == 0) {
-            jit::js_JitOptions.forceRegisterAllocator = true;
-            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_Stupid;
-        } else {
-            return OptionFailure("ion-regalloc", str);
-        }
-    }
-
-    if (op->getBoolOption("ion-eager"))
-        jit::js_JitOptions.setEagerCompilation();
-
-    if (op->getBoolOption("ion-compile-try-catch"))
-        jit::js_JitOptions.compileTryCatch = true;
-
-    bool parallelCompilation = true;
-    if (const char *str = op->getStringOption("ion-parallel-compile")) {
-        if (strcmp(str, "off") == 0)
-            parallelCompilation = false;
-        else if (strcmp(str, "on") != 0)
-            return OptionFailure("ion-parallel-compile", str);
-    }
-#ifdef JS_THREADSAFE
-    cx->runtime()->setParallelIonCompilationEnabled(parallelCompilation);
-#endif
-
-#endif /* JS_ION */
-
-#ifdef DEBUG
-    if (op->getBoolOption("dump-entrained-variables"))
-        dumpEntrainedVariables = true;
-#endif
-
     /* |scriptArgs| gets bound on the global before any code is run. */
     if (!BindScriptArgs(cx, obj, op))
         return EXIT_FAILURE;
 
     MultiStringRange filePaths = op->getMultiStringOption('f');
     MultiStringRange codeChunks = op->getMultiStringOption('e');
 
     if (filePaths.empty() && codeChunks.empty() && !op->getStringArg("script")) {
@@ -5843,30 +5667,185 @@ ProcessArgs(JSContext *cx, JSObject *obj
     }
 
     if (op->getBoolOption('i'))
         Process(cx, obj, nullptr, true);
 
     return gExitCode ? gExitCode : EXIT_SUCCESS;
 }
 
+static bool
+SetRuntimeOptions(JSRuntime *rt, const OptionParser &op)
+{
+#if defined(JS_ION)
+    bool enableBaseline = !op.getBoolOption("no-baseline");
+    bool enableIon = !op.getBoolOption("no-ion");
+    bool enableTypeInference = !op.getBoolOption("no-ti");
+    bool enableAsmJS = !op.getBoolOption("no-asmjs");
+
+    JS::RuntimeOptionsRef(rt).setBaseline(enableBaseline)
+                             .setIon(enableIon)
+                             .setTypeInference(enableTypeInference)
+                             .setAsmJS(enableAsmJS);
+
+    if (const char *str = op.getStringOption("ion-gvn")) {
+        if (strcmp(str, "off") == 0) {
+            jit::js_JitOptions.disableGvn = true;
+        } else if (strcmp(str, "pessimistic") == 0) {
+            jit::js_JitOptions.forceGvnKind = true;
+            jit::js_JitOptions.forcedGvnKind = jit::GVN_Pessimistic;
+        } else if (strcmp(str, "optimistic") == 0) {
+            jit::js_JitOptions.forceGvnKind = true;
+            jit::js_JitOptions.forcedGvnKind = jit::GVN_Optimistic;
+        } else {
+            return OptionFailure("ion-gvn", str);
+        }
+    }
+
+    if (const char *str = op.getStringOption("ion-licm")) {
+        if (strcmp(str, "on") == 0)
+            jit::js_JitOptions.disableLicm = false;
+        else if (strcmp(str, "off") == 0)
+            jit::js_JitOptions.disableLicm = true;
+        else
+            return OptionFailure("ion-licm", str);
+    }
+
+    if (const char *str = op.getStringOption("ion-edgecase-analysis")) {
+        if (strcmp(str, "on") == 0)
+            jit::js_JitOptions.disableEdgeCaseAnalysis = false;
+        else if (strcmp(str, "off") == 0)
+            jit::js_JitOptions.disableEdgeCaseAnalysis = true;
+        else
+            return OptionFailure("ion-edgecase-analysis", str);
+    }
+
+     if (const char *str = op.getStringOption("ion-range-analysis")) {
+         if (strcmp(str, "on") == 0)
+             jit::js_JitOptions.disableRangeAnalysis = false;
+         else if (strcmp(str, "off") == 0)
+             jit::js_JitOptions.disableRangeAnalysis = true;
+         else
+             return OptionFailure("ion-range-analysis", str);
+     }
+
+    if (op.getBoolOption("ion-check-range-analysis"))
+        jit::js_JitOptions.checkRangeAnalysis = true;
+
+    if (const char *str = op.getStringOption("ion-inlining")) {
+        if (strcmp(str, "on") == 0)
+            jit::js_JitOptions.disableInlining = false;
+        else if (strcmp(str, "off") == 0)
+            jit::js_JitOptions.disableInlining = true;
+        else
+            return OptionFailure("ion-inlining", str);
+    }
+
+    if (const char *str = op.getStringOption("ion-osr")) {
+        if (strcmp(str, "on") == 0)
+            jit::js_JitOptions.osr = true;
+        else if (strcmp(str, "off") == 0)
+            jit::js_JitOptions.osr = false;
+        else
+            return OptionFailure("ion-osr", str);
+    }
+
+    if (const char *str = op.getStringOption("ion-limit-script-size")) {
+        if (strcmp(str, "on") == 0)
+            jit::js_JitOptions.limitScriptSize = true;
+        else if (strcmp(str, "off") == 0)
+            jit::js_JitOptions.limitScriptSize = false;
+        else
+            return OptionFailure("ion-limit-script-size", str);
+    }
+
+    int32_t useCount = op.getIntOption("ion-uses-before-compile");
+    if (useCount >= 0)
+        jit::js_JitOptions.setUsesBeforeCompile(useCount);
+
+    useCount = op.getIntOption("baseline-uses-before-compile");
+    if (useCount >= 0)
+        jit::js_JitOptions.baselineUsesBeforeCompile = useCount;
+
+    if (op.getBoolOption("baseline-eager"))
+        jit::js_JitOptions.baselineUsesBeforeCompile = 0;
+
+    if (const char *str = op.getStringOption("ion-regalloc")) {
+        if (strcmp(str, "lsra") == 0) {
+            jit::js_JitOptions.forceRegisterAllocator = true;
+            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_LSRA;
+        } else if (strcmp(str, "backtracking") == 0) {
+            jit::js_JitOptions.forceRegisterAllocator = true;
+            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_Backtracking;
+        } else if (strcmp(str, "stupid") == 0) {
+            jit::js_JitOptions.forceRegisterAllocator = true;
+            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_Stupid;
+        } else {
+            return OptionFailure("ion-regalloc", str);
+        }
+    }
+
+    if (op.getBoolOption("ion-eager"))
+        jit::js_JitOptions.setEagerCompilation();
+
+    if (op.getBoolOption("ion-compile-try-catch"))
+        jit::js_JitOptions.compileTryCatch = true;
+
+    bool parallelCompilation = true;
+    if (const char *str = op.getStringOption("ion-parallel-compile")) {
+        if (strcmp(str, "off") == 0)
+            parallelCompilation = false;
+        else if (strcmp(str, "on") != 0)
+            return OptionFailure("ion-parallel-compile", str);
+    }
+#ifdef JS_THREADSAFE
+    rt->setParallelIonCompilationEnabled(parallelCompilation);
+#endif
+
+#endif // JS_ION
+
+#ifdef JS_ARM_SIMULATOR
+    if (op.getBoolOption("arm-sim-icache-checks"))
+        jit::Simulator::ICacheCheckingEnabled = true;
+
+    int32_t stopAt = op.getIntOption("arm-sim-stop-at");
+    if (stopAt >= 0)
+        jit::Simulator::StopSimAt = stopAt;
+#endif
+
+    reportWarnings = op.getBoolOption('w');
+    compileOnly = op.getBoolOption('c');
+    printTiming = op.getBoolOption('b');
+    rt->profilingScripts = enableDisassemblyDumps = op.getBoolOption('D');
+
+    jsCacheDir = op.getStringOption("js-cache");
+    if (jsCacheDir) {
+        if (op.getBoolOption("js-cache-per-process"))
+            jsCacheDir = JS_smprintf("%s/%u", jsCacheDir, (unsigned)getpid());
+        jsCacheAsmJSPath = JS_smprintf("%s/asmjs.cache", jsCacheDir);
+    }
+
+#ifdef JS_THREADSAFE
+    int32_t threadCount = op.getIntOption("thread-count");
+    if (threadCount >= 0)
+        SetFakeCPUCount(threadCount);
+#endif /* JS_THREADSAFE */
+
+#ifdef DEBUG
+    dumpEntrainedVariables = op.getBoolOption("dump-entrained-variables");
+#endif
+
+    return true;
+}
+
 static int
 Shell(JSContext *cx, OptionParser *op, char **envp)
 {
     JSAutoRequest ar(cx);
 
-    /*
-     * First check to see if type inference is enabled. These flags
-     * must be set on the compartment when it is constructed.
-     */
-    if (op->getBoolOption("no-ti")) {
-        enableTypeInference = false;
-        JS::ContextOptionsRef(cx).toggleTypeInference();
-    }
-
     if (op->getBoolOption("fuzzing-safe"))
         fuzzingSafe = true;
     else
         fuzzingSafe = (getenv("MOZ_FUZZING_SAFE") && getenv("MOZ_FUZZING_SAFE")[0] != '0');
 
     RootedObject glob(cx);
     JS::CompartmentOptions options;
     options.setVersion(JSVERSION_LATEST);
@@ -6072,53 +6051,48 @@ main(int argc, char **argv, char **envp)
     if (op.getHelpOption())
         return EXIT_SUCCESS;
 
 #ifdef DEBUG
     /*
      * Process OOM options as early as possible so that we can observe as many
      * allocations as possible.
      */
-    if (op.getBoolOption('O'))
-        OOM_printAllocationCount = true;
+    OOM_printAllocationCount = op.getBoolOption('O');
 
 #if defined(JS_CODEGEN_X86) && defined(JS_ION)
     if (op.getBoolOption("no-fpu"))
         JSC::MacroAssembler::SetFloatingPointDisabled();
 #endif
 
 #if (defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)) && defined(JS_ION)
     if (op.getBoolOption("no-sse3")) {
         JSC::MacroAssembler::SetSSE3Disabled();
         PropagateFlagToNestedShells("--no-sse3");
     }
     if (op.getBoolOption("no-sse4")) {
         JSC::MacroAssembler::SetSSE4Disabled();
         PropagateFlagToNestedShells("--no-sse4");
     }
 #endif
-#endif
-
-#ifdef JS_ARM_SIMULATOR
-    if (op.getBoolOption("arm-sim-icache-checks"))
-        jit::Simulator::ICacheCheckingEnabled = true;
-
-    int32_t stopAt = op.getIntOption("arm-sim-stop-at");
-    if (stopAt >= 0)
-        jit::Simulator::StopSimAt = stopAt;
-#endif
+
+#endif // DEBUG
 
     // Start the engine.
     if (!JS_Init())
         return 1;
 
     /* Use the same parameters as the browser in xpcjsruntime.cpp. */
     rt = JS_NewRuntime(32L * 1024L * 1024L, JS_USE_HELPER_THREADS);
     if (!rt)
         return 1;
+
+    if (!SetRuntimeOptions(rt, op))
+        return 1;
+
     gTimeoutFunc = NullValue();
     if (!JS_AddNamedValueRootRT(rt, &gTimeoutFunc, "gTimeoutFunc"))
         return 1;
 
     JS_SetGCParameter(rt, JSGC_MAX_BYTES, 0xffffffff);
 #ifdef JSGC_GENERATIONAL
     Maybe<JS::AutoDisableGenerationalGC> noggc;
     if (op.getBoolOption("no-ggc"))
--- a/js/src/vm/ArrayBufferObject.cpp
+++ b/js/src/vm/ArrayBufferObject.cpp
@@ -39,21 +39,16 @@
 #include "vm/WrapperObject.h"
 
 #include "jsatominlines.h"
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 
 #include "vm/Shape-inl.h"
 
-#if JS_USE_NEW_OBJECT_REPRESENTATION
-// See the comment above OldObjectRepresentationHack.
-#  error "TypedArray support for new object representation unimplemented."
-#endif
-
 using namespace js;
 using namespace js::gc;
 using namespace js::types;
 
 /*
  * Allocate array buffers with the maximum number of fixed slots marked as
  * reserved, so that the fixed slots may be used for the buffer's contents.
  * The last fixed slot is kept for the object's private data.
--- a/js/src/vm/ArrayBufferObject.h
+++ b/js/src/vm/ArrayBufferObject.h
@@ -315,11 +315,97 @@ ArrayBufferViewObject::setBufferLink(Arr
 
 inline void
 ArrayBufferViewObject::setNextView(ArrayBufferViewObject *view)
 {
     setFixedSlot(NEXT_VIEW_SLOT, PrivateValue(view));
     PostBarrierTypedArrayObject(this);
 }
 
+extern uint32_t JS_FASTCALL
+ClampDoubleToUint8(const double x);
+
+struct uint8_clamped {
+    uint8_t val;
+
+    uint8_clamped() { }
+    uint8_clamped(const uint8_clamped& other) : val(other.val) { }
+
+    // invoke our assignment helpers for constructor conversion
+    uint8_clamped(uint8_t x)    { *this = x; }
+    uint8_clamped(uint16_t x)   { *this = x; }
+    uint8_clamped(uint32_t x)   { *this = x; }
+    uint8_clamped(int8_t x)     { *this = x; }
+    uint8_clamped(int16_t x)    { *this = x; }
+    uint8_clamped(int32_t x)    { *this = x; }
+    uint8_clamped(double x)     { *this = x; }
+
+    uint8_clamped& operator=(const uint8_clamped& x) {
+        val = x.val;
+        return *this;
+    }
+
+    uint8_clamped& operator=(uint8_t x) {
+        val = x;
+        return *this;
+    }
+
+    uint8_clamped& operator=(uint16_t x) {
+        val = (x > 255) ? 255 : uint8_t(x);
+        return *this;
+    }
+
+    uint8_clamped& operator=(uint32_t x) {
+        val = (x > 255) ? 255 : uint8_t(x);
+        return *this;
+    }
+
+    uint8_clamped& operator=(int8_t x) {
+        val = (x >= 0) ? uint8_t(x) : 0;
+        return *this;
+    }
+
+    uint8_clamped& operator=(int16_t x) {
+        val = (x >= 0)
+              ? ((x < 255)
+                 ? uint8_t(x)
+                 : 255)
+              : 0;
+        return *this;
+    }
+
+    uint8_clamped& operator=(int32_t x) {
+        val = (x >= 0)
+              ? ((x < 255)
+                 ? uint8_t(x)
+                 : 255)
+              : 0;
+        return *this;
+    }
+
+    uint8_clamped& operator=(const double x) {
+        val = uint8_t(ClampDoubleToUint8(x));
+        return *this;
+    }
+
+    operator uint8_t() const {
+        return val;
+    }
+
+    void staticAsserts() {
+        static_assert(sizeof(uint8_clamped) == 1,
+                      "uint8_clamped must be layout-compatible with uint8_t");
+    }
+};
+
+/* Note that we can't use std::numeric_limits here due to uint8_clamped. */
+template<typename T> inline const bool TypeIsFloatingPoint() { return false; }
+template<> inline const bool TypeIsFloatingPoint<float>() { return true; }
+template<> inline const bool TypeIsFloatingPoint<double>() { return true; }
+
+template<typename T> inline const bool TypeIsUnsigned() { return false; }
+template<> inline const bool TypeIsUnsigned<uint8_t>() { return true; }
+template<> inline const bool TypeIsUnsigned<uint16_t>() { return true; }
+template<> inline const bool TypeIsUnsigned<uint32_t>() { return true; }
+
 } // namespace js
 
 #endif // vm_ArrayBufferObject_h
--- a/js/src/vm/GlobalObject.h
+++ b/js/src/vm/GlobalObject.h
@@ -10,16 +10,17 @@
 #include "jsarray.h"
 #include "jsbool.h"
 #include "jsexn.h"
 #include "jsfun.h"
 #include "jsnum.h"
 
 #include "builtin/RegExp.h"
 #include "js/Vector.h"
+#include "vm/ArrayBufferObject.h"
 #include "vm/ErrorObject.h"
 
 extern JSObject *
 js_InitObjectClass(JSContext *cx, js::HandleObject obj);
 
 extern JSObject *
 js_InitFunctionClass(JSContext *cx, js::HandleObject obj);
 
--- a/js/src/vm/ObjectImpl.cpp
+++ b/js/src/vm/ObjectImpl.cpp
@@ -378,667 +378,30 @@ js::ObjectImpl::markChildren(JSTracer *t
         clasp->trace(trc, obj);
 
     if (shape_->isNative()) {
         MarkObjectSlots(trc, obj, 0, obj->slotSpan());
         gc::MarkArraySlots(trc, obj->getDenseInitializedLength(), obj->getDenseElements(), "objectElements");
     }
 }
 
-bool
-DenseElementsHeader::getOwnElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                                   unsigned resolveFlags, PropDesc *desc)
-{
-    MOZ_ASSERT(this == &obj->elementsHeader());
-
-    uint32_t len = initializedLength();
-    if (index >= len) {
-        *desc = PropDesc::undefined();
-        return true;
-    }
-
-    HeapSlot &slot = obj->elements[index];
-    if (slot.isMagic(JS_ELEMENTS_HOLE)) {
-        *desc = PropDesc::undefined();
-        return true;
-    }
-
-    *desc = PropDesc(slot, PropDesc::Writable, PropDesc::Enumerable, PropDesc::Configurable);
-    return true;
-}
-
-bool
-SparseElementsHeader::getOwnElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                                    unsigned resolveFlags, PropDesc *desc)
-{
-    MOZ_ASSERT(this == &obj->elementsHeader());
-
-    MOZ_ASSUME_UNREACHABLE("NYI");
-}
-
-template<typename T>
-static Value
-ElementToValue(const T &t)
-{
-    return NumberValue(t);
-}
-
-template<>
-/* static */ Value
-ElementToValue(const uint8_clamped &u)
-{
-    return NumberValue(uint8_t(u));
-}
-
-template<typename T>
-bool
-TypedElementsHeader<T>::getOwnElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                                      unsigned resolveFlags, PropDesc *desc)
-{
-    MOZ_ASSERT(this == &obj->elementsHeader());
-
-    if (index >= length()) {
-        *desc = PropDesc::undefined();
-        return true;
-    }
-
-    *desc = PropDesc(ElementToValue(getElement(index)), PropDesc::Writable,
-                     PropDesc::Enumerable, PropDesc::Configurable);
-    return false;
-}
-
-bool
-ArrayBufferElementsHeader::getOwnElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                                         unsigned resolveFlags, PropDesc *desc)
-{
-    MOZ_ASSERT(this == &obj->elementsHeader());
-
-    MOZ_ASSUME_UNREACHABLE("NYI");
-}
-
-bool
-SparseElementsHeader::defineElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                                    const PropDesc &desc, bool shouldThrow, unsigned resolveFlags,
-                                    bool *succeeded)
-{
-    MOZ_ASSERT(this == &obj->elementsHeader());
-
-    MOZ_ASSUME_UNREACHABLE("NYI");
-}
-
-bool
-DenseElementsHeader::defineElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                                   const PropDesc &desc, bool shouldThrow, unsigned resolveFlags,
-                                   bool *succeeded)
-{
-    MOZ_ASSERT(this == &obj->elementsHeader());
-
-    MOZ_ASSERT_IF(desc.hasGet() || desc.hasSet(), !desc.hasValue() && !desc.hasWritable());
-    MOZ_ASSERT_IF(desc.hasValue() || desc.hasWritable(), !desc.hasGet() && !desc.hasSet());
-
-    /*
-     * If desc is an accessor descriptor or a data descriptor with atypical
-     * attributes, convert to sparse and retry.
-     */
-    if (desc.hasGet() || desc.hasSet() ||
-        (desc.hasEnumerable() && !desc.enumerable()) ||
-        (desc.hasConfigurable() && !desc.configurable()) ||
-        (desc.hasWritable() && !desc.writable()))
-    {
-        if (!obj->makeElementsSparse(cx))
-            return false;
-        SparseElementsHeader &elts = obj->elementsHeader().asSparseElements();
-        return elts.defineElement(cx, obj, index, desc, shouldThrow, resolveFlags, succeeded);
-    }
-
-    /* Does the element exist?  All behavior depends upon this. */
-    uint32_t initLen = initializedLength();
-    if (index < initLen) {
-        HeapSlot &slot = obj->elements[index];
-        if (!slot.isMagic(JS_ELEMENTS_HOLE)) {
-            /*
-             * The element exists with attributes { [[Enumerable]]: true,
-             * [[Configurable]]: true, [[Writable]]: true, [[Value]]: slot }.
-             */
-            // XXX jwalden fill this in!
-        }
-    }
-
-    /*
-     * If the element doesn't exist, we can only add it if the object is
-     * extensible.
-     */
-    bool extensible;
-    if (!JSObject::isExtensible(cx, obj, &extensible))
-        return false;
-    if (!extensible) {
-        *succeeded = false;
-        if (!shouldThrow)
-            return true;
-        RootedValue val(cx, ObjectValue(*obj));
-        MOZ_ALWAYS_FALSE(js_ReportValueErrorFlags(cx, JSREPORT_ERROR, JSMSG_OBJECT_NOT_EXTENSIBLE,
-                                                  JSDVG_IGNORE_STACK,
-                                                  val, NullPtr(),
-                                                  nullptr, nullptr));
-        return false;
-    }
-
-    /* Otherwise we ensure space for it exists and that it's initialized. */
-    ObjectImpl::DenseElementsResult res = obj->ensureDenseElementsInitialized(cx, index, 0);
-
-    /* Propagate any error. */
-    if (res == ObjectImpl::Failure)
-        return false;
-
-    /* Otherwise, if the index was too far out of range, go sparse. */
-    if (res == ObjectImpl::ConvertToSparse) {
-        if (!obj->makeElementsSparse(cx))
-            return false;
-        SparseElementsHeader &elts = obj->elementsHeader().asSparseElements();
-        return elts.defineElement(cx, obj, index, desc, shouldThrow, resolveFlags, succeeded);
-    }
-
-    /* But if we were able to ensure the element's existence, we're good. */
-    MOZ_ASSERT(res == ObjectImpl::Succeeded);
-    obj->elements[index].set(obj->asObjectPtr(), HeapSlot::Element, index, desc.value());
-    *succeeded = true;
-    return true;
-}
-
 JSObject *
 js::ArrayBufferDelegate(JSContext *cx, Handle<ObjectImpl*> obj)
 {
     MOZ_ASSERT(obj->hasClass(&ArrayBufferObject::class_) ||
                obj->hasClass(&SharedArrayBufferObject::class_));
 
     if (obj->getPrivate())
         return static_cast<JSObject *>(obj->getPrivate());
     JSObject *delegate = NewObjectWithGivenProto(cx, &JSObject::class_,
                                                  obj->getTaggedProto(), nullptr);
     obj->setPrivateGCThing(delegate);
     return delegate;
 }
 
-template <typename T>
-bool
-TypedElementsHeader<T>::defineElement(JSContext *cx, Handle<ObjectImpl*> obj,
-                                      uint32_t index, const PropDesc &desc, bool shouldThrow,
-                                      unsigned resolveFlags, bool *succeeded)
-{
-    /* XXX jwalden This probably isn't how typed arrays should behave... */
-    *succeeded = false;
-
-    RootedValue val(cx, ObjectValue(*obj));
-    js_ReportValueErrorFlags(cx, JSREPORT_ERROR, JSMSG_OBJECT_NOT_EXTENSIBLE,
-                             JSDVG_IGNORE_STACK,
-                             val, NullPtr(), nullptr, nullptr);
-    return false;
-}
-
-bool
-ArrayBufferElementsHeader::defineElement(JSContext *cx, Handle<ObjectImpl*> obj,
-                                         uint32_t index, const PropDesc &desc, bool shouldThrow,
-                                         unsigned resolveFlags, bool *succeeded)
-{
-    MOZ_ASSERT(this == &obj->elementsHeader());
-
-    Rooted<JSObject*> delegate(cx, ArrayBufferDelegate(cx, obj));
-    if (!delegate)
-        return false;
-    return DefineElement(cx, delegate, index, desc, shouldThrow, resolveFlags, succeeded);
-}
-
-bool
-js::GetOwnProperty(JSContext *cx, Handle<ObjectImpl*> obj, PropertyId pid_, unsigned resolveFlags,
-                   PropDesc *desc)
-{
-    JS_NEW_OBJECT_REPRESENTATION_ONLY();
-
-    JS_CHECK_RECURSION(cx, return false);
-
-    Rooted<PropertyId> pid(cx, pid_);
-
-    if (Downcast(obj)->is<ProxyObject>())
-        MOZ_ASSUME_UNREACHABLE("NYI: proxy [[GetOwnProperty]]");
-
-    RootedShape shape(cx, obj->nativeLookup(cx, pid));
-    if (!shape) {
-        /* Not found: attempt to resolve it. */
-        const Class *clasp = obj->getClass();
-        JSResolveOp resolve = clasp->resolve;
-        if (resolve != JS_ResolveStub) {
-            Rooted<jsid> id(cx, pid.get().asId());
-            Rooted<JSObject*> robj(cx, static_cast<JSObject*>(obj.get()));
-            if (clasp->flags & JSCLASS_NEW_RESOLVE) {
-                Rooted<JSObject*> obj2(cx, nullptr);
-                JSNewResolveOp op = reinterpret_cast<JSNewResolveOp>(resolve);
-                if (!op(cx, robj, id, resolveFlags, &obj2))
-                    return false;
-            } else {
-                if (!resolve(cx, robj, id))
-                    return false;
-            }
-        }
-
-        /* Now look it up again. */
-        shape = obj->nativeLookup(cx, pid);
-        if (!shape) {
-            desc->setUndefined();
-            return true;
-        }
-    }
-
-    if (shape->isDataDescriptor()) {
-        *desc = PropDesc(obj->nativeGetSlot(shape->slot()), shape->writability(),
-                         shape->enumerability(), shape->configurability());
-        return true;
-    }
-
-    if (shape->isAccessorDescriptor()) {
-        *desc = PropDesc(shape->getterValue(), shape->setterValue(),
-                         shape->enumerability(), shape->configurability());
-        return true;
-    }
-
-    MOZ_ASSUME_UNREACHABLE("NYI: PropertyOp-based properties");
-}
-
-bool
-js::GetOwnElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index, unsigned resolveFlags,
-                  PropDesc *desc)
-{
-    ElementsHeader &header = obj->elementsHeader();
-    switch (header.kind()) {
-      case DenseElements:
-        return header.asDenseElements().getOwnElement(cx, obj, index, resolveFlags, desc);
-      case SparseElements:
-        return header.asSparseElements().getOwnElement(cx, obj, index, resolveFlags, desc);
-      case Uint8Elements:
-        return header.asUint8Elements().getOwnElement(cx, obj, index, resolveFlags, desc);
-      case Int8Elements:
-        return header.asInt8Elements().getOwnElement(cx, obj, index, resolveFlags, desc);
-      case Uint16Elements:
-        return header.asUint16Elements().getOwnElement(cx, obj, index, resolveFlags, desc);
-      case Int16Elements:
-        return header.asInt16Elements().getOwnElement(cx, obj, index, resolveFlags, desc);
-      case Uint32Elements:
-        return header.asUint32Elements().getOwnElement(cx, obj, index, resolveFlags, desc);
-      case Int32Elements:
-        return header.asInt32Elements().getOwnElement(cx, obj, index, resolveFlags, desc);
-      case Uint8ClampedElements:
-        return header.asUint8ClampedElements().getOwnElement(cx, obj, index, resolveFlags, desc);
-      case Float32Elements:
-        return header.asFloat32Elements().getOwnElement(cx, obj, index, resolveFlags, desc);
-      case Float64Elements:
-        return header.asFloat64Elements().getOwnElement(cx, obj, index, resolveFlags, desc);
-      case ArrayBufferElements:
-        return header.asArrayBufferElements().getOwnElement(cx, obj, index, resolveFlags, desc);
-    }
-
-    MOZ_ASSUME_UNREACHABLE("bad elements kind!");
-}
-
-bool
-js::GetProperty(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver,
-                Handle<PropertyId> pid, unsigned resolveFlags, MutableHandle<Value> vp)
-{
-    JS_NEW_OBJECT_REPRESENTATION_ONLY();
-
-    MOZ_ASSERT(receiver);
-
-    Rooted<ObjectImpl*> current(cx, obj);
-
-    do {
-        MOZ_ASSERT(obj);
-
-        if (Downcast(current)->is<ProxyObject>())
-            MOZ_ASSUME_UNREACHABLE("NYI: proxy [[GetP]]");
-
-        AutoPropDescRooter desc(cx);
-        if (!GetOwnProperty(cx, current, pid, resolveFlags, &desc.getPropDesc()))
-            return false;
-
-        /* No property?  Recur or bottom out. */
-        if (desc.isUndefined()) {
-            current = current->getTaggedProto().toObjectOrNull();
-            if (current)
-                continue;
-
-            vp.setUndefined();
-            return true;
-        }
-
-        /* If it's a data property, return the value. */
-        if (desc.isDataDescriptor()) {
-            vp.set(desc.value());
-            return true;
-        }
-
-        /* If it's an accessor property, call its [[Get]] with the receiver. */
-        if (desc.isAccessorDescriptor()) {
-            Rooted<Value> get(cx, desc.getterValue());
-            if (get.isUndefined()) {
-                vp.setUndefined();
-                return true;
-            }
-
-            InvokeArgs args(cx);
-            if (!args.init(0))
-                return false;
-
-            args.setCallee(get);
-            args.setThis(ObjectValue(*receiver));
-
-            bool ok = Invoke(cx, args);
-            vp.set(args.rval());
-            return ok;
-        }
-
-        /* Otherwise it's a PropertyOp-based property.  XXX handle this! */
-        MOZ_ASSUME_UNREACHABLE("NYI: handle PropertyOp'd properties here");
-    } while (false);
-
-    MOZ_ASSUME_UNREACHABLE("buggy control flow");
-}
-
-bool
-js::GetElement(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver, uint32_t index,
-               unsigned resolveFlags, Value *vp)
-{
-    JS_NEW_OBJECT_REPRESENTATION_ONLY();
-
-    Rooted<ObjectImpl*> current(cx, obj);
-
-    RootedValue getter(cx);
-    do {
-        MOZ_ASSERT(current);
-
-        if (Downcast(current)->is<ProxyObject>())
-            MOZ_ASSUME_UNREACHABLE("NYI: proxy [[GetP]]");
-
-        PropDesc desc;
-        if (!GetOwnElement(cx, current, index, resolveFlags, &desc))
-            return false;
-
-        /* No property?  Recur or bottom out. */
-        if (desc.isUndefined()) {
-            current = current->getTaggedProto().toObjectOrNull();
-            if (current)
-                continue;
-
-            vp->setUndefined();
-            return true;
-        }
-
-        /* If it's a data property, return the value. */
-        if (desc.isDataDescriptor()) {
-            *vp = desc.value();
-            return true;
-        }
-
-        /* If it's an accessor property, call its [[Get]] with the receiver. */
-        if (desc.isAccessorDescriptor()) {
-            getter = desc.getterValue();
-            if (getter.isUndefined()) {
-                vp->setUndefined();
-                return true;
-            }
-
-            InvokeArgs args(cx);
-            if (!args.init(0))
-                return false;
-
-            /* Push getter, receiver, and no args. */
-            args.setCallee(getter);
-            args.setThis(ObjectValue(*current));
-
-            bool ok = Invoke(cx, args);
-            *vp = args.rval();
-            return ok;
-        }
-
-        /* Otherwise it's a PropertyOp-based property.  XXX handle this! */
-        MOZ_ASSUME_UNREACHABLE("NYI: handle PropertyOp'd properties here");
-    } while (false);
-
-    MOZ_ASSUME_UNREACHABLE("buggy control flow");
-}
-
-bool
-js::HasElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index, unsigned resolveFlags,
-               bool *found)
-{
-    JS_NEW_OBJECT_REPRESENTATION_ONLY();
-
-    Rooted<ObjectImpl*> current(cx, obj);
-
-    do {
-        MOZ_ASSERT(current);
-
-        if (Downcast(current)->is<ProxyObject>())
-            MOZ_ASSUME_UNREACHABLE("NYI: proxy [[HasProperty]]");
-
-        PropDesc prop;
-        if (!GetOwnElement(cx, current, index, resolveFlags, &prop))
-            return false;
-
-        if (!prop.isUndefined()) {
-            *found = true;
-            return true;
-        }
-
-        current = current->getTaggedProto().toObjectOrNull();
-        if (current)
-            continue;
-
-        *found = false;
-        return true;
-    } while (false);
-
-    MOZ_ASSUME_UNREACHABLE("buggy control flow");
-}
-
-bool
-js::DefineElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index, const PropDesc &desc,
-                  bool shouldThrow, unsigned resolveFlags, bool *succeeded)
-{
-    JS_NEW_OBJECT_REPRESENTATION_ONLY();
-
-    ElementsHeader &header = obj->elementsHeader();
-
-    switch (header.kind()) {
-      case DenseElements:
-        return header.asDenseElements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                      resolveFlags, succeeded);
-      case SparseElements:
-        return header.asSparseElements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                       resolveFlags, succeeded);
-      case Uint8Elements:
-        return header.asUint8Elements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                      resolveFlags, succeeded);
-      case Int8Elements:
-        return header.asInt8Elements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                     resolveFlags, succeeded);
-      case Uint16Elements:
-        return header.asUint16Elements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                       resolveFlags, succeeded);
-      case Int16Elements:
-        return header.asInt16Elements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                      resolveFlags, succeeded);
-      case Uint32Elements:
-        return header.asUint32Elements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                       resolveFlags, succeeded);
-      case Int32Elements:
-        return header.asInt32Elements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                      resolveFlags, succeeded);
-      case Uint8ClampedElements:
-        return header.asUint8ClampedElements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                             resolveFlags, succeeded);
-      case Float32Elements:
-        return header.asFloat32Elements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                        resolveFlags, succeeded);
-      case Float64Elements:
-        return header.asFloat64Elements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                        resolveFlags, succeeded);
-      case ArrayBufferElements:
-        return header.asArrayBufferElements().defineElement(cx, obj, index, desc, shouldThrow,
-                                                            resolveFlags, succeeded);
-    }
-
-    MOZ_ASSUME_UNREACHABLE("bad elements kind!");
-}
-
-bool
-SparseElementsHeader::setElement(JSContext *cx, Handle<ObjectImpl*> obj,
-                                 Handle<ObjectImpl*> receiver, uint32_t index, const Value &v,
-                                 unsigned resolveFlags, bool *succeeded)
-{
-    MOZ_ASSERT(this == &obj->elementsHeader());
-
-    MOZ_ASSUME_UNREACHABLE("NYI");
-}
-
-bool
-DenseElementsHeader::setElement(JSContext *cx, Handle<ObjectImpl*> obj,
-                                Handle<ObjectImpl*> receiver, uint32_t index, const Value &v,
-                                unsigned resolveFlags, bool *succeeded)
-{
-    MOZ_ASSERT(this == &obj->elementsHeader());
-
-    MOZ_ASSUME_UNREACHABLE("NYI");
-}
-
-template <typename T>
-bool
-TypedElementsHeader<T>::setElement(JSContext *cx, Handle<ObjectImpl*> obj,
-                                   Handle<ObjectImpl*> receiver, uint32_t index, const Value &v,
-                                   unsigned resolveFlags, bool *succeeded)
-{
-    MOZ_ASSERT(this == &obj->elementsHeader());
-
-    uint32_t len = length();
-    if (index >= len) {
-        /*
-         * Silent ignore is better than an exception here, because at some
-         * point we may want to support other properties on these objects.
-         */
-        *succeeded = true;
-        return true;
-    }
-
-    /* Convert the value being set to the element type. */
-    double d;
-    if (v.isNumber()) {
-        d = v.toNumber();
-    } else if (v.isNull()) {
-        d = 0.0;
-    } else if (v.isPrimitive()) {
-        if (v.isString()) {
-            if (!StringToNumber(cx, v.toString(), &d))
-                return false;
-        } else if (v.isUndefined()) {
-            d = GenericNaN();
-        } else {
-            d = double(v.toBoolean());
-        }
-    } else {
-        // non-primitive assignments become NaN or 0 (for float/int arrays)
-        d = GenericNaN();
-    }
-
-    assign(index, d);
-    *succeeded = true;
-    return true;
-}
-
-bool
-ArrayBufferElementsHeader::setElement(JSContext *cx, Handle<ObjectImpl*> obj,
-                                      Handle<ObjectImpl*> receiver, uint32_t index, const Value &v,
-                                      unsigned resolveFlags, bool *succeeded)
-{
-    MOZ_ASSERT(this == &obj->elementsHeader());
-
-    JSObject *delegate = ArrayBufferDelegate(cx, obj);
-    if (!delegate)
-        return false;
-    return SetElement(cx, obj, receiver, index, v, resolveFlags, succeeded);
-}
-
-bool
-js::SetElement(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver,
-               uint32_t index, const Value &v, unsigned resolveFlags, bool *succeeded)
-{
-    JS_NEW_OBJECT_REPRESENTATION_ONLY();
-
-    Rooted<ObjectImpl*> current(cx, obj);
-    RootedValue setter(cx);
-
-    MOZ_ASSERT(receiver);
-
-    do {
-        MOZ_ASSERT(current);
-
-        if (Downcast(current)->is<ProxyObject>())
-            MOZ_ASSUME_UNREACHABLE("NYI: proxy [[SetP]]");
-
-        PropDesc ownDesc;
-        if (!GetOwnElement(cx, current, index, resolveFlags, &ownDesc))
-            return false;
-
-        if (!ownDesc.isUndefined()) {
-            if (ownDesc.isDataDescriptor()) {
-                if (!ownDesc.writable()) {
-                    *succeeded = false;
-                    return true;
-                }
-
-                if (receiver == current) {
-                    PropDesc updateDesc = PropDesc::valueOnly(v);
-                    return DefineElement(cx, receiver, index, updateDesc, false, resolveFlags,
-                                         succeeded);
-                }
-
-                PropDesc newDesc;
-                return DefineElement(cx, receiver, index, newDesc, false, resolveFlags, succeeded);
-            }
-
-            if (ownDesc.isAccessorDescriptor()) {
-                setter = ownDesc.setterValue();
-                if (setter.isUndefined()) {
-                    *succeeded = false;
-                    return true;
-                }
-
-                InvokeArgs args(cx);
-                if (!args.init(1))
-                    return false;
-
-                /* Push set, receiver, and v as the sole argument. */
-                args.setCallee(setter);
-                args.setThis(ObjectValue(*current));
-                args[0].set(v);
-
-                *succeeded = true;
-                return Invoke(cx, args);
-            }
-
-            MOZ_ASSUME_UNREACHABLE("NYI: setting PropertyOp-based property");
-        }
-
-        current = current->getTaggedProto().toObjectOrNull();
-        if (current)
-            continue;
-
-        PropDesc newDesc(v, PropDesc::Writable, PropDesc::Enumerable, PropDesc::Configurable);
-        return DefineElement(cx, receiver, index, newDesc, false, resolveFlags, succeeded);
-    } while (false);
-
-    MOZ_ASSUME_UNREACHABLE("buggy control flow");
-}
-
 void
 AutoPropDescRooter::trace(JSTracer *trc)
 {
     gc::MarkValueRoot(trc, &propDesc.pd_, "AutoPropDescRooter pd");
     gc::MarkValueRoot(trc, &propDesc.value_, "AutoPropDescRooter value");
     gc::MarkValueRoot(trc, &propDesc.get_, "AutoPropDescRooter get");
     gc::MarkValueRoot(trc, &propDesc.set_, "AutoPropDescRooter set");
 }
--- a/js/src/vm/ObjectImpl.h
+++ b/js/src/vm/ObjectImpl.h
@@ -72,607 +72,17 @@ Debug_SetSlotRangeToCrashOnTouch(HeapSlo
 static MOZ_ALWAYS_INLINE void
 Debug_SetSlotRangeToCrashOnTouch(HeapSlot *begin, HeapSlot *end)
 {
 #ifdef DEBUG
     Debug_SetValueRangeToCrashOnTouch((Value *) begin, end - begin);
 #endif
 }
 
-/*
- * Properties are stored differently depending on the type of the key.  If the
- * key is an unsigned 32-bit integer (i.e. an index), we call such properties
- * "elements" and store them in one of a number of forms (optimized for dense
- * property storage, typed array data, and so on).  All other properties are
- * stored using shapes and shape trees.  Keys for these properties are either
- * PropertyNames (that is, atomized strings whose contents are not unsigned
- * 32-bit integers) or SpecialIds (see jsid for details); the union of these
- * types, used in individual shapes, is PropertyId.
- */
-class PropertyId
-{
-    jsid id;
-
-  public:
-    bool isName() const {
-        MOZ_ASSERT(JSID_IS_STRING(id) || JSID_IS_SPECIAL(id));
-        return JSID_IS_STRING(id);
-    }
-    bool isSpecial() const {
-        MOZ_ASSERT(JSID_IS_STRING(id) || JSID_IS_SPECIAL(id));
-        return !isName();
-    }
-
-    PropertyId() {
-        *this = PropertyId(SpecialId());
-    }
-    explicit PropertyId(PropertyName *name)
-      : id(NON_INTEGER_ATOM_TO_JSID(name))
-    { }
-    explicit PropertyId(const SpecialId &sid)
-      : id(SPECIALID_TO_JSID(sid))
-    { }
-
-    PropertyName * asName() const {
-        return JSID_TO_STRING(id)->asAtom().asPropertyName();
-    }
-    SpecialId asSpecial() const {
-        return JSID_TO_SPECIALID(id);
-    }
-    const jsid &asId() const {
-        return id;
-    }
-    jsid &asId() {
-        return id;
-    }
-
-    bool operator==(const PropertyId &rhs) const { return id == rhs.id; }
-    bool operator!=(const PropertyId &rhs) const { return id != rhs.id; }
-};
-
-class DenseElementsHeader;
-class SparseElementsHeader;
-class Uint8ElementsHeader;
-class Int8ElementsHeader;
-class Uint16ElementsHeader;
-class Int16ElementsHeader;
-class Uint32ElementsHeader;
-class Int32ElementsHeader;
-class Uint8ClampedElementsHeader;
-class Float32ElementsHeader;
-class Float64ElementsHeader;
-class Uint8ClampedElementsHeader;
-class ArrayBufferElementsHeader;
-
-enum ElementsKind {
-    DenseElements,
-    SparseElements,
-
-    ArrayBufferElements,
-
-    /* These typed element types must remain contiguous. */
-    Uint8Elements,
-    Int8Elements,
-    Uint16Elements,
-    Int16Elements,
-    Uint32Elements,
-    Int32Elements,
-    Uint8ClampedElements,
-    Float32Elements,
-    Float64Elements
-};
-
-class ElementsHeader
-{
-  protected:
-    uint32_t type;
-    uint32_t length; /* Array length, ArrayBuffer length, typed array length */
-
-    union {
-        class {
-            friend class DenseElementsHeader;
-            uint32_t initializedLength;
-            uint32_t capacity;
-        } dense;
-        class {
-            friend class SparseElementsHeader;
-            Shape *shape;
-        } sparse;
-        class {
-            friend class ArrayBufferElementsHeader;
-            JSObject * views;
-        } buffer;
-    };
-
-    void staticAsserts() {
-        static_assert(sizeof(ElementsHeader) == ValuesPerHeader * sizeof(Value),
-                      "Elements size and values-per-Elements mismatch");
-    }
-
-  public:
-    ElementsKind kind() const {
-        MOZ_ASSERT(type <= ArrayBufferElements);
-        return ElementsKind(type);
-    }
-
-    inline bool isDenseElements() const { return kind() == DenseElements; }
-    inline bool isSparseElements() const { return kind() == SparseElements; }
-    inline bool isArrayBufferElements() const { return kind() == ArrayBufferElements; }
-    inline bool isUint8Elements() const { return kind() == Uint8Elements; }
-    inline bool isInt8Elements() const { return kind() == Int8Elements; }
-    inline bool isUint16Elements() const { return kind() == Uint16Elements; }
-    inline bool isInt16Elements() const { return kind() == Int16Elements; }
-    inline bool isUint32Elements() const { return kind() == Uint32Elements; }
-    inline bool isInt32Elements() const { return kind() == Int32Elements; }
-    inline bool isUint8ClampedElements() const { return kind() == Uint8ClampedElements; }
-    inline bool isFloat32Elements() const { return kind() == Float32Elements; }
-    inline bool isFloat64Elements() const { return kind() == Float64Elements; }
-
-    inline DenseElementsHeader & asDenseElements();
-    inline SparseElementsHeader & asSparseElements();
-    inline ArrayBufferElementsHeader & asArrayBufferElements();
-    inline Uint8ElementsHeader & asUint8Elements();
-    inline Int8ElementsHeader & asInt8Elements();
-    inline Uint16ElementsHeader & asUint16Elements();
-    inline Int16ElementsHeader & asInt16Elements();
-    inline Uint32ElementsHeader & asUint32Elements();
-    inline Int32ElementsHeader & asInt32Elements();
-    inline Uint8ClampedElementsHeader & asUint8ClampedElements();
-    inline Float32ElementsHeader & asFloat32Elements();
-    inline Float64ElementsHeader & asFloat64Elements();
-
-    static ElementsHeader * fromElements(HeapSlot *elems) {
-        return reinterpret_cast<ElementsHeader *>(uintptr_t(elems) - sizeof(ElementsHeader));
-    }
-
-    static const size_t ValuesPerHeader = 2;
-};
-
-class DenseElementsHeader : public ElementsHeader
-{
-  public:
-    uint32_t capacity() const {
-        MOZ_ASSERT(ElementsHeader::isDenseElements());
-        return dense.capacity;
-    }
-
-    uint32_t initializedLength() const {
-        MOZ_ASSERT(ElementsHeader::isDenseElements());
-        return dense.initializedLength;
-    }
-
-    uint32_t length() const {
-        MOZ_ASSERT(ElementsHeader::isDenseElements());
-        return ElementsHeader::length;
-    }
-
-    bool getOwnElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                       unsigned resolveFlags, PropDesc *desc);
-
-    bool defineElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                       const PropDesc &desc, bool shouldThrow, unsigned resolveFlags,
-                       bool *succeeded);
-
-    bool setElement(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver,
-                    uint32_t index, const Value &v, unsigned resolveFlags, bool *succeeded);
-
-  private:
-    inline bool isDenseElements() const MOZ_DELETE;
-    inline DenseElementsHeader & asDenseElements() MOZ_DELETE;
-
-    DenseElementsHeader(const DenseElementsHeader &other) MOZ_DELETE;
-    void operator=(const DenseElementsHeader &other) MOZ_DELETE;
-};
-
-class SparseElementsHeader : public ElementsHeader
-{
-  public:
-    Shape *shape() {
-        MOZ_ASSERT(ElementsHeader::isSparseElements());
-        return sparse.shape;
-    }
-
-    uint32_t length() const {
-        MOZ_ASSERT(ElementsHeader::isSparseElements());
-        return ElementsHeader::length;
-    }
-
-    bool getOwnElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                       unsigned resolveFlags, PropDesc *desc);
-
-    bool defineElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                       const PropDesc &desc, bool shouldThrow, unsigned resolveFlags,
-                       bool *succeeded);
-
-    bool setElement(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver,
-                    uint32_t index, const Value &v, unsigned resolveFlags, bool *succeeded);
-
-  private:
-    inline bool isSparseElements() const MOZ_DELETE;
-    inline SparseElementsHeader & asSparseElements() MOZ_DELETE;
-
-    SparseElementsHeader(const SparseElementsHeader &other) MOZ_DELETE;
-    void operator=(const SparseElementsHeader &other) MOZ_DELETE;
-};
-
-extern uint32_t JS_FASTCALL
-ClampDoubleToUint8(const double x);
-
-struct uint8_clamped {
-    uint8_t val;
-
-    uint8_clamped() { }
-    uint8_clamped(const uint8_clamped& other) : val(other.val) { }
-
-    // invoke our assignment helpers for constructor conversion
-    uint8_clamped(uint8_t x)    { *this = x; }
-    uint8_clamped(uint16_t x)   { *this = x; }
-    uint8_clamped(uint32_t x)   { *this = x; }
-    uint8_clamped(int8_t x)     { *this = x; }
-    uint8_clamped(int16_t x)    { *this = x; }
-    uint8_clamped(int32_t x)    { *this = x; }
-    uint8_clamped(double x)     { *this = x; }
-
-    uint8_clamped& operator=(const uint8_clamped& x) {
-        val = x.val;
-        return *this;
-    }
-
-    uint8_clamped& operator=(uint8_t x) {
-        val = x;
-        return *this;
-    }
-
-    uint8_clamped& operator=(uint16_t x) {
-        val = (x > 255) ? 255 : uint8_t(x);
-        return *this;
-    }
-
-    uint8_clamped& operator=(uint32_t x) {
-        val = (x > 255) ? 255 : uint8_t(x);
-        return *this;
-    }
-
-    uint8_clamped& operator=(int8_t x) {
-        val = (x >= 0) ? uint8_t(x) : 0;
-        return *this;
-    }
-
-    uint8_clamped& operator=(int16_t x) {
-        val = (x >= 0)
-              ? ((x < 255)
-                 ? uint8_t(x)
-                 : 255)
-              : 0;
-        return *this;
-    }
-
-    uint8_clamped& operator=(int32_t x) {
-        val = (x >= 0)
-              ? ((x < 255)
-                 ? uint8_t(x)
-                 : 255)
-              : 0;
-        return *this;
-    }
-
-    uint8_clamped& operator=(const double x) {
-        val = uint8_t(ClampDoubleToUint8(x));
-        return *this;
-    }
-
-    operator uint8_t() const {
-        return val;
-    }
-
-    void staticAsserts() {
-        static_assert(sizeof(uint8_clamped) == 1,
-                      "uint8_clamped must be layout-compatible with uint8_t");
-    }
-};
-
-/* Note that we can't use std::numeric_limits here due to uint8_clamped. */
-template<typename T> inline const bool TypeIsFloatingPoint() { return false; }
-template<> inline const bool TypeIsFloatingPoint<float>() { return true; }
-template<> inline const bool TypeIsFloatingPoint<double>() { return true; }
-
-template<typename T> inline const bool TypeIsUnsigned() { return false; }
-template<> inline const bool TypeIsUnsigned<uint8_t>() { return true; }
-template<> inline const bool TypeIsUnsigned<uint16_t>() { return true; }
-template<> inline const bool TypeIsUnsigned<uint32_t>() { return true; }
-
-template <typename T>
-class TypedElementsHeader : public ElementsHeader
-{
-    T getElement(uint32_t index) {
-        MOZ_ASSERT(index < length());
-        return reinterpret_cast<T *>(this + 1)[index];
-    }
-
-    inline void assign(uint32_t index, double d);
-
-    void setElement(uint32_t index, T value) {
-        MOZ_ASSERT(index < length());
-        reinterpret_cast<T *>(this + 1)[index] = value;
-    }
-
-  public:
-    uint32_t length() const {
-        MOZ_ASSERT(Uint8Elements <= kind());
-        MOZ_ASSERT(kind() <= Float64Elements);
-        return ElementsHeader::length;
-    }
-
-    bool getOwnElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                       unsigned resolveFlags, PropDesc *desc);
-
-    bool defineElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                       const PropDesc &desc, bool shouldThrow, unsigned resolveFlags,
-                       bool *succeeded);
-
-    bool setElement(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver,
-                    uint32_t index, const Value &v, unsigned resolveFlags, bool *succeeded);
-
-  private:
-    TypedElementsHeader(const TypedElementsHeader &other) MOZ_DELETE;
-    void operator=(const TypedElementsHeader &other) MOZ_DELETE;
-};
-
-template<typename T> inline void
-TypedElementsHeader<T>::assign(uint32_t index, double d)
-{
-    MOZ_ASSUME_UNREACHABLE("didn't specialize for this element type");
-}
-
-template<> inline void
-TypedElementsHeader<uint8_clamped>::assign(uint32_t index, double d)
-{
-    double i = ToInteger(d);
-    uint8_t u = (i <= 0)
-                ? 0
-                : (i >= 255)
-                ? 255
-                : uint8_t(i);
-    setElement(index, uint8_clamped(u));
-}
-
-template<> inline void
-TypedElementsHeader<uint8_t>::assign(uint32_t index, double d)
-{
-    setElement(index, uint8_t(ToUint32(d)));
-}
-
-template<> inline void
-TypedElementsHeader<int8_t>::assign(uint32_t index, double d)
-{
-    /* FIXME: Casting out-of-range signed integers has undefined behavior! */
-    setElement(index, int8_t(ToInt32(d)));
-}
-
-template<> inline void
-TypedElementsHeader<uint16_t>::assign(uint32_t index, double d)
-{
-    setElement(index, uint16_t(ToUint32(d)));
-}
-
-template<> inline void
-TypedElementsHeader<int16_t>::assign(uint32_t index, double d)
-{
-    /* FIXME: Casting out-of-range signed integers has undefined behavior! */
-    setElement(index, int16_t(ToInt32(d)));
-}
-
-template<> inline void
-TypedElementsHeader<uint32_t>::assign(uint32_t index, double d)
-{
-    setElement(index, ToUint32(d));
-}
-
-template<> inline void
-TypedElementsHeader<int32_t>::assign(uint32_t index, double d)
-{
-    /* FIXME: Casting out-of-range signed integers has undefined behavior! */
-    setElement(index, int32_t(ToInt32(d)));
-}
-
-template<> inline void
-TypedElementsHeader<float>::assign(uint32_t index, double d)
-{
-    setElement(index, float(d));
-}
-
-template<> inline void
-TypedElementsHeader<double>::assign(uint32_t index, double d)
-{
-    setElement(index, d);
-}
-
-class Uint8ElementsHeader : public TypedElementsHeader<uint8_t>
-{
-  private:
-    inline bool isUint8Elements() const MOZ_DELETE;
-    inline Uint8ElementsHeader & asUint8Elements() MOZ_DELETE;
-    Uint8ElementsHeader(const Uint8ElementsHeader &other) MOZ_DELETE;
-    void operator=(const Uint8ElementsHeader &other) MOZ_DELETE;
-};
-class Int8ElementsHeader : public TypedElementsHeader<int8_t>
-{
-  private:
-    bool isInt8Elements() const MOZ_DELETE;
-    Int8ElementsHeader & asInt8Elements() MOZ_DELETE;
-    Int8ElementsHeader(const Int8ElementsHeader &other) MOZ_DELETE;
-    void operator=(const Int8ElementsHeader &other) MOZ_DELETE;
-};
-class Uint16ElementsHeader : public TypedElementsHeader<uint16_t>
-{
-  private:
-    bool isUint16Elements() const MOZ_DELETE;
-    Uint16ElementsHeader & asUint16Elements() MOZ_DELETE;
-    Uint16ElementsHeader(const Uint16ElementsHeader &other) MOZ_DELETE;
-    void operator=(const Uint16ElementsHeader &other) MOZ_DELETE;
-};
-class Int16ElementsHeader : public TypedElementsHeader<int16_t>
-{
-  private:
-    bool isInt16Elements() const MOZ_DELETE;
-    Int16ElementsHeader & asInt16Elements() MOZ_DELETE;
-    Int16ElementsHeader(const Int16ElementsHeader &other) MOZ_DELETE;
-    void operator=(const Int16ElementsHeader &other) MOZ_DELETE;
-};
-class Uint32ElementsHeader : public TypedElementsHeader<uint32_t>
-{
-  private:
-    bool isUint32Elements() const MOZ_DELETE;
-    Uint32ElementsHeader & asUint32Elements() MOZ_DELETE;
-    Uint32ElementsHeader(const Uint32ElementsHeader &other) MOZ_DELETE;
-    void operator=(const Uint32ElementsHeader &other) MOZ_DELETE;
-};
-class Int32ElementsHeader : public TypedElementsHeader<int32_t>
-{
-  private:
-    bool isInt32Elements() const MOZ_DELETE;
-    Int32ElementsHeader & asInt32Elements() MOZ_DELETE;
-    Int32ElementsHeader(const Int32ElementsHeader &other) MOZ_DELETE;
-    void operator=(const Int32ElementsHeader &other) MOZ_DELETE;
-};
-class Float32ElementsHeader : public TypedElementsHeader<float>
-{
-  private:
-    bool isFloat32Elements() const MOZ_DELETE;
-    Float32ElementsHeader & asFloat32Elements() MOZ_DELETE;
-    Float32ElementsHeader(const Float32ElementsHeader &other) MOZ_DELETE;
-    void operator=(const Float32ElementsHeader &other) MOZ_DELETE;
-};
-class Float64ElementsHeader : public TypedElementsHeader<double>
-{
-  private:
-    bool isFloat64Elements() const MOZ_DELETE;
-    Float64ElementsHeader & asFloat64Elements() MOZ_DELETE;
-    Float64ElementsHeader(const Float64ElementsHeader &other) MOZ_DELETE;
-    void operator=(const Float64ElementsHeader &other) MOZ_DELETE;
-};
-
-class Uint8ClampedElementsHeader : public TypedElementsHeader<uint8_clamped>
-{
-  private:
-    inline bool isUint8Clamped() const MOZ_DELETE;
-    inline Uint8ClampedElementsHeader & asUint8ClampedElements() MOZ_DELETE;
-    Uint8ClampedElementsHeader(const Uint8ClampedElementsHeader &other) MOZ_DELETE;
-    void operator=(const Uint8ClampedElementsHeader &other) MOZ_DELETE;
-};
-
-class ArrayBufferElementsHeader : public ElementsHeader
-{
-  public:
-    bool getOwnElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                       unsigned resolveFlags, PropDesc *desc);
-
-    bool defineElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index,
-                       const PropDesc &desc, bool shouldThrow, unsigned resolveFlags,
-                       bool *succeeded);
-
-    bool setElement(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver,
-                    uint32_t index, const Value &v, unsigned resolveFlags, bool *succeeded);
-
-    JSObject **viewList() { return &buffer.views; }
-
-  private:
-    inline bool isArrayBufferElements() const MOZ_DELETE;
-    inline ArrayBufferElementsHeader & asArrayBufferElements() MOZ_DELETE;
-
-    ArrayBufferElementsHeader(const ArrayBufferElementsHeader &other) MOZ_DELETE;
-    void operator=(const ArrayBufferElementsHeader &other) MOZ_DELETE;
-};
-
-inline DenseElementsHeader &
-ElementsHeader::asDenseElements()
-{
-    MOZ_ASSERT(isDenseElements());
-    return *static_cast<DenseElementsHeader *>(this);
-}
-
-inline SparseElementsHeader &
-ElementsHeader::asSparseElements()
-{
-    MOZ_ASSERT(isSparseElements());
-    return *static_cast<SparseElementsHeader *>(this);
-}
-
-inline Uint8ElementsHeader &
-ElementsHeader::asUint8Elements()
-{
-    MOZ_ASSERT(isUint8Elements());
-    return *static_cast<Uint8ElementsHeader *>(this);
-}
-
-inline Int8ElementsHeader &
-ElementsHeader::asInt8Elements()
-{
-    MOZ_ASSERT(isInt8Elements());
-    return *static_cast<Int8ElementsHeader *>(this);
-}
-
-inline Uint16ElementsHeader &
-ElementsHeader::asUint16Elements()
-{
-    MOZ_ASSERT(isUint16Elements());
-    return *static_cast<Uint16ElementsHeader *>(this);
-}
-
-inline Int16ElementsHeader &
-ElementsHeader::asInt16Elements()
-{
-    MOZ_ASSERT(isInt16Elements());
-    return *static_cast<Int16ElementsHeader *>(this);
-}
-
-inline Uint32ElementsHeader &
-ElementsHeader::asUint32Elements()
-{
-    MOZ_ASSERT(isUint32Elements());
-    return *static_cast<Uint32ElementsHeader *>(this);
-}
-
-inline Int32ElementsHeader &
-ElementsHeader::asInt32Elements()
-{
-    MOZ_ASSERT(isInt32Elements());
-    return *static_cast<Int32ElementsHeader *>(this);
-}
-
-inline Uint8ClampedElementsHeader &
-ElementsHeader::asUint8ClampedElements()
-{
-    MOZ_ASSERT(isUint8ClampedElements());
-    return *static_cast<Uint8ClampedElementsHeader *>(this);
-}
-
-inline Float32ElementsHeader &
-ElementsHeader::asFloat32Elements()
-{
-    MOZ_ASSERT(isFloat32Elements());
-    return *static_cast<Float32ElementsHeader *>(this);
-}
-
-inline Float64ElementsHeader &
-ElementsHeader::asFloat64Elements()
-{
-    MOZ_ASSERT(isFloat64Elements());
-    return *static_cast<Float64ElementsHeader *>(this);
-}
-
-inline ArrayBufferElementsHeader &
-ElementsHeader::asArrayBufferElements()
-{
-    MOZ_ASSERT(isArrayBufferElements());
-    return *static_cast<ArrayBufferElementsHeader *>(this);
-}
-
 class ArrayObject;
-class ArrayBufferObject;
 
 /*
  * ES6 20130308 draft 8.4.2.4 ArraySetLength.
  *
  * |id| must be "length", |attrs| are the attributes to be used for the newly-
  * changed length property, |value| is the value for the new length, and
  * |setterIsStrict| indicates whether invalid changes will cause a TypeError
  * to be thrown.
@@ -1043,21 +453,16 @@ class ObjectImpl : public gc::BarrieredC
         JS_ASSERT(getClass()->isNative());
         return getElementsHeader()->initializedLength;
     }
     uint32_t getDenseCapacity() {
         JS_ASSERT(getClass()->isNative());
         return getElementsHeader()->capacity;
     }
 
-    bool makeElementsSparse(JSContext *cx) {
-        JS_NEW_OBJECT_REPRESENTATION_ONLY();
-        MOZ_ASSUME_UNREACHABLE("NYI");
-    }
-
   protected:
 #ifdef DEBUG
     void checkShapeConsistency();
 #else
     void checkShapeConsistency() { }
 #endif
 
     Shape *
@@ -1163,33 +568,16 @@ class ObjectImpl : public gc::BarrieredC
      * since they normally don't have a lot of slots.
      */
     static const uint32_t SLOT_CAPACITY_MIN = 8;
 
     HeapSlot *fixedSlots() const {
         return reinterpret_cast<HeapSlot *>(uintptr_t(this) + sizeof(ObjectImpl));
     }
 
-    friend class ElementsHeader;
-    friend class DenseElementsHeader;
-    friend class SparseElementsHeader;
-
-    enum DenseElementsResult {
-        Failure,
-        ConvertToSparse,
-        Succeeded
-    };
-
-    DenseElementsResult ensureDenseElementsInitialized(JSContext *cx, uint32_t index,
-                                                       uint32_t extra)
-    {
-        JS_NEW_OBJECT_REPRESENTATION_ONLY();
-        MOZ_ASSUME_UNREACHABLE("NYI");
-    }
-
     /*
      * These functions are currently public for simplicity; in the long run
      * it may make sense to make at least some of them private.
      */
 
   public:
     Shape * lastProperty() const {
         MOZ_ASSERT(shape_);
@@ -1245,38 +633,32 @@ class ObjectImpl : public gc::BarrieredC
 
     /* Compute dynamicSlotsCount() for this object. */
     uint32_t numDynamicSlots() const {
         return dynamicSlotsCount(numFixedSlots(), slotSpan(), getClass());
     }
 
 
     Shape *nativeLookup(ExclusiveContext *cx, jsid id);
-    Shape *nativeLookup(ExclusiveContext *cx, PropertyId pid) {
-        return nativeLookup(cx, pid.asId());
-    }
     Shape *nativeLookup(ExclusiveContext *cx, PropertyName *name) {
         return nativeLookup(cx, NameToId(name));
     }
 
     bool nativeContains(ExclusiveContext *cx, jsid id) {
         return nativeLookup(cx, id) != nullptr;
     }
     bool nativeContains(ExclusiveContext *cx, PropertyName* name) {
         return nativeLookup(cx, name) != nullptr;
     }
     bool nativeContains(ExclusiveContext *cx, Shape* shape) {
         return nativeLookup(cx, shape->propid()) == shape;
     }
 
     /* Contextless; can be called from parallel code. */
     Shape *nativeLookupPure(jsid id);
-    Shape *nativeLookupPure(PropertyId pid) {
-        return nativeLookupPure(pid.asId());
-    }
     Shape *nativeLookupPure(PropertyName *name) {
         return nativeLookupPure(NameToId(name));
     }
 
     bool nativeContainsPure(jsid id) {
         return nativeLookupPure(id) != nullptr;
     }
     bool nativeContainsPure(PropertyName* name) {
@@ -1441,21 +823,16 @@ class ObjectImpl : public gc::BarrieredC
     }
 
     /* Elements accessors. */
 
     ObjectElements * getElementsHeader() const {
         return ObjectElements::fromElements(elements);
     }
 
-    ElementsHeader & elementsHeader() const {
-        JS_NEW_OBJECT_REPRESENTATION_ONLY();
-        return *ElementsHeader::fromElements(elements);
-    }
-
     inline HeapSlot *fixedElements() const {
         static_assert(2 * sizeof(Value) == sizeof(ObjectElements),
                       "when elements are stored inline, the first two "
                       "slots will hold the ObjectElements header");
         return &fixedSlots()[2];
     }
 
 #ifdef DEBUG
@@ -1660,73 +1037,11 @@ IsObjectValueInCompartment(js::Value v, 
         return true;
     return reinterpret_cast<ObjectImpl*>(&v.toObject())->compartment() == comp;
 }
 #endif
 
 extern JSObject *
 ArrayBufferDelegate(JSContext *cx, Handle<ObjectImpl*> obj);
 
-/* Generic [[GetOwnProperty]] method. */
-bool
-GetOwnElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index, unsigned resolveFlags,
-              PropDesc *desc);
-extern bool
-GetOwnProperty(JSContext *cx, Handle<ObjectImpl*> obj, PropertyId pid, unsigned resolveFlags,
-               PropDesc *desc);
-inline bool
-GetOwnProperty(JSContext *cx, Handle<ObjectImpl*> obj, Handle<PropertyName*> name,
-               unsigned resolveFlags, PropDesc *desc)
-{
-    return GetOwnProperty(cx, obj, PropertyId(name), resolveFlags, desc);
-}
-inline bool
-GetOwnProperty(JSContext *cx, Handle<ObjectImpl*> obj, Handle<SpecialId> sid, unsigned resolveFlags,
-               PropDesc *desc)
-{
-    return GetOwnProperty(cx, obj, PropertyId(sid), resolveFlags, desc);
-}
-
-/* Proposed default [[GetP]](Receiver, P) method. */
-extern bool
-GetElement(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver, uint32_t index,
-           unsigned resolveFlags, Value *vp);
-extern bool
-GetProperty(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver,
-            Handle<PropertyId> pid, unsigned resolveFlags, MutableHandle<Value> vp);
-inline bool
-GetProperty(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver,
-            Handle<PropertyName*> name, unsigned resolveFlags, MutableHandle<Value> vp)
-{
-    Rooted<PropertyId> pid(cx, PropertyId(name));
-    return GetProperty(cx, obj, receiver, pid, resolveFlags, vp);
-}
-inline bool
-GetProperty(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver,
-            Handle<SpecialId> sid, unsigned resolveFlags, MutableHandle<Value> vp)
-{
-    Rooted<PropertyId> pid(cx, PropertyId(sid));
-    return GetProperty(cx, obj, receiver, pid, resolveFlags, vp);
-}
-
-extern bool
-DefineElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index, const PropDesc &desc,
-              bool shouldThrow, unsigned resolveFlags, bool *succeeded);
-
-/* Proposed default [[SetP]](Receiver, P, V) method. */
-extern bool
-SetElement(JSContext *cx, Handle<ObjectImpl*> obj, Handle<ObjectImpl*> receiver, uint32_t index,
-           const Value &v, unsigned resolveFlags, bool *succeeded);
-
-extern bool
-HasElement(JSContext *cx, Handle<ObjectImpl*> obj, uint32_t index, unsigned resolveFlags,
-           bool *found);
-
-template <> struct GCMethods<PropertyId>
-{
-    static PropertyId initial() { return PropertyId(); }
-    static ThingRootKind kind() { return THING_ROOT_PROPERTY_ID; }
-    static bool poisoned(PropertyId propid) { return IsPoisonedId(propid.asId()); }
-};
-
 } /* namespace js */
 
 #endif /* vm_ObjectImpl_h */
--- a/js/src/vm/Runtime.h
+++ b/js/src/vm/Runtime.h
@@ -1699,16 +1699,17 @@ struct JSRuntime : public JS::shadow::Ru
         TriggerCallbackAnyThreadForkJoin
     };
 
     void triggerOperationCallback(OperationCallbackTrigger trigger);
 
     void addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf, JS::RuntimeSizes *runtime);
 
   private:
+    JS::RuntimeOptions options_;
 
     JSUseHelperThreads useHelperThreads_;
 
     // Settings for how helper threads can be used.
     bool parallelIonCompilationEnabled_;
     bool parallelParsingEnabled_;
 
     // True iff this is a DOM Worker runtime.
@@ -1746,16 +1747,23 @@ struct JSRuntime : public JS::shadow::Ru
 
     void setIsWorkerRuntime() {
         isWorkerRuntime_ = true;
     }
     bool isWorkerRuntime() const {
         return isWorkerRuntime_;
     }
 
+    const JS::RuntimeOptions &options() const {
+        return options_;
+    }
+    JS::RuntimeOptions &options() {
+        return options_;
+    }
+
 #ifdef DEBUG
   public:
     js::AutoEnterPolicy *enteredPolicy;
 #endif
 
     /* See comment for JS::SetLargeAllocationFailureCallback in jsapi.h. */
     JS::LargeAllocationFailureCallback largeAllocationFailureCallback;
     /* See comment for JS::SetOutOfMemoryCallback in jsapi.h. */
--- a/js/xpconnect/src/Makefile.in
+++ b/js/xpconnect/src/Makefile.in
@@ -1,18 +1,17 @@
 #
 # 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/.
 
-EXTRA_MDDEPEND_FILES = dom_qsgen.pp dictionary_helper_gen.pp event_impl_gen.pp
+EXTRA_MDDEPEND_FILES = dom_qsgen.pp event_impl_gen.pp
 
 INSTALL_TARGETS += extra_export_files
 extra_export_files_FILES := \
-  DictionaryHelpers.h \
   GeneratedEventClasses.h \
   GeneratedEvents.h \
   $(NULL)
 extra_export_files_DEST = $(DIST)/include
 extra_export_files_TARGET := export
 
 include $(topsrcdir)/config/rules.mk
 
@@ -28,58 +27,35 @@ dom_quickstubs.cpp: $(srcdir)/dom_quicks
 	  $(srcdir)/qsgen.py \
 	  --idlpath=$(DEPTH)/dist/idl \
 	  --header-output dom_quickstubs.h \
 	  --stub-output dom_quickstubs.cpp \
 	  --makedepend-output $(MDDEPDIR)/dom_qsgen.pp \
 	  $(ENABLE_TRACEABLE_FLAGS) \
 	  $(srcdir)/dom_quickstubs.qsconf
 
-DictionaryHelpers.h: DictionaryHelpers.cpp
-
-DictionaryHelpers.cpp: $(srcdir)/dictionary_helper_gen.conf \
-                       event_impl_gen.conf \
-                       $(srcdir)/dictionary_helper_gen.py \
-                       $(LIBXUL_DIST)/sdk/bin/header.py \
-                       $(LIBXUL_DIST)/sdk/bin/xpidl.py
-	$(PYTHON) $(topsrcdir)/config/pythonpath.py \
-	  $(PLY_INCLUDE) \
-	  -I$(LIBXUL_DIST)/sdk/bin \
-	  $(srcdir)/dictionary_helper_gen.py \
-	  -I $(DEPTH)/dist/idl \
-	  --header-output DictionaryHelpers.h \
-	  --stub-output DictionaryHelpers.cpp \
-	  --makedepend-output $(MDDEPDIR)/dictionary_helper_gen.pp \
-	  $(srcdir)/dictionary_helper_gen.conf \
-	  event_impl_gen.conf
-
 event_impl_gen.conf : $(srcdir)/event_impl_gen.conf.in
 	$(call py_action,preprocessor,$(DEFINES) $(ACDEFINES) $^ -o event_impl_gen.conf)
 
-GeneratedEvents.h: $(srcdir)/dictionary_helper_gen.conf \
-                   event_impl_gen.conf \
-                   $(srcdir)/dictionary_helper_gen.py \
+GeneratedEvents.h: event_impl_gen.conf \
                    $(srcdir)/event_impl_gen.py \
                    $(LIBXUL_DIST)/sdk/bin/header.py \
                    $(LIBXUL_DIST)/sdk/bin/xpidl.py
 	$(PYTHON) $(topsrcdir)/config/pythonpath.py \
 	  $(PLY_INCLUDE) \
 	  -I$(LIBXUL_DIST)/sdk/bin \
 	  $(srcdir)/event_impl_gen.py \
 	  -I $(DEPTH)/dist/idl \
 	  --header-output GeneratedEvents.h \
 	  event_impl_gen.conf
 
 GeneratedEventClasses.h: GeneratedEvents.cpp
 
-GeneratedEvents.cpp: DictionaryHelpers.h \
-                     GeneratedEvents.h \
-                     $(srcdir)/dictionary_helper_gen.conf \
+GeneratedEvents.cpp: GeneratedEvents.h \
                      event_impl_gen.conf \
-                     $(srcdir)/dictionary_helper_gen.py \
                      $(srcdir)/event_impl_gen.py \
                      $(LIBXUL_DIST)/sdk/bin/header.py \
                      $(LIBXUL_DIST)/sdk/bin/xpidl.py
 	$(PYTHON) $(topsrcdir)/config/pythonpath.py \
 	  $(PLY_INCLUDE) \
 	  -I$(LIBXUL_DIST)/sdk/bin \
 	  $(srcdir)/event_impl_gen.py \
 	  -I $(DEPTH)/dist/idl \
@@ -97,12 +73,11 @@ GeneratedEvents-webidl: event_impl_gen.c
 	  --webidltarget=$(top_srcdir)/dom/webidl \
 	  event_impl_gen.conf
 
 GARBAGE += \
 		event_impl_gen.conf \
 		xpidl_debug \
 		$(MDDEPDIR)/dom_qsgen.pp \
 		$(MDDEPDIR)/dombindingsgen.pp \
-		$(MDDEPDIR)/dictionary_helper_gen.pp \
 		$(MDDEPDIR)/event_impl_gen.pp \
 		$(wildcard $(topsrcdir)/other-licenses/ply/ply/*.pyc) \
 		$(NULL)
--- a/js/xpconnect/src/XPCComponents.cpp
+++ b/js/xpconnect/src/XPCComponents.cpp
@@ -3241,36 +3241,51 @@ nsXPCComponents_Utils::Dispatch(HandleVa
                                                    getter_AddRefs(run));
     NS_ENSURE_SUCCESS(rv, rv);
     MOZ_ASSERT(run);
 
     // Dispatch.
     return NS_DispatchToMainThread(run);
 }
 
-#define GENERATE_JSOPTION_GETTER_SETTER(_attr, _getter, _setter)    \
-    NS_IMETHODIMP                                                   \
-    nsXPCComponents_Utils::Get## _attr(JSContext* cx, bool* aValue) \
-    {                                                               \
-        *aValue = ContextOptionsRef(cx)._getter();                  \
-        return NS_OK;                                               \
-    }                                                               \
-    NS_IMETHODIMP                                                   \
-    nsXPCComponents_Utils::Set## _attr(JSContext* cx, bool aValue)  \
-    {                                                               \
-        ContextOptionsRef(cx)._setter(aValue);                      \
-        return NS_OK;                                               \
+#define GENERATE_JSCONTEXTOPTION_GETTER_SETTER(_attr, _getter, _setter) \
+    NS_IMETHODIMP                                                       \
+    nsXPCComponents_Utils::Get## _attr(JSContext* cx, bool* aValue)     \
+    {                                                                   \
+        *aValue = ContextOptionsRef(cx)._getter();                      \
+        return NS_OK;                                                   \
+    }                                                                   \
+    NS_IMETHODIMP                                                       \
+    nsXPCComponents_Utils::Set## _attr(JSContext* cx, bool aValue)      \
+    {                                                                   \
+        ContextOptionsRef(cx)._setter(aValue);                          \
+        return NS_OK;                                                   \
     }
 
-GENERATE_JSOPTION_GETTER_SETTER(Strict, extraWarnings, setExtraWarnings)
-GENERATE_JSOPTION_GETTER_SETTER(Werror, werror, setWerror)
-GENERATE_JSOPTION_GETTER_SETTER(Strict_mode, strictMode, setStrictMode)
-GENERATE_JSOPTION_GETTER_SETTER(Ion, ion, setIon)
-
-#undef GENERATE_JSOPTION_GETTER_SETTER
+#define GENERATE_JSRUNTIMEOPTION_GETTER_SETTER(_attr, _getter, _setter) \
+    NS_IMETHODIMP                                                       \
+    nsXPCComponents_Utils::Get## _attr(JSContext* cx, bool* aValue)     \
+    {                                                                   \
+        *aValue = RuntimeOptionsRef(cx)._getter();                      \
+        return NS_OK;                                                   \
+    }                                                                   \
+    NS_IMETHODIMP                                                       \
+    nsXPCComponents_Utils::Set## _attr(JSContext* cx, bool aValue)      \
+    {                                                                   \
+        RuntimeOptionsRef(cx)._setter(aValue);                          \
+        return NS_OK;                                                   \
+    }
+
+GENERATE_JSCONTEXTOPTION_GETTER_SETTER(Strict, extraWarnings, setExtraWarnings)
+GENERATE_JSCONTEXTOPTION_GETTER_SETTER(Werror, werror, setWerror)
+GENERATE_JSCONTEXTOPTION_GETTER_SETTER(Strict_mode, strictMode, setStrictMode)
+GENERATE_JSRUNTIMEOPTION_GETTER_SETTER(Ion, ion, setIon)
+
+#undef GENERATE_JSCONTEXTOPTION_GETTER_SETTER
+#undef GENERATE_JSRUNTIMEOPTION_GETTER_SETTER
 
 NS_IMETHODIMP
 nsXPCComponents_Utils::SetGCZeal(int32_t aValue, JSContext* cx)
 {
 #ifdef JS_GC_ZEAL
     JS_SetGCZeal(cx, uint8_t(aValue), JS_DEFAULT_ZEAL_FREQ);
 #endif
     return NS_OK;
--- a/js/xpconnect/src/XPCJSRuntime.cpp
+++ b/js/xpconnect/src/XPCJSRuntime.cpp
@@ -41,16 +41,17 @@
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/WindowBinding.h"
 #include "mozilla/Attributes.h"
 #include "AccessCheck.h"
 #include "nsGlobalWindow.h"
 #include "nsAboutProtocolUtils.h"
 
 #include "GeckoProfiler.h"
+#include "nsIXULRuntime.h"
 #include "nsJSPrincipals.h"
 
 #ifdef MOZ_CRASHREPORTER
 #include "nsExceptionHandler.h"
 #endif
 
 using namespace mozilla;
 using namespace xpc;
@@ -1498,16 +1499,55 @@ void XPCJSRuntime::SystemIsBeingShutDown
 {
     DOM_ClearInterfaces();
 
     if (mDetachedWrappedNativeProtoMap)
         mDetachedWrappedNativeProtoMap->
             Enumerate(DetachedWrappedNativeProtoShutdownMarker, nullptr);
 }
 
+#define JS_OPTIONS_DOT_STR "javascript.options."
+
+static void
+ReloadPrefsCallback(const char *pref, void *data)
+{
+    XPCJSRuntime *runtime = reinterpret_cast<XPCJSRuntime *>(data);
+    JSRuntime *rt = runtime->Runtime();
+
+    bool safeMode = false;
+    nsCOMPtr<nsIXULRuntime> xr = do_GetService("@mozilla.org/xre/runtime;1");
+    if (xr) {
+        xr->GetInSafeMode(&safeMode);
+    }
+
+    bool useBaseline = Preferences::GetBool(JS_OPTIONS_DOT_STR "baselinejit") && !safeMode;
+    bool useTypeInference = Preferences::GetBool(JS_OPTIONS_DOT_STR "typeinference") && !safeMode;
+    bool useIon = Preferences::GetBool(JS_OPTIONS_DOT_STR "ion") && !safeMode;
+    bool useAsmJS = Preferences::GetBool(JS_OPTIONS_DOT_STR "asmjs") && !safeMode;
+
+    bool parallelParsing = Preferences::GetBool(JS_OPTIONS_DOT_STR "parallel_parsing");
+    bool parallelIonCompilation = Preferences::GetBool(JS_OPTIONS_DOT_STR
+                                                       "ion.parallel_compilation");
+    bool useBaselineEager = Preferences::GetBool(JS_OPTIONS_DOT_STR
+                                                 "baselinejit.unsafe_eager_compilation");
+    bool useIonEager = Preferences::GetBool(JS_OPTIONS_DOT_STR "ion.unsafe_eager_compilation");
+
+    JS::RuntimeOptionsRef(rt).setBaseline(useBaseline)
+                             .setTypeInference(useTypeInference)
+                             .setIon(useIon)
+                           .  setAsmJS(useAsmJS);
+
+    JS_SetParallelParsingEnabled(rt, parallelParsing);
+    JS_SetParallelIonCompilationEnabled(rt, parallelIonCompilation);
+    JS_SetGlobalJitCompilerOption(rt, JSJITCOMPILER_BASELINE_USECOUNT_TRIGGER,
+                                  useBaselineEager ? 0 : -1);
+    JS_SetGlobalJitCompilerOption(rt, JSJITCOMPILER_ION_USECOUNT_TRIGGER,
+                                  useIonEager ? 0 : -1);
+}
+
 XPCJSRuntime::~XPCJSRuntime()
 {
     // This destructor runs before ~CycleCollectedJSRuntime, which does the
     // actual JS_DestroyRuntime() call. But destroying the runtime triggers
     // one final GC, which can call back into the runtime with various
     // callback if we aren't careful. Null out the relevant callbacks.
     js::SetActivityCallback(Runtime(), nullptr, nullptr);
     JS_SetFinalizeCallback(Runtime(), nullptr);
@@ -1583,16 +1623,18 @@ XPCJSRuntime::~XPCJSRuntime()
         stack->sampleRuntime(nullptr);
 #endif
 
 #ifdef DEBUG
     for (uint32_t i = 0; i < XPCCCX_STRING_CACHE_SIZE; ++i) {
         MOZ_ASSERT(mScratchStrings[i].empty(), "Short lived string still in use");
     }
 #endif
+
+    Preferences::UnregisterCallback(ReloadPrefsCallback, JS_OPTIONS_DOT_STR, this);
 }
 
 static void
 GetCompartmentName(JSCompartment *c, nsCString &name, bool replaceSlashes)
 {
     if (js::IsAtomsCompartment(c)) {
         name.AssignLiteral("atoms");
     } else if (JSPrincipals *principals = JS_GetCompartmentPrincipals(c)) {
@@ -3119,16 +3161,20 @@ XPCJSRuntime::XPCJSRuntime(nsXPConnect* 
     RegisterJSMainRuntimeCompartmentsUserDistinguishedAmount(JSMainRuntimeCompartmentsUserDistinguishedAmount);
     mozilla::RegisterJSSizeOfTab(JSSizeOfTab);
 
     // Install a JavaScript 'debugger' keyword handler in debug builds only
 #ifdef DEBUG
     if (!JS_GetGlobalDebugHooks(runtime)->debuggerHandler)
         xpc_InstallJSDebuggerKeywordHandler(runtime);
 #endif
+
+    // Watch for the JS boolean options.
+    ReloadPrefsCallback(nullptr, this);
+    Preferences::RegisterCallback(ReloadPrefsCallback, JS_OPTIONS_DOT_STR, this);
 }
 
 // static
 XPCJSRuntime*
 XPCJSRuntime::newXPCJSRuntime(nsXPConnect* aXPConnect)
 {
     NS_PRECONDITION(aXPConnect,"bad param");
 
@@ -3149,19 +3195,16 @@ XPCJSRuntime::newXPCJSRuntime(nsXPConnec
     }
 
     NS_RUNTIMEABORT("new XPCJSRuntime failed to initialize.");
 
     delete self;
     return nullptr;
 }
 
-// InternStaticDictionaryJSVals is automatically generated.
-bool InternStaticDictionaryJSVals(JSContext* aCx);
-
 bool
 XPCJSRuntime::OnJSContextNew(JSContext *cx)
 {
     // If we were the first cx ever created (like the SafeJSContext), the caller
     // would have had no way to enter a request. Enter one now before doing the
     // rest of the cx setup.
     JSAutoRequest ar(cx);
 
@@ -3173,18 +3216,17 @@ XPCJSRuntime::OnJSContextNew(JSContext *
             if (!str) {
                 mStrIDs[0] = JSID_VOID;
                 return false;
             }
             mStrIDs[i] = INTERNED_STRING_TO_JSID(cx, str);
             mStrJSVals[i] = STRING_TO_JSVAL(str);
         }
 
-        if (!mozilla::dom::DefineStaticJSVals(cx) ||
-            !InternStaticDictionaryJSVals(cx)) {
+        if (!mozilla::dom::DefineStaticJSVals(cx)) {
             return false;
         }
     }
 
     XPCContext* xpc = new XPCContext(this, cx);
     if (!xpc)
         return false;
 
--- a/js/xpconnect/src/XPCShellImpl.cpp
+++ b/js/xpconnect/src/XPCShellImpl.cpp
@@ -1031,21 +1031,21 @@ ProcessArgsForCompartment(JSContext *cx,
                 return;
             break;
         case 'S':
             ContextOptionsRef(cx).toggleWerror();
         case 's':
             ContextOptionsRef(cx).toggleExtraWarnings();
             break;
         case 'I':
-            ContextOptionsRef(cx).toggleIon()
+            RuntimeOptionsRef(cx).toggleIon()
                                  .toggleAsmJS();
             break;
         case 'n':
-            ContextOptionsRef(cx).toggleTypeInference();
+            RuntimeOptionsRef(cx).toggleTypeInference();
             break;
         }
     }
 }
 
 static int
 ProcessArgs(JSContext *cx, JS::Handle<JSObject*> obj, char **argv, int argc, XPCShellDirProvider* aDirProvider)
 {
@@ -1478,19 +1478,16 @@ XRE_XPCShellMain(int argc, char **argv, 
         JS_SetOperationCallback(rt, XPCShellOperationCallback);
 
         cx = JS_NewContext(rt, 8192);
         if (!cx) {
             printf("JS_NewContext failed!\n");
             return 1;
         }
 
-        // Ion not enabled yet here because of bug 931861.
-        JS::ContextOptionsRef(cx).setBaseline(true);
-
         argc--;
         argv++;
         ProcessArgsForCompartment(cx, argv, argc);
 
         nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID());
         if (!xpc) {
             printf("failed to get nsXPConnect service!\n");
             return 1;
deleted file mode 100644
--- a/js/xpconnect/src/dictionary_helper_gen.conf
+++ /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/.
-
-# Dictionary interface name, interface file name
-dictionaries = [
-     [ 'SmsThreadListItem', 'nsIMobileMessageCallback.idl' ],
-     [ 'MmsAttachment', 'nsIDOMMozMmsMessage.idl' ]
-   ]
-
-# include file names
-special_includes = [
-    'XPCQuickStubs.h',
-    'nsIDOMFile.h'
-  ]
-
-# name of the type to not include using #include "typename.h"
-exclude_automatic_type_include = [
-    'nsISupports',
-    'mozIDOMApplication',
-    'nsIDOMBlob'
-  ]
deleted file mode 100644
--- a/js/xpconnect/src/dictionary_helper_gen.py
+++ /dev/null
@@ -1,436 +0,0 @@
-#!/usr/bin/env python
-# header.py - Generate C++ header files from IDL.
-#
-# 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/.
-
-import sys, os, xpidl, makeutils
-
-def strip_begin(text, suffix):
-    if not text.startswith(suffix):
-        return text
-    return text[len(suffix):]
-
-def strip_end(text, suffix):
-    if not text.endswith(suffix):
-        return text
-    return text[:-len(suffix)]
-
-def findIDL(includePath, interfaceFileName):
-    for d in includePath:
-        # Not os.path.join: we need a forward slash even on Windows because
-        # this filename ends up in makedepend output.
-        path = d + '/' + interfaceFileName
-        if os.path.exists(path):
-            return path
-    raise BaseException("No IDL file found for interface %s "
-                        "in include path %r"
-                        % (interfaceFileName, includePath))
-
-def loadIDL(parser, includePath, filename):
-    idlFile = findIDL(includePath, filename)
-    if not idlFile in makeutils.dependencies:
-        makeutils.dependencies.append(idlFile)
-    idl = p.parse(open(idlFile).read(), idlFile)
-    idl.resolve(includePath, p)
-    return idl
-
-class Configuration:
-    def __init__(self, filename):
-        config = {}
-        execfile(filename, config)
-        self.dictionaries = config.get('dictionaries', [])
-        self.special_includes = config.get('special_includes', [])
-        self.exclude_automatic_type_include = config.get('exclude_automatic_type_include', [])
-
-def readConfigFile(filename):
-    return Configuration(filename)
-
-def firstCap(str):
-    return str[0].upper() + str[1:]
-
-def attributeVariableTypeAndName(a):
-    if a.realtype.nativeType('in').endswith('*'):
-        l = ["nsCOMPtr<%s> %s" % (a.realtype.nativeType('in').strip('* '),
-                   a.name)]
-    elif a.realtype.nativeType('in').count("nsAString"):
-        l = ["nsString %s" % a.name]
-    elif a.realtype.nativeType('in').count("JS::Value"):
-        l = ["JS::Value %s" % a.name]
-    elif a.realtype.nativeType('in').count("DOMTimeStamp"):
-        l = ["uint64_t /* DOMTimeStamp */ %s" % a.name]
-    else:
-        l = ["%s%s" % (a.realtype.nativeType('in'),
-                       a.name)]
-
-    return ", ".join(l)
-
-def print_header(idl, fd, conf, dictname, dicts):
-    for p in idl.productions:
-        if p.kind == 'dictionary':
-            interfaces = []
-            base = p.base
-            baseiface = p
-            while base is not None and not base in dicts:
-                baseiface = baseiface.idl.getName(baseiface.base, baseiface.location)
-                dicts.append(base)
-                interfaces.append(baseiface)
-                base = baseiface.base
-
-            interfaces.reverse()
-            for iface in interfaces:
-                write_header(iface, fd)
-
-            if not p.name in dicts:
-                dicts.append(p.name)
-                write_header(p, fd)
-
-def print_header_file(fd, conf):
-    fd.write("/* THIS FILE IS AUTOGENERATED - DO NOT EDIT */\n\n"
-             "#ifndef _gen_mozilla_idl_dictionary_helpers_h_\n"
-             "#define _gen_mozilla_idl_dictionary_helpers_h_\n\n")
-
-    fd.write("#include \"js/TypeDecls.h\"\n"
-             "#include \"js/Value.h\"\n"
-             "#include \"nsError.h\"\n"
-             "#include \"nsStringGlue.h\"\n"
-             "#include \"nsCOMPtr.h\"\n\n")
-
-    forwards = []
-    attrnames = []
-    for d in conf.dictionaries:
-        idl = loadIDL(p, options.incdirs, d[1])
-        collect_names_and_non_primitive_attribute_types(idl, d[0], attrnames, forwards)
-    
-    for c in forwards:
-        fd.write("class %s;\n" % c)
-
-
-    fd.write("\n"
-             "namespace mozilla {\n"
-             "namespace idl {\n\n")
-
-    dicts = []
-    for d in conf.dictionaries:
-        if not d[0] in set(dicts):
-            idl = loadIDL(p, options.incdirs, d[1])
-            print_header(idl, fd, conf, d[0], dicts)
-    fd.write("}\n"
-             "}\n"
-             "#endif\n")
-
-def collect_names_and_non_primitive_attribute_types(idl, dictname, attrnames, forwards):
-    for p in idl.productions:
-        if p.kind == 'dictionary':
-            interfaces = []
-            base = p.base
-            baseiface = p
-            while base is not None:
-                baseiface = baseiface.idl.getName(baseiface.base, baseiface.location)    
-                interfaces.append(baseiface)
-                base = baseiface.base
-
-            interfaces.reverse()
-            interfaces.append(p)
-
-            for iface in interfaces:
-                collect_names_and_non_primitive_attribute_types_from_interface(iface, attrnames, forwards)
-
-def collect_names_and_non_primitive_attribute_types_from_interface(iface, attrnames, forwards):
-    for member in iface.members:
-        if isinstance(member, xpidl.Attribute):
-            if not member.name in attrnames:
-                attrnames.append(member.name)
-            if member.realtype.nativeType('in').endswith('*'):
-                t = member.realtype.nativeType('in').strip('* ')
-                if not t in forwards:
-                    forwards.append(t)
-
-def print_cpp(idl, fd, conf, dictname, dicts):
-    for p in idl.productions:
-        if p.kind == 'dictionary':
-            interfaces = []
-            base = p.base
-            baseiface = p
-            while base is not None and not base in dicts:
-                baseiface = baseiface.idl.getName(baseiface.base, baseiface.location)
-                dicts.append(base)
-                interfaces.append(baseiface)
-                base = baseiface.base
-
-            interfaces.reverse()
-            for iface in interfaces:
-                write_cpp(iface, fd)
-
-            if not p.name in dicts:
-                dicts.append(p.name)
-                write_cpp(p, fd)
-
-def get_jsid(name):
-    return ("gDictionary_id_%s" % name)
-
-def print_cpp_file(fd, conf):
-    fd.write("/* THIS FILE IS AUTOGENERATED - DO NOT EDIT */\n\n")
-    fd.write('#include "DictionaryHelpers.h"\n')
-    fd.write('#include "mozilla/dom/BindingUtils.h"\n')
-
-    includes = []
-    for s in conf.special_includes:
-        if not s in includes:
-            includes.append(strip_end(s, ".h"))
-    
-    for d in conf.dictionaries:
-        if not d[1] in includes:
-            includes.append(strip_end(d[1], ".idl"))
-
-    attrnames = []
-    for d in conf.dictionaries:
-        idl = loadIDL(p, options.incdirs, d[1])
-        collect_names_and_non_primitive_attribute_types(idl, d[0], attrnames, includes)
-    
-    for c in includes:
-      if not c in conf.exclude_automatic_type_include:
-            fd.write("#include \"%s.h\"\n" % c)
-
-    fd.write("\n"
-             "using namespace mozilla::idl;\n"
-             "using namespace mozilla::dom;\n\n")
-
-    for a in attrnames:
-        fd.write("static InternedStringId %s;\n" % get_jsid(a))
-
-    fd.write("\n"
-             "bool\n"
-             "InternStaticDictionaryJSVals(JSContext* aCx)\n"
-             "{\n"
-             "  return\n")
-    for a in attrnames:
-        fd.write("    %s.init(aCx, \"%s\") &&\n"
-                 % (get_jsid(a), a))
-
-    fd.write("    true;\n")
-    fd.write("}\n\n")
-
-    dicts = []
-    for d in conf.dictionaries:
-        if not d[0] in set(dicts):
-            idl = p.parse(open(findIDL(options.incdirs, d[1])).read(), d[1])
-            idl.resolve(options.incdirs, p)
-            print_cpp(idl, fd, conf, d[0], dicts)
-
-def init_value(attribute):
-    realtype = attribute.realtype.nativeType('in')
-    realtype = realtype.strip(' ')
-    if attribute.defvalue is None:
-        if realtype.endswith('*'):
-            return "nullptr"
-        if realtype == "bool":
-            return "false"
-        if realtype.count("nsAString"):
-            return ""
-        if realtype.count("nsACString"):
-            return ""
-        return "0"
-    else:
-        if realtype.count("double") and attribute.defvalue == "Infinity":
-            return "mozilla::PositiveInfinity<double>()"
-        if realtype.count("double") and attribute.defvalue == "-Infinity":
-            return "mozilla::NegativeInfinity<double>()"
-        if realtype.count("nsAString"):
-            return "NS_LITERAL_STRING(\"%s\")" % attribute.defvalue
-        if realtype.count("nsACString"):
-            return "NS_LITERAL_CSTRING(\"%s\")" % attribute.defvalue
-        raise xpidl.IDLError("Default value of %s is not supported for type %s" %
-                             (attribute.defvalue, realtype), attribute.location)
-
-def write_header(iface, fd):
-    attributes = []
-    for member in iface.members:
-        if isinstance(member, xpidl.Attribute):
-            attributes.append(member)
-
-    fd.write("class %s" % iface.name)
-    if iface.base is not None:
-        fd.write(" : public %s" % iface.base)
-    fd.write("\n{\npublic:\n")
-    fd.write("  %s();\n" % iface.name)
-    fd.write("  ~%s();\n\n" % iface.name)
-
-    fd.write("  // If aCx or aVal is null, NS_OK is returned and \n"
-             "  // dictionary will use the default values. \n"
-             "  nsresult Init(JSContext* aCx, const jsval* aVal);\n")
-
-    fd.write("\n")
-
-    for member in attributes:
-        fd.write("  %s;\n" % attributeVariableTypeAndName(member))
-
-    fd.write("};\n\n")
-
-def write_getter(a, iface, fd):
-    realtype = a.realtype.nativeType('in')
-    fd.write("    NS_ENSURE_STATE(JS_GetPropertyById(aCx, aObj, %s, &v));\n"
-             % get_jsid(a.name))
-    if realtype.count("bool"):
-        fd.write("    aDict.%s = JS::ToBoolean(v);\n" % a.name)
-    elif realtype.count("uint16_t"):
-        fd.write("    uint32_t u;\n")
-        fd.write("    NS_ENSURE_STATE(JS::ToUint32(aCx, v, &u));\n")
-        fd.write("    aDict.%s = u;\n" % a.name)
-    elif realtype.count("int16_t"):
-        fd.write("    int32_t i;\n")
-        fd.write("    NS_ENSURE_STATE(JS::ToInt32(aCx, v, &i));\n")
-        fd.write("    aDict.%s = i;\n" % a.name)
-    elif realtype.count("uint32_t"):
-        fd.write("    NS_ENSURE_STATE(JS::ToUint32(aCx, v, &aDict.%s));\n" % a.name)
-    elif realtype.count("int32_t"):
-        fd.write("    NS_ENSURE_STATE(JS::ToInt32(aCx, v, &aDict.%s));\n" % a.name)
-    elif realtype.count("uint64_t") or realtype.count("DOMTimeStamp"):
-        fd.write("    NS_ENSURE_STATE(JS::ToUint64(aCx, v, &aDict.%s));\n" % a.name)
-    elif realtype.count("int64_t"):
-        fd.write("    NS_ENSURE_STATE(JS::ToInt64(aCx, v, &aDict.%s));\n" % a.name)
-    elif realtype.count("double"):
-        fd.write("    NS_ENSURE_STATE(JS::ToNumber(aCx, v, &aDict.%s));\n" % a.name)
-    elif realtype.count("float"):
-        fd.write("    double d;\n")
-        fd.write("    NS_ENSURE_STATE(JS::ToNumber(aCx, v, &d));")
-        fd.write("    aDict.%s = (float) d;\n" % a.name)
-    elif realtype.count("nsAString"):
-        if a.nullable:
-            fd.write("    xpc_qsDOMString d(aCx, v, &v, false, xpc_qsDOMString::eNull, xpc_qsDOMString::eNull);\n")
-        else:
-            fd.write("    xpc_qsDOMString d(aCx, v, &v, false, xpc_qsDOMString::eStringify, xpc_qsDOMString::eStringify);\n")
-        fd.write("    NS_ENSURE_STATE(d.IsValid());\n")
-        fd.write("    aDict.%s = d;\n" % a.name)
-    elif realtype.count("nsIVariant"):
-        fd.write("    nsCOMPtr<nsIVariant> d(already_AddRefed<nsIVariant>(XPCVariant::newVariant(ccx, v)));\n")
-        fd.write("    NS_ENSURE_STATE(d);\n")
-        fd.write("    aDict.%s = d;\n" % a.name)
-    elif realtype.endswith('*'):
-        fd.write("    %s d;\n" % realtype)
-        fd.write("    xpc_qsSelfRef ref;\n")
-        fd.write("    nsresult rv = xpc_qsUnwrapArg<%s>(aCx, v, &d, &ref.ptr, &v);\n" % realtype.strip('* '))
-        fd.write("    NS_ENSURE_SUCCESS(rv, rv);\n")
-        fd.write("    aDict.%s = d;\n" % a.name)
-    else:
-        raise BaseException("Unsupported type %s found in dictionary %s" % (realtype, iface.name))
-
-def write_cpp(iface, fd):
-    attributes = []
-    for member in iface.members:
-        if isinstance(member, xpidl.Attribute):
-            attributes.append(member)
-
-    fd.write("%s::%s()" % (iface.name, iface.name))
-
-    if iface.base is not None or len(attributes) > 0:
-        fd.write(" :\n")
-
-    if iface.base is not None:
-        fd.write("  %s()" % iface.base)
-        if len(attributes) > 0:
-            fd.write(",\n")
-
-    for i in range(len(attributes)):
-        fd.write("  %s(%s)" % (attributes[i].name, init_value(attributes[i])))
-        if i < (len(attributes) - 1):
-            fd.write(",")
-        fd.write("\n")
-
-    fd.write("{")
-    hasnullable = False
-    for i in range(len(attributes)):
-        if attributes[i].nullable:
-            hasnullable = True
-            fd.write("\n  %s.SetIsVoid(true);" % attributes[i].name)
-    if hasnullable:
-        fd.write("\n")
-    fd.write("}\n\n")
-    fd.write("%s::~%s() {}\n\n" % (iface.name, iface.name))
-
-    fd.write("static nsresult\n%s_InitInternal(%s& aDict, JSContext* aCx, JS::HandleObject aObj)\n" %
-             (iface.name, iface.name))
-    fd.write("{\n")
-    if iface.base is not None:
-        fd.write("  nsresult rv = %s_InitInternal(aDict, aCx, aObj);\n" %
-                 iface.base)
-        fd.write("  NS_ENSURE_SUCCESS(rv, rv);\n")
-
-    fd.write("  bool found = false;\n")
-    needccx = False
-    for a in attributes:
-        if a.realtype.nativeType('in').count("nsIVariant"):
-            needccx = True
-    fd.write("  JS::RootedValue v(aCx, JSVAL_VOID);\n")
-    if needccx:
-        fd.write("  XPCCallContext ccx(NATIVE_CALLER, aCx);\n")
-        fd.write("  NS_ENSURE_STATE(ccx.IsValid());\n")
-    for a in attributes:
-        fd.write("  NS_ENSURE_STATE(JS_HasPropertyById(aCx, aObj, %s, &found));\n"
-                 % get_jsid(a.name))
-        fd.write("  if (found) {\n")
-        write_getter(a, iface, fd)
-        fd.write("  }\n")
-    fd.write("  return NS_OK;\n")
-    fd.write("}\n\n")
-    
-    fd.write("nsresult\n%s::Init(JSContext* aCx, const jsval* aVal)\n" % iface.name)
-    fd.write("{\n"
-             "  MOZ_ASSERT(NS_IsMainThread());\n"
-             "  if (!aCx || !aVal) {\n"
-             "    return NS_OK;\n"
-             "  }\n"
-             "  if (!aVal->isObject()) {\n"
-             "    return aVal->isNullOrUndefined() ? NS_OK : NS_ERROR_TYPE_ERR;\n"
-             "  }\n\n"
-             "  JS::RootedObject obj(aCx, &aVal->toObject());\n"
-             "  nsCxPusher pusher;\n"
-             "  pusher.Push(aCx);\n"
-             "  JSAutoCompartment ac(aCx, obj);\n")
-
-    fd.write("  return %s_InitInternal(*this, aCx, obj);\n}\n\n" %
-                 iface.name)
-
-
-if __name__ == '__main__':
-    from optparse import OptionParser
-    o = OptionParser(usage="usage: %prog [options] configfile")
-    o.add_option('-I', action='append', dest='incdirs', default=['.'],
-                 help="Directory to search for imported files")
-    o.add_option('-o', "--stub-output",
-                 type='string', dest='stub_output', default=None,
-                 help="Quick stub C++ source output file", metavar="FILE")
-    o.add_option('--header-output', type='string', default=None,
-                 help="Quick stub header output file", metavar="FILE")
-    o.add_option('--makedepend-output', type='string', default=None,
-                 help="gnumake dependencies output file", metavar="FILE")
-    o.add_option('--cachedir', dest='cachedir', default=None,
-                 help="Directory in which to cache lex/parse tables.")
-    (options, filenames) = o.parse_args()
-    if len(filenames) < 1:
-        o.error("At least one config filename is needed.")
-    filename = filenames[0]
-
-    if options.cachedir is not None:
-        if not os.path.isdir(options.cachedir):
-            os.mkdir(options.cachedir)
-        sys.path.append(options.cachedir)
-
-    # Instantiate the parser.
-    p = xpidl.IDLParser(outputdir=options.cachedir)
-
-    conf = readConfigFile(filename)
-
-    if options.header_output is not None:
-        outfd = open(options.header_output, 'w')
-        print_header_file(outfd, conf)
-        outfd.close()
-    if options.stub_output is not None:
-        makeutils.targets.append(options.stub_output)
-        outfd = open(options.stub_output, 'w')
-        print_cpp_file(outfd, conf)
-        outfd.close()
-        if options.makedepend_output is not None:
-            makeutils.writeMakeDependOutput(options.makedepend_output)
-
--- a/js/xpconnect/src/moz.build
+++ b/js/xpconnect/src/moz.build
@@ -48,33 +48,31 @@ UNIFIED_SOURCES += [
 ]
 
 # XPCComponents.cpp cannot be built in unified mode because it uses plarena.h.
 SOURCES += [
     'XPCComponents.cpp',
 ]
 
 GENERATED_SOURCES += [
-    'DictionaryHelpers.cpp',
     'dom_quickstubs.cpp',
     'GeneratedEvents.cpp',
 ]
 
 FAIL_ON_WARNINGS = True
 
 MSVC_ENABLE_PGO = True
 
 LIBRARY_NAME = 'xpconnect_s'
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
 FINAL_LIBRARY = 'gklayout'
 
 GENERATED_FILES = [
-    'DictionaryHelpers.h',
     'dom_quickstubs.h',
     'GeneratedEventClasses.h',
     'GeneratedEvents.h',
 ]
 
 DEFINES['JS_THREADSAFE'] = True
 
 if CONFIG['MOZ_JSDEBUGGER']:
--- a/js/xpconnect/src/nsXPConnect.cpp
+++ b/js/xpconnect/src/nsXPConnect.cpp
@@ -349,75 +349,32 @@ TraceXPCGlobal(JSTracer *trc, JSObject *
         return;
     }
 #endif
 
     if (js::GetObjectClass(obj)->flags & JSCLASS_DOM_GLOBAL)
         mozilla::dom::TraceProtoAndIfaceCache(trc, obj);
 }
 
-#ifdef DEBUG
-#include "mozilla/Preferences.h"
-#include "nsIXULRuntime.h"
-static void
-CheckTypeInference(JSContext *cx, const JSClass *clasp, nsIPrincipal *principal)
-{
-    // Check that the global class isn't whitelisted.
-    if (strcmp(clasp->name, "Sandbox") ||
-        strcmp(clasp->name, "nsXBLPrototypeScript compilation scope") ||
-        strcmp(clasp->name, "nsXULPrototypeScript compilation scope"))
-        return;
-
-    // Check that the pref is on.
-    if (!mozilla::Preferences::GetBool("javascript.options.typeinference"))
-        return;
-
-    // Check that we're not chrome.
-    bool isSystem;
-    nsIScriptSecurityManager* ssm;
-    ssm = XPCWrapper::GetSecurityManager();
-    if (NS_FAILED(ssm->IsSystemPrincipal(principal, &isSystem)) || !isSystem)
-        return;
-
-    // Check that safe mode isn't on.
-    bool safeMode;
-    nsCOMPtr<nsIXULRuntime> xr = do_GetService("@mozilla.org/xre/runtime;1");
-    if (!xr) {
-        NS_WARNING("Couldn't get XUL runtime!");
-        return;
-    }
-    if (NS_FAILED(xr->GetInSafeMode(&safeMode)) || safeMode)
-        return;
-
-    // Finally, do the damn assert.
-    MOZ_ASSERT(ContextOptionsRef(cx).typeInference());
-}
-#else
-#define CheckTypeInference(cx, clasp, principal) {}
-#endif
-
 namespace xpc {
 
 JSObject*
 CreateGlobalObject(JSContext *cx, const JSClass *clasp, nsIPrincipal *principal,
                    JS::CompartmentOptions& aOptions)
 {
-    // Make sure that Type Inference is enabled for everything non-chrome.
-    // Sandboxes and compilation scopes are exceptions. See bug 744034.
-    CheckTypeInference(cx, clasp, principal);
-
     MOZ_ASSERT(NS_IsMainThread(), "using a principal off the main thread?");
     MOZ_ASSERT(principal);
 
     RootedObject global(cx,
                         JS_NewGlobalObject(cx, clasp, nsJSPrincipals::get(principal),
                                            JS::DontFireOnNewGlobalHook, aOptions));
     if (!global)
         return nullptr;
     JSAutoCompartment ac(cx, global);
+
     // The constructor automatically attaches the scope to the compartment private
     // of |global|.
     (void) new XPCWrappedNativeScope(cx, global);
 
 #ifdef DEBUG
     // Verify that the right trace hook is called. Note that this doesn't
     // work right for wrapped globals, since the tracing situation there is
     // more complicated. Manual inspection shows that they do the right thing.
--- a/layout/base/nsDisplayList.cpp
+++ b/layout/base/nsDisplayList.cpp
@@ -674,26 +674,28 @@ static void RecordFrameMetrics(nsIFrame*
   }
 
   nsIScrollableFrame* scrollableFrame = nullptr;
   if (aScrollFrame)
     scrollableFrame = aScrollFrame->GetScrollTargetFrame();
 
   if (scrollableFrame) {
     nsRect contentBounds = scrollableFrame->GetScrollRange();
+    nsPoint scrollPosition = scrollableFrame->GetScrollPosition();
     if (scrollableFrame->GetScrollbarStyles().mVertical == NS_STYLE_OVERFLOW_HIDDEN) {
-      metrics.SetDisableScrollingY(true);
+      contentBounds.y = scrollPosition.y;
+      contentBounds.height = 0;
     }
     if (scrollableFrame->GetScrollbarStyles().mHorizontal == NS_STYLE_OVERFLOW_HIDDEN) {
-      metrics.SetDisableScrollingX(true);
+      contentBounds.x = scrollPosition.x;
+      contentBounds.width = 0;
     }
     contentBounds.width += scrollableFrame->GetScrollPortRect().width;
     contentBounds.height += scrollableFrame->GetScrollPortRect().height;
     metrics.mScrollableRect = CSSRect::FromAppUnits(contentBounds);
-    nsPoint scrollPosition = scrollableFrame->GetScrollPosition();
     metrics.mScrollOffset = CSSPoint::FromAppUnits(scrollPosition);
 
     // If the frame was scrolled since the last layers update, and by
     // something other than the APZ code, we want to tell the APZ to update
     // its scroll offset.
     nsIAtom* originOfLastScroll = scrollableFrame->OriginOfLastScroll();
     if (originOfLastScroll && originOfLastScroll != nsGkAtoms::apz) {
       metrics.SetScrollOffsetUpdated(scrollableFrame->CurrentScrollGeneration());
--- a/layout/base/nsPresContext.cpp
+++ b/layout/base/nsPresContext.cpp
@@ -63,16 +63,18 @@
 // Needed for Start/Stop of Image Animation
 #include "imgIContainer.h"
 #include "nsIImageLoadingContent.h"
 
 #include "nsCSSParser.h"
 #include "nsBidiUtils.h"
 #include "nsServiceManagerUtils.h"
 
+#include "URL.h"
+
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::layers;
 
 // BEGIN temporary diagnostic stuff for bug 946929
 struct PCLink;
 static PCLink* sTopPCLink;
 struct PCLink {
@@ -691,26 +693,38 @@ nsPresContext::GetDocumentColorPreferenc
 {
   // Make sure the preferences are initialized.  In the normal run,
   // they would already be, because gfxPlatform would have been created,
   // but in some reference tests, that is not the case.
   gfxPrefs::GetSingleton();
 
   int32_t useAccessibilityTheme = 0;
   bool usePrefColors = true;
-  nsCOMPtr<nsIDocShellTreeItem> docShell(mContainer);
-  if (docShell) {
-    if (nsIDocShellTreeItem::typeChrome == docShell->ItemType()) {
-      usePrefColors = false;
-    } else {
-      useAccessibilityTheme =
-        LookAndFeel::GetInt(LookAndFeel::eIntID_UseAccessibilityTheme, 0);
-      usePrefColors = !useAccessibilityTheme;
+  bool isChromeDocShell = false;
+
+  nsIDocument* doc = mDocument->GetDisplayDocument();
+  if (doc && doc->GetDocShell()) {
+    isChromeDocShell = nsIDocShellTreeItem::typeChrome ==
+                       doc->GetDocShell()->ItemType();
+  } else {
+    nsCOMPtr<nsIDocShellTreeItem> docShell(mContainer);
+    if (docShell) {
+      isChromeDocShell = nsIDocShellTreeItem::typeChrome == docShell->ItemType();
     }
-
+  }
+
+  mIsChromeOriginImage = mDocument->IsBeingUsedAsImage() &&
+                         IsChromeURI(mDocument->GetDocumentURI());
+
+  if (isChromeDocShell || mIsChromeOriginImage) {
+    usePrefColors = false;
+  } else {
+    useAccessibilityTheme =
+      LookAndFeel::GetInt(LookAndFeel::eIntID_UseAccessibilityTheme, 0);
+    usePrefColors = !useAccessibilityTheme;
   }
   if (usePrefColors) {
     usePrefColors =
       !Preferences::GetBool("browser.display.use_system_colors", false);
   }
 
   if (usePrefColors) {
     nsAdoptingString colorStr =
--- a/layout/base/nsPresContext.h
+++ b/layout/base/nsPresContext.h
@@ -823,24 +823,25 @@ public:
 
   bool IsDynamic() { return (mType == eContext_PageLayout || mType == eContext_Galley); }
   bool IsScreen() { return (mMedium == nsGkAtoms::screen ||
                               mType == eContext_PageLayout ||
                               mType == eContext_PrintPreview); }
 
   // Is this presentation in a chrome docshell?
   bool IsChrome() const { return mIsChrome; }
+  bool IsChromeOriginImage() const { return mIsChromeOriginImage; }
   void UpdateIsChrome();
 
   // Public API for native theme code to get style internals.
   virtual bool HasAuthorSpecifiedRules(nsIFrame *aFrame, uint32_t ruleTypeMask) const;
 
   // Is it OK to let the page specify colors and backgrounds?
   bool UseDocumentColors() const {
-    return GetCachedBoolPref(kPresContext_UseDocumentColors) || IsChrome();
+    return GetCachedBoolPref(kPresContext_UseDocumentColors) || IsChrome() || IsChromeOriginImage();
   }
 
   // Explicitly enable and disable paint flashing.
   void SetPaintFlashing(bool aPaintFlashing) {
     mPaintFlashing = aPaintFlashing;
     mPaintFlashingInitialized = true;
   }
 
@@ -1313,16 +1314,17 @@ protected:
   unsigned              mIsVisual : 1;
 
   unsigned              mProcessingRestyles : 1;
   unsigned              mProcessingAnimationStyleChange : 1;
 
   unsigned              mFireAfterPaintEvents : 1;
 
   unsigned              mIsChrome : 1;
+  unsigned              mIsChromeOriginImage : 1;
 
   // Should we paint flash in this context? Do not use this variable directly.
   // Use GetPaintFlashing() method instead.
   mutable unsigned mPaintFlashing : 1;
   mutable unsigned mPaintFlashingInitialized : 1;
 
 #ifdef DEBUG
   bool                  mInitialized;
--- a/layout/forms/nsComboboxControlFrame.cpp
+++ b/layout/forms/nsComboboxControlFrame.cpp
@@ -824,51 +824,35 @@ nsComboboxControlFrame::Reflow(nsPresCon
   }
 
   mDisplayWidth = aReflowState.ComputedWidth() - buttonWidth;
 
   nsresult rv = nsBlockFrame::Reflow(aPresContext, aDesiredSize, aReflowState,
                                     aStatus);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  // Now set the correct width and height on our button.  The width we need to
-  // set always, the height only if we had an auto height.
+  // The button should occupy the same space as a scrollbar
   nsRect buttonRect = mButtonFrame->GetRect();
-  // If we have a non-intrinsic computed height, our kids should have sized
-  // themselves properly on their own.
-  if (aReflowState.ComputedHeight() == NS_INTRINSICSIZE) {
-    // The display frame is going to be the right height and width at this
-    // point. Use its height as the button height.
-    nsRect displayRect = mDisplayFrame->GetRect();
-    buttonRect.height = displayRect.height;
-    buttonRect.y = displayRect.y;
-  }
-#ifdef DEBUG
-  else {
-    nscoord buttonHeight = mButtonFrame->GetSize().height;
-    nscoord displayHeight = mDisplayFrame->GetSize().height;
-
-    // The button and display area should be equal heights, unless the computed
-    // height on the combobox is too small to fit their borders and padding.
-    NS_ASSERTION(buttonHeight == displayHeight ||
-                 (aReflowState.ComputedHeight() < buttonHeight &&
-                  buttonHeight ==
-                    mButtonFrame->GetUsedBorderAndPadding().TopBottom()) ||
-                 (aReflowState.ComputedHeight() < displayHeight &&
-                  displayHeight ==
-                    mDisplayFrame->GetUsedBorderAndPadding().TopBottom()),
-                 "Different heights?");
-  }
-#endif
 
   if (StyleVisibility()->mDirection == NS_STYLE_DIRECTION_RTL) {
-    // Make sure the right edge of the button frame stays where it is now
-    buttonRect.x -= buttonWidth - buttonRect.width;
+    buttonRect.x = aReflowState.ComputedPhysicalBorderPadding().left -
+                   aReflowState.ComputedPhysicalPadding().left;
+  }
+  else {
+    buttonRect.x = aReflowState.ComputedPhysicalBorderPadding().LeftRight() +
+                   mDisplayWidth -
+                   (aReflowState.ComputedPhysicalBorderPadding().right -
+                    aReflowState.ComputedPhysicalPadding().right);
   }
   buttonRect.width = buttonWidth;
+
+  buttonRect.y = this->GetUsedBorder().top;
+  buttonRect.height = mDisplayFrame->GetRect().height +
+                      this->GetUsedPadding().TopBottom();
+
   mButtonFrame->SetRect(buttonRect);
 
   if (!NS_INLINE_IS_BREAK_BEFORE(aStatus) &&
       !NS_FRAME_IS_FULLY_COMPLETE(aStatus)) {
     // This frame didn't fit inside a fragmentation container.  Splitting
     // a nsComboboxControlFrame makes no sense, so we override the status here.
     aStatus = NS_FRAME_COMPLETE;
   }
--- a/layout/generic/crashtests/crashtests.list
+++ b/layout/generic/crashtests/crashtests.list
@@ -350,17 +350,17 @@ load 494283-2.html
 load 494300-1.xul
 load 494332-1.html
 load 495875-1.html
 load 495875-2.html
 load 496742.html
 load 499138.html
 load 499862-1.html
 load 499857-1.html
-asserts-if(winWidget,3-4) load 499885-1.xhtml # bug 893509
+asserts-if(winWidget,0-3) load 499885-1.xhtml
 load 501535-1.html
 load 503961-1.xhtml
 load 503961-2.html
 load 508168-1.html
 load 508816-1.xul
 load 508908-1.html
 load 505912-1.html
 load 509749-1.html
new file mode 100644
--- /dev/null
+++ b/layout/reftests/forms/select/padding-button-placement-ref.html
@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+    </head>
+    <body>
+        <div style="box-sizing:border-box; width:402px; height:202px; border:1px solid black; border-right:50px solid black;"></div>
+        <div style="box-sizing:border-box; width:402px; height:202px; border:1px solid black; border-left:50px solid black;"></div>
+    </body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/forms/select/padding-button-placement.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+    </head>
+    <body>
+        <!-- The div's border should hide the select's button -->
+        <!-- z-index:1 works around an unrelated bug in B2G -->
+        <div style="position:absolute; z-index:1; box-sizing:border-box; width:402px; height:202px; border-right:50px solid black;"></div>
+        <div><select style="background:transparent; border-radius:0; box-sizing:content-box; padding:50px; width:300px; height:100px; border:1px solid black; direction:ltr"></select></div>
+
+        <div style="position:absolute; z-index:1; box-sizing:border-box; width:402px; height:202px; border-left:50px solid black;"></div>
+        <div><select style="background:transparent; border-radius:0; box-sizing:content-box; padding:50px; width:300px; height:100px; border:1px solid black; direction:rtl"></select></div>
+    </body>
+</html>
--- a/layout/reftests/forms/select/reftest.list
+++ b/layout/reftests/forms/select/reftest.list
@@ -1,5 +1,6 @@
 skip-if(B2G) == out-of-bounds-selectedindex.html out-of-bounds-selectedindex-ref.html # test for bug 471741
 skip-if(B2G) == multiple.html multiple-ref.html
 == boguskids.html boguskids-ref.html
 == dynamic-boguskids.html boguskids-ref.html
 == option-children.html option-children-ref.html
+fuzzy(1,4) == padding-button-placement.html padding-button-placement-ref.html
--- a/modules/libpref/src/init/all.js
+++ b/modules/libpref/src/init/all.js
@@ -751,25 +751,22 @@ pref("dom.event.clipboardevents.enabled"
 
 pref("dom.webcomponents.enabled",           false);
 
 pref("javascript.enabled",                  true);
 pref("javascript.options.strict",           false);
 #ifdef DEBUG
 pref("javascript.options.strict.debug",     true);
 #endif
-pref("javascript.options.baselinejit.content", true);
-pref("javascript.options.baselinejit.chrome",  true);
-pref("javascript.options.ion.content",      true);
-pref("javascript.options.ion.chrome",       true);
+pref("javascript.options.baselinejit",      true);
+pref("javascript.options.ion",              true);
 pref("javascript.options.asmjs",            true);
 pref("javascript.options.parallel_parsing", true);
 pref("javascript.options.ion.parallel_compilation", true);
-pref("javascript.options.typeinference.content", true);
-pref("javascript.options.typeinference.chrome", true);
+pref("javascript.options.typeinference",    true);
 // This preference limits the memory usage of javascript.
 // If you want to change these values for your device,
 // please find Bug 417052 comment 17 and Bug 456721
 // Comment 32 and Bug 613551.
 pref("javascript.options.mem.high_water_mark", 128);
 pref("javascript.options.mem.max", -1);
 pref("javascript.options.mem.gc_per_compartment", true);
 pref("javascript.options.mem.gc_incremental", true);
--- a/netwerk/base/public/nsIUDPSocket.idl
+++ b/netwerk/base/public/nsIUDPSocket.idl
@@ -7,24 +7,26 @@
 
 interface nsINetAddr;
 interface nsIUDPSocketListener;
 interface nsIUDPMessage;
 interface nsISocketTransport;
 interface nsIOutputStream;
 
 %{ C++
+#include "nsTArrayForwardDeclare.h"
 namespace mozilla {
 namespace net {
 union NetAddr;
 }
 }
 %}
 native NetAddr(mozilla::net::NetAddr);
 [ptr] native NetAddrPtr(mozilla::net::NetAddr);
+[ref] native Uint8TArrayRef(FallibleTArray<uint8_t>);
 
 /**
  * nsIUDPSocket
  *
  * An interface to a UDP socket that can accept incoming connections.
  */
 [scriptable, uuid(6EFE692D-F0B0-4A9E-9E63-837C7452446D)]
 interface nsIUDPSocket : nsISupports
@@ -203,9 +205,15 @@ interface nsIUDPMessage : nsISupports
      * Data of the message
      */
     readonly attribute ACString data;
 
     /**
      * Stream to send a response
      */
     readonly attribute nsIOutputStream outputStream;
+
+    /**
+     * Raw Data of the message
+     */
+    [implicit_jscontext] readonly attribute jsval rawData;
+    [noscript, notxpcom, nostdcall] Uint8TArrayRef getDataAsTArray();
 };
--- a/netwerk/base/src/nsUDPSocket.cpp
+++ b/netwerk/base/src/nsUDPSocket.cpp
@@ -1,15 +1,17 @@
 /* vim:set ts=2 sw=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 "mozilla/Attributes.h"
 #include "mozilla/Endian.h"
+#include "mozilla/dom/TypedArray.h"
+#include "mozilla/HoldDropJSObjects.h"
 
 #include "nsSocketTransport2.h"
 #include "nsUDPSocket.h"
 #include "nsProxyRelease.h"
 #include "nsAutoPtr.h"
 #include "nsError.h"
 #include "nsNetCID.h"
 #include "prnetdb.h"
@@ -134,60 +136,101 @@ NS_IMETHODIMP nsUDPOutputStream::IsNonBl
 {
   *_retval = true;
   return NS_OK;
 }
 
 //-----------------------------------------------------------------------------
 // nsUDPMessage impl
 //-----------------------------------------------------------------------------
-NS_IMPL_ISUPPORTS1(nsUDPMessage, nsIUDPMessage)
+NS_IMPL_CYCLE_COLLECTING_ADDREF(nsUDPMessage)
+NS_IMPL_CYCLE_COLLECTING_RELEASE(nsUDPMessage)
+
+NS_IMPL_CYCLE_COLLECTION_CLASS(nsUDPMessage)
+
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsUDPMessage)
+  NS_INTERFACE_MAP_ENTRY(nsISupports)
+  NS_INTERFACE_MAP_ENTRY(nsIUDPMessage)
+NS_INTERFACE_MAP_END
 
-nsUDPMessage::nsUDPMessage(PRNetAddr* aAddr,
-             nsIOutputStream* aOutputStream,
-             const nsACString& aData)
+NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsUDPMessage)
+  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mJsobj)
+NS_IMPL_CYCLE_COLLECTION_TRACE_END
+
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsUDPMessage)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsUDPMessage)
+  tmp->mJsobj = nullptr;
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+
+nsUDPMessage::nsUDPMessage(NetAddr* aAddr,
+                           nsIOutputStream* aOutputStream,
+                           FallibleTArray<uint8_t>& aData)
   : mOutputStream(aOutputStream)
-  , mData(aData)
 {
   memcpy(&mAddr, aAddr, sizeof(NetAddr));
+  aData.SwapElements(mData);
 }
 
 nsUDPMessage::~nsUDPMessage()
 {
+  mozilla::DropJSObjects(this);
 }
 
 /* readonly attribute nsINetAddr from; */
-NS_IMETHODIMP nsUDPMessage::GetFromAddr(nsINetAddr * *aFromAddr)
+NS_IMETHODIMP
+nsUDPMessage::GetFromAddr(nsINetAddr * *aFromAddr)
 {
   NS_ENSURE_ARG_POINTER(aFromAddr);
 
-  NetAddr clientAddr;
-  PRNetAddrToNetAddr(&mAddr, &clientAddr);
-
-  nsCOMPtr<nsINetAddr> result = new nsNetAddr(&clientAddr);
+  nsCOMPtr<nsINetAddr> result = new nsNetAddr(&mAddr);
   result.forget(aFromAddr);
 
   return NS_OK;
 }
 
 /* readonly attribute ACString data; */
-NS_IMETHODIMP nsUDPMessage::GetData(nsACString & aData)
+NS_IMETHODIMP
+nsUDPMessage::GetData(nsACString & aData)
 {
-  aData = mData;
+  aData.Assign(reinterpret_cast<const char*>(mData.Elements()), mData.Length());
   return NS_OK;
 }
 
 /* readonly attribute nsIOutputStream outputStream; */
-NS_IMETHODIMP nsUDPMessage::GetOutputStream(nsIOutputStream * *aOutputStream)
+NS_IMETHODIMP
+nsUDPMessage::GetOutputStream(nsIOutputStream * *aOutputStream)
 {
   NS_ENSURE_ARG_POINTER(aOutputStream);
   NS_IF_ADDREF(*aOutputStream = mOutputStream);
   return NS_OK;
 }
 
+/* readonly attribute jsval rawData; */
+NS_IMETHODIMP
+nsUDPMessage::GetRawData(JSContext* cx,
+                         JS::MutableHandleValue aRawData)
+{
+  if(!mJsobj){
+    mJsobj = mozilla::dom::Uint8Array::Create(cx, nullptr, mData.Length(), mData.Elements());
+    mozilla::HoldJSObjects(this);
+  }
+  aRawData.setObject(*mJsobj);
+  return NS_OK;
+}
+
+/* [noscript, notxpcom, nostdcall] Uint8ArrayRef getDataAsTArray(); */
+FallibleTArray<uint8_t>&
+nsUDPMessage::GetDataAsTArray()
+{
+  return mData;
+}
+
 //-----------------------------------------------------------------------------
 // nsUDPSocket
 //-----------------------------------------------------------------------------
 
 nsUDPSocket::nsUDPSocket()
   : mLock("nsUDPSocket.mLock")
   , mFD(nullptr)
   , mAttached(false)
@@ -298,16 +341,88 @@ nsUDPSocket::TryAttach()
 
   //
   // now, configure our poll flags for listening...
   //
   mPollFlags = (PR_POLL_READ | PR_POLL_EXCEPT);
   return NS_OK;
 }
 
+namespace {
+//-----------------------------------------------------------------------------
+// UDPMessageProxy
+//-----------------------------------------------------------------------------
+class UDPMessageProxy MOZ_FINAL : public nsIUDPMessage
+{
+public:
+  UDPMessageProxy(NetAddr* aAddr,
+                  nsIOutputStream* aOutputStream,
+                  FallibleTArray<uint8_t>& aData)
+  : mOutputStream(aOutputStream)
+  {
+    memcpy(&mAddr, aAddr, sizeof(NetAddr));
+    aData.SwapElements(mData);
+  }
+
+  NS_DECL_THREADSAFE_ISUPPORTS
+  NS_DECL_NSIUDPMESSAGE
+
+private:
+  NetAddr mAddr;
+  nsCOMPtr<nsIOutputStream> mOutputStream;
+  FallibleTArray<uint8_t> mData;
+};
+
+NS_IMPL_ISUPPORTS1(UDPMessageProxy, nsIUDPMessage)
+
+/* readonly attribute nsINetAddr from; */
+NS_IMETHODIMP
+UDPMessageProxy::GetFromAddr(nsINetAddr * *aFromAddr)
+{
+  NS_ENSURE_ARG_POINTER(aFromAddr);
+
+  nsCOMPtr<nsINetAddr> result = new nsNetAddr(&mAddr);
+  result.forget(aFromAddr);
+
+  return NS_OK;
+}
+
+/* readonly attribute ACString data; */
+NS_IMETHODIMP
+UDPMessageProxy::GetData(nsACString & aData)
+{
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript, notxpcom, nostdcall] Uint8TArrayRef getDataAsTArray(); */
+FallibleTArray<uint8_t>&
+UDPMessageProxy::GetDataAsTArray()
+{
+  return mData;
+}
+
+/* readonly attribute jsval rawData; */
+NS_IMETHODIMP
+UDPMessageProxy::GetRawData(JSContext* cx,
+                            JS::MutableHandleValue aRawData)
+{
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* readonly attribute nsIOutputStream outputStream; */
+NS_IMETHODIMP
+UDPMessageProxy::GetOutputStream(nsIOutputStream * *aOutputStream)
+{
+  NS_ENSURE_ARG_POINTER(aOutputStream);
+  NS_IF_ADDREF(*aOutputStream = mOutputStream);
+  return NS_OK;
+}
+
+} //anonymous namespace
+
 //-----------------------------------------------------------------------------
 // nsUDPSocket::nsASocketHandler
 //-----------------------------------------------------------------------------
 
 void
 nsUDPSocket::OnSocketReady(PRFileDesc *fd, int16_t outFlags)
 {
   NS_ASSERTION(NS_SUCCEEDED(mCondition), "oops");
@@ -328,19 +443,19 @@ nsUDPSocket::OnSocketReady(PRFileDesc *f
 
   if (count < 1) {
     NS_WARNING("error of recvfrom on UDP socket");
     mCondition = NS_ERROR_UNEXPECTED;
     return;
   }
   mByteReadCount += count;
 
-  nsCString data;
-  if (!data.Assign(buff, count, mozilla::fallible_t())) {
-    mCondition = NS_ERROR_OUT_OF_MEMORY;
+  FallibleTArray<uint8_t> data;
+  if(!data.AppendElements(buff, count)){
+    mCondition = NS_ERROR_UNEXPECTED;
     return;
   }
 
   nsCOMPtr<nsIAsyncInputStream> pipeIn;
   nsCOMPtr<nsIAsyncOutputStream> pipeOut;
 
   uint32_t segsize = 1400;
   uint32_t segcount = 0;
@@ -355,17 +470,19 @@ nsUDPSocket::OnSocketReady(PRFileDesc *f
   nsCOMPtr<nsUDPOutputStream> os = new nsUDPOutputStream(this, mFD, prClientAddr);
   rv = NS_AsyncCopy(pipeIn, os, mSts,
                     NS_ASYNCCOPY_VIA_READSEGMENTS, 1400);
 
   if (NS_FAILED(rv)) {
     return;
   }
 
-  nsCOMPtr<nsIUDPMessage> message = new nsUDPMessage(&prClientAddr, pipeOut, data);
+  NetAddr netAddr;
+  PRNetAddrToNetAddr(&prClientAddr, &netAddr);
+  nsCOMPtr<nsIUDPMessage> message = new UDPMessageProxy(&netAddr, pipeOut, data);
   mListener->OnPacketReceived(this, message);
 }
 
 void
 nsUDPSocket::OnSocketDetached(PRFileDesc *fd)
 {
   // force a failure condition if none set; maybe the STS is shutting down :-/
   if (NS_SUCCEEDED(mCondition))
@@ -529,17 +646,19 @@ NS_IMETHODIMP
 nsUDPSocket::GetAddress(NetAddr *aResult)
 {
   // no need to enter the lock here
   memcpy(aResult, &mAddr, sizeof(mAddr));
   return NS_OK;
 }
 
 namespace {
-
+//-----------------------------------------------------------------------------
+// SocketListenerProxy
+//-----------------------------------------------------------------------------
 class SocketListenerProxy MOZ_FINAL : public nsIUDPSocketListener
 {
 public:
   SocketListenerProxy(nsIUDPSocketListener* aListener)
     : mListener(new nsMainThreadPtrHolder<nsIUDPSocketListener>(aListener))
     , mTargetThread(do_GetCurrentThread())
   { }
 
@@ -608,17 +727,30 @@ SocketListenerProxy::OnStopListening(nsI
   nsRefPtr<OnStopListeningRunnable> r =
     new OnStopListeningRunnable(mListener, aSocket, aStatus);
   return mTargetThread->Dispatch(r, NS_DISPATCH_NORMAL);
 }
 
 NS_IMETHODIMP
 SocketListenerProxy::OnPacketReceivedRunnable::Run()
 {
-  mListener->OnPacketReceived(mSocket, mMessage);
+  NetAddr netAddr;
+  nsCOMPtr<nsINetAddr> nsAddr;
+  mMessage->GetFromAddr(getter_AddRefs(nsAddr));
+  nsAddr->GetNetAddr(&netAddr);
+
+  nsCOMPtr<nsIOutputStream> outputStream;
+  mMessage->GetOutputStream(getter_AddRefs(outputStream));
+
+  FallibleTArray<uint8_t>& data = mMessage->GetDataAsTArray();
+
+  nsCOMPtr<nsIUDPMessage> message = new nsUDPMessage(&netAddr,
+                                                     outputStream,
+                                                     data);
+  mListener->OnPacketReceived(mSocket, message);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 SocketListenerProxy::OnStopListeningRunnable::Run()
 {
   mListener->OnStopListening(mSocket, mStatus);
   return NS_OK;
--- a/netwerk/base/src/nsUDPSocket.h
+++ b/netwerk/base/src/nsUDPSocket.h
@@ -5,16 +5,17 @@
 
 #ifndef nsUDPSocket_h__
 #define nsUDPSocket_h__
 
 #include "nsIUDPSocket.h"
 #include "mozilla/Mutex.h"
 #include "nsIOutputStream.h"
 #include "nsAutoPtr.h"
+#include "nsCycleCollectionParticipant.h"
 
 //-----------------------------------------------------------------------------
 
 class nsUDPSocket : public nsASocketHandler
                   , public nsIUDPSocket
 {
 public:
   NS_DECL_THREADSAFE_ISUPPORTS
@@ -56,29 +57,31 @@ private:
   uint64_t   mByteWriteCount;
 };
 
 //-----------------------------------------------------------------------------
 
 class nsUDPMessage : public nsIUDPMessage
 {
 public:
-  NS_DECL_THREADSAFE_ISUPPORTS
+  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
+  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(nsUDPMessage)
   NS_DECL_NSIUDPMESSAGE
 
-  nsUDPMessage(PRNetAddr* aAddr,
+  nsUDPMessage(mozilla::net::NetAddr* aAddr,
                nsIOutputStream* aOutputStream,
-               const nsACString& aData);
+               FallibleTArray<uint8_t>& aData);
 
 private:
   virtual ~nsUDPMessage();
 
-  PRNetAddr mAddr;
+  mozilla::net::NetAddr mAddr;
   nsCOMPtr<nsIOutputStream> mOutputStream;
-  nsCString mData;
+  FallibleTArray<uint8_t> mData;
+  JS::Heap<JSObject*> mJsobj;
 };
 
 
 //-----------------------------------------------------------------------------
 
 class nsUDPOutputStream : public nsIOutputStream
 {
 public:
--- a/netwerk/dns/effective_tld_names.dat
+++ b/netwerk/dns/effective_tld_names.dat
@@ -396,18 +396,18 @@ edu.bo
 gov.bo
 gob.bo
 int.bo
 org.bo
 net.bo
 mil.bo
 tv.bo
 
-// br : http://registro.br/dominio/dpn.html
-// Submitted by registry <fneves@registro.br> 2011-03-01
+// br : http://registro.br/dominio/categoria.html
+// Submitted by registry <fneves@registro.br> 2014-03-04
 br
 adm.br
 adv.br
 agr.br
 am.br
 arq.br
 art.br
 ato.br
@@ -442,16 +442,17 @@ ind.br
 inf.br
 jor.br
 jus.br
 leg.br
 lel.br
 mat.br
 med.br
 mil.br
+mp.br
 mus.br
 net.br
 nom.br
 not.br
 ntr.br
 odo.br
 org.br
 ppg.br
@@ -1082,16 +1083,17 @@ tozsde.hu
 utazas.hu
 video.hu
 
 // id : https://register.pandi.or.id/
 id
 ac.id
 biz.id
 co.id
+desa.id
 go.id
 mil.id
 my.id
 net.id
 or.id
 sch.id
 web.id
 
@@ -6761,314 +6763,314 @@ shoes
 career
 
 // otsuka : 2013-10-11 Otsuka Holdings Co. Ltd.
 otsuka
 
 // xn--fiQ64b : 2013-10-14 CITIC Group Corporation
 中信
 
-// gift : 2013-10-18 Uniregistry Corp. 
+// gift : 2013-10-18 Uniregistry Corp.
 gift
 
-// recipes : 2013-10-18 Grand Island, LLC 
+// recipes : 2013-10-18 Grand Island, LLC
 recipes
 
-// coffee : 2013-10-18 Trixy Cover, LLC 
+// coffee : 2013-10-18 Trixy Cover, LLC
 coffee
 
-// luxury : 2013-10-18 Luxury Partners, LLC 
+// luxury : 2013-10-18 Luxury Partners, LLC
 luxury
 
-// domains : 2013-10-18 Sugar Cross, LLC 
+// domains : 2013-10-18 Sugar Cross, LLC
 domains
 
-// photos : 2013-10-18 Sea Corner, LLC 
+// photos : 2013-10-18 Sea Corner, LLC
 photos
 
-// limo : 2013-10-18 Hidden Frostbite, LLC 
+// limo : 2013-10-18 Hidden Frostbite, LLC
 limo
 
-// viajes : 2013-10-18 Black Madison, LLC 
+// viajes : 2013-10-18 Black Madison, LLC
 viajes
 
-// wang : 2013-10-24 Zodiac Leo Limited 
+// wang : 2013-10-24 Zodiac Leo Limited
 wang
 
-// democrat : 2013-10-24 United TLD Holdco Ltd. 
+// democrat : 2013-10-24 United TLD Holdco Ltd.
 democrat
 
-// mango : 2013-10-25 PUNTO FA S.L. 
+// mango : 2013-10-25 PUNTO FA S.L.
 mango
 
-// cab : 2013-10-25 Half Sunset, LLC 
+// cab : 2013-10-25 Half Sunset, LLC
 cab
 
-// support : 2013-10-25 Grand Orchard, LLC 
+// support : 2013-10-25 Grand Orchard, LLC
 support
 
-// dance : 2013-10-25 United TLD Holdco Ltd. 
+// dance : 2013-10-25 United TLD Holdco Ltd.
 dance
 
-// nagoya : 2013-10-25 GMO Registry, Inc. 
+// nagoya : 2013-10-25 GMO Registry, Inc.
 nagoya
 
-// computer : 2013-10-25 Pine Mill, LLC 
+// computer : 2013-10-25 Pine Mill, LLC
 computer
 
-// wien : 2013-10-28 punkt.wien GmbH 
+// wien : 2013-10-28 punkt.wien GmbH
 wien
 
-// berlin : 2013-10-31 dotBERLIN GmbH & Co. KG 
+// berlin : 2013-10-31 dotBERLIN GmbH & Co. KG
 berlin
 
-// codes : 2013-10-31 Puff Willow, LLC 
+// codes : 2013-10-31 Puff Willow, LLC
 codes
 
-// email : 2013-10-31 Spring Madison, LLC 
+// email : 2013-10-31 Spring Madison, LLC
 email
 
-// xn--mgbab2bd : 2013-10-31 CORE Association 
+// xn--mgbab2bd : 2013-10-31 CORE Association
 بازار
 
-// repair : 2013-11-07 Lone Sunset, LLC 
+// repair : 2013-11-07 Lone Sunset, LLC
 repair
 
-// holiday : 2013-11-07 Goose Woods, LLC 
+// holiday : 2013-11-07 Goose Woods, LLC
 holiday
 
-// center : 2013-11-07 Tin Mill, LLC 
+// center : 2013-11-07 Tin Mill, LLC
 center
 
-// systems : 2013-11-07 Dash Cypress, LLC 
+// systems : 2013-11-07 Dash Cypress, LLC
 systems
 
-// wiki : 2013-11-07 Top Level Design, LLC 
+// wiki : 2013-11-07 Top Level Design, LLC
 wiki
 
-// ceo : 2013-11-07 CEOTLD Pty Ltd 
+// ceo : 2013-11-07 CEOTLD Pty Ltd
 ceo
 
-// international : 2013-11-07 Wild Way, LLC 
+// international : 2013-11-07 Wild Way, LLC
 international
 
-// solar : 2013-11-07 Ruby Town, LLC 
+// solar : 2013-11-07 Ruby Town, LLC
 solar