merge mozilla-inbound to mozilla-central a=merge
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Thu, 19 Nov 2015 14:44:11 +0100
changeset 307387 a523d4c7efe2f43dd6b25a176c07b729918d550f
parent 307237 57d98a5d56ccabc7bbd0a3198cacdf769003ed2f (current diff)
parent 307386 775cc28c73b31a5607abe07701ce9cb0f40f1c92 (diff)
child 307410 e321d5a4e45bd7c85b4e5eb8f1d8ef8c4d1498bb
child 307450 484c6f441151b3404f24c855dea1157558b0b9e6
child 307474 a1159ab1dd77b09cb1b335cd93f5d146bcaa50bc
push id5513
push userraliiev@mozilla.com
push dateMon, 25 Jan 2016 13:55:34 +0000
treeherdermozilla-beta@5ee97dd05b5c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone45.0a1
first release with
nightly linux32
a523d4c7efe2 / 45.0a1 / 20151119065326 / files
nightly linux64
a523d4c7efe2 / 45.0a1 / 20151119065326 / files
nightly mac
a523d4c7efe2 / 45.0a1 / 20151119065326 / files
nightly win32
a523d4c7efe2 / 45.0a1 / 20151119065326 / files
nightly win64
a523d4c7efe2 / 45.0a1 / 20151119065326 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
merge mozilla-inbound to mozilla-central a=merge
dom/media/apple/AppleDecoder.cpp
dom/media/apple/AppleDecoder.h
dom/media/apple/AppleMP3Reader.cpp
dom/media/apple/AppleMP3Reader.h
dom/media/apple/moz.build
media/webrtc/trunk/webrtc/base/compile_assert.h
media/webrtc/trunk/webrtc/base/stringdigest.h
media/webrtc/trunk/webrtc/build/ios-webrtc.sh
media/webrtc/trunk/webrtc/build/tsan_suppressions_webrtc.cc
media/webrtc/trunk/webrtc/build/version.py
media/webrtc/trunk/webrtc/build/vie-webrtc.sh
media/webrtc/trunk/webrtc/common_audio/signal_processing/cross_correlation_neon.S
media/webrtc/trunk/webrtc/common_audio/signal_processing/downsample_fast_neon.S
media/webrtc/trunk/webrtc/common_audio/signal_processing/min_max_operations_neon.S
media/webrtc/trunk/webrtc/common_audio/signal_processing/vector_scaling_operations_neon.S
media/webrtc/trunk/webrtc/common_video/interface/texture_video_frame.h
media/webrtc/trunk/webrtc/common_video/plane_unittest.cc
media/webrtc/trunk/webrtc/common_video/texture_video_frame.cc
media/webrtc/trunk/webrtc/common_video/texture_video_frame_unittest.cc
media/webrtc/trunk/webrtc/modules/audio_coding/codecs/isac/fix/source/isacfix.gypi
media/webrtc/trunk/webrtc/modules/audio_coding/codecs/isac/main/source/isac.gypi
media/webrtc/trunk/webrtc/modules/audio_coding/codecs/tools/audio_codec_speed_tests.gypi
media/webrtc/trunk/webrtc/modules/audio_coding/codecs/tools/audio_codec_speed_tests.isolate
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_amr.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_amr.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_amrwb.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_amrwb.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_celt.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_celt.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_cng.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_cng.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_dtmf_playout.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_dtmf_playout.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_g722.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_g722.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_g7221.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_g7221.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_g7221c.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_g7221c.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_g729.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_g729.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_g7291.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_g7291.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_gsmfr.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_gsmfr.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_ilbc.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_ilbc.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_isac.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_isac.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_isac_macros.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_opus.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_opus.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_opus_unittest.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_pcm16b.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_pcm16b.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_pcma.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_pcma.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_pcmu.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_pcmu.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_red.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_red.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_speex.cc
media/webrtc/trunk/webrtc/modules/audio_coding/main/acm2/acm_speex.h
media/webrtc/trunk/webrtc/modules/audio_coding/main/test/dual_stream_unittest.cc
media/webrtc/trunk/webrtc/modules/audio_coding/neteq/audio_decoder.cc
media/webrtc/trunk/webrtc/modules/audio_coding/neteq/interface/audio_decoder.h
media/webrtc/trunk/webrtc/modules/audio_coding/neteq/test/RTPcat.cc
media/webrtc/trunk/webrtc/modules/audio_coding/neteq/test/neteq_opus_fec_quality_test.cc
media/webrtc/trunk/webrtc/modules/audio_conference_mixer/source/audio_conference_mixer.gypi
media/webrtc/trunk/webrtc/modules/audio_device/android/OWNERS
media/webrtc/trunk/webrtc/modules/audio_device/sndio/audio_device_sndio.cc
media/webrtc/trunk/webrtc/modules/audio_processing/aecm/aecm_core_neon.S
media/webrtc/trunk/webrtc/modules/audio_processing/aecm/aecm_core_neon_offsets.c
media/webrtc/trunk/webrtc/modules/audio_processing/agc/analog_agc.c
media/webrtc/trunk/webrtc/modules/audio_processing/agc/analog_agc.h
media/webrtc/trunk/webrtc/modules/audio_processing/agc/digital_agc.c
media/webrtc/trunk/webrtc/modules/audio_processing/agc/digital_agc.h
media/webrtc/trunk/webrtc/modules/audio_processing/agc/include/gain_control.h
media/webrtc/trunk/webrtc/modules/audio_processing/gen_core_neon_offsets.gyp
media/webrtc/trunk/webrtc/modules/audio_processing/gen_core_neon_offsets_chromium.gyp
media/webrtc/trunk/webrtc/modules/audio_processing/lib_core_neon_offsets.gypi
media/webrtc/trunk/webrtc/modules/audio_processing/ns/nsx_core_neon.S
media/webrtc/trunk/webrtc/modules/audio_processing/ns/nsx_core_neon_offsets.c
media/webrtc/trunk/webrtc/modules/audio_processing/utility/fft4g.c
media/webrtc/trunk/webrtc/modules/audio_processing/utility/fft4g.h
media/webrtc/trunk/webrtc/modules/audio_processing/utility/ring_buffer.c
media/webrtc/trunk/webrtc/modules/audio_processing/utility/ring_buffer.h
media/webrtc/trunk/webrtc/modules/audio_processing/utility/ring_buffer_unittest.cc
media/webrtc/trunk/webrtc/modules/desktop_capture/app_capturer.h
media/webrtc/trunk/webrtc/modules/desktop_capture/app_capturer_mac.mm
media/webrtc/trunk/webrtc/modules/desktop_capture/app_capturer_null.cc
media/webrtc/trunk/webrtc/modules/desktop_capture/app_capturer_unittest.cc
media/webrtc/trunk/webrtc/modules/desktop_capture/app_capturer_win.cc
media/webrtc/trunk/webrtc/modules/desktop_capture/app_capturer_x11.cc
media/webrtc/trunk/webrtc/modules/desktop_capture/desktop_device_info.cc
media/webrtc/trunk/webrtc/modules/desktop_capture/mac/desktop_device_info_mac.h
media/webrtc/trunk/webrtc/modules/desktop_capture/mac/desktop_device_info_mac.mm
media/webrtc/trunk/webrtc/modules/desktop_capture/win/desktop_device_info_win.cc
media/webrtc/trunk/webrtc/modules/desktop_capture/win/desktop_device_info_win.h
media/webrtc/trunk/webrtc/modules/desktop_capture/x11/desktop_device_info_x11.cc
media/webrtc/trunk/webrtc/modules/desktop_capture/x11/desktop_device_info_x11.h
media/webrtc/trunk/webrtc/modules/desktop_capture/x11/shared_x_util.cc
media/webrtc/trunk/webrtc/modules/media_file/source/avi_file.cc
media/webrtc/trunk/webrtc/modules/media_file/source/avi_file.h
media/webrtc/trunk/webrtc/modules/media_file/source/media_file.gypi
media/webrtc/trunk/webrtc/modules/remote_bitrate_estimator/remote_bitrate_estimator_components.gyp
media/webrtc/trunk/webrtc/modules/rtp_rtcp/source/rtp_rtcp.gypi
media/webrtc/trunk/webrtc/modules/utility/source/frame_scaler.cc
media/webrtc/trunk/webrtc/modules/utility/source/frame_scaler.h
media/webrtc/trunk/webrtc/modules/utility/source/utility.gypi
media/webrtc/trunk/webrtc/modules/utility/source/video_coder.cc
media/webrtc/trunk/webrtc/modules/utility/source/video_coder.h
media/webrtc/trunk/webrtc/modules/utility/source/video_frames_queue.cc
media/webrtc/trunk/webrtc/modules/utility/source/video_frames_queue.h
media/webrtc/trunk/webrtc/modules/video_capture/android/java/src/org/webrtc/videoengine/CaptureCapabilityAndroid.java
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/OWNERS
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/benchmark.cc
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/benchmark.h
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/exportfig.m
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/normal_async_test.cc
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/normal_async_test.h
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/normal_test.cc
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/normal_test.h
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/packet_loss_test.cc
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/packet_loss_test.h
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/plotBenchmark.m
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/test.cc
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/test.h
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/test_framework.gypi
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/unit_test.cc
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/unit_test.h
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/video_source.cc
media/webrtc/trunk/webrtc/modules/video_coding/codecs/test_framework/video_source.h
media/webrtc/trunk/webrtc/modules/video_coding/main/source/er_tables_xor.h
media/webrtc/trunk/webrtc/modules/video_coding/main/source/video_coding.gypi
media/webrtc/trunk/webrtc/modules/video_coding/main/source/video_coding_test.gypi
media/webrtc/trunk/webrtc/modules/video_coding/main/test/codec_database_test.cc
media/webrtc/trunk/webrtc/modules/video_coding/main/test/codec_database_test.h
media/webrtc/trunk/webrtc/modules/video_coding/main/test/generic_codec_test.cc
media/webrtc/trunk/webrtc/modules/video_coding/main/test/generic_codec_test.h
media/webrtc/trunk/webrtc/modules/video_coding/main/test/jitter_estimate_test.h
media/webrtc/trunk/webrtc/modules/video_coding/main/test/media_opt_test.cc
media/webrtc/trunk/webrtc/modules/video_coding/main/test/media_opt_test.h
media/webrtc/trunk/webrtc/modules/video_coding/main/test/mt_rx_tx_test.cc
media/webrtc/trunk/webrtc/modules/video_coding/main/test/mt_test_common.cc
media/webrtc/trunk/webrtc/modules/video_coding/main/test/mt_test_common.h
media/webrtc/trunk/webrtc/modules/video_coding/main/test/normal_test.cc
media/webrtc/trunk/webrtc/modules/video_coding/main/test/normal_test.h
media/webrtc/trunk/webrtc/modules/video_coding/main/test/quality_modes_test.cc
media/webrtc/trunk/webrtc/modules/video_coding/main/test/quality_modes_test.h
media/webrtc/trunk/webrtc/modules/video_coding/main/test/test_callbacks.cc
media/webrtc/trunk/webrtc/modules/video_coding/main/test/test_callbacks.h
media/webrtc/trunk/webrtc/modules/video_coding/main/test/test_macros.h
media/webrtc/trunk/webrtc/modules/video_coding/main/test/video_rtp_play_mt.cc
media/webrtc/trunk/webrtc/modules/video_coding/main/test/video_source.cc
media/webrtc/trunk/webrtc/modules/video_processing/main/source/video_processing.gypi
media/webrtc/trunk/webrtc/system_wrappers/interface/compile_assert.h
media/webrtc/trunk/webrtc/system_wrappers/interface/scoped_ptr.h
media/webrtc/trunk/webrtc/system_wrappers/interface/template_util.h
media/webrtc/trunk/webrtc/system_wrappers/source/droid-cpu-features.c
media/webrtc/trunk/webrtc/system_wrappers/source/move.h
media/webrtc/trunk/webrtc/system_wrappers/source/set_thread_name_win.h
media/webrtc/trunk/webrtc/system_wrappers/source/system_wrappers.gyp
media/webrtc/trunk/webrtc/system_wrappers/source/system_wrappers_tests.gyp
media/webrtc/trunk/webrtc/system_wrappers/source/system_wrappers_unittests.isolate
media/webrtc/trunk/webrtc/test/manual/README
media/webrtc/trunk/webrtc/test/manual/adapter.js
media/webrtc/trunk/webrtc/test/manual/audio-and-video.html
media/webrtc/trunk/webrtc/test/manual/iframe-apprtc.html
media/webrtc/trunk/webrtc/test/manual/iframe-video.html
media/webrtc/trunk/webrtc/test/manual/multiple-audio.html
media/webrtc/trunk/webrtc/test/manual/multiple-video.html
media/webrtc/trunk/webrtc/test/manual/single-audio.html
media/webrtc/trunk/webrtc/test/manual/single-video.html
media/webrtc/trunk/webrtc/test/manual/two-video-devices.html
media/webrtc/trunk/webrtc/video_engine/browser_capture_impl.h
media/webrtc/trunk/webrtc/video_engine/desktop_capture_impl.cc
media/webrtc/trunk/webrtc/video_engine/desktop_capture_impl.h
media/webrtc/trunk/webrtc/video_engine/vie_channel.cc
testing/specialpowers/components/SpecialPowersObserver.js
testing/web-platform/meta/content-security-policy/blink-contrib/self-doesnt-match-blob.sub.html.ini
testing/web-platform/meta/content-security-policy/blink-contrib/star-doesnt-match-blob.sub.html.ini
testing/web-platform/meta/mixed-content/blockable/http-csp/cross-origin-http/worker-request/top-level/keep-scheme-redirect/opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/http-csp/cross-origin-http/worker-request/top-level/no-redirect/opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/http-csp/cross-origin-http/worker-request/top-level/swap-scheme-redirect/opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/http-csp/same-host-http/worker-request/top-level/keep-scheme-redirect/opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/http-csp/same-host-http/worker-request/top-level/no-redirect/opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/http-csp/same-host-http/worker-request/top-level/swap-scheme-redirect/opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/meta-csp/cross-origin-http/worker-request/top-level/no-redirect/opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/meta-csp/same-host-http/worker-request/top-level/no-redirect/opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/worker-request/top-level/keep-scheme-redirect/no-opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/worker-request/top-level/no-redirect/no-opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/worker-request/top-level/swap-scheme-redirect/no-opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/worker-request/top-level/keep-scheme-redirect/no-opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/worker-request/top-level/no-redirect/no-opt-in-blocks.https.html.ini
testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/worker-request/top-level/swap-scheme-redirect/no-opt-in-blocks.https.html.ini
testing/web-platform/meta/workers/Worker_cross_origin_security_err.htm.ini
toolkit/components/telemetry/TelemetrySession.jsm
--- a/CLOBBER
+++ b/CLOBBER
@@ -17,9 +17,9 @@
 #
 # Modifying this file will now automatically clobber the buildbot machines \o/
 #
 
 # Are you updating CLOBBER because you think it's needed for your WebIDL
 # changes to stick? As of bug 928195, this shouldn't be necessary! Please
 # don't change CLOBBER for WebIDL changes any more.
 
-Bug 1214058 New xpcshell test not getting picked up
+Bug 1198458 Fix failures in TaskCluster builds due to analog_agc.cc moving
--- a/accessible/windows/msaa/nsWinUtils.cpp
+++ b/accessible/windows/msaa/nsWinUtils.cpp
@@ -41,17 +41,17 @@ already_AddRefed<nsIDOMCSSStyleDeclarati
 nsWinUtils::GetComputedStyleDeclaration(nsIContent* aContent)
 {
   nsIContent* elm = nsCoreUtils::GetDOMElementFor(aContent);
   if (!elm)
     return nullptr;
 
   // Returns number of items in style declaration
   nsCOMPtr<nsPIDOMWindow> window =
-    do_QueryInterface(elm->OwnerDoc()->GetWindow());
+    do_QueryInterface(elm->OwnerDoc()->GetInnerWindow());
   if (!window)
     return nullptr;
 
   ErrorResult dummy;
   nsCOMPtr<nsICSSDeclaration> cssDecl;
   nsCOMPtr<Element> domElement(do_QueryInterface(elm));
   cssDecl = window->GetComputedStyle(*domElement, EmptyString(), dummy);
   nsCOMPtr<nsIDOMCSSStyleDeclaration> domDecl = do_QueryInterface(cssDecl);
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -339,20 +339,16 @@ pref("image.mem.allow_locking_in_content
 // Almost everything that was factored into 'max_decoded_image_kb' is now stored
 // in the surface cache.  1/8 of main memory is 32MB on a 256MB device, which is
 // about the same as the old 'max_decoded_image_kb'.
 pref("image.mem.surfacecache.max_size_kb", 131072);  // 128MB
 pref("image.mem.surfacecache.size_factor", 8);  // 1/8 of main memory
 pref("image.mem.surfacecache.discard_factor", 2);  // Discard 1/2 of the surface cache at a time.
 pref("image.mem.surfacecache.min_expiration_ms", 86400000); // 24h, we rely on the out of memory hook
 
-// XXX this isn't a good check for "are touch events supported", but
-// we don't really have a better one at the moment.
-// enable touch events interfaces
-pref("dom.w3c_touch_events.enabled", 1);
 pref("dom.w3c_touch_events.safetyX", 0); // escape borders in units of 1/240"
 pref("dom.w3c_touch_events.safetyY", 120); // escape borders in units of 1/240"
 
 #ifdef MOZ_SAFE_BROWSING
 pref("browser.safebrowsing.enabled", true);
 // Prevent loading of pages identified as malware
 pref("browser.safebrowsing.malware.enabled", true);
 pref("browser.safebrowsing.downloads.enabled", true);
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -481,20 +481,16 @@ pref("general.warnOnAboutConfig",       
 pref("dom.disable_window_open_feature.location",  true);
 // prevent JS from setting status messages
 pref("dom.disable_window_status_change",          true);
 // allow JS to move and resize existing windows
 pref("dom.disable_window_move_resize",            false);
 // prevent JS from monkeying with window focus, etc
 pref("dom.disable_window_flip",                   true);
 
-// Disable touch events on Desktop Firefox by default until they are properly
-// supported (bug 736048)
-pref("dom.w3c_touch_events.enabled",        0);
-
 // popups.policy 1=allow,2=reject
 pref("privacy.popups.policy",               1);
 pref("privacy.popups.usecustom",            true);
 pref("privacy.popups.showBrowserMessage",   true);
 
 pref("privacy.item.cookies",                false);
 
 pref("privacy.clearOnShutdown.history",     true);
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -6139,38 +6139,34 @@ var BrowserOffline = {
       Services.obs.removeObserver(this, "network:offline-status-changed");
     }
   },
 
   toggleOfflineStatus: function ()
   {
     var ioService = Services.io;
 
-    // Stop automatic management of the offline status
-    try {
-      ioService.manageOfflineStatus = false;
-    } catch (ex) {
-    }
-
     if (!ioService.offline && !this._canGoOffline()) {
       this._updateOfflineUI(false);
       return;
     }
 
     ioService.offline = !ioService.offline;
   },
 
   /////////////////////////////////////////////////////////////////////////////
   // nsIObserver
   observe: function (aSubject, aTopic, aState)
   {
     if (aTopic != "network:offline-status-changed")
       return;
 
-    this._updateOfflineUI(aState == "offline");
+    // This notification is also received because of a loss in connectivity,
+    // which we ignore by updating the UI to the current value of io.offline
+    this._updateOfflineUI(Services.io.offline);
   },
 
   /////////////////////////////////////////////////////////////////////////////
   // BrowserOffline Implementation Methods
   _canGoOffline: function ()
   {
     try {
       var cancelGoOffline = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool);
--- a/build/autoconf/icu.m4
+++ b/build/autoconf/icu.m4
@@ -15,17 +15,17 @@ MOZ_ARG_WITH_BOOL(system-icu,
 [  --with-system-icu
                           Use system ICU (located with pkgconfig)],
     MOZ_NATIVE_ICU=1)
 
 if test -n "$MOZ_NATIVE_ICU"; then
     PKG_CHECK_MODULES(MOZ_ICU, icu-i18n >= 50.1)
     MOZ_SHARED_ICU=1
 else
-    MOZ_ICU_CFLAGS='-I$(topsrcdir)/intl/icu/source/common -I$(topsrcdir)/intl/icu/source/i18n'
+    MOZ_ICU_CFLAGS="-I$_topsrcdir/intl/icu/source/common -I$_topsrcdir/intl/icu/source/i18n"
     AC_SUBST_LIST(MOZ_ICU_CFLAGS)
 fi
 
 AC_SUBST(MOZ_NATIVE_ICU)
 
 MOZ_ARG_WITH_STRING(intl-api,
 [  --with-intl-api, --with-intl-api=build, --without-intl-api
     Determine the status of the ECMAScript Internationalization API.  The first
--- a/build/clang-plugin/clang-plugin.cpp
+++ b/build/clang-plugin/clang-plugin.cpp
@@ -151,16 +151,17 @@ bool isInIgnoredNamespaceForImplicitCtor
   if (name == "") {
     return false;
   }
 
   return name == "std" ||               // standard C++ lib
          name == "__gnu_cxx" ||         // gnu C++ lib
          name == "boost" ||             // boost
          name == "webrtc" ||            // upstream webrtc
+         name == "rtc" ||               // upstream webrtc 'base' package
          name.substr(0, 4) == "icu_" || // icu
          name == "google" ||            // protobuf
          name == "google_breakpad" ||   // breakpad
          name == "soundtouch" ||        // libsoundtouch
          name == "stagefright" ||       // libstagefright
          name == "MacFileUtilities" ||  // MacFileUtilities
          name == "dwarf2reader" ||      // dwarf2reader
          name == "arm_ex_to_module" ||  // arm_ex_to_module
--- a/build/gecko_templates.mozbuild
+++ b/build/gecko_templates.mozbuild
@@ -155,16 +155,16 @@ def GeckoFramework(name, **kwargs):
     Framework(name)
 
     kwargs.setdefault('mozglue', 'library')
 
     GeckoBinary(**kwargs)
 
 
 @template
-def XPCOMBinaryComponent(name, **kwargs):
+def XPCOMBinaryComponent(name):
     '''Template defining an XPCOM binary component for Gecko.
 
     `name` is the name of the component.
     '''
-    GeckoSharedLibrary(name, **kwargs)
+    GeckoSharedLibrary(name)
 
     IS_COMPONENT = True
--- a/build/gyp.mozbuild
+++ b/build/gyp.mozbuild
@@ -1,15 +1,17 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 gyp_vars = {
+    'lsan': 0,
+    'asan': 0,
     'build_with_mozilla': 1,
     'build_with_chromium': 0,
     'use_official_google_api_keys': 0,
     'have_clock_monotonic': 1 if CONFIG['HAVE_CLOCK_MONOTONIC'] else 0,
     'have_ethtool_cmd_speed_hi': 1 if CONFIG['MOZ_WEBRTC_HAVE_ETHTOOL_SPEED_HI'] else 0,
     'include_alsa_audio': 1 if CONFIG['MOZ_ALSA'] else 0,
     'include_pulse_audio': 1 if CONFIG['MOZ_PULSEAUDIO'] else 0,
     # basic stuff for everything
@@ -22,24 +24,24 @@ gyp_vars = {
     # use_system_lib* still seems to be in use in trunk/build
     'use_system_libjpeg': 0,
     'use_system_libvpx': 0,
     'build_json': 0,
     'build_libjpeg': 0,
     'build_libyuv': 0,
     'build_libvpx': 0,
     'build_ssl': 0,
+    'build_json': 0,
+    'build_icu': 0,
+    'build_opus': 0,
     'libyuv_dir': '/media/libyuv',
     'yuv_disable_avx2': 0 if CONFIG['HAVE_X86_AVX2'] else 1,
     # don't use openssl
     'use_openssl': 0,
 
-    # saves 4MB when webrtc_trace is off
-    'enable_lazy_trace_alloc': 1 if CONFIG['RELEASE_BUILD'] else 0,
-
     'use_x11': 1 if CONFIG['MOZ_X11'] else 0,
     'use_glib': 1 if CONFIG['GLIB_LIBS'] else 0,
 
      # turn off mandatory use of NEON and instead use NEON detection
     'arm_neon': 0,
     'arm_neon_optional': 1,
 
     'moz_widget_toolkit_gonk': 0,
@@ -58,17 +60,19 @@ gyp_vars = {
     # Enable and force use of hardware AEC
     'hardware_aec_ns': 1 if CONFIG['MOZ_WEBRTC_HARDWARE_AEC_NS'] else 0,
 
     # codec enable/disables:
     'include_g711': 1,
     'include_opus': 1,
     'include_g722': 1,
     'include_ilbc': 0,
-    'include_isac': 0,
+    # We turn on ISAC because the AGC uses parts of it, and depend on the
+    # linker to throw away uneeded bits.
+    'include_isac': 1,
     'include_pcm16b': 1,
 }
 
 os = CONFIG['OS_TARGET']
 
 if os == 'WINNT':
     gyp_vars.update(
         MSVS_VERSION=CONFIG['_MSVS_VERSION'],
--- a/build/mobile/b2gautomation.py
+++ b/build/mobile/b2gautomation.py
@@ -352,21 +352,20 @@ class B2GRemoteAutomation(Automation):
         self.marionette.execute_script("""
             let SECURITY_PREF = "security.turn_off_all_security_so_that_viruses_can_take_over_this_computer";
             Components.utils.import("resource://gre/modules/Services.jsm");
             Services.prefs.setBoolPref(SECURITY_PREF, true);
 
             if (!testUtils.hasOwnProperty("specialPowersObserver")) {
               let loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
                 .getService(Components.interfaces.mozIJSSubScriptLoader);
-              loader.loadSubScript("chrome://specialpowers/content/SpecialPowersObserver.js",
+              loader.loadSubScript("chrome://specialpowers/content/SpecialPowersObserver.jsm",
                 testUtils);
               testUtils.specialPowersObserver = new testUtils.SpecialPowersObserver();
               testUtils.specialPowersObserver.init();
-              testUtils.specialPowersObserver._loadFrameScript();
             }
             """)
 
         if not self.context_chrome:
             self.marionette.set_context(self.marionette.CONTEXT_CONTENT)
 
         # run the script that starts the tests
         if self.test_script:
--- a/configure.in
+++ b/configure.in
@@ -87,17 +87,17 @@ AC_PROG_AWK
 dnl Initialize the Pthread test variables early so they can be
 dnl  overridden by each platform.
 dnl ========================================================
 MOZ_USE_PTHREADS=
 _PTHREAD_LDFLAGS=""
 
 dnl Do not allow objdir == srcdir builds.
 dnl ==============================================================
-_topsrcdir=`cd \`dirname $0\`; pwd`
+_topsrcdir=`cd \`dirname $0\`; pwd -W 2>/dev/null || pwd`
 _objdir=`pwd`
 
 dnl TODO Don't exempt L10N builds once bug 842760 is resolved.
 if test "$_topsrcdir" = "$_objdir" -a "${with_l10n_base+set}" != set; then
   echo "  ***"
   echo "  * Building directly in the main source directory is not allowed."
   echo "  *"
   echo "  * To build, you must run configure from a separate directory"
@@ -4147,17 +4147,16 @@ cairo-gtk3)
     MOZ_ENABLE_GTK3=1
     MOZ_ENABLE_XREMOTE=1
     MOZ_GL_DEFAULT_PROVIDER=GLX
 
     AC_DEFINE(MOZ_X11)
     MOZ_X11=1
     USE_FC_FREETYPE=1
 
-    TK_CFLAGS='$(MOZ_GTK3_CFLAGS)'
     MOZ_WIDGET_GTK=3
     AC_DEFINE_UNQUOTED(MOZ_WIDGET_GTK,$MOZ_WIDGET_GTK)
     MOZ_PDF_PRINTING=1
     MOZ_INSTRUMENT_EVENT_LOOP=1
     ;;
 
 cairo-gtk2|cairo-gtk2-x11)
     MOZ_WIDGET_TOOLKIT=gtk2
@@ -4165,18 +4164,16 @@ cairo-gtk2|cairo-gtk2-x11)
     MOZ_ENABLE_GTK2=1
     MOZ_ENABLE_XREMOTE=1
     MOZ_GL_DEFAULT_PROVIDER=GLX
 
     AC_DEFINE(MOZ_X11)
     MOZ_X11=1
     USE_FC_FREETYPE=1
 
-    TK_CFLAGS='$(MOZ_GTK2_CFLAGS)'
-    TK_LIBS='$(MOZ_GTK2_LIBS)'
     AC_DEFINE(MOZ_WIDGET_GTK2)
     MOZ_WIDGET_GTK=2
     AC_DEFINE_UNQUOTED(MOZ_WIDGET_GTK,$MOZ_WIDGET_GTK)
     MOZ_PDF_PRINTING=1
     MOZ_INSTRUMENT_EVENT_LOOP=1
     ;;
 
 cairo-qt)
@@ -4186,18 +4183,16 @@ cairo-qt)
       MOZ_ENABLE_XREMOTE=1
       MOZ_GL_DEFAULT_PROVIDER=GLX
       MOZ_X11=1
       AC_DEFINE(MOZ_X11)
       XT_LIBS=
     fi
 
     USE_FC_FREETYPE=1
-    TK_CFLAGS='$(MOZ_QT_CFLAGS)'
-    TK_LIBS='$(MOZ_QT_LIBS)'
     AC_DEFINE(MOZ_WIDGET_QT)
     MOZ_PDF_PRINTING=1
     AC_DEFINE(QT_NO_KEYWORDS)
     ;;
 
 cairo-cocoa)
     MOZ_WIDGET_TOOLKIT=cocoa
     AC_DEFINE(MOZ_WIDGET_COCOA)
@@ -4223,28 +4218,24 @@ cairo-uikit)
     CXXFLAGS="$CXXFLAGS $TK_CFLAGS"
     MOZ_USER_DIR="Mozilla"
     MOZ_FS_LAYOUT=bundle
     ;;
 
 cairo-android)
     AC_DEFINE(MOZ_WIDGET_ANDROID)
     MOZ_WIDGET_TOOLKIT=android
-    TK_CFLAGS='$(MOZ_CAIRO_CFLAGS) $(MOZ_PIXMAN_CFLAGS)'
-    TK_LIBS='$(MOZ_CAIRO_LIBS) $(MOZ_PIXMAN_LIBS)'
     MOZ_PDF_PRINTING=1
     MOZ_INSTRUMENT_EVENT_LOOP=1
     ;;
 
 cairo-gonk)
     AC_DEFINE(MOZ_WIDGET_GONK)
     AC_DEFINE(MOZ_TOUCH)
     MOZ_WIDGET_TOOLKIT=gonk
-    TK_CFLAGS='$(MOZ_CAIRO_CFLAGS) $(MOZ_PIXMAN_CFLAGS)'
-    TK_LIBS='$(MOZ_CAIRO_LIBS) $(MOZ_PIXMAN_LIBS)'
     MOZ_PDF_PRINTING=1
     MOZ_TOUCH=1
     MOZ_INSTRUMENT_EVENT_LOOP=1
     ;;
 
 esac
 
 AC_SUBST(MOZ_PDF_PRINTING)
@@ -4260,19 +4251,17 @@ fi
 if test "$MOZ_INSTRUMENT_EVENT_LOOP"; then
    AC_DEFINE(MOZ_INSTRUMENT_EVENT_LOOP)
 fi
 
 if test "$COMPILE_ENVIRONMENT"; then
   if test "$MOZ_ENABLE_GTK3"; then
     PKG_CHECK_MODULES(MOZ_GTK3, gtk+-3.0 >= $GTK3_VERSION gtk+-unix-print-3.0 glib-2.0 gobject-2.0 $GDK_PACKAGES)
     MOZ_GTK3_CFLAGS="-I${_topsrcdir}/widget/gtk/compat-gtk3 $MOZ_GTK3_CFLAGS"
-    dnl Contrary to MOZ_GTK2_LIBS, MOZ_GTK3_LIBS needs to be literally added to TK_LIBS instead
-    dnl of a make reference because of how TK_LIBS is mangled in toolkit/library/moz.build
-    dnl for GTK+3 builds.
+    TK_CFLAGS=$MOZ_GTK3_CFLAGS
     TK_LIBS=$MOZ_GTK3_LIBS
     AC_DEFINE_UNQUOTED(GDK_VERSION_MIN_REQUIRED,$GDK_VERSION_MIN_REQUIRED)
     AC_DEFINE_UNQUOTED(GDK_VERSION_MAX_ALLOWED,$GDK_VERSION_MIN_REQUIRED)
     GLIB_VERSION_MAX_ALLOWED=GLIB_VERSION_2_32
   fi
   if test "$MOZ_ENABLE_GTK2"; then
     GLIB_VERSION_MAX_ALLOWED=$GLIB_VERSION_MIN_REQUIRED
   fi
@@ -4281,17 +4270,20 @@ if test "$COMPILE_ENVIRONMENT"; then
       GDK_PACKAGES=gdk-x11-2.0
     fi
     AC_DEFINE_UNQUOTED(GLIB_VERSION_MIN_REQUIRED,$GLIB_VERSION_MIN_REQUIRED)
     AC_DEFINE_UNQUOTED(GLIB_VERSION_MAX_ALLOWED,$GLIB_VERSION_MAX_ALLOWED)
 
     PKG_CHECK_MODULES(MOZ_GTK2, gtk+-2.0 >= $GTK2_VERSION gtk+-unix-print-2.0 glib-2.0 >= $GLIB_VERSION gobject-2.0 $GDK_PACKAGES)
     MOZ_GTK2_CFLAGS="-I${_topsrcdir}/widget/gtk/compat $MOZ_GTK2_CFLAGS"
   fi
-
+  if test "$MOZ_ENABLE_GTK2"; then
+    TK_CFLAGS=$MOZ_GTK3_CFLAGS
+    TK_LIBS=$MOZ_GTK3_LIBS
+  fi
 fi # COMPILE_ENVIRONMENT
 
 AC_SUBST(MOZ_FS_LAYOUT)
 
 dnl ========================================================
 dnl Use ARM userspace kernel helpers; tell NSPR to enable
 dnl their usage and use them in spidermonkey.
 dnl ========================================================
@@ -4507,16 +4499,18 @@ then
     PKG_CHECK_MODULES(LIBCONTENTACTION, contentaction-0.1, _LIB_FOUND=1, _LIB_FOUND=)
     if test "$MOZ_ENABLE_CONTENTACTION"; then
        MOZ_ENABLE_CONTENTACTION=1
        MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS $_CONTENTACTION_CFLAGS"
        MOZ_QT_LIBS="$MOZ_QT_LIBS $_CONTENTACTION_LIBS"
        AC_DEFINE(MOZ_ENABLE_CONTENTACTION)
        AC_SUBST(MOZ_ENABLE_CONTENTACTION)
     fi
+    TK_CFLAGS=$MOZ_QT_CFLAGS
+    TK_LIBS=$MOZ_QT_LIBS
 fi
 
 AC_SUBST(GTK_CONFIG)
 AC_SUBST_LIST(TK_CFLAGS)
 AC_SUBST_LIST(TK_LIBS)
 
 AC_SUBST(MOZ_ENABLE_GTK2)
 AC_SUBST(MOZ_ENABLE_GTK3)
@@ -6326,18 +6320,18 @@ MOZ_ARG_ENABLE_BOOL(tree-freetype,
 if test -n "$MOZ_TREE_FREETYPE"; then
    if test -n "$_WIN32_MSVC"; then
       AC_ERROR("building with in-tree freetype is not supported on MSVC")
    fi
    AC_DEFINE(MOZ_TREE_FREETYPE)
    AC_SUBST(MOZ_TREE_FREETYPE)
    MOZ_ENABLE_CAIRO_FT=1
    FT_FONT_FEATURE="#define CAIRO_HAS_FT_FONT 1"
-   FT2_CFLAGS='-I$(topsrcdir)/modules/freetype2/include'
-   CAIRO_FT_CFLAGS='-I$(topsrcdir)/modules/freetype2/include'
+   FT2_CFLAGS="-I$_topsrcdir/modules/freetype2/include"
+   CAIRO_FT_CFLAGS="-I$_topsrcdir/modules/freetype2/include"
    CAIRO_FT_OSLIBS=''
    AC_DEFINE(HAVE_FT_BITMAP_SIZE_Y_PPEM)
    AC_DEFINE(HAVE_FT_GLYPHSLOT_EMBOLDEN)
    AC_DEFINE(HAVE_FT_LOAD_SFNT_TABLE)
    AC_SUBST_LIST(CAIRO_FT_CFLAGS)
 fi
 
 dnl ========================================================
@@ -8282,16 +8276,23 @@ else
     if test "$MOZ_X11"; then
         PKG_CHECK_MODULES(CAIRO_XRENDER, cairo-xlib-xrender >= $CAIRO_VERSION)
         MOZ_CAIRO_LIBS="$MOZ_CAIRO_LIBS $XLDFLAGS $CAIRO_XRENDER_LIBS"
         MOZ_CAIRO_OSLIBS="$MOZ_CAIRO_LIBS"
         MOZ_CAIRO_CFLAGS="$MOZ_CAIRO_CFLAGS $CAIRO_XRENDER_CFLAGS"
     fi
 fi
 
+case "$MOZ_WIDGET_TOOLKIT" in
+android|gonk)
+    TK_CFLAGS="$MOZ_CAIRO_CFLAGS $MOZ_PIXMAN_CFLAGS"
+    TK_LIBS="$MOZ_CAIRO_LIBS $MOZ_PIXMAN_LIBS"
+    ;;
+esac
+
 AC_SUBST(MOZ_TREE_CAIRO)
 AC_SUBST_LIST(MOZ_CAIRO_CFLAGS)
 AC_SUBST_LIST(MOZ_CAIRO_LIBS)
 AC_SUBST_LIST(MOZ_CAIRO_OSLIBS)
 AC_SUBST(MOZ_TREE_PIXMAN)
 
 dnl ========================================================
 dnl Skia
--- a/devtools/client/fontinspector/test/browser.ini
+++ b/devtools/client/fontinspector/test/browser.ini
@@ -7,8 +7,9 @@ support-files =
   ostrich-black.ttf
   ostrich-regular.ttf
   head.js
 
 [browser_fontinspector.js]
 [browser_fontinspector_edit-previews.js]
 [browser_fontinspector_edit-previews-show-all.js]
 [browser_fontinspector_theme-change.js]
+skip-if = e10s && debug && os == 'win'
--- a/devtools/client/framework/test/browser.ini
+++ b/devtools/client/framework/test/browser.ini
@@ -23,16 +23,17 @@ support-files =
 [browser_keybindings_01.js]
 [browser_keybindings_02.js]
 [browser_keybindings_03.js]
 [browser_new_activation_workflow.js]
 [browser_target_events.js]
 [browser_target_remote.js]
 [browser_target_support.js]
 [browser_two_tabs.js]
+skip-if = e10s && debug && os == 'win'
 [browser_toolbox_dynamic_registration.js]
 [browser_toolbox_getpanelwhenready.js]
 [browser_toolbox_highlight.js]
 [browser_toolbox_hosts.js]
 [browser_toolbox_hosts_size.js]
 [browser_toolbox_minimize.js]
 skip-if = true # Bug 1177463 - Temporarily hide the minimize button
 [browser_toolbox_options.js]
--- a/devtools/client/inspector/test/browser.ini
+++ b/devtools/client/inspector/test/browser.ini
@@ -73,16 +73,17 @@ skip-if = e10s # GCLI isn't e10s compati
 [browser_inspector_highlighter-rulers_02.js]
 [browser_inspector_highlighter-selector_01.js]
 [browser_inspector_highlighter-selector_02.js]
 [browser_inspector_highlighter-xbl.js]
 [browser_inspector_highlighter-zoom.js]
 [browser_inspector_iframe-navigation.js]
 [browser_inspector_infobar_01.js]
 [browser_inspector_initialization.js]
+skip-if = e10s && debug && os == 'win'
 [browser_inspector_inspect-object-element.js]
 [browser_inspector_invalidate.js]
 [browser_inspector_keyboard-shortcuts-copy-outerhtml.js]
 [browser_inspector_keyboard-shortcuts.js]
 [browser_inspector_menu-01-sensitivity.js]
 [browser_inspector_menu-02-copy-items.js]
 [browser_inspector_menu-03-paste-items.js]
 [browser_inspector_menu-04-use-in-console.js]
--- a/devtools/client/markupview/test/browser.ini
+++ b/devtools/client/markupview/test/browser.ini
@@ -40,16 +40,17 @@ support-files =
 [browser_markupview_anonymous_01.js]
 [browser_markupview_anonymous_02.js]
 skip-if = e10s # scratchpad.xul is not loading in e10s window
 [browser_markupview_anonymous_03.js]
 [browser_markupview_anonymous_04.js]
 [browser_markupview_copy_image_data.js]
 [browser_markupview_css_completion_style_attribute.js]
 [browser_markupview_dragdrop_autoscroll.js]
+skip-if = e10s && os == 'win'
 [browser_markupview_dragdrop_distance.js]
 [browser_markupview_dragdrop_dragRootNode.js]
 [browser_markupview_dragdrop_escapeKeyPress.js]
 [browser_markupview_dragdrop_invalidNodes.js]
 [browser_markupview_dragdrop_reorder.js]
 [browser_markupview_events.js]
 skip-if = e10s # Bug 1040751 - CodeMirror editor.destroy() isn't e10s compatible
 [browser_markupview_events_form.js]
--- a/devtools/client/performance/test/browser.ini
+++ b/devtools/client/performance/test/browser.ini
@@ -50,17 +50,17 @@ skip-if = true # Bug 1161817
 [browser_perf-legacy-front-05.js]
 [browser_perf-legacy-front-06.js]
 [browser_perf-legacy-front-07.js]
 [browser_perf-legacy-front-08.js]
 [browser_perf-legacy-front-09.js]
 [browser_perf-loading-01.js]
 [browser_perf-loading-02.js]
 [browser_perf-marker-details-01.js]
-skip-if = os == 'linux' # Bug 1172120
+skip-if = e10s || os == 'linux' # Bug 1172120
 [browser_perf-markers-docload.js]
 [browser_perf-options-01.js]
 [browser_perf-options-02.js]
 [browser_perf-options-03.js]
 [browser_perf-options-invert-call-tree-01.js]
 [browser_perf-options-invert-call-tree-02.js]
 [browser_perf-options-invert-flame-graph-01.js]
 [browser_perf-options-invert-flame-graph-02.js]
--- a/devtools/client/responsivedesign/test/browser.ini
+++ b/devtools/client/responsivedesign/test/browser.ini
@@ -6,11 +6,12 @@ support-files =
   touch.html
 
 [browser_responsive_cmd.js]
 [browser_responsivecomputedview.js]
 skip-if = e10s # Bug ??????
 [browser_responsiveruleview.js]
 skip-if = e10s # Bug ??????
 [browser_responsiveui.js]
+skip-if = e10s && os == 'win'
 [browser_responsiveui_touch.js]
 [browser_responsiveuiaddcustompreset.js]
 [browser_responsive_devicewidth.js]
--- a/devtools/client/shadereditor/test/browser.ini
+++ b/devtools/client/shadereditor/test/browser.ini
@@ -29,19 +29,31 @@ skip-if = true # Bug 942473, caused by B
 [browser_se_shaders-edit-03.js]
 [browser_webgl-actor-test-01.js]
 [browser_webgl-actor-test-02.js]
 [browser_webgl-actor-test-03.js]
 [browser_webgl-actor-test-04.js]
 [browser_webgl-actor-test-05.js]
 [browser_webgl-actor-test-06.js]
 [browser_webgl-actor-test-07.js]
+skip-if = e10s && os == 'win'
 [browser_webgl-actor-test-08.js]
+skip-if = e10s && os == 'win'
 [browser_webgl-actor-test-09.js]
+skip-if = e10s && os == 'win'
 [browser_webgl-actor-test-10.js]
+skip-if = e10s && os == 'win'
 [browser_webgl-actor-test-11.js]
+skip-if = e10s && os == 'win'
 [browser_webgl-actor-test-12.js]
+skip-if = e10s && os == 'win'
 [browser_webgl-actor-test-13.js]
+skip-if = e10s && os == 'win'
 [browser_webgl-actor-test-14.js]
+skip-if = e10s && os == 'win'
 [browser_webgl-actor-test-15.js]
+skip-if = e10s && os == 'win'
 [browser_webgl-actor-test-16.js]
+skip-if = e10s && os == 'win'
 [browser_webgl-actor-test-17.js]
+skip-if = e10s && os == 'win'
 [browser_webgl-actor-test-18.js]
+skip-if = e10s && os == 'win'
--- a/devtools/client/webconsole/test/browser.ini
+++ b/devtools/client/webconsole/test/browser.ini
@@ -135,16 +135,17 @@ support-files =
   test_bug_1010953_cspro.html
   test_bug1045902_console_csp_ignore_reflected_xss_message.html^headers^
   test_bug1045902_console_csp_ignore_reflected_xss_message.html
   test_bug1092055_shouldwarn.js^headers^
   test_bug1092055_shouldwarn.js
   test_bug1092055_shouldwarn.html
 
 [browser_bug1045902_console_csp_ignore_reflected_xss_message.js]
+skip-if = e10s && debug
 [browser_bug664688_sandbox_update_after_navigation.js]
 skip-if = e10s # Bug 1042253 - webconsole e10s tests (intermittent Linux debug)
 [browser_bug_638949_copy_link_location.js]
 [browser_bug_862916_console_dir_and_filter_off.js]
 [browser_bug_865288_repeat_different_objects.js]
 [browser_bug_865871_variables_view_close_on_esc_key.js]
 [browser_bug_869003_inspect_cross_domain_object.js]
 [browser_bug_871156_ctrlw_close_tab.js]
@@ -282,31 +283,34 @@ skip-if = e10s # Bug 1042253 - webconsol
 [browser_webconsole_bug_762593_insecure_passwords_about_blank_web_console_warning.js]
 skip-if = buildapp == 'mulet'
 [browser_webconsole_bug_762593_insecure_passwords_web_console_warning.js]
 skip-if = true # Bug 1110500 - mouse event failure in test
 [browser_webconsole_bug_764572_output_open_url.js]
 skip-if = e10s # Bug 1042253 - webconsole tests disabled with e10s
 [browser_webconsole_bug_766001_JS_Console_in_Debugger.js]
 [browser_webconsole_bug_770099_violation.js]
+skip-if = e10s && os == 'win'
 [browser_webconsole_bug_782653_CSS_links_in_Style_Editor.js]
 skip-if = buildapp == 'mulet'
 [browser_webconsole_bug_804845_ctrl_key_nav.js]
 skip-if = os != "mac"
 [browser_webconsole_bug_817834_add_edited_input_to_history.js]
 [browser_webconsole_bug_837351_securityerrors.js]
 skip-if = buildapp == 'mulet'
 [browser_webconsole_bug_915141_toggle_response_logging_with_keyboard.js]
 [browser_webconsole_filter_buttons_contextmenu.js]
 [browser_webconsole_bug_1006027_message_timestamps_incorrect.js]
 skip-if = e10s # Bug 1042253 - webconsole e10s tests (Linux debug intermittent)
 [browser_webconsole_bug_1010953_cspro.js]
+skip-if = e10s && os == 'win'
 [browser_webconsole_certificate_messages.js]
 skip-if = e10s # Bug 1042253 - webconsole tests disabled with e10s
 [browser_webconsole_show_subresource_security_errors.js]
+skip-if = e10s && os == 'win'
 [browser_webconsole_cached_autocomplete.js]
 [browser_webconsole_change_font_size.js]
 [browser_webconsole_chrome.js]
 [browser_webconsole_clickable_urls.js]
 skip-if = e10s # Bug 1042253 - webconsole e10s tests (Linux debug timeout)
 [browser_webconsole_closure_inspection.js]
 skip-if = e10s # Bug 1042253 - webconsole tests disabled with e10s
 [browser_webconsole_completion.js]
new file mode 100644
--- /dev/null
+++ b/devtools/shared/heapsnapshot/DominatorTree.cpp
@@ -0,0 +1,30 @@
+/* -*-  Mode: C++; 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/. */
+
+#include "mozilla/devtools/DominatorTree.h"
+#include "mozilla/dom/DominatorTreeBinding.h"
+
+namespace mozilla {
+namespace devtools {
+
+/*** Cycle Collection Boilerplate *****************************************************************/
+
+NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(DominatorTree, mParent)
+NS_IMPL_CYCLE_COLLECTING_ADDREF(DominatorTree)
+NS_IMPL_CYCLE_COLLECTING_RELEASE(DominatorTree)
+
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(DominatorTree)
+  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
+  NS_INTERFACE_MAP_ENTRY(nsISupports)
+NS_INTERFACE_MAP_END
+
+/* virtual */ JSObject*
+DominatorTree::WrapObject(JSContext* aCx, JS::HandleObject aGivenProto)
+{
+  return dom::DominatorTreeBinding::Wrap(aCx, this, aGivenProto);
+}
+
+} // namespace devtools
+} // namespace mozilla
new file mode 100644
--- /dev/null
+++ b/devtools/shared/heapsnapshot/DominatorTree.h
@@ -0,0 +1,50 @@
+/* -*-  Mode: C++; 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/. */
+
+#ifndef mozilla_devtools_DominatorTree__
+#define mozilla_devtools_DominatorTree__
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/ErrorResult.h"
+#include "mozilla/RefCounted.h"
+#include "js/UbiNodeDominatorTree.h"
+#include "nsWrapperCache.h"
+
+namespace mozilla {
+namespace devtools {
+
+class DominatorTree final : public nsISupports
+                          , public nsWrapperCache
+{
+protected:
+  nsCOMPtr<nsISupports> mParent;
+
+  virtual ~DominatorTree() { }
+
+private:
+  JS::ubi::DominatorTree mDominatorTree;
+
+public:
+  explicit DominatorTree(JS::ubi::DominatorTree&& aDominatorTree, nsISupports* aParent)
+    : mParent(aParent)
+    , mDominatorTree(Move(aDominatorTree))
+  {
+    MOZ_ASSERT(aParent);
+  };
+
+  NS_DECL_CYCLE_COLLECTING_ISUPPORTS;
+  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(DominatorTree);
+
+  nsISupports* GetParentObject() const { return mParent; }
+
+  virtual JSObject* WrapObject(JSContext* aCx,
+                               JS::Handle<JSObject*> aGivenProto) override;
+
+};
+
+} // namespace devtools
+} // namespace mozilla
+
+#endif // mozilla_devtools_DominatorTree__
--- a/devtools/shared/heapsnapshot/HeapSnapshot.cpp
+++ b/devtools/shared/heapsnapshot/HeapSnapshot.cpp
@@ -47,16 +47,18 @@ using namespace dom;
 
 using ::google::protobuf::io::ArrayInputStream;
 using ::google::protobuf::io::CodedInputStream;
 using ::google::protobuf::io::GzipInputStream;
 using ::google::protobuf::io::ZeroCopyInputStream;
 
 using JS::ubi::AtomOrTwoByteChars;
 
+/*** Cycle Collection Boilerplate *****************************************************************/
+
 NS_IMPL_CYCLE_COLLECTION_CLASS(HeapSnapshot)
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(HeapSnapshot)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mParent)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(HeapSnapshot)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mParent)
@@ -376,16 +378,19 @@ HeapSnapshot::saveStackFrame(const proto
   {
     return false;
   }
 
   outFrameId = id;
   return true;
 }
 
+#undef GET_STRING_OR_REF_WITH_PROP_NAMES
+#undef GET_STRING_OR_REF
+
 static inline bool
 StreamHasData(GzipInputStream& stream)
 {
   // Test for the end of the stream. The protobuf library gives no way to tell
   // the difference between an underlying read error and the stream being
   // done. All we can do is attempt to read data and extrapolate guestimations
   // from the result of that operation.
 
@@ -510,18 +515,36 @@ HeapSnapshot::TakeCensus(JSContext* cx, 
   }
 
   if (NS_WARN_IF(!handler.report(rval))) {
     rv.Throw(NS_ERROR_OUT_OF_MEMORY);
     return;
   }
 }
 
-#undef GET_STRING_OR_REF_WITH_PROP_NAMES
-#undef GET_STRING_OR_REF
+already_AddRefed<DominatorTree>
+HeapSnapshot::ComputeDominatorTree(ErrorResult& rv)
+{
+  Maybe<JS::ubi::DominatorTree> maybeTree;
+  {
+    auto ccrt = CycleCollectedJSRuntime::Get();
+    MOZ_ASSERT(ccrt);
+    auto rt = ccrt->Runtime();
+    MOZ_ASSERT(rt);
+    JS::AutoCheckCannotGC nogc(rt);
+    maybeTree = JS::ubi::DominatorTree::Create(rt, nogc, getRoot());
+  }
+
+  if (maybeTree.isNothing()) {
+    rv.Throw(NS_ERROR_OUT_OF_MEMORY);
+    return nullptr;
+  }
+
+  return MakeAndAddRef<DominatorTree>(Move(*maybeTree), mParent);
+}
 
 
 /*** Saving Heap Snapshots ************************************************************************/
 
 // If we are only taking a snapshot of the heap affected by the given set of
 // globals, find the set of zones the globals are allocated within. Returns
 // false on OOM failure.
 static bool
--- a/devtools/shared/heapsnapshot/HeapSnapshot.h
+++ b/devtools/shared/heapsnapshot/HeapSnapshot.h
@@ -4,16 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_devtools_HeapSnapshot__
 #define mozilla_devtools_HeapSnapshot__
 
 #include "js/HashTable.h"
 #include "mozilla/ErrorResult.h"
 #include "mozilla/devtools/DeserializedNode.h"
+#include "mozilla/devtools/DominatorTree.h"
 #include "mozilla/dom/BindingDeclarations.h"
 #include "mozilla/dom/Nullable.h"
 #include "mozilla/HashFunctions.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/RefCounted.h"
 #include "mozilla/RefPtr.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/UniquePtr.h"
@@ -145,16 +146,18 @@ public:
     MOZ_ASSERT(p);
     const DeserializedNode& node = *p;
     return JS::ubi::Node(const_cast<DeserializedNode*>(&node));
   }
 
   void TakeCensus(JSContext* cx, JS::HandleObject options,
                   JS::MutableHandleValue rval, ErrorResult& rv);
 
+  already_AddRefed<DominatorTree> ComputeDominatorTree(ErrorResult& rv);
+
   dom::Nullable<uint64_t> GetCreationTime() {
     static const uint64_t maxTime = uint64_t(1) << 53;
     if (timestamp.isSome() && timestamp.ref() <= maxTime) {
       return dom::Nullable<uint64_t>(timestamp.ref());
     }
 
     return dom::Nullable<uint64_t>();
   }
--- a/devtools/shared/heapsnapshot/moz.build
+++ b/devtools/shared/heapsnapshot/moz.build
@@ -10,16 +10,17 @@ if CONFIG['ENABLE_TESTS']:
 XPCSHELL_TESTS_MANIFESTS += [ 'tests/unit/xpcshell.ini' ]
 MOCHITEST_MANIFESTS += [ 'tests/mochitest/mochitest.ini' ]
 MOCHITEST_CHROME_MANIFESTS += [ 'tests/mochitest/chrome.ini' ]
 
 EXPORTS.mozilla.devtools += [
     'AutoMemMap.h',
     'CoreDump.pb.h',
     'DeserializedNode.h',
+    'DominatorTree.h',
     'FileDescriptorOutputStream.h',
     'HeapSnapshot.h',
     'HeapSnapshotTempFileHelperChild.h',
     'HeapSnapshotTempFileHelperParent.h',
     'ZeroCopyNSIOutputStream.h',
 ]
 
 IPDL_SOURCES += [
@@ -27,16 +28,17 @@ IPDL_SOURCES += [
 ]
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
 SOURCES += [
     'AutoMemMap.cpp',
     'CoreDump.pb.cc',
     'DeserializedNode.cpp',
+    'DominatorTree.cpp',
     'FileDescriptorOutputStream.cpp',
     'HeapSnapshot.cpp',
     'HeapSnapshotTempFileHelperParent.cpp',
     'ZeroCopyNSIOutputStream.cpp',
 ]
 
 # Disable RTTI in google protocol buffer
 DEFINES['GOOGLE_PROTOBUF_NO_RTTI'] = True
--- a/devtools/shared/heapsnapshot/tests/mochitest/chrome.ini
+++ b/devtools/shared/heapsnapshot/tests/mochitest/chrome.ini
@@ -1,7 +1,8 @@
 [DEFAULT]
 tags = devtools devtools-memory
 skip-if = buildapp == 'b2g' || os == 'android'
 support-files =
 
+[test_DominatorTree_01.html]
 [test_SaveHeapSnapshot.html]
 
new file mode 100644
--- /dev/null
+++ b/devtools/shared/heapsnapshot/tests/mochitest/test_DominatorTree_01.html
@@ -0,0 +1,37 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+Sanity test that we can compute dominator trees from a heap snapshot in a web window.
+-->
+<head>
+  <meta charset="utf-8">
+  <title>ChromeUtils.saveHeapSnapshot test</title>
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
+</head>
+<body>
+<pre id="test">
+<script>
+SimpleTest.waitForExplicitFinish();
+window.onload = function() {
+  const path = ChromeUtils.saveHeapSnapshot({ runtime: true });
+  const snapshot = ChromeUtils.readHeapSnapshot(path);
+
+  const dominatorTree = snapshot.computeDominatorTree();
+  ok(dominatorTree);
+  ok(dominatorTree instanceof DominatorTree);
+
+  let threw = false;
+  try {
+    new DominatorTree();
+  } catch (e) {
+    threw = true;
+  }
+  ok(threw, "Constructor shouldn't be usable");
+
+  SimpleTest.finish();
+};
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/devtools/shared/heapsnapshot/tests/unit/dominator-tree-worker.js
@@ -0,0 +1,47 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+console.log("Initializing worker.");
+
+self.onmessage = e => {
+  console.log("Starting test.");
+  try {
+    const path = ThreadSafeChromeUtils.saveHeapSnapshot({ runtime: true });
+    const snapshot = ThreadSafeChromeUtils.readHeapSnapshot(path);
+
+    const dominatorTree = snapshot.computeDominatorTree();
+    ok(dominatorTree);
+    ok(dominatorTree instanceof DominatorTree);
+
+    let threw = false;
+    try {
+      new DominatorTree();
+    } catch (e) {
+      threw = true;
+    }
+    ok(threw, "Constructor shouldn't be usable");
+  } catch (e) {
+    ok(false, "Unexpected error inside worker:\n" + e.toString() + "\n" + e.stack);
+  } finally {
+    done();
+  }
+};
+
+// Proxy assertions to the main thread.
+function ok(val, msg) {
+  console.log("ok(" + !!val + ", \"" + msg + "\")");
+  self.postMessage({
+    type: "assertion",
+    passed: !!val,
+    msg,
+    stack: Error().stack
+  });
+}
+
+// Tell the main thread we are done with the tests.
+function done() {
+  console.log("done()");
+  self.postMessage({
+    type: "done"
+  });
+}
new file mode 100644
--- /dev/null
+++ b/devtools/shared/heapsnapshot/tests/unit/test_DominatorTree_01.js
@@ -0,0 +1,23 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Sanity test that we can compute dominator trees.
+
+function run_test() {
+  const path = ChromeUtils.saveHeapSnapshot({ runtime: true });
+  const snapshot = ChromeUtils.readHeapSnapshot(path);
+
+  const dominatorTree = snapshot.computeDominatorTree();
+  ok(dominatorTree);
+  ok(dominatorTree instanceof DominatorTree);
+
+  let threw = false;
+  try {
+    new DominatorTree();
+  } catch (e) {
+    threw = true;
+  }
+  ok(threw, "Constructor shouldn't be usable");
+
+  do_test_finished();
+}
new file mode 100644
--- /dev/null
+++ b/devtools/shared/heapsnapshot/tests/unit/test_DominatorTree_02.js
@@ -0,0 +1,40 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Test that we can compute dominator trees from a snapshot in a worker.
+
+add_task(function* () {
+  const worker = new ChromeWorker("resource://test/dominator-tree-worker.js");
+  worker.postMessage({});
+
+  let assertionCount = 0;
+  worker.onmessage = e => {
+    if (e.data.type !== "assertion") {
+      return;
+    }
+
+    ok(e.data.passed, e.data.msg + "\n" + e.data.stack);
+    assertionCount++;
+  };
+
+  yield waitForDone(worker);
+
+  ok(assertionCount > 0);
+  worker.terminate();
+});
+
+function waitForDone(w) {
+  return new Promise((resolve, reject) => {
+    w.onerror = e => {
+      reject();
+      ok(false, "Error in worker: " + e);
+    };
+
+    w.addEventListener("message", function listener(e) {
+      if (e.data.type === "done") {
+        w.removeEventListener("message", listener, false);
+        resolve();
+      }
+    }, false);
+  });
+}
--- a/devtools/shared/heapsnapshot/tests/unit/xpcshell.ini
+++ b/devtools/shared/heapsnapshot/tests/unit/xpcshell.ini
@@ -2,16 +2,17 @@
 tags = devtools heapsnapshot devtools-memory
 head = head_heapsnapshot.js
 tail =
 firefox-appdir = browser
 skip-if = toolkit == 'android' || toolkit == 'gonk'
 
 support-files =
   Census.jsm
+  dominator-tree-worker.js
   heap-snapshot-worker.js
   Match.jsm
 
 [test_census_diff_01.js]
 [test_census_diff_02.js]
 [test_census_diff_03.js]
 [test_census_diff_04.js]
 [test_census_diff_05.js]
@@ -22,16 +23,18 @@ support-files =
 [test_census-tree-node-01.js]
 [test_census-tree-node-02.js]
 [test_census-tree-node-03.js]
 [test_census-tree-node-04.js]
 [test_census-tree-node-05.js]
 [test_census-tree-node-06.js]
 [test_census-tree-node-07.js]
 [test_census-tree-node-08.js]
+[test_DominatorTree_01.js]
+[test_DominatorTree_02.js]
 [test_HeapAnalyses_getCreationTime_01.js]
 [test_HeapAnalyses_readHeapSnapshot_01.js]
 [test_HeapAnalyses_takeCensusDiff_01.js]
 [test_HeapAnalyses_takeCensusDiff_02.js]
 [test_HeapAnalyses_takeCensus_01.js]
 [test_HeapAnalyses_takeCensus_02.js]
 [test_HeapAnalyses_takeCensus_03.js]
 [test_HeapAnalyses_takeCensus_04.js]
--- a/dom/base/FragmentOrElement.cpp
+++ b/dom/base/FragmentOrElement.cpp
@@ -504,17 +504,16 @@ NS_IMPL_CYCLE_COLLECTING_ADDREF(nsNodeSu
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsNodeSupportsWeakRefTearoff)
 
 NS_IMETHODIMP
 nsNodeSupportsWeakRefTearoff::GetWeakReference(nsIWeakReference** aInstancePtr)
 {
   nsINode::nsSlots* slots = mNode->Slots();
   if (!slots->mWeakReference) {
     slots->mWeakReference = new nsNodeWeakReference(mNode);
-    NS_ENSURE_TRUE(slots->mWeakReference, NS_ERROR_OUT_OF_MEMORY);
   }
 
   NS_ADDREF(*aInstancePtr = slots->mWeakReference);
 
   return NS_OK;
 }
 
 //----------------------------------------------------------------------
--- a/dom/base/nsAttrValue.cpp
+++ b/dom/base/nsAttrValue.cpp
@@ -162,20 +162,17 @@ nsAttrValue::~nsAttrValue()
   ResetIfSet();
 }
 
 /* static */
 nsresult
 nsAttrValue::Init()
 {
   NS_ASSERTION(!sEnumTableArray, "nsAttrValue already initialized");
-
   sEnumTableArray = new nsTArray<const EnumTable*>;
-  NS_ENSURE_TRUE(sEnumTableArray, NS_ERROR_OUT_OF_MEMORY);
-  
   return NS_OK;
 }
 
 /* static */
 void
 nsAttrValue::Shutdown()
 {
   delete sEnumTableArray;
@@ -1845,24 +1842,18 @@ bool
 nsAttrValue::EnsureEmptyAtomArray()
 {
   if (Type() == eAtomArray) {
     ResetMiscAtomOrString();
     GetAtomArrayValue()->Clear();
     return true;
   }
 
-  AtomArray* array = new AtomArray;
-  if (!array) {
-    Reset();
-    return false;
-  }
-
   MiscContainer* cont = EnsureEmptyMiscContainer();
-  cont->mValue.mAtomArray = array;
+  cont->mValue.mAtomArray = new AtomArray;
   cont->mType = eAtomArray;
 
   return true;
 }
 
 already_AddRefed<nsStringBuffer>
 nsAttrValue::GetStringBuffer(const nsAString& aValue) const
 {
--- a/dom/base/nsCCUncollectableMarker.cpp
+++ b/dom/base/nsCCUncollectableMarker.cpp
@@ -51,17 +51,16 @@ NS_IMPL_ISUPPORTS(nsCCUncollectableMarke
 nsresult
 nsCCUncollectableMarker::Init()
 {
   if (sInited) {
     return NS_OK;
   }
 
   nsCOMPtr<nsIObserver> marker = new nsCCUncollectableMarker;
-  NS_ENSURE_TRUE(marker, NS_ERROR_OUT_OF_MEMORY);
 
   nsCOMPtr<nsIObserverService> obs =
     mozilla::services::GetObserverService();
   if (!obs)
     return NS_ERROR_FAILURE;
 
   nsresult rv;
 
--- a/dom/base/nsContentPermissionHelper.cpp
+++ b/dom/base/nsContentPermissionHelper.cpp
@@ -146,17 +146,16 @@ ContentPermissionRequestParent::~Content
 {
   MOZ_COUNT_DTOR(ContentPermissionRequestParent);
 }
 
 bool
 ContentPermissionRequestParent::Recvprompt()
 {
   mProxy = new nsContentPermissionRequestProxy();
-  NS_ASSERTION(mProxy, "Alloc of request proxy failed");
   if (NS_FAILED(mProxy->Init(mRequests, this))) {
     mProxy->Cancel();
   }
   return true;
 }
 
 bool
 ContentPermissionRequestParent::RecvNotifyVisibility(const bool& aIsVisible)
--- a/dom/base/nsContentPolicy.cpp
+++ b/dom/base/nsContentPolicy.cpp
@@ -31,18 +31,16 @@ using mozilla::LogLevel;
 NS_IMPL_ISUPPORTS(nsContentPolicy, nsIContentPolicy)
 
 static PRLogModuleInfo* gConPolLog;
 
 nsresult
 NS_NewContentPolicy(nsIContentPolicy **aResult)
 {
   *aResult = new nsContentPolicy;
-  if (!*aResult)
-      return NS_ERROR_OUT_OF_MEMORY;
   NS_ADDREF(*aResult);
   return NS_OK;
 }
 
 nsContentPolicy::nsContentPolicy()
     : mPolicies(NS_CONTENTPOLICY_CATEGORY)
     , mSimplePolicies(NS_SIMPLECONTENTPOLICY_CATEGORY)
 {
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -1406,17 +1406,16 @@ nsDOMConstructor::Create(const char16_t*
     return NS_ERROR_DOM_SECURITY_ERR;
   }
 
   bool constructable = aNameStruct ?
                          IsConstructable(aNameStruct) :
                          IsConstructable(aData);
 
   *aResult = new nsDOMConstructor(aName, constructable, currentInner);
-  NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
   NS_ADDREF(*aResult);
   return NS_OK;
 }
 
 NS_IMPL_ADDREF(nsDOMConstructor)
 NS_IMPL_RELEASE(nsDOMConstructor)
 NS_INTERFACE_MAP_BEGIN(nsDOMConstructor)
   NS_INTERFACE_MAP_ENTRY(nsIDOMDOMConstructor)
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -1893,17 +1893,16 @@ nsDOMWindowUtils::SendQueryContentEvent(
       break;
   }
 
   nsEventStatus status;
   nsresult rv = targetWidget->DispatchEvent(&queryEvent, status);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsQueryContentEventResult* result = new nsQueryContentEventResult();
-  NS_ENSURE_TRUE(result, NS_ERROR_OUT_OF_MEMORY);
   result->SetEventResult(widget, queryEvent);
   NS_ADDREF(*aResult = result);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMWindowUtils::SendSelectionSetEvent(uint32_t aOffset,
                                         uint32_t aLength,
--- a/dom/base/nsDocument.cpp
+++ b/dom/base/nsDocument.cpp
@@ -309,18 +309,16 @@ nsIdentifierMapEntry::AppendAllIdContent
 }
 
 void
 nsIdentifierMapEntry::AddContentChangeCallback(nsIDocument::IDTargetObserver aCallback,
                                                void* aData, bool aForImage)
 {
   if (!mChangeCallbacks) {
     mChangeCallbacks = new nsTHashtable<ChangeCallbackEntry>;
-    if (!mChangeCallbacks)
-      return;
   }
 
   ChangeCallback cc = { aCallback, aData, aForImage };
   mChangeCallbacks->PutEntry(cc);
 }
 
 void
 nsIdentifierMapEntry::RemoveContentChangeCallback(nsIDocument::IDTargetObserver aCallback,
@@ -1242,19 +1240,16 @@ IMPL_SHIM(nsIApplicationCacheContainer)
 #define TRY_SHIM(_i)                                                       \
   PR_BEGIN_MACRO                                                           \
     if (IID_IS(_i)) {                                                      \
       nsCOMPtr<_i> real = do_GetInterface(mCallbacks);                     \
       if (!real) {                                                         \
         return NS_NOINTERFACE;                                             \
       }                                                                    \
       nsCOMPtr<_i> shim = new _i##Shim(this, real);                        \
-      if (!shim) {                                                         \
-        return NS_ERROR_OUT_OF_MEMORY;                                     \
-      }                                                                    \
       shim.forget(aSink);                                                  \
       return NS_OK;                                                        \
     }                                                                      \
   PR_END_MACRO
 
 NS_IMETHODIMP
 nsExternalResourceMap::LoadgroupCallbacks::GetInterface(const nsIID & aIID,
                                                         void **aSink)
@@ -10029,18 +10024,16 @@ nsDocument::SetChangeScrollPosWhenScroll
   mChangeScrollPosWhenScrollingToRef = aValue;
 }
 
 void
 nsIDocument::RegisterActivityObserver(nsISupports* aSupports)
 {
   if (!mActivityObservers) {
     mActivityObservers = new nsTHashtable<nsPtrHashKey<nsISupports> >();
-    if (!mActivityObservers)
-      return;
   }
   mActivityObservers->PutEntry(aSupports);
 }
 
 bool
 nsIDocument::UnregisterActivityObserver(nsISupports* aSupports)
 {
   if (!mActivityObservers) {
--- a/dom/base/nsDocumentEncoder.cpp
+++ b/dom/base/nsDocumentEncoder.cpp
@@ -1302,18 +1302,16 @@ nsDocumentEncoder::SetNodeFixup(nsIDocum
 
 
 nsresult NS_NewTextEncoder(nsIDocumentEncoder** aResult); // make mac compiler happy
 
 nsresult
 NS_NewTextEncoder(nsIDocumentEncoder** aResult)
 {
   *aResult = new nsDocumentEncoder;
-  if (!*aResult)
-    return NS_ERROR_OUT_OF_MEMORY;
  NS_ADDREF(*aResult);
  return NS_OK;
 }
 
 class nsHTMLCopyEncoder : public nsDocumentEncoder
 {
 public:
 
@@ -2049,18 +2047,16 @@ nsHTMLCopyEncoder::IsEmptyTextContent(ns
 }
 
 nsresult NS_NewHTMLCopyTextEncoder(nsIDocumentEncoder** aResult); // make mac compiler happy
 
 nsresult
 NS_NewHTMLCopyTextEncoder(nsIDocumentEncoder** aResult)
 {
   *aResult = new nsHTMLCopyEncoder;
-  if (!*aResult)
-    return NS_ERROR_OUT_OF_MEMORY;
  NS_ADDREF(*aResult);
  return NS_OK;
 }
 
 int32_t
 nsHTMLCopyEncoder::GetImmediateContextCount(const nsTArray<nsINode*>& aAncestorArray)
 {
   int32_t i = aAncestorArray.Length(), j = 0;
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -185,17 +185,16 @@ nsFocusManager::~nsFocusManager()
   }
 }
 
 // static
 nsresult
 nsFocusManager::Init()
 {
   nsFocusManager* fm = new nsFocusManager();
-  NS_ENSURE_TRUE(fm, NS_ERROR_OUT_OF_MEMORY);
   NS_ADDREF(fm);
   sInstance = fm;
 
   gFocusLog = PR_NewLogModule("Focus");
   gFocusNavigationLog = PR_NewLogModule("FocusNavigation");
 
   nsIContent::sTabFocusModelAppliesToXUL =
     Preferences::GetBool("accessibility.tabfocus_applies_to_xul",
--- a/dom/base/nsGenConImageContent.cpp
+++ b/dom/base/nsGenConImageContent.cpp
@@ -71,18 +71,16 @@ NS_IMPL_ISUPPORTS_INHERITED(nsGenConImag
                             imgIOnloadBlocker)
 
 nsresult
 NS_NewGenConImageContent(nsIContent** aResult, already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
                          imgRequestProxy* aImageRequest)
 {
   NS_PRECONDITION(aImageRequest, "Must have request!");
   nsGenConImageContent *it = new nsGenConImageContent(aNodeInfo);
-  if (!it)
-    return NS_ERROR_OUT_OF_MEMORY;
   NS_ADDREF(*aResult = it);
   nsresult rv = it->Init(aImageRequest);
   if (NS_FAILED(rv))
     NS_RELEASE(*aResult);
   return rv;
 }
 
 nsGenConImageContent::~nsGenConImageContent()
--- a/dom/base/nsGenericDOMDataNode.cpp
+++ b/dom/base/nsGenericDOMDataNode.cpp
@@ -338,17 +338,16 @@ nsGenericDOMDataNode::SetTextInternal(ui
     NS_ENSURE_TRUE(ok, NS_ERROR_OUT_OF_MEMORY);
   }
   else {
     // Merging old and new
 
     // Allocate new buffer
     int32_t newLength = textLength - aCount + aLength;
     char16_t* to = new char16_t[newLength];
-    NS_ENSURE_TRUE(to, NS_ERROR_OUT_OF_MEMORY);
 
     // Copy over appropriate data
     if (aOffset) {
       mText.CopyTo(to, 0, aOffset);
     }
     if (aLength) {
       memcpy(to + aOffset, aBuffer, aLength * sizeof(char16_t));
     }
--- a/dom/base/nsGlobalWindowCommands.cpp
+++ b/dom/base/nsGlobalWindowCommands.cpp
@@ -983,25 +983,23 @@ nsClipboardDragDropHookCommand::GetComma
 
   RegisterWindowCommands
 
 ----------------------------------------------------------------------------*/
 
 #define NS_REGISTER_ONE_COMMAND(_cmdClass, _cmdName)                \
   {                                                                 \
     _cmdClass* theCmd = new _cmdClass();                            \
-    if (!theCmd) return NS_ERROR_OUT_OF_MEMORY;                     \
     rv = inCommandTable->RegisterCommand(_cmdName,                  \
                    static_cast<nsIControllerCommand *>(theCmd));    \
   }
 
 #define NS_REGISTER_FIRST_COMMAND(_cmdClass, _cmdName)              \
   {                                                                 \
     _cmdClass* theCmd = new _cmdClass();                            \
-    if (!theCmd) return NS_ERROR_OUT_OF_MEMORY;                     \
     rv = inCommandTable->RegisterCommand(_cmdName,                  \
                    static_cast<nsIControllerCommand *>(theCmd));
 
 #define NS_REGISTER_NEXT_COMMAND(_cmdClass, _cmdName)               \
     rv = inCommandTable->RegisterCommand(_cmdName,                  \
                    static_cast<nsIControllerCommand *>(theCmd));
 
 #define NS_REGISTER_LAST_COMMAND(_cmdClass, _cmdName)               \
--- a/dom/base/nsImageLoadingContent.cpp
+++ b/dom/base/nsImageLoadingContent.cpp
@@ -380,20 +380,16 @@ nsImageLoadingContent::AddObserver(imgIN
   // otherwise we have to create a new entry
 
   ImageObserver* observer = &mObserverList;
   while (observer->mNext) {
     observer = observer->mNext;
   }
 
   observer->mNext = new ImageObserver(aObserver);
-  if (! observer->mNext) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
   ReplayImageStatus(mCurrentRequest, aObserver);
   ReplayImageStatus(mPendingRequest, aObserver);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsImageLoadingContent::RemoveObserver(imgINotificationObserver* aObserver)
--- a/dom/base/nsNameSpaceManager.cpp
+++ b/dom/base/nsNameSpaceManager.cpp
@@ -184,17 +184,17 @@ nsresult nsNameSpaceManager::AddNameSpac
     // We've wrapped...  Can't do anything else here; just bail.
     return NS_ERROR_OUT_OF_MEMORY;
   }
   
   NS_ASSERTION(aNameSpaceID - 1 == (int32_t) mURIArray.Length(),
                "BAD! AddNameSpace not called in right order!");
 
   nsString* uri = new nsString(aURI);
-  if (!uri || !mURIArray.AppendElement(uri)) {
+  if (!mURIArray.AppendElement(uri)) {
     delete uri;
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   mURIToIDTable.Put(uri, aNameSpaceID);
 
   return NS_OK;
 }
--- a/dom/base/nsObjectLoadingContent.cpp
+++ b/dom/base/nsObjectLoadingContent.cpp
@@ -2931,19 +2931,16 @@ nsObjectLoadingContent::AsyncStartPlugin
   nsCOMPtr<nsIContent> thisContent =
     do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
   nsIDocument* doc = thisContent->OwnerDoc();
   if (doc->IsStaticDocument() || doc->IsBeingUsedAsImage()) {
     return NS_OK;
   }
 
   nsCOMPtr<nsIRunnable> event = new nsAsyncInstantiateEvent(this);
-  if (!event) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
   nsresult rv = NS_DispatchToCurrentThread(event);
   if (NS_SUCCEEDED(rv)) {
     // Track pending events
     mPendingInstantiateEvent = event;
   }
 
   return rv;
 }
--- a/dom/base/nsScriptNameSpaceManager.cpp
+++ b/dom/base/nsScriptNameSpaceManager.cpp
@@ -475,18 +475,16 @@ nsScriptNameSpaceManager::RegisterDOMCID
 
   // XXX Should we bail out here?
   NS_ASSERTION(s->mType == nsGlobalNameStruct::eTypeNotInitialized ||
                s->mType == nsGlobalNameStruct::eTypeNewDOMBinding ||
                s->mType == nsGlobalNameStruct::eTypeExternalClassInfoCreator,
                "Someone tries to register classinfo data for a class that isn't new or external!");
 
   s->mData = new nsExternalDOMClassInfoData;
-  NS_ENSURE_TRUE(s->mData, NS_ERROR_OUT_OF_MEMORY);
-
   s->mType = nsGlobalNameStruct::eTypeExternalClassInfo;
   s->mData->mName = aName;
   s->mData->mNameUTF16 = className;
   if (aConstructorFptr)
     s->mData->u.mExternalConstructorFptr = aConstructorFptr;
   else
     // null constructor will cause us to use nsDOMGenericSH::doCreate
     s->mData->u.mExternalConstructorFptr = nullptr;
--- a/dom/base/nsTextFragment.cpp
+++ b/dom/base/nsTextFragment.cpp
@@ -37,18 +37,16 @@ using mozilla::CheckedUint32;
 nsresult
 nsTextFragment::Init()
 {
   // Create whitespace strings
   uint32_t i;
   for (i = 0; i <= TEXTFRAG_MAX_NEWLINES; ++i) {
     sSpaceSharedString[i] = new char[1 + i + TEXTFRAG_WHITE_AFTER_NEWLINE];
     sTabSharedString[i] = new char[1 + i + TEXTFRAG_WHITE_AFTER_NEWLINE];
-    NS_ENSURE_TRUE(sSpaceSharedString[i] && sTabSharedString[i],
-                   NS_ERROR_OUT_OF_MEMORY);
     sSpaceSharedString[i][0] = ' ';
     sTabSharedString[i][0] = ' ';
     uint32_t j;
     for (j = 1; j < 1 + i; ++j) {
       sSpaceSharedString[i][j] = '\n';
       sTabSharedString[i][j] = '\n';
     }
     for (; j < (1 + i + TEXTFRAG_WHITE_AFTER_NEWLINE); ++j) {
--- a/dom/base/nsTextNode.cpp
+++ b/dom/base/nsTextNode.cpp
@@ -209,20 +209,16 @@ NS_NewAttributeContent(nsNodeInfoManager
   
   *aResult = nullptr;
 
   already_AddRefed<mozilla::dom::NodeInfo> ni = aNodeInfoManager->GetTextNodeInfo();
 
   nsAttributeTextNode* textNode = new nsAttributeTextNode(ni,
                                                           aNameSpaceID,
                                                           aAttrName);
-  if (!textNode) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
   NS_ADDREF(*aResult = textNode);
 
   return NS_OK;
 }
 
 NS_IMPL_ISUPPORTS_INHERITED(nsAttributeTextNode, nsTextNode,
                             nsIMutationObserver)
 
--- a/dom/bindings/BindingUtils.cpp
+++ b/dom/bindings/BindingUtils.cpp
@@ -462,16 +462,48 @@ ErrorResult::operator=(ErrorResult&& aRH
   // Note: It's important to do this last, since this affects the condition
   // checks above!
   mResult = aRHS.mResult;
   aRHS.mResult = NS_OK;
   return *this;
 }
 
 void
+ErrorResult::CloneTo(ErrorResult& aRv) const
+{
+  aRv.ClearUnionData();
+  aRv.mResult = mResult;
+#ifdef DEBUG
+  aRv.mMightHaveUnreportedJSException = mMightHaveUnreportedJSException;
+#endif
+
+  if (IsErrorWithMessage()) {
+#ifdef DEBUG
+    aRv.mUnionState = HasMessage;
+#endif
+    aRv.mMessage = new Message();
+    aRv.mMessage->mArgs = mMessage->mArgs;
+    aRv.mMessage->mErrorNumber = mMessage->mErrorNumber;
+  } else if (IsDOMException()) {
+#ifdef DEBUG
+    aRv.mUnionState = HasDOMExceptionInfo;
+#endif
+    aRv.mDOMExceptionInfo = new DOMExceptionInfo(mDOMExceptionInfo->mRv,
+                                                 mDOMExceptionInfo->mMessage);
+  } else if (IsJSException()) {
+#ifdef DEBUG
+    aRv.mUnionState = HasJSException;
+#endif
+    JSContext* cx = nsContentUtils::RootingCxForThread();
+    JS::Rooted<JS::Value> exception(cx, mJSException);
+    aRv.ThrowJSException(cx, exception);
+  }
+}
+
+void
 ErrorResult::SuppressException()
 {
   WouldReportJSException();
   ClearUnionData();
   // We don't use AssignErrorCode, because we want to override existing error
   // states, which AssignErrorCode is not allowed to do.
   mResult = NS_OK;
 }
--- a/dom/bindings/BindingUtils.h
+++ b/dom/bindings/BindingUtils.h
@@ -3280,16 +3280,23 @@ struct StrongPtrForMember
 
 inline
 JSObject*
 GetErrorPrototype(JSContext* aCx, JS::Handle<JSObject*> aForObj)
 {
   return JS_GetErrorPrototype(aCx);
 }
 
+inline
+JSObject*
+GetIteratorPrototype(JSContext* aCx, JS::Handle<JSObject*> aForObj)
+{
+  return JS_GetIteratorPrototype(aCx);
+}
+
 // Resolve an id on the given global object that wants to be included in
 // Exposed=System webidl annotations.  False return value means exception
 // thrown.
 bool SystemGlobalResolve(JSContext* cx, JS::Handle<JSObject*> obj,
                          JS::Handle<jsid> id, bool* resolvedp);
 
 // Enumerate all ids on the given global object that wants to be included in
 // Exposed=System webidl annotations.  False return value means exception
--- a/dom/bindings/Bindings.conf
+++ b/dom/bindings/Bindings.conf
@@ -404,16 +404,20 @@ DOMInterfaces = {
 'Document': {
     'nativeType': 'nsIDocument',
     'binaryNames': {
         'documentURI': 'documentURIFromJS',
         'URL': 'documentURIFromJS'
     }
 },
 
+'DominatorTree': {
+    'nativeType': 'mozilla::devtools::DominatorTree'
+},
+
 'DOMException': {
     'binaryNames': {
         'message': 'messageMoz',
     },
 },
 
 'DOMMatrixReadOnly': {
     'headerFile': 'mozilla/dom/DOMMatrix.h',
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -575,16 +575,18 @@ def InterfacePrototypeObjectProtoGetter(
     if descriptor.hasNamedPropertiesObject:
         protoGetter = "GetNamedPropertiesObject"
         protoHandleGetter = None
     elif parentProtoName is None:
         if descriptor.interface.getExtendedAttribute("ArrayClass"):
             protoGetter = "JS_GetArrayPrototype"
         elif descriptor.interface.getExtendedAttribute("ExceptionClass"):
             protoGetter = "GetErrorPrototype"
+        elif descriptor.interface.isIteratorInterface():
+            protoGetter = "GetIteratorPrototype"
         else:
             protoGetter = "JS_GetObjectPrototype"
         protoHandleGetter = None
     else:
         prefix = toBindingNamespace(parentProtoName)
         protoGetter = prefix + "::GetProtoObject"
         protoHandleGetter = prefix + "::GetProtoObjectHandle"
 
@@ -2254,16 +2256,32 @@ class MethodDefiner(PropertyDefiner):
                 "name": "@@iterator",
                 "methodInfo": False,
                 "selfHostedName": "ArrayValues",
                 "length": 0,
                 "flags": "JSPROP_ENUMERATE",
                 "condition": MemberCondition(None, None)
             })
 
+        # Output an @@iterator for generated iterator interfaces.  This should
+        # not be necessary, but
+        # https://bugzilla.mozilla.org/show_bug.cgi?id=1091945 means that
+        # %IteratorPrototype%[@@iterator] is a broken puppy.
+        if (not static and
+            not unforgeable and
+            descriptor.interface.isIteratorInterface()):
+            self.regular.append({
+                "name": "@@iterator",
+                "methodInfo": False,
+                "selfHostedName": "IteratorIdentity",
+                "length": 0,
+                "flags": "0",
+                "condition": MemberCondition(None, None)
+            })
+
         # Generate the maplike/setlike iterator, if one wasn't already
         # generated by a method. If we already have an @@iterator symbol, fail.
         if descriptor.interface.maplikeOrSetlikeOrIterable:
             if hasIterator(methods, self.regular):
                 raise TypeError("Cannot have maplike/setlike/iterable interface with "
                                 "other members that generate @@iterator "
                                 "on interface %s, such as indexed getters "
                                 "or aliased functions." %
--- a/dom/bindings/ErrorResult.h
+++ b/dom/bindings/ErrorResult.h
@@ -110,16 +110,21 @@ public:
     AssignErrorCode(aRv);
   }
 
   void Throw(nsresult rv) {
     MOZ_ASSERT(NS_FAILED(rv), "Please don't try throwing success");
     AssignErrorCode(rv);
   }
 
+  // Duplicate our current state on the given ErrorResult object.  Any existing
+  // errors or messages on the target will be suppressed before cloning.  Our
+  // own error state remains unchanged.
+  void CloneTo(ErrorResult& aRv) const;
+
   // Use SuppressException when you want to suppress any exception that might be
   // on the ErrorResult.  After this call, the ErrorResult will be back a "no
   // exception thrown" state.
   void SuppressException();
 
   // Use StealNSResult() when you want to safely convert the ErrorResult to an
   // nsresult that you will then return to a caller.  This will
   // SuppressException(), since there will no longer be a way to report it.
--- a/dom/bindings/test/test_iterable.html
+++ b/dom/bindings/test/test_iterable.html
@@ -45,27 +45,38 @@
          }
        }
 
        var itr;
        // Simple single type iterable creation and functionality test
        info("IterableSingle: Testing simple iterable creation and functionality");
        itr = new TestInterfaceIterableSingle();
        testExistence("IterableSingle: ", itr, base_properties);
+       var keys = [...itr.keys()];
+       var values = [...itr.values()];
+       var entries = [...itr.entries()];
        var key_itr = itr.keys();
        var value_itr = itr.values();
        var entries_itr = itr.entries();
        for (var i = 0; i < 3; ++i) {
          var key = key_itr.next();
          var value = value_itr.next();
          var entry = entries_itr.next();
          is(key.value, i, "IterableSingle: Key iterator value should be " + i);
+         is(key.value, keys[i],
+            "IterableSingle: Key iterator value should match destructuring " + i);
          is(value.value, key.value, "IterableSingle: Value iterator value should be " + key.value);
+         is(value.value, values[i],
+            "IterableSingle: Value iterator value should match destructuring " + i);
          is(entry.value[0], i, "IterableSingle: Entry iterator value 0 should be " + i);
          is(entry.value[1], i, "IterableSingle: Entry iterator value 1 should be " + i);
+         is(entry.value[0], entries[i][0],
+            "IterableSingle: Entry iterator value 0 should match destructuring " + i);
+         is(entry.value[1], entries[i][1],
+            "IterableSingle: Entry iterator value 1 should match destructuring " + i);
        }
        var key = key_itr.next();
        var value = value_itr.next();
        var entry = entries_itr.next();
        is(key.value, undefined, "IterableSingle: Key iterator value should be undefined");
        is(key.done, true, "IterableSingle: Key iterator done should be true");
        is(value.value, undefined, "IterableSingle: Value iterator value should be undefined");
        is(value.done, true, "IterableSingle: Value iterator done should be true");
@@ -75,27 +86,38 @@
           "[object TestInterfaceIterableSingleIteratorPrototype]",
           "iterator prototype should have the right brand");
 
        // Simple dual type iterable creation and functionality test
        info("IterableDouble: Testing simple iterable creation and functionality");
        itr = new TestInterfaceIterableDouble();
        testExistence("IterableDouble: ", itr, base_properties);
        var elements = [["a", "b"], ["c", "d"], ["e", "f"]]
+       var keys = [...itr.keys()];
+       var values = [...itr.values()];
+       var entries = [...itr.entries()];
        var key_itr = itr.keys();
        var value_itr = itr.values();
        var entries_itr = itr.entries();
        for (var i = 0; i < 3; ++i) {
          var key = key_itr.next();
          var value = value_itr.next();
          var entry = entries_itr.next();
          is(key.value, elements[i][0], "IterableDouble: Key iterator value should be " + elements[i][0]);
+         is(key.value, keys[i],
+            "IterableDouble: Key iterator value should match destructuring " + i);
          is(value.value, elements[i][1], "IterableDouble: Value iterator value should be " + elements[i][1]);
+         is(value.value, values[i],
+            "IterableDouble: Value iterator value should match destructuring " + i);
          is(entry.value[0], elements[i][0], "IterableDouble: Entry iterator value 0 should be " + elements[i][0]);
          is(entry.value[1], elements[i][1], "IterableDouble: Entry iterator value 1 should be " + elements[i][1]);
+         is(entry.value[0], entries[i][0],
+            "IterableDouble: Entry iterator value 0 should match destructuring " + i);
+         is(entry.value[1], entries[i][1],
+            "IterableDouble: Entry iterator value 1 should match destructuring " + i);
        }
        var key = key_itr.next();
        var value = value_itr.next();
        var entry = entries_itr.next()
        is(key.value, undefined, "IterableDouble: Key iterator value should be undefined");
        is(key.done, true, "IterableDouble: Key iterator done should be true");
        is(value.value, undefined, "IterableDouble: Value iterator value should be undefined");
        is(value.done, true, "IterableDouble: Value iterator done should be true");
--- a/dom/browser-element/BrowserElementChild.js
+++ b/dom/browser-element/BrowserElementChild.js
@@ -48,17 +48,17 @@ if (!('BrowserElementIsPreloaded' in thi
     if (isTopBrowserElement(docShell)) {
       Services.scriptloader.loadSubScript("chrome://global/content/BrowserElementCopyPaste.js");
     }
   } else {
     // rocketbar in system app and other in-process case (ex. B2G desktop client)
     Services.scriptloader.loadSubScript("chrome://global/content/BrowserElementCopyPaste.js");
   }
 
-  if (Services.prefs.getIntPref("dom.w3c_touch_events.enabled") == 1) {
+  if (Services.prefs.getIntPref("dom.w3c_touch_events.enabled") != 0) {
     if (docShell.asyncPanZoomEnabled === false) {
       Services.scriptloader.loadSubScript("chrome://global/content/BrowserElementPanningAPZDisabled.js");
       ContentPanningAPZDisabled.init();
     }
 
     Services.scriptloader.loadSubScript("chrome://global/content/BrowserElementPanning.js");
     ContentPanning.init();
   }
--- a/dom/devicestorage/DeviceStorageRequestParent.cpp
+++ b/dom/devicestorage/DeviceStorageRequestParent.cpp
@@ -47,18 +47,18 @@ DeviceStorageRequestParent::Dispatch()
       BlobParent* bp = static_cast<BlobParent*>(p.blobParent());
       RefPtr<BlobImpl> blobImpl = bp->GetBlobImpl();
 
       ErrorResult rv;
       nsCOMPtr<nsIInputStream> stream;
       blobImpl->GetInternalStream(getter_AddRefs(stream), rv);
       MOZ_ASSERT(!rv.Failed());
 
-      RefPtr<CancelableRunnable> r = new WriteFileEvent(this, dsf, stream,
-                                                          DEVICE_STORAGE_REQUEST_CREATE);
+      RefPtr<CancelableRunnable> r = new WriteFileEvent(this, dsf.forget(), stream,
+                                                        DEVICE_STORAGE_REQUEST_CREATE);
 
       nsCOMPtr<nsIEventTarget> target
         = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
       MOZ_ASSERT(target);
       target->Dispatch(r, NS_DISPATCH_NORMAL);
       break;
     }
 
@@ -72,79 +72,79 @@ DeviceStorageRequestParent::Dispatch()
       BlobParent* bp = static_cast<BlobParent*>(p.blobParent());
       RefPtr<BlobImpl> blobImpl = bp->GetBlobImpl();
 
       ErrorResult rv;
       nsCOMPtr<nsIInputStream> stream;
       blobImpl->GetInternalStream(getter_AddRefs(stream), rv);
       MOZ_ASSERT(!rv.Failed());
 
-      RefPtr<CancelableRunnable> r = new WriteFileEvent(this, dsf, stream,
-                                                          DEVICE_STORAGE_REQUEST_APPEND);
+      RefPtr<CancelableRunnable> r = new WriteFileEvent(this, dsf.forget(), stream,
+                                                        DEVICE_STORAGE_REQUEST_APPEND);
 
       nsCOMPtr<nsIEventTarget> target
         = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
       MOZ_ASSERT(target);
       target->Dispatch(r, NS_DISPATCH_NORMAL);
       break;
     }
 
     case DeviceStorageParams::TDeviceStorageCreateFdParams:
     {
       DeviceStorageCreateFdParams p = mParams;
 
       RefPtr<DeviceStorageFile> dsf =
         new DeviceStorageFile(p.type(), p.storageName(), p.relpath());
 
-      RefPtr<CancelableRunnable> r = new CreateFdEvent(this, dsf);
+      RefPtr<CancelableRunnable> r = new CreateFdEvent(this, dsf.forget());
 
       nsCOMPtr<nsIEventTarget> target
         = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
       MOZ_ASSERT(target);
       target->Dispatch(r, NS_DISPATCH_NORMAL);
       break;
     }
 
     case DeviceStorageParams::TDeviceStorageGetParams:
     {
       DeviceStorageGetParams p = mParams;
       RefPtr<DeviceStorageFile> dsf =
         new DeviceStorageFile(p.type(), p.storageName(),
                               p.rootDir(), p.relpath());
-      RefPtr<CancelableRunnable> r = new ReadFileEvent(this, dsf);
+      RefPtr<CancelableRunnable> r = new ReadFileEvent(this, dsf.forget());
 
       nsCOMPtr<nsIEventTarget> target
         = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
       MOZ_ASSERT(target);
       target->Dispatch(r, NS_DISPATCH_NORMAL);
       break;
     }
 
     case DeviceStorageParams::TDeviceStorageDeleteParams:
     {
       DeviceStorageDeleteParams p = mParams;
 
       RefPtr<DeviceStorageFile> dsf =
         new DeviceStorageFile(p.type(), p.storageName(), p.relpath());
-      RefPtr<CancelableRunnable> r = new DeleteFileEvent(this, dsf);
+      RefPtr<CancelableRunnable> r = new DeleteFileEvent(this, dsf.forget());
 
       nsCOMPtr<nsIEventTarget> target
         = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
       MOZ_ASSERT(target);
       target->Dispatch(r, NS_DISPATCH_NORMAL);
       break;
     }
 
     case DeviceStorageParams::TDeviceStorageFreeSpaceParams:
     {
       DeviceStorageFreeSpaceParams p = mParams;
 
       RefPtr<DeviceStorageFile> dsf =
         new DeviceStorageFile(p.type(), p.storageName());
-      RefPtr<FreeSpaceFileEvent> r = new FreeSpaceFileEvent(this, dsf);
+      RefPtr<FreeSpaceFileEvent> r = new FreeSpaceFileEvent(this, dsf.forget());
 
       nsCOMPtr<nsIEventTarget> target
         = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
       MOZ_ASSERT(target);
       target->Dispatch(r, NS_DISPATCH_NORMAL);
       break;
     }
 
@@ -153,69 +153,69 @@ DeviceStorageRequestParent::Dispatch()
       DeviceStorageUsedSpaceCache* usedSpaceCache
         = DeviceStorageUsedSpaceCache::CreateOrGet();
       MOZ_ASSERT(usedSpaceCache);
 
       DeviceStorageUsedSpaceParams p = mParams;
 
       RefPtr<DeviceStorageFile> dsf =
         new DeviceStorageFile(p.type(), p.storageName());
-      RefPtr<UsedSpaceFileEvent> r = new UsedSpaceFileEvent(this, dsf);
+      RefPtr<UsedSpaceFileEvent> r = new UsedSpaceFileEvent(this, dsf.forget());
 
       usedSpaceCache->Dispatch(r);
       break;
     }
 
     case DeviceStorageParams::TDeviceStorageFormatParams:
     {
       DeviceStorageFormatParams p = mParams;
 
       RefPtr<DeviceStorageFile> dsf =
         new DeviceStorageFile(p.type(), p.storageName());
       RefPtr<PostFormatResultEvent> r
-        = new PostFormatResultEvent(this, dsf);
+        = new PostFormatResultEvent(this, dsf.forget());
       DebugOnly<nsresult> rv = NS_DispatchToMainThread(r);
       MOZ_ASSERT(NS_SUCCEEDED(rv));
       break;
     }
 
     case DeviceStorageParams::TDeviceStorageMountParams:
     {
       DeviceStorageMountParams p = mParams;
 
       RefPtr<DeviceStorageFile> dsf =
         new DeviceStorageFile(p.type(), p.storageName());
       RefPtr<PostMountResultEvent> r
-        = new PostMountResultEvent(this, dsf);
+        = new PostMountResultEvent(this, dsf.forget());
       DebugOnly<nsresult> rv = NS_DispatchToMainThread(r);
       MOZ_ASSERT(NS_SUCCEEDED(rv));
       break;
     }
 
     case DeviceStorageParams::TDeviceStorageUnmountParams:
     {
       DeviceStorageUnmountParams p = mParams;
 
       RefPtr<DeviceStorageFile> dsf =
         new DeviceStorageFile(p.type(), p.storageName());
       RefPtr<PostUnmountResultEvent> r
-        = new PostUnmountResultEvent(this, dsf);
+        = new PostUnmountResultEvent(this, dsf.forget());
       DebugOnly<nsresult> rv = NS_DispatchToMainThread(r);
       MOZ_ASSERT(NS_SUCCEEDED(rv));
       break;
     }
 
     case DeviceStorageParams::TDeviceStorageEnumerationParams:
     {
       DeviceStorageEnumerationParams p = mParams;
       RefPtr<DeviceStorageFile> dsf
         = new DeviceStorageFile(p.type(), p.storageName(),
                                 p.rootdir(), NS_LITERAL_STRING(""));
       RefPtr<CancelableRunnable> r
-        = new EnumerateFileEvent(this, dsf, p.since());
+        = new EnumerateFileEvent(this, dsf.forget(), p.since());
 
       nsCOMPtr<nsIEventTarget> target
         = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
       MOZ_ASSERT(target);
       target->Dispatch(r, NS_DISPATCH_NORMAL);
       break;
     }
     default:
@@ -388,20 +388,25 @@ DeviceStorageRequestParent::~DeviceStora
 NS_IMPL_ADDREF(DeviceStorageRequestParent)
 NS_IMPL_RELEASE(DeviceStorageRequestParent)
 
 void
 DeviceStorageRequestParent::ActorDestroy(ActorDestroyReason)
 {
   MutexAutoLock lock(mMutex);
   mActorDestroyed = true;
-  int32_t count = mRunnables.Length();
-  for (int32_t index = 0; index < count; index++) {
-    mRunnables[index]->Cancel();
+  for (auto& runnable : mRunnables) {
+    runnable->Cancel();
   }
+  // Ensure we clear all references to the runnables so that there won't
+  // be leak due to cyclic reference. Note that it is safe to release
+  // the references here, since if a runnable is not cancelled yet, the
+  // corresponding thread should still hold a reference to it, and thus
+  // the runnable will end up being released in that thread, not here.
+  mRunnables.Clear();
 }
 
 DeviceStorageRequestParent::PostFreeSpaceResultEvent::PostFreeSpaceResultEvent(
   DeviceStorageRequestParent* aParent,
   uint64_t aFreeSpace)
   : CancelableRunnable(aParent)
   , mFreeSpace(aFreeSpace)
 {
@@ -414,89 +419,50 @@ nsresult
 DeviceStorageRequestParent::PostFreeSpaceResultEvent::CancelableRun() {
   MOZ_ASSERT(NS_IsMainThread());
 
   FreeSpaceStorageResponse response(mFreeSpace);
   Unused << mParent->Send__delete__(mParent, response);
   return NS_OK;
 }
 
-DeviceStorageRequestParent::PostUsedSpaceResultEvent::
-  PostUsedSpaceResultEvent(DeviceStorageRequestParent* aParent,
-                             const nsAString& aType,
-                             uint64_t aUsedSpace)
-  : CancelableRunnable(aParent)
-  , mType(aType)
-  , mUsedSpace(aUsedSpace)
-{
-}
-
-DeviceStorageRequestParent::PostUsedSpaceResultEvent::
-  ~PostUsedSpaceResultEvent() {}
-
 nsresult
 DeviceStorageRequestParent::PostUsedSpaceResultEvent::CancelableRun() {
   MOZ_ASSERT(NS_IsMainThread());
 
   UsedSpaceStorageResponse response(mUsedSpace);
   Unused << mParent->Send__delete__(mParent, response);
   return NS_OK;
 }
 
 DeviceStorageRequestParent::PostErrorEvent::
   PostErrorEvent(DeviceStorageRequestParent* aParent, const char* aError)
   : CancelableRunnable(aParent)
 {
   CopyASCIItoUTF16(aError, mError);
 }
 
-DeviceStorageRequestParent::PostErrorEvent::~PostErrorEvent() {}
-
 nsresult
 DeviceStorageRequestParent::PostErrorEvent::CancelableRun() {
   MOZ_ASSERT(NS_IsMainThread());
 
   ErrorResponse response(mError);
   Unused << mParent->Send__delete__(mParent, response);
   return NS_OK;
 }
 
-DeviceStorageRequestParent::PostSuccessEvent::
-  PostSuccessEvent(DeviceStorageRequestParent* aParent)
-  : CancelableRunnable(aParent)
-{
-}
-
-DeviceStorageRequestParent::PostSuccessEvent::~PostSuccessEvent() {}
-
 nsresult
 DeviceStorageRequestParent::PostSuccessEvent::CancelableRun() {
   MOZ_ASSERT(NS_IsMainThread());
 
   SuccessResponse response;
   Unused << mParent->Send__delete__(mParent, response);
   return NS_OK;
 }
 
-DeviceStorageRequestParent::PostBlobSuccessEvent::
-  PostBlobSuccessEvent(DeviceStorageRequestParent* aParent,
-                       DeviceStorageFile* aFile,
-                       uint32_t aLength,
-                       nsACString& aMimeType,
-                       uint64_t aLastModifiedDate)
-  : CancelableRunnable(aParent)
-  , mLength(aLength)
-  , mLastModificationDate(aLastModifiedDate)
-  , mFile(aFile)
-  , mMimeType(aMimeType)
-{
-}
-
-DeviceStorageRequestParent::PostBlobSuccessEvent::~PostBlobSuccessEvent() {}
-
 nsresult
 DeviceStorageRequestParent::PostBlobSuccessEvent::CancelableRun() {
   MOZ_ASSERT(NS_IsMainThread());
 
   nsString mime;
   CopyASCIItoUTF16(mMimeType, mime);
 
   nsString fullPath;
@@ -515,52 +481,25 @@ DeviceStorageRequestParent::PostBlobSucc
 
   BlobResponse response;
   response.blobParent() = actor;
 
   Unused << mParent->Send__delete__(mParent, response);
   return NS_OK;
 }
 
-DeviceStorageRequestParent::PostEnumerationSuccessEvent::
-  PostEnumerationSuccessEvent(DeviceStorageRequestParent* aParent,
-                              const nsAString& aStorageType,
-                              const nsAString& aRelPath,
-                              InfallibleTArray<DeviceStorageFileValue>& aPaths)
-  : CancelableRunnable(aParent)
-  , mStorageType(aStorageType)
-  , mRelPath(aRelPath)
-  , mPaths(aPaths)
-{
-}
-
-DeviceStorageRequestParent::PostEnumerationSuccessEvent::
-  ~PostEnumerationSuccessEvent() {}
-
 nsresult
 DeviceStorageRequestParent::PostEnumerationSuccessEvent::CancelableRun() {
   MOZ_ASSERT(NS_IsMainThread());
 
   EnumerationResponse response(mStorageType, mRelPath, mPaths);
   Unused << mParent->Send__delete__(mParent, response);
   return NS_OK;
 }
 
-DeviceStorageRequestParent::CreateFdEvent::
-  CreateFdEvent(DeviceStorageRequestParent* aParent,
-                 DeviceStorageFile* aFile)
-  : CancelableRunnable(aParent)
-  , mFile(aFile)
-{
-}
-
-DeviceStorageRequestParent::CreateFdEvent::~CreateFdEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::CreateFdEvent::CancelableRun()
 {
   MOZ_ASSERT(!NS_IsMainThread());
 
   nsCOMPtr<nsIRunnable> r;
 
   if (!mFile->mFile) {
@@ -583,32 +522,16 @@ DeviceStorageRequestParent::CreateFdEven
   }
   else {
     r = new PostFileDescriptorResultEvent(mParent, fileDescriptor);
   }
 
   return NS_DispatchToMainThread(r);
 }
 
-DeviceStorageRequestParent::WriteFileEvent::
-  WriteFileEvent(DeviceStorageRequestParent* aParent,
-                 DeviceStorageFile* aFile,
-                 nsIInputStream* aInputStream,
-                 int32_t aRequestType)
-  : CancelableRunnable(aParent)
-  , mFile(aFile)
-  , mInputStream(aInputStream)
-  , mRequestType(aRequestType)
-{
-}
-
-DeviceStorageRequestParent::WriteFileEvent::~WriteFileEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::WriteFileEvent::CancelableRun()
 {
   MOZ_ASSERT(!NS_IsMainThread());
 
   nsCOMPtr<nsIRunnable> r;
 
   if (!mInputStream || !mFile->mFile) {
@@ -642,27 +565,16 @@ DeviceStorageRequestParent::WriteFileEve
   }
   else {
     r = new PostPathResultEvent(mParent, mFile->mPath);
   }
 
   return NS_DispatchToMainThread(r);
 }
 
-DeviceStorageRequestParent::DeleteFileEvent::
-  DeleteFileEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile)
-  : CancelableRunnable(aParent)
-  , mFile(aFile)
-{
-}
-
-DeviceStorageRequestParent::DeleteFileEvent::~DeleteFileEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::DeleteFileEvent::CancelableRun()
 {
   MOZ_ASSERT(!NS_IsMainThread());
 
   mFile->Remove();
 
   nsCOMPtr<nsIRunnable> r;
@@ -678,55 +590,31 @@ DeviceStorageRequestParent::DeleteFileEv
   }
   else {
     r = new PostPathResultEvent(mParent, mFile->mPath);
   }
 
   return NS_DispatchToMainThread(r);
 }
 
-DeviceStorageRequestParent::FreeSpaceFileEvent::
-  FreeSpaceFileEvent(DeviceStorageRequestParent* aParent,
-                     DeviceStorageFile* aFile)
-  : CancelableRunnable(aParent)
-  , mFile(aFile)
-{
-}
-
-DeviceStorageRequestParent::FreeSpaceFileEvent::~FreeSpaceFileEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::FreeSpaceFileEvent::CancelableRun()
 {
   MOZ_ASSERT(!NS_IsMainThread());
 
   int64_t freeSpace = 0;
   if (mFile) {
     mFile->GetStorageFreeSpace(&freeSpace);
   }
 
   nsCOMPtr<nsIRunnable> r;
   r = new PostFreeSpaceResultEvent(mParent, static_cast<uint64_t>(freeSpace));
   return NS_DispatchToMainThread(r);
 }
 
-DeviceStorageRequestParent::UsedSpaceFileEvent::
-  UsedSpaceFileEvent(DeviceStorageRequestParent* aParent,
-                     DeviceStorageFile* aFile)
-  : CancelableRunnable(aParent)
-  , mFile(aFile)
-{
-}
-
-DeviceStorageRequestParent::UsedSpaceFileEvent::~UsedSpaceFileEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::UsedSpaceFileEvent::CancelableRun()
 {
   MOZ_ASSERT(!NS_IsMainThread());
 
   uint64_t picturesUsage = 0, videosUsage = 0, musicUsage = 0, totalUsage = 0;
   mFile->AccumDiskUsage(&picturesUsage, &videosUsage,
                         &musicUsage, &totalUsage);
@@ -742,34 +630,30 @@ DeviceStorageRequestParent::UsedSpaceFil
     r = new PostUsedSpaceResultEvent(mParent, mFile->mStorageType, musicUsage);
   } else {
     r = new PostUsedSpaceResultEvent(mParent, mFile->mStorageType, totalUsage);
   }
   return NS_DispatchToMainThread(r);
 }
 
 DeviceStorageRequestParent::ReadFileEvent::
-  ReadFileEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile)
-  : CancelableRunnable(aParent)
-  , mFile(aFile)
+  ReadFileEvent(DeviceStorageRequestParent* aParent,
+                already_AddRefed<DeviceStorageFile>&& aFile)
+  : CancelableFileEvent(aParent, Move(aFile))
 {
   nsCOMPtr<nsIMIMEService> mimeService
     = do_GetService(NS_MIMESERVICE_CONTRACTID);
   if (mimeService) {
     nsresult rv = mimeService->GetTypeFromFile(mFile->mFile, mMimeType);
     if (NS_FAILED(rv)) {
       mMimeType.Truncate();
     }
   }
 }
 
-DeviceStorageRequestParent::ReadFileEvent::~ReadFileEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::ReadFileEvent::CancelableRun()
 {
   MOZ_ASSERT(!NS_IsMainThread());
 
   nsCOMPtr<nsIRunnable> r;
 
   if (!mFile->mFile) {
@@ -793,35 +677,22 @@ DeviceStorageRequestParent::ReadFileEven
 
   PRTime modDate;
   rv = mFile->mFile->GetLastModifiedTime(&modDate);
   if (NS_FAILED(rv)) {
     r = new PostErrorEvent(mParent, POST_ERROR_EVENT_UNKNOWN);
     return NS_DispatchToMainThread(r);
   }
 
-  r = new PostBlobSuccessEvent(mParent, mFile, static_cast<uint64_t>(fileSize),
+  r = new PostBlobSuccessEvent(mParent, mFile.forget(),
+                               static_cast<uint64_t>(fileSize),
                                mMimeType, modDate);
   return NS_DispatchToMainThread(r);
 }
 
-DeviceStorageRequestParent::EnumerateFileEvent::
-  EnumerateFileEvent(DeviceStorageRequestParent* aParent,
-                     DeviceStorageFile* aFile,
-                     uint64_t aSince)
-  : CancelableRunnable(aParent)
-  , mFile(aFile)
-  , mSince(aSince)
-{
-}
-
-DeviceStorageRequestParent::EnumerateFileEvent::~EnumerateFileEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::EnumerateFileEvent::CancelableRun()
 {
   MOZ_ASSERT(!NS_IsMainThread());
 
   nsCOMPtr<nsIRunnable> r;
   if (mFile->mFile) {
     bool check = false;
@@ -843,131 +714,66 @@ DeviceStorageRequestParent::EnumerateFil
     values.AppendElement(dsvf);
   }
 
   r = new PostEnumerationSuccessEvent(mParent, mFile->mStorageType,
                                       mFile->mRootDir, values);
   return NS_DispatchToMainThread(r);
 }
 
-
-DeviceStorageRequestParent::PostPathResultEvent::
-  PostPathResultEvent(DeviceStorageRequestParent* aParent,
-                      const nsAString& aPath)
-  : CancelableRunnable(aParent)
-  , mPath(aPath)
-{
-}
-
-DeviceStorageRequestParent::PostPathResultEvent::~PostPathResultEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::PostPathResultEvent::CancelableRun()
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   SuccessResponse response;
   Unused << mParent->Send__delete__(mParent, response);
   return NS_OK;
 }
 
-DeviceStorageRequestParent::PostFileDescriptorResultEvent::
-  PostFileDescriptorResultEvent(DeviceStorageRequestParent* aParent,
-                                const FileDescriptor& aFileDescriptor)
-  : CancelableRunnable(aParent)
-  , mFileDescriptor(aFileDescriptor)
-{
-}
-
-DeviceStorageRequestParent::PostFileDescriptorResultEvent::
-  ~PostFileDescriptorResultEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::PostFileDescriptorResultEvent::CancelableRun()
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   FileDescriptorResponse response(mFileDescriptor);
   Unused << mParent->Send__delete__(mParent, response);
   return NS_OK;
 }
 
-DeviceStorageRequestParent::PostFormatResultEvent::
-  PostFormatResultEvent(DeviceStorageRequestParent* aParent,
-                           DeviceStorageFile* aFile)
-  : CancelableRunnable(aParent)
-  , mFile(aFile)
-{
-}
-
-DeviceStorageRequestParent::PostFormatResultEvent::
-  ~PostFormatResultEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::PostFormatResultEvent::CancelableRun()
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   nsString state = NS_LITERAL_STRING("unavailable");
   if (mFile) {
     mFile->DoFormat(state);
   }
 
   FormatStorageResponse response(state);
   Unused << mParent->Send__delete__(mParent, response);
   return NS_OK;
 }
 
-DeviceStorageRequestParent::PostMountResultEvent::
-  PostMountResultEvent(DeviceStorageRequestParent* aParent,
-                           DeviceStorageFile* aFile)
-  : CancelableRunnable(aParent)
-  , mFile(aFile)
-{
-}
-
-DeviceStorageRequestParent::PostMountResultEvent::
-  ~PostMountResultEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::PostMountResultEvent::CancelableRun()
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   nsString state = NS_LITERAL_STRING("unavailable");
   if (mFile) {
     mFile->DoMount(state);
   }
 
   MountStorageResponse response(state);
   Unused << mParent->Send__delete__(mParent, response);
   return NS_OK;
 }
 
-DeviceStorageRequestParent::PostUnmountResultEvent::
-  PostUnmountResultEvent(DeviceStorageRequestParent* aParent,
-                           DeviceStorageFile* aFile)
-  : CancelableRunnable(aParent)
-  , mFile(aFile)
-{
-}
-
-DeviceStorageRequestParent::PostUnmountResultEvent::
-  ~PostUnmountResultEvent()
-{
-}
-
 nsresult
 DeviceStorageRequestParent::PostUnmountResultEvent::CancelableRun()
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   nsString state = NS_LITERAL_STRING("unavailable");
   if (mFile) {
     mFile->DoUnmount(state);
--- a/dom/devicestorage/DeviceStorageRequestParent.h
+++ b/dom/devicestorage/DeviceStorageRequestParent.h
@@ -69,157 +69,188 @@ private:
     virtual nsresult CancelableRun() = 0;
 
   protected:
     RefPtr<DeviceStorageRequestParent> mParent;
   private:
     bool mCanceled;
   };
 
+  class CancelableFileEvent : public CancelableRunnable
+  {
+  protected:
+    CancelableFileEvent(DeviceStorageRequestParent* aParent,
+                        already_AddRefed<DeviceStorageFile>&& aFile)
+      : CancelableRunnable(aParent)
+      , mFile(Move(aFile)) {}
+
+    RefPtr<DeviceStorageFile> mFile;
+  };
+
   class PostErrorEvent : public CancelableRunnable
   {
     public:
       PostErrorEvent(DeviceStorageRequestParent* aParent, const char* aError);
-      virtual ~PostErrorEvent();
+      virtual ~PostErrorEvent() {}
       virtual nsresult CancelableRun();
     private:
       nsString mError;
   };
 
   class PostSuccessEvent : public CancelableRunnable
   {
     public:
-      explicit PostSuccessEvent(DeviceStorageRequestParent* aParent);
-      virtual ~PostSuccessEvent();
+      explicit PostSuccessEvent(DeviceStorageRequestParent* aParent)
+        : CancelableRunnable(aParent) {}
+      virtual ~PostSuccessEvent() {}
       virtual nsresult CancelableRun();
   };
 
-  class PostBlobSuccessEvent : public CancelableRunnable
+  class PostBlobSuccessEvent : public CancelableFileEvent
   {
     public:
-      PostBlobSuccessEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile, uint32_t aLength, nsACString& aMimeType, uint64_t aLastModifiedDate);
-      virtual ~PostBlobSuccessEvent();
+      PostBlobSuccessEvent(DeviceStorageRequestParent* aParent,
+                           already_AddRefed<DeviceStorageFile>&& aFile,
+                           uint32_t aLength, nsACString& aMimeType,
+                           uint64_t aLastModifiedDate)
+        : CancelableFileEvent(aParent, Move(aFile))
+        , mLength(aLength)
+        , mLastModificationDate(aLastModifiedDate)
+        , mMimeType(aMimeType) {}
+      virtual ~PostBlobSuccessEvent() {}
       virtual nsresult CancelableRun();
     private:
       uint32_t mLength;
       uint64_t mLastModificationDate;
-      RefPtr<DeviceStorageFile> mFile;
       nsCString mMimeType;
   };
 
   class PostEnumerationSuccessEvent : public CancelableRunnable
   {
     public:
       PostEnumerationSuccessEvent(DeviceStorageRequestParent* aParent,
                                   const nsAString& aStorageType,
                                   const nsAString& aRelPath,
-                                  InfallibleTArray<DeviceStorageFileValue>& aPaths);
-      virtual ~PostEnumerationSuccessEvent();
+                                  InfallibleTArray<DeviceStorageFileValue>& aPaths)
+        : CancelableRunnable(aParent)
+        , mStorageType(aStorageType)
+        , mRelPath(aRelPath)
+        , mPaths(aPaths) {}
+      virtual ~PostEnumerationSuccessEvent() {}
       virtual nsresult CancelableRun();
     private:
       const nsString mStorageType;
       const nsString mRelPath;
       InfallibleTArray<DeviceStorageFileValue> mPaths;
   };
 
-  class CreateFdEvent : public CancelableRunnable
+  class CreateFdEvent : public CancelableFileEvent
   {
     public:
-      CreateFdEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile);
-      virtual ~CreateFdEvent();
+      CreateFdEvent(DeviceStorageRequestParent* aParent,
+                    already_AddRefed<DeviceStorageFile>&& aFile)
+        : CancelableFileEvent(aParent, Move(aFile)) {}
+      virtual ~CreateFdEvent() {}
       virtual nsresult CancelableRun();
-    private:
-      RefPtr<DeviceStorageFile> mFile;
   };
 
-  class WriteFileEvent : public CancelableRunnable
+  class WriteFileEvent : public CancelableFileEvent
   {
     public:
-      WriteFileEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile,
-                     nsIInputStream* aInputStream, int32_t aRequestType);
-      virtual ~WriteFileEvent();
+      WriteFileEvent(DeviceStorageRequestParent* aParent,
+                     already_AddRefed<DeviceStorageFile>&& aFile,
+                     nsIInputStream* aInputStream, int32_t aRequestType)
+        : CancelableFileEvent(aParent, Move(aFile))
+        , mInputStream(aInputStream)
+        , mRequestType(aRequestType) {}
+      virtual ~WriteFileEvent() {}
       virtual nsresult CancelableRun();
     private:
-      RefPtr<DeviceStorageFile> mFile;
       nsCOMPtr<nsIInputStream> mInputStream;
       int32_t mRequestType;
   };
 
-  class DeleteFileEvent : public CancelableRunnable
+  class DeleteFileEvent : public CancelableFileEvent
   {
     public:
-      DeleteFileEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile);
-      virtual ~DeleteFileEvent();
+      DeleteFileEvent(DeviceStorageRequestParent* aParent,
+                      already_AddRefed<DeviceStorageFile>&& aFile)
+        : CancelableFileEvent(aParent, Move(aFile)) {}
+      virtual ~DeleteFileEvent() {}
       virtual nsresult CancelableRun();
-    private:
-      RefPtr<DeviceStorageFile> mFile;
   };
 
-  class FreeSpaceFileEvent : public CancelableRunnable
+  class FreeSpaceFileEvent : public CancelableFileEvent
   {
     public:
-      FreeSpaceFileEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile);
-      virtual ~FreeSpaceFileEvent();
+      FreeSpaceFileEvent(DeviceStorageRequestParent* aParent,
+                         already_AddRefed<DeviceStorageFile>&& aFile)
+        : CancelableFileEvent(aParent, Move(aFile)) {}
+      virtual ~FreeSpaceFileEvent() {}
       virtual nsresult CancelableRun();
-     private:
-       RefPtr<DeviceStorageFile> mFile;
   };
 
-  class UsedSpaceFileEvent : public CancelableRunnable
+  class UsedSpaceFileEvent : public CancelableFileEvent
   {
     public:
-      UsedSpaceFileEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile);
-      virtual ~UsedSpaceFileEvent();
+      UsedSpaceFileEvent(DeviceStorageRequestParent* aParent,
+                         already_AddRefed<DeviceStorageFile>&& aFile)
+        : CancelableFileEvent(aParent, Move(aFile)) {}
+      virtual ~UsedSpaceFileEvent() {}
       virtual nsresult CancelableRun();
-     private:
-       RefPtr<DeviceStorageFile> mFile;
   };
 
-  class ReadFileEvent : public CancelableRunnable
+  class ReadFileEvent : public CancelableFileEvent
   {
     public:
-      ReadFileEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile);
-      virtual ~ReadFileEvent();
+      ReadFileEvent(DeviceStorageRequestParent* aParent,
+                    already_AddRefed<DeviceStorageFile>&& aFile);
+      virtual ~ReadFileEvent() {}
       virtual nsresult CancelableRun();
     private:
-      RefPtr<DeviceStorageFile> mFile;
       nsCString mMimeType;
   };
 
-  class EnumerateFileEvent : public CancelableRunnable
+  class EnumerateFileEvent : public CancelableFileEvent
   {
     public:
-      EnumerateFileEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile, uint64_t aSince);
-      virtual ~EnumerateFileEvent();
+      EnumerateFileEvent(DeviceStorageRequestParent* aParent,
+                         already_AddRefed<DeviceStorageFile>&& aFile,
+                         uint64_t aSince)
+        : CancelableFileEvent(aParent, Move(aFile))
+        , mSince(aSince) {}
+      virtual ~EnumerateFileEvent() {}
       virtual nsresult CancelableRun();
     private:
-      RefPtr<DeviceStorageFile> mFile;
       uint64_t mSince;
   };
 
   class PostPathResultEvent : public CancelableRunnable
   {
     public:
-      PostPathResultEvent(DeviceStorageRequestParent* aParent, const nsAString& aPath);
-      virtual ~PostPathResultEvent();
+      PostPathResultEvent(DeviceStorageRequestParent* aParent,
+                          const nsAString& aPath)
+        : CancelableRunnable(aParent)
+        , mPath(aPath) {}
+      virtual ~PostPathResultEvent() {}
       virtual nsresult CancelableRun();
     private:
-      RefPtr<DeviceStorageFile> mFile;
       nsString mPath;
   };
 
   class PostFileDescriptorResultEvent : public CancelableRunnable
   {
     public:
       PostFileDescriptorResultEvent(DeviceStorageRequestParent* aParent,
-                                    const FileDescriptor& aFileDescriptor);
-      virtual ~PostFileDescriptorResultEvent();
+                                    const FileDescriptor& aFileDescriptor)
+        : CancelableRunnable(aParent)
+        , mFileDescriptor(aFileDescriptor) {}
+      virtual ~PostFileDescriptorResultEvent() {}
       virtual nsresult CancelableRun();
     private:
-      RefPtr<DeviceStorageFile> mFile;
       FileDescriptor mFileDescriptor;
   };
 
  class PostFreeSpaceResultEvent : public CancelableRunnable
  {
     public:
       PostFreeSpaceResultEvent(DeviceStorageRequestParent* aParent,
                                uint64_t aFreeSpace);
@@ -229,52 +260,55 @@ private:
       uint64_t mFreeSpace;
  };
 
  class PostUsedSpaceResultEvent : public CancelableRunnable
  {
     public:
       PostUsedSpaceResultEvent(DeviceStorageRequestParent* aParent,
                                const nsAString& aType,
-                               uint64_t aUsedSpace);
-      virtual ~PostUsedSpaceResultEvent();
+                               uint64_t aUsedSpace)
+        : CancelableRunnable(aParent)
+        , mType(aType)
+        , mUsedSpace(aUsedSpace) {}
+      virtual ~PostUsedSpaceResultEvent() {}
       virtual nsresult CancelableRun();
     private:
       nsString mType;
       uint64_t mUsedSpace;
  };
 
- class PostFormatResultEvent : public CancelableRunnable
+ class PostFormatResultEvent : public CancelableFileEvent
  {
     public:
-      PostFormatResultEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile);
-      virtual ~PostFormatResultEvent();
+      PostFormatResultEvent(DeviceStorageRequestParent* aParent,
+                            already_AddRefed<DeviceStorageFile>&& aFile)
+        : CancelableFileEvent(aParent, Move(aFile)) {}
+      virtual ~PostFormatResultEvent() {}
       virtual nsresult CancelableRun();
-    private:
-      RefPtr<DeviceStorageFile> mFile;
  };
 
- class PostMountResultEvent : public CancelableRunnable
+ class PostMountResultEvent : public CancelableFileEvent
  {
     public:
-      PostMountResultEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile);
-      virtual ~PostMountResultEvent();
+      PostMountResultEvent(DeviceStorageRequestParent* aParent,
+                           already_AddRefed<DeviceStorageFile>&& aFile)
+        : CancelableFileEvent(aParent, Move(aFile)) {}
+      virtual ~PostMountResultEvent() {}
       virtual nsresult CancelableRun();
-    private:
-      RefPtr<DeviceStorageFile> mFile;
  };
 
- class PostUnmountResultEvent : public CancelableRunnable
+ class PostUnmountResultEvent : public CancelableFileEvent
  {
     public:
-      PostUnmountResultEvent(DeviceStorageRequestParent* aParent, DeviceStorageFile* aFile);
-      virtual ~PostUnmountResultEvent();
+      PostUnmountResultEvent(DeviceStorageRequestParent* aParent,
+                             already_AddRefed<DeviceStorageFile>&& aFile)
+        : CancelableFileEvent(aParent, Move(aFile)) {}
+      virtual ~PostUnmountResultEvent() {}
       virtual nsresult CancelableRun();
-    private:
-      RefPtr<DeviceStorageFile> mFile;
  };
 
 protected:
   bool AddRunnable(CancelableRunnable* aRunnable) {
     MutexAutoLock lock(mMutex);
     if (mActorDestroyed)
       return false;
 
--- a/dom/events/EventDispatcher.cpp
+++ b/dom/events/EventDispatcher.cpp
@@ -637,19 +637,20 @@ EventDispatcher::Dispatch(nsISupports* a
           }
         }
         break;
       }
     }
     if (NS_SUCCEEDED(rv)) {
       if (aTargets) {
         aTargets->Clear();
-        aTargets->SetCapacity(chain.Length());
-        for (uint32_t i = 0; i < chain.Length(); ++i) {
-          aTargets->AppendElement(chain[i].CurrentTarget()->GetTargetForDOMEvent());
+        uint32_t numTargets = chain.Length();
+        EventTarget** targets = aTargets->AppendElements(numTargets);
+        for (uint32_t i = 0; i < numTargets; ++i) {
+          targets[i] = chain[i].CurrentTarget()->GetTargetForDOMEvent();
         }
       } else {
         // Event target chain is created. Handle the chain.
         EventChainPostVisitor postVisitor(preVisitor);
         EventTargetChainItem::HandleEventTargetChain(chain, postVisitor,
                                                      aCallback, cd);
 
         preVisitor.mEventStatus = postVisitor.mEventStatus;
--- a/dom/events/TouchEvent.cpp
+++ b/dom/events/TouchEvent.cpp
@@ -176,17 +176,20 @@ TouchEvent::ChangedTouches()
 // static
 bool
 TouchEvent::PrefEnabled(JSContext* aCx, JSObject* aGlobal)
 {
   bool prefValue = false;
   int32_t flag = 0;
   if (NS_SUCCEEDED(Preferences::GetInt("dom.w3c_touch_events.enabled", &flag))) {
     if (flag == 2) {
-#if defined(XP_WIN) || MOZ_WIDGET_GTK == 3
+#if defined(MOZ_B2G) || defined(MOZ_WIDGET_ANDROID)
+      // Touch support is always enabled on B2G and android.
+      prefValue = true;
+#elif defined(XP_WIN) || MOZ_WIDGET_GTK == 3
       static bool sDidCheckTouchDeviceSupport = false;
       static bool sIsTouchDeviceSupportPresent = false;
       // On Windows and GTK3 we auto-detect based on device support.
       if (!sDidCheckTouchDeviceSupport) {
         sDidCheckTouchDeviceSupport = true;
         sIsTouchDeviceSupportPresent = WidgetUtils::IsTouchDeviceSupportPresent();
       }
       prefValue = sIsTouchDeviceSupportPresent;
--- a/dom/html/HTMLMediaElement.cpp
+++ b/dom/html/HTMLMediaElement.cpp
@@ -3464,16 +3464,19 @@ void HTMLMediaElement::FirstFrameLoaded(
       mPreloadAction == HTMLMediaElement::PRELOAD_METADATA) {
     mSuspendedAfterFirstFrame = true;
     mDecoder->Suspend();
   }
 }
 
 void HTMLMediaElement::NetworkError()
 {
+  if (mDecoder) {
+    ShutdownDecoder();
+  }
   Error(nsIDOMMediaError::MEDIA_ERR_NETWORK);
 }
 
 void HTMLMediaElement::DecodeError()
 {
   nsAutoString src;
   GetCurrentSrc(src);
   const char16_t* params[] = { src.get() };
--- a/dom/html/nsFormSubmission.cpp
+++ b/dom/html/nsFormSubmission.cpp
@@ -843,12 +843,11 @@ GetSubmissionFromForm(nsGenericHTMLEleme
       }
       const char16_t* enctypeStrPtr = enctypeStr.get();
       SendJSWarning(doc, "ForgotPostWarning",
                     &enctypeStrPtr, 1);
     }
     *aFormSubmission = new nsFSURLEncoded(charset, method, doc,
                                           aOriginatingElement);
   }
-  NS_ENSURE_TRUE(*aFormSubmission, NS_ERROR_OUT_OF_MEMORY);
 
   return NS_OK;
 }
--- a/dom/ipc/preload.js
+++ b/dom/ipc/preload.js
@@ -87,17 +87,17 @@ var DoPreloadPostfork = function(aCallba
 
   try {
     if (Services.prefs.getBoolPref("dom.mozInputMethod.enabled")) {
       Services.scriptloader.loadSubScript("chrome://global/content/forms.js", global);
     }
   } catch (e) {
   }
 
-  if (Services.prefs.getIntPref("dom.w3c_touch_events.enabled") == 1) {
+  if (Services.prefs.getIntPref("dom.w3c_touch_events.enabled") != 0) {
     try {
       if (Services.prefs.getBoolPref("layers.async-pan-zoom.enabled") === false) {
         Services.scriptloader.loadSubScript("chrome://global/content/BrowserElementPanningAPZDisabled.js", global);
       }
     } catch (e) {
     }
 
     Services.scriptloader.loadSubScript("chrome://global/content/BrowserElementPanning.js", global);
--- a/dom/ipc/tests/test_bug1086684.html
+++ b/dom/ipc/tests/test_bug1086684.html
@@ -16,17 +16,17 @@
 
     const childFrameURL =
       "http://mochi.test:8888/tests/dom/ipc/tests/file_bug1086684.html";
 
     function childFrameScript() {
       "use strict";
 
       let { MockFilePicker } =
-        Components.utils.import("resource://specialpowers/MockFilePicker.jsm", {});
+        Components.utils.import("chrome://specialpowers/content/MockFilePicker.jsm", {});
 
       function parentReady(message) {
         MockFilePicker.init(content);
         MockFilePicker.returnFiles = [message.data.file];
         MockFilePicker.returnValue = MockFilePicker.returnOK;
 
         let input = content.document.getElementById("f");
         input.addEventListener("change", () => {
--- a/dom/json/nsJSON.cpp
+++ b/dom/json/nsJSON.cpp
@@ -293,18 +293,16 @@ nsresult
 nsJSONWriter::Write(const char16_t *aBuffer, uint32_t aLength)
 {
   if (mStream) {
     return WriteToStream(mStream, mEncoder, aBuffer, aLength);
   }
 
   if (!mDidWrite) {
     mBuffer = new char16_t[JSON_STREAM_BUFSIZE];
-    if (!mBuffer)
-      return NS_ERROR_OUT_OF_MEMORY;
     mDidWrite = true;
   }
 
   if (JSON_STREAM_BUFSIZE <= aLength + mBufferCount) {
     mOutputString.Append(mBuffer, mBufferCount);
     mBufferCount = 0;
   }
 
@@ -476,19 +474,16 @@ nsJSON::DecodeInternal(JSContext* cx,
 
   return NS_OK;
 }
 
 nsresult
 NS_NewJSON(nsISupports* aOuter, REFNSIID aIID, void** aResult)
 {
   nsJSON* json = new nsJSON();
-  if (!json)
-    return NS_ERROR_OUT_OF_MEMORY;
-
   NS_ADDREF(json);
   *aResult = json;
 
   return NS_OK;
 }
 
 nsJSONListener::nsJSONListener(JSContext *cx, JS::Value *rootVal,
                                bool needsConverter)
--- a/dom/jsurl/nsJSProtocolHandler.cpp
+++ b/dom/jsurl/nsJSProtocolHandler.cpp
@@ -405,18 +405,16 @@ nsresult nsJSChannel::Init(nsIURI *aURI)
 {
     RefPtr<nsJSURI> jsURI;
     nsresult rv = aURI->QueryInterface(kJSURICID,
                                        getter_AddRefs(jsURI));
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Create the nsIStreamIO layer used by the nsIStreamIOChannel.
     mIOThunk = new nsJSThunk();
-    if (!mIOThunk)
-        return NS_ERROR_OUT_OF_MEMORY;
 
     // Create a stock input stream channel...
     // Remember, until AsyncOpen is called, the script will not be evaluated
     // and the underlying Input Stream will not be created...
     nsCOMPtr<nsIChannel> channel;
 
     nsCOMPtr<nsIPrincipal> nullPrincipal = nsNullPrincipal::Create();
     NS_ENSURE_TRUE(nullPrincipal, NS_ERROR_FAILURE);
@@ -1124,18 +1122,16 @@ NS_IMPL_ISUPPORTS(nsJSProtocolHandler, n
 
 nsresult
 nsJSProtocolHandler::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
 {
     if (aOuter)
         return NS_ERROR_NO_AGGREGATION;
 
     nsJSProtocolHandler* ph = new nsJSProtocolHandler();
-    if (!ph)
-        return NS_ERROR_OUT_OF_MEMORY;
     NS_ADDREF(ph);
     nsresult rv = ph->Init();
     if (NS_SUCCEEDED(rv)) {
         rv = ph->QueryInterface(aIID, aResult);
     }
     NS_RELEASE(ph);
     return rv;
 }
--- a/dom/media/DecoderTraits.cpp
+++ b/dom/media/DecoderTraits.cpp
@@ -51,20 +51,16 @@
 #endif
 #include "RtspOmxDecoder.h"
 #include "RtspOmxReader.h"
 #endif
 #ifdef MOZ_DIRECTSHOW
 #include "DirectShowDecoder.h"
 #include "DirectShowReader.h"
 #endif
-#ifdef MOZ_APPLEMEDIA
-#include "AppleDecoder.h"
-#include "AppleMP3Reader.h"
-#endif
 #ifdef MOZ_FMP4
 #include "MP4Decoder.h"
 #include "MP4Demuxer.h"
 #endif
 #include "MediaFormatReader.h"
 
 #include "MP3Decoder.h"
 #include "MP3Demuxer.h"
@@ -365,48 +361,16 @@ IsMP3SupportedType(const nsACString& aTy
                    const nsAString& aCodecs = EmptyString())
 {
 #ifdef MOZ_OMX_DECODER
   return false;
 #endif
   return MP3Decoder::CanHandleMediaType(aType, aCodecs);
 }
 
-#ifdef MOZ_APPLEMEDIA
-static const char * const gAppleMP3Types[] = {
-  "audio/mp3",
-  "audio/mpeg",
-  nullptr,
-};
-
-static const char * const gAppleMP3Codecs[] = {
-  "mp3",
-  nullptr
-};
-
-static bool
-IsAppleMediaSupportedType(const nsACString& aType,
-                     const char * const ** aCodecs = nullptr)
-{
-  if (MediaDecoder::IsAppleMP3Enabled()
-      && CodecListContains(gAppleMP3Types, aType)) {
-
-    if (aCodecs) {
-      *aCodecs = gAppleMP3Codecs;
-    }
-
-    return true;
-  }
-
-  // TODO MP4
-
-  return false;
-}
-#endif
-
 /* static */
 bool DecoderTraits::ShouldHandleMediaType(const char* aMIMEType)
 {
 #ifdef MOZ_WAVE
   if (IsWaveType(nsDependentCString(aMIMEType))) {
     // We should not return true for Wave types, since there are some
     // Wave codecs actually in use in the wild that we don't support, and
     // we should allow those to be handled by plugins or helper apps.
@@ -468,19 +432,16 @@ DecoderTraits::CanHandleCodecsType(const
     } else {
       codecList = gH264Codecs;
     }
   }
 #endif
 #ifdef MOZ_DIRECTSHOW
   DirectShowDecoder::GetSupportedCodecs(nsDependentCString(aMIMEType), &codecList);
 #endif
-#ifdef MOZ_APPLEMEDIA
-  IsAppleMediaSupportedType(nsDependentCString(aMIMEType), &codecList);
-#endif
 #ifdef MOZ_ANDROID_OMX
   if (MediaDecoder::IsAndroidMediaEnabled()) {
     EnsureAndroidMediaPluginHost()->FindDecoder(nsDependentCString(aMIMEType), &codecList);
   }
 #endif
   if (!codecList) {
     return CANPLAY_MAYBE;
   }
@@ -555,21 +516,16 @@ DecoderTraits::CanHandleMediaType(const 
     return CANPLAY_MAYBE;
   }
 #endif
 #ifdef MOZ_DIRECTSHOW
   if (DirectShowDecoder::GetSupportedCodecs(nsDependentCString(aMIMEType), nullptr)) {
     return CANPLAY_MAYBE;
   }
 #endif
-#ifdef MOZ_APPLEMEDIA
-  if (IsAppleMediaSupportedType(nsDependentCString(aMIMEType), nullptr)) {
-    return CANPLAY_MAYBE;
-  }
-#endif
 #ifdef MOZ_ANDROID_OMX
   if (MediaDecoder::IsAndroidMediaEnabled() &&
       EnsureAndroidMediaPluginHost()->FindDecoder(nsDependentCString(aMIMEType), nullptr)) {
     return CANPLAY_MAYBE;
   }
 #endif
 #ifdef NECKO_PROTOCOL_rtsp
   if (IsRtspSupportedType(nsDependentCString(aMIMEType))) {
@@ -672,22 +628,16 @@ InstantiateDecoder(const nsACString& aTy
 #ifdef MOZ_DIRECTSHOW
   // Note: DirectShow should come before WMF, so that we prefer DirectShow's
   // MP3 support over WMF's.
   if (IsDirectShowSupportedType(aType)) {
     decoder = new DirectShowDecoder(aOwner);
     return decoder.forget();
   }
 #endif
-#ifdef MOZ_APPLEMEDIA
-  if (IsAppleMediaSupportedType(aType)) {
-    decoder = new AppleDecoder(aOwner);
-    return decoder.forget();
-  }
-#endif
 
   return nullptr;
 }
 
 /* static */
 already_AddRefed<MediaDecoder>
 DecoderTraits::CreateDecoder(const nsACString& aType, MediaDecoderOwner* aOwner)
 {
@@ -752,21 +702,16 @@ MediaDecoderReader* DecoderTraits::Creat
       static_cast<MediaDecoderReader*>(new MediaFormatReader(aDecoder, new WebMDemuxer(aDecoder->GetResource()))) :
       new WebMReader(aDecoder);
   } else
 #ifdef MOZ_DIRECTSHOW
   if (IsDirectShowSupportedType(aType)) {
     decoderReader = new DirectShowReader(aDecoder);
   } else
 #endif
-#ifdef MOZ_APPLEMEDIA
-  if (IsAppleMediaSupportedType(aType)) {
-    decoderReader = new AppleMP3Reader(aDecoder);
-  } else
-#endif
   if (false) {} // dummy if to take care of the dangling else
 
   return decoderReader;
 }
 
 /* static */
 bool DecoderTraits::IsSupportedInVideoDocument(const nsACString& aType)
 {
@@ -796,18 +741,15 @@ bool DecoderTraits::IsSupportedInVideoDo
 #endif
 #ifdef MOZ_FMP4
     IsMP4SupportedType(aType) ||
 #endif
     IsMP3SupportedType(aType) ||
 #ifdef MOZ_DIRECTSHOW
     IsDirectShowSupportedType(aType) ||
 #endif
-#ifdef MOZ_APPLEMEDIA
-    IsAppleMediaSupportedType(aType) ||
-#endif
 #ifdef NECKO_PROTOCOL_rtsp
     IsRtspSupportedType(aType) ||
 #endif
     false;
 }
 
 } // namespace mozilla
--- a/dom/media/MediaCache.cpp
+++ b/dom/media/MediaCache.cpp
@@ -635,19 +635,16 @@ MediaCache::MaybeShutdown()
 
 static void
 InitMediaCache()
 {
   if (gMediaCache)
     return;
 
   gMediaCache = new MediaCache();
-  if (!gMediaCache)
-    return;
-
   nsresult rv = gMediaCache->Init();
   if (NS_FAILED(rv)) {
     delete gMediaCache;
     gMediaCache = nullptr;
   }
 }
 
 nsresult
--- a/dom/media/MediaDecoder.cpp
+++ b/dom/media/MediaDecoder.cpp
@@ -1617,24 +1617,16 @@ MediaDecoder::IsOmxAsyncEnabled()
 #ifdef MOZ_ANDROID_OMX
 bool
 MediaDecoder::IsAndroidMediaEnabled()
 {
   return Preferences::GetBool("media.plugins.enabled");
 }
 #endif
 
-#ifdef MOZ_APPLEMEDIA
-bool
-MediaDecoder::IsAppleMP3Enabled()
-{
-  return Preferences::GetBool("media.apple.mp3.enabled");
-}
-#endif
-
 NS_IMETHODIMP
 MediaMemoryTracker::CollectReports(nsIHandleReportCallback* aHandleReport,
                                    nsISupports* aData, bool aAnonymize)
 {
   int64_t video = 0, audio = 0;
 
   // NB: When resourceSizes' ref count goes to 0 the promise will report the
   //     resources memory and finish the asynchronous memory report.
--- a/dom/media/MediaDecoder.h
+++ b/dom/media/MediaDecoder.h
@@ -717,20 +717,16 @@ private:
 #ifdef MOZ_ANDROID_OMX
   static bool IsAndroidMediaEnabled();
 #endif
 
 #ifdef MOZ_WMF
   static bool IsWMFEnabled();
 #endif
 
-#ifdef MOZ_APPLEMEDIA
-  static bool IsAppleMP3Enabled();
-#endif
-
   // Return statistics. This is used for progress events and other things.
   // This can be called from any thread. It's only a snapshot of the
   // current state, since other threads might be changing the state
   // at any time.
   MediaStatistics GetStatistics();
 
   // Return the frame decode/paint related statistics.
   FrameStatistics& GetFrameStatistics() { return mFrameStats; }
--- a/dom/media/MediaManager.cpp
+++ b/dom/media/MediaManager.cpp
@@ -1473,17 +1473,16 @@ MediaManager::EnumerateRawDevices(uint64
       return NS_OK;
           })));
   }));
   return p.forget();
 }
 
 MediaManager::MediaManager()
   : mMediaThread(nullptr)
-  , mMutex("mozilla::MediaManager")
   , mBackend(nullptr) {
   mPrefs.mFreq   = 1000; // 1KHz test tone
   mPrefs.mWidth  = 0; // adaptive default
   mPrefs.mHeight = 0; // adaptive default
   mPrefs.mFPS    = MediaEngine::DEFAULT_VIDEO_FPS;
   mPrefs.mMinFPS = MediaEngine::DEFAULT_VIDEO_MIN_FPS;
   nsresult rv;
   nsCOMPtr<nsIPrefService> prefs = do_GetService("@mozilla.org/preferences-service;1", &rv);
@@ -2395,20 +2394,20 @@ MediaManager::GetUserMediaDevices(nsPIDO
     }
   }
   return NS_ERROR_UNEXPECTED;
 }
 
 MediaEngine*
 MediaManager::GetBackend(uint64_t aWindowId)
 {
+  MOZ_ASSERT(MediaManager::IsInMediaThread());
   // Plugin backends as appropriate. The default engine also currently
   // includes picture support for Android.
   // This IS called off main-thread.
-  MutexAutoLock lock(mMutex);
   if (!mBackend) {
     MOZ_RELEASE_ASSERT(!sInShutdown);  // we should never create a new backend in shutdown
 #if defined(MOZ_WEBRTC)
     mBackend = new MediaEngineWebRTC(mPrefs);
 #else
     mBackend = new MediaEngineDefault();
 #endif
   }
@@ -2595,69 +2594,63 @@ MediaManager::Shutdown()
     prefs->RemoveObserver("media.navigator.video.default_minfps", this);
     prefs->RemoveObserver("media.navigator.audio.fake_frequency", this);
   }
 
   // Close off any remaining active windows.
   GetActiveWindows()->Clear();
   mActiveCallbacks.Clear();
   mCallIds.Clear();
-  {
-    MutexAutoLock lock(mMutex);
-    if (mBackend) {
-      mBackend->Shutdown(); // ok to invoke multiple times
-    }
-  }
 
   // Because mMediaThread is not an nsThread, we must dispatch to it so it can
   // clean up BackgroundChild. Continue stopping thread once this is done.
 
   class ShutdownTask : public Task
   {
   public:
-    ShutdownTask(already_AddRefed<MediaEngine> aBackend,
+    ShutdownTask(MediaManager* aManager,
                  nsRunnable* aReply)
-      : mReply(aReply)
-      , mBackend(aBackend) {}
+      : mManager(aManager)
+      , mReply(aReply) {}
   private:
     virtual void
     Run()
     {
       LOG(("MediaManager Thread Shutdown"));
       MOZ_ASSERT(MediaManager::IsInMediaThread());
+      // Must shutdown backend on MediaManager thread, since that's where we started it from!
+      {
+        if (mManager->mBackend) {
+          mManager->mBackend->Shutdown(); // ok to invoke multiple times
+        }
+      }
       mozilla::ipc::BackgroundChild::CloseForCurrentThread();
       // must explicitly do this before dispatching the reply, since the reply may kill us with Stop()
-      mBackend = nullptr; // last reference, will invoke Shutdown() again
+      mManager->mBackend = nullptr; // last reference, will invoke Shutdown() again
 
       if (NS_FAILED(NS_DispatchToMainThread(mReply.forget()))) {
         LOG(("Will leak thread: DispatchToMainthread of reply runnable failed in MediaManager shutdown"));
       }
     }
+    RefPtr<MediaManager> mManager;
     RefPtr<nsRunnable> mReply;
-    RefPtr<MediaEngine> mBackend;
   };
 
   // Post ShutdownTask to execute on mMediaThread and pass in a lambda
   // callback to be executed back on this thread once it is done.
   //
   // The lambda callback "captures" the 'this' pointer for member access.
   // This is safe since this is guaranteed to be here since sSingleton isn't
   // cleared until the lambda function clears it.
 
   // note that this == sSingleton
   RefPtr<MediaManager> that(sSingleton);
   // Release the backend (and call Shutdown()) from within the MediaManager thread
-  RefPtr<MediaEngine> temp;
-  {
-    MutexAutoLock lock(mMutex);
-    temp = mBackend.forget();
-  }
   // Don't use MediaManager::PostTask() because we're sInShutdown=true here!
-  mMediaThread->message_loop()->PostTask(FROM_HERE, new ShutdownTask(
-      temp.forget(),
+  mMediaThread->message_loop()->PostTask(FROM_HERE, new ShutdownTask(this,
       media::NewRunnableFrom([this, that]() mutable {
     LOG(("MediaManager shutdown lambda running, releasing MediaManager singleton and thread"));
     if (mMediaThread) {
       mMediaThread->Stop();
     }
 
     // Remove async shutdown blocker
 
--- a/dom/media/MediaManager.h
+++ b/dom/media/MediaManager.h
@@ -528,18 +528,17 @@ private:
   WindowTable mActiveWindows;
   nsClassHashtable<nsStringHashKey, GetUserMediaTask> mActiveCallbacks;
   nsClassHashtable<nsUint64HashKey, nsTArray<nsString>> mCallIds;
 
   // Always exists
   nsAutoPtr<base::Thread> mMediaThread;
   nsCOMPtr<nsIAsyncShutdownBlocker> mShutdownBlocker;
 
-  Mutex mMutex;
-  // protected with mMutex:
+  // ONLY accessed from MediaManagerThread
   RefPtr<MediaEngine> mBackend;
 
   static StaticRefPtr<MediaManager> sSingleton;
 
   media::CoatCheck<PledgeSourceSet> mOutstandingPledges;
   media::CoatCheck<PledgeChar> mOutstandingCharPledges;
   media::CoatCheck<GetUserMediaCallbackMediaStreamListener::PledgeVoid> mOutstandingVoidPledges;
 #if defined(MOZ_B2G_CAMERA) && defined(MOZ_WIDGET_GONK)
--- a/dom/media/MediaResource.cpp
+++ b/dom/media/MediaResource.cpp
@@ -544,18 +544,16 @@ nsresult ChannelMediaResource::OpenChann
       int64_t cl = -1;
       if (NS_SUCCEEDED(hc->GetContentLength(&cl)) && cl != -1) {
         mCacheStream.NotifyDataLength(cl);
       }
     }
   }
 
   mListener = new Listener(this);
-  NS_ENSURE_TRUE(mListener, NS_ERROR_OUT_OF_MEMORY);
-
   if (aStreamListener) {
     *aStreamListener = mListener;
     NS_ADDREF(*aStreamListener);
   } else {
     nsresult rv = mChannel->SetNotificationCallbacks(mListener.get());
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = SetupChannelHeaders();
deleted file mode 100644
--- a/dom/media/apple/AppleDecoder.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "AppleDecoder.h"
-#include "AppleMP3Reader.h"
-
-#include "MediaDecoderStateMachine.h"
-
-namespace mozilla {
-
-AppleDecoder::AppleDecoder(MediaDecoderOwner* aOwner)
-  : MediaDecoder(aOwner)
-{
-}
-
-MediaDecoder *
-AppleDecoder::Clone(MediaDecoderOwner* aOwner)
-{
-  return new AppleDecoder(aOwner);
-}
-
-MediaDecoderStateMachine *
-AppleDecoder::CreateStateMachine()
-{
-  // TODO MP4
-  return new MediaDecoderStateMachine(this, new AppleMP3Reader(this));
-}
-
-} // namespace mozilla
deleted file mode 100644
--- a/dom/media/apple/AppleDecoder.h
+++ /dev/null
@@ -1,24 +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/. */
-
-#ifndef __AppleDecoder_h__
-#define __AppleDecoder_h__
-
-#include "MediaDecoder.h"
-
-namespace mozilla {
-
-class AppleDecoder : public MediaDecoder
-{
-public:
-  explicit AppleDecoder(MediaDecoderOwner* aOwner);
-
-  virtual MediaDecoder* Clone(MediaDecoderOwner* aOwner) override;
-  virtual MediaDecoderStateMachine* CreateStateMachine() override;
-
-};
-
-} // namespace mozilla
-
-#endif // __AppleDecoder_h__
deleted file mode 100644
--- a/dom/media/apple/AppleMP3Reader.cpp
+++ /dev/null
@@ -1,543 +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 "AppleMP3Reader.h"
-
-#include "nsISeekableStream.h"
-#include "MediaDecoder.h"
-
-// Number of bytes we will read and pass to the audio parser in each
-// |DecodeAudioData| call.
-#define AUDIO_READ_BYTES 4096
-
-// Maximum number of audio frames we will accept from the audio decoder in one
-// go.  Carefully select this to work well with both the mp3 1152 max frames
-// per block and power-of-2 allocation sizes.  Since we must pre-allocate the
-// buffer we cannot use AudioCompactor without paying for an additional
-// allocation and copy.  Therefore, choosing a value that divides exactly into
-// 1152 is most memory efficient.
-#define MAX_AUDIO_FRAMES 128
-
-using namespace mozilla::media;
-
-namespace mozilla {
-
-extern LazyLogModule gMediaDecoderLog;
-#define LOGE(...) MOZ_LOG(gMediaDecoderLog, mozilla::LogLevel::Error, (__VA_ARGS__))
-#define LOGW(...) MOZ_LOG(gMediaDecoderLog, mozilla::LogLevel::Warning, (__VA_ARGS__))
-#define LOGD(...) MOZ_LOG(gMediaDecoderLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
-
-#define PROPERTY_ID_FORMAT "%c%c%c%c"
-#define PROPERTY_ID_PRINT(x) ((x) >> 24), \
-                             ((x) >> 16) & 0xff, \
-                             ((x) >> 8) & 0xff, \
-                             (x) & 0xff
-
-AppleMP3Reader::AppleMP3Reader(AbstractMediaDecoder *aDecoder)
-  : MediaDecoderReader(aDecoder)
-  , mStreamReady(false)
-  , mAudioFramesPerCompressedPacket(0)
-  , mCurrentAudioFrame(0)
-  , mAudioChannels(0)
-  , mAudioSampleRate(0)
-  , mAudioFileStream(nullptr)
-  , mAudioConverter(nullptr)
-  , mMP3FrameParser(mDecoder->GetResource()->GetLength())
-  , mResource(mDecoder->GetResource())
-{
-  MOZ_ASSERT(NS_IsMainThread(), "Should be on main thread");
-}
-
-AppleMP3Reader::~AppleMP3Reader()
-{
-  MOZ_ASSERT(NS_IsMainThread(), "Should be on main thread");
-}
-
-
-/*
- * The Apple audio decoding APIs are very callback-happy. When the parser has
- * some metadata, it will call back to here.
- */
-static void _AudioMetadataCallback(void *aThis,
-                                   AudioFileStreamID aFileStream,
-                                   AudioFileStreamPropertyID aPropertyID,
-                                   UInt32 *aFlags)
-{
-  ((AppleMP3Reader*)aThis)->AudioMetadataCallback(aFileStream, aPropertyID,
-                                                  aFlags);
-}
-
-/*
- * Similar to above, this is called when the parser has enough data to parse
- * one or more samples.
- */
-static void _AudioSampleCallback(void *aThis,
-                                 UInt32 aNumBytes, UInt32 aNumPackets,
-                                 const void *aData,
-                                 AudioStreamPacketDescription *aPackets)
-{
-  ((AppleMP3Reader*)aThis)->AudioSampleCallback(aNumBytes, aNumPackets,
-                                                aData, aPackets);
-}
-
-
-/*
- * If we're not at end of stream, read |aNumBytes| from the media resource,
- * put it in |aData|, and return true.
- * Otherwise, put as much data as is left into |aData|, set |aNumBytes| to the
- * amount of data we have left, and return false.
- */
-nsresult
-AppleMP3Reader::Read(uint32_t *aNumBytes, char *aData)
-{
-  nsresult rv = mResource.Read(aData, *aNumBytes, aNumBytes);
-
-  if (NS_FAILED(rv)) {
-    *aNumBytes = 0;
-    return NS_ERROR_FAILURE;
-  }
-
-  // XXX Maybe return a better value than NS_ERROR_FAILURE?
-  return *aNumBytes ? NS_OK : NS_ERROR_FAILURE;
-}
-
-nsresult
-AppleMP3Reader::Init()
-{
-  AudioFileTypeID fileType = kAudioFileMP3Type;
-
-  OSStatus rv = AudioFileStreamOpen(this,
-                                    _AudioMetadataCallback,
-                                    _AudioSampleCallback,
-                                    fileType,
-                                    &mAudioFileStream);
-
-  if (rv) {
-    return NS_ERROR_FAILURE;
-  }
-
-  return NS_OK;
-}
-
-
-struct PassthroughUserData {
-  AppleMP3Reader *mReader;
-  UInt32 mNumPackets;
-  UInt32 mDataSize;
-  const void *mData;
-  AudioStreamPacketDescription *mPacketDesc;
-  bool mDone;
-};
-
-// Error value we pass through the decoder to signal that nothing has gone wrong
-// during decoding, but more data is needed.
-const UInt32 kNeedMoreData = 'MOAR';
-
-/*
- * This function is called from |AudioConverterFillComplexBuffer|, which is
- * called from |AudioSampleCallback| below, which in turn is called by
- * |AudioFileStreamParseBytes|, which is called by |DecodeAudioData|.
- *
- * Mercifully, this is all synchronous.
- *
- * This callback is run when the AudioConverter (decoder) wants more MP3 packets
- * to decode.
- */
-/* static */ OSStatus
-AppleMP3Reader::PassthroughInputDataCallback(AudioConverterRef aAudioConverter,
-                                             UInt32 *aNumDataPackets /* in/out */,
-                                             AudioBufferList *aData /* in/out */,
-                                             AudioStreamPacketDescription **aPacketDesc,
-                                             void *aUserData)
-{
-  if (!aPacketDesc) {
-    return kAudioFileStreamError_UnspecifiedError;
-  }
-
-  PassthroughUserData *userData = (PassthroughUserData *)aUserData;
-  if (userData->mDone) {
-    // We make sure this callback is run _once_, with all the data we received
-    // from |AudioFileStreamParseBytes|. When we return an error, the decoder
-    // simply passes the return value on to the calling method,
-    // |AudioSampleCallback|; and flushes all of the audio frames it had
-    // buffered. It does not change the decoder's state.
-    LOGD("requested too much data; returning\n");
-    *aNumDataPackets = 0;
-    return kNeedMoreData;
-  }
-
-  userData->mDone = true;
-
-  LOGD("AudioConverter wants %u packets of audio data\n", *aNumDataPackets);
-
-  *aNumDataPackets = userData->mNumPackets;
-  *aPacketDesc = userData->mPacketDesc;
-
-  aData->mBuffers[0].mNumberChannels = userData->mReader->mAudioChannels;
-  aData->mBuffers[0].mDataByteSize = userData->mDataSize;
-  aData->mBuffers[0].mData = const_cast<void *>(userData->mData);
-
-  return 0;
-}
-
-/*
- * This callback is called when |AudioFileStreamParseBytes| has enough data to
- * extract one or more MP3 packets.
- */
-void
-AppleMP3Reader::AudioSampleCallback(UInt32 aNumBytes,
-                                    UInt32 aNumPackets,
-                                    const void *aData,
-                                    AudioStreamPacketDescription *aPackets)
-{
-  LOGD("got %u bytes, %u packets\n", aNumBytes, aNumPackets);
-
-  // 1 frame per packet * num channels * 32-bit float
-  uint32_t decodedSize = MAX_AUDIO_FRAMES * mAudioChannels *
-                         sizeof(AudioDataValue);
-
-  // descriptions for _decompressed_ audio packets. ignored.
-  nsAutoArrayPtr<AudioStreamPacketDescription>
-    packets(new AudioStreamPacketDescription[MAX_AUDIO_FRAMES]);
-
-  // This API insists on having MP3 packets spoon-fed to it from a callback.
-  // This structure exists only to pass our state and the result of the parser
-  // on to the callback above.
-  PassthroughUserData userData = { this, aNumPackets, aNumBytes, aData, aPackets, false };
-
-  do {
-    // Decompressed audio buffer
-    auto decoded = MakeUnique<uint8_t[]>(decodedSize);
-
-    AudioBufferList decBuffer;
-    decBuffer.mNumberBuffers = 1;
-    decBuffer.mBuffers[0].mNumberChannels = mAudioChannels;
-    decBuffer.mBuffers[0].mDataByteSize = decodedSize;
-    decBuffer.mBuffers[0].mData = decoded.get();
-
-    // in: the max number of packets we can handle from the decoder.
-    // out: the number of packets the decoder is actually returning.
-    UInt32 numFrames = MAX_AUDIO_FRAMES;
-
-    OSStatus rv = AudioConverterFillComplexBuffer(mAudioConverter,
-                                                  PassthroughInputDataCallback,
-                                                  &userData,
-                                                  &numFrames /* in/out */,
-                                                  &decBuffer,
-                                                  packets.get());
-
-    if (rv && rv != kNeedMoreData) {
-      LOGE("Error decoding audio stream: %x\n", rv);
-      break;
-    }
-
-    // If we decoded zero frames then AudiOConverterFillComplexBuffer is out
-    // of data to provide.  We drained its internal buffer completely on the
-    // last pass.
-    if (numFrames == 0 && rv == kNeedMoreData) {
-      LOGD("FillComplexBuffer out of data exactly\n");
-      break;
-    }
-
-    int64_t time = FramesToUsecs(mCurrentAudioFrame, mAudioSampleRate).value();
-    int64_t duration = FramesToUsecs(numFrames, mAudioSampleRate).value();
-
-    LOGD("pushed audio at time %lfs; duration %lfs\n",
-         (double)time / USECS_PER_S, (double)duration / USECS_PER_S);
-
-    auto samples = UniquePtr<AudioDataValue[]>(reinterpret_cast<AudioDataValue*>
-					       (decoded.release()));
-    AudioData *audio = new AudioData(mResource.Tell(),
-                                     time, duration, numFrames,
-                                     Move(samples),
-                                     mAudioChannels, mAudioSampleRate);
-    mAudioQueue.Push(audio);
-
-    mCurrentAudioFrame += numFrames;
-
-    if (rv == kNeedMoreData) {
-      // No error; we just need more data.
-      LOGD("FillComplexBuffer out of data\n");
-      break;
-    }
-  } while (true);
-}
-
-bool
-AppleMP3Reader::DecodeAudioData()
-{
-  MOZ_ASSERT(OnTaskQueue());
-
-  // Read AUDIO_READ_BYTES if we can
-  char bytes[AUDIO_READ_BYTES];
-  uint32_t numBytes = AUDIO_READ_BYTES;
-
-  nsresult readrv = Read(&numBytes, bytes);
-
-  // This function calls |AudioSampleCallback| above, synchronously, when it
-  // finds compressed MP3 frame.
-  OSStatus rv = AudioFileStreamParseBytes(mAudioFileStream,
-                                          numBytes,
-                                          bytes,
-                                          0 /* flags */);
-
-  if (NS_FAILED(readrv)) {
-    mAudioQueue.Finish();
-    return false;
-  }
-
-  // DataUnavailable just means there wasn't enough data to demux anything.
-  // We should have more to push into the demuxer next time we're called.
-  if (rv && rv != kAudioFileStreamError_DataUnavailable) {
-    LOGE("AudioFileStreamParseBytes returned unknown error %x", rv);
-    return false;
-  }
-
-  return true;
-}
-
-bool
-AppleMP3Reader::DecodeVideoFrame(bool &aKeyframeSkip,
-                                 int64_t aTimeThreshold)
-{
-  MOZ_ASSERT(OnTaskQueue());
-  return false;
-}
-
-bool
-AppleMP3Reader::IsMediaSeekable()
-{
-  // not used
-  return true;
-}
-
-/*
- * Query the MP3 parser for a piece of metadata.
- */
-static nsresult
-GetProperty(AudioFileStreamID aAudioFileStream,
-            AudioFileStreamPropertyID aPropertyID, void *aData)
-{
-  UInt32 size;
-  Boolean writeable;
-  OSStatus rv = AudioFileStreamGetPropertyInfo(aAudioFileStream, aPropertyID,
-                                               &size, &writeable);
-
-  if (rv) {
-    LOGW("Couldn't get property " PROPERTY_ID_FORMAT "\n",
-         PROPERTY_ID_PRINT(aPropertyID));
-    return NS_ERROR_FAILURE;
-  }
-
-  rv = AudioFileStreamGetProperty(aAudioFileStream, aPropertyID,
-                                  &size, aData);
-
-  return NS_OK;
-}
-
-
-nsresult
-AppleMP3Reader::ReadMetadata(MediaInfo* aInfo,
-                             MetadataTags** aTags)
-{
-  MOZ_ASSERT(OnTaskQueue());
-
-  *aTags = nullptr;
-
-  /*
-   * Feed bytes into the parser until we have all the metadata we need to
-   * set up the decoder. When the parser has enough data, it will
-   * synchronously call back to |AudioMetadataCallback| below.
-   */
-  OSStatus rv;
-  nsresult readrv;
-  uint32_t offset = 0;
-  do {
-    char bytes[AUDIO_READ_BYTES];
-    uint32_t numBytes = AUDIO_READ_BYTES;
-    readrv = Read(&numBytes, bytes);
-
-    rv = AudioFileStreamParseBytes(mAudioFileStream,
-                                   numBytes,
-                                   bytes,
-                                   0 /* flags */);
-
-    mMP3FrameParser.Parse(reinterpret_cast<uint8_t*>(bytes), numBytes, offset);
-
-    offset += numBytes;
-
-    // We have to do our decoder setup from the callback. When it's done it will
-    // set mStreamReady.
-  } while (!mStreamReady && !rv && NS_SUCCEEDED(readrv));
-
-  if (rv) {
-    LOGE("Error decoding audio stream metadata\n");
-    return NS_ERROR_FAILURE;
-  }
-
-  if (!mAudioConverter) {
-    LOGE("Failed to setup the AudioToolbox audio decoder\n");
-    return NS_ERROR_FAILURE;
-  }
-
-  if (!mMP3FrameParser.IsMP3()) {
-    LOGE("Frame parser failed to parse MP3 stream\n");
-    return NS_ERROR_FAILURE;
-  }
-
-  if (mStreamReady) {
-    aInfo->mAudio.mRate = mAudioSampleRate;
-    aInfo->mAudio.mChannels = mAudioChannels;
-  }
-
-  // This special snowflake reader doesn't seem to set *aInfo = mInfo like all
-  // the others. Yuck.
-  mDuration = mMP3FrameParser.GetDuration();
-  mInfo.mMetadataDuration.emplace(TimeUnit::FromMicroseconds(mDuration));
-  aInfo->mMetadataDuration.emplace(TimeUnit::FromMicroseconds(mDuration));
-
-  return NS_OK;
-}
-
-
-void
-AppleMP3Reader::AudioMetadataCallback(AudioFileStreamID aFileStream,
-                                      AudioFileStreamPropertyID aPropertyID,
-                                      UInt32 *aFlags)
-{
-  if (aPropertyID == kAudioFileStreamProperty_ReadyToProducePackets) {
-    /*
-     * The parser is ready to send us packets of MP3 audio.
-     *
-     * We need to set the decoder up here, because if
-     * |AudioFileStreamParseBytes| has enough audio data, then it will call
-     * |AudioSampleCallback| before we get back to |ReadMetadata|.
-     */
-    SetupDecoder();
-    mStreamReady = true;
-  }
-}
-
-
-void
-AppleMP3Reader::SetupDecoder()
-{
-  // Get input format description from demuxer
-  AudioStreamBasicDescription inputFormat, outputFormat;
-  GetProperty(mAudioFileStream, kAudioFileStreamProperty_DataFormat, &inputFormat);
-
-  memset(&outputFormat, 0, sizeof(outputFormat));
-
-  // Set output format
-#if defined(MOZ_SAMPLE_TYPE_FLOAT32)
-  outputFormat.mBitsPerChannel = 32;
-  outputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat;
-#elif defined(MOZ_SAMPLE_TYPE_S16)
-  outputFormat.mBitsPerChannel = 32;
-  outputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
-#else
-#error Unknown audio sample type
-#endif
-
-  mAudioSampleRate = outputFormat.mSampleRate = inputFormat.mSampleRate;
-  mAudioChannels
-    = outputFormat.mChannelsPerFrame = inputFormat.mChannelsPerFrame;
-  mAudioFramesPerCompressedPacket = inputFormat.mFramesPerPacket;
-
-  outputFormat.mFormatID = kAudioFormatLinearPCM;
-
-  // Set up the decoder so it gives us one sample per frame; this way, it will
-  // pass us all the samples it has in one go. Also makes it much easier to
-  // deinterlace.
-  outputFormat.mFramesPerPacket = 1;
-  outputFormat.mBytesPerPacket = outputFormat.mBytesPerFrame
-    = outputFormat.mChannelsPerFrame * outputFormat.mBitsPerChannel / 8;
-
-  OSStatus rv = AudioConverterNew(&inputFormat,
-                                  &outputFormat,
-                                  &mAudioConverter);
-
-  if (rv) {
-    LOGE("Error constructing audio format converter: %x\n", rv);
-    mAudioConverter = nullptr;
-    return;
-  }
-}
-
-
-RefPtr<MediaDecoderReader::SeekPromise>
-AppleMP3Reader::Seek(int64_t aTime, int64_t aEndTime)
-{
-  MOZ_ASSERT(OnTaskQueue());
-
-  // Find the exact frame/packet that contains |aTime|.
-  mCurrentAudioFrame = aTime * mAudioSampleRate / USECS_PER_S;
-  SInt64 packet = mCurrentAudioFrame / mAudioFramesPerCompressedPacket;
-
-  // |AudioFileStreamSeek| will pass back through |byteOffset| the byte offset
-  // into the stream it expects next time it reads.
-  SInt64 byteOffset;
-  UInt32 flags = 0;
-
-  OSStatus rv = AudioFileStreamSeek(mAudioFileStream,
-                                    packet,
-                                    &byteOffset,
-                                    &flags);
-
-  if (rv) {
-    LOGE("Couldn't seek demuxer. Error code %x\n", rv);
-    return SeekPromise::CreateAndReject(NS_ERROR_FAILURE, __func__);
-  }
-
-  LOGD("computed byte offset = %lld; estimated = %s\n",
-       byteOffset,
-       (flags & kAudioFileStreamSeekFlag_OffsetIsEstimated) ? "YES" : "NO");
-
-  mResource.Seek(nsISeekableStream::NS_SEEK_SET, byteOffset);
-
-  ResetDecode();
-
-  return SeekPromise::CreateAndResolve(aTime, __func__);
-}
-
-void
-AppleMP3Reader::NotifyDataArrivedInternal()
-{
-  MOZ_ASSERT(OnTaskQueue());
-  if (!mMP3FrameParser.NeedsData()) {
-    return;
-  }
-
-  AutoPinned<MediaResource> resource(mResource.GetResource());
-  nsTArray<MediaByteRange> byteRanges;
-  nsresult rv = resource->GetCachedRanges(byteRanges);
-
-  if (NS_FAILED(rv)) {
-    return;
-  }
-
-  IntervalSet<int64_t> intervals;
-  for (auto& range : byteRanges) {
-    intervals += mFilter.NotifyDataArrived(range.Length(), range.mStart);
-  }
-  for (const auto& interval : intervals) {
-    RefPtr<MediaByteBuffer> bytes =
-      resource->MediaReadAt(interval.mStart, interval.Length());
-    NS_ENSURE_TRUE_VOID(bytes);
-    mMP3FrameParser.Parse(bytes->Elements(), interval.Length(), interval.mStart);
-    if (!mMP3FrameParser.IsMP3()) {
-      return;
-    }
-  }
-
-  uint64_t duration = mMP3FrameParser.GetDuration();
-  if (duration != mDuration) {
-    LOGD("Updating media duration to %lluus\n", duration);
-    MOZ_ASSERT(mDecoder);
-    mDuration = duration;
-    mDecoder->DispatchUpdateEstimatedMediaDuration(duration);
-  }
-}
-
-} // namespace mozilla
deleted file mode 100644
--- a/dom/media/apple/AppleMP3Reader.h
+++ /dev/null
@@ -1,86 +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/. */
-
-#ifndef __AppleMP3Reader_h__
-#define __AppleMP3Reader_h__
-
-#include "MediaDecoderReader.h"
-#include "MediaResource.h"
-#include "MP3FrameParser.h"
-#include "VideoUtils.h"
-
-#include <AudioToolbox/AudioToolbox.h>
-
-namespace mozilla {
-
-class AppleMP3Reader : public MediaDecoderReader
-{
-public:
-  explicit AppleMP3Reader(AbstractMediaDecoder *aDecoder);
-  virtual ~AppleMP3Reader() override;
-
-  virtual nsresult Init() override;
-
-  nsresult PushDataToDemuxer();
-
-  virtual bool DecodeAudioData() override;
-  virtual bool DecodeVideoFrame(bool &aKeyframeSkip,
-                                int64_t aTimeThreshold) override;
-
-  virtual nsresult ReadMetadata(MediaInfo* aInfo,
-                                MetadataTags** aTags) override;
-
-  virtual RefPtr<SeekPromise>
-  Seek(int64_t aTime, int64_t aEndTime) override;
-
-  void AudioSampleCallback(UInt32 aNumBytes,
-                           UInt32 aNumPackets,
-                           const void *aData,
-                           AudioStreamPacketDescription *aPackets);
-
-  void AudioMetadataCallback(AudioFileStreamID aFileStream,
-                             AudioFileStreamPropertyID aPropertyID,
-                             UInt32 *aFlags);
-
-protected:
-  virtual void NotifyDataArrivedInternal() override;
-public:
-
-  virtual bool IsMediaSeekable() override;
-
-private:
-  void SetupDecoder();
-  nsresult Read(uint32_t *aNumBytes, char *aData);
-
-  static OSStatus PassthroughInputDataCallback(AudioConverterRef aAudioConverter,
-                                               UInt32 *aNumDataPackets,
-                                               AudioBufferList *aData,
-                                               AudioStreamPacketDescription **aPacketDesc,
-                                               void *aUserData);
-
-  // Initialisation has to be done in a callback, so we store the result here.
-  bool mStreamReady;
-
-  // Number of audio samples in an audio packet. Constant over all packets in a
-  // stream.
-  UInt32 mAudioFramesPerCompressedPacket;
-  // Store the next audio frame to be played; so we can keep time when seeking.
-  UInt64 mCurrentAudioFrame;
-  UInt32 mAudioChannels;
-  UInt32 mAudioSampleRate;
-
-  uint64_t mDuration;
-
-  AudioFileStreamID mAudioFileStream;
-  AudioConverterRef mAudioConverter;
-
-  MP3FrameParser mMP3FrameParser;
-
-  MediaResourceIndex mResource;
-  NotifyDataArrivedFilter mFilter;
-};
-
-} // namespace mozilla
-
-#endif // __AppleMP3Reader_h__
deleted file mode 100644
--- a/dom/media/apple/moz.build
+++ /dev/null
@@ -1,19 +0,0 @@
-# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-EXPORTS += [
-    'AppleDecoder.h',
-    'AppleMP3Reader.h',
-]
-
-UNIFIED_SOURCES += [
-    'AppleDecoder.cpp',
-    'AppleMP3Reader.cpp',
-]
-
-FINAL_LIBRARY = 'xul'
-
-OS_LIBS += ['-framework AudioToolbox']
--- a/dom/media/moz.build
+++ b/dom/media/moz.build
@@ -53,19 +53,16 @@ if CONFIG['MOZ_DIRECTSHOW']:
     DIRS += ['directshow']
 
 if CONFIG['MOZ_ANDROID_OMX']:
     DIRS += ['android']
 
 if CONFIG['MOZ_FMP4']:
     DIRS += ['fmp4']
 
-if CONFIG['MOZ_APPLEMEDIA']:
-    DIRS += ['apple']
-
 if CONFIG['MOZ_WEBRTC']:
     DIRS += ['bridge']
 
 if CONFIG['MOZ_OMX_DECODER']:
     DIRS += ['omx']
 
 if CONFIG['MOZ_EME']:
     DIRS += ['eme']
@@ -296,16 +293,21 @@ if CONFIG['MOZ_DIRECTSHOW']:
 if CONFIG['MOZ_WEBRTC']:
     LOCAL_INCLUDES += [
         '/media/webrtc/signaling/src/common',
         '/media/webrtc/trunk',
     ]
 
 DEFINES['MOZILLA_INTERNAL_API'] = True
 
+if CONFIG['OS_TARGET'] == 'WINNT':
+    DEFINES['WEBRTC_WIN'] = True
+else:
+    DEFINES['WEBRTC_POSIX'] = True
+
 if CONFIG['MOZ_OMX_DECODER']:
     DEFINES['MOZ_OMX_DECODER'] = True
 
 if CONFIG['ANDROID_VERSION'] > '15':
     DEFINES['MOZ_OMX_WEBM_DECODER'] = True
 
 if CONFIG['MOZ_GONK_MEDIACODEC']:
     DEFINES['MOZ_GONK_MEDIACODEC'] = True
--- a/dom/media/omx/OMXCodecWrapper.cpp
+++ b/dom/media/omx/OMXCodecWrapper.cpp
@@ -46,31 +46,42 @@ enum BufferState
   BUFFER_OK,
   BUFFER_FAIL,
   WAIT_FOR_NEW_BUFFER
 };
 
 bool
 OMXCodecReservation::ReserveOMXCodec()
 {
-  if (mClient) {
-    // Already tried reservation.
-    return false;
+  if (!mClient) {
+    mClient = new mozilla::MediaSystemResourceClient(mType);
+  } else {
+    if (mOwned) {
+      //CODEC_ERROR("OMX Reservation: (%d) already owned", (int) mType);
+      return true;
+    }
+    //CODEC_ERROR("OMX Reservation: (%d) already NOT owned", (int) mType);
   }
-  mClient = new mozilla::MediaSystemResourceClient(mType);
-  return mClient->AcquireSyncNoWait(); // don't wait if resrouce is not available
+  mOwned = mClient->AcquireSyncNoWait(); // don't wait if resource is not available
+  //CODEC_ERROR("OMX Reservation: (%d) Acquire was %s", (int) mType, mOwned ? "Successful" : "Failed");
+  return mOwned;
 }
 
 void
 OMXCodecReservation::ReleaseOMXCodec()
 {
   if (!mClient) {
     return;
   }
-  mClient->ReleaseResource();
+  //CODEC_ERROR("OMX Reservation: Releasing resource: (%d) %s", (int) mType, mOwned ? "Owned" : "Not owned");
+  if (mOwned) {
+    mClient->ReleaseResource();
+    mClient = nullptr;
+    mOwned = false;
+  }
 }
 
 OMXAudioEncoder*
 OMXCodecWrapper::CreateAACEncoder()
 {
   nsAutoPtr<OMXAudioEncoder> aac(new OMXAudioEncoder(CodecType::AAC_ENC));
   // Return the object only when media codec is valid.
   NS_ENSURE_TRUE(aac->IsValid(), nullptr);
--- a/dom/media/omx/OMXCodecWrapper.h
+++ b/dom/media/omx/OMXCodecWrapper.h
@@ -21,17 +21,17 @@
 #include <speex/speex_resampler.h>
 
 namespace android {
 
 // Wrapper class for managing HW codec reservations
 class OMXCodecReservation : public RefBase
 {
 public:
-  OMXCodecReservation(bool aEncoder)
+  OMXCodecReservation(bool aEncoder) : mOwned(false)
   {
     mType = aEncoder ? mozilla::MediaSystemResourceType::VIDEO_ENCODER :
             mozilla::MediaSystemResourceType::VIDEO_DECODER;
   }
 
   virtual ~OMXCodecReservation()
   {
     ReleaseOMXCodec();
@@ -40,16 +40,17 @@ public:
   /** Reserve the Encode or Decode resource for this instance */
   virtual bool ReserveOMXCodec();
 
   /** Release the Encode or Decode resource for this instance */
   virtual void ReleaseOMXCodec();
 
 private:
   mozilla::MediaSystemResourceType mType;
+  bool mOwned;  // We already own this resource
 
   RefPtr<mozilla::MediaSystemResourceClient> mClient;
 };
 
 
 class OMXAudioEncoder;
 class OMXVideoEncoder;
 
--- a/dom/media/platforms/ffmpeg/FFmpegDataDecoder.cpp
+++ b/dom/media/platforms/ffmpeg/FFmpegDataDecoder.cpp
@@ -8,17 +8,17 @@
 
 #include <string.h>
 #include <unistd.h>
 
 #include "FFmpegLibs.h"
 #include "FFmpegLog.h"
 #include "FFmpegDataDecoder.h"
 #include "prsystem.h"
-#include "FFmpegDecoderModule.h"
+#include "FFmpegRuntimeLinker.h"
 
 namespace mozilla
 {
 
 bool FFmpegDataDecoder<LIBAV_VER>::sFFmpegInitDone = false;
 StaticMutex FFmpegDataDecoder<LIBAV_VER>::sMonitor;
 
 FFmpegDataDecoder<LIBAV_VER>::FFmpegDataDecoder(FlushableTaskQueue* aTaskQueue,
@@ -84,17 +84,17 @@ FFmpegDataDecoder<LIBAV_VER>::InitDecode
     NS_WARNING("Couldn't init ffmpeg context");
     return NS_ERROR_FAILURE;
   }
 
   mCodecContext->opaque = this;
 
   // FFmpeg takes this as a suggestion for what format to use for audio samples.
   uint32_t major, minor;
-  FFmpegDecoderModule<LIBAV_VER>::GetVersion(major, minor);
+  FFmpegRuntimeLinker::GetVersion(major, minor);
   // LibAV 0.8 produces rubbish float interlaved samples, request 16 bits audio.
   mCodecContext->request_sample_fmt = major == 53 && minor <= 34 ?
     AV_SAMPLE_FMT_S16 : AV_SAMPLE_FMT_FLT;
 
   // FFmpeg will call back to this to negotiate a video pixel format.
   mCodecContext->get_format = ChoosePixelFormat;
 
   mCodecContext->thread_count = PR_GetNumberOfProcessors();
--- a/dom/media/platforms/ffmpeg/FFmpegDecoderModule.h
+++ b/dom/media/platforms/ffmpeg/FFmpegDecoderModule.h
@@ -21,25 +21,16 @@ public:
   static already_AddRefed<PlatformDecoderModule>
   Create()
   {
     RefPtr<PlatformDecoderModule> pdm = new FFmpegDecoderModule();
 
     return pdm.forget();
   }
 
-  static bool
-  GetVersion(uint32_t& aMajor, uint32_t& aMinor)
-  {
-    uint32_t version = avcodec_version();
-    aMajor = (version >> 16) & 0xff;
-    aMinor = (version >> 8) & 0xff;
-    return true;
-  }
-
   FFmpegDecoderModule() {}
   virtual ~FFmpegDecoderModule() {}
 
   already_AddRefed<MediaDataDecoder>
   CreateVideoDecoder(const VideoInfo& aConfig,
                      layers::LayersBackend aLayersBackend,
                      layers::ImageContainer* aImageContainer,
                      FlushableTaskQueue* aVideoTaskQueue,
--- a/dom/media/platforms/ffmpeg/FFmpegFunctionList.h
+++ b/dom/media/platforms/ffmpeg/FFmpegFunctionList.h
@@ -11,21 +11,19 @@ AV_FUNC(avcodec_decode_video2, 0)
 AV_FUNC(avcodec_default_get_buffer, 0)
 AV_FUNC(avcodec_default_release_buffer, 0)
 AV_FUNC(avcodec_find_decoder, 0)
 AV_FUNC(avcodec_flush_buffers, 0)
 AV_FUNC(avcodec_alloc_context3, 0)
 AV_FUNC(avcodec_get_edge_width, 0)
 AV_FUNC(avcodec_open2, 0)
 AV_FUNC(av_init_packet, 0)
-AV_FUNC(av_dict_get, 0)
 AV_FUNC(av_parser_init, 0)
 AV_FUNC(av_parser_close, 0)
 AV_FUNC(av_parser_parse2, 0)
-AV_FUNC(avcodec_version, 0)
 AV_FUNC(avcodec_register_all, 0)
 
 /* libavutil */
 AV_FUNC(av_image_fill_linesizes, 0)
 AV_FUNC(av_image_fill_pointers, 0)
 AV_FUNC(av_log_set_level, 0)
 AV_FUNC(av_malloc, 0)
 AV_FUNC(av_freep, 0)
--- a/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.cpp
+++ b/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.cpp
@@ -1,129 +1,161 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include <dlfcn.h>
-
 #include "FFmpegRuntimeLinker.h"
 #include "mozilla/ArrayUtils.h"
 #include "FFmpegLog.h"
 #include "mozilla/Preferences.h"
-
-#define NUM_ELEMENTS(X) (sizeof(X) / sizeof((X)[0]))
+#include "prlink.h"
 
 namespace mozilla
 {
 
 FFmpegRuntimeLinker::LinkStatus FFmpegRuntimeLinker::sLinkStatus =
   LinkStatus_INIT;
 
-struct AvCodecLib
-{
-  const char* Name;
-  already_AddRefed<PlatformDecoderModule> (*Factory)();
-  uint32_t Version;
-};
-
 template <int V> class FFmpegDecoderModule
 {
 public:
   static already_AddRefed<PlatformDecoderModule> Create();
 };
 
-static const AvCodecLib sLibs[] = {
-  { "libavcodec-ffmpeg.so.56", FFmpegDecoderModule<55>::Create, 55 },
-  { "libavcodec.so.56", FFmpegDecoderModule<55>::Create, 55 },
-  { "libavcodec.so.55", FFmpegDecoderModule<55>::Create, 55 },
-  { "libavcodec.so.54", FFmpegDecoderModule<54>::Create, 54 },
-  { "libavcodec.so.53", FFmpegDecoderModule<53>::Create, 53 },
-  { "libavcodec.56.dylib", FFmpegDecoderModule<55>::Create, 55 },
-  { "libavcodec.55.dylib", FFmpegDecoderModule<55>::Create, 55 },
-  { "libavcodec.54.dylib", FFmpegDecoderModule<54>::Create, 54 },
-  { "libavcodec.53.dylib", FFmpegDecoderModule<53>::Create, 53 },
+static const char* sLibs[] = {
+#if defined(XP_DARWIN)
+  "libavcodec.56.dylib",
+  "libavcodec.55.dylib",
+  "libavcodec.54.dylib",
+  "libavcodec.53.dylib",
+#else
+  "libavcodec-ffmpeg.so.56",
+  "libavcodec.so.56",
+  "libavcodec.so.55",
+  "libavcodec.so.54",
+  "libavcodec.so.53",
+#endif
 };
 
-void* FFmpegRuntimeLinker::sLinkedLib = nullptr;
-const AvCodecLib* FFmpegRuntimeLinker::sLib = nullptr;
+PRLibrary* FFmpegRuntimeLinker::sLinkedLib = nullptr;
+const char* FFmpegRuntimeLinker::sLib = nullptr;
+static unsigned (*avcodec_version)() = nullptr;
 
 #define AV_FUNC(func, ver) void (*func)();
+
 #define LIBAVCODEC_ALLVERSION
 #include "FFmpegFunctionList.h"
 #undef LIBAVCODEC_ALLVERSION
 #undef AV_FUNC
 
 /* static */ bool
 FFmpegRuntimeLinker::Link()
 {
   if (sLinkStatus) {
     return sLinkStatus == LinkStatus_SUCCEEDED;
   }
 
   MOZ_ASSERT(NS_IsMainThread());
 
   for (size_t i = 0; i < ArrayLength(sLibs); i++) {
-    const AvCodecLib* lib = &sLibs[i];
-    sLinkedLib = dlopen(lib->Name, RTLD_NOW | RTLD_LOCAL);
+    const char* lib = sLibs[i];
+    PRLibSpec lspec;
+    lspec.type = PR_LibSpec_Pathname;
+    lspec.value.pathname = lib;
+    sLinkedLib = PR_LoadLibraryWithFlags(lspec, PR_LD_NOW | PR_LD_LOCAL);
     if (sLinkedLib) {
-      if (Bind(lib->Name, lib->Version)) {
+      if (Bind(lib)) {
         sLib = lib;
         sLinkStatus = LinkStatus_SUCCEEDED;
         return true;
       }
       // Shouldn't happen but if it does then we try the next lib..
       Unlink();
     }
   }
 
   FFMPEG_LOG("H264/AAC codecs unsupported without [");
   for (size_t i = 0; i < ArrayLength(sLibs); i++) {
-    FFMPEG_LOG("%s %s", i ? "," : "", sLibs[i].Name);
+    FFMPEG_LOG("%s %s", i ? "," : "", sLibs[i]);
   }
   FFMPEG_LOG(" ]\n");
 
   Unlink();
 
   sLinkStatus = LinkStatus_FAILED;
   return false;
 }
 
 /* static */ bool
-FFmpegRuntimeLinker::Bind(const char* aLibName, uint32_t Version)
+FFmpegRuntimeLinker::Bind(const char* aLibName)
 {
+  avcodec_version = (typeof(avcodec_version))PR_FindSymbol(sLinkedLib,
+                                                           "avcodec_version");
+  uint32_t major, minor;
+  if (!GetVersion(major, minor)) {
+    return false;
+  }
+  if (major > 55) {
+    // All major greater than 56 currently use the same ABI as 55.
+    major = 55;
+  }
+
 #define LIBAVCODEC_ALLVERSION
 #define AV_FUNC(func, ver)                                                     \
-  if (ver == 0 || ver == Version) {                                            \
-    if (!(func = (typeof(func))dlsym(sLinkedLib, #func))) {                    \
+  if (ver == 0 || ver == major) {                                              \
+    if (!(func = (typeof(func))PR_FindSymbol(sLinkedLib, #func))) {            \
       FFMPEG_LOG("Couldn't load function " #func " from %s.", aLibName);       \
       return false;                                                            \
     }                                                                          \
   }
 #include "FFmpegFunctionList.h"
 #undef AV_FUNC
 #undef LIBAVCODEC_ALLVERSION
   return true;
 }
 
 /* static */ already_AddRefed<PlatformDecoderModule>
 FFmpegRuntimeLinker::CreateDecoderModule()
 {
   if (!Link()) {
     return nullptr;
   }
-  RefPtr<PlatformDecoderModule> module = sLib->Factory();
+  uint32_t major, minor;
+  if (!GetVersion(major, minor)) {
+    return  nullptr;
+  }
+
+  RefPtr<PlatformDecoderModule> module;
+  switch (major) {
+    case 53: module = FFmpegDecoderModule<53>::Create(); break;
+    case 54: module = FFmpegDecoderModule<54>::Create(); break;
+    default: module = FFmpegDecoderModule<55>::Create(); break;
+  }
   return module.forget();
 }
 
 /* static */ void
 FFmpegRuntimeLinker::Unlink()
 {
   if (sLinkedLib) {
-    dlclose(sLinkedLib);
+    PR_UnloadLibrary(sLinkedLib);
     sLinkedLib = nullptr;
     sLib = nullptr;
     sLinkStatus = LinkStatus_INIT;
+    avcodec_version = nullptr;
   }
 }
 
+/* static */ bool
+FFmpegRuntimeLinker::GetVersion(uint32_t& aMajor, uint32_t& aMinor)
+{
+  if (!avcodec_version) {
+    return false;
+  }
+  uint32_t version = avcodec_version();
+  aMajor = (version >> 16) & 0xff;
+  aMinor = (version >> 8) & 0xff;
+  return true;
+}
+
 } // namespace mozilla
--- a/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.h
+++ b/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.h
@@ -5,33 +5,34 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef __FFmpegRuntimeLinker_h__
 #define __FFmpegRuntimeLinker_h__
 
 #include "PlatformDecoderModule.h"
 #include <stdint.h>
 
+struct PRLibrary;
+
 namespace mozilla
 {
 
-struct AvCodecLib;
-
 class FFmpegRuntimeLinker
 {
 public:
   static bool Link();
   static void Unlink();
   static already_AddRefed<PlatformDecoderModule> CreateDecoderModule();
+  static bool GetVersion(uint32_t& aMajor, uint32_t& aMinor);
 
 private:
-  static void* sLinkedLib;
-  static const AvCodecLib* sLib;
+  static PRLibrary* sLinkedLib;
+  static const char* sLib;
 
-  static bool Bind(const char* aLibName, uint32_t Version);
+  static bool Bind(const char* aLibName);
 
   static enum LinkStatus {
     LinkStatus_INIT = 0,
     LinkStatus_FAILED,
     LinkStatus_SUCCEEDED
   } sLinkStatus;
 };
 
--- a/dom/media/systemservices/CamerasChild.cpp
+++ b/dom/media/systemservices/CamerasChild.cpp
@@ -642,17 +642,17 @@ CamerasChild::Shutdown()
   CamerasSingleton::Child() = nullptr;
   CamerasSingleton::Thread() = nullptr;
 }
 
 bool
 CamerasChild::RecvDeliverFrame(const int& capEngine,
                                const int& capId,
                                mozilla::ipc::Shmem&& shmem,
-                               const int& size,
+                               const size_t& size,
                                const uint32_t& time_stamp,
                                const int64_t& ntp_time,
                                const int64_t& render_time)
 {
   MutexAutoLock lock(mCallbackMutex);
   CaptureEngine capEng = static_cast<CaptureEngine>(capEngine);
   if (Callback(capEng, capId)) {
     unsigned char* image = shmem.get<unsigned char>();
--- a/dom/media/systemservices/CamerasChild.h
+++ b/dom/media/systemservices/CamerasChild.h
@@ -80,17 +80,17 @@ class CamerasChild final : public PCamer
 public:
   // We are owned by the PBackground thread only. CamerasSingleton
   // takes a non-owning reference.
   NS_INLINE_DECL_REFCOUNTING(CamerasChild)
 
   // IPC messages recevied, received on the PBackground thread
   // these are the actual callbacks with data
   virtual bool RecvDeliverFrame(const int&, const int&, mozilla::ipc::Shmem&&,
-                                const int&, const uint32_t&, const int64_t&,
+                                const size_t&, const uint32_t&, const int64_t&,
                                 const int64_t&) override;
   virtual bool RecvFrameSizeChange(const int&, const int&,
                                    const int& w, const int& h) override;
 
   // these are response messages to our outgoing requests
   virtual bool RecvReplyNumberOfCaptureDevices(const int&) override;
   virtual bool RecvReplyNumberOfCapabilities(const int&) override;
   virtual bool RecvReplyAllocateCaptureDevice(const int&) override;
@@ -154,19 +154,19 @@ private:
   // The monitor below isn't sufficient for this, as it will drop
   // the lock when Wait-ing for a response, allowing us to send a new
   // request. The Notify on receiving the response will then unblock
   // both waiters and one will be guaranteed to get the wrong result.
   // Take this one before taking mReplyMonitor.
   Mutex mRequestMutex;
   // Hold to wait for an async response to our calls
   Monitor mReplyMonitor;
-  // Async resposne valid?
+  // Async response valid?
   bool mReceivedReply;
-  // Aynsc reponses data contents;
+  // Async responses data contents;
   bool mReplySuccess;
   int mReplyInteger;
   webrtc::CaptureCapability mReplyCapability;
   nsCString mReplyDeviceName;
   nsCString mReplyDeviceID;
 };
 
 } // namespace camera
--- a/dom/media/systemservices/CamerasParent.cpp
+++ b/dom/media/systemservices/CamerasParent.cpp
@@ -11,16 +11,18 @@
 
 #include "mozilla/Assertions.h"
 #include "mozilla/unused.h"
 #include "mozilla/Logging.h"
 #include "mozilla/ipc/BackgroundParent.h"
 #include "nsThreadUtils.h"
 #include "nsXPCOM.h"
 
+#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
+
 #undef LOG
 #undef LOG_ENABLED
 mozilla::LazyLogModule gCamerasParentLog("CamerasParent");
 #define LOG(args) MOZ_LOG(gCamerasParentLog, mozilla::LogLevel::Debug, args)
 #define LOG_ENABLED() MOZ_LOG_TEST(gCamerasParentLog, mozilla::LogLevel::Debug)
 
 namespace mozilla {
 namespace camera {
@@ -85,17 +87,17 @@ CallbackHelper::FrameSizeChange(unsigned
 
 class DeliverFrameRunnable : public nsRunnable {
 public:
   DeliverFrameRunnable(CamerasParent *aParent,
                        CaptureEngine engine,
                        int cap_id,
                        ShmemBuffer buffer,
                        unsigned char* altbuffer,
-                       int size,
+                       size_t size,
                        uint32_t time_stamp,
                        int64_t ntp_time,
                        int64_t render_time)
     : mParent(aParent), mCapEngine(engine), mCapId(cap_id), mBuffer(Move(buffer)),
       mSize(size), mTimeStamp(time_stamp), mNtpTime(ntp_time),
       mRenderTime(render_time) {
     // No ShmemBuffer (of the right size) was available, so make an
     // extra buffer here.  We have no idea when we are going to run and
@@ -131,17 +133,17 @@ public:
   }
 
 private:
   RefPtr<CamerasParent> mParent;
   CaptureEngine mCapEngine;
   int mCapId;
   ShmemBuffer mBuffer;
   mozilla::UniquePtr<unsigned char[]> mAlternateBuffer;
-  int mSize;
+  size_t mSize;
   uint32_t mTimeStamp;
   int64_t mNtpTime;
   int64_t mRenderTime;
   int mResult;
 };
 
 NS_IMPL_ISUPPORTS(CamerasParent, nsIObserver)
 
@@ -227,17 +229,17 @@ CamerasParent::StopVideoCapture()
   }
 }
 
 int
 CamerasParent::DeliverFrameOverIPC(CaptureEngine cap_engine,
                                    int cap_id,
                                    ShmemBuffer buffer,
                                    unsigned char* altbuffer,
-                                   int size,
+                                   size_t size,
                                    uint32_t time_stamp,
                                    int64_t ntp_time,
                                    int64_t render_time)
 {
   // No ShmemBuffers were available, so construct one now of the right size
   // and copy into it. That is an extra copy, but we expect this to be
   // the exceptional case, because we just assured the next call *will* have a
   // buffer of the right size.
@@ -276,17 +278,17 @@ CamerasParent::DeliverFrameOverIPC(Captu
 ShmemBuffer
 CamerasParent::GetBuffer(size_t aSize)
 {
   return mShmemPool.GetIfAvailable(aSize);
 }
 
 int
 CallbackHelper::DeliverFrame(unsigned char* buffer,
-                             int size,
+                             size_t size,
                              uint32_t time_stamp,
                              int64_t ntp_time,
                              int64_t render_time,
                              void *handle)
 {
   // Get a shared memory buffer to copy the frame data into
   ShmemBuffer shMemBuffer = mParent->GetBuffer(size);
   if (!shMemBuffer.Valid()) {
@@ -305,16 +307,27 @@ CallbackHelper::DeliverFrame(unsigned ch
                              Move(shMemBuffer), buffer, size, time_stamp,
                              ntp_time, render_time);
   MOZ_ASSERT(mParent);
   nsIThread* thread = mParent->GetBackgroundThread();
   MOZ_ASSERT(thread != nullptr);
   thread->Dispatch(runnable, NS_DISPATCH_NORMAL);
   return 0;
 }
+// XXX!!! FIX THIS -- we should move to pure DeliverI420Frame
+int
+CallbackHelper::DeliverI420Frame(const webrtc::I420VideoFrame& webrtc_frame)
+{
+  return DeliverFrame(const_cast<uint8_t*>(webrtc_frame.buffer(webrtc::kYPlane)),
+                      CalcBufferSize(webrtc::kI420, webrtc_frame.width(), webrtc_frame.height()),
+                      webrtc_frame.timestamp(),
+                      webrtc_frame.ntp_time_ms(),
+                      webrtc_frame.render_time_ms(),
+                      (void*) webrtc_frame.native_handle());
+}
 
 bool
 CamerasParent::RecvReleaseFrame(mozilla::ipc::Shmem&& s) {
   mShmemPool.Put(ShmemBuffer(s));
   return true;
 }
 
 bool
--- a/dom/media/systemservices/CamerasParent.h
+++ b/dom/media/systemservices/CamerasParent.h
@@ -36,21 +36,22 @@ public:
   CallbackHelper(CaptureEngine aCapEng, int aCapId, CamerasParent *aParent)
     : mCapEngine(aCapEng), mCapturerId(aCapId), mParent(aParent) {};
 
   // ViEExternalRenderer implementation. These callbacks end up
   // running on the VideoCapture thread.
   virtual int FrameSizeChange(unsigned int w, unsigned int h,
                               unsigned int streams) override;
   virtual int DeliverFrame(unsigned char* buffer,
-                           int size,
+                           size_t size,
                            uint32_t time_stamp,
                            int64_t ntp_time,
                            int64_t render_time,
                            void *handle) override;
+  virtual int DeliverI420Frame(const webrtc::I420VideoFrame& webrtc_frame) override;
   virtual bool IsTextureSupported() override { return false; };
 
   friend CamerasParent;
 
 private:
   CaptureEngine mCapEngine;
   int mCapturerId;
   CamerasParent *mParent;
@@ -103,17 +104,17 @@ public:
                               || !mWebRTCAlive; };
   ShmemBuffer GetBuffer(size_t aSize);
 
   // helper to forward to the PBackground thread
   int DeliverFrameOverIPC(CaptureEngine capEng,
                           int cap_id,
                           ShmemBuffer buffer,
                           unsigned char* altbuffer,
-                          int size,
+                          size_t size,
                           uint32_t time_stamp,
                           int64_t ntp_time,
                           int64_t render_time);
 
 
   CamerasParent();
 
 protected:
--- a/dom/media/systemservices/LoadManager.cpp
+++ b/dom/media/systemservices/LoadManager.cpp
@@ -165,24 +165,16 @@ LoadManagerSingleton::LoadHasChanged(web
 }
 
 void
 LoadManagerSingleton::AddObserver(webrtc::CPULoadStateObserver * aObserver)
 {
   LOG(("LoadManager - Adding Observer"));
   MutexAutoLock lock(mLock);
   mObservers.AppendElement(aObserver);
-  if (mObservers.Length() == 1) {
-    if (!mLoadMonitor) {
-      mLoadMonitor = new LoadMonitor(mLoadMeasurementInterval);
-      mLoadMonitor->Init(mLoadMonitor);
-      mLoadMonitor->SetLoadChangeCallback(this);
-      mLastStateChange = TimeStamp::Now();
-    }
-  }
 }
 
 void
 LoadManagerSingleton::RemoveObserver(webrtc::CPULoadStateObserver * aObserver)
 {
   LOG(("LoadManager - Removing Observer"));
   MutexAutoLock lock(mLock);
   if (!mObservers.RemoveElement(aObserver)) {
--- a/dom/media/systemservices/MediaUtils.h
+++ b/dom/media/systemservices/MediaUtils.h
@@ -5,16 +5,17 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_MediaUtils_h
 #define mozilla_MediaUtils_h
 
 #include "nsAutoPtr.h"
 #include "nsThreadUtils.h"
 #include "nsIAsyncShutdown.h"
+#include "base/task.h"
 
 namespace mozilla {
 namespace media {
 
 /*
  * media::Pledge - A promise-like pattern for c++ that takes lambda functions.
  *
  * Asynchronous APIs that proxy to another thread or to the chrome process and
--- a/dom/media/systemservices/PCameras.ipdl
+++ b/dom/media/systemservices/PCameras.ipdl
@@ -22,17 +22,17 @@ struct CaptureCapability
 async protocol PCameras
 {
   manager PBackground;
 
 child:
   async FrameSizeChange(int capEngine, int cap_id, int w, int h);
   // transfers ownership of |buffer| from parent to child
   async DeliverFrame(int capEngine, int cap_id,
-                     Shmem buffer, int size, uint32_t time_stamp,
+                     Shmem buffer, size_t size, uint32_t time_stamp,
                      int64_t ntp_time, int64_t render_time);
   async ReplyNumberOfCaptureDevices(int numdev);
   async ReplyNumberOfCapabilities(int numdev);
   async ReplyAllocateCaptureDevice(int numdev);
   async ReplyGetCaptureCapability(CaptureCapability cap);
   async ReplyGetCaptureDevice(nsCString device_name, nsCString device_id);
   async ReplyFailure();
   async ReplySuccess();
--- a/dom/media/systemservices/moz.build
+++ b/dom/media/systemservices/moz.build
@@ -21,16 +21,21 @@ if CONFIG['MOZ_WEBRTC']:
         'LoadManagerFactory.cpp',
         'LoadMonitor.cpp',
         'ShmemPool.cpp',
     ]
     LOCAL_INCLUDES += [
         '/media/webrtc/signaling',
         '/media/webrtc/trunk',
     ]
+if CONFIG['OS_TARGET'] == 'WINNT':
+    DEFINES['WEBRTC_WIN'] = True
+else:
+    DEFINES['WEBRTC_POSIX'] = True
+
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gonk'):
     EXPORTS += [
         'OpenSLESProvider.h'
     ]
     UNIFIED_SOURCES += [
         'OpenSLESProvider.cpp',
     ]
--- a/dom/media/tests/mochitest/mochitest.ini
+++ b/dom/media/tests/mochitest/mochitest.ini
@@ -80,17 +80,17 @@ skip-if = toolkit == 'gonk' || buildapp 
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || (android_version == '18' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_basicAudioVideoNoBundle.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || (android_version == '18' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_basicAudioVideoNoBundleNoRtcpMux.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || android_version == '18' # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_basicAudioVideoNoRtcpMux.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || android_version == '18' # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_basicVideo.html]
-skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g(Bug 960442, video support for WebRTC is disabled on b2g)
+skip-if = toolkit == 'gonk' || buildapp == 'mulet' || (android_version == '18' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_basicScreenshare.html]
 # no screenshare on b2g/android
 # frequent timeouts/crashes on e10s (bug 1048455)
 skip-if = buildapp == 'b2g' || buildapp == 'mulet' || toolkit == 'android' || e10s # Bug 1141029 Mulet parity with B2G Desktop for TC
 [test_peerConnection_basicWindowshare.html]
 # no screenshare on b2g/android
 # frequent timeouts/crashes on e10s (bug 1048455)
 skip-if = buildapp == 'b2g' || buildapp == 'mulet' || toolkit == 'android' || e10s # Bug 1141029 Mulet parity with B2G Desktop for TC
@@ -105,17 +105,17 @@ skip-if = toolkit == 'gonk' || buildapp 
 skip-if = toolkit == 'gonk' # B2G emulator is too slow to handle a two-way audio call reliably
 [test_peerConnection_bug1042791.html]
 skip-if = buildapp == 'b2g' || buildapp == 'mulet' || os == 'android' # bug 1043403 # Bug 1141029 Mulet parity with B2G Desktop for TC
 [test_peerConnection_bug1064223.html]
 [test_peerConnection_capturedVideo.html]
 tags=capturestream
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || android_version == '18' # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_captureStream_canvas_2d.html]
-skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g(Bug 960442, video support for WebRTC is disabled on b2g)
+skip-if = toolkit == 'gonk' || buildapp == 'mulet' || (android_version == '18' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_captureStream_canvas_webgl.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g(Bug 960442, video support for WebRTC is disabled on b2g)
 # [test_peerConnection_certificates.html] # bug 1180968
 # skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g (Bug 1059867)
 [test_peerConnection_close.html]
 [test_peerConnection_closeDuringIce.html]
 [test_peerConnection_errorCallbacks.html]
 [test_peerConnection_iceFailure.html]
@@ -130,18 +130,18 @@ skip-if = toolkit == 'gonk' # B2G emulat
 skip-if = toolkit == 'gonk' # B2G emulator is too slow to handle a two-way audio call reliably
 [test_peerConnection_offerRequiresReceiveAudio.html]
 [test_peerConnection_offerRequiresReceiveVideo.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g(Bug 960442, video support for WebRTC is disabled on b2g)
 [test_peerConnection_offerRequiresReceiveVideoAudio.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || (android_version == '18' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_promiseSendOnly.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || (android_version == '18' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
-[test_peerConnection_relayOnly.html]
-skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g(Bug 960442, video support for WebRTC is disabled on b2g)
+#[test_peerConnection_relayOnly.html]
+#skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g(Bug 960442, video support for WebRTC is disabled on b2g)
 [test_peerConnection_callbacks.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || (android_version == '18' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_replaceTrack.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || android_version == '18' # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_syncSetDescription.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || (android_version == '18' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_setLocalAnswerInHaveLocalOffer.html]
 [test_peerConnection_setLocalAnswerInStable.html]
--- a/dom/media/tests/mochitest/pc.js
+++ b/dom/media/tests/mochitest/pc.js
@@ -1513,24 +1513,31 @@ PeerConnectionWrapper.prototype = {
         var res = stats[key];
         // validate stats
         ok(res.id == key, "Coherent stats id");
         var nowish = Date.now() + 1000;        // TODO: clock drift observed
         var minimum = this.whenCreated - 1000; // on Windows XP (Bug 979649)
         if (isWinXP) {
           todo(false, "Can't reliably test rtcp timestamps on WinXP (Bug 979649)");
         } else if (!twoMachines) {
-          ok(res.timestamp >= minimum,
-             "Valid " + (res.isRemote? "rtcp" : "rtp") + " timestamp " +
-                 res.timestamp + " >= " + minimum + " (" +
-                 (res.timestamp - minimum) + " ms)");
-          ok(res.timestamp <= nowish,
-             "Valid " + (res.isRemote? "rtcp" : "rtp") + " timestamp " +
-                 res.timestamp + " <= " + nowish + " (" +
-                 (res.timestamp - nowish) + " ms)");
+          // Bug 1225729: On android, sometimes the first RTCP of the first
+          // test run gets this value, likely because no RTP has been sent yet.
+          if (res.timestamp != 2085978496000) {
+            ok(res.timestamp >= minimum,
+               "Valid " + (res.isRemote? "rtcp" : "rtp") + " timestamp " +
+                   res.timestamp + " >= " + minimum + " (" +
+                   (res.timestamp - minimum) + " ms)");
+            ok(res.timestamp <= nowish,
+               "Valid " + (res.isRemote? "rtcp" : "rtp") + " timestamp " +
+                   res.timestamp + " <= " + nowish + " (" +
+                   (res.timestamp - nowish) + " ms)");
+          } else {
+            info("Bug 1225729: Uninitialized timestamp (" + res.timestamp +
+                 "), should be >=" + minimum + " and <= " + nowish);
+          }
         }
         if (!res.isRemote) {
           counters[res.type] = toNum(counters[res.type]) + 1;
 
           switch (res.type) {
             case "inboundrtp":
             case "outboundrtp": {
               // ssrc is a 32 bit number returned as a string by spec
--- a/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp
+++ b/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp
@@ -271,29 +271,29 @@ MediaEngineRemoteVideoSource::FrameSizeC
   mWidth = w;
   mHeight = h;
   LOG(("MediaEngineRemoteVideoSource Video FrameSizeChange: %ux%u", w, h));
   return 0;
 }
 
 int
 MediaEngineRemoteVideoSource::DeliverFrame(unsigned char* buffer,
-                                           int size,
+                                           size_t size,
                                            uint32_t time_stamp,
                                            int64_t ntp_time,
                                            int64_t render_time,
                                            void *handle)
 {
   // Check for proper state.
   if (mState != kStarted) {
     LOG(("DeliverFrame: video not started"));
     return 0;
   }
 
-  if (mWidth*mHeight + 2*(((mWidth+1)/2)*((mHeight+1)/2)) != size) {
+  if ((size_t) (mWidth*mHeight + 2*(((mWidth+1)/2)*((mHeight+1)/2))) != size) {
     MOZ_ASSERT(false, "Wrong size frame in DeliverFrame!");
     return 0;
   }
 
   // Create a video frame and append it to the track.
   RefPtr<layers::PlanarYCbCrImage> image = mImageContainer->CreatePlanarYCbCrImage();
 
   uint8_t* frame = static_cast<uint8_t*> (buffer);
--- a/dom/media/webrtc/MediaEngineRemoteVideoSource.h
+++ b/dom/media/webrtc/MediaEngineRemoteVideoSource.h
@@ -33,36 +33,42 @@
 // WebRTC library includes follow
 #include "webrtc/common.h"
 #include "webrtc/video_engine/include/vie_capture.h"
 #include "webrtc/video_engine/include/vie_render.h"
 #include "CamerasChild.h"
 
 #include "NullTransport.h"
 
+namespace webrtc {
+class I420VideoFrame;
+}
+
 namespace mozilla {
 
 /**
  * The WebRTC implementation of the MediaEngine interface.
  */
 class MediaEngineRemoteVideoSource : public MediaEngineCameraVideoSource,
                                      public webrtc::ExternalRenderer
 {
 public:
   NS_DECL_THREADSAFE_ISUPPORTS
 
   // ExternalRenderer
   virtual int FrameSizeChange(unsigned int w, unsigned int h,
                               unsigned int streams) override;
   virtual int DeliverFrame(unsigned char* buffer,
-                           int size,
+                           size_t size,
                            uint32_t time_stamp,
                            int64_t ntp_time,
                            int64_t render_time,
                            void *handle) override;
+  // XXX!!!! FIX THIS
+  virtual int DeliverI420Frame(const webrtc::I420VideoFrame& webrtc_frame) override { return 0; };
   virtual bool IsTextureSupported() override { return false; };
 
   // MediaEngineCameraVideoSource
   MediaEngineRemoteVideoSource(int aIndex, mozilla::camera::CaptureEngine aCapEngine,
                                dom::MediaSourceEnum aMediaSource,
                                const char* aMonitorName = "RemoteVideo.Monitor");
 
   virtual nsresult Allocate(const dom::MediaTrackConstraints& aConstraints,
--- a/dom/media/webrtc/MediaEngineWebRTC.cpp
+++ b/dom/media/webrtc/MediaEngineWebRTC.cpp
@@ -246,17 +246,17 @@ MediaEngineWebRTC::EnumerateAudioDevices
 #ifdef MOZ_WIDGET_ANDROID
   jobject context = mozilla::AndroidBridge::Bridge()->GetGlobalContextRef();
 
   // get the JVM
   JavaVM* jvm;
   JNIEnv* const env = jni::GetEnvForThread();
   MOZ_ALWAYS_TRUE(!env->GetJavaVM(&jvm));
 
-  if (webrtc::VoiceEngine::SetAndroidObjects(jvm, env, (void*)context) != 0) {
+  if (webrtc::VoiceEngine::SetAndroidObjects(jvm, (void*)context) != 0) {
     LOG(("VoiceEngine:SetAndroidObjects Failed"));
     return;
   }
 #endif
 
   if (!mVoiceEngine) {
     mVoiceEngine = webrtc::VoiceEngine::Create();
     if (!mVoiceEngine) {
--- a/dom/media/webrtc/moz.build
+++ b/dom/media/webrtc/moz.build
@@ -15,16 +15,20 @@ XPIDL_MODULE = 'content_webrtc'
 EXPORTS += [
     'MediaEngine.h',
     'MediaEngineCameraVideoSource.h',
     'MediaEngineDefault.h',
     'MediaTrackConstraints.h',
 ]
 
 if CONFIG['MOZ_WEBRTC']:
+    if CONFIG['OS_TARGET'] == 'WINNT':
+        DEFINES['WEBRTC_WIN'] = True
+    else:
+        DEFINES['WEBRTC_POSIX'] = True
     EXPORTS += ['AudioOutputObserver.h',
                 'MediaEngineRemoteVideoSource.h',
                 'MediaEngineWebRTC.h']
     EXPORTS.mozilla.dom += [ 'RTCIdentityProviderRegistrar.h' ]
     UNIFIED_SOURCES += [
         'MediaEngineCameraVideoSource.cpp',
         'MediaEngineRemoteVideoSource.cpp',
         'MediaEngineTabVideoSource.cpp',
--- a/dom/media/webspeech/synth/SpeechSynthesis.cpp
+++ b/dom/media/webspeech/synth/SpeechSynthesis.cpp
@@ -187,17 +187,17 @@ SpeechSynthesis::Cancel()
 
 void
 SpeechSynthesis::Pause()
 {
   if (Paused()) {
     return;
   }
 
-  if (mCurrentTask &&
+  if (mCurrentTask && !mSpeechQueue.IsEmpty() &&
       mSpeechQueue.ElementAt(0)->GetState() != SpeechSynthesisUtterance::STATE_ENDED) {
     mCurrentTask->Pause();
   } else {
     mHoldQueue = true;
   }
 }
 
 void
--- a/dom/media/webspeech/synth/windows/SapiService.cpp
+++ b/dom/media/webspeech/synth/windows/SapiService.cpp
@@ -162,16 +162,17 @@ SapiService::SpeechEventCallback(WPARAM 
         break;
       }
     }
   }
 }
 
 NS_INTERFACE_MAP_BEGIN(SapiService)
   NS_INTERFACE_MAP_ENTRY(nsISpeechService)
+  NS_INTERFACE_MAP_ENTRY(nsIObserver)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsISpeechService)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_ADDREF(SapiService)
 NS_IMPL_RELEASE(SapiService)
 
 SapiService::SapiService()
   : mInitialized(false)
@@ -359,16 +360,23 @@ SapiService::Speak(const nsAString& aTex
 
 NS_IMETHODIMP
 SapiService::GetServiceType(SpeechServiceType* aServiceType)
 {
   *aServiceType = nsISpeechService::SERVICETYPE_INDIRECT_AUDIO;
   return NS_OK;
 }
 
+NS_IMETHODIMP
+SapiService::Observe(nsISupports* aSubject, const char* aTopic,
+                     const char16_t* aData)
+{
+  return NS_OK;
+}
+
 SapiService*
 SapiService::GetInstance()
 {
   MOZ_ASSERT(NS_IsMainThread());
   if (XRE_GetProcessType() != GeckoProcessType_Default) {
     MOZ_ASSERT(false,
                "SapiService can only be started on main gecko process");
     return nullptr;
--- a/dom/media/webspeech/synth/windows/SapiService.h
+++ b/dom/media/webspeech/synth/windows/SapiService.h
@@ -4,33 +4,36 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_SapiService_h
 #define mozilla_dom_SapiService_h
 
 #include "nsAutoPtr.h"
 #include "nsISpeechService.h"
+#include "nsIObserver.h"
 #include "nsRefPtrHashtable.h"
 #include "nsTArray.h"
 #include "mozilla/StaticPtr.h"
 
 #include <windows.h>
 #include <sapi.h>
 
 namespace mozilla {
 namespace dom {
 
 class SapiCallback;
 
 class SapiService final : public nsISpeechService
+                        , public nsIObserver
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSISPEECHSERVICE
+  NS_DECL_NSIOBSERVER
 
   SapiService();
   bool Init();
 
   static SapiService* GetInstance();
   static already_AddRefed<SapiService> GetInstanceForService();
 
   static void Shutdown();
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -577,19 +577,16 @@ nsresult nsNPAPIPluginInstance::SetWindo
   return NS_OK;
 }
 
 nsresult
 nsNPAPIPluginInstance::NewStreamFromPlugin(const char* type, const char* target,
                                            nsIOutputStream* *result)
 {
   nsPluginStreamToFile* stream = new nsPluginStreamToFile(target, mOwner);
-  if (!stream)
-    return NS_ERROR_OUT_OF_MEMORY;
-
   return stream->QueryInterface(kIOutputStreamIID, (void**)result);
 }
 
 nsresult
 nsNPAPIPluginInstance::NewStreamListener(const char* aURL, void* notifyData,
                                          nsNPAPIPluginStreamListener** listener)
 {
   RefPtr<nsNPAPIPluginStreamListener> sl = new nsNPAPIPluginStreamListener(this, notifyData, aURL);
--- a/dom/plugins/base/nsPluginHost.cpp
+++ b/dom/plugins/base/nsPluginHost.cpp
@@ -2222,19 +2222,16 @@ nsresult nsPluginHost::ScanPluginsDirect
 
         // Mark aPluginsChanged so pluginreg is rewritten
         *aPluginsChanged = true;
         continue;
       }
 
       pluginTag = new nsPluginTag(&info, fileModTime, fromExtension);
       pluginFile.FreePluginInfo(info);
-      if (!pluginTag)
-        return NS_ERROR_OUT_OF_MEMORY;
-
       pluginTag->mLibrary = library;
       uint32_t state;
       rv = pluginTag->GetBlocklistState(&state);
       NS_ENSURE_SUCCESS(rv, rv);
 
       // If the blocklist says it is risky and we have never seen this
       // plugin before, then disable it.
       // If the blocklist says this is an outdated plugin, warn about
@@ -3314,18 +3311,16 @@ nsPluginHost::RemoveCachedPluginsInfo(co
 
 #ifdef XP_WIN
 nsresult
 nsPluginHost::EnsurePrivateDirServiceProvider()
 {
   if (!mPrivateDirServiceProvider) {
     nsresult rv;
     mPrivateDirServiceProvider = new nsPluginDirServiceProvider();
-    if (!mPrivateDirServiceProvider)
-      return NS_ERROR_OUT_OF_MEMORY;
     nsCOMPtr<nsIDirectoryService> dirService(do_GetService(kDirectoryServiceContractID, &rv));
     if (NS_FAILED(rv))
       return rv;
     rv = dirService->RegisterProvider(mPrivateDirServiceProvider);
     if (NS_FAILED(rv))
       return rv;
   }
   return NS_OK;
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -1145,32 +1145,26 @@ void nsPluginInstanceOwner::AddToCARefre
   if (NS_SUCCEEDED(mInstance->GetMIMEType(&mime)) && mime &&
       nsPluginHost::GetSpecialType(nsDependentCString(mime)) ==
       nsPluginHost::eSpecialType_Flash) {
     return;
   }
 
   if (!sCARefreshListeners) {
     sCARefreshListeners = new nsTArray<nsPluginInstanceOwner*>();
-    if (!sCARefreshListeners) {
-      return;
-    }
   }
 
   if (sCARefreshListeners->Contains(this)) {
     return;
   }
 
   sCARefreshListeners->AppendElement(this);
 
   if (!sCATimer) {
     sCATimer = new nsCOMPtr<nsITimer>();
-    if (!sCATimer) {
-      return;
-    }
   }
 
   if (sCARefreshListeners->Length() == 1) {
     *sCATimer = do_CreateInstance("@mozilla.org/timer;1");
     (*sCATimer)->InitWithFuncCallback(CARefresh, nullptr,
                    DEFAULT_REFRESH_RATE, nsITimer::TYPE_REPEATING_SLACK);
   }
 }
--- a/dom/plugins/base/nsPluginNativeWindow.cpp
+++ b/dom/plugins/base/nsPluginNativeWindow.cpp
@@ -36,17 +36,17 @@ nsPluginNativeWindowPLATFORM::nsPluginNa
 nsPluginNativeWindowPLATFORM::~nsPluginNativeWindowPLATFORM() 
 {
 }
 
 nsresult PLUG_NewPluginNativeWindow(nsPluginNativeWindow ** aPluginNativeWindow)
 {
   NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
   *aPluginNativeWindow = new nsPluginNativeWindowPLATFORM();
-  return *aPluginNativeWindow ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+  return NS_OK;
 }
 
 nsresult PLUG_DeletePluginNativeWindow(nsPluginNativeWindow * aPluginNativeWindow)
 {
   NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
   nsPluginNativeWindowPLATFORM *p = (nsPluginNativeWindowPLATFORM *)aPluginNativeWindow;
   delete p;
   return NS_OK;
--- a/dom/plugins/base/nsPluginNativeWindowGtk.cpp
+++ b/dom/plugins/base/nsPluginNativeWindowGtk.cpp
@@ -52,17 +52,17 @@ nsPluginNativeWindowGtk::~nsPluginNative
     gtk_widget_destroy(mSocketWidget);
   }
 }
 
 nsresult PLUG_NewPluginNativeWindow(nsPluginNativeWindow ** aPluginNativeWindow)
 {
   NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
   *aPluginNativeWindow = new nsPluginNativeWindowGtk();
-  return *aPluginNativeWindow ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+  return NS_OK;
 }
 
 nsresult PLUG_DeletePluginNativeWindow(nsPluginNativeWindow * aPluginNativeWindow)
 {
   NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
   nsPluginNativeWindowGtk *p = (nsPluginNativeWindowGtk *)aPluginNativeWindow;
   delete p;
   return NS_OK;
--- a/dom/plugins/base/nsPluginNativeWindowQt.cpp
+++ b/dom/plugins/base/nsPluginNativeWindowQt.cpp
@@ -57,17 +57,17 @@ nsPluginNativeWindowQt::~nsPluginNativeW
   fprintf(stderr,"\n\n\nDestoying plugin native window %p\n\n\n", (void *) this);
 #endif
 }
 
 nsresult PLUG_NewPluginNativeWindow(nsPluginNativeWindow **aPluginNativeWindow)
 {
   NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
   *aPluginNativeWindow = new nsPluginNativeWindowQt();
-  return *aPluginNativeWindow ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+  return NS_OK;
 }
 
 nsresult PLUG_DeletePluginNativeWindow(nsPluginNativeWindow * aPluginNativeWindow)
 {
   NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
   nsPluginNativeWindowQt *p = (nsPluginNativeWindowQt *)aPluginNativeWindow;
   delete p;
   return NS_OK;
--- a/dom/plugins/base/nsPluginNativeWindowWin.cpp
+++ b/dom/plugins/base/nsPluginNativeWindowWin.cpp
@@ -570,23 +570,21 @@ nsPluginNativeWindowWin::GetPluginWindow
   PluginWindowEvent *event;
 
   // We have the ability to alloc if needed in case in the future some plugin
   // should post multiple PostMessages. However, this could lead to many
   // alloc's per second which could become a performance issue. See bug 169247.
   if (!mCachedPluginWindowEvent)
   {
     event = new PluginWindowEvent();
-    if (!event) return nullptr;
     mCachedPluginWindowEvent = event;
   }
   else if (mCachedPluginWindowEvent->InUse())
   {
     event = new PluginWindowEvent();
-    if (!event) return nullptr;
   }
   else
   {
     event = mCachedPluginWindowEvent;
   }
 
   event->Init(mWeakRef, aWnd, aMsg, aWParam, aLParam);
   return event;
@@ -734,18 +732,17 @@ nsresult nsPluginNativeWindowWin::UndoSu
   return NS_OK;
 }
 
 nsresult PLUG_NewPluginNativeWindow(nsPluginNativeWindow ** aPluginNativeWindow)
 {
   NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
 
   *aPluginNativeWindow = new nsPluginNativeWindowWin();
-
-  return *aPluginNativeWindow ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+  return NS_OK;
 }
 
 nsresult PLUG_DeletePluginNativeWindow(nsPluginNativeWindow * aPluginNativeWindow)
 {
   NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
   nsPluginNativeWindowWin *p = (nsPluginNativeWindowWin *)aPluginNativeWindow;
   delete p;
   return NS_OK;
--- a/dom/plugins/base/nsPluginStreamListenerPeer.cpp
+++ b/dom/plugins/base/nsPluginStreamListenerPeer.cpp
@@ -730,22 +730,17 @@ nsPluginStreamListenerPeer::RequestRead(
     converter = this;
     // set current stream offset equal to the first offset in the range list
     // it will work for single byte range request
     // for multy range we'll reset it in ODA
     SetStreamOffset(rangeList->offset);
   } else {
     nsWeakPtr weakpeer =
     do_GetWeakReference(static_cast<nsISupportsWeakReference*>(this));
-    nsPluginByteRangeStreamListener *brrListener =
-    new nsPluginByteRangeStreamListener(weakpeer);
-    if (brrListener)
-      converter = brrListener;
-    else
-      return NS_ERROR_OUT_OF_MEMORY;
+    converter = new nsPluginByteRangeStreamListener(weakpeer);
   }
 
   mPendingRequests += numRequests;
 
   nsCOMPtr<nsISupportsPRUint32> container = do_CreateInstance(NS_SUPPORTS_PRUINT32_CONTRACTID, &rv);
   if (NS_FAILED(rv))
     return rv;
   rv = container->SetData(MAGIC_REQUEST_CONTEXT);
--- a/dom/plugins/ipc/PluginInstanceChild.cpp
+++ b/dom/plugins/ipc/PluginInstanceChild.cpp
@@ -2156,19 +2156,16 @@ PluginInstanceChild::FlashThrottleMessag
                                           WPARAM aWParam,
                                           LPARAM aLParam,
                                           bool isWindowed)
 {
     // We reuse ChildAsyncCall so we get the cancelation work
     // that's done in Destroy.
     FlashThrottleAsyncMsg* task = new FlashThrottleAsyncMsg(this,
         aWnd, aMsg, aWParam, aLParam, isWindowed);
-    if (!task)
-        return; 
-
     {
         MutexAutoLock lock(mAsyncCallMutex);
         mPendingAsyncCalls.AppendElement(task);
     }
     MessageLoop::current()->PostDelayedTask(FROM_HERE,
         task, kFlashWMUSERMessageThrottleDelayMs);
 }
 
--- a/dom/plugins/ipc/PluginInstanceParent.cpp
+++ b/dom/plugins/ipc/PluginInstanceParent.cpp
@@ -999,17 +999,17 @@ PluginInstanceParent::NPP_SetWindow(cons
         mShWidth = window.width * scaleFactor;
         mShHeight = window.height * scaleFactor;
     }
 #endif
 
 #if defined(MOZ_X11) && defined(XP_UNIX) && !defined(XP_MACOSX)
     const NPSetWindowCallbackStruct* ws_info =
       static_cast<NPSetWindowCallbackStruct*>(aWindow->ws_info);
-    window.visualID = ws_info->visual ? ws_info->visual->visualid : None;
+    window.visualID = ws_info->visual ? ws_info->visual->visualid : 0;
     window.colormap = ws_info->colormap;
 #endif
 
     if (!CallNPP_SetWindow(window)) {
         return NPERR_GENERIC_ERROR;
     }
 
     return NPERR_NO_ERROR;
@@ -1528,21 +1528,16 @@ PluginInstanceParent::GetActorForNPObjec
     }
 
     PluginScriptableObjectParent* actor;
     if (mScriptableObjects.Get(aObject, &actor)) {
         return actor;
     }
 
     actor = new PluginScriptableObjectParent(LocalObject);
-    if (!actor) {
-        NS_ERROR("Out of memory!");
-        return nullptr;
-    }
-
     if (!SendPPluginScriptableObjectConstructor(actor)) {
         NS_WARNING("Failed to send constructor message!");
         return nullptr;
     }
 
     actor->InitializeLocal(aObject);
     return actor;
 }
--- a/dom/plugins/test/testplugin/nptest.cpp
+++ b/dom/plugins/test/testplugin/nptest.cpp
@@ -773,18 +773,16 @@ NPP_New(NPMIMEType pluginType, NPP insta
   NPN_GetValue(instance, NPNVSupportsWindowless, &browserSupportsWindowless);
   if (!browserSupportsWindowless && !pluginSupportsWindowMode()) {
     printf("Windowless mode not supported by the browser, windowed mode not supported by the plugin!\n");
     return NPERR_GENERIC_ERROR;
   }
 
   // set up our our instance data
   InstanceData* instanceData = new InstanceData;
-  if (!instanceData)
-    return NPERR_OUT_OF_MEMORY_ERROR;
   instanceData->npp = instance;
   instanceData->streamMode = NP_ASFILEONLY;
   instanceData->testFunction = FUNCTION_NONE;
   instanceData->functionToFail = FUNCTION_NONE;
   instanceData->failureCode = 0;
   instanceData->callOnDestroy = nullptr;
   instanceData->streamChunkSize = 1024;
   instanceData->streamBuf = nullptr;
--- a/dom/presentation/provider/MulticastDNSDeviceProvider.cpp
+++ b/dom/presentation/provider/MulticastDNSDeviceProvider.cpp
@@ -170,19 +170,16 @@ MulticastDNSDeviceProvider::Init()
   nsresult rv;
 
   mMulticastDNS = do_GetService(DNSSERVICEDISCOVERY_CONTRACT_ID, &rv);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
   mWrappedListener = new DNSServiceWrappedListener();
-  if (NS_WARN_IF(!mWrappedListener)) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
   if (NS_WARN_IF(NS_FAILED(rv = mWrappedListener->SetListener(this)))) {
     return rv;
   }
 
   mPresentationServer = do_CreateInstance(TCP_PRESENTATION_SERVER_CONTACT_ID, &rv);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
--- a/dom/svg/test/mochitest.ini
+++ b/dom/svg/test/mochitest.ini
@@ -65,16 +65,17 @@ skip-if = true
 [test_pointer-events-3.xhtml]
 skip-if = android_version == '18' # bug 1147994
 [test_pointer-events-4.xhtml]
 [test_pointer-events-5.xhtml]
 [test_pointer-events-6.xhtml]
 [test_pointer-events-7.xhtml]
 [test_scientific.html]
 [test_selectSubString.xhtml]
+[test_stroke-hit-testing.xhtml]
 [test_stroke-linecap-hit-testing.xhtml]
 [test_SVGLengthList-2.xhtml]
 [test_SVGLengthList.xhtml]
 [test_SVGMatrix.xhtml]
 [test_SVG_namespace_ids.html]
 [test_SVGNumberList.xhtml]
 [test_SVGPathSegList.xhtml]
 [test_SVGPointList.xhtml]
new file mode 100644
--- /dev/null
+++ b/dom/svg/test/test_stroke-hit-testing.xhtml
@@ -0,0 +1,67 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=676001
+-->
+<head>
+  <title>Test hit-testing of stroke</title>
+  <style>
+
+:hover { stroke: lime; }
+
+  </style>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body onload="run()">
+<script class="testbody" type="text/javascript">
+<![CDATA[
+
+SimpleTest.waitForExplicitFinish();
+
+function run()
+{
+  var div = document.getElementById('div');
+  var line = document.getElementById('line');
+  var circle = document.getElementById('circle');
+  var offsetX = div.offsetLeft;
+  var offsetY = div.offsetTop;
+  var got;
+
+  // line
+  got = document.elementFromPoint(offsetX + 116, offsetY + 103);
+  is(got, line, 'Should hit line (1)');
+
+  got = document.elementFromPoint(offsetX + 123, offsetY + 108);
+  is(got, line, 'Should hit line (2)');
+
+  // circle
+  got = document.elementFromPoint(offsetX + 188, offsetY + 158);
+  is(got, circle, 'Should hit circle (1)');
+
+  got = document.elementFromPoint(offsetX + 185, offsetY + 162);
+  is(got, circle, 'Should hit circle (2)');
+
+  SimpleTest.finish();
+}
+
+]]>
+</script>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=676001">Mozilla Bug 676001</a>
+<p id="display"></p>
+<div id="content">
+
+  <div width="100%" height="1" id="div"></div>
+  <svg xmlns="http://www.w3.org/2000/svg" id="svg" width="500" height="300">
+    <line id="line" x1="100" y1="100" x2="600" y2="180"
+          stroke="red" stroke-width="40"/>
+    <!-- the circle test points need to be within the mochitest test harness
+         viewport for test content in order for elementFromPoint to work -->
+    <circle id="circle" cx="100" cy="150" r="100"
+            fill="none" stroke="red" stroke-width="40"/>
+  </svg>
+
+</div>
+<pre id="test">
+</pre>
+</body>
+</html>
--- a/dom/tests/mochitest/bugs/test_bug406375.html
+++ b/dom/tests/mochitest/bugs/test_bug406375.html
@@ -12,20 +12,16 @@ https://bugzilla.mozilla.org/show_bug.cg
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=406375">Mozilla Bug 406375</a>
 <p id="display"></p>
 <div id="content" style="display: none">
   
 </div>
 <pre id="test">
 <script type="application/javascript">
 
-if (navigator.platform.startsWith("Mac")) {
-  SimpleTest.expectAssertions(1);
-}
-
 /** Test for Bug 406375 **/
 
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   window.showModalDialog("file_bug406375.html");
   ok(true, "This test should not hang");
--- a/dom/tests/mochitest/chrome/chrome.ini
+++ b/dom/tests/mochitest/chrome/chrome.ini
@@ -6,16 +6,20 @@ support-files =
   DOMWindowCreated_content.html
   MozDomFullscreen_chrome.xul
   child_focus_frame.html
   file_DOM_element_instanceof.xul
   file_MozDomFullscreen.html
   file_bug799299.xul
   file_bug800817.xul
   file_bug830858.xul
+  file_bug1224790-1_modal.xul
+  file_bug1224790-1_nonmodal.xul
+  file_bug1224790-2_modal.xul
+  file_bug1224790-2_nonmodal.xul
   file_subscript_bindings.js
   focus_frameset.html
   focus_window2.xul
   fullscreen.xul
   queryCaretRectUnix.html
   queryCaretRectWin.html
   selectAtPoint.html
   sizemode_attribute.xul
@@ -27,16 +31,20 @@ support-files =
 
 [test_DOMWindowCreated.xul]
 [test_DOM_element_instanceof.xul]
 [test_activation.xul]
 [test_bug799299.xul]
 [test_bug800817.xul]
 [test_bug830396.xul]
 [test_bug830858.xul]
+[test_bug1224790-1.xul]
+skip-if = os != 'cocoa'
+[test_bug1224790-2.xul]
+skip-if = os != 'cocoa'
 [test_callback_wrapping.xul]
 [test_clonewrapper.xul]
 [test_cyclecollector.xul]
 [test_docshell_swap.xul]
 [test_focus.xul]
 skip-if = buildapp == 'mulet'
 [test_focus_docnav.xul]
 [test_focus_switchbinding.xul]
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/chrome/file_bug1224790-1_modal.xul
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
+<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1224790
+-->
+<dialog title="Mozilla Bug 1224790"
+        buttons="accept"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+
+  <!-- test results are displayed in the html:body -->
+  <body xmlns="http://www.w3.org/1999/xhtml">
+  </body>
+
+  <!-- test code goes here -->
+  <script type="application/javascript">
+  <![CDATA[
+  /** Test for Bug 1224790 **/
+
+  function runTests() {
+    window.openDialog('file_bug1224790-1_nonmodal.xul', '', 'dialog=no');
+  }
+
+  function nonModalClosed() {
+    window.close();
+    opener.wrappedJSObject.modalClosed();
+  }
+
+  SimpleTest.waitForFocus(runTests);
+  ]]>
+  </script>
+</dialog>
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/chrome/file_bug1224790-1_nonmodal.xul
@@ -0,0 +1,28 @@
+<?xml version="1.0"?>
+<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
+<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1224790
+-->
+<window title="Mozilla Bug 1224790"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+
+  <!-- test results are displayed in the html:body -->
+  <body xmlns="http://www.w3.org/1999/xhtml">
+  </body>
+
+  <!-- test code goes here -->
+  <script type="application/javascript">
+  <![CDATA[
+  /** Test for Bug 1224790 **/
+
+  function runTests() {
+    window.close();
+    opener.wrappedJSObject.nonModalClosed();
+  }
+
+  SimpleTest.waitForFocus(runTests);
+  ]]>
+  </script>
+</window>
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/chrome/file_bug1224790-2_modal.xul
@@ -0,0 +1,35 @@
+<?xml version="1.0"?>
+<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
+<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1224790
+-->
+<dialog title="Mozilla Bug 1224790"
+        buttons="accept"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+
+  <!-- test results are displayed in the html:body -->
+  <body xmlns="http://www.w3.org/1999/xhtml">
+  </body>
+
+  <!-- test code goes here -->
+  <script type="application/javascript">
+  <![CDATA[
+  /** Test for Bug 1224790 **/
+
+  var nonModal = null;
+
+  function runTests() {
+    nonModal = window.openDialog('file_bug1224790-2_nonmodal.xul', '', 'dialog=no');
+  }
+
+  function nonModalOpened() {
+    window.close();
+    nonModal.wrappedJSObject.modalClosed(opener);
+  }
+
+  SimpleTest.waitForFocus(runTests);
+  ]]>
+  </script>
+</dialog>
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/chrome/file_bug1224790-2_nonmodal.xul
@@ -0,0 +1,46 @@
+<?xml version="1.0"?>
+<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
+<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1224790
+-->
+<window title="Mozilla Bug 1224790"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+
+  <!-- test results are displayed in the html:body -->
+  <body xmlns="http://www.w3.org/1999/xhtml">
+  </body>
+
+  <!-- test code goes here -->
+  <script type="application/javascript">
+  <![CDATA[
+  /** Test for Bug 1224790 **/
+
+  function runTests() {
+    opener.wrappedJSObject.nonModalOpened()
+  }
+
+  function modalClosed(grandparent) {
+    // Request cycle collection to trigger destructor for parent modal window,
+    // that mutates mAncestorLink of this window.
+    const Ci = Components.interfaces;
+    const Cu = Components.utils;
+    var { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
+    var windowUtils = window.QueryInterface(Ci.nsIInterfaceRequestor).
+      getInterface(Ci.nsIDOMWindowUtils);
+
+    Services.obs.notifyObservers(null, "child-cc-request", null);
+    windowUtils.cycleCollect();
+
+    // Wait for a while.
+    setTimeout(function() {
+      window.close();
+      grandparent.wrappedJSObject.nonModalClosed();
+    }, 3000);
+  }
+
+  SimpleTest.waitForFocus(runTests);
+  ]]>
+  </script>
+</window>
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/chrome/test_bug1224790-1.xul
@@ -0,0 +1,58 @@
+<?xml version="1.0"?>
+<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
+<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1224790
+-->
+<window title="Mozilla Bug 1224790"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
+
+  <!-- test code goes here -->
+  <script type="application/javascript">
+  <![CDATA[
+
+  /** Test for Bug 1224790 **/
+  /*
+   * 1. Opens modal dialog
+   * 2. Open non-modal window from modal dialog
+   * 3. Close non-modal window
+   * 4. Close modal dialog
+   * 5. Click button to ensure mouse event is working
+   */
+
+  function startTest() {
+    window.openDialog('file_bug1224790-1_modal.xul', '', 'modal');
+  }
+
+  function modalClosed() {
+    SimpleTest.waitForFocus(gotFocus);
+  }
+
+  function gotFocus() {
+    var button = document.getElementById('button');
+    synthesizeMouseAtCenter(button, { type: 'mousemove' }, window);
+    // The bug is not reproducible with synthesizeMouseAtCenter.
+    // Need to emulate native mouse event.
+    synthesizeNativeOSXClick(button.boxObject.screenX + button.boxObject.width / 2,
+                             button.boxObject.screenY + button.boxObject.height / 2);
+  }
+
+  function onClick() {
+    ok(true, "Click event should be fired");
+    SimpleTest.finish();
+  }
+
+  SimpleTest.waitForExplicitFinish();
+  SimpleTest.waitForFocus(startTest);
+  ]]>
+  </script>
+
+  <!-- test results are displayed in the html:body -->
+  <body xmlns="http://www.w3.org/1999/xhtml">
+  <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1224790"
+     target="_blank">Mozilla Bug 1224790</a>
+  </body>
+  <button id="button" label="button" oncommand="onClick()" />
+</window>
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/chrome/test_bug1224790-2.xul
@@ -0,0 +1,59 @@
+<?xml version="1.0"?>
+<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
+<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1224790
+-->
+<window title="Mozilla Bug 1224790"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
+
+  <!-- test code goes here -->
+  <script type="application/javascript">
+  <![CDATA[
+
+  /** Test for Bug 1224790 **/
+  /*
+   * 1. Opens modal dialog
+   * 2. Open non-modal window from modal dialog
+   * 3. Close modal dialog
+   * 4. Wait for a while for destructor for modal dialog
+   * 5. Close non-modal window
+   * 6. Click button to ensure mouse event is working
+   */
+
+  function startTest() {
+    window.openDialog('file_bug1224790-2_modal.xul', '', 'modal');
+  }
+
+  function nonModalClosed() {
+    SimpleTest.waitForFocus(gotFocus);
+  }
+
+  function gotFocus() {
+    var button = document.getElementById('button');
+    synthesizeMouseAtCenter(button, { type: 'mousemove' }, window);
+    // The bug is not reproducible with synthesizeMouseAtCenter.
+    // Need to emulate native mouse event.
+    synthesizeNativeOSXClick(button.boxObject.screenX + button.boxObject.width / 2,
+                             button.boxObject.screenY + button.boxObject.height / 2);
+  }
+
+  function onClick() {
+    ok(true, "Click event should be fired");
+    SimpleTest.finish();
+  }
+
+  SimpleTest.waitForExplicitFinish();
+  SimpleTest.waitForFocus(startTest);
+  ]]>
+  </script>
+
+  <!-- test results are displayed in the html:body -->
+  <body xmlns="http://www.w3.org/1999/xhtml">
+  <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1224790"
+     target="_blank">Mozilla Bug 1224790</a>
+  </body>
+  <button id="button" label="button" oncommand="onClick()" />
+</window>
new file mode 100644
--- /dev/null
+++ b/dom/webidl/DominatorTree.webidl
@@ -0,0 +1,41 @@
+/* -*- 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/.
+ */
+
+/**
+ * In a directed graph with a root node `R`, a node `A` is said to "dominate" a
+ * node `B` iff every path from `R` to `B` contains `A`. A node `A` is said to
+ * be the "immediate dominator" of a node `B` iff it dominates `B`, is not `B`
+ * itself, and does not dominate any other nodes which also dominate `B` in
+ * turn.
+ *
+ * If we take every node from a graph `G` and create a new graph `T` with edges
+ * to each node from its immediate dominator, then `T` is a tree (each node has
+ * only one immediate dominator, or none if it is the root). This tree is called
+ * a "dominator tree".
+ *
+ * This interface represents a dominator tree constructed from a HeapSnapshot's
+ * heap graph. The domination relationship and dominator trees are useful tools
+ * for analyzing heap graphs because they tell you:
+ *
+ *   - Exactly what could be reclaimed by the GC if some node `A` became
+ *     unreachable: those nodes which are dominated by `A`,
+ *
+ *   - The "retained size" of a node in the heap graph, in contrast to its
+ *     "shallow size". The "shallow size" is the space taken by a node itself,
+ *     not counting anything it references. The "retained size" of a node is its
+ *     shallow size plus the size of all the things that would be collected if
+ *     the original node wasn't (directly or indirectly) referencing them. In
+ *     other words, the retained size is the shallow size of a node plus the
+ *     shallow sizes of every other node it dominates. For example, the root
+ *     node in a binary tree might have a small shallow size that does not take
+ *     up much space itself, but it dominates the rest of the binary tree and
+ *     its retained size is therefore significant (assuming no external
+ *     references into the tree).
+ */
+[ChromeOnly, Exposed=(Window,System,Worker)]
+interface DominatorTree {
+
+};
--- a/dom/webidl/HeapSnapshot.webidl
+++ b/dom/webidl/HeapSnapshot.webidl
@@ -51,9 +51,17 @@ interface HeapSnapshot {
    *       }
    *     }
    *
    * See the `takeCensus` section of the `js/src/doc/Debugger/Debugger.Memory.md`
    * file for detailed documentation.
    */
   [Throws]
   any takeCensus(object? options);
+
+  /**
+   * Compute the dominator tree for this heap snapshot.
+   *
+   * @see DominatorTree.webidl
+   */
+  [Throws]
+  DominatorTree computeDominatorTree();
 };
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -118,16 +118,17 @@ WEBIDL_FILES = [
     'Document.webidl',
     'DocumentFragment.webidl',
     'DocumentTimeline.webidl',
     'DocumentType.webidl',
     'DOMCursor.webidl',
     'DOMError.webidl',
     'DOMException.webidl',
     'DOMImplementation.webidl',
+    'DominatorTree.webidl',
     'DOMMatrix.webidl',
     'DOMMobileMessageError.webidl',
     'DOMParser.webidl',
     'DOMPoint.webidl',
     'DOMQuad.webidl',
     'DOMRect.webidl',
     'DOMRectList.webidl',
     'DOMRequest.webidl',
--- a/dom/workers/ServiceWorkerManager.cpp
+++ b/dom/workers/ServiceWorkerManager.cpp
@@ -2094,34 +2094,26 @@ ServiceWorkerManager::StorePendingReadyP
 
   data = new PendingReadyPromise(aURI, aPromise);
   mPendingReadyPromises.Put(aWindow, data);
 }
 
 void
 ServiceWorkerManager::CheckPendingReadyPromises()
 {
-  mPendingReadyPromises.Enumerate(CheckPendingReadyPromisesEnumerator, this);
-}
-
-PLDHashOperator
-ServiceWorkerManager::CheckPendingReadyPromisesEnumerator(
-                                          nsISupports* aSupports,
-                                          nsAutoPtr<PendingReadyPromise>& aData,
-                                          void* aPtr)
-{
-  ServiceWorkerManager* aSwm = static_cast<ServiceWorkerManager*>(aPtr);
-
-  nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aSupports);
-
-  if (aSwm->CheckReadyPromise(window, aData->mURI, aData->mPromise)) {
-    return PL_DHASH_REMOVE;
-  }
-
-  return PL_DHASH_NEXT;
+  for (auto iter = mPendingReadyPromises.Iter(); !iter.Done(); iter.Next()) {
+    nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(iter.Key());
+    MOZ_ASSERT(window);
+
+    nsAutoPtr<PendingReadyPromise>& pendingReadyPromise = iter.Data();
+    if (CheckReadyPromise(window, pendingReadyPromise->mURI,
+                          pendingReadyPromise->mPromise)) {
+      iter.Remove();
+    }    
+  }
 }
 
 bool
 ServiceWorkerManager::CheckReadyPromise(nsPIDOMWindow* aWindow,
                                         nsIURI* aURI, Promise* aPromise)
 {
   MOZ_ASSERT(aWindow);
   MOZ_ASSERT(aURI);
--- a/dom/workers/ServiceWorkerManager.h
+++ b/dom/workers/ServiceWorkerManager.h
@@ -589,21 +589,16 @@ private:
   void AppendPendingOperation(ServiceWorkerJobQueue* aQueue,
                               ServiceWorkerJob* aJob);
 
   bool HasBackgroundActor() const
   {
     return !!mActor;
   }
 
-  static PLDHashOperator
-  CheckPendingReadyPromisesEnumerator(nsISupports* aSupports,
-                                      nsAutoPtr<PendingReadyPromise>& aData,
-                                      void* aUnused);
-
   nsClassHashtable<nsISupportsHashKey, PendingReadyPromise> mPendingReadyPromises;
 
   void
   MaybeRemoveRegistration(ServiceWorkerRegistrationInfo* aRegistration);
 
   // Does all cleanup except removing the registration from
   // mServiceWorkerRegistrationInfos. This is useful when we clear
   // registrations via remove()/removeAll() since we are iterating over the
--- a/dom/workers/test/mochitest.ini
+++ b/dom/workers/test/mochitest.ini
@@ -107,16 +107,17 @@ support-files =
   empty.html
   worker_performance_user_timing.js
   worker_performance_observer.js
   sharedworker_performance_user_timing.js
   referrer.sjs
   performance_observer.html
   sharedWorker_ports.js
   sharedWorker_lifetime.js
+  worker_referrer.js
 
 [test_404.html]
 [test_atob.html]
 [test_blobConstructor.html]
 [test_blobWorkers.html]
 [test_bug949946.html]
 [test_bug978260.html]
 [test_bug998474.html]
--- a/dom/workers/test/referrer.sjs
+++ b/dom/workers/test/referrer.sjs
@@ -1,11 +1,15 @@
 function handleRequest(request, response)
 {
   if (request.queryString == "result") {
     response.write(getState("referer"));
-  } else {
+    setState("referer", "INVALID");
+  } else if (request.queryString == "worker") {
     response.setHeader("Content-Type", "text/javascript", false);
     response.write("onmessage = function() { postMessage(42); }");
     setState("referer", request.getHeader("referer"));
+  } else if (request.queryString == 'import') {
+    setState("referer", request.getHeader("referer"));
+    response.write("'hello world'");
   }
 }
 
--- a/dom/workers/test/test_referrer.html
+++ b/dom/workers/test/test_referrer.html
@@ -10,26 +10,49 @@
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <p id="display"></p>
 <div id="content" style="display: none"></div>
 <pre id="test"></pre>
 <script class="testbody" type="text/javascript">
 
-  var worker = new Worker("referrer.sjs");
-  worker.onmessage = function() {
-    var xhr = new XMLHttpRequest();
-    xhr.open('GET', 'referrer.sjs?result', true);
-    xhr.onload = function() {
-      is(xhr.responseText, location.href, "The referrer has been sent.");
+  function test_mainScript() {
+    var worker = new Worker("referrer.sjs?worker");
+    worker.onmessage = function() {
+      var xhr = new XMLHttpRequest();
+      xhr.open('GET', 'referrer.sjs?result', true);
+      xhr.onload = function() {
+        is(xhr.responseText, location.href, "The referrer has been sent.");
+        next();
+      }
+      xhr.send();
+    }
+    worker.postMessage(42);
+  }
+
+  function test_importScript() {
+    var worker = new Worker("worker_referrer.js");
+    worker.onmessage = function(e) {
+      is(e.data, location.href.replace("test_referrer.html", "worker_referrer.js"), "The referrer has been sent.");
+      next();
+    }
+    worker.postMessage(42);
+  }
+
+  var tests = [ test_mainScript, test_importScript ];
+  function next() {
+    if (!tests.length) {
       SimpleTest.finish();
+      return;
     }
-    xhr.send();
+
+    var test = tests.shift();
+    test();
   }
-  worker.postMessage(42);
 
   SimpleTest.waitForExplicitFinish();
+  next();
 
 </script>
 </pre>
 </body>
 </html>
new file mode 100644
--- /dev/null
+++ b/dom/workers/test/worker_referrer.js
@@ -0,0 +1,9 @@
+onmessage = function() {
+  importScripts(['referrer.sjs?import']);
+  var xhr = new XMLHttpRequest();
+  xhr.open('GET', 'referrer.sjs?result', true);
+  xhr.onload = function() {
+    postMessage(xhr.responseText);
+  }
+  xhr.send();
+}
--- a/dom/xbl/nsXBLProtoImplMethod.cpp
+++ b/dom/xbl/nsXBLProtoImplMethod.cpp
@@ -45,18 +45,16 @@ void
 nsXBLProtoImplMethod::AppendBodyText(const nsAString& aText)
 {
   NS_PRECONDITION(!IsCompiled(),
                   "Must not be compiled when accessing uncompiled method");
 
   nsXBLUncompiledMethod* uncompiledMethod = GetUncompiledMethod();
   if (!uncompiledMethod) {
     uncompiledMethod = new nsXBLUncompiledMethod();
-    if (!uncompiledMethod)
-      return;
     SetUncompiledMethod(uncompiledMethod);
   }
 
   uncompiledMethod->AppendBodyText(aText);
 }
 
 void
 nsXBLProtoImplMethod::AddParameter(const nsAString& aText)
@@ -67,35 +65,31 @@ nsXBLProtoImplMethod::AddParameter(const
   if (aText.IsEmpty()) {
     NS_WARNING("Empty name attribute in xbl:parameter!");
     return;
   }
 
   nsXBLUncompiledMethod* uncompiledMethod = GetUncompiledMethod();
   if (!uncompiledMethod) {
     uncompiledMethod = new nsXBLUncompiledMethod();
-    if (!uncompiledMethod)
-      return;
     SetUncompiledMethod(uncompiledMethod);
   }
 
   uncompiledMethod->AddParameter(aText);
 }
 
 void
 nsXBLProtoImplMethod::SetLineNumber(uint32_t aLineNumber)
 {
   NS_PRECONDITION(!IsCompiled(),
                   "Must not be compiled when accessing uncompiled method");
 
   nsXBLUncompiledMethod* uncompiledMethod = GetUncompiledMethod();
   if (!uncompiledMethod) {
     uncompiledMethod = new nsXBLUncompiledMethod();
-    if (!uncompiledMethod)
-      return;
     SetUncompiledMethod(uncompiledMethod);
   }
 
   uncompiledMethod->SetLineNumber(aLineNumber);
 }
 
 nsresult
 nsXBLProtoImplMethod::InstallMember(JSContext* aCx,
@@ -163,18 +157,16 @@ nsXBLProtoImplMethod::CompileMember(Auto
   }
 
   // We have a method.
   // Allocate an array for our arguments.
   int32_t paramCount = uncompiledMethod->GetParameterCount();
   char** args = nullptr;
   if (paramCount > 0) {
     args = new char*[paramCount];
-    if (!args)
-      return NS_ERROR_OUT_OF_MEMORY;
 
     // Add our parameters to our args array.
     int32_t argPos = 0;
     for (nsXBLParameter* curr = uncompiledMethod->mParameters;
          curr;
          curr = curr->mNext) {
       args[argPos] = curr->mName;
       argPos++;
--- a/dom/xbl/nsXBLProtoImplMethod.h
+++ b/dom/xbl/nsXBLProtoImplMethod.h
@@ -60,18 +60,16 @@ struct nsXBLUncompiledMethod {
   }
 
   void AppendBodyText(const nsAString& aText) {
     mBodyText.AppendText(aText);
   }
 
   void AddParameter(const nsAString& aText) {
     nsXBLParameter* param = new nsXBLParameter(aText);
-    if (!param)
-      return;
     if (!mParameters)
       mParameters = param;
     else
       mLastParameter->mNext = param;
     mLastParameter = param;
   }
 
   void SetLineNumber(uint32_t aLineNumber) {
--- a/dom/xbl/nsXBLResourceLoader.cpp
+++ b/dom/xbl/nsXBLResourceLoader.cpp
@@ -192,19 +192,16 @@ nsXBLResourceLoader::StyleSheetLoaded(CS
   }
   return NS_OK;
 }
 
 void 
 nsXBLResourceLoader::AddResource(nsIAtom* aResourceType, const nsAString& aSrc)
 {
   nsXBLResource* res = new nsXBLResource(aResourceType, aSrc);
-  if (!res)
-    return;
-
   if (!mResourceList)
     mResourceList = res;
   else
     mLastResource->mNext = res;
 
   mLastResource = res;
 }
 
--- a/dom/xslt/base/txList.cpp
+++ b/dom/xslt/base/txList.cpp
@@ -60,18 +60,16 @@ nsresult txList::insertAfter(void* objPt
  * If refItem is a null pointer the Object will be inserted at the
  * end of the txList (ie, insert before nothing).
  * This method assumes refItem is a member of this list, and since this
  * is a private method, I feel that's a valid assumption
 **/
 nsresult txList::insertBefore(void* objPtr, ListItem* refItem)
 {
     ListItem* item = new ListItem;
-    NS_ENSURE_TRUE(item, NS_ERROR_OUT_OF_MEMORY);
-
     item->objPtr = objPtr;
     item->nextItem = 0;
     item->prevItem = 0;
 
     //-- if refItem == null insert at end
     if (!refItem) {
         //-- add to back of list
         if (lastItem) {
--- a/dom/xslt/xpath/txExprLexer.cpp
+++ b/dom/xslt/xpath/txExprLexer.cpp
@@ -356,15 +356,12 @@ txExprLexer::parse(const nsASingleFragme
       NS_ENSURE_TRUE(newToken != mLastItem, NS_ERROR_FAILURE);
       prevToken = newToken;
       addToken(newToken);
     }
   }
 
   // add a endToken to the list
   newToken = new Token(end, end, Token::END);
-  if (!newToken) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
   addToken(newToken);
 
   return NS_OK;
 }
--- a/dom/xslt/xpath/txExprParser.cpp
+++ b/dom/xslt/xpath/txExprParser.cpp
@@ -116,18 +116,16 @@ txExprParser::createAVT(const nsSubstrin
         
         // Add expression, create a concat() call if necessary
         if (!expr) {
             expr = Move(newExpr);
         }
         else {
             if (!concat) {
                 concat = new txCoreFunctionCall(txCoreFunctionCall::CONCAT);
-                NS_ENSURE_TRUE(concat, NS_ERROR_OUT_OF_MEMORY);
-
                 rv = concat->addParam(expr.forget());
                 expr = concat;
                 NS_ENSURE_SUCCESS(rv, rv);
             }
 
             rv = concat->addParam(newExpr.forget());
             NS_ENSURE_SUCCESS(rv, rv);
         }
--- a/dom/xslt/xpath/txNodeSet.cpp
+++ b/dom/xslt/xpath/txNodeSet.cpp
@@ -348,17 +348,16 @@ txNodeSet::append(const txNodeSet& aNode
 nsresult
 txNodeSet::mark(int32_t aIndex)
 {
     NS_ASSERTION(aIndex >= 0 && mStart && mEnd - mStart > aIndex,
                  "index out of bounds");
     if (!mMarks) {
         int32_t length = size();
         mMarks = new bool[length];
-        NS_ENSURE_TRUE(mMarks, NS_ERROR_OUT_OF_MEMORY);
         memset(mMarks, 0, length * sizeof(bool));
     }
     if (mDirection == kForward) {
         mMarks[aIndex] = true;
     }
     else {
         mMarks[size() - aIndex - 1] = true;
     }
--- a/dom/xslt/xpath/txNodeSetAdaptor.cpp
+++ b/dom/xslt/xpath/txNodeSetAdaptor.cpp
@@ -21,18 +21,17 @@ txNodeSetAdaptor::txNodeSetAdaptor(txNod
 NS_IMPL_ISUPPORTS_INHERITED(txNodeSetAdaptor, txXPathObjectAdaptor, txINodeSet)
 
 nsresult
 txNodeSetAdaptor::Init()
 {
     if (!mValue) {
         mValue = new txNodeSet(nullptr);
     }
-
-    return mValue ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+    return NS_OK;
 }
 
 NS_IMETHODIMP
 txNodeSetAdaptor::Item(uint32_t aIndex, nsIDOMNode **aResult)
 {
     *aResult = nullptr;
 
     if (aIndex > (uint32_t)NodeSet()->size()) {
--- a/dom/xslt/xpath/txResultRecycler.cpp
+++ b/dom/xslt/xpath/txResultRecycler.cpp
@@ -72,17 +72,16 @@ txResultRecycler::recycle(txAExprResult*
     }
 }
 
 nsresult
 txResultRecycler::getStringResult(StringResult** aResult)
 {
     if (mStringResults.isEmpty()) {
         *aResult = new StringResult(this);
-        NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
     }
     else {
         *aResult = static_cast<StringResult*>(mStringResults.pop());
         (*aResult)->mValue.Truncate();
         (*aResult)->mRecycler = this;
     }
     NS_ADDREF(*aResult);
 
@@ -90,17 +89,16 @@ txResultRecycler::getStringResult(String
 }
 
 nsresult
 txResultRecycler::getStringResult(const nsAString& aValue,
                                   txAExprResult** aResult)
 {
     if (mStringResults.isEmpty()) {
         *aResult = new StringResult(aValue, this);
-        NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
     }
     else {
         StringResult* strRes =
             static_cast<StringResult*>(mStringResults.pop());
         strRes->mValue = aValue;
         strRes->mRecycler = this;
         *aResult = strRes;
     }
@@ -116,50 +114,47 @@ txResultRecycler::getEmptyStringResult(t
     NS_ADDREF(*aResult);
 }
 
 nsresult
 txResultRecycler::getNodeSet(txNodeSet** aResult)
 {
     if (mNodeSetResults.isEmpty()) {
         *aResult = new txNodeSet(this);
-        NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
     }
     else {
         *aResult = static_cast<txNodeSet*>(mNodeSetResults.pop());
         (*aResult)->mRecycler = this;
     }
     NS_ADDREF(*aResult);
 
     return NS_OK;
 }
 
 nsresult
 txResultRecycler::getNodeSet(txNodeSet* aNodeSet, txNodeSet** aResult)
 {
     if (mNodeSetResults.isEmpty()) {
         *aResult = new txNodeSet(*aNodeSet, this);
-        NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
     }
     else {
         *aResult = static_cast<txNodeSet*>(mNodeSetResults.pop());
         (*aResult)->append(*aNodeSet);
         (*aResult)->mRecycler = this;
     }
     NS_ADDREF(*aResult);
 
     return NS_OK;
 }
 
 nsresult
 txResultRecycler::getNodeSet(const txXPathNode& aNode, txAExprResult** aResult)
 {
     if (mNodeSetResults.isEmpty()) {
         *aResult = new txNodeSet(aNode, this);
-        NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
     }
     else {
         txNodeSet* nodes = static_cast<txNodeSet*>(mNodeSetResults.pop());
         nodes->append(aNode);
         nodes->mRecycler = this;
         *aResult = nodes;
     }
     NS_ADDREF(*aResult);
@@ -167,17 +162,16 @@ txResultRecycler::getNodeSet(const txXPa
     return NS_OK;
 }
 
 nsresult
 txResultRecycler::getNumberResult(double aValue, txAExprResult** aResult)
 {
     if (mNumberResults.isEmpty()) {
         *aResult = new NumberResult(aValue, this);
-        NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
     }
     else {
         NumberResult* numRes =
             static_cast<NumberResult*>(mNumberResults.pop());
         numRes->value = aValue;
         numRes->mRecycler = this;
         *aResult = numRes;
     }
--- a/dom/xslt/xpath/txXPCOMExtensionFunction.cpp
+++ b/dom/xslt/xpath/txXPCOMExtensionFunction.cpp
@@ -251,18 +251,17 @@ TX_ResolveFunctionCallXPCOM(const nsCStr
         return NS_OK;
     }
 
     *aFunction = new txXPCOMExtensionFunctionCall(helper, iid, methodIndex,
 #ifdef TX_TO_STRING
                                                   aName,
 #endif
                                                   aState);
-
-    return *aFunction ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+    return NS_OK;
 }
 
 txArgumentType
 txXPCOMExtensionFunctionCall::GetParamType(const nsXPTParamInfo &aParam,
                                            nsIInterfaceInfo *aInfo)
 {
     uint8_t tag = aParam.GetType().TagPart();
     switch (tag) {
@@ -335,20 +334,16 @@ txParamArrayHolder::~txParamArrayHolder(
     }
 }
 
 bool
 txParamArrayHolder::Init(uint8_t aCount)
 {
     mCount = aCount;
     mArray = new nsXPTCVariant[mCount];
-    if (!mArray) {
-        return false;
-    }
-
     memset(mArray, 0, mCount * sizeof(nsXPTCVariant));
 
     return true;
 }
 
 nsresult
 txXPCOMExtensionFunctionCall::evaluate(txIEvalContext* aContext,
                                        txAExprResult** aResult)
@@ -384,19 +379,16 @@ txXPCOMExtensionFunctionCall::evaluate(t
     if (type == eCONTEXT) {
         if (paramInfo.IsOut()) {
             // We don't support out values.
             return NS_ERROR_FAILURE;
         }
 
         // Create context wrapper.
         context = new txFunctionEvaluationContext(aContext, mState);
-        if (!context) {
-            return NS_ERROR_OUT_OF_MEMORY;
-        }
 
         nsXPTCVariant &invokeParam = invokeParams[0];
         invokeParam.type = paramInfo.GetType();
         invokeParam.SetValNeedsCleanup();
         NS_ADDREF((txIFunctionEvaluationContext*&)invokeParam.val.p = context);
 
         // Skip first argument, since it's the context.
         paramStart = 1;
@@ -507,20 +499,16 @@ txXPCOMExtensionFunctionCall::evaluate(t
     if (returnType == eUNKNOWN) {
         return NS_ERROR_FAILURE;
     }
 
     nsXPTCVariant &returnParam = invokeParams[inArgs];
     returnParam.type = returnInfo.GetType();
     if (returnType == eSTRING) {
         nsString *value = new nsString();
-        if (!value) {
-            return NS_ERROR_FAILURE;
-        }
-
         returnParam.SetValNeedsCleanup();
         returnParam.val.p = value;
     }
     else {
         returnParam.SetIndirect();
         if (returnType == eNODESET || returnType == eOBJECT) {
             returnParam.SetValNeedsCleanup();
         }
--- a/dom/xslt/xpath/txXPathOptimizer.cpp
+++ b/dom/xslt/xpath/txXPathOptimizer.cpp
@@ -128,30 +128,26 @@ txXPathOptimizer::optimizeStep(Expr* aIn
         if (!step->getSubExprAt(0) &&
             step->getNodeTest()->getType() == txNameTest::NAME_TEST &&
             (nameTest = static_cast<txNameTest*>(step->getNodeTest()))->
                 mLocalName != nsGkAtoms::_asterisk) {
 
             *aOutExpr = new txNamedAttributeStep(nameTest->mNamespace,
                                                  nameTest->mPrefix,
                                                  nameTest->mLocalName);
-            NS_ENSURE_TRUE(*aOutExpr, NS_ERROR_OUT_OF_MEMORY);
-
             return NS_OK; // return since we no longer have a step-object.
         }
     }
 
     // Test for predicates that can be combined into the nodetest
     Expr* pred;
     while ((pred = step->getSubExprAt(0)) &&
            !pred->canReturnType(Expr::NUMBER_RESULT) &&
            !pred->isSensitiveTo(Expr::NODESET_CONTEXT)) {
         txNodeTest* predTest = new txPredicatedNodeTest(step->getNodeTest(), pred);
-        NS_ENSURE_TRUE(predTest, NS_ERROR_OUT_OF_MEMORY);
-
         step->dropFirst();
         step->setNodeTest(predTest);
     }
 
     return NS_OK;
 }
 
 nsresult
@@ -247,18 +243,16 @@ txXPathOptimizer::optimizeUnion(Expr* aI
             LocationStep* step = static_cast<LocationStep*>(subExpr);
             if (step->getAxisIdentifier() != axis) {
                 continue;
             }
             
             // Create a txUnionNodeTest if needed
             if (!unionTest) {
                 nsAutoPtr<txNodeTest> owner(unionTest = new txUnionNodeTest);
-                NS_ENSURE_TRUE(unionTest, NS_ERROR_OUT_OF_MEMORY);
-                
                 rv = unionTest->addNodeTest(currentStep->getNodeTest());
                 NS_ENSURE_SUCCESS(rv, rv);
 
                 currentStep->setNodeTest(unionTest);
                 owner.forget();
             }
 
             // Merge the nodetest into the union
--- a/dom/xslt/xslt/txBufferingHandler.cpp
+++ b/dom/xslt/xslt/txBufferingHandler.cpp
@@ -199,36 +199,32 @@ txBufferingHandler::attribute(nsIAtom* a
         // XXX ErrorReport: Can't add attributes without element
         return NS_OK;
     }
 
     txOutputTransaction* transaction =
         new txAttributeAtomTransaction(aPrefix, aLocalName,
                                        aLowercaseLocalName, aNsID,
                                        aValue);
-    NS_ENSURE_TRUE(transaction, NS_ERROR_OUT_OF_MEMORY);
-
     return mBuffer->addTransaction(transaction);
 }
 
 nsresult
 txBufferingHandler::attribute(nsIAtom* aPrefix, const nsSubstring& aLocalName,
                               const int32_t aNsID, const nsString& aValue)
 {
     NS_ENSURE_TRUE(mBuffer, NS_ERROR_OUT_OF_MEMORY);
 
     if (!mCanAddAttribute) {
         // XXX ErrorReport: Can't add attributes without element
         return NS_OK;
     }
 
     txOutputTransaction* transaction =
         new txAttributeTransaction(aPrefix, aLocalName, aNsID, aValue);
-    NS_ENSURE_TRUE(transaction, NS_ERROR_OUT_OF_MEMORY);
-
     return mBuffer->addTransaction(transaction);
 }
 
 nsresult
 txBufferingHandler::characters(const nsSubstring& aData, bool aDOE)
 {
     NS_ENSURE_TRUE(mBuffer, NS_ERROR_OUT_OF_MEMORY);
 
@@ -242,118 +238,102 @@ txBufferingHandler::characters(const nsS
     if (transaction && transaction->mType == type) {
         mBuffer->mStringValue.Append(aData);
         static_cast<txCharacterTransaction*>(transaction)->mLength +=
             aData.Length();
         return NS_OK;
     }
 
     transaction = new txCharacterTransaction(type, aData.Length());
-    NS_ENSURE_TRUE(transaction, NS_ERROR_OUT_OF_MEMORY);
-
     mBuffer->mStringValue.Append(aData);
     return mBuffer->addTransaction(transaction);
 }
 
 nsresult
 txBufferingHandler::comment(const nsString& aData)
 {
     NS_ENSURE_TRUE(mBuffer, NS_ERROR_OUT_OF_MEMORY);
 
     mCanAddAttribute = false;
 
     txOutputTransaction* transaction = new txCommentTransaction(aData);
-    NS_ENSURE_TRUE(transaction, NS_ERROR_OUT_OF_MEMORY);
-
     return mBuffer->addTransaction(transaction);
 }
 
 nsresult
 txBufferingHandler::endDocument(nsresult aResult)
 {
     NS_ENSURE_TRUE(mBuffer, NS_ERROR_OUT_OF_MEMORY);
 
     txOutputTransaction* transaction =
         new txOutputTransaction(txOutputTransaction::eEndDocumentTransaction);
-    NS_ENSURE_TRUE(transaction, NS_ERROR_OUT_OF_MEMORY);
-
     return mBuffer->addTransaction(transaction);
 }
 
 nsresult
 txBufferingHandler::endElement()
 {
     NS_ENSURE_TRUE(mBuffer, NS_ERROR_OUT_OF_MEMORY);
 
     mCanAddAttribute = false;
 
     txOutputTransaction* transaction =
         new txOutputTransaction(txOutputTransaction::eEndElementTransaction);
-    NS_ENSURE_TRUE(transaction, NS_ERROR_OUT_OF_MEMORY);
-
     return mBuffer->addTransaction(transaction);
 }
 
 nsresult
 txBufferingHandler::processingInstruction(const nsString& aTarget,
                                           const nsString& aData)
 {
     NS_ENSURE_TRUE(mBuffer, NS_ERROR_OUT_OF_MEMORY);
 
     mCanAddAttribute = false;
 
     txOutputTransaction* transaction =
         new txPITransaction(aTarget, aData);
-    NS_ENSURE_TRUE(transaction, NS_ERROR_OUT_OF_MEMORY);
-
     return mBuffer->addTransaction(transaction);
 }
 
 nsresult
 txBufferingHandler::startDocument()
 {
     NS_ENSURE_TRUE(mBuffer, NS_ERROR_OUT_OF_MEMORY);
 
     txOutputTransaction* transaction =
         new txOutputTransaction(txOutputTransaction::eStartDocumentTransaction);
-    NS_ENSURE_TRUE(transaction, NS_ERROR_OUT_OF_MEMORY);
-
     return mBuffer->addTransaction(transaction);
 }
 
 nsresult
 txBufferingHandler::startElement(nsIAtom* aPrefix, nsIAtom* aLocalName,
                                  nsIAtom* aLowercaseLocalName,
                                  int32_t aNsID)
 {
     NS_ENSURE_TRUE(mBuffer, NS_ERROR_OUT_OF_MEMORY);
 
     mCanAddAttribute = true;
 
     txOutputTransaction* transaction =
         new txStartElementAtomTransaction(aPrefix, aLocalName,
                                           aLowercaseLocalName, aNsID);
-    NS_ENSURE_TRUE(transaction, NS_ERROR_OUT_OF_MEMORY);
-
     return mBuffer->addTransaction(transaction);
 }
 
 nsresult
 txBufferingHandler::startElement(nsIAtom* aPrefix,
                                  const nsSubstring& aLocalName,
                                  const int32_t aNsID)
 {
     NS_ENSURE_TRUE(mBuffer, NS_ERROR_OUT_OF_MEMORY);
 
     mCanAddAttribute = true;
 
     txOutputTransaction* transaction =
         new txStartElementTransaction(aPrefix, aLocalName, aNsID);
-    NS_ENSURE_TRUE(transaction, NS_ERROR_OUT_OF_MEMORY);
-
     return mBuffer->addTransaction(transaction);
 }
 
 txResultBuffer::txResultBuffer()
 {
     MOZ_COUNT_CTOR(txResultBuffer);
 }
 
--- a/dom/xslt/xslt/txEXSLTFunctions.cpp
+++ b/dom/xslt/xslt/txEXSLTFunctions.cpp
@@ -703,18 +703,17 @@ TX_ConstructEXSLTFunction(nsIAtom *aName
                           FunctionCall **aResult)
 {
     uint32_t i;
     for (i = 0; i < ArrayLength(descriptTable); ++i) {
         txEXSLTFunctionDescriptor& desc = descriptTable[i];
         if (aName == *desc.mName && aNamespaceID == desc.mNamespaceID) {
             *aResult = new txEXSLTFunctionCall(
                 static_cast<txEXSLTFunctionCall::eType>(i));
-
-            return *aResult ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+            return NS_OK;
         }
     }
 
     return NS_ERROR_XPATH_UNKNOWN_FUNCTION;
 }
 
 extern bool
 TX_InitEXSLTFunction()
--- a/dom/xslt/xslt/txExecutionState.cpp
+++ b/dom/xslt/xslt/txExecutionState.cpp
@@ -98,18 +98,16 @@ txExecutionState::init(const txXPathNode
                        txOwningExpandedNameMap<txIGlobalParameter>* aGlobalParams)
 {
     nsresult rv = NS_OK;
 
     mGlobalParams = aGlobalParams;
 
     // Set up initial context
     mEvalContext = new txSingleNodeContext(aNode, this);
-    NS_ENSURE_TRUE(mEvalContext, NS_ERROR_OUT_OF_MEMORY);
-
     mInitialEvalContext = mEvalContext;
 
     // Set up output and result-handler
     txAXMLEventHandler* handler;
     rv = mOutputHandlerFactory->
         createHandlerWith(mStylesheet->getOutputFormat(), &handler);
     NS_ENSURE_SUCCESS(rv, rv);
 
@@ -124,17 +122,16 @@ txExecutionState::init(const txXPathNode
     rv = mKeyHash.init();
     NS_ENSURE_SUCCESS(rv, rv);
     
     mRecycler = new txResultRecycler;
     
     // The actual value here doesn't really matter since noone should use this
     // value. But lets put something errorlike in just in case
     mGlobalVarPlaceholderValue = new StringResult(NS_LITERAL_STRING("Error"), nullptr);
-    NS_ENSURE_TRUE(mGlobalVarPlaceholderValue, NS_ERROR_OUT_OF_MEMORY);
 
     // Initiate first instruction. This has to be done last since findTemplate
     // might use us.
     txStylesheet::ImportFrame* frame = 0;
     txExpandedName nullName;
     txInstruction* templ = mStylesheet->findTemplate(aNode, nullName,
                                                      this, nullptr, &frame);
     pushTemplateRule(frame, nullName, nullptr);
@@ -477,17 +474,16 @@ txExecutionState::returnFromTemplate()
 }
 
 nsresult
 txExecutionState::bindVariable(const txExpandedName& aName,
                                txAExprResult* aValue)
 {
     if (!mLocalVariables) {
         mLocalVariables = new txVariableMap;
-        NS_ENSURE_TRUE(mLocalVariables, NS_ERROR_OUT_OF_MEMORY);
     }
     return mLocalVariables->bindVariable(aName, aValue);
 }
 
 void
 txExecutionState::removeVariable(const txExpandedName& aName)
 {
     mLocalVariables->removeVariable(aName);
--- a/dom/xslt/xslt/txFormatNumberFunctionCall.cpp
+++ b/dom/xslt/xslt/txFormatNumberFunctionCall.cpp
@@ -270,18 +270,16 @@ txFormatNumberFunctionCall::evaluate(txI
 
     int bufsize;
     if (value > 1)
         bufsize = (int)log10(value) + 30;
     else
         bufsize = 1 + 30;
 
     char* buf = new char[bufsize];
-    NS_ENSURE_TRUE(buf, NS_ERROR_OUT_OF_MEMORY);
-
     int bufIntDigits, sign;
     char* endp;
     PR_dtoa(value, 0, 0, &bufIntDigits, &sign, &endp, buf, bufsize-1);
 
     int buflen = endp - buf;
     int intDigits;
     intDigits = bufIntDigits > minIntegerSize ? bufIntDigits : minIntegerSize;
 
--- a/dom/xslt/xslt/txInstructions.cpp
+++ b/dom/xslt/xslt/txInstructions.cpp
@@ -694,18 +694,16 @@ txPushParams::execute(txExecutionState& 
 {
     return aEs.pushParamMap(nullptr);
 }
 
 nsresult
 txPushRTFHandler::execute(txExecutionState& aEs)
 {
     txAXMLEventHandler* handler = new txRtfHandler;
-    NS_ENSURE_TRUE(handler, NS_ERROR_OUT_OF_MEMORY);
-    
     nsresult rv = aEs.pushResultHandler(handler);
     if (NS_FAILED(rv)) {
         delete handler;
         return rv;
     }
 
     return NS_OK;
 }
@@ -714,18 +712,16 @@ txPushStringHandler::txPushStringHandler
     : mOnlyText(aOnlyText)
 {
 }
 
 nsresult
 txPushStringHandler::execute(txExecutionState& aEs)
 {
     txAXMLEventHandler* handler = new txTextHandler(mOnlyText);
-    NS_ENSURE_TRUE(handler, NS_ERROR_OUT_OF_MEMORY);
-    
     nsresult rv = aEs.pushResultHandler(handler);
     if (NS_FAILED(rv)) {
         delete handler;
         return rv;
     }
 
     return NS_OK;
 }
--- a/dom/xslt/xslt/txMozillaStylesheetCompiler.cpp
+++ b/dom/xslt/xslt/txMozillaStylesheetCompiler.cpp
@@ -524,18 +524,16 @@ handleNode(nsINode* aNode, txStylesheetC
     
     if (aNode->IsElement()) {
         dom::Element* element = aNode->AsElement();
 
         uint32_t attsCount = element->GetAttrCount();
         nsAutoArrayPtr<txStylesheetAttr> atts;
         if (attsCount > 0) {
             atts = new txStylesheetAttr[attsCount];
-            NS_ENSURE_TRUE(atts, NS_ERROR_OUT_OF_MEMORY);
-
             uint32_t counter;
             for (counter = 0; counter < attsCount; ++counter) {
                 txStylesheetAttr& att = atts[counter];
                 const nsAttrName* name = element->GetAttrNameAt(counter);
                 att.mNamespaceID = name->NamespaceID();
                 att.mLocalName = name->LocalName();
                 att.mPrefix = name->GetPrefix();
                 element->GetAttr(att.mNamespaceID, att.mLocalName, att.mValue);
--- a/dom/xslt/xslt/txMozillaXSLTProcessor.cpp
+++ b/dom/xslt/xslt/txMozillaXSLTProcessor.cpp
@@ -511,17 +511,16 @@ txMozillaXSLTProcessor::AddXSLTParam(con
         NS_ENSURE_SUCCESS(rv, rv);
 
         // Evaluate
         rv = expr->evaluate(&paramContext, getter_AddRefs(value));
         NS_ENSURE_SUCCESS(rv, rv);
     }
     else {
         value = new StringResult(aValue, nullptr);
-        NS_ENSURE_TRUE(value, NS_ERROR_OUT_OF_MEMORY);
     }
 
     nsCOMPtr<nsIAtom> name = do_GetAtom(aName);
     int32_t nsId = kNameSpaceID_Unknown;
     rv = nsContentUtils::NameSpaceManager()->
         RegisterNameSpace(aNamespace, nsId);
     NS_ENSURE_SUCCESS(rv, rv);
 
@@ -569,22 +568,17 @@ txMozillaXSLTProcessor::DoTransform()
     NS_ASSERTION(mObserver, "no observer");
     NS_ASSERTION(NS_IsMainThread(), "should only be on main thread");
 
     nsresult rv;
     nsCOMPtr<nsIDocument> document = do_QueryInterface(mSource, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsCOMPtr<nsIRunnable> event = new nsTransformBlockerEvent(this);
-    if (!event) {
-        return NS_ERROR_OUT_OF_MEMORY;
-    }
-
     document->BlockOnload();
-
     rv = NS_DispatchToCurrentThread(event);
     if (NS_FAILED(rv)) {
         // XXX Maybe we should just display the source document in this case?
         //     Also, set up context information, see bug 204655.
         reportError(rv, nullptr, nullptr);
     }
 
     return rv;
@@ -951,18 +945,16 @@ txMozillaXSLTProcessor::SetParameter(con
 
     txVariable* var = static_cast<txVariable*>(mVariables.get(varName));
     if (var) {
         var->setValue(value);
         return NS_OK;
     }
 
     var = new txVariable(value);
-    NS_ENSURE_TRUE(var, NS_ERROR_OUT_OF_MEMORY);
-
     return mVariables.add(varName, var);
 }
 
 NS_IMETHODIMP
 txMozillaXSLTProcessor::GetParameter(const nsAString& aNamespaceURI,
                                      const nsAString& aLocalName,
                                      nsIVariant **aResult)
 {
@@ -1409,33 +1401,29 @@ txVariable::Convert(nsIVariant *aValue, 
         case nsIDataType::VTYPE_FLOAT:
         case nsIDataType::VTYPE_DOUBLE:
         {
             double value;
             nsresult rv = aValue->GetAsDouble(&value);
             NS_ENSURE_SUCCESS(rv, rv);
 
             *aResult = new NumberResult(value, nullptr);
-            NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
-
             NS_ADDREF(*aResult);
 
             return NS_OK;
         }
 
         // Boolean
         case nsIDataType::VTYPE_BOOL:
         {
             bool value;
             nsresult rv = aValue->GetAsBool(&value);
             NS_ENSURE_SUCCESS(rv, rv);
 
             *aResult = new BooleanResult(value);
-            NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
-
             NS_ADDREF(*aResult);
 
             return NS_OK;
         }
 
         // String
         case nsIDataType::VTYPE_CHAR:
         case nsIDataType::VTYPE_WCHAR:
@@ -1448,18 +1436,16 @@ txVariable::Convert(nsIVariant *aValue, 
         case nsIDataType::VTYPE_CSTRING:
         case nsIDataType::VTYPE_ASTRING:
         {
             nsAutoString value;
             nsresult rv = aValue->GetAsAString(value);
             NS_ENSURE_SUCCESS(rv, rv);
 
             *aResult = new StringResult(value, nullptr);
-            NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
-
             NS_ADDREF(*aResult);
 
             return NS_OK;
         }
 
         // Nodeset
         case nsIDataType::VTYPE_INTERFACE:
         case nsIDataType::VTYPE_INTERFACE_IS:
@@ -1532,20 +1518,16 @@ txVariable::Convert(nsIVariant *aValue, 
                 JS::Rooted<JS::Value> v(cx, JS::ObjectValue(*jsobj));
                 JS::Rooted<JSString*> str(cx, JS::ToString(cx, v));
                 NS_ENSURE_TRUE(str, NS_ERROR_FAILURE);
 
                 nsAutoJSString value;
                 NS_ENSURE_TRUE(value.init(cx, str), NS_ERROR_FAILURE);
 
                 *aResult = new StringResult(value, nullptr);
-                if (!*aResult) {
-                    return NS_ERROR_OUT_OF_MEMORY;
-                }
-
                 NS_ADDREF(*aResult);
 
                 return NS_OK;
             }
 
             break;
         }
 
--- a/dom/xslt/xslt/txNodeSorter.cpp
+++ b/dom/xslt/xslt/txNodeSorter.cpp
@@ -32,17 +32,16 @@ txNodeSorter::~txNodeSorter()
 }
 
 nsresult
 txNodeSorter::addSortElement(Expr* aSelectExpr, Expr* aLangExpr,
                              Expr* aDataTypeExpr, Expr* aOrderExpr,
                              Expr* aCaseOrderExpr, txIEvalContext* aContext)
 {
     nsAutoPtr<SortKey> key(new SortKey);
-    NS_ENSURE_TRUE(key, NS_ERROR_OUT_OF_MEMORY);
     nsresult rv = NS_OK;
 
     // Select
     key->mExpr = aSelectExpr;
 
     // Order
     bool ascending = true;
     if (aOrderExpr) {
@@ -93,22 +92,20 @@ txNodeSorter::addSortElement(Expr* aSele
                 // XXX ErrorReport: unknown value for case-order attribute
                 return NS_ERROR_XSLT_BAD_VALUE;
             }
         }
 
         key->mComparator = new txResultStringComparator(ascending,
                                                         upperFirst,
                                                         lang);
-        NS_ENSURE_TRUE(key->mComparator, NS_ERROR_OUT_OF_MEMORY);
     }
     else if (TX_StringEqualsAtom(dataType, nsGkAtoms::number)) {
         // Number comparator
         key->mComparator = new txResultNumberComparator(ascending);
-        NS_ENSURE_TRUE(key->mComparator, NS_ERROR_OUT_OF_MEMORY);
     }
     else {
         // XXX ErrorReport: unknown data-type
         return NS_ERROR_XSLT_BAD_VALUE;
     }
 
     // mSortKeys owns key now. 
     rv = mSortKeys.add(key);
--- a/dom/xslt/xslt/txPatternParser.cpp
+++ b/dom/xslt/xslt/txPatternParser.cpp
@@ -58,20 +58,16 @@ nsresult txPatternParser::createUnionPat
     }
 
     if (type != Token::UNION_OP) {
         delete locPath;
         return NS_ERROR_XPATH_PARSE_FAILURE;
     }
 
     txUnionPattern* unionPattern = new txUnionPattern();
-    if (!unionPattern) {
-        delete locPath;
-        return NS_ERROR_OUT_OF_MEMORY;
-    }
     rv = unionPattern->addPattern(locPath);
 #if 0 // XXX addPattern can't fail yet, it doesn't check for mem
     if (NS_FAILED(rv)) {
         delete unionPattern;
         delete locPath;
         return rv;
     }
 #endif
@@ -122,18 +118,17 @@ nsresult txPatternParser::createLocPathP
             aLexer.nextToken();
             break;
         case Token::PARENT_OP:
             aLexer.nextToken();
             isAbsolute = true;
             if (aLexer.peek()->mType == Token::END || 
                 aLexer.peek()->mType == Token::UNION_OP) {
                 aPattern = new txRootPattern();
-
-                return aPattern ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+                return NS_OK;
             }
             break;
         case Token::FUNCTION_NAME_AND_PAREN:
             // id(Literal) or key(Literal, Literal)
             {
                 nsCOMPtr<nsIAtom> nameAtom =
                     do_GetAtom(aLexer.nextToken()->Value());
                 if (nameAtom == nsGkAtoms::id) {
@@ -158,29 +153,18 @@ nsresult txPatternParser::createLocPathP
     type = aLexer.peek()->mType;
     if (!isAbsolute && type != Token::PARENT_OP
         && type != Token::ANCESTOR_OP) {
         aPattern = stepPattern;
         return NS_OK;
     }
 
     pathPattern = new txLocPathPattern();
-    if (!pathPattern) {
-        delete stepPattern;
-        return NS_ERROR_OUT_OF_MEMORY;
-    }
-
     if (isAbsolute) {
         txRootPattern* root = new txRootPattern();
-        if (!root) {
-            delete stepPattern;
-            delete pathPattern;
-            return NS_ERROR_OUT_OF_MEMORY;
-        }
-
 #ifdef TX_TO_STRING
         root->setSerialize(false);
 #endif
 
         rv = pathPattern->addStep(root, isChild);
         if (NS_FAILED(rv)) {
             delete stepPattern;
             delete pathPattern;
@@ -224,17 +208,17 @@ nsresult txPatternParser::createIdPatter
     // check for '(' Literal ')'
     if (aLexer.peek()->mType != Token::LITERAL)
         return NS_ERROR_XPATH_PARSE_FAILURE;
     const nsDependentSubstring& value =
         aLexer.nextToken()->Value();
     if (aLexer.nextToken()->mType != Token::R_PAREN)
         return NS_ERROR_XPATH_PARSE_FAILURE;
     aPattern  = new txIdPattern(value);
-    return aPattern ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+    return NS_OK;
 }
 
 nsresult txPatternParser::createKeyPattern(txExprLexer& aLexer,
                                            txIParseContext* aContext,
                                            txPattern*& aPattern)
 {
     // check for '(' Literal, Literal ')'
     if (aLexer.peek()->mType != Token::LITERAL)
@@ -258,18 +242,17 @@ nsresult txPatternParser::createKeyPatte
     nsCOMPtr<nsIAtom> prefix, localName;
     int32_t namespaceID;
     nsresult rv = resolveQName(key, getter_AddRefs(prefix), aContext,
                                getter_AddRefs(localName), namespaceID);
     if (NS_FAILED(rv))
         return rv;
 
     aPattern  = new txKeyPattern(prefix, localName, namespaceID, value);
-
-    return aPattern ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+    return NS_OK;
 }
 
 nsresult txPatternParser::createStepPattern(txExprLexer& aLexer,
                                             txIParseContext* aContext,
                                             txPattern*& aPattern)
 {
     nsresult rv = NS_OK;
     bool isAttr = false;
@@ -303,30 +286,22 @@ nsresult txPatternParser::createStepPatt
             // XXX error report namespace resolve failed
             return rv;
         }
 
         uint16_t nodeType = isAttr ?
                             (uint16_t)txXPathNodeType::ATTRIBUTE_NODE :
                             (uint16_t)txXPathNodeType::ELEMENT_NODE;
         nodeTest = new txNameTest(prefix, lName, nspace, nodeType);
-        if (!nodeTest) {
-            return NS_ERROR_OUT_OF_MEMORY;
-        }
     }
     else {
         rv = createNodeTypeTest(aLexer, &nodeTest);
         NS_ENSURE_SUCCESS(rv, rv);
     }
 
     nsAutoPtr<txStepPattern> step(new txStepPattern(nodeTest, isAttr));
-    if (!step) {
-        delete nodeTest;
-        return NS_ERROR_OUT_OF_MEMORY;
-    }
-
     rv = parsePredicates(step, aLexer, aContext);
     NS_ENSURE_SUCCESS(rv, rv);
 
     aPattern = step.forget();
 
     return NS_OK;
 }
--- a/dom/xslt/xslt/txRtfHandler.cpp
+++ b/dom/xslt/xslt/txRtfHandler.cpp
@@ -57,20 +57,17 @@ nsresult txResultTreeFragment::flushToHa
 
     return mBuffer->flushToHandler(aHandler);
 }
 
 nsresult
 txRtfHandler::getAsRTF(txAExprResult** aResult)
 {
     *aResult = new txResultTreeFragment(Move(mBuffer));
-    NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
-
     NS_ADDREF(*aResult);
-
     return NS_OK;
 }
 
 nsresult
 txRtfHandler::endDocument(nsresult aResult)
 {
     return NS_OK;
 }
--- a/dom/xslt/xslt/txStylesheet.cpp
+++ b/dom/xslt/xslt/txStylesheet.cpp
@@ -23,69 +23,50 @@ txStylesheet::txStylesheet()
     : mRootFrame(nullptr)
 {
 }
 
 nsresult
 txStylesheet::init()
 {
     mRootFrame = new ImportFrame;
-    NS_ENSURE_TRUE(mRootFrame, NS_ERROR_OUT_OF_MEMORY);
     
     // Create default templates
     // element/root template
     mContainerTemplate = new txPushParams;
-    NS_ENSURE_TRUE(mContainerTemplate, NS_ERROR_OUT_OF_MEMORY);
 
     nsAutoPtr<txNodeTest> nt(new txNodeTypeTest(txNodeTypeTest::NODE_TYPE));
-    NS_ENSURE_TRUE(nt, NS_ERROR_OUT_OF_MEMORY);
-
     nsAutoPtr<Expr> nodeExpr(new LocationStep(nt, LocationStep::CHILD_AXIS));
-    NS_ENSURE_TRUE(nodeExpr, NS_ERROR_OUT_OF_MEMORY);
-
     nt.forget();
 
     txPushNewContext* pushContext = new txPushNewContext(Move(nodeExpr));
     mContainerTemplate->mNext = pushContext;
-    NS_ENSURE_TRUE(pushContext, NS_ERROR_OUT_OF_MEMORY);
 
     txApplyDefaultElementTemplate* applyTemplates =
         new txApplyDefaultElementTemplate;
     pushContext->mNext = applyTemplates;
-    NS_ENSURE_TRUE(applyTemplates, NS_ERROR_OUT_OF_MEMORY);
 
     txLoopNodeSet* loopNodeSet = new txLoopNodeSet(applyTemplates);
     applyTemplates->mNext = loopNodeSet;
-    NS_ENSURE_TRUE(loopNodeSet, NS_ERROR_OUT_OF_MEMORY);
 
     txPopParams* popParams = new txPopParams;
     pushContext->mBailTarget = loopNodeSet->mNext = popParams;
-    NS_ENSURE_TRUE(popParams, NS_ERROR_OUT_OF_MEMORY);
 
     popParams->mNext = new txReturn();
-    NS_ENSURE_TRUE(popParams->mNext, NS_ERROR_OUT_OF_MEMORY);
 
     // attribute/textnode template
     nt = new txNodeTypeTest(txNodeTypeTest::NODE_TYPE);
-    NS_ENSURE_TRUE(nt, NS_ERROR_OUT_OF_MEMORY);
-
     nodeExpr = new LocationStep(nt, LocationStep::SELF_AXIS);
-    NS_ENSURE_TRUE(nodeExpr, NS_ERROR_OUT_OF_MEMORY);
-
     nt.forget();
 
     mCharactersTemplate = new txValueOf(Move(nodeExpr), false);
-    NS_ENSURE_TRUE(mCharactersTemplate, NS_ERROR_OUT_OF_MEMORY);
-
     mCharactersTemplate->mNext = new txReturn();
-    NS_ENSURE_TRUE(mCharactersTemplate->mNext, NS_ERROR_OUT_OF_MEMORY);
 
     // pi/comment/namespace template
     mEmptyTemplate = new txReturn();
-    NS_ENSURE_TRUE(mEmptyTemplate, NS_ERROR_OUT_OF_MEMORY);
 
     return NS_OK;
 }
 
 txStylesheet::~txStylesheet()
 {
     // Delete all ImportFrames
     delete mRootFrame;
@@ -346,18 +327,16 @@ txStylesheet::doneCompiling()
             return NS_ERROR_OUT_OF_MEMORY;
         }
         
         frameStripSpaceTests.Clear();
     }
 
     if (!mDecimalFormats.get(txExpandedName())) {
         nsAutoPtr<txDecimalFormat> format(new txDecimalFormat);
-        NS_ENSURE_TRUE(format, NS_ERROR_OUT_OF_MEMORY);
-        
         rv = mDecimalFormats.add(txExpandedName(), format);
         NS_ENSURE_SUCCESS(rv, rv);
         
         format.forget();
     }
 
     return NS_OK;
 }
@@ -389,18 +368,16 @@ txStylesheet::addTemplate(txTemplateItem
 
     // get the txList for the right mode
     nsTArray<MatchableTemplate>* templates =
         aImportFrame->mMatchableTemplates.get(aTemplate->mMode);
 
     if (!templates) {
         nsAutoPtr< nsTArray<MatchableTemplate> > newList(
             new nsTArray<MatchableTemplate>);
-        NS_ENSURE_TRUE(newList, NS_ERROR_OUT_OF_MEMORY);
-
         rv = aImportFrame->mMatchableTemplates.set(aTemplate->mMode, newList);
         NS_ENSURE_SUCCESS(rv, rv);
 
         templates = newList.forget();
     }
 
     // Add the simple patterns to the list of matchable templates, according
     // to default priority
@@ -541,18 +518,16 @@ txStylesheet::addGlobalVariable(txVariab
 {
     if (mGlobalVariables.get(aVariable->mName)) {
         return NS_OK;
     }
     nsAutoPtr<GlobalVariable> var(
         new GlobalVariable(Move(aVariable->mValue),
                            Move(aVariable->mFirstInstruction),
                            aVariable->mIsParam));
-    NS_ENSURE_TRUE(var, NS_ERROR_OUT_OF_MEMORY);
-    
     nsresult rv = mGlobalVariables.add(aVariable->mName, var);
     NS_ENSURE_SUCCESS(rv, rv);
     
     var.forget();
     
     return NS_OK;
     
 }
@@ -561,18 +536,16 @@ nsresult
 txStylesheet::addKey(const txExpandedName& aName,
                      nsAutoPtr<txPattern> aMatch, nsAutoPtr<Expr> aUse)
 {
     nsresult rv = NS_OK;
 
     txXSLKey* xslKey = mKeys.get(aName);
     if (!xslKey) {
         xslKey = new txXSLKey(aName);
-        NS_ENSURE_TRUE(xslKey, NS_ERROR_OUT_OF_MEMORY);
-
         rv = mKeys.add(aName, xslKey);
         if (NS_FAILED(rv)) {
             delete xslKey;
             return rv;
         }
     }
     if (!xslKey->addKey(Move(aMatch), Move(aUse))) {
         return NS_ERROR_OUT_OF_MEMORY;
--- a/dom/xslt/xslt/txStylesheetCompileHandlers.cpp
+++ b/dom/xslt/xslt/txStylesheetCompileHandlers.cpp
@@ -108,18 +108,16 @@ parseUseAttrSets(txStylesheetAttr* aAttr
     nsWhitespaceTokenizer tok(attr->mValue);
     while (tok.hasMoreTokens()) {
         txExpandedName name;
         rv = name.init(tok.nextToken(), aState.mElementContext->mMappings,
                        false);
         NS_ENSURE_SUCCESS(rv, rv);
 
         nsAutoPtr<txInstruction> instr(new txInsertAttrSet(name));
-        NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
         rv = aState.addInstruction(Move(instr));
         NS_ENSURE_SUCCESS(rv, rv);
     }
     return NS_OK;
 }
 
 static nsresult
 parseExcludeResultPrefixes(txStylesheetAttr* aAttributes,
@@ -186,17 +184,16 @@ getExprAttr(txStylesheetAttr* aAttribute
     if (NS_FAILED(rv) && aState.ignoreError(rv)) {
         // use default value in fcp for not required exprs
         if (aRequired) {
             aExpr = new txErrorExpr(
 #ifdef TX_TO_STRING
                                     attr->mValue
 #endif
                                     );
-            NS_ENSURE_TRUE(aExpr, NS_ERROR_OUT_OF_MEMORY);
         }
         else {
             aExpr = nullptr;
         }
         return NS_OK;
     }
 
     return rv;
@@ -223,17 +220,16 @@ getAVTAttr(txStylesheetAttr* aAttributes
     if (NS_FAILED(rv) && aState.fcp()) {
         // use default value in fcp for not required exprs
         if (aRequired) {
             aAVT = new txErrorExpr(
 #ifdef TX_TO_STRING
                                    attr->mValue
 #endif
                                    );
-            NS_ENSURE_TRUE(aAVT, NS_ERROR_OUT_OF_MEMORY);
         }
         else {
             aAVT = nullptr;
         }
         return NS_OK;
     }
 
     return rv;
@@ -520,22 +516,18 @@ txFnStartLREStylesheet(int32_t aNamespac
     nsresult rv = getStyleAttr(aAttributes, aAttrCount, kNameSpaceID_XSLT,
                                nsGkAtoms::version, true, &attr);
     NS_ENSURE_SUCCESS(rv, rv);
 
     txExpandedName nullExpr;
     double prio = UnspecifiedNaN<double>();
 
     nsAutoPtr<txPattern> match(new txRootPattern());
-    NS_ENSURE_TRUE(match, NS_ERROR_OUT_OF_MEMORY);
-
     nsAutoPtr<txTemplateItem> templ(new txTemplateItem(Move(match), nullExpr,
                                                        nullExpr, prio));
-    NS_ENSURE_TRUE(templ, NS_ERROR_OUT_OF_MEMORY);
-
     aState.openInstructionContainer(templ);
     rv = aState.addToplevelItem(templ);
     NS_ENSURE_SUCCESS(rv, rv);
 
     templ.forget();
 
     rv = aState.pushHandlerTable(gTxTemplateHandler);
     NS_ENSURE_SUCCESS(rv, rv);
@@ -548,18 +540,16 @@ static nsresult
 txFnEndLREStylesheet(txStylesheetCompilerState& aState)
 {
     nsresult rv = txFnEndLRE(aState);
     NS_ENSURE_SUCCESS(rv, rv);
 
     aState.popHandlerTable();
 
     nsAutoPtr<txInstruction> instr(new txReturn());
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     aState.closeInstructionContainer();
 
     return NS_OK;
 }
 
@@ -633,18 +623,16 @@ txFnStartAttributeSet(int32_t aNamespace
 {
     nsresult rv = NS_OK;
     txExpandedName name;
     rv = getQNameAttr(aAttributes, aAttrCount, nsGkAtoms::name, true,
                       aState, name);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txAttributeSetItem> attrSet(new txAttributeSetItem(name));
-    NS_ENSURE_TRUE(attrSet, NS_ERROR_OUT_OF_MEMORY);
-
     aState.openInstructionContainer(attrSet);
 
     rv = aState.addToplevelItem(attrSet);
     NS_ENSURE_SUCCESS(rv, rv);
 
     attrSet.forget();
 
     rv = parseUseAttrSets(aAttributes, aAttrCount, false, aState);
@@ -654,18 +642,16 @@ txFnStartAttributeSet(int32_t aNamespace
 }
 
 static nsresult
 txFnEndAttributeSet(txStylesheetCompilerState& aState)
 {
     aState.popHandlerTable();
 
     nsAutoPtr<txInstruction> instr(new txReturn());
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     aState.closeInstructionContainer();
 
     return NS_OK;
 }
 
@@ -681,18 +667,16 @@ txFnStartDecimalFormat(int32_t aNamespac
 {
     nsresult rv = NS_OK;
     txExpandedName name;
     rv = getQNameAttr(aAttributes, aAttrCount, nsGkAtoms::name, false,
                       aState, name);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txDecimalFormat> format(new txDecimalFormat);
-    NS_ENSURE_TRUE(format, NS_ERROR_OUT_OF_MEMORY);
-
     rv = getCharAttr(aAttributes, aAttrCount, nsGkAtoms::decimalSeparator,
                      false, aState, format->mDecimalSeparator);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = getCharAttr(aAttributes, aAttrCount, nsGkAtoms::groupingSeparator,
                      false, aState, format->mGroupingSeparator);
     NS_ENSURE_SUCCESS(rv, rv);
 
@@ -756,21 +740,17 @@ static nsresult
 txFnStartImport(int32_t aNamespaceID,
                 nsIAtom* aLocalName,
                 nsIAtom* aPrefix,
                 txStylesheetAttr* aAttributes,
                 int32_t aAttrCount,
                 txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txImportItem> import(new txImportItem);
-    NS_ENSURE_TRUE(import, NS_ERROR_OUT_OF_MEMORY);
-    
     import->mFrame = new txStylesheet::ImportFrame;
-    NS_ENSURE_TRUE(import->mFrame, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addToplevelItem(import);
     NS_ENSURE_SUCCESS(rv, rv);
     
     txImportItem* importPtr = import.forget();
     
     txStylesheetAttr* attr = nullptr;
     rv = getStyleAttr(aAttributes, aAttrCount, kNameSpaceID_None,
                       nsGkAtoms::href, true, &attr);
@@ -905,17 +885,16 @@ txFnStartOutput(int32_t aNamespaceID,
                 nsIAtom* aPrefix,
                 txStylesheetAttr* aAttributes,
                 int32_t aAttrCount,
                 txStylesheetCompilerState& aState)
 {
     nsresult rv = NS_OK;
 
     nsAutoPtr<txOutputItem> item(new txOutputItem);
-    NS_ENSURE_TRUE(item, NS_ERROR_OUT_OF_MEMORY);
 
     txExpandedName methodExpName;
     rv = getQNameAttr(aAttributes, aAttrCount, nsGkAtoms::method, false,
                       aState, methodExpName);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!methodExpName.isNull()) {
         if (methodExpName.mNamespaceID != kNameSpaceID_None) {
@@ -972,18 +951,16 @@ txFnStartOutput(int32_t aNamespaceID,
     }
 
     getStyleAttr(aAttributes, aAttrCount, kNameSpaceID_None,
                  nsGkAtoms::cdataSectionElements, false, &attr);
     if (attr) {
         nsWhitespaceTokenizer tokens(attr->mValue);
         while (tokens.hasMoreTokens()) {
             nsAutoPtr<txExpandedName> qname(new txExpandedName());
-            NS_ENSURE_TRUE(qname, NS_ERROR_OUT_OF_MEMORY);
-
             rv = qname->init(tokens.nextToken(),
                              aState.mElementContext->mMappings, false);
             NS_ENSURE_SUCCESS(rv, rv);
 
             rv = item->mFormat.mCDATASectionElements.add(qname);
             NS_ENSURE_SUCCESS(rv, rv);
             qname.forget();
         }
@@ -1028,18 +1005,16 @@ txFnStartStripSpace(int32_t aNamespaceID
     txStylesheetAttr* attr = nullptr;
     nsresult rv = getStyleAttr(aAttributes, aAttrCount, kNameSpaceID_None,
                                nsGkAtoms::elements, true, &attr);
     NS_ENSURE_SUCCESS(rv, rv);
 
     bool strip = aLocalName == nsGkAtoms::stripSpace;
 
     nsAutoPtr<txStripSpaceItem> stripItem(new txStripSpaceItem);
-    NS_ENSURE_TRUE(stripItem, NS_ERROR_OUT_OF_MEMORY);
-
     nsWhitespaceTokenizer tokenizer(attr->mValue);
     while (tokenizer.hasMoreTokens()) {
         const nsASingleFragmentString& name = tokenizer.nextToken();
         int32_t ns = kNameSpaceID_None;
         nsCOMPtr<nsIAtom> prefix, localName;
         rv = XMLUtils::splitQName(name, getter_AddRefs(prefix),
                                   getter_AddRefs(localName));
         if (NS_FAILED(rv)) {
@@ -1070,18 +1045,16 @@ txFnStartStripSpace(int32_t aNamespaceID
             localName = nsGkAtoms::_asterisk;
         }
         if (prefix) {
             ns = aState.mElementContext->mMappings->lookupNamespace(prefix);
             NS_ENSURE_TRUE(ns != kNameSpaceID_Unknown, NS_ERROR_FAILURE);
         }
         nsAutoPtr<txStripSpaceTest> sst(new txStripSpaceTest(prefix, localName,
                                                              ns, strip));
-        NS_ENSURE_TRUE(sst, NS_ERROR_OUT_OF_MEMORY);
-
         rv = stripItem->addStripSpaceTest(sst);
         NS_ENSURE_SUCCESS(rv, rv);
         
         sst.forget();
     }
 
     rv = aState.addToplevelItem(stripItem);
     NS_ENSURE_SUCCESS(rv, rv);
@@ -1126,35 +1099,31 @@ txFnStartTemplate(int32_t aNamespaceID,
 
     nsAutoPtr<txPattern> match;
     rv = getPatternAttr(aAttributes, aAttrCount, nsGkAtoms::match,
                         name.isNull(), aState, match);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txTemplateItem> templ(new txTemplateItem(Move(match), name, mode,
                                                        prio));
-    NS_ENSURE_TRUE(templ, NS_ERROR_OUT_OF_MEMORY);
-
     aState.openInstructionContainer(templ);
     rv = aState.addToplevelItem(templ);
     NS_ENSURE_SUCCESS(rv, rv);
     
     templ.forget();
 
     return aState.pushHandlerTable(gTxParamHandler);
 }
 
 static nsresult
 txFnEndTemplate(txStylesheetCompilerState& aState)
 {
     aState.popHandlerTable();
 
     nsAutoPtr<txInstruction> instr(new txReturn());
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     aState.closeInstructionContainer();
 
     return NS_OK;
 }
 
@@ -1176,18 +1145,16 @@ txFnStartTopVariable(int32_t aNamespaceI
     nsAutoPtr<Expr> select;
     rv = getExprAttr(aAttributes, aAttrCount, nsGkAtoms::select, false,
                      aState, select);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txVariableItem> var(
         new txVariableItem(name, Move(select),
                            aLocalName == nsGkAtoms::param));
-    NS_ENSURE_TRUE(var, NS_ERROR_OUT_OF_MEMORY);
-
     aState.openInstructionContainer(var);
     rv = aState.pushPtr(var, aState.eVariableItem);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (var->mValue) {
         // XXX should be gTxErrorHandler?
         rv = aState.pushHandlerTable(gTxIgnoreHandler);
         NS_ENSURE_SUCCESS(rv, rv);
@@ -1213,23 +1180,20 @@ txFnEndTopVariable(txStylesheetCompilerS
     txVariableItem* var =
         static_cast<txVariableItem*>(aState.popPtr(aState.eVariableItem));
 
     if (prev == gTxTopVariableHandler) {
         // No children were found.
         NS_ASSERTION(!var->mValue,
                      "There shouldn't be a select-expression here");
         var->mValue = new txLiteralExpr(EmptyString());
-        NS_ENSURE_TRUE(var->mValue, NS_ERROR_OUT_OF_MEMORY);
     }
     else if (!var->mValue) {
         // If we don't have a select-expression there mush be children.
         nsAutoPtr<txInstruction> instr(new txReturn());
-        NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
         nsresult rv = aState.addInstruction(Move(instr));
         NS_ENSURE_SUCCESS(rv, rv);
     }
 
     aState.closeInstructionContainer();
 
     return NS_OK;
 }
@@ -1277,18 +1241,16 @@ txFnStartLRE(int32_t aNamespaceID,
              txStylesheetAttr* aAttributes,
              int32_t aAttrCount,
              txStylesheetCompilerState& aState)
 {
     nsresult rv = NS_OK;
 
     nsAutoPtr<txInstruction> instr(new txStartLREElement(aNamespaceID,
                                                          aLocalName, aPrefix));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
     
     rv = parseExcludeResultPrefixes(aAttributes, aAttrCount, kNameSpaceID_XSLT);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = parseUseAttrSets(aAttributes, aAttrCount, true, aState);
     NS_ENSURE_SUCCESS(rv, rv);
@@ -1308,31 +1270,27 @@ txFnStartLRE(int32_t aNamespaceID,
 
         nsAutoPtr<Expr> avt;
         rv = txExprParser::createAVT(attr->mValue, &aState,
                                      getter_Transfers(avt));
         NS_ENSURE_SUCCESS(rv, rv);
 
         instr = new txLREAttribute(attr->mNamespaceID, attr->mLocalName,
                                    attr->mPrefix, Move(avt));
-        NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-        
         rv = aState.addInstruction(Move(instr));
         NS_ENSURE_SUCCESS(rv, rv);
     }
 
     return NS_OK;
 }
 
 static nsresult
 txFnEndLRE(txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txInstruction> instr(new txEndElement);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
 }
 
 /*
   "LRE text"
@@ -1340,18 +1298,16 @@ txFnEndLRE(txStylesheetCompilerState& aS
   txText
 */
 static nsresult
 txFnText(const nsAString& aStr, txStylesheetCompilerState& aState)
 {
     TX_RETURN_IF_WHITESPACE(aStr, aState);
 
     nsAutoPtr<txInstruction> instr(new txText(aStr, false));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
 }
 
 /*
   xsl:apply-imports
@@ -1365,24 +1321,20 @@ txFnStartApplyImports(int32_t aNamespace
                       nsIAtom* aPrefix,
                       txStylesheetAttr* aAttributes,
                       int32_t aAttrCount,
                       txStylesheetCompilerState& aState)
 {
     nsresult rv = NS_OK;
 
     nsAutoPtr<txInstruction> instr(new txApplyImportsStart);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr = new txApplyImportsEnd;
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return aState.pushHandlerTable(gTxIgnoreHandler);
 }
 
 static nsresult
 txFnEndApplyImports(txStylesheetCompilerState& aState)
@@ -1408,53 +1360,43 @@ txFnStartApplyTemplates(int32_t aNamespa
                         nsIAtom* aPrefix,
                         txStylesheetAttr* aAttributes,
                         int32_t aAttrCount,
                         txStylesheetCompilerState& aState)
 {
     nsresult rv = NS_OK;
 
     nsAutoPtr<txInstruction> instr(new txPushParams);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     txExpandedName mode;
     rv = getQNameAttr(aAttributes, aAttrCount, nsGkAtoms::mode, false,
                       aState, mode);
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr = new txApplyTemplates(mode);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.pushObject(instr);
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr.forget();
 
     nsAutoPtr<Expr> select;
     rv = getExprAttr(aAttributes, aAttrCount, nsGkAtoms::select, false,
                      aState, select);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!select) {
         nsAutoPtr<txNodeTest> nt(
             new txNodeTypeTest(txNodeTypeTest::NODE_TYPE));
-        NS_ENSURE_TRUE(nt, NS_ERROR_OUT_OF_MEMORY);
-
         select = new LocationStep(nt, LocationStep::CHILD_AXIS);
-        NS_ENSURE_TRUE(select, NS_ERROR_OUT_OF_MEMORY);
-
         nt.forget();
     }
 
     nsAutoPtr<txPushNewContext> pushcontext( new txPushNewContext(Move(select)));
-    NS_ENSURE_TRUE(pushcontext, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.pushSorter(pushcontext);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = aState.pushObject(pushcontext);
     NS_ENSURE_SUCCESS(rv, rv);
     
     pushcontext.forget();
 
@@ -1471,28 +1413,24 @@ txFnEndApplyTemplates(txStylesheetCompil
     nsAutoPtr<txInstruction> instr(pushcontext); // txPushNewContext
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     aState.popSorter();
 
     instr = static_cast<txInstruction*>(aState.popObject()); // txApplyTemplates
     nsAutoPtr<txLoopNodeSet> loop(new txLoopNodeSet(instr));
-    NS_ENSURE_TRUE(loop, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr = loop.forget();
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr = new txPopParams;
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-    
     pushcontext->mBailTarget = instr;
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
 }
 
 /*
@@ -1508,35 +1446,31 @@ txFnStartAttribute(int32_t aNamespaceID,
                    nsIAtom* aPrefix,
                    txStylesheetAttr* aAttributes,
                    int32_t aAttrCount,
                    txStylesheetCompilerState& aState)
 {
     nsresult rv = NS_OK;
 
     nsAutoPtr<txInstruction> instr(new txPushStringHandler(true));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<Expr> name;
     rv = getAVTAttr(aAttributes, aAttrCount, nsGkAtoms::name, true,
                     aState, name);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<Expr> nspace;
     rv = getAVTAttr(aAttributes, aAttrCount, nsGkAtoms::_namespace, false,
                     aState, nspace);
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr = new txAttribute(Move(name), Move(nspace),
                             aState.mElementContext->mMappings);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.pushObject(instr);
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr.forget();
 
     // We need to push the template-handler since the current might be
     // the attributeset-handler
     return aState.pushHandlerTable(gTxTemplateHandler);
@@ -1568,29 +1502,25 @@ txFnStartCallTemplate(int32_t aNamespace
                       nsIAtom* aPrefix,
                       txStylesheetAttr* aAttributes,
                       int32_t aAttrCount,
                       txStylesheetCompilerState& aState)
 {
     nsresult rv = NS_OK;
 
     nsAutoPtr<txInstruction> instr(new txPushParams);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     txExpandedName name;
     rv = getQNameAttr(aAttributes, aAttrCount, nsGkAtoms::name, true,
                       aState, name);
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr = new txCallTemplate(name);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.pushObject(instr);
     NS_ENSURE_SUCCESS(rv, rv);
     
     instr.forget();
 
     return aState.pushHandlerTable(gTxCallTemplateHandler);
 }
 
@@ -1600,18 +1530,16 @@ txFnEndCallTemplate(txStylesheetCompiler
     aState.popHandlerTable();
 
     // txCallTemplate
     nsAutoPtr<txInstruction> instr(static_cast<txInstruction*>(aState.popObject()));
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr = new txPopParams;
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
 }
 
 /*
   xsl:choose
@@ -1669,30 +1597,26 @@ static nsresult
 txFnStartComment(int32_t aNamespaceID,
                  nsIAtom* aLocalName,
                  nsIAtom* aPrefix,
                  txStylesheetAttr* aAttributes,
                  int32_t aAttrCount,
                  txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txInstruction> instr(new txPushStringHandler(true));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
 }
 
 static nsresult
 txFnEndComment(txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txInstruction> instr(new txComment);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
 }
 
 /*
   xsl:copy
@@ -1707,18 +1631,16 @@ static nsresult
 txFnStartCopy(int32_t aNamespaceID,
               nsIAtom* aLocalName,
               nsIAtom* aPrefix,
               txStylesheetAttr* aAttributes,
               int32_t aAttrCount,
               txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txCopy> copy(new txCopy);
-    NS_ENSURE_TRUE(copy, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.pushPtr(copy, aState.eCopy);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txInstruction> instr(copy.forget());
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = parseUseAttrSets(aAttributes, aAttrCount, false, aState);
@@ -1726,18 +1648,16 @@ txFnStartCopy(int32_t aNamespaceID,
 
     return NS_OK;
 }
 
 static nsresult
 txFnEndCopy(txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txInstruction> instr(new txEndElement);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     txCopy* copy = static_cast<txCopy*>(aState.popPtr(aState.eCopy));
     rv = aState.addGotoTarget(&copy->mBailTarget);
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
@@ -1759,18 +1679,16 @@ txFnStartCopyOf(int32_t aNamespaceID,
     nsresult rv = NS_OK;
 
     nsAutoPtr<Expr> select;
     rv = getExprAttr(aAttributes, aAttrCount, nsGkAtoms::select, true,
                     aState, select);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txInstruction> instr(new txCopyOf(Move(select)));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-    
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return aState.pushHandlerTable(gTxIgnoreHandler);
 }
 
 static nsresult
 txFnEndCopyOf(txStylesheetCompilerState& aState)
@@ -1805,33 +1723,29 @@ txFnStartElement(int32_t aNamespaceID,
     nsAutoPtr<Expr> nspace;
     rv = getAVTAttr(aAttributes, aAttrCount, nsGkAtoms::_namespace, false,
                     aState, nspace);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txInstruction> instr(
         new txStartElement(Move(name), Move(nspace),
                            aState.mElementContext->mMappings));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = parseUseAttrSets(aAttributes, aAttrCount, false, aState);
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
 }
 
 static nsresult
 txFnEndElement(txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txInstruction> instr(new txEndElement);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
 }
 
 /*
     xsl:fallback
@@ -1881,31 +1795,27 @@ txFnStartForEach(int32_t aNamespaceID,
     nsresult rv = NS_OK;
 
     nsAutoPtr<Expr> select;
     rv = getExprAttr(aAttributes, aAttrCount, nsGkAtoms::select, true,
                      aState, select);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txPushNewContext> pushcontext(new txPushNewContext(Move(select)));
-    NS_ENSURE_TRUE(pushcontext, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.pushPtr(pushcontext, aState.ePushNewContext);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = aState.pushSorter(pushcontext);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txInstruction> instr(pushcontext.forget());
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
     
     instr = new txPushNullTemplateRule;
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.pushPtr(instr, aState.ePushNullTemplateRule);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return aState.pushHandlerTable(gTxForEachHandler);
 }
@@ -1974,18 +1884,16 @@ txFnStartIf(int32_t aNamespaceID,
 
     nsAutoPtr<Expr> test;
     rv = getExprAttr(aAttributes, aAttrCount, nsGkAtoms::test, true,
                      aState, test);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txConditionalGoto> condGoto(new txConditionalGoto(Move(test),
                                                                 nullptr));
-    NS_ENSURE_TRUE(condGoto, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.pushPtr(condGoto, aState.eConditionalGoto);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txInstruction> instr(condGoto.forget());
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
@@ -2010,29 +1918,25 @@ static nsresult
 txFnStartMessage(int32_t aNamespaceID,
                  nsIAtom* aLocalName,
                  nsIAtom* aPrefix,
                  txStylesheetAttr* aAttributes,
                  int32_t aAttrCount,
                  txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txInstruction> instr(new txPushStringHandler(false));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     txThreeState term;
     rv = getYesNoAttr(aAttributes, aAttrCount, nsGkAtoms::terminate,
                       false, aState, term);
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr = new txMessage(term == eTrue);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.pushObject(instr);
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr.forget();
 
     return NS_OK;
 }
 
@@ -2116,18 +2020,16 @@ txFnStartNumber(int32_t aNamespaceID,
     rv = getAVTAttr(aAttributes, aAttrCount, nsGkAtoms::groupingSize,
                     false, aState, groupingSize);
     NS_ENSURE_SUCCESS(rv, rv);
     
     nsAutoPtr<txInstruction> instr(new txNumber(level, Move(count), Move(from),
                                                 Move(value), Move(format),
                                                 Move(groupingSeparator),
                                                 Move(groupingSize)));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-    
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return aState.pushHandlerTable(gTxIgnoreHandler);
 }
 
 static nsresult
 txFnEndNumber(txStylesheetCompilerState& aState)
@@ -2197,18 +2099,16 @@ txFnStartParam(int32_t aNamespaceID,
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<Expr> select;
     rv = getExprAttr(aAttributes, aAttrCount, nsGkAtoms::select, false,
                      aState, select);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txSetVariable> var(new txSetVariable(name, Move(select)));
-    NS_ENSURE_TRUE(var, NS_ERROR_OUT_OF_MEMORY);
-
     if (var->mValue) {
         // XXX should be gTxErrorHandler?
         rv = aState.pushHandlerTable(gTxIgnoreHandler);
         NS_ENSURE_SUCCESS(rv, rv);
     }
     else {
         rv = aState.pushHandlerTable(gTxVariableHandler);
         NS_ENSURE_SUCCESS(rv, rv);
@@ -2230,17 +2130,16 @@ txFnEndParam(txStylesheetCompilerState& 
     txHandlerTable* prev = aState.mHandlerTable;
     aState.popHandlerTable();
 
     if (prev == gTxVariableHandler) {
         // No children were found.
         NS_ASSERTION(!var->mValue,
                      "There shouldn't be a select-expression here");
         var->mValue = new txLiteralExpr(EmptyString());
-        NS_ENSURE_TRUE(var->mValue, NS_ERROR_OUT_OF_MEMORY);
     }
 
     nsresult rv = aState.addVariable(var->mName);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txInstruction> instr(var.forget());
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
@@ -2263,29 +2162,25 @@ static nsresult
 txFnStartPI(int32_t aNamespaceID,
             nsIAtom* aLocalName,
             nsIAtom* aPrefix,
             txStylesheetAttr* aAttributes,
             int32_t aAttrCount,
             txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txInstruction> instr(new txPushStringHandler(true));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<Expr> name;
     rv = getAVTAttr(aAttributes, aAttrCount, nsGkAtoms::name, true,
                     aState, name);
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr = new txProcessingInstruction(Move(name));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.pushObject(instr);
     NS_ENSURE_SUCCESS(rv, rv);
 
     instr.forget();
 
     return NS_OK;
 }
 
@@ -2318,20 +2213,18 @@ txFnStartSort(int32_t aNamespaceID,
     nsAutoPtr<Expr> select;
     rv = getExprAttr(aAttributes, aAttrCount, nsGkAtoms::select, false,
                      aState, select);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!select) {
         nsAutoPtr<txNodeTest> nt(
               new txNodeTypeTest(txNodeTypeTest::NODE_TYPE));
-        NS_ENSURE_TRUE(nt, NS_ERROR_OUT_OF_MEMORY);
 
         select = new LocationStep(nt, LocationStep::SELF_AXIS);
-        NS_ENSURE_TRUE(select, NS_ERROR_OUT_OF_MEMORY);
 
         nt.forget();
     }
 
     nsAutoPtr<Expr> lang;
     rv = getAVTAttr(aAttributes, aAttrCount, nsGkAtoms::lang, false,
                     aState, lang);
     NS_ENSURE_SUCCESS(rv, rv);
@@ -2400,18 +2293,16 @@ txFnEndText(txStylesheetCompilerState& a
     aState.popHandlerTable();
     return NS_OK;
 }
 
 static nsresult
 txFnTextText(const nsAString& aStr, txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txInstruction> instr(new txText(aStr, aState.mDOE));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
 }
 
 /*
   xsl:value-of
@@ -2435,18 +2326,16 @@ txFnStartValueOf(int32_t aNamespaceID,
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<Expr> select;
     rv = getExprAttr(aAttributes, aAttrCount, nsGkAtoms::select, true,
                      aState, select);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txInstruction> instr(new txValueOf(Move(select), doe == eTrue));
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return aState.pushHandlerTable(gTxIgnoreHandler);
 }
 
 static nsresult
 txFnEndValueOf(txStylesheetCompilerState& aState)
@@ -2478,18 +2367,16 @@ txFnStartVariable(int32_t aNamespaceID,
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<Expr> select;
     rv = getExprAttr(aAttributes, aAttrCount, nsGkAtoms::select, false,
                      aState, select);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txSetVariable> var(new txSetVariable(name, Move(select)));
-    NS_ENSURE_TRUE(var, NS_ERROR_OUT_OF_MEMORY);
-
     if (var->mValue) {
         // XXX should be gTxErrorHandler?
         rv = aState.pushHandlerTable(gTxIgnoreHandler);
         NS_ENSURE_SUCCESS(rv, rv);
     }
     else {
         rv = aState.pushHandlerTable(gTxVariableHandler);
         NS_ENSURE_SUCCESS(rv, rv);
@@ -2512,17 +2399,16 @@ txFnEndVariable(txStylesheetCompilerStat
     txHandlerTable* prev = aState.mHandlerTable;
     aState.popHandlerTable();
 
     if (prev == gTxVariableHandler) {
         // No children were found.
         NS_ASSERTION(!var->mValue,
                      "There shouldn't be a select-expression here");
         var->mValue = new txLiteralExpr(EmptyString());
-        NS_ENSURE_TRUE(var->mValue, NS_ERROR_OUT_OF_MEMORY);
     }
 
     nsresult rv = aState.addVariable(var->mName);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txInstruction> instr(var.forget());
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
@@ -2534,34 +2420,30 @@ static nsresult
 txFnStartElementStartRTF(int32_t aNamespaceID,
                          nsIAtom* aLocalName,
                          nsIAtom* aPrefix,
                          txStylesheetAttr* aAttributes,
                          int32_t aAttrCount,
                          txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txInstruction> instr(new txPushRTFHandler);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     aState.mHandlerTable = gTxTemplateHandler;
 
     return NS_XSLT_GET_NEW_HANDLER;
 }
 
 static nsresult
 txFnTextStartRTF(const nsAString& aStr, txStylesheetCompilerState& aState)
 {
     TX_RETURN_IF_WHITESPACE(aStr, aState);
 
     nsAutoPtr<txInstruction> instr(new txPushRTFHandler);
-    NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     aState.mHandlerTable = gTxTemplateHandler;
 
     return NS_XSLT_GET_NEW_HANDLER;
 }
 
@@ -2582,35 +2464,31 @@ txFnStartWhen(int32_t aNamespaceID,
 
     nsAutoPtr<Expr> test;
     rv = getExprAttr(aAttributes, aAttrCount, nsGkAtoms::test, true,
                      aState, test);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txConditionalGoto> condGoto(new txConditionalGoto(Move(test),
                                                                 nullptr));
-    NS_ENSURE_TRUE(condGoto, NS_ERROR_OUT_OF_MEMORY);
-
     rv = aState.pushPtr(condGoto, aState.eConditionalGoto);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txInstruction> instr(condGoto.forget());
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return aState.pushHandlerTable(gTxTemplateHandler);
 }
 
 static nsresult
 txFnEndWhen(txStylesheetCompilerState& aState)
 {
     aState.popHandlerTable();
     nsAutoPtr<txGoTo> gotoinstr(new txGoTo(nullptr));
-    NS_ENSURE_TRUE(gotoinstr, NS_ERROR_OUT_OF_MEMORY);
-    
     nsresult rv = aState.mChooseGotoList->add(gotoinstr);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txInstruction> instr(gotoinstr.forget());
     rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     txConditionalGoto* condGoto =
@@ -2644,18 +2522,16 @@ txFnStartWithParam(int32_t aNamespaceID,
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<Expr> select;
     rv = getExprAttr(aAttributes, aAttrCount, nsGkAtoms::select, false,
                      aState, select);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoPtr<txSetParam> var(new txSetParam(name, Move(select)));
-    NS_ENSURE_TRUE(var, NS_ERROR_OUT_OF_MEMORY);
-
     if (var->mValue) {
         // XXX should be gTxErrorHandler?
         rv = aState.pushHandlerTable(gTxIgnoreHandler);
         NS_ENSURE_SUCCESS(rv, rv);
     }
     else {
         rv = aState.pushHandlerTable(gTxVariableHandler);
         NS_ENSURE_SUCCESS(rv, rv);
@@ -2676,17 +2552,16 @@ txFnEndWithParam(txStylesheetCompilerSta
     txHandlerTable* prev = aState.mHandlerTable;
     aState.popHandlerTable();
 
     if (prev == gTxVariableHandler) {
         // No children were found.
         NS_ASSERTION(!var->mValue,
                      "There shouldn't be a select-expression here");
         var->mValue = new txLiteralExpr(EmptyString());
-        NS_ENSURE_TRUE(var->mValue, NS_ERROR_OUT_OF_MEMORY);
     }
 
     nsAutoPtr<txInstruction> instr(var.forget());
     nsresult rv = aState.addInstruction(Move(instr));
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
 }
@@ -2720,18 +2595,16 @@ txFnStartUnknownInstruction(int32_t aNam
 
 static nsresult
 txFnEndUnknownInstruction(txStylesheetCompilerState& aState)
 {
     aState.popHandlerTable();
 
     if (aState.mSearchingForFallback) {
         nsAutoPtr<txInstruction> instr(new txErrorInstruction());
-        NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
         nsresult rv = aState.addInstruction(Move(instr));
         NS_ENSURE_SUCCESS(rv, rv);
     }
 
     aState.mSearchingForFallback = false;
 
     return NS_OK;
 }
--- a/dom/xslt/xslt/txStylesheetCompiler.cpp
+++ b/dom/xslt/xslt/txStylesheetCompiler.cpp
@@ -80,18 +80,16 @@ txStylesheetCompiler::startElement(int32
         txStylesheetAttr* attr = aAttributes + i;
         if (attr->mNamespaceID == kNameSpaceID_XMLNS) {
             rv = ensureNewElementContext();
             NS_ENSURE_SUCCESS(rv, rv);
 
             if (!hasOwnNamespaceMap) {
                 mElementContext->mMappings =
                     new txNamespaceMap(*mElementContext->mMappings);
-                NS_ENSURE_TRUE(mElementContext->mMappings,
-                               NS_ERROR_OUT_OF_MEMORY);
                 hasOwnNamespaceMap = true;
             }
 
             if (attr->mLocalName == nsGkAtoms::xmlns) {
                 mElementContext->mMappings->mapNamespace(nullptr, attr->mValue);
             }
             else {
                 mElementContext->mMappings->
@@ -116,17 +114,16 @@ txStylesheetCompiler::startElement(const
     }
 
     nsresult rv = flushCharacters();
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoArrayPtr<txStylesheetAttr> atts;
     if (aAttrCount > 0) {
         atts = new txStylesheetAttr[aAttrCount];
-        NS_ENSURE_TRUE(atts, NS_ERROR_OUT_OF_MEMORY);
     }
 
     bool hasOwnNamespaceMap = false;
     int32_t i;
     for (i = 0; i < aAttrCount; ++i) {
         rv = XMLUtils::splitExpatName(aAttrs[i * 2],
                                       getter_AddRefs(atts[i].mPrefix),
                                       getter_AddRefs(atts[i].mLocalName),
@@ -144,18 +141,16 @@ txStylesheetCompiler::startElement(const
 
         if (prefixToBind) {
             rv = ensureNewElementContext();
             NS_ENSURE_SUCCESS(rv, rv);
 
             if (!hasOwnNamespaceMap) {
                 mElementContext->mMappings =
                     new txNamespaceMap(*mElementContext->mMappings);
-                NS_ENSURE_TRUE(mElementContext->mMappings,
-                               NS_ERROR_OUT_OF_MEMORY);
                 hasOwnNamespaceMap = true;
             }
 
             rv = mElementContext->mMappings->
                 mapNamespace(prefixToBind, atts[i].mValue);
             NS_ENSURE_SUCCESS(rv, rv);
         }
     }
@@ -331,18 +326,16 @@ txStylesheetCompiler::endElement()
     nsresult rv = flushCharacters();
     NS_ENSURE_SUCCESS(rv, rv);
 
     int32_t i;
     for (i = mInScopeVariables.Length() - 1; i >= 0; --i) {
         txInScopeVariable* var = mInScopeVariables[i];
         if (!--(var->mLevel)) {
             nsAutoPtr<txInstruction> instr(new txRemoveVariable(var->mName));
-            NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
-
             rv = addInstruction(Move(instr));
             NS_ENSURE_SUCCESS(rv, rv);
             
             mInScopeVariables.RemoveElementAt(i);
             delete var;
         }
     }
 
@@ -477,18 +470,16 @@ txStylesheetCompiler::ensureNewElementCo
 {
     // Do we already have a new context?
     if (!mElementContext->mDepth) {
         return NS_OK;
     }
     
     nsAutoPtr<txElementContext>
         context(new txElementContext(*mElementContext));
-    NS_ENSURE_TRUE(context, NS_ERROR_OUT_OF_MEMORY);
-
     nsresult rv = pushObject(mElementContext);
     NS_ENSURE_SUCCESS(rv, rv);
 
     mElementContext.forget();
     mElementContext = Move(context);
 
     return NS_OK;
 }
@@ -567,30 +558,27 @@ txStylesheetCompilerState::init(const ns
     nsresult rv = NS_OK;
     if (aStylesheet) {
         mStylesheet = aStylesheet;
         mToplevelIterator = *aInsertPosition;
         mIsTopCompiler = false;
     }
     else {
         mStylesheet = new txStylesheet;
-        NS_ENSURE_TRUE(mStylesheet, NS_ERROR_OUT_OF_MEMORY);
-        
         rv = mStylesheet->init();
         NS_ENSURE_SUCCESS(rv, rv);
         
         mToplevelIterator =
             txListIterator(&mStylesheet->mRootFrame->mToplevelItems);
         mToplevelIterator.next(); // go to the end of the list
         mIsTopCompiler = true;
     }
    
     mElementContext = new txElementContext(aStylesheetURI);
-    NS_ENSURE_TRUE(mElementContext && mElementContext->mMappings,
-                   NS_ERROR_OUT_OF_MEMORY);
+    NS_ENSURE_TRUE(mElementContext->mMappings, NS_ERROR_OUT_OF_MEMORY);
 
     // Push the "old" txElementContext
     rv = pushObject(0);
     NS_ENSURE_SUCCESS(rv, rv);
     
     return NS_OK;
 }
 
@@ -644,17 +632,16 @@ txStylesheetCompilerState::popSorter()
 nsresult
 txStylesheetCompilerState::pushChooseGotoList()
 {
     nsresult rv = pushObject(mChooseGotoList);
     NS_ENSURE_SUCCESS(rv, rv);
 
     mChooseGotoList.forget();
     mChooseGotoList = new txList;
-    NS_ENSURE_TRUE(mChooseGotoList, NS_ERROR_OUT_OF_MEMORY);
 
     return NS_OK;
 }
 
 void
 txStylesheetCompilerState::popChooseGotoList()
 {
     // this will delete the old value
@@ -836,18 +823,16 @@ txStylesheetCompilerState::addGotoTarget
     
     return NS_OK;
 }
 
 nsresult
 txStylesheetCompilerState::addVariable(const txExpandedName& aName)
 {
     txInScopeVariable* var = new txInScopeVariable(aName);
-    NS_ENSURE_TRUE(var, NS_ERROR_OUT_OF_MEMORY);
-
     if (!mInScopeVariables.AppendElement(var)) {
         delete var;
         return NS_ERROR_OUT_OF_MEMORY;
     }
 
     return NS_OK;
 }
 
@@ -958,17 +943,18 @@ TX_ConstructXSLTFunction(nsIAtom* aName,
         *aFunction = new txXSLTEnvironmentFunctionCall(
             txXSLTEnvironmentFunctionCall::FUNCTION_AVAILABLE,
             aState->mElementContext->mMappings);
     }
     else {
         return NS_ERROR_XPATH_UNKNOWN_FUNCTION;
     }
 
-    return *aFunction ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+    MOZ_ASSERT(*aFunction);
+    return NS_OK;
 }
 
 typedef nsresult (*txFunctionFactory)(nsIAtom* aName,
                                       int32_t aNamespaceID,
                                       txStylesheetCompilerState* aState,
                                       FunctionCall** aResult);
 struct txFunctionFactoryMapping
 {
@@ -1029,19 +1015,16 @@ findFunction(nsIAtom* aName, int32_t aNa
         const txFunctionFactoryMapping& mapping = kExtensionFunctions[i];
         if (mapping.mNamespaceID == aNamespaceID) {
             return mapping.mFactory(aName, aNamespaceID, aState, aResult);
         }
     }
 
     if (!sXPCOMFunctionMappings) {
         sXPCOMFunctionMappings = new nsTArray<txXPCOMFunctionMapping>;
-        if (!sXPCOMFunctionMappings) {
-            return NS_ERROR_OUT_OF_MEMORY;
-        }
     }
 
     txXPCOMFunctionMapping *map = nullptr;
     uint32_t count = sXPCOMFunctionMappings->Length();
     for (i = 0; i < count; ++i) {
         map = &sXPCOMFunctionMappings->ElementAt(i);
         if (map->mNamespaceID == aNamespaceID) {
             break;
@@ -1099,17 +1082,17 @@ txStylesheetCompilerState::resolveFuncti
                                                FunctionCall **aFunction)
 {
     *aFunction = nullptr;
 
     nsresult rv = findFunction(aName, aID, this, aFunction);
     if (rv == NS_ERROR_XPATH_UNKNOWN_FUNCTION &&
         (aID != kNameSpaceID_None || fcp())) {
         *aFunction = new txErrorFunctionCall(aName);
-        rv = *aFunction ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+        rv = NS_OK;
     }
 
     return rv;
 }
 
 bool
 txStylesheetCompilerState::caseInsensitiveNameTests()
 {
--- a/dom/xslt/xslt/txXPathResultComparator.cpp
+++ b/dom/xslt/xslt/txXPathResultComparator.cpp
@@ -68,20 +68,16 @@ txResultStringComparator::createSortable
     if (!val) {
         return NS_ERROR_OUT_OF_MEMORY;
     }
 
     if (!mCollation)
         return NS_ERROR_FAILURE;
 
     val->mCaseKey = new nsString;
-    if (!val->mCaseKey) {
-        return NS_ERROR_OUT_OF_MEMORY;
-    }
-
     nsString& nsCaseKey = *(nsString *)val->mCaseKey;
     nsresult rv = aExpr->evaluateToString(aContext, nsCaseKey);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (nsCaseKey.IsEmpty()) {
         aResult = val.forget();
 
         return NS_OK;
--- a/dom/xslt/xslt/txXSLTNumber.cpp
+++ b/dom/xslt/xslt/txXSLTNumber.cpp
@@ -132,21 +132,19 @@ txXSLTNumber::getValueList(Expr* aValueE
             {
                 nodeTest = new txNodeTypeTest(txNodeTypeTest::TEXT_TYPE);
                 break;
             }
             case txXPathNodeType::PROCESSING_INSTRUCTION_NODE:
             {
                 txNodeTypeTest* typeTest;
                 typeTest = new txNodeTypeTest(txNodeTypeTest::PI_TYPE);
-                if (typeTest) {
-                    nsAutoString nodeName;
-                    txXPathNodeUtils::getNodeName(currNode, nodeName);
-                    typeTest->setNodeName(nodeName);
-                }
+                nsAutoString nodeName;
+                txXPathNodeUtils::getNodeName(currNode, nodeName);
+                typeTest->setNodeName(nodeName);
                 nodeTest = typeTest;
                 break;
             }
             case txXPathNodeType::COMMENT_NODE:
             {
                 nodeTest = new txNodeTypeTest(txNodeTypeTest::COMMENT_TYPE);
                 break;
             }
@@ -156,24 +154,18 @@ txXSLTNumber::getValueList(Expr* aValueE
             {
                 // this won't match anything as we walk up the tree
                 // but it's what the spec says to do
                 nodeTest = new txNameTest(0, nsGkAtoms::_asterisk, 0,
                                           nodeType);
                 break;
             }
         }
-        NS_ENSURE_TRUE(nodeTest, NS_ERROR_OUT_OF_MEMORY);
-
+        MOZ_ASSERT(nodeTest);
         countPattern = new txStepPattern(nodeTest, false);
-        if (!countPattern) {
-            // XXX error reporting
-            delete nodeTest;
-            return NS_ERROR_OUT_OF_MEMORY;
-        }
     }
 
 
     // Generate list of values depending on the value of the level-attribute
 
     // level = "single"
     if (aLevel == eLevelSingle) {
         txXPathTreeWalker walker(currNode);
--- a/dom/xslt/xslt/txXSLTNumberCounters.cpp
+++ b/dom/xslt/xslt/txXSLTNumberCounters.cpp
@@ -75,34 +75,35 @@ txFormattedCounter::getCounterFor(const 
             
             case '1':
             default:
                 // if we don't recognize the token then use "1"
                 aCounter = new txDecimalCounter(1, aGroupSize,
                                                 aGroupSeparator);
                 break;
         }
-        return aCounter ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+        MOZ_ASSERT(aCounter);
+        return NS_OK;
     }
     
     // for now, the only multi-char token we support are decimals
     int32_t i;
     for (i = 0; i < length-1; ++i) {
         if (aToken.CharAt(i) != '0')
             break;
     }
     if (i == length-1 && aToken.CharAt(i) == '1') {
         aCounter = new txDecimalCounter(length, aGroupSize, aGroupSeparator);
     }
     else {
         // if we don't recognize the token then use '1'
         aCounter = new txDecimalCounter(1, aGroupSize, aGroupSeparator);
     }
-
-    return aCounter ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+    MOZ_ASSERT(aCounter);
+    return NS_OK;
 }
 
 
 txDecimalCounter::txDecimalCounter(int32_t aMinLength, int32_t aGroupSize,
                                    const nsAString& aGroupSeparator)
     : mMinLength(aMinLength), mGroupSize(aGroupSize),
       mGroupSeparator(aGroupSeparator)
 {
--- a/dom/xul/templates/nsRDFBinding.cpp
+++ b/dom/xul/templates/nsRDFBinding.cpp
@@ -21,19 +21,16 @@ RDFBindingSet::~RDFBindingSet()
 
     MOZ_COUNT_DTOR(RDFBindingSet);
 }
 
 nsresult
 RDFBindingSet::AddBinding(nsIAtom* aVar, nsIAtom* aRef, nsIRDFResource* aPredicate)
 {
     RDFBinding* newbinding = new RDFBinding(aRef, aPredicate, aVar);
-    if (! newbinding)
-        return NS_ERROR_OUT_OF_MEMORY;
-
     if (mFirst) {
         RDFBinding* binding = mFirst;
 
         while (binding) { 
             // the binding is dependant on the calculation of a previous binding
             if (binding->mSubjectVariable == aVar)
                 newbinding->mHasDependency = true;
 
@@ -203,19 +200,16 @@ nsBindingValues::ClearBindingSet()
 nsresult
 nsBindingValues::SetBindingSet(RDFBindingSet* aBindings)
 {
     ClearBindingSet();
 
     int32_t count = aBindings->Count();
     if (count) {
         mValues = new nsCOMPtr<nsIRDFNode>[count];
-        if (!mValues)
-            return NS_ERROR_OUT_OF_MEMORY;
-
         mBindings = aBindings;
     }
     else {
         mValues = nullptr;
     }
 
     return NS_OK;
 }
--- a/dom/xul/templates/nsRDFConInstanceTestNode.cpp
+++ b/dom/xul/templates/nsRDFConInstanceTestNode.cpp
@@ -204,20 +204,16 @@ nsRDFConInstanceTestNode::FilterInstanti
                     (container == mContainer) ? "consistent" : "inconsistent"));
 
             if (((mEmpty == empty) && (mContainer == container)) ||
                 ((mEmpty == eDontCare) && (mContainer == container)) ||
                 ((mContainer == eDontCare) && (mEmpty == empty)))
             {
                 Element* element =
                     new nsRDFConInstanceTestNode::Element(valueres, container, empty);
-
-                if (! element)
-                    return NS_ERROR_OUT_OF_MEMORY;
-
                 inst->AddSupportingElement(element);
             }
             else {
                 aInstantiations.Erase(inst--);
             }
         }
     }
 
--- a/dom/xul/templates/nsRDFConMemberTestNode.cpp
+++ b/dom/xul/templates/nsRDFConMemberTestNode.cpp
@@ -174,20 +174,16 @@ nsRDFConMemberTestNode::FilterInstantiat
             MOZ_LOG(gXULTemplateLog, LogLevel::Debug,
                    ("    consistency check => %s", isconsistent ? "passed" : "failed"));
 
             if (isconsistent) {
                 // Add a memory element to our set-of-support.
                 Element* element =
                     new nsRDFConMemberTestNode::Element(containerRes,
                                                         memberValue);
-
-                if (! element)
-                    return NS_ERROR_OUT_OF_MEMORY;
-
                 inst->AddSupportingElement(element);
             }
             else {
                 // it's inconsistent. remove it.
                 aInstantiations.Erase(inst--);
             }
 
             // We're done, go on to the next instantiation
@@ -226,20 +222,16 @@ nsRDFConMemberTestNode::FilterInstantiat
                            ("    member => %s", NS_ConvertUTF16toUTF8(member).get()));
                 }
 
                 Instantiation newinst = *inst;
                 newinst.AddAssignment(mMemberVariable, node);
 
                 Element* element =
                     new nsRDFConMemberTestNode::Element(containerRes, node);
-
-                if (! element)
-                    return NS_ERROR_OUT_OF_MEMORY;
-
                 newinst.AddSupportingElement(element);
                 aInstantiations.Insert(inst, newinst);
             }
         }
 
         if (hasMemberBinding) {
             // Oh, this is so nasty. If we have a member assignment, then
             // grovel through each one of our inbound arcs to see if
@@ -315,20 +307,16 @@ nsRDFConMemberTestNode::FilterInstantiat
 
                         // Add a new instantiation
                         Instantiation newinst = *inst;
                         newinst.AddAssignment(mContainerVariable, source);
 
                         Element* element =
                             new nsRDFConMemberTestNode::Element(source,
                                                                 memberValue);
-
-                        if (! element)
-                            return NS_ERROR_OUT_OF_MEMORY;
-
                         newinst.AddSupportingElement(element);
 
                         aInstantiations.Insert(inst, newinst);
                     }
                 }
             }
         }
 
--- a/dom/xul/templates/nsRDFPropertyTestNode.cpp
+++ b/dom/xul/templates/nsRDFPropertyTestNode.cpp
@@ -175,20 +175,16 @@ nsRDFPropertyTestNode::FilterInstantiati
             MOZ_LOG(gXULTemplateLog, LogLevel::Debug,
                    ("    consistency check => %s", hasAssertion ? "passed" : "failed"));
 
             if (hasAssertion) {
                 // it's consistent.
                 Element* element =
                     new nsRDFPropertyTestNode::Element(sourceRes, mProperty,
                                                        targetValue);
-
-                if (! element)
-                    return NS_ERROR_OUT_OF_MEMORY;
-
                 inst->AddSupportingElement(element);
             }
             else {
                 // it's inconsistent. remove it.
                 aInstantiations.Erase(inst--);
             }
         }
         else if ((hasSourceBinding && ! hasTargetBinding) ||
@@ -269,20 +265,16 @@ nsRDFPropertyTestNode::FilterInstantiati
                 // instantiation set with the new assignment that we've
                 // introduced. Ownership will be transferred to the
                 Instantiation newinst = *inst;
                 newinst.AddAssignment(variable, value);
 
                 Element* element =
                     new nsRDFPropertyTestNode::Element(sourceRes, mProperty,
                                                        targetValue);
-
-                if (! element)
-                    return NS_ERROR_OUT_OF_MEMORY;
-
                 newinst.AddSupportingElement(element);
 
                 aInstantiations.Insert(inst, newinst);
             }
 
             // finally, remove the "under specified" instantiation.
             aInstantiations.Erase(inst--);
         }
--- a/dom/xul/templates/nsRDFQuery.cpp
+++ b/dom/xul/templates/nsRDFQuery.cpp
@@ -28,19 +28,16 @@ nsRDFQuery::Finish()
     mCachedResults = nullptr;
 }
 
 nsresult
 nsRDFQuery::SetCachedResults(nsXULTemplateQueryProcessorRDF* aProcessor,
                              const InstantiationSet& aInstantiations)
 {
     mCachedResults = new nsXULTemplateResultSetRDF(aProcessor, this, &aInstantiations);
-    if (! mCachedResults)
-        return NS_ERROR_OUT_OF_MEMORY;
-
     return NS_OK;
 }
 
 
 void
 nsRDFQuery::UseCachedResults(nsISimpleEnumerator** aResults)
 {
     *aResults = mCachedResults;
--- a/dom/xul/templates/nsResourceSet.cpp
+++ b/dom/xul/templates/nsResourceSet.cpp
@@ -51,19 +51,16 @@ nsResourceSet::Add(nsIRDFResource* aReso
         return NS_ERROR_NULL_POINTER;
 
     if (Contains(aResource))
         return NS_OK;
 
     if (mCount >= mCapacity) {
         int32_t capacity = mCapacity + 4;
         nsIRDFResource** resources = new nsIRDFResource*[capacity];
-        if (! resources)
-            return NS_ERROR_OUT_OF_MEMORY;
-
         for (int32_t i = mCount - 1; i >= 0; --i)
             resources[i] = mResources[i];
 
         delete[] mResources;
 
         mResources = resources;
         mCapacity = capacity;
     }
<