merge mozilla-inbound to mozilla-central a=merge
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Mon, 24 Jul 2017 13:01:44 +0200
changeset 419224 60a5308fa987676fa5ed9fd5b3ad6c9938af0539
parent 419205 758016d026077ebaf65aaecc8df437a7164dd9b5 (current diff)
parent 419223 5edfe512460d3d2f5f9577e7f76c4361bc9f7292 (diff)
child 419225 782617166c61dee0a16e387314211e10bd68fadb
child 419273 17d7de773b6d3aecd88fdd7882b7d236b4f62e37
child 419294 d055c4a269c41792c09bceeae314084c7eba9bc0
push id7566
push usermtabara@mozilla.com
push dateWed, 02 Aug 2017 08:25:16 +0000
treeherdermozilla-beta@86913f512c3c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone56.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
merge mozilla-inbound to mozilla-central a=merge
ipc/glue/CodeCoverageHandler.cpp
ipc/glue/CodeCoverageHandler.h
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -180,16 +180,19 @@
 @RESPATH@/components/appstartup.xpt
 @RESPATH@/components/autocomplete.xpt
 @RESPATH@/components/autoconfig.xpt
 @RESPATH@/components/browser-element.xpt
 @RESPATH@/browser/components/browsercompsbase.xpt
 @RESPATH@/browser/components/browser-feeds.xpt
 @RESPATH@/components/caps.xpt
 @RESPATH@/components/chrome.xpt
+#ifdef MOZ_CODE_COVERAGE
+@RESPATH@/components/code-coverage.xpt
+#endif
 @RESPATH@/components/commandhandler.xpt
 @RESPATH@/components/commandlines.xpt
 @RESPATH@/components/composer.xpt
 @RESPATH@/components/content_events.xpt
 @RESPATH@/components/content_html.xpt
 @RESPATH@/components/content_geckomediaplugins.xpt
 #ifdef MOZ_WEBRTC
 @RESPATH@/components/content_webrtc.xpt
--- a/devtools/server/tests/mochitest/chrome.ini
+++ b/devtools/server/tests/mochitest/chrome.ini
@@ -1,17 +1,20 @@
 [DEFAULT]
 tags = devtools
 skip-if = os == 'android'
 support-files =
   animation-data.html
+  doc_Debugger.Source.prototype.introductionType.xul
   Debugger.Source.prototype.element.js
   Debugger.Source.prototype.element-2.js
   Debugger.Source.prototype.element.html
   hello-actor.js
+  iframe1_makeGlobalObjectReference.html
+  iframe2_makeGlobalObjectReference.html
   inspector_css-properties.html
   inspector_getImageData.html
   inspector_getOffsetParent.html
   inspector-delay-image-response.sjs
   inspector-eyedropper.html
   inspector-helpers.js
   inspector-search-data.html
   inspector-styles-data.css
new file mode 100644
--- /dev/null
+++ b/devtools/server/tests/mochitest/doc_Debugger.Source.prototype.introductionType.xul
@@ -0,0 +1,4 @@
+<?xml version="1.0"?>
+<window xmlns='http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'>
+<script id='xulie'>function xulScriptFunc() { debugger; }</script>
+</window>
new file mode 100644
--- /dev/null
+++ b/devtools/server/tests/mochitest/iframe1_makeGlobalObjectReference.html
@@ -0,0 +1,1 @@
+<html>The word 'smorgasbord' spoken by an adorably plump child, symbolizing prosperity</html>
new file mode 100644
--- /dev/null
+++ b/devtools/server/tests/mochitest/iframe2_makeGlobalObjectReference.html
@@ -0,0 +1,1 @@
+<html>Her retrospection, in hindsight, was prescient.</html>
--- a/devtools/server/tests/mochitest/test_Debugger.Source.prototype.introductionType.html
+++ b/devtools/server/tests/mochitest/test_Debugger.Source.prototype.introductionType.html
@@ -28,19 +28,18 @@ let Tootles, TootlesDO;
 window.onload = function () {
   SimpleTest.waitForExplicitFinish();
   runNextTest();
 };
 
 addTest(function setup() {
   // Create an iframe to debug.
   let iframe = document.createElement("iframe");
-  iframe.src = "data:text/html," +
-               "<div id='Tootles' onclick='debugger;'>I'm a DIV!</div>" +
-               "<script id='Auddie'>function auddie() { debugger; }<\/script>";
+  iframe.srcdoc = "<div id='Tootles' onclick='debugger;'>I'm a DIV!</div>" +
+                  "<script id='Auddie'>function auddie() { debugger; }<\/script>";
   iframe.onload = onLoadHandler;
   document.body.appendChild(iframe);
 
   function onLoadHandler() {
     // Now that the iframe's window has been created, we can add
     // it as a debuggee.
     dbg = new Debugger();
     iframeDO = dbg.addDebuggee(iframe.contentWindow);
@@ -135,21 +134,17 @@ addTest(function InsertRover() {
 
     runNextTest();
   }
 });
 
 // Create a XUL document with a script element, and check its introduction type.
 addTest(function XULDocumentScript() {
   let xulFrame = document.createElement("iframe");
-  xulFrame.src = "data:application/vnd.mozilla.xul+xml;charset=utf-8," +
-                 "<?xml version=\"1.0\"?>" +
-                 "<window xmlns='http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'>" +
-                 "<script id='xulie'>function xulScriptFunc() { debugger; }<\/script>" +
-                 "</window>";
+  xulFrame.src = "doc_Debugger.Source.prototype.introductionType.xul";
   xulFrame.onload = xulLoaded;
   info("Appending iframe containing XUL document");
   document.body.appendChild(xulFrame);
 
   function xulLoaded() {
     info("Loaded XUL document");
     let xulFrameDO = dbg.addDebuggee(xulFrame.contentWindow);
     let xulFnDO = xulFrameDO.getOwnPropertyDescriptor("xulScriptFunc").value;
--- a/devtools/server/tests/mochitest/test_makeGlobalObjectReference.html
+++ b/devtools/server/tests/mochitest/test_makeGlobalObjectReference.html
@@ -19,18 +19,17 @@ Debugger.prototype.makeGlobalObjectRefer
 
 Components.utils.import("resource://gre/modules/jsdebugger.jsm");
 addDebuggerToGlobal(this);
 
 window.onload = function () {
   SimpleTest.waitForExplicitFinish();
 
   let iframe = document.createElement("iframe");
-  iframe.src = "data:text/html,<html>The word 'smorgasbord'," +
-               " spoken by an adorably plump child, symbolizing prosperity</html>";
+  iframe.src = "iframe1_makeGlobalObjectReference.html";
   iframe.onload = iframeOnLoad;
   document.body.appendChild(iframe);
 
   function iframeOnLoad() {
     let dbg = new Debugger();
 
     // 'o' for 'outer window'
     let g1o = iframe.contentWindow;
@@ -61,18 +60,17 @@ window.onload = function () {
     ok(dbg.addDebuggee(g1o) === g1iDO, "addDebuggee returns the inner window's D.O");
     ok(dbg.hasDebuggee(g1o), "addDebuggee adds the correct global");
     ok(dbg.hasDebuggee(g1iDO),
        "hasDebuggee can take a D.O referring to the inner window");
     ok(dbg.hasDebuggee(g1oDO),
        "hasDebuggee can take a D.O referring to the outer window");
 
     let iframe2 = document.createElement("iframe");
-    iframe2.src = "data:text/html,<html>Her retrospection," +
-                  " in hindsight, was prescient.</html>";
+    iframe2.src = "iframe2_makeGlobalObjectReference.html";
     iframe2.onload = iframe2OnLoad;
     document.body.appendChild(iframe2);
 
     function iframe2OnLoad() {
       // makeGlobalObjectReference dereferences CCWs.
       let g2o = iframe2.contentWindow;
       g2o.g1o = g1o;
 
--- a/devtools/shared/webconsole/test/test_commands_other.html
+++ b/devtools/shared/webconsole/test/test_commands_other.html
@@ -67,17 +67,27 @@ function testEnd() {
   gWin.close();
   gWin = null;
   closeDebugger(gState, function() {
     gState = null;
     SimpleTest.finish();
   });
 }
 
-window.onload = function() {
+let load = Task.async(function*() {
+  removeEventListener("load", load);
+
+  yield new Promise(resolve => {
+    SpecialPowers.pushPrefEnv({"set": [
+      ["security.data_uri.unique_opaque_origin", false],
+    ]}, resolve);
+  });
+
   // Open a content window to test XRay functionality on built in functions.
   gWin = window.open("data:text/html,");
   info ("Waiting for content window to load");
   gWin.onload = startTest;
-}
+});
+addEventListener("load", load);
+
 </script>
 </body>
 </html>
--- a/devtools/shared/webconsole/test/test_jsterm_queryselector.html
+++ b/devtools/shared/webconsole/test/test_jsterm_queryselector.html
@@ -118,17 +118,27 @@ function testEnd() {
   gWin.close();
   gWin = null;
   closeDebugger(gState, function() {
     gState = null;
     SimpleTest.finish();
   });
 }
 
-window.onload = function() {
+let load = Task.async(function*() {
+  removeEventListener("load", load);
+
+  yield new Promise(resolve => {
+    SpecialPowers.pushPrefEnv({"set": [
+      ["security.data_uri.unique_opaque_origin", false],
+    ]}, resolve);
+  });
+
   // Open a content window to test XRay functionality on built in functions.
   gWin = window.open("data:text/html,");
   info ("Waiting for content window to load");
   gWin.onload = startTest;
-}
+});
+addEventListener("load", load);
+
 </script>
 </body>
 </html>
--- a/docshell/test/chrome/test_principalInherit.xul
+++ b/docshell/test/chrome/test_principalInherit.xul
@@ -76,17 +76,18 @@ var tests = [
       });
       newWin.document.documentElement.appendChild(frame);
     });
   }
 ];
 
 addLoadEvent(function onLoad() {
   ok(Components.stack, "this test must be run with the system principal");
-  SimpleTest.executeSoon(nextTest);
+  SpecialPowers.pushPrefEnv({"set": [
+    ["security.data_uri.unique_opaque_origin", false]]}, nextTest);
 });
 
 function loadListener(target, func) {
   target.addEventListener("load", function lis() {
     target.removeEventListener("load", lis, true);
     func();
   }, true);
 }
--- a/dom/fetch/FetchDriver.cpp
+++ b/dom/fetch/FetchDriver.cpp
@@ -753,17 +753,21 @@ FetchDriver::OnDataAvailable(nsIRequest*
 }
 
 NS_IMETHODIMP
 FetchDriver::OnStopRequest(nsIRequest* aRequest,
                            nsISupports* aContext,
                            nsresult aStatusCode)
 {
   workers::AssertIsOnMainThread();
-  if (NS_FAILED(aStatusCode)) {
+
+  // We need to check mObserver, which is nulled by FailWithNetworkError(),
+  // because in the case of "error" redirect mode, aStatusCode may be NS_OK but
+  // mResponse will definitely be null so we must not take the else branch.
+  if (NS_FAILED(aStatusCode) || !mObserver) {
     nsCOMPtr<nsIAsyncOutputStream> outputStream = do_QueryInterface(mPipeOutputStream);
     if (outputStream) {
       outputStream->CloseWithStatus(NS_BINDING_FAILED);
     }
 
     // We proceed as usual here, since we've already created a successful response
     // from OnStartRequest.
   } else {
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -3537,16 +3537,40 @@ ContentChild::RecvShareCodeCoverageMutex
   CodeCoverageHandler::Init(aHandle);
   return IPC_OK();
 #else
   NS_RUNTIMEABORT("Shouldn't receive this message in non-code coverage builds!");
   return IPC_FAIL_NO_REASON(this);
 #endif
 }
 
+mozilla::ipc::IPCResult
+ContentChild::RecvDumpCodeCoverageCounters()
+{
+#ifdef MOZ_CODE_COVERAGE
+  CodeCoverageHandler::DumpCounters(0);
+  return IPC_OK();
+#else
+  NS_RUNTIMEABORT("Shouldn't receive this message in non-code coverage builds!");
+  return IPC_FAIL_NO_REASON(this);
+#endif
+}
+
+mozilla::ipc::IPCResult
+ContentChild::RecvResetCodeCoverageCounters()
+{
+#ifdef MOZ_CODE_COVERAGE
+  CodeCoverageHandler::ResetCounters(0);
+  return IPC_OK();
+#else
+  NS_RUNTIMEABORT("Shouldn't receive this message in non-code coverage builds!");
+  return IPC_FAIL_NO_REASON(this);
+#endif
+}
+
 already_AddRefed<nsIEventTarget>
 ContentChild::GetSpecificMessageEventTarget(const Message& aMsg)
 {
   if (aMsg.type() == PJavaScript::Msg_DropTemporaryStrongReferences__ID
       || aMsg.type() == PJavaScript::Msg_DropObject__ID) {
     return do_AddRef(SystemGroup::EventTargetFor(TaskCategory::Other));
   }
 
--- a/dom/ipc/ContentChild.h
+++ b/dom/ipc/ContentChild.h
@@ -601,16 +601,22 @@ public:
 
   mozilla::ipc::IPCResult
   RecvSetPermissionsWithKey(const nsCString& aPermissionKey,
                             nsTArray<IPC::Permission>&& aPerms) override;
 
   virtual mozilla::ipc::IPCResult
   RecvShareCodeCoverageMutex(const CrossProcessMutexHandle& aHandle) override;
 
+  virtual mozilla::ipc::IPCResult
+  RecvDumpCodeCoverageCounters() override;
+
+  virtual mozilla::ipc::IPCResult
+  RecvResetCodeCoverageCounters() override;
+
 #if defined(XP_WIN) && defined(ACCESSIBILITY)
   bool
   SendGetA11yContentId();
 #endif // defined(XP_WIN) && defined(ACCESSIBILITY)
 
   // Get a reference to the font family list passed from the chrome process,
   // for use during gfx initialization.
   InfallibleTArray<mozilla::dom::FontFamilyListEntry>&
--- a/dom/ipc/PContent.ipdl
+++ b/dom/ipc/PContent.ipdl
@@ -603,16 +603,18 @@ child:
      * plugins changes. The chrome process sends up the last epoch it observed.
      * If the epoch last seen by the content process is the same, the content
      * process ignores the update. Otherwise the content process updates its
      * list and reloads its plugins.
      **/
     async SetPluginList(uint32_t pluginEpoch, PluginTag[] plugins, FakePluginTag[] fakePlugins);
 
     async ShareCodeCoverageMutex(CrossProcessMutexHandle handle);
+    async DumpCodeCoverageCounters();
+    async ResetCodeCoverageCounters();
 
 parent:
     async InitBackground(Endpoint<PBackgroundParent> aEndpoint);
 
     sync CreateChildProcess(IPCTabContext context,
                             ProcessPriority priority,
                             TabId openerTabId,
                             TabId tabId)
--- a/dom/media/DOMMediaStream.cpp
+++ b/dom/media/DOMMediaStream.cpp
@@ -1529,183 +1529,8 @@ DOMAudioNodeMediaStream::CreateTrackUnio
                                                        AudioNode* aNode,
                                                        MediaStreamGraph* aGraph)
 {
   RefPtr<DOMAudioNodeMediaStream> stream = new DOMAudioNodeMediaStream(aWindow, aNode);
   stream->InitTrackUnionStream(aGraph);
   return stream.forget();
 }
 
-DOMHwMediaStream::DOMHwMediaStream(nsPIDOMWindowInner* aWindow)
-  : DOMLocalMediaStream(aWindow, nullptr)
-{
-#ifdef MOZ_WIDGET_GONK
-  if (!mWindow) {
-    NS_ERROR("Expected window here.");
-    mPrincipalHandle = PRINCIPAL_HANDLE_NONE;
-    return;
-  }
-  nsIDocument* doc = mWindow->GetExtantDoc();
-  if (!doc) {
-    NS_ERROR("Expected document here.");
-    mPrincipalHandle = PRINCIPAL_HANDLE_NONE;
-    return;
-  }
-  mPrincipalHandle = MakePrincipalHandle(doc->NodePrincipal());
-#endif
-}
-
-DOMHwMediaStream::~DOMHwMediaStream()
-{
-}
-
-already_AddRefed<DOMHwMediaStream>
-DOMHwMediaStream::CreateHwStream(nsPIDOMWindowInner* aWindow,
-                                 OverlayImage* aImage)
-{
-  RefPtr<DOMHwMediaStream> stream = new DOMHwMediaStream(aWindow);
-
-  MediaStreamGraph* graph =
-    MediaStreamGraph::GetInstance(MediaStreamGraph::SYSTEM_THREAD_DRIVER,
-                                  AudioChannel::Normal, aWindow);
-  stream->InitSourceStream(graph);
-  stream->Init(stream->GetInputStream(), aImage);
-
-  return stream.forget();
-}
-
-void
-DOMHwMediaStream::Init(MediaStream* stream, OverlayImage* aImage)
-{
-  SourceMediaStream* srcStream = stream->AsSourceStream();
-
-#ifdef MOZ_WIDGET_GONK
-  if (aImage) {
-    mOverlayImage = aImage;
-  } else {
-    Data imageData;
-    imageData.mOverlayId = DEFAULT_IMAGE_ID;
-    imageData.mSize.width = DEFAULT_IMAGE_WIDTH;
-    imageData.mSize.height = DEFAULT_IMAGE_HEIGHT;
-
-    mOverlayImage = new OverlayImage();
-    mOverlayImage->SetData(imageData);
-  }
-#endif
-
-  if (srcStream) {
-    VideoSegment segment;
-#ifdef MOZ_WIDGET_GONK
-    const StreamTime delta = STREAM_TIME_MAX; // Because MediaStreamGraph will run out frames in non-autoplay mode,
-                                              // we must give it bigger frame length to cover this situation.
-
-    RefPtr<Image> image = static_cast<Image*>(mOverlayImage.get());
-    mozilla::gfx::IntSize size = image->GetSize();
-
-    segment.AppendFrame(image.forget(), delta, size, mPrincipalHandle);
-#endif
-    srcStream->AddTrack(TRACK_VIDEO_PRIMARY, 0, new VideoSegment());
-    srcStream->AppendToTrack(TRACK_VIDEO_PRIMARY, &segment);
-    srcStream->AdvanceKnownTracksTime(STREAM_TIME_MAX);
-  }
-}
-
-int32_t
-DOMHwMediaStream::RequestOverlayId()
-{
-#ifdef MOZ_WIDGET_GONK
-  return mOverlayImage->GetOverlayId();
-#else
-  return -1;
-#endif
-}
-
-void
-DOMHwMediaStream::SetImageSize(uint32_t width, uint32_t height)
-{
-#ifdef MOZ_WIDGET_GONK
-  if (mOverlayImage->GetSidebandStream().IsValid()) {
-    OverlayImage::SidebandStreamData imgData;
-    imgData.mStream = mOverlayImage->GetSidebandStream();
-    imgData.mSize = IntSize(width, height);
-    mOverlayImage->SetData(imgData);
-  } else {
-    OverlayImage::Data imgData;
-    imgData.mOverlayId = mOverlayImage->GetOverlayId();
-    imgData.mSize = IntSize(width, height);
-    mOverlayImage->SetData(imgData);
-  }
-#endif
-
-  SourceMediaStream* srcStream = GetInputStream()->AsSourceStream();
-  StreamTracks::Track* track = srcStream->FindTrack(TRACK_VIDEO_PRIMARY);
-
-  if (!track || !track->GetSegment()) {
-    return;
-  }
-
-#ifdef MOZ_WIDGET_GONK
-  // Clear the old segment.
-  // Changing the existing content of segment is a Very BAD thing, and this way will
-  // confuse consumers of MediaStreams.
-  // It is only acceptable for DOMHwMediaStream
-  // because DOMHwMediaStream doesn't have consumers of TV streams currently.
-  track->GetSegment()->Clear();
-
-  // Change the image size.
-  const StreamTime delta = STREAM_TIME_MAX;
-  RefPtr<Image> image = static_cast<Image*>(mOverlayImage.get());
-  mozilla::gfx::IntSize size = image->GetSize();
-  VideoSegment segment;
-
-  segment.AppendFrame(image.forget(), delta, size, mPrincipalHandle);
-  srcStream->AppendToTrack(TRACK_VIDEO_PRIMARY, &segment);
-#endif
-}
-
-void
-DOMHwMediaStream::SetOverlayImage(OverlayImage* aImage)
-{
-  if (!aImage) {
-    return;
-  }
-#ifdef MOZ_WIDGET_GONK
-  mOverlayImage = aImage;
-#endif
-
-  SourceMediaStream* srcStream = GetInputStream()->AsSourceStream();
-  StreamTracks::Track* track = srcStream->FindTrack(TRACK_VIDEO_PRIMARY);
-
-  if (!track || !track->GetSegment()) {
-    return;
-  }
-
-#ifdef MOZ_WIDGET_GONK
-  // Clear the old segment.
-  // Changing the existing content of segment is a Very BAD thing, and this way will
-  // confuse consumers of MediaStreams.
-  // It is only acceptable for DOMHwMediaStream
-  // because DOMHwMediaStream doesn't have consumers of TV streams currently.
-  track->GetSegment()->Clear();
-
-  // Change the image size.
-  const StreamTime delta = STREAM_TIME_MAX;
-  RefPtr<Image> image = static_cast<Image*>(mOverlayImage.get());
-  mozilla::gfx::IntSize size = image->GetSize();
-  VideoSegment segment;
-
-  segment.AppendFrame(image.forget(), delta, size, mPrincipalHandle);
-  srcStream->AppendToTrack(TRACK_VIDEO_PRIMARY, &segment);
-#endif
-}
-
-void
-DOMHwMediaStream::SetOverlayId(int32_t aOverlayId)
-{
-#ifdef MOZ_WIDGET_GONK
-  OverlayImage::Data imgData;
-
-  imgData.mOverlayId = aOverlayId;
-  imgData.mSize = mOverlayImage->GetSize();
-
-  mOverlayImage->SetData(imgData);
-#endif
-}
--- a/dom/media/DOMMediaStream.h
+++ b/dom/media/DOMMediaStream.h
@@ -22,17 +22,16 @@
 // See dom/media/webaudio/AudioContext.h for more fun!
 #ifdef CurrentTime
 #undef CurrentTime
 #endif
 
 namespace mozilla {
 
 class AbstractThread;
-class DOMHwMediaStream;
 class DOMLocalMediaStream;
 class DOMMediaStream;
 class MediaStream;
 class MediaInputPort;
 class DirectMediaStreamListener;
 class MediaStreamGraph;
 class ProcessedMediaStream;
 
@@ -450,19 +449,16 @@ public:
 
   /**
    * Allows users to get access to media data without going through graph
    * queuing. Returns a bool to let us know if direct data will be delivered.
    */
   bool AddDirectListener(DirectMediaStreamListener *aListener);
   void RemoveDirectListener(DirectMediaStreamListener *aListener);
 
-  virtual DOMLocalMediaStream* AsDOMLocalMediaStream() { return nullptr; }
-  virtual DOMHwMediaStream* AsDOMHwMediaStream() { return nullptr; }
-
   /**
    * Legacy method that returns true when the playback stream has finished.
    */
   bool IsFinished() const;
 
   /**
    * Becomes inactive only when the playback stream has finished.
    */
@@ -823,45 +819,11 @@ protected:
   ~DOMAudioNodeMediaStream();
 
 private:
   // If this object wraps a stream owned by an AudioNode, we need to ensure that
   // the node isn't cycle-collected too early.
   RefPtr<AudioNode> mStreamNode;
 };
 
-class DOMHwMediaStream : public DOMLocalMediaStream
-{
-  typedef mozilla::gfx::IntSize IntSize;
-  typedef layers::OverlayImage OverlayImage;
-#ifdef MOZ_WIDGET_GONK
-  typedef layers::OverlayImage::Data Data;
-#endif
-
-public:
-  explicit DOMHwMediaStream(nsPIDOMWindowInner* aWindow);
-
-  static already_AddRefed<DOMHwMediaStream> CreateHwStream(nsPIDOMWindowInner* aWindow,
-                                                           OverlayImage* aImage = nullptr);
-  virtual DOMHwMediaStream* AsDOMHwMediaStream() override { return this; }
-  int32_t RequestOverlayId();
-  void SetOverlayId(int32_t aOverlayId);
-  void SetImageSize(uint32_t width, uint32_t height);
-  void SetOverlayImage(OverlayImage* aImage);
-
-protected:
-  ~DOMHwMediaStream();
-
-private:
-  void Init(MediaStream* aStream, OverlayImage* aImage);
-
-#ifdef MOZ_WIDGET_GONK
-  const int DEFAULT_IMAGE_ID = 0x01;
-  const int DEFAULT_IMAGE_WIDTH = 400;
-  const int DEFAULT_IMAGE_HEIGHT = 300;
-  RefPtr<OverlayImage> mOverlayImage;
-  PrincipalHandle mPrincipalHandle;
-#endif
-};
-
 } // namespace mozilla
 
 #endif /* NSDOMMEDIASTREAM_H_ */
--- a/dom/media/MediaData.cpp
+++ b/dom/media/MediaData.cpp
@@ -9,19 +9,16 @@
 #include "ImageContainer.h"
 #include "MediaInfo.h"
 #include "VideoUtils.h"
 #include "YCbCrUtils.h"
 #include "mozilla/layers/ImageBridgeChild.h"
 #include "mozilla/layers/KnowsCompositor.h"
 #include "mozilla/layers/SharedRGBImage.h"
 
-#ifdef MOZ_WIDGET_GONK
-#include <cutils/properties.h>
-#endif
 #include <stdint.h>
 
 #ifdef XP_WIN
 #include "mozilla/layers/D3D11YCbCrImage.h"
 #endif
 
 namespace mozilla {
 
@@ -139,41 +136,16 @@ static bool ValidateBufferAndPicture(con
     // The specified picture dimensions can't be contained inside the video
     // frame, we'll stomp memory if we try to copy it. Fail.
     NS_WARNING("Overflowing picture rect");
     return false;
   }
   return true;
 }
 
-#ifdef MOZ_WIDGET_GONK
-static bool
-IsYV12Format(const VideoData::YCbCrBuffer::Plane& aYPlane,
-             const VideoData::YCbCrBuffer::Plane& aCbPlane,
-             const VideoData::YCbCrBuffer::Plane& aCrPlane)
-{
-  return
-    aYPlane.mWidth % 2 == 0
-    && aYPlane.mHeight % 2 == 0
-    && aYPlane.mWidth / 2 == aCbPlane.mWidth
-    && aYPlane.mHeight / 2 == aCbPlane.mHeight
-    && aCbPlane.mWidth == aCrPlane.mWidth
-    && aCbPlane.mHeight == aCrPlane.mHeight;
-}
-
-static bool
-IsInEmulator()
-{
-  char propQemu[PROPERTY_VALUE_MAX];
-  property_get("ro.kernel.qemu", propQemu, "");
-  return !strncmp(propQemu, "1", 1);
-}
-
-#endif
-
 VideoData::VideoData(int64_t aOffset,
                      const TimeUnit& aTime,
                      const TimeUnit& aDuration,
                      bool aKeyframe,
                      const TimeUnit& aTimecode,
                      IntSize aDisplay,
                      layers::ImageContainer::FrameID aFrameID)
   : MediaData(VIDEO_DATA, aOffset, aTime, aDuration, 1)
@@ -330,29 +302,20 @@ VideoData::CreateAndCopyData(const Video
 
   RefPtr<VideoData> v(new VideoData(aOffset,
                                     aTime,
                                     aDuration,
                                     aKeyframe,
                                     aTimecode,
                                     aInfo.mDisplay,
                                     0));
-#ifdef MOZ_WIDGET_GONK
-  const YCbCrBuffer::Plane &Y = aBuffer.mPlanes[0];
-  const YCbCrBuffer::Plane &Cb = aBuffer.mPlanes[1];
-  const YCbCrBuffer::Plane &Cr = aBuffer.mPlanes[2];
-#endif
 
   // Currently our decoder only knows how to output to ImageFormat::PLANAR_YCBCR
   // format.
-#ifdef MOZ_WIDGET_GONK
-  if (IsYV12Format(Y, Cb, Cr) && !IsInEmulator()) {
-    v->mImage = new layers::GrallocImage();
-  }
-#elif XP_WIN
+#if XP_WIN
   if (aAllocator && aAllocator->GetCompositorBackendType()
                     == layers::LayersBackend::LAYERS_D3D11) {
     RefPtr<layers::D3D11YCbCrImage> d3d11Image = new layers::D3D11YCbCrImage();
     PlanarYCbCrData data = ConstructPlanarYCbCrData(aInfo, aBuffer, aPicture);
     if (d3d11Image->SetData(layers::ImageBridgeChild::GetSingleton()
                             ? layers::ImageBridgeChild::GetSingleton().get()
                             : aAllocator,
                             aContainer, data)) {
@@ -373,30 +336,16 @@ VideoData::CreateAndCopyData(const Video
   PlanarYCbCrImage* videoImage = v->mImage->AsPlanarYCbCrImage();
   MOZ_ASSERT(videoImage);
 
   if (!VideoData::SetVideoDataToImage(videoImage, aInfo, aBuffer, aPicture,
                                       true /* aCopyData */)) {
     return nullptr;
   }
 
-#ifdef MOZ_WIDGET_GONK
-  if (!videoImage->IsValid() && IsYV12Format(Y, Cb, Cr)) {
-    // Failed to allocate gralloc. Try fallback.
-    v->mImage = aContainer->CreatePlanarYCbCrImage();
-    if (!v->mImage) {
-      return nullptr;
-    }
-    videoImage = v->mImage->AsPlanarYCbCrImage();
-    if (!VideoData::SetVideoDataToImage(videoImage, aInfo, aBuffer, aPicture,
-                                        true /* aCopyData */)) {
-      return nullptr;
-    }
-  }
-#endif
   return v.forget();
 }
 
 
 /* static */
 already_AddRefed<VideoData>
 VideoData::CreateAndCopyData(const VideoInfo& aInfo,
                              ImageContainer* aContainer,
--- a/dom/media/MediaManager.cpp
+++ b/dom/media/MediaManager.cpp
@@ -7,19 +7,16 @@
 #include "MediaManager.h"
 
 #include "MediaStreamGraph.h"
 #include "mozilla/dom/MediaStreamTrack.h"
 #include "MediaStreamListener.h"
 #include "nsArray.h"
 #include "nsContentUtils.h"
 #include "nsHashPropertyBag.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsIAudioManager.h"
-#endif
 #include "nsIEventTarget.h"
 #include "nsIUUIDGenerator.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIPermissionManager.h"
 #include "nsIPopupWindowManager.h"
 #include "nsIDocShell.h"
 #include "nsIDocument.h"
 #include "nsISupportsPrimitives.h"
@@ -1657,17 +1654,17 @@ private:
 
   bool mDeviceChosen;
 public:
   nsAutoPtr<MediaManager::SourceSet> mSourceSet;
 private:
   RefPtr<MediaManager> mManager; // get ref to this when creating the runnable
 };
 
-#if defined(ANDROID) && !defined(MOZ_WIDGET_GONK)
+#if defined(ANDROID)
 class GetUserMediaRunnableWrapper : public Runnable
 {
 public:
   // This object must take ownership of task
   GetUserMediaRunnableWrapper(GetUserMediaTask* task)
     : Runnable("GetUserMediaRunnableWrapper")
     , mTask(task) {
   }
@@ -1881,17 +1878,16 @@ MediaManager::Get() {
     nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
     if (obs) {
       obs->AddObserver(sSingleton, "last-pb-context-exited", false);
       obs->AddObserver(sSingleton, "getUserMedia:got-device-permission", false);
       obs->AddObserver(sSingleton, "getUserMedia:privileged:allow", false);
       obs->AddObserver(sSingleton, "getUserMedia:response:allow", false);
       obs->AddObserver(sSingleton, "getUserMedia:response:deny", false);
       obs->AddObserver(sSingleton, "getUserMedia:revoke", false);
-      obs->AddObserver(sSingleton, "phone-state-changed", false);
     }
     // else MediaManager won't work properly and will leak (see bug 837874)
     nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
     if (prefs) {
       prefs->AddObserver("media.navigator.video.default_width", sSingleton, false);
       prefs->AddObserver("media.navigator.video.default_height", sSingleton, false);
       prefs->AddObserver("media.navigator.video.default_fps", sSingleton, false);
       prefs->AddObserver("media.navigator.video.default_minfps", sSingleton, false);
@@ -3204,28 +3200,16 @@ MediaManager::Observe(nsISupports* aSubj
       MOZ_ASSERT(NS_SUCCEEDED(rv));
       if (NS_SUCCEEDED(rv)) {
         LOG(("Revoking MediaCapture access for window %" PRIu64, windowID));
         OnNavigation(windowID);
       }
     }
     return NS_OK;
   }
-#ifdef MOZ_WIDGET_GONK
-  else if (!strcmp(aTopic, "phone-state-changed")) {
-    nsString state(aData);
-    nsresult rv;
-    uint32_t phoneState = state.ToInteger(&rv);
-
-    if (NS_SUCCEEDED(rv) && phoneState == nsIAudioManager::PHONE_STATE_IN_CALL) {
-      StopMediaStreams();
-    }
-    return NS_OK;
-  }
-#endif
 
   return NS_OK;
 }
 
 nsresult
 MediaManager::GetActiveMediaCaptureWindows(nsIArray** aArray)
 {
   MOZ_ASSERT(aArray);
--- a/dom/media/encoder/OpusTrackEncoder.cpp
+++ b/dom/media/encoder/OpusTrackEncoder.cpp
@@ -5,22 +5,17 @@
 #include "OpusTrackEncoder.h"
 #include "nsString.h"
 #include "GeckoProfiler.h"
 #include "mozilla/CheckedInt.h"
 
 #include <opus/opus.h>
 
 #undef LOG
-#ifdef MOZ_WIDGET_GONK
-#include <android/log.h>
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "MediaEncoder", ## args);
-#else
 #define LOG(args, ...)
-#endif
 
 namespace mozilla {
 
 // The Opus format supports up to 8 channels, and supports multitrack audio up
 // to 255 channels, but the current implementation supports only mono and
 // stereo, and downmixes any more than that.
 static const int MAX_SUPPORTED_AUDIO_CHANNELS = 8;
 
--- a/dom/media/gmp/GMPServiceParent.cpp
+++ b/dom/media/gmp/GMPServiceParent.cpp
@@ -204,21 +204,17 @@ GeckoMediaPluginServiceParent::InitStora
 
   // GMP storage should be used in the chrome process only.
   if (!XRE_IsParentProcess()) {
     return NS_OK;
   }
 
   // Directory service is main thread only, so cache the profile dir here
   // so that we can use it off main thread.
-#ifdef MOZ_WIDGET_GONK
-  nsresult rv = NS_NewLocalFile(NS_LITERAL_STRING("/data/b2g/mozilla"), false, getter_AddRefs(mStorageBaseDir));
-#else
   nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(mStorageBaseDir));
-#endif
 
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
   rv = mStorageBaseDir->AppendNative(NS_LITERAL_CSTRING("gmp"));
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
--- a/dom/media/ogg/OggCodecState.cpp
+++ b/dom/media/ogg/OggCodecState.cpp
@@ -14,28 +14,16 @@
 #include "OggCodecState.h"
 #include "OpusDecoder.h"
 #include "OpusParser.h"
 #include "VideoUtils.h"
 #include "XiphExtradata.h"
 #include "nsDebug.h"
 #include "opus/opus_multistream.h"
 
-// On Android JellyBean, the hardware.h header redefines version_major and
-// version_minor, which breaks our build.  See:
-// https://bugzilla.mozilla.org/show_bug.cgi?id=912702#c6
-#ifdef MOZ_WIDGET_GONK
-#ifdef version_major
-#undef version_major
-#endif
-#ifdef version_minor
-#undef version_minor
-#endif
-#endif
-
 namespace mozilla {
 
 extern LazyLogModule gMediaDecoderLog;
 #define LOG(type, msg) MOZ_LOG(gMediaDecoderLog, type, msg)
 
 using media::TimeUnit;
 
 /** Decoder base class for Ogg-encapsulated streams. */
--- a/dom/media/ogg/OggWriter.cpp
+++ b/dom/media/ogg/OggWriter.cpp
@@ -2,22 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 #include "OggWriter.h"
 #include "prtime.h"
 #include "GeckoProfiler.h"
 
 #undef LOG
-#ifdef MOZ_WIDGET_GONK
-#include <android/log.h>
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "MediaEncoder", ## args);
-#else
 #define LOG(args, ...)
-#endif
 
 namespace mozilla {
 
 OggWriter::OggWriter() : ContainerWriter()
 {
   if (NS_FAILED(Init())) {
     LOG("ERROR! Fail to initialize the OggWriter.");
   }
--- a/dom/media/platforms/omx/OmxPlatformLayer.cpp
+++ b/dom/media/platforms/omx/OmxPlatformLayer.cpp
@@ -3,21 +3,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "OmxPlatformLayer.h"
 
 #include "OMX_VideoExt.h" // For VP8.
 
-#if defined(MOZ_WIDGET_GONK) && (ANDROID_VERSION == 20 || ANDROID_VERSION == 19)
-#define OMX_PLATFORM_GONK
-#include "GonkOmxPlatformLayer.h"
-#endif
-
 #include "VPXDecoder.h"
 
 #ifdef LOG
 #undef LOG
 #endif
 
 #define LOG(arg, ...) MOZ_LOG(sPDMLog, mozilla::LogLevel::Debug, ("OmxPlatformLayer -- %s: " arg, __func__, ##__VA_ARGS__))
 
--- a/dom/media/systemservices/MediaSystemResourceService.cpp
+++ b/dom/media/systemservices/MediaSystemResourceService.cpp
@@ -42,33 +42,16 @@ MediaSystemResourceService::Shutdown()
     sSingleton = nullptr;
   }
 }
 
 MediaSystemResourceService::MediaSystemResourceService()
   : mDestroyed(false)
 {
   MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
-#ifdef MOZ_WIDGET_GONK
-  // The maximum number of hardware resoureces available.
-  // XXX need to hange to a dynamic way.
-  enum
-  {
-    VIDEO_DECODER_COUNT = 1,
-    VIDEO_ENCODER_COUNT = 1
-  };
-
-  MediaSystemResource* resource;
-
-  resource = new MediaSystemResource(VIDEO_DECODER_COUNT);
-  mResources.Put(static_cast<uint32_t>(MediaSystemResourceType::VIDEO_DECODER), resource);
-
-  resource = new MediaSystemResource(VIDEO_ENCODER_COUNT);
-  mResources.Put(static_cast<uint32_t>(MediaSystemResourceType::VIDEO_ENCODER), resource);
-#endif
 }
 
 MediaSystemResourceService::~MediaSystemResourceService()
 {
 }
 
 void
 MediaSystemResourceService::Destroy()
--- a/dom/media/webrtc/MediaEngineCameraVideoSource.cpp
+++ b/dom/media/webrtc/MediaEngineCameraVideoSource.cpp
@@ -332,17 +332,17 @@ MediaEngineCameraVideoSource::ChooseCapa
 void
 MediaEngineCameraVideoSource::SetName(nsString aName)
 {
   mDeviceName = aName;
   bool hasFacingMode = false;
   VideoFacingModeEnum facingMode = VideoFacingModeEnum::User;
 
   // Set facing mode based on device name.
-#if defined(ANDROID) && !defined(MOZ_WIDGET_GONK)
+#if defined(ANDROID)
   // Names are generated. Example: "Camera 0, Facing back, Orientation 90"
   //
   // See media/webrtc/trunk/webrtc/modules/video_capture/android/java/src/org/
   // webrtc/videoengine/VideoCaptureDeviceInfoAndroid.java
 
   if (aName.Find(NS_LITERAL_STRING("Facing back")) != kNotFound) {
     hasFacingMode = true;
     facingMode = VideoFacingModeEnum::Environment;
--- a/dom/media/webrtc/MediaEngineDefault.cpp
+++ b/dom/media/webrtc/MediaEngineDefault.cpp
@@ -182,17 +182,17 @@ MediaEngineDefaultVideoSource::Start(Sou
   }
 
   aStream->AddTrack(aID, 0, new VideoSegment(), SourceMediaStream::ADDTRACK_QUEUED);
 
   // Remember TrackID so we can end it later
   mTrackID = aID;
 
   // Start timer for subsequent frames
-#if (defined(MOZ_WIDGET_GONK) || defined(MOZ_WIDGET_ANDROID)) && defined(DEBUG)
+#if defined(MOZ_WIDGET_ANDROID) && defined(DEBUG)
 // emulator debug is very, very slow and has problems dealing with realtime audio inputs
   mTimer->InitWithCallback(this, (1000 / mOpts.mFPS)*10, nsITimer::TYPE_REPEATING_SLACK);
 #else
   mTimer->InitWithCallback(this, 1000 / mOpts.mFPS, nsITimer::TYPE_REPEATING_SLACK);
 #endif
   mState = kStarted;
 
   return NS_OK;
--- a/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp
+++ b/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp
@@ -354,19 +354,16 @@ MediaEngineRemoteVideoSource::NotifyPull
     // nullptr images are allowed
     AppendToTrack(aSource, mImage, aID, delta, aPrincipalHandle);
   }
 }
 
 void
 MediaEngineRemoteVideoSource::FrameSizeChange(unsigned int w, unsigned int h)
 {
-#if defined(MOZ_WIDGET_GONK)
-  mMonitor.AssertCurrentThreadOwns(); // mWidth and mHeight are protected...
-#endif
   if ((mWidth < 0) || (mHeight < 0) ||
       (w !=  (unsigned int) mWidth) || (h != (unsigned int) mHeight)) {
     LOG(("MediaEngineRemoteVideoSource Video FrameSizeChange: %ux%u was %ux%u", w, h, mWidth, mHeight));
     mWidth = w;
     mHeight = h;
 
     auto settings = mSettings;
     NS_DispatchToMainThread(media::NewRunnableFrom([settings, w, h]() mutable {
--- a/dom/media/webrtc/MediaEngineWebRTC.cpp
+++ b/dom/media/webrtc/MediaEngineWebRTC.cpp
@@ -320,17 +320,17 @@ MediaEngineWebRTC::EnumerateAudioDevices
     } else {
       mAudioInput = new mozilla::AudioInputWebRTC(mVoiceEngine);
     }
   }
 
   int nDevices = 0;
   mAudioInput->GetNumOfRecordingDevices(nDevices);
   int i;
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
   i = 0; // Bug 1037025 - let the OS handle defaulting for now on android/b2g
 #else
   // -1 is "default communications device" depending on OS in webrtc.org code
   i = -1;
 #endif
   for (; i < nDevices; i++) {
     // We use constants here because GetRecordingDeviceName takes char[128].
     char deviceName[128];
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/fetch/file_fetch_cached_redirect.html
@@ -0,0 +1,1 @@
+<html><body>My contents don't matter.  Only my header matters!</body></html>
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/fetch/file_fetch_cached_redirect.html^headers^
@@ -0,0 +1,3 @@
+HTTP 302 Redirect
+Location: //example.org/target_does_not_matter.html
+Cache-Control: max-age=10
--- a/dom/tests/mochitest/fetch/mochitest.ini
+++ b/dom/tests/mochitest/fetch/mochitest.ini
@@ -1,16 +1,19 @@
 [DEFAULT]
 support-files =
   fetch_test_framework.js
   file_fetch_controller.html
+  file_fetch_cached_redirect.html
+  file_fetch_cached_redirect.html^headers^
   file_fetch_csp_block_frame.html
   file_fetch_csp_block_frame.html^headers^
   test_fetch_basic.js
   test_fetch_basic_http.js
+  test_fetch_cached_redirect.js
   test_fetch_cors.js
   file_fetch_observer.html
   test_formdataparsing.js
   test_headers_common.js
   test_request.js
   test_response.js
   utils.js
   nested_worker_wrapper.js
@@ -45,16 +48,17 @@ support-files =
 [test_headers_sw_reroute.html]
 [test_headers_mainthread.html]
 [test_fetch_basic.html]
 [test_fetch_basic_sw_reroute.html]
 [test_fetch_basic_sw_empty_reroute.html]
 [test_fetch_basic_http.html]
 [test_fetch_basic_http_sw_reroute.html]
 [test_fetch_basic_http_sw_empty_reroute.html]
+[test_fetch_cached_redirect.html]
 [test_fetch_controller.html]
 [test_fetch_cors.html]
 skip-if = toolkit == 'android' && debug # Bug 1210282
 [test_fetch_cors_sw_reroute.html]
 skip-if = toolkit == 'android' && debug # Bug 1210282
 [test_fetch_cors_sw_empty_reroute.html]
 skip-if = toolkit == 'android' && debug # Bug 1210282
 [test_fetch_csp_block.html]
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/fetch/test_fetch_cached_redirect.html
@@ -0,0 +1,22 @@
+<!--
+  Any copyright is dedicated to the Public Domain.
+  http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Bug 1374943 - Test fetch cached redirects</title>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <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 type="text/javascript" src="utils.js"> </script>
+<script type="text/javascript" src="fetch_test_framework.js"> </script>
+<script class="testbody" type="text/javascript">
+testScript("test_fetch_cached_redirect.js");
+</script>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/fetch/test_fetch_cached_redirect.js
@@ -0,0 +1,20 @@
+async function testCachedRedirectErrorMode() {
+  // This is a file that returns a 302 to someplace else and will be cached.
+  const REDIRECTING_URL = "file_fetch_cached_redirect.html";
+
+  let firstResponse = await(fetch(REDIRECTING_URL, { redirect: "manual" }));
+  // okay, now it should be in the cahce.
+  try {
+    let secondResponse = await(fetch(REDIRECTING_URL, { redirect: "error" }));
+  } catch(ex) {
+
+  }
+
+  ok(true, "didn't crash");
+}
+
+function runTest() {
+  return Promise.resolve()
+    .then(testCachedRedirectErrorMode)
+    // Put more promise based tests here.
+}
--- a/gfx/2d/ScaledFontDWrite.h
+++ b/gfx/2d/ScaledFontDWrite.h
@@ -34,18 +34,18 @@ public:
   {}
 
   ScaledFontDWrite(IDWriteFontFace *aFontFace,
                    const RefPtr<UnscaledFont>& aUnscaledFont,
                    Float aSize,
                    bool aUseEmbeddedBitmap,
                    bool aForceGDIMode,
                    IDWriteRenderingParams *aParams,
+                   Float aGamma,
                    Float aContrast,
-                   Float aGamma,
                    const gfxFontStyle* aStyle = nullptr);
 
   FontType GetType() const override { return FontType::DWRITE; }
 
   already_AddRefed<Path> GetPathForGlyphs(const GlyphBuffer &aBuffer, const DrawTarget *aTarget) override;
   void CopyGlyphsToBuilder(const GlyphBuffer &aBuffer, PathBuilder *aBuilder, const Matrix *aTransformHint) override;
 
   void CopyGlyphsToSink(const GlyphBuffer &aBuffer, ID2D1GeometrySink *aSink);
--- a/gfx/layers/wr/WebRenderBridgeParent.cpp
+++ b/gfx/layers/wr/WebRenderBridgeParent.cpp
@@ -1090,20 +1090,20 @@ WebRenderBridgeParent::SampleAnimations(
 void
 WebRenderBridgeParent::CompositeToTarget(gfx::DrawTarget* aTarget, const gfx::IntRect* aRect)
 {
   AutoProfilerTracing tracing("Paint", "CompositeToTraget");
   if (mPaused) {
     return;
   }
 
-  const uint32_t maxPendingFrameCount = 2;
+  const uint32_t maxPendingFrameCount = 1;
 
   if (!mForceRendering &&
-      wr::RenderThread::Get()->GetPendingFrameCount(mApi->GetId()) > maxPendingFrameCount) {
+      wr::RenderThread::Get()->GetPendingFrameCount(mApi->GetId()) >= maxPendingFrameCount) {
     // Render thread is busy, try next time.
     ScheduleComposition();
     return;
   }
 
   bool scheduleComposite = false;
   nsTArray<wr::WrOpacityProperty> opacityArray;
   nsTArray<wr::WrTransformProperty> transformArray;
@@ -1118,16 +1118,18 @@ WebRenderBridgeParent::CompositeToTarget
       scheduleComposite = true;
     }
   }
 
   if (PushAPZStateToWR(transformArray)) {
     scheduleComposite = true;
   }
 
+  wr::RenderThread::Get()->IncPendingFrameCount(mApi->GetId());
+
   if (!transformArray.IsEmpty() || !opacityArray.IsEmpty()) {
     mApi->GenerateFrame(opacityArray, transformArray);
   } else {
     mApi->GenerateFrame();
   }
 
   if (!mCompositableHolder->GetCompositeUntilTime().IsNull()) {
     scheduleComposite = true;
--- a/gfx/webrender_bindings/RenderThread.cpp
+++ b/gfx/webrender_bindings/RenderThread.cpp
@@ -373,17 +373,16 @@ WebRenderThreadPool::~WebRenderThreadPoo
 
 } // namespace wr
 } // namespace mozilla
 
 extern "C" {
 
 void wr_notifier_new_frame_ready(mozilla::wr::WrWindowId aWindowId)
 {
-  mozilla::wr::RenderThread::Get()->IncPendingFrameCount(aWindowId);
   mozilla::wr::RenderThread::Get()->NewFrameReady(mozilla::wr::WindowId(aWindowId));
 }
 
 void wr_notifier_new_scroll_frame_ready(mozilla::wr::WrWindowId aWindowId, bool aCompositeNeeded)
 {
   // It is not necessary to update rendering with new_scroll_frame_ready.
   // WebRenderBridgeParent::CompositeToTarget() is implemented to call
   // WebRenderAPI::GenerateFrame() if it is necessary to trigger UpdateAndRender().
--- a/hal/Hal.cpp
+++ b/hal/Hal.cpp
@@ -84,29 +84,25 @@ InSandbox()
 }
 
 void
 AssertMainProcess()
 {
   MOZ_ASSERT(GeckoProcessType_Default == XRE_GetProcessType());
 }
 
-#if !defined(MOZ_WIDGET_GONK)
-
 bool
 WindowIsActive(nsPIDOMWindowInner* aWindow)
 {
   nsIDocument* document = aWindow->GetDoc();
   NS_ENSURE_TRUE(document, false);
 
   return !document->Hidden();
 }
 
-#endif // !defined(MOZ_WIDGET_GONK)
-
 StaticAutoPtr<WindowIdentifier::IDArrayType> gLastIDToVibrate;
 
 void InitLastIDToVibrate()
 {
   gLastIDToVibrate = new WindowIdentifier::IDArrayType();
   ClearOnShutdown(&gLastIDToVibrate);
 }
 
@@ -118,28 +114,26 @@ Vibrate(const nsTArray<uint32_t>& patter
   Vibrate(pattern, WindowIdentifier(window));
 }
 
 void
 Vibrate(const nsTArray<uint32_t>& pattern, const WindowIdentifier &id)
 {
   AssertMainThread();
 
-#if !defined(MOZ_WIDGET_GONK)
   // Only active windows may start vibrations.  If |id| hasn't gone
   // through the IPC layer -- that is, if our caller is the outside
   // world, not hal_proxy -- check whether the window is active.  If
   // |id| has gone through IPC, don't check the window's visibility;
   // only the window corresponding to the bottommost process has its
   // visibility state set correctly.
   if (!id.HasTraveledThroughIPC() && !WindowIsActive(id.GetWindow())) {
     HAL_LOG("Vibrate: Window is inactive, dropping vibrate.");
     return;
   }
-#endif // !defined(MOZ_WIDGET_GONK)
 
   if (!InSandbox()) {
     if (!gLastIDToVibrate) {
       InitLastIDToVibrate();
     }
     *gLastIDToVibrate = id.AsArray();
   }
 
--- a/hal/linux/LinuxPower.cpp
+++ b/hal/linux/LinuxPower.cpp
@@ -7,76 +7,45 @@
 #include "HalLog.h"
 
 #include <unistd.h>
 #include <sys/reboot.h>
 #include "nsIObserverService.h"
 #include "mozilla/Services.h"
 #include "MainThreadUtils.h"
 
-#if defined(MOZ_WIDGET_GONK)
-#include "cutils/android_reboot.h"
-#include "cutils/properties.h"
-#endif
-
 namespace mozilla {
 namespace hal_impl {
 
-#if (defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 19)
-static void
-PowerCtl(const char* aValue, int aCmd)
-{
-  // this invokes init's powerctl builtin via /init.rc
-  property_set("sys.powerctl", aValue);
-  // device should reboot in few moments, but if it doesn't - call
-  // android_reboot() to make sure that init isn't stuck somewhere
-  sleep(10);
-  HAL_LOG("Powerctl call takes too long, forcing %s.", aValue);
-  android_reboot(aCmd, 0, nullptr);
-}
-#endif
-
 void
 Reboot()
 {
   if (NS_IsMainThread()) {
     nsCOMPtr<nsIObserverService> obsServ = services::GetObserverService();
     if (obsServ) {
       obsServ->NotifyObservers(nullptr, "system-reboot", nullptr);
     }
   }
 
-#if !defined(MOZ_WIDGET_GONK)
   sync();
   reboot(RB_AUTOBOOT);
-#elif (ANDROID_VERSION < 19)
-  android_reboot(ANDROID_RB_RESTART, 0, nullptr);
-#else
-  PowerCtl("reboot", ANDROID_RB_RESTART);
-#endif
 }
 
 void
 PowerOff()
 {
   if (NS_IsMainThread()) {
     nsCOMPtr<nsIObserverService> obsServ = services::GetObserverService();
     if (obsServ) {
       obsServ->NotifyObservers(nullptr, "system-power-off", nullptr);
     }
   }
 
-#if !defined(MOZ_WIDGET_GONK)
   sync();
   reboot(RB_POWER_OFF);
-#elif (ANDROID_VERSION < 19)
-  android_reboot(ANDROID_RB_POWEROFF, 0, nullptr);
-#else
-  PowerCtl("shutdown", ANDROID_RB_POWEROFF);
-#endif
 }
 
 // Structure to specify how watchdog pthread is going to work.
 typedef struct watchdogParam
 {
   hal::ShutdownMode mode; // Specify how to shutdown the system.
   int32_t timeoutSecs;    // Specify the delayed seconds to shutdown the system.
 
--- a/ipc/glue/moz.build
+++ b/ipc/glue/moz.build
@@ -209,25 +209,16 @@ IPDL_SOURCES = [
 
 LOCAL_INCLUDES += [
     '/dom/ipc',
     '/toolkit/crashreporter',
     '/toolkit/xre',
     '/xpcom/threads',
 ]
 
-if CONFIG['MOZ_CODE_COVERAGE']:
-    SOURCES += [
-        'CodeCoverageHandler.cpp',
-    ]
-
-    EXPORTS.mozilla += [
-        'CodeCoverageHandler.h',
-    ]
-
 include('/ipc/chromium/chromium-config.mozbuild')
 
 FINAL_LIBRARY = 'xul'
 
 for var in ('MOZ_CHILD_PROCESS_NAME', 'MOZ_CHILD_PROCESS_NAME_PIE',
             'MOZ_CHILD_PROCESS_BUNDLE', 'DLL_PREFIX', 'DLL_SUFFIX'):
     DEFINES[var] = '"%s"' % CONFIG[var]
 
--- a/media/libpng/pnglibconf.h
+++ b/media/libpng/pnglibconf.h
@@ -98,29 +98,16 @@
 #if defined(FT_CONFIG_OPTION_USE_PNG)
 #define PNG_READ_PACK_SUPPORTED
 #define PNG_READ_FILLER_SUPPORTED
 #define PNG_READ_STRIP_16_TO_8_SUPPORTED
 #define PNG_READ_USER_TRANSFORM_SUPPORTED
 #define PNG_SEQUENTIAL_READ_SUPPORTED
 #endif
 
-/* necessary for boot animation code (Gonk) */
-#ifdef MOZ_WIDGET_GONK
-#define PNG_bKGD_SUPPORTED
-#define PNG_UNKNOWN_CHUNKS_SUPPORTED
-#define PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
-#define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
-#define PNG_EASY_ACCESS_SUPPORTED
-#define PNG_READ_bKGD_SUPPORTED
-#define PNG_READ_BGR_SUPPORTED
-#define PNG_READ_GRAY_TO_RGB_SUPPORTED
-#define PNG_READ_STRIP_ALPHA_SUPPORTED
-#endif
-
 #define PNG_WRITE_SUPPORTED
 #define PNG_WRITE_APNG_SUPPORTED
 #define PNG_WRITE_tRNS_SUPPORTED
 #define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
 #define PNG_WRITE_FLUSH_SUPPORTED
 #define PNG_WRITE_OPTIMIZE_CMF_SUPPORTED
 #define PNG_WRITE_INT_FUNCTIONS_SUPPORTED
 
--- a/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.cc
+++ b/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.cc
@@ -90,19 +90,17 @@ AudioManager::AudioManager()
   j_audio_manager_.reset(new JavaAudioManager(
       j_native_registration_.get(),
       j_native_registration_->NewObject(
           "<init>", "(Landroid/content/Context;J)V",
           JVM::GetInstance()->context(), PointerTojlong(this))));
 }
 
 AudioManager::~AudioManager() {
-#if !defined(MOZ_WIDGET_GONK)
   ALOGD("~dtor%s", GetThreadInfo().c_str());
-#endif
   RTC_DCHECK(thread_checker_.CalledOnValidThread());
   Close();
 }
 
 void AudioManager::SetActiveAudioLayer(
     AudioDeviceModule::AudioLayer audio_layer) {
   ALOGD("SetActiveAudioLayer(%d)%s", audio_layer, GetThreadInfo().c_str());
   RTC_DCHECK(thread_checker_.CalledOnValidThread());
--- a/testing/specialpowers/content/SpecialPowersObserver.jsm
+++ b/testing/specialpowers/content/SpecialPowersObserver.jsm
@@ -82,16 +82,18 @@ SpecialPowersObserver.prototype._loadFra
     this._messageManager.addMessageListener("SPChromeScriptMessage", this);
     this._messageManager.addMessageListener("SPQuotaManager", this);
     this._messageManager.addMessageListener("SPSetTestPluginEnabledState", this);
     this._messageManager.addMessageListener("SPLoadExtension", this);
     this._messageManager.addMessageListener("SPStartupExtension", this);
     this._messageManager.addMessageListener("SPUnloadExtension", this);
     this._messageManager.addMessageListener("SPExtensionMessage", this);
     this._messageManager.addMessageListener("SPCleanUpSTSData", this);
+    this._messageManager.addMessageListener("SPRequestDumpCoverageCounters", this);
+    this._messageManager.addMessageListener("SPRequestResetCoverageCounters", this);
 
     this._messageManager.loadFrameScript(CHILD_LOGGER_SCRIPT, true);
     this._messageManager.loadFrameScript(CHILD_SCRIPT_API, true);
     this._messageManager.loadFrameScript(CHILD_SCRIPT, true);
     this._isFrameScriptLoaded = true;
     this._createdFiles = null;
   }
 };
@@ -150,16 +152,18 @@ SpecialPowersObserver.prototype.uninit =
     this._messageManager.removeMessageListener("SPChromeScriptMessage", this);
     this._messageManager.removeMessageListener("SPQuotaManager", this);
     this._messageManager.removeMessageListener("SPSetTestPluginEnabledState", this);
     this._messageManager.removeMessageListener("SPLoadExtension", this);
     this._messageManager.removeMessageListener("SPStartupExtension", this);
     this._messageManager.removeMessageListener("SPUnloadExtension", this);
     this._messageManager.removeMessageListener("SPExtensionMessage", this);
     this._messageManager.removeMessageListener("SPCleanUpSTSData", this);
+    this._messageManager.removeMessageListener("SPRequestDumpCoverageCounters", this);
+    this._messageManager.removeMessageListener("SPRequestResetCoverageCounters", this);
 
     this._messageManager.removeDelayedFrameScript(CHILD_LOGGER_SCRIPT);
     this._messageManager.removeDelayedFrameScript(CHILD_SCRIPT_API);
     this._messageManager.removeDelayedFrameScript(CHILD_SCRIPT);
     this._isFrameScriptLoaded = false;
   }
 };
 
--- a/testing/specialpowers/content/SpecialPowersObserverAPI.js
+++ b/testing/specialpowers/content/SpecialPowersObserverAPI.js
@@ -541,16 +541,30 @@ SpecialPowersObserverAPI.prototype = {
         let flags = aMessage.data.flags;
         let uri = Services.io.newURI(origin);
         let sss = Cc["@mozilla.org/ssservice;1"].
                   getService(Ci.nsISiteSecurityService);
         sss.removeState(Ci.nsISiteSecurityService.HEADER_HSTS, uri, flags);
         return undefined;
       }
 
+      case "SPRequestDumpCoverageCounters": {
+        let codeCoverage = Cc["@mozilla.org/tools/code-coverage;1"].
+                           getService(Ci.nsICodeCoverage);
+        codeCoverage.dumpCounters();
+        return undefined; // See comment at the beginning of this function.
+      }
+
+      case "SPRequestResetCoverageCounters": {
+        let codeCoverage = Cc["@mozilla.org/tools/code-coverage;1"].
+                           getService(Ci.nsICodeCoverage);
+        codeCoverage.resetCounters();
+        return undefined; // See comment at the beginning of this function.
+      }
+
       case "SPLoadExtension": {
         let {Extension} = Components.utils.import("resource://gre/modules/Extension.jsm", {});
 
         let id = aMessage.data.id;
         let ext = aMessage.data.ext;
         let extension = Extension.generate(ext);
 
         let resultListener = (...args) => {
--- a/testing/specialpowers/content/specialpowers.js
+++ b/testing/specialpowers/content/specialpowers.js
@@ -34,17 +34,19 @@ function SpecialPowers(window) {
   this.SP_SYNC_MESSAGES = ["SPChromeScriptMessage",
                            "SPLoadChromeScript",
                            "SPImportInMainProcess",
                            "SPObserverService",
                            "SPPermissionManager",
                            "SPPrefService",
                            "SPProcessCrashService",
                            "SPSetTestPluginEnabledState",
-                           "SPCleanUpSTSData"];
+                           "SPCleanUpSTSData",
+                           "SPRequestDumpCoverageCounters",
+                           "SPRequestResetCoverageCounters"];
 
   this.SP_ASYNC_MESSAGES = ["SpecialPowers.Focus",
                             "SpecialPowers.Quit",
                             "SpecialPowers.CreateFiles",
                             "SpecialPowers.RemoveFiles",
                             "SPPingService",
                             "SPLoadExtension",
                             "SPStartupExtension",
--- a/testing/specialpowers/content/specialpowersAPI.js
+++ b/testing/specialpowers/content/specialpowersAPI.js
@@ -1928,16 +1928,24 @@ SpecialPowersAPI.prototype = {
   removeServiceWorkerDataForExampleDomain() {
     this.notifyObserversInParentProcess(null, "browser:purge-domain-data", "example.com");
   },
 
   cleanUpSTSData(origin, flags) {
     return this._sendSyncMessage("SPCleanUpSTSData", {origin, flags: flags || 0});
   },
 
+  requestDumpCoverageCounters() {
+    this._sendSyncMessage("SPRequestDumpCoverageCounters", {});
+  },
+
+  requestResetCoverageCounters() {
+    this._sendSyncMessage("SPRequestResetCoverageCounters", {});
+  },
+
   _nextExtensionID: 0,
   _extensionListeners: null,
 
   loadExtension(ext, handler) {
     if (this._extensionListeners == null) {
       this._extensionListeners = new Set();
 
       this._addMessageListener("SPExtensionMessage", msg => {
--- a/testing/talos/talos/talos-powers/components/TalosPowersService.js
+++ b/testing/talos/talos/talos-powers/components/TalosPowersService.js
@@ -1,13 +1,13 @@
 /* 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/. */
 
-const { interfaces: Ci, utils: Cu } = Components;
+const { interfaces: Ci, utils: Cu, classes: Cc } = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Services",
   "resource://gre/modules/Services.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "OS",
   "resource://gre/modules/osfile.jsm");
 
 const FRAME_SCRIPT = "chrome://talos-powers/content/talos-powers-content.js";
@@ -290,16 +290,30 @@ TalosPowersService.prototype = {
 
     // arg: handle from startFrameTimeRecording. return: array with composition intervals
     stopFrameTimeRecording(arg, callback, win) {
       var rv = win.QueryInterface(Ci.nsIInterfaceRequestor)
                   .getInterface(Ci.nsIDOMWindowUtils)
                   .stopFrameTimeRecording(arg);
       callback(rv);
     },
+
+    requestDumpCoverageCounters(arg, callback, win) {
+      let codeCoverage = Cc["@mozilla.org/tools/code-coverage;1"].
+                         getService(Ci.nsICodeCoverage);
+      codeCoverage.dumpCounters();
+      callback();
+    },
+
+    requestResetCoverageCounters(arg, callback, win) {
+      let codeCoverage = Cc["@mozilla.org/tools/code-coverage;1"].
+                         getService(Ci.nsICodeCoverage);
+      codeCoverage.resetCounters();
+      callback();
+    },
   },
 
   RecieveParentExecCommand(msg) {
     function sendResult(result) {
       let mm = msg.target.messageManager;
       mm.sendAsyncMessage("TalosPowers:ParentExec:ReplyMsg", {
         id: msg.data.id,
         result
--- a/toolkit/toolkit.mozbuild
+++ b/toolkit/toolkit.mozbuild
@@ -106,16 +106,17 @@ else:
 
 # toolkit
 
 # This must precede xpfe.
 if CONFIG['MOZ_JPROF']:
     DIRS += ['/tools/jprof']
 
 DIRS += [
+    '/tools/code-coverage',
     '/tools/power',
     '/tools/profiler',
     '/tools/memory-profiler',
     '/xpfe/components',
 ]
 
 if CONFIG['MOZ_ENABLE_XREMOTE']:
     DIRS += ['/widget/xremoteclient']
rename from ipc/glue/CodeCoverageHandler.cpp
rename to tools/code-coverage/CodeCoverageHandler.cpp
rename from ipc/glue/CodeCoverageHandler.h
rename to tools/code-coverage/CodeCoverageHandler.h
--- a/ipc/glue/CodeCoverageHandler.h
+++ b/tools/code-coverage/CodeCoverageHandler.h
@@ -15,26 +15,26 @@ namespace mozilla {
 
 class CodeCoverageHandler {
 public:
   static void Init();
   static void Init(const CrossProcessMutexHandle& aHandle);
   static CodeCoverageHandler* Get();
   CrossProcessMutex* GetMutex();
   CrossProcessMutexHandle GetMutexHandle(int aProcId);
+  static void DumpCounters(int);
+  static void ResetCounters(int);
 
 private:
   CodeCoverageHandler();
   CodeCoverageHandler(const CrossProcessMutexHandle& aHandle);
 
   static StaticAutoPtr<CodeCoverageHandler> instance;
   CrossProcessMutex mGcovLock;
 
   DISALLOW_COPY_AND_ASSIGN(CodeCoverageHandler);
 
   void SetSignalHandlers();
-  static void DumpCounters(int);
-  static void ResetCounters(int);
 };
 
 }
 
 #endif // mozilla_codecoveragehandler_h
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/moz.build
@@ -0,0 +1,34 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+if CONFIG['MOZ_CODE_COVERAGE']:
+    XPIDL_MODULE = 'code-coverage'
+
+    XPIDL_SOURCES += [
+        'nsICodeCoverage.idl',
+    ]
+
+    SOURCES += [
+        'CodeCoverageHandler.cpp',
+        'nsCodeCoverage.cpp',
+        'nsCodeCoverageFactory.cpp',
+    ]
+
+    EXPORTS.mozilla += [
+        'CodeCoverageHandler.h',
+    ]
+
+    LOCAL_INCLUDES += [
+        '/ipc/chromium/src',
+        '/xpcom/base',
+    ]
+
+    include('/ipc/chromium/chromium-config.mozbuild')
+
+    XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
+    MOCHITEST_MANIFESTS += ['tests/mochitest/mochitest.ini']
+
+    FINAL_LIBRARY = 'xul'
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/nsCodeCoverage.cpp
@@ -0,0 +1,49 @@
+/* -*- 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 "nsCodeCoverage.h"
+#include "mozilla/CodeCoverageHandler.h"
+#include "mozilla/Unused.h"
+#include "mozilla/dom/ContentParent.h"
+
+using namespace mozilla;
+using namespace mozilla::dom;
+
+NS_IMPL_ISUPPORTS(nsCodeCoverage,
+                  nsICodeCoverage)
+
+nsCodeCoverage::nsCodeCoverage()
+{
+}
+
+nsCodeCoverage::~nsCodeCoverage()
+{
+}
+
+NS_IMETHODIMP nsCodeCoverage::DumpCounters()
+{
+  MOZ_ASSERT(XRE_IsParentProcess());
+  MOZ_ASSERT(NS_IsMainThread());
+
+  CodeCoverageHandler::DumpCounters(0);
+  for (auto* cp : ContentParent::AllProcesses(ContentParent::eLive)) {
+    Unused << cp->SendDumpCodeCoverageCounters();
+  }
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP nsCodeCoverage::ResetCounters()
+{
+  MOZ_ASSERT(XRE_IsParentProcess());
+  MOZ_ASSERT(NS_IsMainThread());
+
+  CodeCoverageHandler::ResetCounters(0);
+  for (auto* cp : ContentParent::AllProcesses(ContentParent::eLive)) {
+    Unused << cp->SendResetCodeCoverageCounters();
+  }
+
+  return NS_OK;
+}
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/nsCodeCoverage.h
@@ -0,0 +1,26 @@
+/* -*- 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 tools_codecoverage_nscodecoverage_h
+#define tools_codecoverage_nscodecoverage_h
+
+#include "nsICodeCoverage.h"
+
+#define NS_CODECOVERAGE_CID \
+{ 0x93576af0, 0xa62f, 0x4c88, \
+{ 0xbc, 0x12, 0xf1, 0x85, 0x5d, 0x4e, 0x01, 0x73 } }
+
+class nsCodeCoverage final : nsICodeCoverage {
+public:
+  NS_DECL_THREADSAFE_ISUPPORTS
+  NS_DECL_NSICODECOVERAGE
+
+  nsCodeCoverage();
+
+private:
+  ~nsCodeCoverage();
+};
+
+#endif // tools_codecoverage_nscodecoverage_h
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/nsCodeCoverageFactory.cpp
@@ -0,0 +1,30 @@
+/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/ModuleUtils.h"
+#include "nsCOMPtr.h"
+#include "nsCodeCoverage.h"
+
+NS_GENERIC_FACTORY_CONSTRUCTOR(nsCodeCoverage)
+
+NS_DEFINE_NAMED_CID(NS_CODECOVERAGE_CID);
+
+static const mozilla::Module::CIDEntry kCodeCoverageCIDs[] = {
+    { &kNS_CODECOVERAGE_CID, false, nullptr, nsCodeCoverageConstructor },
+    { nullptr }
+};
+
+static const mozilla::Module::ContractIDEntry kCodeCoverageContracts[] = {
+    { "@mozilla.org/tools/code-coverage;1", &kNS_CODECOVERAGE_CID },
+    { nullptr }
+};
+
+static const mozilla::Module kCodeCoverageModule = {
+    mozilla::Module::kVersion,
+    kCodeCoverageCIDs,
+    kCodeCoverageContracts
+};
+
+NSMODULE_DEFN(nsCodeCoverageModule) = &kCodeCoverageModule;
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/nsICodeCoverage.idl
@@ -0,0 +1,28 @@
+/* -*- 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 "nsISupports.idl"
+
+/**
+ * The nsICodeCoverage component allows controlling the code coverage counters
+ * collected by Firefox during execution.
+ * By resetting and dumping the counters, one can analyze the coverage information
+ * for a subset of the program execution (e.g. startup code coverage).
+ *
+ */
+
+[scriptable, uuid(57d92056-37b4-4d0a-a52f-deb8f6dac8bc)]
+interface nsICodeCoverage : nsISupports
+{
+  /**
+   * Write the coverage counters to disk.
+   */
+  void dumpCounters();
+
+  /**
+   * Reset the coverage counters to 0 (as if nothing was executed).
+   */
+  void resetCounters();
+};
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/tests/mochitest/.eslintrc.js
@@ -0,0 +1,7 @@
+"use strict";
+
+module.exports = {
+  "extends": [
+    "plugin:mozilla/mochitest-test"
+  ]
+};
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/tests/mochitest/mochitest.ini
@@ -0,0 +1,3 @@
+[DEFAULT]
+
+[test_coverage_specialpowers.html]
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/tests/mochitest/test_coverage_specialpowers.html
@@ -0,0 +1,36 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1380659
+-->
+<head>
+  <meta charset="utf-8">
+  <title>Test for Bug 123456</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript">
+
+  /** Test for Bug 1380659 **/
+
+  SimpleTest.waitForExplicitFinish();
+
+  SpecialPowers.requestDumpCoverageCounters();
+  SimpleTest.ok(true, "Counters dumped.");
+
+  SpecialPowers.requestResetCoverageCounters();
+  SimpleTest.ok(true, "Counters reset.");
+
+  SimpleTest.finish();
+
+  </script>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1380659">Mozilla Bug 1380659</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+
+</div>
+<pre id="test">
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/tests/xpcshell/.eslintrc.js
@@ -0,0 +1,7 @@
+"use strict";
+
+module.exports = {
+  "extends": [
+    "plugin:mozilla/xpcshell-test"
+  ]
+};
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/tests/xpcshell/head.js
@@ -0,0 +1,7 @@
+/* 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/. */
+
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const Cu = Components.utils;
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/tests/xpcshell/test_basic.js
@@ -0,0 +1,17 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+function run_test() {
+  Assert.ok("@mozilla.org/tools/code-coverage;1" in Cc);
+
+  let codeCoverageCc = Cc["@mozilla.org/tools/code-coverage;1"];
+  Assert.ok(!!codeCoverageCc);
+
+  let codeCoverage = codeCoverageCc.getService(Ci.nsICodeCoverage);
+  Assert.ok(!!codeCoverage);
+
+  codeCoverage.dumpCounters();
+
+  codeCoverage.resetCounters();
+}
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/tests/xpcshell/test_basic_child_and_parent.js
@@ -0,0 +1,17 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+function run_test() {
+  do_load_child_test_harness();
+  do_test_pending();
+
+  sendCommand("let v = 'test';", function() {
+      let codeCoverage = Components.classes["@mozilla.org/tools/code-coverage;1"].getService(Components.interfaces.nsICodeCoverage);
+
+      codeCoverage.dumpCounters();
+      codeCoverage.resetCounters();
+
+      do_test_finished();
+  });
+}
new file mode 100644
--- /dev/null
+++ b/tools/code-coverage/tests/xpcshell/xpcshell.ini
@@ -0,0 +1,5 @@
+[DEFAULT]
+head = head.js
+
+[test_basic.js]
+[test_basic_child_and_parent.js]
--- a/tools/moz.build
+++ b/tools/moz.build
@@ -2,16 +2,19 @@
 # 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/.
 
 with Files("**"):
     BUG_COMPONENT = ("Core", "General")
 
+with Files("code-coverage/**"):
+    BUG_COMPONENT = ("Testing", "Code Coverage")
+
 with Files("compare-locales/docs/**"):
     BUG_COMPONENT = ('Mozilla Localizations', 'Documentation')
 
 with Files("compare-locales/mach_commands.py"):
     BUG_COMPONENT = ("Localization Infrastructure and Tools", "compare-locales")
 
 with Files("coverity/**"):
     BUG_COMPONENT = ("Core", "Rewriting and Analysis")
--- a/uriloader/exthandler/nsExternalHelperAppService.cpp
+++ b/uriloader/exthandler/nsExternalHelperAppService.cpp
@@ -557,42 +557,25 @@ static const nsExtraMimeTypeEntry extraM
   { TEXT_XML, "xml,xsl,xbl", "Extensible Markup Language" },
   { TEXT_CSS, "css", "Style Sheet" },
   { TEXT_VCARD, "vcf,vcard", "Contact Information" },
   { VIDEO_OGG, "ogv", "Ogg Video" },
   { VIDEO_OGG, "ogg", "Ogg Video" },
   { APPLICATION_OGG, "ogg", "Ogg Video"},
   { AUDIO_OGG, "oga", "Ogg Audio" },
   { AUDIO_OGG, "opus", "Opus Audio" },
-#ifdef MOZ_WIDGET_GONK
-  { AUDIO_AMR, "amr", "Adaptive Multi-Rate Audio" },
-  { AUDIO_FLAC, "flac", "FLAC Audio" },
-  { VIDEO_AVI, "avi", "Audio Video Interleave" },
-  { VIDEO_AVI, "divx", "Audio Video Interleave" },
-  { VIDEO_MPEG_TS, "ts", "MPEG Transport Stream" },
-  { VIDEO_MPEG_TS, "m2ts", "MPEG-2 Transport Stream" },
-  { VIDEO_MATROSKA, "mkv", "MATROSKA VIDEO" },
-  { AUDIO_MATROSKA, "mka", "MATROSKA AUDIO" },
-#endif
   { VIDEO_WEBM, "webm", "Web Media Video" },
   { AUDIO_WEBM, "webm", "Web Media Audio" },
   { AUDIO_MP3, "mp3", "MPEG Audio" },
   { VIDEO_MP4, "mp4", "MPEG-4 Video" },
   { AUDIO_MP4, "m4a", "MPEG-4 Audio" },
   { VIDEO_RAW, "yuv", "Raw YUV Video" },
   { AUDIO_WAV, "wav", "Waveform Audio" },
   { VIDEO_3GPP, "3gpp,3gp", "3GPP Video" },
   { VIDEO_3GPP2,"3g2", "3GPP2 Video" },
-#ifdef MOZ_WIDGET_GONK
-  // The AUDIO_3GPP has to come after the VIDEO_3GPP entry because the Gallery
-  // app on Firefox OS depends on the "3gp" extension mapping to the
-  // "video/3gpp" MIME type.
-  { AUDIO_3GPP, "3gpp,3gp", "3GPP Audio" },
-  { AUDIO_3GPP2, "3g2", "3GPP2 Audio" },
-#endif
   { AUDIO_MIDI, "mid", "Standard MIDI Audio" }
 };
 
 #undef MAC_TYPE
 
 /**
  * File extensions for which decoding should be disabled.
  * NOTE: These MUST be lower-case and ASCII.
--- a/widget/EventMessageList.h
+++ b/widget/EventMessageList.h
@@ -380,17 +380,17 @@ NS_EVENT_MESSAGE(eOpen)
 
 // Device motion and orientation
 NS_EVENT_MESSAGE(eDeviceOrientation)
 NS_EVENT_MESSAGE(eAbsoluteDeviceOrientation)
 NS_EVENT_MESSAGE(eDeviceMotion)
 NS_EVENT_MESSAGE(eDeviceProximity)
 NS_EVENT_MESSAGE(eUserProximity)
 NS_EVENT_MESSAGE(eDeviceLight)
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
 NS_EVENT_MESSAGE(eOrientationChange)
 #endif
 
 // WebVR events
 NS_EVENT_MESSAGE(eVRDisplayActivate)
 NS_EVENT_MESSAGE(eVRDisplayDeactivate)
 NS_EVENT_MESSAGE(eVRDisplayConnect)
 NS_EVENT_MESSAGE(eVRDisplayDisconnect)
--- a/widget/nsContentProcessWidgetFactory.cpp
+++ b/widget/nsContentProcessWidgetFactory.cpp
@@ -12,18 +12,16 @@
 #include "nsDragServiceProxy.h"
 #include "nsFilePickerProxy.h"
 #include "mozilla/widget/PuppetBidiKeyboard.h"
 #include "mozilla/widget/ScreenManager.h"
 
 using namespace mozilla;
 using namespace mozilla::widget;
 
-#ifndef MOZ_WIDGET_GONK
-
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsClipboardProxy)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsColorPickerProxy)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDragServiceProxy)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsFilePickerProxy)
 NS_GENERIC_FACTORY_CONSTRUCTOR(PuppetBidiKeyboard)
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(ScreenManager, ScreenManager::GetAddRefedSingleton)
 
 NS_DEFINE_NAMED_CID(NS_CLIPBOARD_CID);
@@ -62,10 +60,8 @@ static const mozilla::Module::ContractID
 
 static const mozilla::Module kWidgetModule = {
     mozilla::Module::kVersion,
     kWidgetCIDs,
     kWidgetContracts
 };
 
 NSMODULE_DEFN(nsContentProcessWidgetModule) = &kWidgetModule;
-
-#endif /* MOZ_WIDGET_GONK */
--- a/xpfe/appshell/nsAppShellService.cpp
+++ b/xpfe/appshell/nsAppShellService.cpp
@@ -727,23 +727,16 @@ nsAppShellService::JustCreateTopWindow(n
     aInitialHeight = 1;
     window->SetIntrinsicallySized(true);
   }
 
   bool center = aChromeMask & nsIWebBrowserChrome::CHROME_CENTER_SCREEN;
 
   widgetInitData.mRTL = LocaleService::GetInstance()->IsAppLocaleRTL();
 
-#ifdef MOZ_WIDGET_GONK
-  // B2G multi-screen support. Screen ID is for differentiating screens of
-  // windows, and due to the hardware limitation, it is platform-specific for
-  // now, which align with the value of display type defined in HWC.
-  widgetInitData.mScreenId = mScreenId;
-#endif
-
   nsresult rv = window->Initialize(parent, center ? aParent : nullptr,
                                    aUrl, aInitialWidth, aInitialHeight,
                                    aIsHiddenWindow, aOpeningTab,
                                    aOpenerWindow, widgetInitData);
 
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Enforce the Private Browsing autoStart pref first.