Merge m-c to fx-team a=merge
authorWes Kocher <wkocher@mozilla.com>
Tue, 06 Jan 2015 19:51:17 -0800
changeset 248232 a185d1c79df9f53255915f113d2d11c26b32a7cf
parent 248231 5d3be0c407a84f4460f52b352806891fe993f0d4 (current diff)
parent 248124 33781a3a5201c2371d5d31eeaaaeb5f34a3aaced (diff)
child 248233 854a6dbbd5e4cce6798d20dbaa0a3e6835b6b36e
push id4489
push userraliiev@mozilla.com
push dateMon, 23 Feb 2015 15:17:55 +0000
treeherdermozilla-beta@fd7c3dc24146 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone37.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 m-c to fx-team a=merge
js/src/vm/NumericConversions.h
--- a/accessible/base/nsAccessibilityService.h
+++ b/accessible/base/nsAccessibilityService.h
@@ -246,16 +246,18 @@ GetAccService()
 }
 
 /**
  * Return true if we're in a content process and not B2G.
  */
 inline bool
 IPCAccessibilityActive()
 {
+  // XXX temporarily disable ipc accessibility because of crashes.
+return false;
 #ifdef MOZ_B2G
   return false;
 #else
   return XRE_GetProcessType() == GeckoProcessType_Content;
 #endif
 }
 
 /**
--- a/browser/config/mozconfigs/linux64/debug-static-analysis-clang
+++ b/browser/config/mozconfigs/linux64/debug-static-analysis-clang
@@ -1,20 +1,19 @@
 MOZ_AUTOMATION_BUILD_SYMBOLS=0
 MOZ_AUTOMATION_PACKAGE_TESTS=0
 MOZ_AUTOMATION_L10N_CHECK=0
 
 . "$topsrcdir/build/mozconfig.common"
 
 ac_add_options --enable-debug
+ac_add_options --enable-dmd
 
 ac_add_options --disable-unified-compilation
 
-ac_add_options --with-google-oauth-api-keyfile=/builds/google-oauth-api.key
-
 # Use Clang as specified in manifest
 export CC="$topsrcdir/clang/bin/clang"
 export CXX="$topsrcdir/clang/bin/clang++"
 
 # Add the static checker
 ac_add_options --enable-clang-plugin
 
 # Avoid dependency on libstdc++ 4.7
--- a/browser/config/mozconfigs/macosx64/debug
+++ b/browser/config/mozconfigs/macosx64/debug
@@ -1,13 +1,12 @@
 . $topsrcdir/build/macosx/mozconfig.common
 
 ac_add_options --enable-debug
 ac_add_options --enable-dmd
-ac_add_options --enable-accessibility
 ac_add_options --enable-signmar
 ac_add_options --with-google-oauth-api-keyfile=/builds/google-oauth-api.key
 
 # Needed to enable breakpad in application.ini
 export MOZILLA_OFFICIAL=1
 
 if test "${MOZ_UPDATE_CHANNEL}" = "nightly"; then
 ac_add_options --with-macbundlename-prefix=Firefox
--- a/browser/config/mozconfigs/macosx64/debug-asan
+++ b/browser/config/mozconfigs/macosx64/debug-asan
@@ -1,14 +1,13 @@
 . $topsrcdir/build/unix/mozconfig.asan
 
 ac_add_options --enable-application=browser
 ac_add_options --enable-debug
 ac_add_options --enable-optimize="-O1"
-ac_add_options --enable-accessibility
 ac_add_options --with-google-oauth-api-keyfile=/builds/google-oauth-api.key
 
 ac_add_options --disable-unified-compilation
 
 # Package js shell.
 export MOZ_PACKAGE_JSSHELL=1
 
 if test "${MOZ_UPDATE_CHANNEL}" = "nightly"; then
new file mode 100644
--- /dev/null
+++ b/browser/config/mozconfigs/macosx64/debug-static-analysis
@@ -0,0 +1,15 @@
+MOZ_AUTOMATION_BUILD_SYMBOLS=0
+MOZ_AUTOMATION_PACKAGE_TESTS=0
+MOZ_AUTOMATION_L10N_CHECK=0
+
+. $topsrcdir/build/macosx/mozconfig.common
+
+ac_add_options --enable-debug
+ac_add_options --enable-dmd
+
+# Treat warnings as errors in directories with FAIL_ON_WARNINGS.
+ac_add_options --enable-warnings-as-errors
+
+ac_add_options --enable-clang-plugin
+
+. "$topsrcdir/build/mozconfig.common.override"
--- a/build/autoconf/clang-plugin.m4
+++ b/build/autoconf/clang-plugin.m4
@@ -28,17 +28,21 @@ if test -n "$ENABLE_CLANG_PLUGIN"; then
     fi
 
     AC_MSG_RESULT([$LLVMCONFIG])
 
     if test -z "$LLVMCONFIG"; then
         AC_MSG_ERROR([Cannot find an llvm-config binary for building a clang plugin])
     fi
     LLVM_CXXFLAGS=`$LLVMCONFIG --cxxflags`
-    LLVM_LDFLAGS=`$LLVMCONFIG --ldflags --system-libs --libs core mc analysis asmparser mcparser bitreader option | xargs`
+    dnl The clang package we use on OSX is old, and its llvm-config doesn't
+    dnl recognize --system-libs, so ask for that separately.  llvm-config's
+    dnl failure here is benign, so we can ignore it if it happens.
+    LLVM_LDFLAGS=`$LLVMCONFIG --system-libs | xargs`
+    LLVM_LDFLAGS="$LLVM_LDFLAGS `$LLVMCONFIG --ldflags --libs core mc analysis asmparser mcparser bitreader option | xargs`"
 
     if test "${OS_ARCH}" = "Darwin"; then
         CLANG_LDFLAGS="-lclangFrontend -lclangDriver -lclangSerialization"
         CLANG_LDFLAGS="$CLANG_LDFLAGS -lclangParse -lclangSema -lclangAnalysis"
         CLANG_LDFLAGS="$CLANG_LDFLAGS -lclangEdit -lclangAST -lclangLex"
         CLANG_LDFLAGS="$CLANG_LDFLAGS -lclangBasic -lclangASTMatchers"
     else
         CLANG_LDFLAGS="-lclangASTMatchers"
--- a/build/autoconf/toolchain.m4
+++ b/build/autoconf/toolchain.m4
@@ -86,16 +86,23 @@ fi
 if test "$GNU_CC"; then
     if `$CC -print-prog-name=ld` -v 2>&1 | grep -c GNU >/dev/null; then
         GCC_USE_GNU_LD=1
     fi
 fi
 
 AC_SUBST(CLANG_CXX)
 AC_SUBST(CLANG_CL)
+
+if test -n "$GNU_CC" -a -z "$CLANG_CC" ; then
+    if test "$GCC_MAJOR_VERSION" -eq 4 -a "$GCC_MINOR_VERSION" -lt 4 ||
+       test "$GCC_MAJOR_VERSION" -lt 4; then
+        AC_MSG_ERROR([Only GCC 4.4 or newer supported])
+    fi
+fi
 ])
 
 AC_DEFUN([MOZ_CROSS_COMPILER],
 [
 echo "cross compiling from $host to $target"
 
 _SAVE_CC="$CC"
 _SAVE_CFLAGS="$CFLAGS"
--- a/configure.in
+++ b/configure.in
@@ -400,23 +400,16 @@ fi
 if test -n "$MOZ_WINCONSOLE"; then
     AC_DEFINE(MOZ_WINCONSOLE)
 fi
 
 MOZ_TOOL_VARIABLES
 
 MOZ_CHECK_COMPILER_WRAPPER
 
-if test -n "$GNU_CC" -a -z "$CLANG_CC" ; then
-    if test "$GCC_MAJOR_VERSION" -eq 4 -a "$GCC_MINOR_VERSION" -lt 4 ||
-       test "$GCC_MAJOR_VERSION" -lt 4; then
-        AC_MSG_ERROR([Only GCC 4.4 or newer supported])
-    fi
-fi
-
 dnl ========================================================
 dnl Special win32 checks
 dnl ========================================================
 
 MOZ_ARG_ENABLE_BOOL(metro,
 [  --enable-metro           Enable Windows Metro build targets],
     MOZ_METRO=1,
     MOZ_METRO=)
@@ -489,22 +482,17 @@ case "$target" in
 
         if test "$_CC_MAJOR_VERSION" != "$_CXX_MAJOR_VERSION"; then
             AC_MSG_ERROR([The major versions of \$CC and \$CXX do not match.])
         fi
 
         AC_DEFINE(_CRT_SECURE_NO_WARNINGS)
         AC_DEFINE(_CRT_NONSTDC_NO_WARNINGS)
 
-        if test "$_CC_MAJOR_VERSION" = "17"; then
-            _CC_SUITE=11
-            MSVS_VERSION=2012
-            MSVC_C_RUNTIME_DLL=msvcr110.dll
-            MSVC_CXX_RUNTIME_DLL=msvcp110.dll
-        elif test "$_CC_MAJOR_VERSION" = "18"; then
+        if test "$_CC_MAJOR_VERSION" = "18"; then
             _CC_SUITE=12
             MSVS_VERSION=2013
             MSVC_C_RUNTIME_DLL=msvcr120.dll
             MSVC_CXX_RUNTIME_DLL=msvcp120.dll
         else
             AC_MSG_ERROR([This version ($CC_VERSION) of the MSVC compiler is unsupported. See https://developer.mozilla.org/en/Windows_Build_Prerequisites.])
         fi
         AC_SUBST(MSVS_VERSION)
@@ -1247,21 +1235,21 @@ dnl Android libstdc++, placed here so it
 dnl computed above.
 dnl ========================================================
 
 MOZ_ANDROID_STLPORT
 
 dnl ========================================================
 dnl Suppress Clang Argument Warnings
 dnl ========================================================
-if test -n "$CLANG_CC"; then
+if test -n "${CLANG_CC}${CLANG_CL}"; then
     _WARNINGS_CFLAGS="-Qunused-arguments ${_WARNINGS_CFLAGS}"
     CPPFLAGS="-Qunused-arguments ${CPPFLAGS}"
 fi
-if test -n "$CLANG_CXX"; then
+if test -n "${CLANG_CXX}${CLANG_CL}"; then
     _WARNINGS_CXXFLAGS="-Qunused-arguments ${_WARNINGS_CXXFLAGS}"
 fi
 
 dnl ========================================================
 dnl = Use Address Sanitizer
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(address-sanitizer,
 [  --enable-address-sanitizer       Enable Address Sanitizer (default=no)],
--- a/dom/archivereader/ArchiveZipFile.cpp
+++ b/dom/archivereader/ArchiveZipFile.cpp
@@ -373,19 +373,18 @@ ArchiveZipFileImpl::GetInternalStream(ns
   }
 
   nsRefPtr<ArchiveInputStream> stream = new ArchiveInputStream(size,
                                                                inputStream,
                                                                mFilename,
                                                                mStart,
                                                                mLength,
                                                                mCentral);
-  NS_ADDREF(stream);
 
-  *aStream = stream;
+  stream.forget(aStream);
   return NS_OK;
 }
 
 void
 ArchiveZipFileImpl::Unlink()
 {
   ArchiveZipFileImpl* tmp = this;
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mArchiveReader);
--- a/dom/asmjscache/AsmJSCache.cpp
+++ b/dom/asmjscache/AsmJSCache.cpp
@@ -349,17 +349,17 @@ public:
     void
     Init(File* aFile)
     {
       MOZ_ASSERT(!mFile);
       mFile = aFile;
     }
 
     File*
-    operator->() const
+    operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN
     {
       MOZ_ASSERT(mFile);
       return mFile;
     }
 
     void
     Forget(File** aFile)
     {
--- a/dom/base/Attr.h
+++ b/dom/base/Attr.h
@@ -74,17 +74,17 @@ public:
   virtual already_AddRefed<nsIURI> GetBaseURI(bool aTryUseXHRDocBaseURI = false) const MOZ_OVERRIDE;
 
   static void Initialize();
   static void Shutdown();
 
   NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Attr,
                                                                    nsIAttribute)
 
-  virtual nsIDOMNode* AsDOMNode() { return this; }
+  virtual nsIDOMNode* AsDOMNode() MOZ_OVERRIDE { return this; }
 
   // WebIDL
   virtual JSObject* WrapNode(JSContext* aCx) MOZ_OVERRIDE;
 
   // XPCOM GetName() is OK
   // XPCOM GetValue() is OK
 
   void SetValue(const nsAString& aValue, ErrorResult& aRv);
@@ -93,17 +93,17 @@ public:
 
   // XPCOM GetNamespaceURI() is OK
   // XPCOM GetPrefix() is OK
   // XPCOM GetLocalName() is OK
 
   Element* GetOwnerElement(ErrorResult& aRv);
 
 protected:
-  virtual Element* GetNameSpaceElement()
+  virtual Element* GetNameSpaceElement() MOZ_OVERRIDE
   {
     return GetElement();
   }
 
   static bool sInitialized;
 
 private:
   already_AddRefed<nsIAtom> GetNameAtom(nsIContent* aContent);
--- a/dom/base/Comment.h
+++ b/dom/base/Comment.h
@@ -47,17 +47,17 @@ public:
   // nsIDOMCharacterData
   NS_FORWARD_NSIDOMCHARACTERDATA(nsGenericDOMDataNode::)
   using nsGenericDOMDataNode::SetData; // Prevent hiding overloaded virtual function.
 
   // nsIDOMComment
   // Empty interface
 
   // nsINode
-  virtual bool IsNodeOfType(uint32_t aFlags) const;
+  virtual bool IsNodeOfType(uint32_t aFlags) const MOZ_OVERRIDE;
 
   virtual nsGenericDOMDataNode* CloneDataNode(mozilla::dom::NodeInfo *aNodeInfo,
                                               bool aCloneText) const MOZ_OVERRIDE;
 
   virtual nsIDOMNode* AsDOMNode() MOZ_OVERRIDE { return this; }
 #ifdef DEBUG
   virtual void List(FILE* out, int32_t aIndent) const MOZ_OVERRIDE;
   virtual void DumpContent(FILE* out = stdout, int32_t aIndent = 0,
--- a/dom/base/Console.cpp
+++ b/dom/base/Console.cpp
@@ -24,34 +24,28 @@
 
 #include "nsIConsoleAPIStorage.h"
 #include "nsIDOMWindowUtils.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsILoadContext.h"
 #include "nsIServiceManager.h"
 #include "nsISupportsPrimitives.h"
 #include "nsIWebNavigation.h"
+#include "nsIXPConnect.h"
 
 // The maximum allowed number of concurrent timers per page.
 #define MAX_PAGE_TIMERS 10000
 
 // The maximum allowed number of concurrent counters per page.
 #define MAX_PAGE_COUNTERS 10000
 
 // The maximum stacktrace depth when populating the stacktrace array used for
 // console.trace().
 #define DEFAULT_MAX_STACKTRACE_DEPTH 200
 
-// The console API methods are async and their action is executed later. This
-// delay tells how much later.
-#define CALL_DELAY 15 // milliseconds
-
-// This constant tells how many messages to process in a single timer execution.
-#define MESSAGES_IN_INTERVAL 1500
-
 // This tag is used in the Structured Clone Algorithm to move js values from
 // worker thread to main thread
 #define CONSOLE_TAG JS_SCTAG_USER_MIN
 
 using namespace mozilla::dom::exceptions;
 using namespace mozilla::dom::workers;
 
 namespace mozilla {
@@ -132,53 +126,93 @@ ConsoleStructuredCloneCallbacksError(JSC
 }
 
 static const JSStructuredCloneCallbacks gConsoleCallbacks = {
   ConsoleStructuredCloneCallbacksRead,
   ConsoleStructuredCloneCallbacksWrite,
   ConsoleStructuredCloneCallbacksError
 };
 
-class ConsoleCallData MOZ_FINAL : public LinkedListElement<ConsoleCallData>
+class ConsoleCallData MOZ_FINAL
 {
 public:
   ConsoleCallData()
     : mMethodName(Console::MethodLog)
     , mPrivate(false)
     , mTimeStamp(JS_Now() / PR_USEC_PER_MSEC)
-    , mMonotonicTimer(0)
-  {
-    MOZ_COUNT_CTOR(ConsoleCallData);
-  }
-
-  ~ConsoleCallData()
-  {
-    MOZ_COUNT_DTOR(ConsoleCallData);
-  }
+    , mIDType(eUnknown)
+    , mOuterIDNumber(0)
+    , mInnerIDNumber(0)
+  { }
 
   void
   Initialize(JSContext* aCx, Console::MethodName aName,
              const nsAString& aString, const Sequence<JS::Value>& aArguments)
   {
     mGlobal = JS::CurrentGlobalOrNull(aCx);
     mMethodName = aName;
     mMethodString = aString;
 
     for (uint32_t i = 0; i < aArguments.Length(); ++i) {
       mArguments.AppendElement(aArguments[i]);
     }
   }
 
+  void
+  SetIDs(uint64_t aOuterID, uint64_t aInnerID)
+  {
+    MOZ_ASSERT(mIDType == eUnknown);
+
+    mOuterIDNumber = aOuterID;
+    mInnerIDNumber = aInnerID;
+    mIDType = eNumber;
+  }
+
+  void
+  SetIDs(const nsAString& aOuterID, const nsAString& aInnerID)
+  {
+    MOZ_ASSERT(mIDType == eUnknown);
+
+    mOuterIDString = aOuterID;
+    mInnerIDString = aInnerID;
+    mIDType = eString;
+  }
+
+  void
+  CleanupJSObjects()
+  {
+    mArguments.Clear();
+    mGlobal = nullptr;
+  }
+
   JS::Heap<JSObject*> mGlobal;
 
   Console::MethodName mMethodName;
   bool mPrivate;
   int64_t mTimeStamp;
   DOMHighResTimeStamp mMonotonicTimer;
 
+  // The concept of outerID and innerID is misleading because when a
+  // ConsoleCallData is created from a window, these are the window IDs, but
+  // when the object is created from a SharedWorker, a ServiceWorker or a
+  // subworker of a ChromeWorker these IDs are the type of worker and the
+  // filename of the callee.
+  // In Console.jsm the ID is 'jsm'.
+  enum {
+    eString,
+    eNumber,
+    eUnknown
+  } mIDType;
+
+  uint64_t mOuterIDNumber;
+  nsString mOuterIDString;
+
+  uint64_t mInnerIDNumber;
+  nsString mInnerIDString;
+
   nsString mMethodString;
   nsTArray<JS::Heap<JS::Value>> mArguments;
 
   // Stack management is complicated, because we want to do it as
   // lazily as possible.  Therefore, we have the following behavior:
   // 1)  mTopStackFrame is initialized whenever we have any JS on the stack
   // 2)  mReifiedStack is initialized if we're created in a worker.
   // 3)  mStack is set (possibly to null if there is no JS on the stack) if
@@ -204,18 +238,19 @@ public:
 
 private:
   JSContext* mCx;
 };
 
 class ConsoleRunnable : public nsRunnable
 {
 public:
-  ConsoleRunnable()
+  explicit ConsoleRunnable(Console* aConsole)
     : mWorkerPrivate(GetCurrentThreadWorkerPrivate())
+    , mConsole(aConsole)
   {
     MOZ_ASSERT(mWorkerPrivate);
   }
 
   virtual
   ~ConsoleRunnable()
   {
   }
@@ -243,56 +278,128 @@ public:
     return syncLoop.Run();
   }
 
 private:
   NS_IMETHOD Run()
   {
     AssertIsOnMainThread();
 
-    RunConsole();
+    // Walk up to our containing page
+    WorkerPrivate* wp = mWorkerPrivate;
+    while (wp->GetParent()) {
+      wp = wp->GetParent();
+    }
+
+    nsPIDOMWindow* window = wp->GetWindow();
+    if (!window) {
+      RunWindowless();
+    } else {
+      RunWithWindow(window);
+    }
 
     nsRefPtr<MainThreadStopSyncLoopRunnable> response =
       new MainThreadStopSyncLoopRunnable(mWorkerPrivate,
                                          mSyncLoopTarget.forget(),
                                          true);
     if (!response->Dispatch(nullptr)) {
       NS_WARNING("Failed to dispatch response!");
     }
 
     return NS_OK;
   }
 
+  void
+  RunWithWindow(nsPIDOMWindow* aWindow)
+  {
+    AutoJSAPI jsapi;
+    MOZ_ASSERT(aWindow);
+
+    nsRefPtr<nsGlobalWindow> win = static_cast<nsGlobalWindow*>(aWindow);
+    if (NS_WARN_IF(!jsapi.Init(win))) {
+      return;
+    }
+
+    MOZ_ASSERT(aWindow->IsInnerWindow());
+    nsPIDOMWindow* outerWindow = aWindow->GetOuterWindow();
+    MOZ_ASSERT(outerWindow);
+
+    RunConsole(jsapi.cx(), outerWindow, aWindow);
+  }
+
+  void
+  RunWindowless()
+  {
+    WorkerPrivate* wp = mWorkerPrivate;
+    while (wp->GetParent()) {
+      wp = wp->GetParent();
+    }
+
+    MOZ_ASSERT(!wp->GetWindow());
+
+    AutoSafeJSContext cx;
+
+    nsCOMPtr<nsIXPConnectJSObjectHolder> sandbox =
+      mConsole->GetOrCreateSandbox(cx, wp->GetPrincipal());
+    if (NS_WARN_IF(!sandbox)) {
+       return;
+    }
+
+    JS::Rooted<JSObject*> global(cx, sandbox->GetJSObject());
+    if (NS_WARN_IF(!global)) {
+      return;
+    }
+
+    // The CreateSandbox call returns a proxy to the actual sandbox object. We
+    // don't need a proxy here.
+    global = js::UncheckedUnwrap(global);
+
+    JSAutoCompartment ac(cx, global);
+
+    RunConsole(cx, nullptr, nullptr);
+  }
+
 protected:
   virtual bool
   PreDispatch(JSContext* aCx) = 0;
 
   virtual void
-  RunConsole() = 0;
+  RunConsole(JSContext* aCx, nsPIDOMWindow* aOuterWindow,
+             nsPIDOMWindow* aInnerWindow) = 0;
 
   WorkerPrivate* mWorkerPrivate;
 
+  // Raw pointer because this method is async and this object is kept alive by
+  // the caller.
+  Console* mConsole;
+
 private:
   nsCOMPtr<nsIEventTarget> mSyncLoopTarget;
 };
 
 // This runnable appends a CallData object into the Console queue running on
 // the main-thread.
 class ConsoleCallDataRunnable MOZ_FINAL : public ConsoleRunnable
 {
 public:
-  explicit ConsoleCallDataRunnable(ConsoleCallData* aCallData)
-    : mCallData(aCallData)
-  {
-  }
+  ConsoleCallDataRunnable(Console* aConsole,
+                          ConsoleCallData* aCallData)
+    : ConsoleRunnable(aConsole)
+    , mCallData(aCallData)
+  { }
 
 private:
+  ~ConsoleCallDataRunnable()
+  { }
+
   bool
   PreDispatch(JSContext* aCx) MOZ_OVERRIDE
   {
+    mWorkerPrivate->AssertIsOnWorkerThread();
+
     ClearException ce(aCx);
     JSAutoCompartment ac(aCx, mCallData->mGlobal);
 
     JS::Rooted<JSObject*> arguments(aCx,
       JS_NewArrayObject(aCx, mCallData->mArguments.Length()));
     if (!arguments) {
       return false;
     }
@@ -306,96 +413,106 @@ private:
     }
 
     JS::Rooted<JS::Value> value(aCx, JS::ObjectValue(*arguments));
 
     if (!mArguments.write(aCx, value, &gConsoleCallbacks, &mStrings)) {
       return false;
     }
 
-    mCallData->mArguments.Clear();
-    mCallData->mGlobal = nullptr;
+    mCallData->CleanupJSObjects();
     return true;
   }
 
   void
-  RunConsole() MOZ_OVERRIDE
+  RunConsole(JSContext* aCx, nsPIDOMWindow* aOuterWindow,
+             nsPIDOMWindow* aInnerWindow) MOZ_OVERRIDE
   {
-    // Walk up to our containing page
-    WorkerPrivate* wp = mWorkerPrivate;
-    while (wp->GetParent()) {
-      wp = wp->GetParent();
+    MOZ_ASSERT(NS_IsMainThread());
+
+    // The windows have to run in parallel.
+    MOZ_ASSERT(!!aOuterWindow == !!aInnerWindow);
+
+    if (aOuterWindow) {
+      mCallData->SetIDs(aOuterWindow->WindowID(), aInnerWindow->WindowID());
+    } else {
+      ConsoleStackEntry frame;
+      if (mCallData->mTopStackFrame) {
+        frame = *mCallData->mTopStackFrame;
+      }
+
+      nsString id;
+      if (mWorkerPrivate->IsSharedWorker()) {
+        id = NS_LITERAL_STRING("SharedWorker");
+      } else if (mWorkerPrivate->IsServiceWorker()) {
+        id = NS_LITERAL_STRING("ServiceWorker");
+      } else {
+        id = NS_LITERAL_STRING("Worker");
+      }
+
+      mCallData->SetIDs(id, frame.mFilename);
     }
 
-    nsPIDOMWindow* window = wp->GetWindow();
-    NS_ENSURE_TRUE_VOID(window);
-
-    nsRefPtr<nsGlobalWindow> win = static_cast<nsGlobalWindow*>(window);
-    NS_ENSURE_TRUE_VOID(win);
+    ProcessCallData(aCx);
+    mCallData->CleanupJSObjects();
+  }
 
-    AutoJSAPI jsapi;
-    if (NS_WARN_IF(!jsapi.Init(win))) {
-      return;
-    }
-    JSContext* cx = jsapi.cx();
-    ClearException ce(cx);
+private:
+  void
+  ProcessCallData(JSContext* aCx)
+  {
+    ClearException ce(aCx);
 
-    ErrorResult error;
-    nsRefPtr<Console> console = win->GetConsole(error);
-    if (error.Failed()) {
-      NS_WARNING("Failed to get console from the window.");
-      return;
-    }
-
-    JS::Rooted<JS::Value> argumentsValue(cx);
-    if (!mArguments.read(cx, &argumentsValue, &gConsoleCallbacks, &mStrings)) {
+    JS::Rooted<JS::Value> argumentsValue(aCx);
+    if (!mArguments.read(aCx, &argumentsValue, &gConsoleCallbacks, &mStrings)) {
       return;
     }
 
     MOZ_ASSERT(argumentsValue.isObject());
-    JS::Rooted<JSObject*> argumentsObj(cx, &argumentsValue.toObject());
-    MOZ_ASSERT(JS_IsArrayObject(cx, argumentsObj));
+    JS::Rooted<JSObject*> argumentsObj(aCx, &argumentsValue.toObject());
+    MOZ_ASSERT(JS_IsArrayObject(aCx, argumentsObj));
 
     uint32_t length;
-    if (!JS_GetArrayLength(cx, argumentsObj, &length)) {
+    if (!JS_GetArrayLength(aCx, argumentsObj, &length)) {
       return;
     }
 
     for (uint32_t i = 0; i < length; ++i) {
-      JS::Rooted<JS::Value> value(cx);
+      JS::Rooted<JS::Value> value(aCx);
 
-      if (!JS_GetElement(cx, argumentsObj, i, &value)) {
+      if (!JS_GetElement(aCx, argumentsObj, i, &value)) {
         return;
       }
 
       mCallData->mArguments.AppendElement(value);
     }
 
     MOZ_ASSERT(mCallData->mArguments.Length() == length);
 
-    mCallData->mGlobal = JS::CurrentGlobalOrNull(cx);
-    console->AppendCallData(mCallData.forget());
+    mCallData->mGlobal = JS::CurrentGlobalOrNull(aCx);
+    mConsole->ProcessCallData(mCallData);
   }
 
-private:
-  nsAutoPtr<ConsoleCallData> mCallData;
+  ConsoleCallData* mCallData;
 
   JSAutoStructuredCloneBuffer mArguments;
   nsTArray<nsString> mStrings;
 };
 
 // This runnable calls ProfileMethod() on the console on the main-thread.
 class ConsoleProfileRunnable MOZ_FINAL : public ConsoleRunnable
 {
 public:
-  ConsoleProfileRunnable(const nsAString& aAction,
+  ConsoleProfileRunnable(Console* aConsole, const nsAString& aAction,
                          const Sequence<JS::Value>& aArguments)
-    : mAction(aAction)
+    : ConsoleRunnable(aConsole)
+    , mAction(aAction)
     , mArguments(aArguments)
   {
+    MOZ_ASSERT(aConsole);
   }
 
 private:
   bool
   PreDispatch(JSContext* aCx) MOZ_OVERRIDE
   {
     ClearException ce(aCx);
 
@@ -425,124 +542,84 @@ private:
     if (!mBuffer.write(aCx, value, &gConsoleCallbacks, &mStrings)) {
       return false;
     }
 
     return true;
   }
 
   void
-  RunConsole() MOZ_OVERRIDE
+  RunConsole(JSContext* aCx, nsPIDOMWindow* aOuterWindow,
+             nsPIDOMWindow* aInnerWindow) MOZ_OVERRIDE
   {
-    // Walk up to our containing page
-    WorkerPrivate* wp = mWorkerPrivate;
-    while (wp->GetParent()) {
-      wp = wp->GetParent();
-    }
-
-    nsPIDOMWindow* window = wp->GetWindow();
-    NS_ENSURE_TRUE_VOID(window);
-
-    nsRefPtr<nsGlobalWindow> win = static_cast<nsGlobalWindow*>(window);
-    NS_ENSURE_TRUE_VOID(win);
+    ClearException ce(aCx);
 
-    AutoJSAPI jsapi;
-    if (NS_WARN_IF(!jsapi.Init(win))) {
-      return;
-    }
-    JSContext* cx = jsapi.cx();
-    ClearException ce(cx);
-
-    ErrorResult error;
-    nsRefPtr<Console> console = win->GetConsole(error);
-    if (error.Failed()) {
-      NS_WARNING("Failed to get console from the window.");
-      return;
-    }
-
-    JS::Rooted<JS::Value> argumentsValue(cx);
-    if (!mBuffer.read(cx, &argumentsValue, &gConsoleCallbacks, &mStrings)) {
+    JS::Rooted<JS::Value> argumentsValue(aCx);
+    if (!mBuffer.read(aCx, &argumentsValue, &gConsoleCallbacks, &mStrings)) {
       return;
     }
 
     MOZ_ASSERT(argumentsValue.isObject());
-    JS::Rooted<JSObject*> argumentsObj(cx, &argumentsValue.toObject());
-    MOZ_ASSERT(JS_IsArrayObject(cx, argumentsObj));
+    JS::Rooted<JSObject*> argumentsObj(aCx, &argumentsValue.toObject());
+    MOZ_ASSERT(JS_IsArrayObject(aCx, argumentsObj));
 
     uint32_t length;
-    if (!JS_GetArrayLength(cx, argumentsObj, &length)) {
+    if (!JS_GetArrayLength(aCx, argumentsObj, &length)) {
       return;
     }
 
     Sequence<JS::Value> arguments;
 
     for (uint32_t i = 0; i < length; ++i) {
-      JS::Rooted<JS::Value> value(cx);
+      JS::Rooted<JS::Value> value(aCx);
 
-      if (!JS_GetElement(cx, argumentsObj, i, &value)) {
+      if (!JS_GetElement(aCx, argumentsObj, i, &value)) {
         return;
       }
 
       arguments.AppendElement(value);
     }
 
-    console->ProfileMethod(cx, mAction, arguments);
+    mConsole->ProfileMethod(aCx, mAction, arguments);
   }
 
-private:
   nsString mAction;
   Sequence<JS::Value> mArguments;
 
   JSAutoStructuredCloneBuffer mBuffer;
   nsTArray<nsString> mStrings;
 };
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(Console)
 
+// We don't need to traverse/unlink mStorage and mSanbox because they are not
+// CCed objects and they are only used on the main thread, even when this
+// Console object is used on workers.
+
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(Console)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mWindow)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mTimer)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mStorage)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
-
-  tmp->ClearConsoleData();
-
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(Console)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWindow)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTimer)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStorage)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(Console)
   NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
-
-  for (ConsoleCallData* data = tmp->mQueuedCalls.getFirst(); data != nullptr;
-       data = data->getNext()) {
-    if (data->mGlobal) {
-      aCallbacks.Trace(&data->mGlobal, "data->mGlobal", aClosure);
-    }
-
-    for (uint32_t i = 0; i < data->mArguments.Length(); ++i) {
-      aCallbacks.Trace(&data->mArguments[i], "data->mArguments[i]", aClosure);
-    }
-  }
-
 NS_IMPL_CYCLE_COLLECTION_TRACE_END
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(Console)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(Console)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Console)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
-  NS_INTERFACE_MAP_ENTRY(nsITimerCallback)
   NS_INTERFACE_MAP_ENTRY(nsIObserver)
-  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsITimerCallback)
+  NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
 Console::Console(nsPIDOMWindow* aWindow)
   : mWindow(aWindow)
   , mOuterID(0)
   , mInnerID(0)
 {
   if (mWindow) {
@@ -561,16 +638,33 @@ Console::Console(nsPIDOMWindow* aWindow)
     }
   }
 
   mozilla::HoldJSObjects(this);
 }
 
 Console::~Console()
 {
+  if (!NS_IsMainThread()) {
+    nsCOMPtr<nsIThread> mainThread;
+    NS_GetMainThread(getter_AddRefs(mainThread));
+
+    if (mStorage) {
+      nsIConsoleAPIStorage* storage;
+      mStorage.forget(&storage);
+      NS_ProxyRelease(mainThread, storage, false);
+    }
+
+    if (mSandbox) {
+      nsIXPConnectJSObjectHolder* sandbox;
+      mSandbox.forget(&sandbox);
+      NS_ProxyRelease(mainThread, sandbox, false);
+    }
+  }
+
   mozilla::DropJSObjects(this);
 }
 
 NS_IMETHODIMP
 Console::Observe(nsISupports* aSubject, const char* aTopic,
                  const char16_t* aData)
 {
   MOZ_ASSERT(NS_IsMainThread());
@@ -588,23 +682,17 @@ Console::Observe(nsISupports* aSubject, 
 
   if (innerID == mInnerID) {
     nsCOMPtr<nsIObserverService> obs =
       do_GetService("@mozilla.org/observer-service;1");
     if (obs) {
       obs->RemoveObserver(this, "inner-window-destroyed");
     }
 
-    ClearConsoleData();
     mTimerRegistry.Clear();
-
-    if (mTimer) {
-      mTimer->Cancel();
-      mTimer = nullptr;
-    }
   }
 
   return NS_OK;
 }
 
 JSObject*
 Console::WrapObject(JSContext* aCx)
 {
@@ -680,17 +768,17 @@ Console::ProfileEnd(JSContext* aCx, cons
 
 void
 Console::ProfileMethod(JSContext* aCx, const nsAString& aAction,
                        const Sequence<JS::Value>& aData)
 {
   if (!NS_IsMainThread()) {
     // Here we are in a worker thread.
     nsRefPtr<ConsoleProfileRunnable> runnable =
-      new ConsoleProfileRunnable(aAction, aData);
+      new ConsoleProfileRunnable(this, aAction, aData);
     runnable->Dispatch();
     return;
   }
 
   ClearException ce(aCx);
 
   RootedDictionary<ConsoleProfileEvent> event(aCx);
   event.mAction = aAction;
@@ -838,53 +926,21 @@ public:
 };
 
 // Queue a call to a console method. See the CALL_DELAY constant.
 void
 Console::Method(JSContext* aCx, MethodName aMethodName,
                 const nsAString& aMethodString,
                 const Sequence<JS::Value>& aData)
 {
-  // This RAII class removes the last element of the mQueuedCalls if something
-  // goes wrong.
-  class RAII {
-  public:
-    explicit RAII(LinkedList<ConsoleCallData>& aList)
-      : mList(aList)
-      , mUnfinished(true)
-    {
-    }
-
-    ~RAII()
-    {
-      if (mUnfinished) {
-        ConsoleCallData* data = mList.popLast();
-        MOZ_ASSERT(data);
-        delete data;
-      }
-    }
-
-    void
-    Finished()
-    {
-      mUnfinished = false;
-    }
-
-  private:
-    LinkedList<ConsoleCallData>& mList;
-    bool mUnfinished;
-  };
-
-  ConsoleCallData* callData = new ConsoleCallData();
-  mQueuedCalls.insertBack(callData);
+  nsAutoPtr<ConsoleCallData> callData(new ConsoleCallData());
 
   ClearException ce(aCx);
 
   callData->Initialize(aCx, aMethodName, aMethodString, aData);
-  RAII raii(mQueuedCalls);
 
   if (mWindow) {
     nsCOMPtr<nsIWebNavigation> webNav = do_GetInterface(mWindow);
     if (!webNav) {
       return;
     }
 
     nsCOMPtr<nsILoadContext> loadContext = do_QueryInterface(webNav);
@@ -984,72 +1040,27 @@ Console::Method(JSContext* aCx, MethodNa
 
       TimeDuration duration =
         mozilla::TimeStamp::Now() - workerPrivate->CreationTimeStamp();
 
       callData->mMonotonicTimer = duration.ToMilliseconds();
     }
   }
 
-  // The operation is completed. RAII class has to be disabled.
-  raii.Finished();
-
-  if (!NS_IsMainThread()) {
-    // Here we are in a worker thread. The ConsoleCallData has to been removed
-    // from the list and it will be deleted by the ConsoleCallDataRunnable or
-    // by the Main-Thread Console object.
-    mQueuedCalls.popLast();
-
-    nsRefPtr<ConsoleCallDataRunnable> runnable =
-      new ConsoleCallDataRunnable(callData);
-    runnable->Dispatch();
+  if (NS_IsMainThread()) {
+    callData->SetIDs(mOuterID, mInnerID);
+    ProcessCallData(callData);
     return;
   }
 
-  if (!mTimer) {
-    mTimer = do_CreateInstance("@mozilla.org/timer;1");
-    mTimer->InitWithCallback(this, CALL_DELAY,
-                             nsITimer::TYPE_REPEATING_SLACK);
-  }
-}
-
-void
-Console::AppendCallData(ConsoleCallData* aCallData)
-{
-  mQueuedCalls.insertBack(aCallData);
-
-  if (!mTimer) {
-    mTimer = do_CreateInstance("@mozilla.org/timer;1");
-    mTimer->InitWithCallback(this, CALL_DELAY,
-                             nsITimer::TYPE_REPEATING_SLACK);
-  }
-}
-
-// Timer callback used to process each of the queued calls.
-NS_IMETHODIMP
-Console::Notify(nsITimer *timer)
-{
-  MOZ_ASSERT(!mQueuedCalls.isEmpty());
-
-  for (uint32_t i = 0; i < MESSAGES_IN_INTERVAL; ++i) {
-    ConsoleCallData* data = mQueuedCalls.popFirst();
-    if (!data) {
-      break;
-    }
-
-    ProcessCallData(data);
-    delete data;
-  }
-
-  if (mQueuedCalls.isEmpty() && mTimer) {
-    mTimer->Cancel();
-    mTimer = nullptr;
-  }
-
-  return NS_OK;
+  // Note: we can pass the reference of callData because this runnable calls
+  // ProcessCallData() synchronously.
+  nsRefPtr<ConsoleCallDataRunnable> runnable =
+    new ConsoleCallDataRunnable(this, callData);
+  runnable->Dispatch();
 }
 
 // We store information to lazily compute the stack in the reserved slots of
 // LazyStackGetter.  The first slot always stores a JS object: it's either the
 // JS wrapper of the nsIStackFrame or the actual reified stack representation.
 // The second slot is a PrivateValue() holding an nsIStackFrame* when we haven't
 // reified the stack yet, or an UndefinedValue() otherwise.
 enum {
@@ -1106,23 +1117,25 @@ Console::ProcessCallData(ConsoleCallData
   AutoSafeJSContext cx;
   ClearException ce(cx);
   RootedDictionary<ConsoleEvent> event(cx);
 
   JSAutoCompartment ac(cx, aData->mGlobal);
 
   event.mID.Construct();
   event.mInnerID.Construct();
-  if (mWindow) {
-    event.mID.Value().SetAsUnsignedLong() = mOuterID;
-    event.mInnerID.Value().SetAsUnsignedLong() = mInnerID;
+
+  MOZ_ASSERT(aData->mIDType != ConsoleCallData::eUnknown);
+  if (aData->mIDType == ConsoleCallData::eString) {
+    event.mID.Value().SetAsString() = aData->mOuterIDString;
+    event.mInnerID.Value().SetAsString() = aData->mInnerIDString;
   } else {
-    // If we are in a JSM, the window doesn't exist.
-    event.mID.Value().SetAsString() = NS_LITERAL_STRING("jsm");
-    event.mInnerID.Value().SetAsString() = frame.mFilename;
+    MOZ_ASSERT(aData->mIDType == ConsoleCallData::eNumber);
+    event.mID.Value().SetAsUnsignedLong() = aData->mOuterIDNumber;
+    event.mInnerID.Value().SetAsUnsignedLong() = aData->mInnerIDNumber;
   }
 
   event.mLevel = aData->mMethodString;
   event.mFilename = frame.mFilename;
   event.mLineNumber = frame.mLineNumber;
   event.mColumnNumber = frame.mColumnNumber;
   event.mFunctionName = frame.mFunctionName;
   event.mTimeStamp = aData->mTimeStamp;
@@ -1238,38 +1251,30 @@ Console::ProcessCallData(ConsoleCallData
     mStorage = do_GetService("@mozilla.org/consoleAPI-storage;1");
   }
 
   if (!mStorage) {
     NS_WARNING("Failed to get the ConsoleAPIStorage service.");
     return;
   }
 
-  nsAutoString innerID;
-  innerID.AppendInt(mInnerID);
+  nsAutoString innerID, outerID;
 
-  if (NS_FAILED(mStorage->RecordEvent(innerID, eventValue))) {
-    NS_WARNING("Failed to record a console event.");
+  MOZ_ASSERT(aData->mIDType != ConsoleCallData::eUnknown);
+  if (aData->mIDType == ConsoleCallData::eString) {
+    outerID = aData->mOuterIDString;
+    innerID = aData->mInnerIDString;
+  } else {
+    MOZ_ASSERT(aData->mIDType == ConsoleCallData::eNumber);
+    outerID.AppendInt(aData->mOuterIDNumber);
+    innerID.AppendInt(aData->mInnerIDNumber);
   }
 
-  nsXPConnect*  xpc = nsXPConnect::XPConnect();
-  nsCOMPtr<nsISupports> wrapper;
-  const nsIID& iid = NS_GET_IID(nsISupports);
-
-  if (NS_FAILED(xpc->WrapJS(cx, eventObj, iid, getter_AddRefs(wrapper)))) {
-    return;
-  }
-
-  nsCOMPtr<nsIObserverService> obs =
-    do_GetService("@mozilla.org/observer-service;1");
-  if (obs) {
-    nsAutoString outerID;
-    outerID.AppendInt(mOuterID);
-
-    obs->NotifyObservers(wrapper, "console-api-log-event", outerID.get());
+  if (NS_FAILED(mStorage->RecordPendingEvent(innerID, outerID, eventValue))) {
+    NS_WARNING("Failed to record a console event.");
   }
 }
 
 void
 Console::ProcessArguments(JSContext* aCx,
                           const nsTArray<JS::Heap<JS::Value>>& aData,
                           Sequence<JS::Value>& aSequence,
                           Sequence<JS::Value>& aStyles)
@@ -1684,32 +1689,43 @@ Console::IncreaseCounter(JSContext* aCx,
   JS::Rooted<JS::Value> value(aCx);
   if (!ToJSValue(aCx, data, &value)) {
     return JS::UndefinedValue();
   }
 
   return value;
 }
 
-void
-Console::ClearConsoleData()
-{
-  while (ConsoleCallData* data = mQueuedCalls.popFirst()) {
-    delete data;
-  }
-}
-
 bool
 Console::ShouldIncludeStackTrace(MethodName aMethodName)
 {
   switch (aMethodName) {
     case MethodError:
     case MethodException:
     case MethodAssert:
     case MethodTrace:
       return true;
     default:
       return false;
   }
 }
 
+nsIXPConnectJSObjectHolder*
+Console::GetOrCreateSandbox(JSContext* aCx, nsIPrincipal* aPrincipal)
+{
+  MOZ_ASSERT(NS_IsMainThread());
+
+  if (!mSandbox) {
+    nsIXPConnect* xpc = nsContentUtils::XPConnect();
+    MOZ_ASSERT(xpc, "This should never be null!");
+
+    nsresult rv = xpc->CreateSandbox(aCx, aPrincipal,
+                                     getter_AddRefs(mSandbox));
+    if (NS_WARN_IF(NS_FAILED(rv))) {
+      return nullptr;
+    }
+  }
+
+  return mSandbox;
+}
+
 } // namespace dom
 } // namespace mozilla
--- a/dom/base/Console.h
+++ b/dom/base/Console.h
@@ -7,40 +7,37 @@
 #define mozilla_dom_Console_h
 
 #include "mozilla/dom/BindingDeclarations.h"
 #include "mozilla/ErrorResult.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsDataHashtable.h"
 #include "nsHashKeys.h"
 #include "nsIObserver.h"
-#include "nsITimer.h"
 #include "nsWrapperCache.h"
 #include "nsDOMNavigationTiming.h"
 #include "nsPIDOMWindow.h"
 
 class nsIConsoleAPIStorage;
+class nsIXPConnectJSObjectHolder;
 
 namespace mozilla {
 namespace dom {
 
 class ConsoleCallData;
 struct ConsoleStackEntry;
 
-class Console MOZ_FINAL : public nsITimerCallback
-                        , public nsIObserver
+class Console MOZ_FINAL : public nsIObserver
                         , public nsWrapperCache
 {
   ~Console();
 
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Console,
-                                                         nsITimerCallback)
-  NS_DECL_NSITIMERCALLBACK
+  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(Console)
   NS_DECL_NSIOBSERVER
 
   explicit Console(nsPIDOMWindow* aWindow);
 
   // WebIDL methods
   nsISupports* GetParentObject() const
   {
     return mWindow;
@@ -127,19 +124,16 @@ private:
     MethodCount
   };
 
   void
   Method(JSContext* aCx, MethodName aName, const nsAString& aString,
          const Sequence<JS::Value>& aData);
 
   void
-  AppendCallData(ConsoleCallData* aData);
-
-  void
   ProcessCallData(ConsoleCallData* aData);
 
   // If the first JS::Value of the array is a string, this method uses it to
   // format a string. The supported sequences are:
   //   %s    - string
   //   %d,%i - integer
   //   %f    - double
   //   %o,%O - a JS object.
@@ -186,34 +180,34 @@ private:
   void
   ProfileMethod(JSContext* aCx, const nsAString& aAction,
                 const Sequence<JS::Value>& aData);
 
   JS::Value
   IncreaseCounter(JSContext* aCx, const ConsoleStackEntry& aFrame,
                    const nsTArray<JS::Heap<JS::Value>>& aArguments);
 
-  void
-  ClearConsoleData();
-
   bool
   ShouldIncludeStackTrace(MethodName aMethodName);
 
+  nsIXPConnectJSObjectHolder*
+  GetOrCreateSandbox(JSContext* aCx, nsIPrincipal* aPrincipal);
+
   nsCOMPtr<nsPIDOMWindow> mWindow;
-  nsCOMPtr<nsITimer> mTimer;
   nsCOMPtr<nsIConsoleAPIStorage> mStorage;
+  nsCOMPtr<nsIXPConnectJSObjectHolder> mSandbox;
 
-  LinkedList<ConsoleCallData> mQueuedCalls;
   nsDataHashtable<nsStringHashKey, DOMHighResTimeStamp> mTimerRegistry;
   nsDataHashtable<nsStringHashKey, uint32_t> mCounterRegistry;
 
   uint64_t mOuterID;
   uint64_t mInnerID;
 
   friend class ConsoleCallData;
+  friend class ConsoleRunnable;
   friend class ConsoleCallDataRunnable;
   friend class ConsoleProfileRunnable;
 };
 
 } // dom namespace
 } // mozilla namespace
 
 #endif /* mozilla_dom_Console_h */
--- a/dom/base/ConsoleAPIStorage.js
+++ b/dom/base/ConsoleAPIStorage.js
@@ -6,19 +6,28 @@
 
 let Cu = Components.utils;
 let Ci = Components.interfaces;
 let Cc = Components.classes;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 
+// The console API events have to be scheduled when stored using
+// |recordPendingEvent|.
+const CALL_DELAY = 15 // milliseconds
+
+// This constant tells how many messages to process in a single timer execution.
+const MESSAGES_IN_INTERVAL = 1500
+
 const STORAGE_MAX_EVENTS = 200;
 
 var _consoleStorage = new Map();
+var _consolePendingStorage = new Map();
+var _timer;
 
 const CONSOLEAPISTORAGE_CID = Components.ID('{96cf7855-dfa9-4c6d-8276-f9705b4890f2}');
 
 /**
  * The ConsoleAPIStorage is meant to cache window.console API calls for later
  * reuse by other components when needed. For example, the Web Console code can
  * display the cached messages when it opens for the active tab.
  *
@@ -109,34 +118,80 @@ ConsoleAPIStorageService.prototype = {
    * Record an event associated with the given window ID.
    *
    * @param string aId
    *        The ID of the inner window for which the event occurred or "jsm" for
    *        messages logged from JavaScript modules..
    * @param object aEvent
    *        A JavaScript object you want to store.
    */
-  recordEvent: function CS_recordEvent(aId, aEvent)
+  recordEvent: function CS_recordEvent(aId, aOuterId, aEvent)
   {
     if (!_consoleStorage.has(aId)) {
       _consoleStorage.set(aId, []);
     }
 
     let storage = _consoleStorage.get(aId);
     storage.push(aEvent);
 
     // truncate
     if (storage.length > STORAGE_MAX_EVENTS) {
       storage.shift();
     }
 
+    Services.obs.notifyObservers(aEvent, "console-api-log-event", aOuterId);
     Services.obs.notifyObservers(aEvent, "console-storage-cache-event", aId);
   },
 
   /**
+   * Similar to recordEvent, but these events are scheduled and stored any
+   * CALL_DELAY millisecs.
+   */
+  recordPendingEvent: function CS_recordPendingEvent(aId, aOuterId, aEvent)
+  {
+    if (!_consolePendingStorage.has(aId)) {
+      _consolePendingStorage.set(aId, []);
+    }
+
+    let storage = _consolePendingStorage.get(aId);
+    storage.push({ outerId: aOuterId, event: aEvent });
+
+    if (!_timer) {
+      _timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+    }
+
+    let self = this;
+    _timer.initWithCallback(function() { self.flushPendingEvents(); },
+                            CALL_DELAY, Ci.nsITimer.TYPE_REPEATING_SLACK);
+  },
+
+  /**
+   * Processes the pending event queue.
+   */
+  flushPendingEvents: function CS_flushPendingEvents()
+  {
+    for (let [id, objs] of _consolePendingStorage) {
+      for (let i = 0; i < objs.length && i < MESSAGES_IN_INTERVAL; ++i) {
+        this.recordEvent(id, objs[i].outerId, objs[i].event);
+      }
+
+      if (objs.length <= MESSAGES_IN_INTERVAL) {
+        _consolePendingStorage.delete(id);
+      } else {
+        _consolePendingStorage.set(id, objs.splice(MESSAGES_IN_INTERVAL));
+      }
+    }
+
+    if (_timer && _consolePendingStorage.size == 0) {
+      _timer.cancel();
+      _timer = null;
+    }
+  },
+
+  /**
    * Clear storage data for the given window.
    *
    * @param string [aId]
    *        Optional, the inner window ID for which you want to clear the
    *        messages. If this is not specified all of the cached messages are
    *        cleared, from all window objects.
    */
   clearEvents: function CS_clearEvents(aId)
--- a/dom/base/DOMQuad.cpp
+++ b/dom/base/DOMQuad.cpp
@@ -79,35 +79,35 @@ public:
   explicit QuadBounds(DOMQuad* aQuad)
     : DOMRectReadOnly(aQuad->GetParentObject())
     , mQuad(aQuad)
   {}
 
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(QuadBounds, DOMRectReadOnly)
   NS_DECL_ISUPPORTS_INHERITED
 
-  virtual double X() const
+  virtual double X() const MOZ_OVERRIDE
   {
     double x1, x2;
     GetHorizontalMinMax(&x1, &x2);
     return x1;
   }
-  virtual double Y() const
+  virtual double Y() const MOZ_OVERRIDE
   {
     double y1, y2;
     GetVerticalMinMax(&y1, &y2);
     return y1;
   }
-  virtual double Width() const
+  virtual double Width() const MOZ_OVERRIDE
   {
     double x1, x2;
     GetHorizontalMinMax(&x1, &x2);
     return x2 - x1;
   }
-  virtual double Height() const
+  virtual double Height() const MOZ_OVERRIDE
   {
     double y1, y2;
     GetVerticalMinMax(&y1, &y2);
     return y2 - y1;
   }
 
   void GetHorizontalMinMax(double* aX1, double* aX2) const
   {
--- a/dom/base/DOMStringList.h
+++ b/dom/base/DOMStringList.h
@@ -19,17 +19,17 @@ class DOMStringList : public nsISupports
 {
 protected:
   virtual ~DOMStringList();
 
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(DOMStringList)
 
-  virtual JSObject* WrapObject(JSContext* aCx);
+  virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE;
   nsISupports* GetParentObject()
   {
     return nullptr;
   }
 
   void IndexedGetter(uint32_t aIndex, bool& aFound, nsAString& aResult)
   {
     EnsureFresh();
--- a/dom/base/DocumentFragment.h
+++ b/dom/base/DocumentFragment.h
@@ -107,17 +107,17 @@ public:
   }
 
   virtual void UnbindFromTree(bool aDeep, bool aNullParent) MOZ_OVERRIDE
   {
     NS_ASSERTION(false, "Trying to unbind a fragment from a tree");
     return;
   }
 
-  virtual Element* GetNameSpaceElement()
+  virtual Element* GetNameSpaceElement() MOZ_OVERRIDE
   {
     return nullptr;
   }
 
   nsIContent* GetHost() const
   {
     return mHost;
   }
--- a/dom/base/Element.cpp
+++ b/dom/base/Element.cpp
@@ -3073,18 +3073,20 @@ GetFullScreenError(nsIDocument* aDoc)
   if (nsContentUtils::IsSitePermDeny(aDoc->NodePrincipal(), "fullscreen")) {
     return "FullScreenDeniedBlocked";
   }
 
   return nullptr;
 }
 
 void
-Element::MozRequestFullScreen(const RequestFullscreenOptions& aOptions)
+Element::MozRequestFullScreen(JSContext* aCx, JS::Handle<JS::Value> aOptions,
+                              ErrorResult& aError)
 {
+  MOZ_ASSERT_IF(!aCx, aOptions.isNullOrUndefined());
   // Only grant full-screen requests if this is called from inside a trusted
   // event handler (i.e. inside an event handler for a user initiated event).
   // This stops the full-screen from being abused similar to the popups of old,
   // and it also makes it harder for bad guys' script to go full-screen and
   // spoof the browser chrome/window and phish logins etc.
   // Note that requests for fullscreen inside a web app's origin are exempt
   // from this restriction.
   const char* error = GetFullScreenError(OwnerDoc());
@@ -3098,23 +3100,33 @@ Element::MozRequestFullScreen(const Requ
                                NS_LITERAL_STRING("mozfullscreenerror"),
                                true,
                                false);
     asyncDispatcher->PostDOMEvent();
     return;
   }
 
   FullScreenOptions opts;
-  if (aOptions.mVrDisplay) {
-    opts.mVRHMDDevice = aOptions.mVrDisplay->GetHMD();
+  RequestFullscreenOptions fsOptions;
+
+  // We need to check if options is convertible to a dict first before
+  // trying to init fsOptions; otherwise Init() would throw, and we want to
+  // silently ignore non-dictionary values
+  if (aCx && IsConvertibleToDictionary(aCx, aOptions)) {
+    if (!fsOptions.Init(aCx, aOptions)) {
+      aError.Throw(NS_ERROR_FAILURE);
+      return;
+    }
+
+    if (fsOptions.mVrDisplay) {
+      opts.mVRHMDDevice = fsOptions.mVrDisplay->GetHMD();
+    }
   }
 
   OwnerDoc()->AsyncRequestFullScreen(this, opts);
-
-  return;
 }
 
 void
 Element::MozRequestPointerLock()
 {
   OwnerDoc()->RequestPointerLock(this);
 }
 
--- a/dom/base/Element.h
+++ b/dom/base/Element.h
@@ -154,17 +154,17 @@ public:
     NS_ABORT_IF_FALSE(mNodeInfo->NodeType() == nsIDOMNode::ELEMENT_NODE,
                       "Bad NodeType in aNodeInfo");
     SetIsElement();
   }
 #endif // MOZILLA_INTERNAL_API
 
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_ELEMENT_IID)
 
-  NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr);
+  NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr) MOZ_OVERRIDE;
 
   /**
    * Method to get the full state of this element.  See mozilla/EventStates.h
    * for the possible bits that could be set here.
    */
   EventStates State() const
   {
     // mState is maintained by having whoever might have changed it
@@ -720,17 +720,20 @@ public:
     }
   }
   void ReleaseCapture()
   {
     if (nsIPresShell::GetCapturingContent() == this) {
       nsIPresShell::SetCapturingContent(nullptr, 0);
     }
   }
-  void MozRequestFullScreen(const RequestFullscreenOptions& aOptions);
+
+  // aCx == nullptr is allowed only if aOptions.isNullOrUndefined()
+  void MozRequestFullScreen(JSContext* aCx, JS::Handle<JS::Value> aOptions,
+                            ErrorResult& aError);
   void MozRequestPointerLock();
   Attr* GetAttributeNode(const nsAString& aName);
   already_AddRefed<Attr> SetAttributeNode(Attr& aNewAttr,
                                           ErrorResult& aError);
   already_AddRefed<Attr> RemoveAttributeNode(Attr& aOldAttr,
                                              ErrorResult& aError);
   Attr* GetAttributeNodeNS(const nsAString& aNamespaceURI,
                            const nsAString& aLocalName);
@@ -1206,17 +1209,17 @@ protected:
 
   /**
    * Internal hook for converting an attribute name-string to an atomized name
    */
   virtual const nsAttrName* InternalGetExistingAttrNameFromQName(const nsAString& aStr) const;
 
   nsIFrame* GetStyledFrame();
 
-  virtual Element* GetNameSpaceElement()
+  virtual Element* GetNameSpaceElement() MOZ_OVERRIDE
   {
     return this;
   }
 
   Attr* GetAttributeNodeNSInternal(const nsAString& aNamespaceURI,
                                    const nsAString& aLocalName);
 
   inline void RegisterActivityObserver();
@@ -1306,19 +1309,19 @@ public:
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS(DestinationInsertionPointList)
 
   // nsIDOMNodeList
   NS_DECL_NSIDOMNODELIST
 
   // nsINodeList
-  virtual nsIContent* Item(uint32_t aIndex);
-  virtual int32_t IndexOf(nsIContent* aContent);
-  virtual nsINode* GetParentObject() { return mParent; }
+  virtual nsIContent* Item(uint32_t aIndex) MOZ_OVERRIDE;
+  virtual int32_t IndexOf(nsIContent* aContent) MOZ_OVERRIDE;
+  virtual nsINode* GetParentObject() MOZ_OVERRIDE { return mParent; }
   virtual uint32_t Length() const;
   virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE;
 protected:
   virtual ~DestinationInsertionPointList();
 
   nsRefPtr<Element> mParent;
   nsCOMArray<nsIContent> mDestinationPoints;
 };
@@ -1462,332 +1465,345 @@ nsresult                                
   NS_IMETHODIMP                                                       \
   _class::Set##_method(bool aValue)                                   \
   {                                                                   \
     return SetBoolAttr(nsGkAtoms::_atom, aValue);                     \
   }
 
 #define NS_FORWARD_NSIDOMELEMENT_TO_GENERIC                                   \
 typedef mozilla::dom::Element Element;                                        \
-NS_IMETHOD GetTagName(nsAString& aTagName) MOZ_FINAL                          \
+NS_IMETHOD GetTagName(nsAString& aTagName) MOZ_FINAL MOZ_OVERRIDE             \
 {                                                                             \
   Element::GetTagName(aTagName);                                              \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetId(nsAString& aId) MOZ_FINAL                                    \
+NS_IMETHOD GetId(nsAString& aId) MOZ_FINAL MOZ_OVERRIDE                       \
 {                                                                             \
   Element::GetId(aId);                                                        \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD SetId(const nsAString& aId) MOZ_FINAL                              \
+NS_IMETHOD SetId(const nsAString& aId) MOZ_FINAL MOZ_OVERRIDE                 \
 {                                                                             \
   Element::SetId(aId);                                                        \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetClassName(nsAString& aClassName) MOZ_FINAL                      \
+NS_IMETHOD GetClassName(nsAString& aClassName) MOZ_FINAL MOZ_OVERRIDE         \
 {                                                                             \
   Element::GetClassName(aClassName);                                          \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD SetClassName(const nsAString& aClassName) MOZ_FINAL                \
+NS_IMETHOD SetClassName(const nsAString& aClassName) MOZ_FINAL MOZ_OVERRIDE   \
 {                                                                             \
   Element::SetClassName(aClassName);                                          \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetClassList(nsISupports** aClassList) MOZ_FINAL                   \
+NS_IMETHOD GetClassList(nsISupports** aClassList) MOZ_FINAL MOZ_OVERRIDE      \
 {                                                                             \
   Element::GetClassList(aClassList);                                          \
   return NS_OK;                                                               \
 }                                                                             \
 NS_IMETHOD GetAttributes(nsIDOMMozNamedAttrMap** aAttributes) MOZ_FINAL       \
+  MOZ_OVERRIDE                                                                \
 {                                                                             \
   NS_ADDREF(*aAttributes = Attributes());                                     \
   return NS_OK;                                                               \
 }                                                                             \
 using Element::GetAttribute;                                                  \
 NS_IMETHOD GetAttribute(const nsAString& name, nsAString& _retval) MOZ_FINAL  \
+  MOZ_OVERRIDE                                                                \
 {                                                                             \
   nsString attr;                                                              \
   GetAttribute(name, attr);                                                   \
   _retval = attr;                                                             \
   return NS_OK;                                                               \
 }                                                                             \
 NS_IMETHOD GetAttributeNS(const nsAString& namespaceURI,                      \
                           const nsAString& localName,                         \
-                          nsAString& _retval) MOZ_FINAL                       \
+                          nsAString& _retval) MOZ_FINAL MOZ_OVERRIDE          \
 {                                                                             \
   Element::GetAttributeNS(namespaceURI, localName, _retval);                  \
   return NS_OK;                                                               \
 }                                                                             \
 NS_IMETHOD SetAttribute(const nsAString& name,                                \
-                        const nsAString& value)                               \
+                        const nsAString& value) MOZ_OVERRIDE                  \
 {                                                                             \
   mozilla::ErrorResult rv;                                                    \
   Element::SetAttribute(name, value, rv);                                     \
   return rv.ErrorCode();                                                      \
 }                                                                             \
 NS_IMETHOD SetAttributeNS(const nsAString& namespaceURI,                      \
                           const nsAString& qualifiedName,                     \
-                          const nsAString& value) MOZ_FINAL                   \
+                          const nsAString& value) MOZ_FINAL MOZ_OVERRIDE      \
 {                                                                             \
   mozilla::ErrorResult rv;                                                    \
   Element::SetAttributeNS(namespaceURI, qualifiedName, value, rv);            \
   return rv.ErrorCode();                                                      \
 }                                                                             \
 using Element::RemoveAttribute;                                               \
-NS_IMETHOD RemoveAttribute(const nsAString& name) MOZ_FINAL                   \
+NS_IMETHOD RemoveAttribute(const nsAString& name) MOZ_FINAL MOZ_OVERRIDE      \
 {                                                                             \
   mozilla::ErrorResult rv;                                                    \
   RemoveAttribute(name, rv);                                                  \
   return rv.ErrorCode();                                                      \
 }                                                                             \
 NS_IMETHOD RemoveAttributeNS(const nsAString& namespaceURI,                   \
                              const nsAString& localName) MOZ_FINAL            \
+  MOZ_OVERRIDE                                                                \
 {                                                                             \
   mozilla::ErrorResult rv;                                                    \
   Element::RemoveAttributeNS(namespaceURI, localName, rv);                    \
   return rv.ErrorCode();                                                      \
 }                                                                             \
 using Element::HasAttribute;                                                  \
 NS_IMETHOD HasAttribute(const nsAString& name,                                \
-                           bool* _retval) MOZ_FINAL                           \
+                           bool* _retval) MOZ_FINAL MOZ_OVERRIDE              \
 {                                                                             \
   *_retval = HasAttribute(name);                                              \
   return NS_OK;                                                               \
 }                                                                             \
 NS_IMETHOD HasAttributeNS(const nsAString& namespaceURI,                      \
                           const nsAString& localName,                         \
-                          bool* _retval) MOZ_FINAL                            \
+                          bool* _retval) MOZ_FINAL MOZ_OVERRIDE               \
 {                                                                             \
   *_retval = Element::HasAttributeNS(namespaceURI, localName);                \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD HasAttributes(bool* _retval) MOZ_FINAL                             \
+NS_IMETHOD HasAttributes(bool* _retval) MOZ_FINAL MOZ_OVERRIDE                \
 {                                                                             \
   *_retval = Element::HasAttributes();                                        \
   return NS_OK;                                                               \
 }                                                                             \
 NS_IMETHOD GetAttributeNode(const nsAString& name,                            \
-                            nsIDOMAttr** _retval) MOZ_FINAL                   \
+                            nsIDOMAttr** _retval) MOZ_FINAL MOZ_OVERRIDE      \
 {                                                                             \
   NS_IF_ADDREF(*_retval = Element::GetAttributeNode(name));                   \
   return NS_OK;                                                               \
 }                                                                             \
 NS_IMETHOD SetAttributeNode(nsIDOMAttr* newAttr,                              \
-                            nsIDOMAttr** _retval) MOZ_FINAL                   \
+                            nsIDOMAttr** _retval) MOZ_FINAL MOZ_OVERRIDE      \
 {                                                                             \
   if (!newAttr) {                                                             \
     return NS_ERROR_INVALID_POINTER;                                          \
   }                                                                           \
   mozilla::ErrorResult rv;                                                    \
   mozilla::dom::Attr* attr = static_cast<mozilla::dom::Attr*>(newAttr);       \
   *_retval = Element::SetAttributeNode(*attr, rv).take();                     \
   return rv.ErrorCode();                                                      \
 }                                                                             \
 NS_IMETHOD RemoveAttributeNode(nsIDOMAttr* oldAttr,                           \
-                               nsIDOMAttr** _retval) MOZ_FINAL                \
+                               nsIDOMAttr** _retval) MOZ_FINAL MOZ_OVERRIDE   \
 {                                                                             \
   if (!oldAttr) {                                                             \
     return NS_ERROR_INVALID_POINTER;                                          \
   }                                                                           \
   mozilla::ErrorResult rv;                                                    \
   mozilla::dom::Attr* attr = static_cast<mozilla::dom::Attr*>(oldAttr);       \
   *_retval = Element::RemoveAttributeNode(*attr, rv).take();                  \
   return rv.ErrorCode();                                                      \
 }                                                                             \
 NS_IMETHOD GetAttributeNodeNS(const nsAString& namespaceURI,                  \
                               const nsAString& localName,                     \
-                              nsIDOMAttr** _retval) MOZ_FINAL                 \
+                              nsIDOMAttr** _retval) MOZ_FINAL MOZ_OVERRIDE    \
 {                                                                             \
   NS_IF_ADDREF(*_retval = Element::GetAttributeNodeNS(namespaceURI,           \
                                                       localName));            \
   return NS_OK;                                                               \
 }                                                                             \
 NS_IMETHOD SetAttributeNodeNS(nsIDOMAttr* newAttr,                            \
-                              nsIDOMAttr** _retval) MOZ_FINAL                 \
+                              nsIDOMAttr** _retval) MOZ_FINAL MOZ_OVERRIDE    \
 {                                                                             \
   mozilla::ErrorResult rv;                                                    \
   mozilla::dom::Attr* attr = static_cast<mozilla::dom::Attr*>(newAttr);       \
   *_retval = Element::SetAttributeNodeNS(*attr, rv).take();                   \
   return rv.ErrorCode();                                                      \
 }                                                                             \
 NS_IMETHOD GetElementsByTagName(const nsAString& name,                        \
                                 nsIDOMHTMLCollection** _retval) MOZ_FINAL     \
+                                                                MOZ_OVERRIDE  \
 {                                                                             \
   Element::GetElementsByTagName(name, _retval);                               \
   return NS_OK;                                                               \
 }                                                                             \
 NS_IMETHOD GetElementsByTagNameNS(const nsAString& namespaceURI,              \
                                   const nsAString& localName,                 \
                                   nsIDOMHTMLCollection** _retval) MOZ_FINAL   \
+                                                                  MOZ_OVERRIDE\
 {                                                                             \
   return Element::GetElementsByTagNameNS(namespaceURI, localName,             \
                                          _retval);                            \
 }                                                                             \
 NS_IMETHOD GetElementsByClassName(const nsAString& classes,                   \
                                   nsIDOMHTMLCollection** _retval) MOZ_FINAL   \
+                                                                  MOZ_OVERRIDE\
 {                                                                             \
   return Element::GetElementsByClassName(classes, _retval);                   \
 }                                                                             \
 NS_IMETHOD GetChildElements(nsIDOMNodeList** aChildElements) MOZ_FINAL        \
+  MOZ_OVERRIDE                                                                \
 {                                                                             \
   nsIHTMLCollection* list = FragmentOrElement::Children();                    \
   return CallQueryInterface(list, aChildElements);                            \
 }                                                                             \
 NS_IMETHOD GetFirstElementChild(nsIDOMElement** aFirstElementChild) MOZ_FINAL \
+  MOZ_OVERRIDE                                                                \
 {                                                                             \
   Element* element = Element::GetFirstElementChild();                         \
   if (!element) {                                                             \
     *aFirstElementChild = nullptr;                                            \
     return NS_OK;                                                             \
   }                                                                           \
   return CallQueryInterface(element, aFirstElementChild);                     \
 }                                                                             \
 NS_IMETHOD GetLastElementChild(nsIDOMElement** aLastElementChild) MOZ_FINAL   \
+  MOZ_OVERRIDE                                                                \
 {                                                                             \
   Element* element = Element::GetLastElementChild();                          \
   if (!element) {                                                             \
     *aLastElementChild = nullptr;                                             \
     return NS_OK;                                                             \
   }                                                                           \
   return CallQueryInterface(element, aLastElementChild);                      \
 }                                                                             \
 NS_IMETHOD GetPreviousElementSibling(nsIDOMElement** aPreviousElementSibling) \
-  MOZ_FINAL                                                                   \
+  MOZ_FINAL MOZ_OVERRIDE                                                      \
 {                                                                             \
   Element* element = Element::GetPreviousElementSibling();                    \
   if (!element) {                                                             \
     *aPreviousElementSibling = nullptr;                                       \
     return NS_OK;                                                             \
   }                                                                           \
   return CallQueryInterface(element, aPreviousElementSibling);                \
 }                                                                             \
 NS_IMETHOD GetNextElementSibling(nsIDOMElement** aNextElementSibling)         \
-  MOZ_FINAL                                                                   \
+  MOZ_FINAL MOZ_OVERRIDE                                                      \
 {                                                                             \
   Element* element = Element::GetNextElementSibling();                        \
   if (!element) {                                                             \
     *aNextElementSibling = nullptr;                                           \
     return NS_OK;                                                             \
   }                                                                           \
   return CallQueryInterface(element, aNextElementSibling);                    \
 }                                                                             \
 NS_IMETHOD GetChildElementCount(uint32_t* aChildElementCount) MOZ_FINAL       \
+  MOZ_OVERRIDE                                                                \
 {                                                                             \
   *aChildElementCount = Element::ChildElementCount();                         \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD MozRemove() MOZ_FINAL                                              \
+NS_IMETHOD MozRemove() MOZ_FINAL MOZ_OVERRIDE                                 \
 {                                                                             \
   nsINode::Remove();                                                          \
   return NS_OK;                                                               \
 }                                                                             \
 NS_IMETHOD GetClientRects(nsIDOMClientRectList** _retval) MOZ_FINAL           \
+  MOZ_OVERRIDE                                                                \
 {                                                                             \
   *_retval = Element::GetClientRects().take();                                \
   return NS_OK;                                                               \
 }                                                                             \
 NS_IMETHOD GetBoundingClientRect(nsIDOMClientRect** _retval) MOZ_FINAL        \
+  MOZ_OVERRIDE                                                                \
 {                                                                             \
   *_retval = Element::GetBoundingClientRect().take();                         \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetScrollTop(int32_t* aScrollTop) MOZ_FINAL                        \
+NS_IMETHOD GetScrollTop(int32_t* aScrollTop) MOZ_FINAL MOZ_OVERRIDE           \
 {                                                                             \
   *aScrollTop = Element::ScrollTop();                                         \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD SetScrollTop(int32_t aScrollTop) MOZ_FINAL                         \
+NS_IMETHOD SetScrollTop(int32_t aScrollTop) MOZ_FINAL MOZ_OVERRIDE            \
 {                                                                             \
   Element::SetScrollTop(aScrollTop);                                          \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetScrollLeft(int32_t* aScrollLeft) MOZ_FINAL                      \
+NS_IMETHOD GetScrollLeft(int32_t* aScrollLeft) MOZ_FINAL MOZ_OVERRIDE         \
 {                                                                             \
   *aScrollLeft = Element::ScrollLeft();                                       \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD SetScrollLeft(int32_t aScrollLeft) MOZ_FINAL                       \
+NS_IMETHOD SetScrollLeft(int32_t aScrollLeft) MOZ_FINAL MOZ_OVERRIDE          \
 {                                                                             \
   Element::SetScrollLeft(aScrollLeft);                                        \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetScrollWidth(int32_t* aScrollWidth) MOZ_FINAL                    \
+NS_IMETHOD GetScrollWidth(int32_t* aScrollWidth) MOZ_FINAL MOZ_OVERRIDE       \
 {                                                                             \
   *aScrollWidth = Element::ScrollWidth();                                     \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetScrollHeight(int32_t* aScrollHeight) MOZ_FINAL                  \
+NS_IMETHOD GetScrollHeight(int32_t* aScrollHeight) MOZ_FINAL MOZ_OVERRIDE     \
 {                                                                             \
   *aScrollHeight = Element::ScrollHeight();                                   \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetClientTop(int32_t* aClientTop) MOZ_FINAL                        \
+NS_IMETHOD GetClientTop(int32_t* aClientTop) MOZ_FINAL MOZ_OVERRIDE           \
 {                                                                             \
   *aClientTop = Element::ClientTop();                                         \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetClientLeft(int32_t* aClientLeft) MOZ_FINAL                      \
+NS_IMETHOD GetClientLeft(int32_t* aClientLeft) MOZ_FINAL MOZ_OVERRIDE         \
 {                                                                             \
   *aClientLeft = Element::ClientLeft();                                       \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetClientWidth(int32_t* aClientWidth) MOZ_FINAL                    \
+NS_IMETHOD GetClientWidth(int32_t* aClientWidth) MOZ_FINAL MOZ_OVERRIDE       \
 {                                                                             \
   *aClientWidth = Element::ClientWidth();                                     \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetClientHeight(int32_t* aClientHeight) MOZ_FINAL                  \
+NS_IMETHOD GetClientHeight(int32_t* aClientHeight) MOZ_FINAL MOZ_OVERRIDE     \
 {                                                                             \
   *aClientHeight = Element::ClientHeight();                                   \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetScrollLeftMax(int32_t* aScrollLeftMax) MOZ_FINAL                \
+NS_IMETHOD GetScrollLeftMax(int32_t* aScrollLeftMax) MOZ_FINAL MOZ_OVERRIDE   \
 {                                                                             \
   *aScrollLeftMax = Element::ScrollLeftMax();                                 \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD GetScrollTopMax(int32_t* aScrollTopMax) MOZ_FINAL                  \
+NS_IMETHOD GetScrollTopMax(int32_t* aScrollTopMax) MOZ_FINAL MOZ_OVERRIDE     \
 {                                                                             \
   *aScrollTopMax = Element::ScrollTopMax();                                   \
   return NS_OK;                                                               \
 }                                                                             \
 NS_IMETHOD MozMatchesSelector(const nsAString& selector,                      \
-                              bool* _retval) MOZ_FINAL                        \
+                              bool* _retval) MOZ_FINAL MOZ_OVERRIDE           \
 {                                                                             \
   mozilla::ErrorResult rv;                                                    \
   *_retval = Element::MozMatchesSelector(selector, rv);                       \
   return rv.ErrorCode();                                                      \
 }                                                                             \
-NS_IMETHOD SetCapture(bool retargetToElement) MOZ_FINAL                       \
+NS_IMETHOD SetCapture(bool retargetToElement) MOZ_FINAL MOZ_OVERRIDE          \
 {                                                                             \
   Element::SetCapture(retargetToElement);                                     \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD ReleaseCapture(void) MOZ_FINAL                                     \
+NS_IMETHOD ReleaseCapture(void) MOZ_FINAL MOZ_OVERRIDE                        \
 {                                                                             \
   Element::ReleaseCapture();                                                  \
   return NS_OK;                                                               \
 }                                                                             \
-NS_IMETHOD MozRequestFullScreen(void) MOZ_FINAL                               \
+NS_IMETHOD MozRequestFullScreen(void) MOZ_FINAL MOZ_OVERRIDE                  \
 {                                                                             \
-  Element::MozRequestFullScreen(mozilla::dom::RequestFullscreenOptions());    \
-  return NS_OK;                                                               \
+  mozilla::ErrorResult rv;                                                    \
+  Element::MozRequestFullScreen(nullptr, JS::UndefinedHandleValue, rv);       \
+  return rv.ErrorCode();                                                      \
 }                                                                             \
-NS_IMETHOD MozRequestPointerLock(void) MOZ_FINAL                              \
+NS_IMETHOD MozRequestPointerLock(void) MOZ_FINAL MOZ_OVERRIDE                 \
 {                                                                             \
   Element::MozRequestPointerLock();                                           \
   return NS_OK;                                                               \
 }                                                                             \
 using nsINode::QuerySelector;                                                 \
 NS_IMETHOD QuerySelector(const nsAString& aSelector,                          \
-                         nsIDOMElement **aReturn) MOZ_FINAL                   \
+                         nsIDOMElement **aReturn) MOZ_FINAL MOZ_OVERRIDE      \
 {                                                                             \
   return nsINode::QuerySelector(aSelector, aReturn);                          \
 }                                                                             \
 using nsINode::QuerySelectorAll;                                              \
 NS_IMETHOD QuerySelectorAll(const nsAString& aSelector,                       \
-                            nsIDOMNodeList **aReturn) MOZ_FINAL               \
+                            nsIDOMNodeList **aReturn) MOZ_FINAL MOZ_OVERRIDE  \
 {                                                                             \
   return nsINode::QuerySelectorAll(aSelector, aReturn);                       \
 }
 
 #endif // mozilla_dom_Element_h__
--- a/dom/base/EventSource.cpp
+++ b/dom/base/EventSource.cpp
@@ -495,17 +495,17 @@ public:
     : mEventSource(aEventsource)
   {
   }
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS(AsyncVerifyRedirectCallbackFwr)
 
   // nsIAsyncVerifyRedirectCallback implementation
-  NS_IMETHOD OnRedirectVerifyCallback(nsresult aResult)
+  NS_IMETHOD OnRedirectVerifyCallback(nsresult aResult) MOZ_OVERRIDE
   {
     nsresult rv = mEventSource->OnRedirectVerifyCallback(aResult);
     if (NS_FAILED(rv)) {
       mEventSource->mErrorLoadOnRedirect = true;
       mEventSource->DispatchFailConnection();
     }
 
     return NS_OK;
--- a/dom/base/File.cpp
+++ b/dom/base/File.cpp
@@ -1078,17 +1078,17 @@ class FileImplMemoryDataOwnerMemoryRepor
   : public nsIMemoryReporter
 {
   ~FileImplMemoryDataOwnerMemoryReporter() {}
 
 public:
   NS_DECL_THREADSAFE_ISUPPORTS
 
   NS_IMETHOD CollectReports(nsIMemoryReporterCallback *aCallback,
-                            nsISupports *aClosure, bool aAnonymize)
+                            nsISupports *aClosure, bool aAnonymize) MOZ_OVERRIDE
   {
     typedef FileImplMemory::DataOwner DataOwner;
 
     StaticMutexAutoLock lock(DataOwner::sDataOwnerMutex);
 
     if (!DataOwner::sDataOwners) {
       return NS_OK;
     }
--- a/dom/base/File.h
+++ b/dom/base/File.h
@@ -434,17 +434,17 @@ public:
     return false;
   }
 
   virtual bool IsDateUnknown() const MOZ_OVERRIDE
   {
     return mIsFile && mLastModificationDate == UINT64_MAX;
   }
 
-  virtual bool IsFile() const
+  virtual bool IsFile() const MOZ_OVERRIDE
   {
     return mIsFile;
   }
 
   virtual bool IsStoredFile() const
   {
     return false;
   }
@@ -455,23 +455,23 @@ public:
     return false;
   }
 
   virtual bool IsSnapshot() const
   {
     return false;
   }
 
-  virtual bool IsSizeUnknown() const
+  virtual bool IsSizeUnknown() const MOZ_OVERRIDE
   {
     return mLength == UINT64_MAX;
   }
 
-  virtual void Unlink() {}
-  virtual void Traverse(nsCycleCollectionTraversalCallback &aCb) {}
+  virtual void Unlink() MOZ_OVERRIDE {}
+  virtual void Traverse(nsCycleCollectionTraversalCallback &aCb) MOZ_OVERRIDE {}
 
 protected:
   virtual ~FileImplBase() {}
 
   indexedDB::FileInfo* GetFileInfo() const
   {
     NS_ASSERTION(IsStoredFile(), "Should only be called on stored files!");
     NS_ASSERTION(!mFileInfos.IsEmpty(), "Must have at least one file info!");
--- a/dom/base/FragmentOrElement.h
+++ b/dom/base/FragmentOrElement.h
@@ -94,17 +94,17 @@ public:
   {
   }
 
   // nsISupports
   NS_DECL_ISUPPORTS
 
   // nsIWeakReference
   NS_DECL_NSIWEAKREFERENCE
-  virtual size_t SizeOfOnlyThis(mozilla::MallocSizeOf aMallocSizeOf) const;
+  virtual size_t SizeOfOnlyThis(mozilla::MallocSizeOf aMallocSizeOf) const MOZ_OVERRIDE;
 
   void NoticeNodeDestruction()
   {
     mNode = nullptr;
   }
 
 private:
   ~nsNodeWeakReference();
--- a/dom/base/ImageEncoder.cpp
+++ b/dom/base/ImageEncoder.cpp
@@ -77,17 +77,17 @@ public:
     : mImgSize(0)
     , mType()
     , mImgData(nullptr)
     , mEncoderThread(aEncoderThread)
     , mEncodeCompleteCallback(aEncodeCompleteCallback)
     , mFailed(false)
   {}
 
-  NS_IMETHOD Run()
+  NS_IMETHOD Run() MOZ_OVERRIDE
   {
     nsresult rv = NS_OK;
     MOZ_ASSERT(NS_IsMainThread());
 
     if (!mFailed) {
       // The correct parentObject has to be set by the mEncodeCompleteCallback.
       nsRefPtr<File> blob =
         File::CreateMemoryFile(nullptr, mImgData, mImgSize, mType);
@@ -185,17 +185,17 @@ public:
     NS_ENSURE_TRUE(*aImgSize <= UINT32_MAX, NS_ERROR_FILE_TOO_BIG);
 
     rv = NS_ReadInputStreamToBuffer(stream, aImgData, *aImgSize);
     NS_ENSURE_SUCCESS(rv, rv);
 
     return rv;
   }
 
-  NS_IMETHOD Run()
+  NS_IMETHOD Run() MOZ_OVERRIDE
   {
     uint64_t imgSize;
     void* imgData = nullptr;
 
     nsresult rv = ProcessImageData(&imgSize, &imgData);
     if (NS_FAILED(rv)) {
       mEncodingCompleteEvent->SetFailed();
     } else {
--- a/dom/base/PerformanceResourceTiming.h
+++ b/dom/base/PerformanceResourceTiming.h
@@ -28,19 +28,19 @@ public:
       PerformanceEntry)
 
   PerformanceResourceTiming(nsPerformanceTiming* aPerformanceTiming,
                             nsPerformance* aPerformance);
 
   virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE;
 
 
-  virtual DOMHighResTimeStamp StartTime() const;
+  virtual DOMHighResTimeStamp StartTime() const MOZ_OVERRIDE;
 
-  virtual DOMHighResTimeStamp Duration() const
+  virtual DOMHighResTimeStamp Duration() const MOZ_OVERRIDE
   {
     return ResponseEnd() - StartTime();
   }
 
   void GetInitiatorType(nsAString& aInitiatorType) const
   {
     aInitiatorType = mInitiatorType;
   }
--- a/dom/base/WebSocket.cpp
+++ b/dom/base/WebSocket.cpp
@@ -1976,17 +1976,17 @@ public:
     if (aStatus >= Canceling) {
       mWebSocketImpl->mWorkerShuttingDown = true;
       mWebSocketImpl->CloseConnection(nsIWebSocketChannel::CLOSE_GOING_AWAY);
     }
 
     return true;
   }
 
-  bool Suspend(JSContext* aCx)
+  bool Suspend(JSContext* aCx) MOZ_OVERRIDE
   {
     mWebSocketImpl->mWorkerShuttingDown = true;
     mWebSocketImpl->CloseConnection(nsIWebSocketChannel::CLOSE_GOING_AWAY);
     return true;
   }
 
 private:
   WebSocketImpl* mWebSocketImpl;
--- a/dom/base/nsContentIterator.cpp
+++ b/dom/base/nsContentIterator.cpp
@@ -81,33 +81,33 @@ class nsContentIterator : public nsICont
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS(nsContentIterator)
 
   explicit nsContentIterator(bool aPre);
 
   // nsIContentIterator interface methods ------------------------------
 
-  virtual nsresult Init(nsINode* aRoot);
+  virtual nsresult Init(nsINode* aRoot) MOZ_OVERRIDE;
 
-  virtual nsresult Init(nsIDOMRange* aRange);
+  virtual nsresult Init(nsIDOMRange* aRange) MOZ_OVERRIDE;
 
-  virtual void First();
+  virtual void First() MOZ_OVERRIDE;
 
-  virtual void Last();
+  virtual void Last() MOZ_OVERRIDE;
 
-  virtual void Next();
+  virtual void Next() MOZ_OVERRIDE;
 
-  virtual void Prev();
+  virtual void Prev() MOZ_OVERRIDE;
 
-  virtual nsINode* GetCurrentNode();
+  virtual nsINode* GetCurrentNode() MOZ_OVERRIDE;
 
-  virtual bool IsDone();
+  virtual bool IsDone() MOZ_OVERRIDE;
 
-  virtual nsresult PositionAt(nsINode* aCurNode);
+  virtual nsresult PositionAt(nsINode* aCurNode) MOZ_OVERRIDE;
 
 protected:
   virtual ~nsContentIterator();
 
   // Recursively get the deepest first/last child of aRoot.  This will return
   // aRoot itself if it has no children.
   nsINode* GetDeepFirstChild(nsINode* aRoot,
                              nsTArray<int32_t>* aIndexes = nullptr);
@@ -1108,31 +1108,31 @@ class nsContentSubtreeIterator : public 
 public:
   nsContentSubtreeIterator() : nsContentIterator(false) {}
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsContentSubtreeIterator, nsContentIterator)
 
   // nsContentIterator overrides ------------------------------
 
-  virtual nsresult Init(nsINode* aRoot);
+  virtual nsresult Init(nsINode* aRoot) MOZ_OVERRIDE;
 
-  virtual nsresult Init(nsIDOMRange* aRange);
+  virtual nsresult Init(nsIDOMRange* aRange) MOZ_OVERRIDE;
 
-  virtual void Next();
+  virtual void Next() MOZ_OVERRIDE;
 
-  virtual void Prev();
+  virtual void Prev() MOZ_OVERRIDE;
 
-  virtual nsresult PositionAt(nsINode* aCurNode);
+  virtual nsresult PositionAt(nsINode* aCurNode) MOZ_OVERRIDE;
 
   // Must override these because we don't do PositionAt
-  virtual void First();
+  virtual void First() MOZ_OVERRIDE;
 
   // Must override these because we don't do PositionAt
-  virtual void Last();
+  virtual void Last() MOZ_OVERRIDE;
 
 protected:
   virtual ~nsContentSubtreeIterator() {}
 
   // Returns the highest inclusive ancestor of aNode that's in the range
   // (possibly aNode itself).  Returns null if aNode is null, or is not itself
   // in the range.  A node is in the range if (node, 0) comes strictly after
   // the range endpoint, and (node, node.length) comes strictly before it, so
--- a/dom/base/nsContentUtils.cpp
+++ b/dom/base/nsContentUtils.cpp
@@ -334,17 +334,17 @@ class DOMEventListenerManagersHashReport
   MOZ_DEFINE_MALLOC_SIZE_OF(MallocSizeOf)
 
   ~DOMEventListenerManagersHashReporter() {}
 
 public:
   NS_DECL_ISUPPORTS
 
   NS_IMETHOD CollectReports(nsIHandleReportCallback* aHandleReport,
-                            nsISupports* aData, bool aAnonymize)
+                            nsISupports* aData, bool aAnonymize) MOZ_OVERRIDE
   {
     // We don't measure the |EventListenerManager| objects pointed to by the
     // entries because those references are non-owning.
     int64_t amount = sEventListenerManagersHash.ops
                    ? PL_DHashTableSizeOfExcludingThis(
                        &sEventListenerManagersHash, nullptr, MallocSizeOf)
                    : 0;
 
@@ -406,17 +406,17 @@ class SameOriginChecker MOZ_FINAL : publ
   NS_DECL_NSIINTERFACEREQUESTOR
 };
 
 class CharsetDetectionObserver MOZ_FINAL : public nsICharsetDetectionObserver
 {
 public:
   NS_DECL_ISUPPORTS
 
-  NS_IMETHOD Notify(const char *aCharset, nsDetectionConfident aConf)
+  NS_IMETHOD Notify(const char *aCharset, nsDetectionConfident aConf) MOZ_OVERRIDE
   {
     mCharset = aCharset;
     return NS_OK;
   }
 
   const nsACString& GetResult() const
   {
     return mCharset;
--- a/dom/base/nsDOMClassInfo.h
+++ b/dom/base/nsDOMClassInfo.h
@@ -280,17 +280,17 @@ public:
   NS_IMETHOD Call(nsIXPConnectWrappedNative *wrapper, JSContext *cx,
                   JSObject *obj, const JS::CallArgs &args, bool *_retval) MOZ_OVERRIDE;
 
   NS_IMETHOD Construct(nsIXPConnectWrappedNative *wrapper, JSContext *cx,
                        JSObject *obj, const JS::CallArgs &args, bool *_retval) MOZ_OVERRIDE;
 
   NS_IMETHOD HasInstance(nsIXPConnectWrappedNative *wrapper, JSContext *cx,
                          JSObject *obj, JS::Handle<JS::Value> val, bool *bp,
-                         bool *_retval);
+                         bool *_retval) MOZ_OVERRIDE;
 
   static nsIClassInfo *doCreate(nsDOMClassInfoData* aData)
   {
     return new nsDOMConstructorSH(aData);
   }
 };
 
 class nsNonDOMObjectSH : public nsDOMGenericSH
--- a/dom/base/nsDocument.cpp
+++ b/dom/base/nsDocument.cpp
@@ -9692,17 +9692,17 @@ namespace {
 /**
  * Stub for LoadSheet(), since all we want is to get the sheet into
  * the CSSLoader's style cache
  */
 class StubCSSLoaderObserver MOZ_FINAL : public nsICSSLoaderObserver {
   ~StubCSSLoaderObserver() {}
 public:
   NS_IMETHOD
-  StyleSheetLoaded(CSSStyleSheet*, bool, nsresult)
+  StyleSheetLoaded(CSSStyleSheet*, bool, nsresult) MOZ_OVERRIDE
   {
     return NS_OK;
   }
   NS_DECL_ISUPPORTS
 };
 NS_IMPL_ISUPPORTS(StubCSSLoaderObserver, nsICSSLoaderObserver)
 
 }
@@ -11832,17 +11832,17 @@ public:
   nsPointerLockPermissionRequest(Element* aElement, bool aUserInputOrChromeCaller)
   : mElement(do_GetWeakReference(aElement)),
     mDocument(do_GetWeakReference(aElement->OwnerDoc())),
     mUserInputOrChromeCaller(aUserInputOrChromeCaller) {}
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSICONTENTPERMISSIONREQUEST
 
-  NS_IMETHOD Run()
+  NS_IMETHOD Run() MOZ_OVERRIDE
   {
     nsCOMPtr<Element> e = do_QueryReferent(mElement);
     nsCOMPtr<nsIDocument> d = do_QueryReferent(mDocument);
     if (!e || !d || gPendingPointerLockRequest != this ||
         e->GetUncomposedDoc() != d) {
       Handled();
       DispatchPointerLockError(d);
       return NS_OK;
--- a/dom/base/nsDocument.h
+++ b/dom/base/nsDocument.h
@@ -986,75 +986,75 @@ public:
   NS_DECL_NSIDOMXPATHEVALUATOR
 
   virtual nsresult Init();
 
   virtual nsresult CreateElem(const nsAString& aName, nsIAtom *aPrefix,
                               int32_t aNamespaceID,
                               nsIContent **aResult) MOZ_OVERRIDE;
 
-  virtual void Sanitize();
+  virtual void Sanitize() MOZ_OVERRIDE;
 
   virtual void EnumerateSubDocuments(nsSubDocEnumFunc aCallback,
-                                                 void *aData);
+                                                 void *aData) MOZ_OVERRIDE;
 
-  virtual bool CanSavePresentation(nsIRequest *aNewRequest);
-  virtual void Destroy();
-  virtual void RemovedFromDocShell();
-  virtual already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const;
+  virtual bool CanSavePresentation(nsIRequest *aNewRequest) MOZ_OVERRIDE;
+  virtual void Destroy() MOZ_OVERRIDE;
+  virtual void RemovedFromDocShell() MOZ_OVERRIDE;
+  virtual already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const MOZ_OVERRIDE;
 
-  virtual void BlockOnload();
-  virtual void UnblockOnload(bool aFireSync);
+  virtual void BlockOnload() MOZ_OVERRIDE;
+  virtual void UnblockOnload(bool aFireSync) MOZ_OVERRIDE;
 
-  virtual void AddStyleRelevantLink(mozilla::dom::Link* aLink);
-  virtual void ForgetLink(mozilla::dom::Link* aLink);
+  virtual void AddStyleRelevantLink(mozilla::dom::Link* aLink) MOZ_OVERRIDE;
+  virtual void ForgetLink(mozilla::dom::Link* aLink) MOZ_OVERRIDE;
 
-  void ClearBoxObjectFor(nsIContent* aContent);
+  virtual void ClearBoxObjectFor(nsIContent* aContent) MOZ_OVERRIDE;
 
   virtual already_AddRefed<mozilla::dom::BoxObject>
   GetBoxObjectFor(mozilla::dom::Element* aElement,
                   mozilla::ErrorResult& aRv) MOZ_OVERRIDE;
 
   virtual Element*
     GetAnonymousElementByAttribute(nsIContent* aElement,
                                    nsIAtom* aAttrName,
-                                   const nsAString& aAttrValue) const;
+                                   const nsAString& aAttrValue) const MOZ_OVERRIDE;
 
   virtual Element* ElementFromPointHelper(float aX, float aY,
                                                       bool aIgnoreRootScrollFrame,
-                                                      bool aFlushLayout);
+                                                      bool aFlushLayout) MOZ_OVERRIDE;
 
   virtual nsresult NodesFromRectHelper(float aX, float aY,
                                                    float aTopSize, float aRightSize,
                                                    float aBottomSize, float aLeftSize,
                                                    bool aIgnoreRootScrollFrame,
                                                    bool aFlushLayout,
-                                                   nsIDOMNodeList** aReturn);
+                                                   nsIDOMNodeList** aReturn) MOZ_OVERRIDE;
 
-  virtual void FlushSkinBindings();
+  virtual void FlushSkinBindings() MOZ_OVERRIDE;
 
-  virtual nsresult InitializeFrameLoader(nsFrameLoader* aLoader);
-  virtual nsresult FinalizeFrameLoader(nsFrameLoader* aLoader);
-  virtual void TryCancelFrameLoaderInitialization(nsIDocShell* aShell);
-  virtual bool FrameLoaderScheduledToBeFinalized(nsIDocShell* aShell);
+  virtual nsresult InitializeFrameLoader(nsFrameLoader* aLoader) MOZ_OVERRIDE;
+  virtual nsresult FinalizeFrameLoader(nsFrameLoader* aLoader) MOZ_OVERRIDE;
+  virtual void TryCancelFrameLoaderInitialization(nsIDocShell* aShell) MOZ_OVERRIDE;
+  virtual bool FrameLoaderScheduledToBeFinalized(nsIDocShell* aShell) MOZ_OVERRIDE;
   virtual nsIDocument*
     RequestExternalResource(nsIURI* aURI,
                             nsINode* aRequestingNode,
-                            ExternalResourceLoad** aPendingLoad);
+                            ExternalResourceLoad** aPendingLoad) MOZ_OVERRIDE;
   virtual void
-    EnumerateExternalResources(nsSubDocEnumFunc aCallback, void* aData);
+    EnumerateExternalResources(nsSubDocEnumFunc aCallback, void* aData) MOZ_OVERRIDE;
 
   nsTArray<nsCString> mHostObjectURIs;
 
   // Returns our (lazily-initialized) animation controller.
   // If HasAnimationController is true, this is guaranteed to return non-null.
   nsSMILAnimationController* GetAnimationController() MOZ_OVERRIDE;
 
   virtual mozilla::PendingPlayerTracker*
-  GetPendingPlayerTracker() MOZ_FINAL
+  GetPendingPlayerTracker() MOZ_FINAL MOZ_OVERRIDE
   {
     return mPendingPlayerTracker;
   }
 
   virtual mozilla::PendingPlayerTracker*
   GetOrCreatePendingPlayerTracker() MOZ_OVERRIDE;
 
   void SetImagesNeedAnimating(bool aAnimating) MOZ_OVERRIDE;
@@ -1130,19 +1130,19 @@ public:
 
   virtual Element *GetElementById(const nsAString& aElementId) MOZ_OVERRIDE;
   virtual const nsSmallVoidArray* GetAllElementsForId(const nsAString& aElementId) const MOZ_OVERRIDE;
 
   virtual Element *LookupImageElement(const nsAString& aElementId) MOZ_OVERRIDE;
   virtual void MozSetImageElement(const nsAString& aImageElementId,
                                   Element* aElement) MOZ_OVERRIDE;
 
-  virtual nsresult AddImage(imgIRequest* aImage);
-  virtual nsresult RemoveImage(imgIRequest* aImage, uint32_t aFlags);
-  virtual nsresult SetImageLockingState(bool aLocked);
+  virtual nsresult AddImage(imgIRequest* aImage) MOZ_OVERRIDE;
+  virtual nsresult RemoveImage(imgIRequest* aImage, uint32_t aFlags) MOZ_OVERRIDE;
+  virtual nsresult SetImageLockingState(bool aLocked) MOZ_OVERRIDE;
 
   // AddPlugin adds a plugin-related element to mPlugins when the element is
   // added to the tree.
   virtual nsresult AddPlugin(nsIObjectLoadingContent* aPlugin) MOZ_OVERRIDE;
   // RemovePlugin removes a plugin-related element to mPlugins when the
   // element is removed from the tree.
   virtual void RemovePlugin(nsIObjectLoadingContent* aPlugin) MOZ_OVERRIDE;
   // GetPlugins returns the plugin-related elements from
@@ -1307,35 +1307,35 @@ public:
                                                   const nsAString& aTypeExtension,
                                                   mozilla::ErrorResult& rv) MOZ_OVERRIDE;
   virtual already_AddRefed<Element> CreateElementNS(const nsAString& aNamespaceURI,
                                                     const nsAString& aQualifiedName,
                                                     const nsAString& aTypeExtension,
                                                     mozilla::ErrorResult& rv) MOZ_OVERRIDE;
   virtual void UseRegistryFromDocument(nsIDocument* aDocument) MOZ_OVERRIDE;
 
-  virtual nsIDocument* MasterDocument()
+  virtual nsIDocument* MasterDocument() MOZ_OVERRIDE
   {
     return mMasterDocument ? mMasterDocument.get()
                            : this;
   }
 
-  virtual void SetMasterDocument(nsIDocument* master)
+  virtual void SetMasterDocument(nsIDocument* master) MOZ_OVERRIDE
   {
     MOZ_ASSERT(master);
     mMasterDocument = master;
     UseRegistryFromDocument(mMasterDocument);
   }
 
-  virtual bool IsMasterDocument()
+  virtual bool IsMasterDocument() MOZ_OVERRIDE
   {
     return !mMasterDocument;
   }
 
-  virtual mozilla::dom::ImportManager* ImportManager()
+  virtual mozilla::dom::ImportManager* ImportManager() MOZ_OVERRIDE
   {
     if (mImportManager) {
       MOZ_ASSERT(!mMasterDocument, "Only the master document has ImportManager set");
       return mImportManager.get();
     }
 
     if (mMasterDocument) {
       return mMasterDocument->ImportManager();
@@ -1344,32 +1344,32 @@ public:
     // ImportManager is created lazily.
     // If the manager is not yet set it has to be the
     // master document and this is the first import in it.
     // Let's create a new manager.
     mImportManager = new mozilla::dom::ImportManager();
     return mImportManager.get();
   }
 
-  virtual bool HasSubImportLink(nsINode* aLink)
+  virtual bool HasSubImportLink(nsINode* aLink) MOZ_OVERRIDE
   {
     return mSubImportLinks.Contains(aLink);
   }
 
-  virtual uint32_t IndexOfSubImportLink(nsINode* aLink)
+  virtual uint32_t IndexOfSubImportLink(nsINode* aLink) MOZ_OVERRIDE
   {
     return mSubImportLinks.IndexOf(aLink);
   }
 
-  virtual void AddSubImportLink(nsINode* aLink)
+  virtual void AddSubImportLink(nsINode* aLink) MOZ_OVERRIDE
   {
     mSubImportLinks.AppendElement(aLink);
   }
 
-  virtual nsINode* GetSubImportLink(uint32_t aIdx)
+  virtual nsINode* GetSubImportLink(uint32_t aIdx) MOZ_OVERRIDE
   {
     return aIdx < mSubImportLinks.Length() ? mSubImportLinks[aIdx].get()
                                            : nullptr;
   }
 
   virtual void UnblockDOMContentLoaded() MOZ_OVERRIDE;
 
 protected:
@@ -1557,17 +1557,17 @@ private:
 public:
   static void ProcessBaseElementQueue();
 
   // Enqueue created callback or register upgrade candidate for
   // newly created custom elements, possibly extending an existing type.
   // ex. <x-button>, <button is="x-button> (type extension)
   virtual void SetupCustomElement(Element* aElement,
                                   uint32_t aNamespaceID,
-                                  const nsAString* aTypeExtension);
+                                  const nsAString* aTypeExtension) MOZ_OVERRIDE;
 
   static bool IsWebComponentsEnabled(JSContext* aCx, JSObject* aObject);
 
   // The "registry" from the web components spec.
   nsRefPtr<mozilla::dom::Registry> mRegistry;
 
   nsRefPtr<mozilla::EventListenerManager> mListenerManager;
   nsRefPtr<mozilla::dom::StyleSheetList> mDOMStyleSheets;
--- a/dom/base/nsFrameMessageManager.cpp
+++ b/dom/base/nsFrameMessageManager.cpp
@@ -1850,17 +1850,17 @@ public:
     }
     return true;
   }
 
   virtual bool DoSendAsyncMessage(JSContext* aCx,
                                   const nsAString& aMessage,
                                   const mozilla::dom::StructuredCloneData& aData,
                                   JS::Handle<JSObject *> aCpows,
-                                  nsIPrincipal* aPrincipal)
+                                  nsIPrincipal* aPrincipal) MOZ_OVERRIDE
   {
     if (!nsFrameMessageManager::sPendingSameProcessAsyncMessages) {
       nsFrameMessageManager::sPendingSameProcessAsyncMessages = new nsTArray<nsCOMPtr<nsIRunnable> >;
     }
     nsCOMPtr<nsIRunnable> ev =
       new nsAsyncMessageToSameProcessParent(aCx, aMessage, aData, aCpows, aPrincipal);
     nsFrameMessageManager::sPendingSameProcessAsyncMessages->AppendElement(ev);
     NS_DispatchToCurrentThread(ev);
--- a/dom/base/nsFrameMessageManager.h
+++ b/dom/base/nsFrameMessageManager.h
@@ -422,16 +422,16 @@ class nsScriptCacheCleaner MOZ_FINAL : p
   {
     nsCOMPtr<nsIObserverService> obsSvc = mozilla::services::GetObserverService();
     if (obsSvc)
       obsSvc->AddObserver(this, "xpcom-shutdown", false);
   }
 
   NS_IMETHODIMP Observe(nsISupports *aSubject,
                         const char *aTopic,
-                        const char16_t *aData)
+                        const char16_t *aData) MOZ_OVERRIDE
   {
     nsFrameScriptExecutor::Shutdown();
     return NS_OK;
   }
 };
 
 #endif
--- a/dom/base/nsGenConImageContent.cpp
+++ b/dom/base/nsGenConImageContent.cpp
@@ -36,21 +36,21 @@ public:
   {
     // No need to notify, since we have no frame.
     return UseAsPrimaryRequest(aImageRequest, false, eImageLoadType_Normal);
   }
 
   // nsIContent overrides
   virtual nsresult BindToTree(nsIDocument* aDocument, nsIContent* aParent,
                               nsIContent* aBindingParent,
-                              bool aCompileEventHandlers);
-  virtual void UnbindFromTree(bool aDeep, bool aNullParent);
-  virtual EventStates IntrinsicState() const;
+                              bool aCompileEventHandlers) MOZ_OVERRIDE;
+  virtual void UnbindFromTree(bool aDeep, bool aNullParent) MOZ_OVERRIDE;
+  virtual EventStates IntrinsicState() const MOZ_OVERRIDE;
 
-  virtual nsresult PreHandleEvent(EventChainPreVisitor& aVisitor)
+  virtual nsresult PreHandleEvent(EventChainPreVisitor& aVisitor) MOZ_OVERRIDE
   {
     MOZ_ASSERT(IsInNativeAnonymousSubtree());
     if (aVisitor.mEvent->message == NS_LOAD ||
         aVisitor.mEvent->message == NS_LOAD_ERROR) {
       // Don't propagate the events to the parent.
       return NS_OK;
     }
     return nsXMLElement::PreHandleEvent(aVisitor);
--- a/dom/base/nsGenericDOMDataNode.h
+++ b/dom/base/nsGenericDOMDataNode.h
@@ -223,17 +223,17 @@ public:
   void ToCString(nsAString& aBuf, int32_t aOffset, int32_t aLen) const;
 #endif
 
   NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS(nsGenericDOMDataNode)
 
 protected:
   virtual ~nsGenericDOMDataNode();
 
-  virtual mozilla::dom::Element* GetNameSpaceElement()
+  virtual mozilla::dom::Element* GetNameSpaceElement() MOZ_OVERRIDE
   {
     nsINode *parent = GetParentNode();
 
     return parent && parent->IsElement() ? parent->AsElement() : nullptr;
   }
 
   /**
    * There are a set of DOM- and scripting-specific instance variables
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -475,24 +475,24 @@ static const char sPopStatePrefStr[] = "
  * on nsGlobalWindow, where any script could see it.
  */
 class nsGlobalWindowObserver MOZ_FINAL : public nsIObserver,
                                          public nsIInterfaceRequestor
 {
 public:
   explicit nsGlobalWindowObserver(nsGlobalWindow* aWindow) : mWindow(aWindow) {}
   NS_DECL_ISUPPORTS
-  NS_IMETHOD Observe(nsISupports* aSubject, const char* aTopic, const char16_t* aData)
+  NS_IMETHOD Observe(nsISupports* aSubject, const char* aTopic, const char16_t* aData) MOZ_OVERRIDE
   {
     if (!mWindow)
       return NS_OK;
     return mWindow->Observe(aSubject, aTopic, aData);
   }
   void Forget() { mWindow = nullptr; }
-  NS_IMETHODIMP GetInterface(const nsIID& aIID, void** aResult)
+  NS_IMETHODIMP GetInterface(const nsIID& aIID, void** aResult) MOZ_OVERRIDE
   {
     if (mWindow && aIID.Equals(NS_GET_IID(nsIDOMWindow)) && mWindow) {
       return mWindow->QueryInterface(aIID, aResult);
     }
     return NS_NOINTERFACE;
   }
 
 private:
@@ -12433,17 +12433,17 @@ nsGlobalWindow::RunTimeout(nsTimeout *aT
   // portion of the list that we are about to process now and those
   // timeouts that will be processed in a future call to
   // win_run_timeout(). This dummy timeout serves as the head of the
   // list for any timeouts inserted as a result of running a timeout.
   nsRefPtr<nsTimeout> dummy_timeout = new nsTimeout();
   dummy_timeout->mFiringDepth = firingDepth;
   dummy_timeout->mWhen = now;
   last_expired_timeout->setNext(dummy_timeout);
-  dummy_timeout->AddRef();
+  nsRefPtr<nsTimeout> timeoutExtraRef(dummy_timeout);
 
   last_insertion_point = mTimeoutInsertionPoint;
   // If we ever start setting mTimeoutInsertionPoint to a non-dummy timeout,
   // the logic in ResetTimersForNonBackgroundWindow will need to change.
   mTimeoutInsertionPoint = dummy_timeout;
 
   Telemetry::AutoCounter<Telemetry::DOM_TIMERS_FIRED_PER_NATIVE_TIMEOUT> timeoutsRan;
 
@@ -12484,16 +12484,17 @@ nsGlobalWindow::RunTimeout(nsTimeout *aT
     bool timeout_was_cleared = RunTimeoutHandler(timeout, scx);
 
     if (timeout_was_cleared) {
       // The running timeout's window was cleared, this means that
       // ClearAllTimeouts() was called from a *nested* call, possibly
       // through a timeout that fired while a modal (to this window)
       // dialog was open or through other non-obvious paths.
       MOZ_ASSERT(dummy_timeout->HasRefCntOne(), "dummy_timeout may leak");
+      unused << timeoutExtraRef.forget().take();
 
       mTimeoutInsertionPoint = last_insertion_point;
 
       return;
     }
 
     // If we have a regular interval timer, we re-schedule the
     // timeout, accounting for clock drift.
@@ -12512,17 +12513,17 @@ nsGlobalWindow::RunTimeout(nsTimeout *aT
     }
 
     // Release the timeout struct since it's possibly out of the list
     timeout->Release();
   }
 
   // Take the dummy timeout off the head of the list
   dummy_timeout->remove();
-  dummy_timeout->Release();
+  timeoutExtraRef = nullptr;
   MOZ_ASSERT(dummy_timeout->HasRefCntOne(), "dummy_timeout may leak");
 
   mTimeoutInsertionPoint = last_insertion_point;
 }
 
 void
 nsGlobalWindow::ClearTimeoutOrInterval(int32_t aTimerID, ErrorResult& aError)
 {
--- a/dom/base/nsGlobalWindow.h
+++ b/dom/base/nsGlobalWindow.h
@@ -353,38 +353,38 @@ public:
 
   // nsWrapperCache
   virtual JSObject *WrapObject(JSContext *cx) MOZ_OVERRIDE
   {
     return IsInnerWindow() || EnsureInnerWindow() ? GetWrapper() : nullptr;
   }
 
   // nsIGlobalJSObjectHolder
-  virtual JSObject *GetGlobalJSObject();
+  virtual JSObject* GetGlobalJSObject() MOZ_OVERRIDE;
 
   // nsIScriptGlobalObject
   JSObject *FastGetGlobalJSObject() const
   {
     return GetWrapperPreserveColor();
   }
 
   void TraceGlobalJSObject(JSTracer* aTrc);
 
-  virtual nsresult EnsureScriptEnvironment();
+  virtual nsresult EnsureScriptEnvironment() MOZ_OVERRIDE;
 
-  virtual nsIScriptContext *GetScriptContext();
+  virtual nsIScriptContext *GetScriptContext() MOZ_OVERRIDE;
 
   void PoisonOuterWindowProxy(JSObject *aObject);
 
-  virtual bool IsBlackForCC(bool aTracingNeeded = true);
+  virtual bool IsBlackForCC(bool aTracingNeeded = true) MOZ_OVERRIDE;
 
   static JSObject* OuterObject(JSContext* aCx, JS::Handle<JSObject*> aObj);
 
   // nsIScriptObjectPrincipal
-  virtual nsIPrincipal* GetPrincipal();
+  virtual nsIPrincipal* GetPrincipal() MOZ_OVERRIDE;
 
   // nsIDOMWindow
   NS_DECL_NSIDOMWINDOW
 
   // nsIDOMJSWindow
   NS_DECL_NSIDOMJSWINDOW
 
   // nsIDOMEventTarget
@@ -407,86 +407,86 @@ public:
     if (IsOuterWindow()) {
       return this;
     }
 
     return GetOuterFromCurrentInner(this);
   }
 
   // nsPIDOMWindow
-  virtual nsPIDOMWindow* GetPrivateRoot();
+  virtual nsPIDOMWindow* GetPrivateRoot() MOZ_OVERRIDE;
 
   // Outer windows only.
-  virtual void ActivateOrDeactivate(bool aActivate);
-  virtual void SetActive(bool aActive);
-  virtual void SetIsBackground(bool aIsBackground);
-  virtual void SetChromeEventHandler(mozilla::dom::EventTarget* aChromeEventHandler);
+  virtual void ActivateOrDeactivate(bool aActivate) MOZ_OVERRIDE;
+  virtual void SetActive(bool aActive) MOZ_OVERRIDE;
+  virtual void SetIsBackground(bool aIsBackground) MOZ_OVERRIDE;
+  virtual void SetChromeEventHandler(mozilla::dom::EventTarget* aChromeEventHandler) MOZ_OVERRIDE;
 
   // Outer windows only.
-  virtual void SetInitialPrincipalToSubject();
+  virtual void SetInitialPrincipalToSubject() MOZ_OVERRIDE;
 
-  virtual PopupControlState PushPopupControlState(PopupControlState state, bool aForce) const;
-  virtual void PopPopupControlState(PopupControlState state) const;
-  virtual PopupControlState GetPopupControlState() const;
+  virtual PopupControlState PushPopupControlState(PopupControlState state, bool aForce) const MOZ_OVERRIDE;
+  virtual void PopPopupControlState(PopupControlState state) const MOZ_OVERRIDE;
+  virtual PopupControlState GetPopupControlState() const MOZ_OVERRIDE;
 
-  virtual already_AddRefed<nsISupports> SaveWindowState();
-  virtual nsresult RestoreWindowState(nsISupports *aState);
+  virtual already_AddRefed<nsISupports> SaveWindowState() MOZ_OVERRIDE;
+  virtual nsresult RestoreWindowState(nsISupports *aState) MOZ_OVERRIDE;
   virtual void SuspendTimeouts(uint32_t aIncrease = 1,
-                                           bool aFreezeChildren = true);
-  virtual nsresult ResumeTimeouts(bool aThawChildren = true);
-  virtual uint32_t TimeoutSuspendCount();
-  virtual nsresult FireDelayedDOMEvents();
-  virtual bool IsFrozen() const
+                               bool aFreezeChildren = true) MOZ_OVERRIDE;
+  virtual nsresult ResumeTimeouts(bool aThawChildren = true) MOZ_OVERRIDE;
+  virtual uint32_t TimeoutSuspendCount() MOZ_OVERRIDE;
+  virtual nsresult FireDelayedDOMEvents() MOZ_OVERRIDE;
+  virtual bool IsFrozen() const MOZ_OVERRIDE
   {
     return mIsFrozen;
   }
-  virtual bool IsRunningTimeout() { return mTimeoutFiringDepth > 0; }
+  virtual bool IsRunningTimeout() MOZ_OVERRIDE { return mTimeoutFiringDepth > 0; }
 
   // Outer windows only.
-  virtual bool WouldReuseInnerWindow(nsIDocument* aNewDocument);
+  virtual bool WouldReuseInnerWindow(nsIDocument* aNewDocument) MOZ_OVERRIDE;
 
-  virtual void SetDocShell(nsIDocShell* aDocShell);
-  virtual void DetachFromDocShell();
+  virtual void SetDocShell(nsIDocShell* aDocShell) MOZ_OVERRIDE;
+  virtual void DetachFromDocShell() MOZ_OVERRIDE;
   virtual nsresult SetNewDocument(nsIDocument *aDocument,
-                                              nsISupports *aState,
-                                              bool aForceReuseInnerWindow);
+                                  nsISupports *aState,
+                                  bool aForceReuseInnerWindow) MOZ_OVERRIDE;
 
   // Outer windows only.
   void DispatchDOMWindowCreated();
 
   virtual void SetOpenerWindow(nsIDOMWindow* aOpener,
-                                           bool aOriginalOpener);
+                               bool aOriginalOpener) MOZ_OVERRIDE;
 
   // Outer windows only.
-  virtual void EnsureSizeUpToDate();
+  virtual void EnsureSizeUpToDate() MOZ_OVERRIDE;
 
-  virtual void EnterModalState();
-  virtual void LeaveModalState();
+  virtual void EnterModalState() MOZ_OVERRIDE;
+  virtual void LeaveModalState() MOZ_OVERRIDE;
 
   // Outer windows only.
-  virtual bool CanClose();
-  virtual void ForceClose();
+  virtual bool CanClose() MOZ_OVERRIDE;
+  virtual void ForceClose() MOZ_OVERRIDE;
 
-  virtual void MaybeUpdateTouchState();
-  virtual void UpdateTouchState();
+  virtual void MaybeUpdateTouchState() MOZ_OVERRIDE;
+  virtual void UpdateTouchState() MOZ_OVERRIDE;
 
   // Outer windows only.
-  virtual bool DispatchCustomEvent(const nsAString& aEventName);
+  virtual bool DispatchCustomEvent(const nsAString& aEventName) MOZ_OVERRIDE;
   bool DispatchResizeEvent(const mozilla::CSSIntSize& aSize);
 
   // Inner windows only.
-  virtual void RefreshCompartmentPrincipal();
+  virtual void RefreshCompartmentPrincipal() MOZ_OVERRIDE;
 
   // Outer windows only.
   virtual nsresult SetFullScreenInternal(bool aIsFullScreen, bool aRequireTrust,
-                                         mozilla::gfx::VRHMDInfo *aHMD = nullptr);
+                                         mozilla::gfx::VRHMDInfo *aHMD = nullptr) MOZ_OVERRIDE;
   bool FullScreen() const;
 
   // Inner windows only.
-  virtual void SetHasGamepadEventListener(bool aHasGamepad = true);
+  virtual void SetHasGamepadEventListener(bool aHasGamepad = true) MOZ_OVERRIDE;
 
   // nsIInterfaceRequestor
   NS_DECL_NSIINTERFACEREQUESTOR
 
   // WebIDL interface.
   already_AddRefed<nsIDOMWindow> IndexedGetter(uint32_t aIndex, bool& aFound);
 
   void GetSupportedNames(nsTArray<nsString>& aNames);
@@ -627,58 +627,58 @@ public:
 
 #ifdef DEBUG
   // Call Unlink on this window. This may cause bad things to happen, so use
   // with caution.
   void RiskyUnlink();
 #endif
 
   virtual JSObject*
-    GetCachedXBLPrototypeHandler(nsXBLPrototypeHandler* aKey);
+    GetCachedXBLPrototypeHandler(nsXBLPrototypeHandler* aKey) MOZ_OVERRIDE;
 
   virtual void
     CacheXBLPrototypeHandler(nsXBLPrototypeHandler* aKey,
-                             JS::Handle<JSObject*> aHandler);
+                             JS::Handle<JSObject*> aHandler) MOZ_OVERRIDE;
 
-  virtual bool TakeFocus(bool aFocus, uint32_t aFocusMethod);
-  virtual void SetReadyForFocus();
-  virtual void PageHidden();
-  virtual nsresult DispatchAsyncHashchange(nsIURI *aOldURI, nsIURI *aNewURI);
-  virtual nsresult DispatchSyncPopState();
+  virtual bool TakeFocus(bool aFocus, uint32_t aFocusMethod) MOZ_OVERRIDE;
+  virtual void SetReadyForFocus() MOZ_OVERRIDE;
+  virtual void PageHidden() MOZ_OVERRIDE;
+  virtual nsresult DispatchAsyncHashchange(nsIURI *aOldURI, nsIURI *aNewURI) MOZ_OVERRIDE;
+  virtual nsresult DispatchSyncPopState() MOZ_OVERRIDE;
 
   // Inner windows only.
-  virtual void EnableDeviceSensor(uint32_t aType);
-  virtual void DisableDeviceSensor(uint32_t aType);
+  virtual void EnableDeviceSensor(uint32_t aType) MOZ_OVERRIDE;
+  virtual void DisableDeviceSensor(uint32_t aType) MOZ_OVERRIDE;
 
-  virtual void EnableTimeChangeNotifications();
-  virtual void DisableTimeChangeNotifications();
+  virtual void EnableTimeChangeNotifications() MOZ_OVERRIDE;
+  virtual void DisableTimeChangeNotifications() MOZ_OVERRIDE;
 
 #ifdef MOZ_B2G
   // Inner windows only.
-  virtual void EnableNetworkEvent(uint32_t aType);
-  virtual void DisableNetworkEvent(uint32_t aType);
+  virtual void EnableNetworkEvent(uint32_t aType) MOZ_OVERRIDE;
+  virtual void DisableNetworkEvent(uint32_t aType) MOZ_OVERRIDE;
 #endif // MOZ_B2G
 
-  virtual nsresult SetArguments(nsIArray *aArguments);
+  virtual nsresult SetArguments(nsIArray* aArguments) MOZ_OVERRIDE;
 
   void MaybeForgiveSpamCount();
   bool IsClosedOrClosing() {
     return (mIsClosed ||
             mInClose ||
             mHavePendingClose ||
             mCleanedUp);
   }
 
   virtual void
   FirePopupBlockedEvent(nsIDocument* aDoc,
                         nsIURI* aPopupURI,
                         const nsAString& aPopupWindowName,
                         const nsAString& aPopupWindowFeatures) MOZ_OVERRIDE;
 
-  virtual uint32_t GetSerial() {
+  virtual uint32_t GetSerial() MOZ_OVERRIDE {
     return mSerial;
   }
 
   static nsGlobalWindow* GetOuterWindowWithId(uint64_t aWindowID) {
     AssertIsOnMainThread();
 
     if (!sWindowsById) {
       return nullptr;
@@ -1148,17 +1148,17 @@ protected:
 
   // Window Control Functions
 
   // Outer windows only.
   virtual nsresult
   OpenNoNavigate(const nsAString& aUrl,
                  const nsAString& aName,
                  const nsAString& aOptions,
-                 nsIDOMWindow **_retval);
+                 nsIDOMWindow** _retval) MOZ_OVERRIDE;
 
 private:
   /**
    * @param aUrl the URL we intend to load into the window.  If aNavigate is
    *        true, we'll actually load this URL into the window. Otherwise,
    *        aUrl is advisory; OpenInternal will not load the URL into the
    *        new window.
    *
@@ -1217,27 +1217,27 @@ private:
                                     nsIDOMWindow **aReturn);
 
 public:
   // Timeout Functions
   // Language agnostic timeout function (all args passed).
   // |interval| is in milliseconds.
   nsresult SetTimeoutOrInterval(nsIScriptTimeoutHandler *aHandler,
                                 int32_t interval,
-                                bool aIsInterval, int32_t *aReturn);
+                                bool aIsInterval, int32_t* aReturn) MOZ_OVERRIDE;
   int32_t SetTimeoutOrInterval(mozilla::dom::Function& aFunction,
                                int32_t aTimeout,
                                const mozilla::dom::Sequence<JS::Value>& aArguments,
                                bool aIsInterval, mozilla::ErrorResult& aError);
   int32_t SetTimeoutOrInterval(JSContext* aCx, const nsAString& aHandler,
                                int32_t aTimeout, bool aIsInterval,
                                mozilla::ErrorResult& aError);
   void ClearTimeoutOrInterval(int32_t aTimerID,
                                   mozilla::ErrorResult& aError);
-  nsresult ClearTimeoutOrInterval(int32_t aTimerID)
+  nsresult ClearTimeoutOrInterval(int32_t aTimerID) MOZ_OVERRIDE
   {
     mozilla::ErrorResult rv;
     ClearTimeoutOrInterval(aTimerID, rv);
     return rv.ErrorCode();
   }
 
   // JS specific timeout functions (JS args grabbed from context).
   nsresult SetTimeoutOrInterval(bool aIsInterval, int32_t* aReturn);
@@ -1272,20 +1272,20 @@ public:
                            const nsAString &aPopupWindowFeatures);
   void FireOfflineStatusEventIfChanged();
 
   // Inner windows only.
   nsresult ScheduleNextIdleObserverCallback();
   uint32_t GetFuzzTimeMS();
   nsresult ScheduleActiveTimerCallback();
   uint32_t FindInsertionIndex(IdleObserverHolder* aIdleObserver);
-  virtual nsresult RegisterIdleObserver(nsIIdleObserver* aIdleObserverPtr);
+  virtual nsresult RegisterIdleObserver(nsIIdleObserver* aIdleObserverPtr) MOZ_OVERRIDE;
   nsresult FindIndexOfElementToRemove(nsIIdleObserver* aIdleObserver,
                                       int32_t* aRemoveElementIndex);
-  virtual nsresult UnregisterIdleObserver(nsIIdleObserver* aIdleObserverPtr);
+  virtual nsresult UnregisterIdleObserver(nsIIdleObserver* aIdleObserverPtr) MOZ_OVERRIDE;
 
   // Inner windows only.
   nsresult FireHashchange(const nsAString &aOldURL, const nsAString &aNewURL);
 
   void FlushPendingNotifications(mozFlushType aType);
 
   // Outer windows only.
   void EnsureReflowFlushAndPaint();
@@ -1357,43 +1357,43 @@ public:
   // context is not available, they will assume a 1:1 ratio.
   int32_t DevToCSSIntPixels(int32_t px);
   int32_t CSSToDevIntPixels(int32_t px);
   nsIntSize DevToCSSIntPixels(nsIntSize px);
   nsIntSize CSSToDevIntPixels(nsIntSize px);
 
   virtual void SetFocusedNode(nsIContent* aNode,
                               uint32_t aFocusMethod = 0,
-                              bool aNeedsFocus = false);
+                              bool aNeedsFocus = false) MOZ_OVERRIDE;
 
-  virtual uint32_t GetFocusMethod();
+  virtual uint32_t GetFocusMethod() MOZ_OVERRIDE;
 
-  virtual bool ShouldShowFocusRing();
+  virtual bool ShouldShowFocusRing() MOZ_OVERRIDE;
 
   virtual void SetKeyboardIndicators(UIStateChangeType aShowAccelerators,
-                                     UIStateChangeType aShowFocusRings);
+                                     UIStateChangeType aShowFocusRings) MOZ_OVERRIDE;
   virtual void GetKeyboardIndicators(bool* aShowAccelerators,
-                                     bool* aShowFocusRings);
+                                     bool* aShowFocusRings) MOZ_OVERRIDE;
 
   // Inner windows only.
   void UpdateCanvasFocus(bool aFocusChanged, nsIContent* aNewContent);
 
 public:
   virtual already_AddRefed<nsPIWindowRoot> GetTopWindowRoot() MOZ_OVERRIDE;
 
 protected:
   static void NotifyDOMWindowDestroyed(nsGlobalWindow* aWindow);
   void NotifyWindowIDDestroyed(const char* aTopic);
 
   static void NotifyDOMWindowFrozen(nsGlobalWindow* aWindow);
   static void NotifyDOMWindowThawed(nsGlobalWindow* aWindow);
 
   void ClearStatus();
 
-  virtual void UpdateParentTarget();
+  virtual void UpdateParentTarget() MOZ_OVERRIDE;
 
   inline int32_t DOMMinTimeoutValue() const;
 
   // Clear the document-dependent slots on our JS wrapper.  Inner windows only.
   void ClearDocumentDependentSlots(JSContext* aCx);
 
   // Inner windows only.
   already_AddRefed<mozilla::dom::StorageEvent>
--- a/dom/base/nsGlobalWindowCommands.cpp
+++ b/dom/base/nsGlobalWindowCommands.cpp
@@ -107,19 +107,19 @@ const char * const sSelectDown2String = 
 #pragma mark -
 #endif
 
 // a base class for selection-related commands, for code sharing
 class nsSelectionCommandsBase : public nsIControllerCommand
 {
 public:
   NS_DECL_ISUPPORTS
-  NS_IMETHOD IsCommandEnabled(const char * aCommandName, nsISupports *aCommandContext, bool *_retval);
-  NS_IMETHOD GetCommandStateParams(const char * aCommandName, nsICommandParams *aParams, nsISupports *aCommandContext);
-  NS_IMETHOD DoCommandParams(const char * aCommandName, nsICommandParams *aParams, nsISupports *aCommandContext);
+  NS_IMETHOD IsCommandEnabled(const char* aCommandName, nsISupports* aCommandContext, bool* _retval) MOZ_OVERRIDE;
+  NS_IMETHOD GetCommandStateParams(const char* aCommandName, nsICommandParams* aParams, nsISupports* aCommandContext) MOZ_OVERRIDE;
+  NS_IMETHOD DoCommandParams(const char* aCommandName, nsICommandParams* aParams, nsISupports* aCommandContext) MOZ_OVERRIDE;
 
 protected:
   virtual ~nsSelectionCommandsBase() {}
 
   static nsresult  GetPresShellFromWindow(nsPIDOMWindow *aWindow, nsIPresShell **aPresShell);
   static nsresult  GetSelectionControllerFromWindow(nsPIDOMWindow *aWindow, nsISelectionController **aSelCon);
 
   // no member variables, please, we're stateless!
--- a/dom/base/nsHostObjectProtocolHandler.cpp
+++ b/dom/base/nsHostObjectProtocolHandler.cpp
@@ -39,17 +39,17 @@ namespace mozilla {
 class HostObjectURLsReporter MOZ_FINAL : public nsIMemoryReporter
 {
   ~HostObjectURLsReporter() {}
 
  public:
   NS_DECL_ISUPPORTS
 
   NS_IMETHOD CollectReports(nsIHandleReportCallback* aHandleReport,
-                            nsISupports* aData, bool aAnonymize)
+                            nsISupports* aData, bool aAnonymize) MOZ_OVERRIDE
   {
     return MOZ_COLLECT_REPORT(
       "host-object-urls", KIND_OTHER, UNITS_COUNT,
       gDataTable ? gDataTable->Count() : 0,
       "The number of host objects stored for access via URLs "
       "(e.g. blobs passed to URL.createObjectURL).");
   }
 };
@@ -57,17 +57,17 @@ class HostObjectURLsReporter MOZ_FINAL :
 NS_IMPL_ISUPPORTS(HostObjectURLsReporter, nsIMemoryReporter)
 
 class BlobURLsReporter MOZ_FINAL : public nsIMemoryReporter
 {
  public:
   NS_DECL_ISUPPORTS
 
   NS_IMETHOD CollectReports(nsIHandleReportCallback* aCallback,
-                            nsISupports* aData, bool aAnonymize)
+                            nsISupports* aData, bool aAnonymize) MOZ_OVERRIDE
   {
     EnumArg env;
     env.mCallback = aCallback;
     env.mData = aData;
     env.mAnonymize = aAnonymize;
 
     if (gDataTable) {
       gDataTable->EnumerateRead(CountCallback, &env);
--- a/dom/base/nsIConsoleAPIStorage.idl
+++ b/dom/base/nsIConsoleAPIStorage.idl
@@ -1,16 +1,16 @@
 /* -*- 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"
 
-[scriptable, uuid(6701600a-17ca-417e-98f9-4ceb175dd15d)]
+[scriptable, uuid(cce39123-585e-411b-9edd-2513f7cf7e47)]
 interface nsIConsoleAPIStorage : nsISupports
 {
   /**
    * Get the events array by inner window ID or all events from all windows.
    *
    * @param string [aId]
    *        Optional, the inner window ID for which you want to get the array of
    *        cached events.
@@ -22,20 +22,39 @@ interface nsIConsoleAPIStorage : nsISupp
   jsval getEvents([optional] in DOMString aId);
 
   /**
    * Record an event associated with the given window ID.
    *
    * @param string aId
    *        The ID of the inner window for which the event occurred or "jsm" for
    *        messages logged from JavaScript modules..
+   * @param string aOuterId
+   *        This ID is used as 3rd parameters for the console-api-log-event
+   *        notification.
    * @param object aEvent
    *        A JavaScript object you want to store.
    */
-  void recordEvent(in DOMString aId, in jsval aEvent);
+  void recordEvent(in DOMString aId, in DOMString aOuterId, in jsval aEvent);
+
+  /**
+   * Similar to recordEvent() but these events will be collected
+   * and dispatched with a timer in order to avoid flooding the devtools
+   * webconsole.
+   *
+   * @param string aId
+   *        The ID of the inner window for which the event occurred or "jsm" for
+   *        messages logged from JavaScript modules..
+   * @param string aOuterId
+   *        This ID is used as 3rd parameters for the console-api-log-event
+   *        notification.
+   * @param object aEvent
+   *        A JavaScript object you want to store.
+   */
+  void recordPendingEvent(in DOMString aId, in DOMString aOuterId, in jsval aEvent);
 
   /**
    * Clear storage data for the given window.
    *
    * @param string [aId]
    *        Optional, the inner window ID for which you want to clear the
    *        messages. If this is not specified all of the cached messages are
    *        cleared, from all window objects.
--- a/dom/base/nsIDocument.h
+++ b/dom/base/nsIDocument.h
@@ -2503,17 +2503,17 @@ protected:
    * These methods should be called before and after dispatching
    * a mutation event.
    * To make this easy and painless, use the mozAutoSubtreeModified helper class.
    */
   virtual void WillDispatchMutationEvent(nsINode* aTarget) = 0;
   virtual void MutationEventDispatched(nsINode* aTarget) = 0;
   friend class mozAutoSubtreeModified;
 
-  virtual Element* GetNameSpaceElement()
+  virtual Element* GetNameSpaceElement() MOZ_OVERRIDE
   {
     return GetRootElement();
   }
 
   void SetContentTypeInternal(const nsACString& aType);
 
   nsCString GetContentTypeInternal() const
   {
--- a/dom/base/nsIDocumentObserver.h
+++ b/dom/base/nsIDocumentObserver.h
@@ -190,66 +190,66 @@ public:
                                 nsIStyleSheet* aStyleSheet,
                                 nsIStyleRule* aStyleRule) = 0;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsIDocumentObserver, NS_IDOCUMENT_OBSERVER_IID)
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_BEGINUPDATE                              \
     virtual void BeginUpdate(nsIDocument* aDocument,                         \
-                             nsUpdateType aUpdateType);
+                             nsUpdateType aUpdateType) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_ENDUPDATE                                \
-    virtual void EndUpdate(nsIDocument* aDocument, nsUpdateType aUpdateType);
+    virtual void EndUpdate(nsIDocument* aDocument, nsUpdateType aUpdateType) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_BEGINLOAD                                \
-    virtual void BeginLoad(nsIDocument* aDocument);
+    virtual void BeginLoad(nsIDocument* aDocument) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_ENDLOAD                                  \
-    virtual void EndLoad(nsIDocument* aDocument);
+    virtual void EndLoad(nsIDocument* aDocument) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_CONTENTSTATECHANGED                      \
     virtual void ContentStateChanged(nsIDocument* aDocument,                 \
                                      nsIContent* aContent,                   \
-                                     mozilla::EventStates aStateMask);
+                                     mozilla::EventStates aStateMask) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_DOCUMENTSTATESCHANGED                    \
     virtual void DocumentStatesChanged(nsIDocument* aDocument,               \
-                                       mozilla::EventStates aStateMask);
+                                       mozilla::EventStates aStateMask) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLESHEETADDED                          \
     virtual void StyleSheetAdded(nsIDocument* aDocument,                     \
                                  nsIStyleSheet* aStyleSheet,                 \
-                                 bool aDocumentSheet);
+                                 bool aDocumentSheet) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLESHEETREMOVED                        \
     virtual void StyleSheetRemoved(nsIDocument* aDocument,                   \
                                    nsIStyleSheet* aStyleSheet,               \
-                                   bool aDocumentSheet);
+                                   bool aDocumentSheet) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLESHEETAPPLICABLESTATECHANGED         \
     virtual void StyleSheetApplicableStateChanged(nsIDocument* aDocument,    \
                                                   nsIStyleSheet* aStyleSheet,\
-                                                  bool aApplicable);
+                                                  bool aApplicable) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLERULECHANGED                         \
     virtual void StyleRuleChanged(nsIDocument* aDocument,                    \
                                   nsIStyleSheet* aStyleSheet,                \
                                   nsIStyleRule* aOldStyleRule,               \
-                                  nsIStyleRule* aNewStyleRule);
+                                  nsIStyleRule* aNewStyleRule) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLERULEADDED                           \
     virtual void StyleRuleAdded(nsIDocument* aDocument,                      \
                                 nsIStyleSheet* aStyleSheet,                  \
-                                nsIStyleRule* aStyleRule);
+                                nsIStyleRule* aStyleRule) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLERULEREMOVED                         \
     virtual void StyleRuleRemoved(nsIDocument* aDocument,                    \
                                   nsIStyleSheet* aStyleSheet,                \
-                                  nsIStyleRule* aStyleRule);
+                                  nsIStyleRule* aStyleRule) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER                                          \
     NS_DECL_NSIDOCUMENTOBSERVER_BEGINUPDATE                                  \
     NS_DECL_NSIDOCUMENTOBSERVER_ENDUPDATE                                    \
     NS_DECL_NSIDOCUMENTOBSERVER_BEGINLOAD                                    \
     NS_DECL_NSIDOCUMENTOBSERVER_ENDLOAD                                      \
     NS_DECL_NSIDOCUMENTOBSERVER_CONTENTSTATECHANGED                          \
     NS_DECL_NSIDOCUMENTOBSERVER_DOCUMENTSTATESCHANGED                        \
--- a/dom/base/nsIMutationObserver.h
+++ b/dom/base/nsIMutationObserver.h
@@ -318,61 +318,61 @@ public:
   virtual void ParentChainChanged(nsIContent *aContent) = 0;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsIMutationObserver, NS_IMUTATION_OBSERVER_IID)
 
 #define NS_DECL_NSIMUTATIONOBSERVER_CHARACTERDATAWILLCHANGE                  \
     virtual void CharacterDataWillChange(nsIDocument* aDocument,             \
                                          nsIContent* aContent,               \
-                                         CharacterDataChangeInfo* aInfo);
+                                         CharacterDataChangeInfo* aInfo) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIMUTATIONOBSERVER_CHARACTERDATACHANGED                     \
     virtual void CharacterDataChanged(nsIDocument* aDocument,                \
                                       nsIContent* aContent,                  \
-                                      CharacterDataChangeInfo* aInfo);
+                                      CharacterDataChangeInfo* aInfo) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTEWILLCHANGE                      \
     virtual void AttributeWillChange(nsIDocument* aDocument,                 \
                                      mozilla::dom::Element* aElement,        \
                                      int32_t aNameSpaceID,                   \
                                      nsIAtom* aAttribute,                    \
-                                     int32_t aModType);
+                                     int32_t aModType) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTECHANGED                         \
     virtual void AttributeChanged(nsIDocument* aDocument,                    \
                                   mozilla::dom::Element* aElement,           \
                                   int32_t aNameSpaceID,                      \
                                   nsIAtom* aAttribute,                       \
-                                  int32_t aModType);
+                                  int32_t aModType) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIMUTATIONOBSERVER_CONTENTAPPENDED                          \
     virtual void ContentAppended(nsIDocument* aDocument,                     \
                                  nsIContent* aContainer,                     \
                                  nsIContent* aFirstNewContent,               \
-                                 int32_t aNewIndexInContainer);
+                                 int32_t aNewIndexInContainer) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIMUTATIONOBSERVER_CONTENTINSERTED                          \
     virtual void ContentInserted(nsIDocument* aDocument,                     \
                                  nsIContent* aContainer,                     \
                                  nsIContent* aChild,                         \
-                                 int32_t aIndexInContainer);
+                                 int32_t aIndexInContainer) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIMUTATIONOBSERVER_CONTENTREMOVED                           \
     virtual void ContentRemoved(nsIDocument* aDocument,                      \
                                 nsIContent* aContainer,                      \
                                 nsIContent* aChild,                          \
                                 int32_t aIndexInContainer,                   \
-                                nsIContent* aPreviousSibling);
+                                nsIContent* aPreviousSibling) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIMUTATIONOBSERVER_NODEWILLBEDESTROYED                      \
-    virtual void NodeWillBeDestroyed(const nsINode* aNode);
+    virtual void NodeWillBeDestroyed(const nsINode* aNode) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIMUTATIONOBSERVER_PARENTCHAINCHANGED                       \
-    virtual void ParentChainChanged(nsIContent *aContent);
+    virtual void ParentChainChanged(nsIContent *aContent) MOZ_OVERRIDE;
 
 #define NS_DECL_NSIMUTATIONOBSERVER                                          \
     NS_DECL_NSIMUTATIONOBSERVER_CHARACTERDATAWILLCHANGE                      \
     NS_DECL_NSIMUTATIONOBSERVER_CHARACTERDATACHANGED                         \
     NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTEWILLCHANGE                          \
     NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTECHANGED                             \
     NS_DECL_NSIMUTATIONOBSERVER_CONTENTAPPENDED                              \
     NS_DECL_NSIMUTATIONOBSERVER_CONTENTINSERTED                              \
--- a/dom/base/nsINode.h
+++ b/dom/base/nsINode.h
@@ -234,17 +234,17 @@ private:
 };
 
 // This should be used for any nsINode sub-class that has fields of its own
 // that it needs to measure;  any sub-class that doesn't use it will inherit
 // SizeOfExcludingThis from its super-class.  SizeOfIncludingThis() need not be
 // defined, it is inherited from nsINode.
 // This macro isn't actually specific to nodes, and bug 956400 will move it into MFBT.
 #define NS_DECL_SIZEOF_EXCLUDING_THIS \
-  virtual size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
+  virtual size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const MOZ_OVERRIDE;
 
 // Categories of node properties
 // 0 is global.
 #define DOM_USER_DATA         1
 #define SMIL_MAPPED_ATTR_ANIMVAL 2
 
 // IID for the nsINode interface
 #define NS_INODE_IID \
@@ -288,17 +288,17 @@ public:
   // - nsHTMLSelectElement:   mOptions, mRestoreState
   // - nsHTMLTableElement:    mTBodies, mRows, mTableInheritedAttributes
   // - nsHTMLTableSectionElement: mRows
   // - nsHTMLTextAreaElement: mControllers, mState
   //
   // The following members don't need to be measured:
   // - nsIContent: mPrimaryFrame, because it's non-owning and measured elsewhere
   //
-  NS_DECL_SIZEOF_EXCLUDING_THIS
+  virtual size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
 
   // SizeOfIncludingThis doesn't need to be overridden by sub-classes because
   // sub-classes of nsINode are guaranteed to be laid out in memory in such a
   // way that |this| points to the start of the allocated object, even in
   // methods of nsINode's sub-classes, and so |aMallocSizeOf(this)| is always
   // safe to call no matter which object it was invoked on.
   virtual size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const {
     return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
@@ -1872,177 +1872,177 @@ ToSupports(nsINode* aPointer)
 
 inline nsISupports*
 ToCanonicalSupports(nsINode* aPointer)
 {
   return aPointer;
 }
 
 #define NS_FORWARD_NSIDOMNODE_TO_NSINODE_HELPER(...) \
-  NS_IMETHOD GetNodeName(nsAString& aNodeName) __VA_ARGS__ \
+  NS_IMETHOD GetNodeName(nsAString& aNodeName) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     aNodeName = nsINode::NodeName(); \
     return NS_OK; \
   } \
-  NS_IMETHOD GetNodeValue(nsAString& aNodeValue) __VA_ARGS__ \
+  NS_IMETHOD GetNodeValue(nsAString& aNodeValue) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     nsINode::GetNodeValue(aNodeValue); \
     return NS_OK; \
   } \
-  NS_IMETHOD SetNodeValue(const nsAString& aNodeValue) __VA_ARGS__ \
+  NS_IMETHOD SetNodeValue(const nsAString& aNodeValue) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     mozilla::ErrorResult rv; \
     nsINode::SetNodeValue(aNodeValue, rv); \
     return rv.ErrorCode(); \
   } \
-  NS_IMETHOD GetNodeType(uint16_t* aNodeType) __VA_ARGS__ \
+  NS_IMETHOD GetNodeType(uint16_t* aNodeType) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     *aNodeType = nsINode::NodeType(); \
     return NS_OK; \
   } \
-  NS_IMETHOD GetParentNode(nsIDOMNode** aParentNode) __VA_ARGS__ \
+  NS_IMETHOD GetParentNode(nsIDOMNode** aParentNode) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::GetParentNode(aParentNode); \
   } \
-  NS_IMETHOD GetParentElement(nsIDOMElement** aParentElement) __VA_ARGS__ \
+  NS_IMETHOD GetParentElement(nsIDOMElement** aParentElement) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::GetParentElement(aParentElement); \
   } \
-  NS_IMETHOD GetChildNodes(nsIDOMNodeList** aChildNodes) __VA_ARGS__ \
+  NS_IMETHOD GetChildNodes(nsIDOMNodeList** aChildNodes) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::GetChildNodes(aChildNodes); \
   } \
-  NS_IMETHOD GetFirstChild(nsIDOMNode** aFirstChild) __VA_ARGS__ \
+  NS_IMETHOD GetFirstChild(nsIDOMNode** aFirstChild) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::GetFirstChild(aFirstChild); \
   } \
-  NS_IMETHOD GetLastChild(nsIDOMNode** aLastChild) __VA_ARGS__ \
+  NS_IMETHOD GetLastChild(nsIDOMNode** aLastChild) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::GetLastChild(aLastChild); \
   } \
-  NS_IMETHOD GetPreviousSibling(nsIDOMNode** aPreviousSibling) __VA_ARGS__ \
+  NS_IMETHOD GetPreviousSibling(nsIDOMNode** aPreviousSibling) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::GetPreviousSibling(aPreviousSibling); \
   } \
-  NS_IMETHOD GetNextSibling(nsIDOMNode** aNextSibling) __VA_ARGS__ \
+  NS_IMETHOD GetNextSibling(nsIDOMNode** aNextSibling) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::GetNextSibling(aNextSibling); \
   } \
-  NS_IMETHOD GetOwnerDocument(nsIDOMDocument** aOwnerDocument) __VA_ARGS__ \
+  NS_IMETHOD GetOwnerDocument(nsIDOMDocument** aOwnerDocument) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::GetOwnerDocument(aOwnerDocument); \
   } \
-  NS_IMETHOD InsertBefore(nsIDOMNode* aNewChild, nsIDOMNode* aRefChild, nsIDOMNode** aResult) __VA_ARGS__ \
+  NS_IMETHOD InsertBefore(nsIDOMNode* aNewChild, nsIDOMNode* aRefChild, nsIDOMNode** aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return ReplaceOrInsertBefore(false, aNewChild, aRefChild, aResult); \
   } \
-  NS_IMETHOD ReplaceChild(nsIDOMNode* aNewChild, nsIDOMNode* aOldChild, nsIDOMNode** aResult) __VA_ARGS__ \
+  NS_IMETHOD ReplaceChild(nsIDOMNode* aNewChild, nsIDOMNode* aOldChild, nsIDOMNode** aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return ReplaceOrInsertBefore(true, aNewChild, aOldChild, aResult); \
   } \
-  NS_IMETHOD RemoveChild(nsIDOMNode* aOldChild, nsIDOMNode** aResult) __VA_ARGS__ \
+  NS_IMETHOD RemoveChild(nsIDOMNode* aOldChild, nsIDOMNode** aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::RemoveChild(aOldChild, aResult); \
   } \
-  NS_IMETHOD AppendChild(nsIDOMNode* aNewChild, nsIDOMNode** aResult) __VA_ARGS__ \
+  NS_IMETHOD AppendChild(nsIDOMNode* aNewChild, nsIDOMNode** aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return InsertBefore(aNewChild, nullptr, aResult); \
   } \
-  NS_IMETHOD HasChildNodes(bool* aResult) __VA_ARGS__ \
+  NS_IMETHOD HasChildNodes(bool* aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     *aResult = nsINode::HasChildNodes(); \
     return NS_OK; \
   } \
-  NS_IMETHOD CloneNode(bool aDeep, uint8_t aArgc, nsIDOMNode** aResult) __VA_ARGS__ \
+  NS_IMETHOD CloneNode(bool aDeep, uint8_t aArgc, nsIDOMNode** aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     if (aArgc == 0) { \
       aDeep = true; \
     } \
     mozilla::ErrorResult rv; \
     nsCOMPtr<nsINode> clone = nsINode::CloneNode(aDeep, rv); \
     if (rv.Failed()) { \
       return rv.ErrorCode(); \
     } \
     *aResult = clone.forget().take()->AsDOMNode(); \
     return NS_OK; \
   } \
-  NS_IMETHOD Normalize() __VA_ARGS__ \
+  NS_IMETHOD Normalize() __VA_ARGS__ MOZ_OVERRIDE \
   { \
     nsINode::Normalize(); \
     return NS_OK; \
   } \
-  NS_IMETHOD GetNamespaceURI(nsAString& aNamespaceURI) __VA_ARGS__ \
+  NS_IMETHOD GetNamespaceURI(nsAString& aNamespaceURI) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     nsINode::GetNamespaceURI(aNamespaceURI); \
     return NS_OK; \
   } \
-  NS_IMETHOD GetPrefix(nsAString& aPrefix) __VA_ARGS__ \
+  NS_IMETHOD GetPrefix(nsAString& aPrefix) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     nsINode::GetPrefix(aPrefix); \
     return NS_OK; \
   } \
-  NS_IMETHOD GetLocalName(nsAString& aLocalName) __VA_ARGS__ \
+  NS_IMETHOD GetLocalName(nsAString& aLocalName) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     aLocalName = nsINode::LocalName(); \
     return NS_OK; \
   } \
-  NS_IMETHOD UnusedPlaceholder(bool* aResult) __VA_ARGS__ \
+  NS_IMETHOD UnusedPlaceholder(bool* aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     *aResult = false; \
     return NS_OK; \
   } \
-  NS_IMETHOD GetDOMBaseURI(nsAString& aBaseURI) __VA_ARGS__ \
+  NS_IMETHOD GetDOMBaseURI(nsAString& aBaseURI) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     nsINode::GetBaseURI(aBaseURI); \
     return NS_OK; \
   } \
-  NS_IMETHOD CompareDocumentPosition(nsIDOMNode* aOther, uint16_t* aResult) __VA_ARGS__ \
+  NS_IMETHOD CompareDocumentPosition(nsIDOMNode* aOther, uint16_t* aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::CompareDocumentPosition(aOther, aResult); \
   } \
-  NS_IMETHOD GetTextContent(nsAString& aTextContent) __VA_ARGS__ \
+  NS_IMETHOD GetTextContent(nsAString& aTextContent) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     mozilla::ErrorResult rv; \
     nsINode::GetTextContent(aTextContent, rv); \
     return rv.ErrorCode(); \
   } \
-  NS_IMETHOD SetTextContent(const nsAString& aTextContent) __VA_ARGS__ \
+  NS_IMETHOD SetTextContent(const nsAString& aTextContent) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     mozilla::ErrorResult rv; \
     nsINode::SetTextContent(aTextContent, rv); \
     return rv.ErrorCode(); \
   } \
-  NS_IMETHOD LookupPrefix(const nsAString& aNamespaceURI, nsAString& aResult) __VA_ARGS__ \
+  NS_IMETHOD LookupPrefix(const nsAString& aNamespaceURI, nsAString& aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     nsINode::LookupPrefix(aNamespaceURI, aResult); \
     return NS_OK; \
   } \
-  NS_IMETHOD IsDefaultNamespace(const nsAString& aNamespaceURI, bool* aResult) __VA_ARGS__ \
+  NS_IMETHOD IsDefaultNamespace(const nsAString& aNamespaceURI, bool* aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     *aResult = nsINode::IsDefaultNamespace(aNamespaceURI); \
     return NS_OK; \
   } \
-  NS_IMETHOD LookupNamespaceURI(const nsAString& aPrefix, nsAString& aResult) __VA_ARGS__ \
+  NS_IMETHOD LookupNamespaceURI(const nsAString& aPrefix, nsAString& aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     nsINode::LookupNamespaceURI(aPrefix, aResult); \
     return NS_OK; \
   } \
-  NS_IMETHOD IsEqualNode(nsIDOMNode* aArg, bool* aResult) __VA_ARGS__ \
+  NS_IMETHOD IsEqualNode(nsIDOMNode* aArg, bool* aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::IsEqualNode(aArg, aResult); \
   } \
-  NS_IMETHOD SetUserData(const nsAString& aKey, nsIVariant* aData, nsIVariant** aResult) __VA_ARGS__ \
+  NS_IMETHOD SetUserData(const nsAString& aKey, nsIVariant* aData, nsIVariant** aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::SetUserData(aKey, aData, aResult); \
   } \
-  NS_IMETHOD GetUserData(const nsAString& aKey, nsIVariant** aResult) __VA_ARGS__ \
+  NS_IMETHOD GetUserData(const nsAString& aKey, nsIVariant** aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::GetUserData(aKey, aResult); \
   } \
-  NS_IMETHOD Contains(nsIDOMNode* aOther, bool* aResult) __VA_ARGS__ \
+  NS_IMETHOD Contains(nsIDOMNode* aOther, bool* aResult) __VA_ARGS__ MOZ_OVERRIDE \
   { \
     return nsINode::Contains(aOther, aResult); \
   }
 
 #define NS_FORWARD_NSIDOMNODE_TO_NSINODE \
   NS_FORWARD_NSIDOMNODE_TO_NSINODE_HELPER(MOZ_FINAL)
 
 #define NS_FORWARD_NSIDOMNODE_TO_NSINODE_OVERRIDABLE \
--- a/dom/base/nsInProcessTabChildGlobal.h
+++ b/dom/base/nsInProcessTabChildGlobal.h
@@ -45,30 +45,30 @@ public:
   NS_FORWARD_SAFE_NSIMESSAGELISTENERMANAGER(mMessageManager)
   NS_FORWARD_SAFE_NSIMESSAGESENDER(mMessageManager)
   NS_IMETHOD SendSyncMessage(const nsAString& aMessageName,
                              JS::Handle<JS::Value> aObject,
                              JS::Handle<JS::Value> aRemote,
                              nsIPrincipal* aPrincipal,
                              JSContext* aCx,
                              uint8_t aArgc,
-                             JS::MutableHandle<JS::Value> aRetval)
+                             JS::MutableHandle<JS::Value> aRetval) MOZ_OVERRIDE
   {
     return mMessageManager
       ? mMessageManager->SendSyncMessage(aMessageName, aObject, aRemote,
                                          aPrincipal, aCx, aArgc, aRetval)
       : NS_ERROR_NULL_POINTER;
   }
   NS_IMETHOD SendRpcMessage(const nsAString& aMessageName,
                             JS::Handle<JS::Value> aObject,
                             JS::Handle<JS::Value> aRemote,
                             nsIPrincipal* aPrincipal,
                             JSContext* aCx,
                             uint8_t aArgc,
-                            JS::MutableHandle<JS::Value> aRetval)
+                            JS::MutableHandle<JS::Value> aRetval) MOZ_OVERRIDE
   {
     return mMessageManager
       ? mMessageManager->SendRpcMessage(aMessageName, aObject, aRemote,
                                         aPrincipal, aCx, aArgc, aRetval)
       : NS_ERROR_NULL_POINTER;
   }
   NS_IMETHOD GetContent(nsIDOMWindow** aContent) MOZ_OVERRIDE;
   NS_IMETHOD GetDocShell(nsIDocShell** aDocShell) MOZ_OVERRIDE;
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -2937,17 +2937,17 @@ public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(nsJSArgArray,
                                                          nsIJSArgArray)
 
   // nsIArray
   NS_DECL_NSIARRAY
 
   // nsIJSArgArray
-  nsresult GetArgs(uint32_t *argc, void **argv);
+  nsresult GetArgs(uint32_t* argc, void** argv) MOZ_OVERRIDE;
 
   void ReleaseJSObjects();
 
 protected:
   ~nsJSArgArray();
   JSContext *mContext;
   JS::Heap<JS::Value> *mArgv;
   uint32_t mArgc;
--- a/dom/base/nsJSTimeoutHandler.cpp
+++ b/dom/base/nsJSTimeoutHandler.cpp
@@ -37,28 +37,28 @@ public:
   // This will call SwapElements on aArguments with an empty array.
   nsJSScriptTimeoutHandler(nsGlobalWindow *aWindow, Function& aFunction,
                            FallibleTArray<JS::Heap<JS::Value> >& aArguments,
                            ErrorResult& aError);
   nsJSScriptTimeoutHandler(JSContext* aCx, nsGlobalWindow *aWindow,
                            const nsAString& aExpression, bool* aAllowEval,
                            ErrorResult& aError);
 
-  virtual const char16_t *GetHandlerText();
-  virtual Function* GetCallback()
+  virtual const char16_t* GetHandlerText() MOZ_OVERRIDE;
+  virtual Function* GetCallback() MOZ_OVERRIDE
   {
     return mFunction;
   }
-  virtual void GetLocation(const char **aFileName, uint32_t *aLineNo)
+  virtual void GetLocation(const char** aFileName, uint32_t* aLineNo) MOZ_OVERRIDE
   {
     *aFileName = mFileName.get();
     *aLineNo = mLineNo;
   }
 
-  virtual const nsTArray<JS::Value>& GetArgs()
+  virtual const nsTArray<JS::Value>& GetArgs() MOZ_OVERRIDE
   {
     return mArgs;
   }
 
   nsresult Init(nsGlobalWindow *aWindow, bool *aIsInterval,
                 int32_t *aInterval, bool* aAllowEval);
 
   void ReleaseJSObjects();
--- a/dom/base/nsObjectLoadingContent.cpp
+++ b/dom/base/nsObjectLoadingContent.cpp
@@ -356,20 +356,20 @@ public:
     : mInstanceOwner(aInstanceOwner)
     , mContent(aContent)
   {
     NS_ASSERTION(aInstanceOwner, "need an owner");
     NS_ASSERTION(aContent, "need a nsObjectLoadingContent");
   }
 
   // nsRunnable
-  NS_IMETHOD Run();
+  NS_IMETHOD Run() MOZ_OVERRIDE;
 
   // nsITimerCallback
-  NS_IMETHOD Notify(nsITimer *timer);
+  NS_IMETHOD Notify(nsITimer* timer) MOZ_OVERRIDE;
 
 protected:
   virtual ~nsStopPluginRunnable() {}
 
 private:
   nsCOMPtr<nsITimer> mTimer;
   nsRefPtr<nsPluginInstanceOwner> mInstanceOwner;
   nsCOMPtr<nsIObjectLoadingContent> mContent;
--- a/dom/base/nsReferencedElement.h
+++ b/dom/base/nsReferencedElement.h
@@ -136,18 +136,18 @@ private:
     NS_DECL_ISUPPORTS_INHERITED
     NS_IMETHOD Run() MOZ_OVERRIDE {
       if (mTarget) {
         mTarget->mPendingNotification = nullptr;
         mTarget->ElementChanged(mFrom, mTo);
       }
       return NS_OK;
     }
-    virtual void SetTo(Element* aTo) { mTo = aTo; }
-    virtual void Clear()
+    virtual void SetTo(Element* aTo) MOZ_OVERRIDE { mTo = aTo; }
+    virtual void Clear() MOZ_OVERRIDE
     {
       Notification::Clear(); mFrom = nullptr; mTo = nullptr;
     }
   protected:
     virtual ~ChangeNotification() {}
 
     nsRefPtr<Element> mFrom;
     nsRefPtr<Element> mTo;
@@ -167,17 +167,17 @@ private:
       }
     }
 
     NS_DECL_ISUPPORTS
     NS_DECL_NSIOBSERVER
   private:
     virtual ~DocumentLoadNotification() {}
 
-    virtual void SetTo(Element* aTo) { }
+    virtual void SetTo(Element* aTo) MOZ_OVERRIDE { }
 
     nsString mRef;
   };
   friend class DocumentLoadNotification;
   
   nsCOMPtr<nsIAtom>      mWatchID;
   nsCOMPtr<nsIDocument>  mWatchDocument;
   nsRefPtr<Element> mElement;
--- a/dom/base/nsScreen.h
+++ b/dom/base/nsScreen.h
@@ -119,17 +119,17 @@ public:
   IMPL_EVENT_HANDLER(mozorientationchange)
 
   bool MozLockOrientation(const nsAString& aOrientation, ErrorResult& aRv);
   bool MozLockOrientation(const mozilla::dom::Sequence<nsString>& aOrientations, ErrorResult& aRv);
   void MozUnlockOrientation();
 
   virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE;
 
-  void Notify(const mozilla::hal::ScreenConfiguration& aConfiguration);
+  void Notify(const mozilla::hal::ScreenConfiguration& aConfiguration) MOZ_OVERRIDE;
 
 protected:
   nsDeviceContext* GetDeviceContext();
   nsresult GetRect(nsRect& aRect);
   nsresult GetAvailRect(nsRect& aRect);
 
   mozilla::dom::ScreenOrientation mOrientation;
 
--- a/dom/base/nsStyledElement.h
+++ b/dom/base/nsStyledElement.h
@@ -31,17 +31,17 @@ class nsStyledElementNotElementCSSInline
 protected:
 
   inline explicit nsStyledElementNotElementCSSInlineStyle(already_AddRefed<mozilla::dom::NodeInfo>& aNodeInfo)
     : nsStyledElementBase(aNodeInfo)
   {}
 
 public:
   // nsIContent interface methods
-  virtual mozilla::css::StyleRule* GetInlineStyleRule();
+  virtual mozilla::css::StyleRule* GetInlineStyleRule() MOZ_OVERRIDE;
   virtual nsresult SetInlineStyleRule(mozilla::css::StyleRule* aStyleRule,
                                       const nsAString* aSerialized,
                                       bool aNotify) MOZ_OVERRIDE;
 
   nsICSSDeclaration* Style();
 
 protected:
 
--- a/dom/base/nsTextNode.cpp
+++ b/dom/base/nsTextNode.cpp
@@ -42,25 +42,25 @@ public:
     mAttrName(aAttrName)
   {
     NS_ASSERTION(mNameSpaceID != kNameSpaceID_Unknown, "Must know namespace");
     NS_ASSERTION(mAttrName, "Must have attr name");
   }
 
   virtual nsresult BindToTree(nsIDocument* aDocument, nsIContent* aParent,
                               nsIContent* aBindingParent,
-                              bool aCompileEventHandlers);
+                              bool aCompileEventHandlers) MOZ_OVERRIDE;
   virtual void UnbindFromTree(bool aDeep = true,
-                              bool aNullParent = true);
+                              bool aNullParent = true) MOZ_OVERRIDE;
 
   NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTECHANGED
   NS_DECL_NSIMUTATIONOBSERVER_NODEWILLBEDESTROYED
 
   virtual nsGenericDOMDataNode *CloneDataNode(mozilla::dom::NodeInfo *aNodeInfo,
-                                              bool aCloneText) const
+                                              bool aCloneText) const MOZ_OVERRIDE
   {
     already_AddRefed<mozilla::dom::NodeInfo> ni =
       nsRefPtr<mozilla::dom::NodeInfo>(aNodeInfo).forget();
     nsAttributeTextNode *it = new nsAttributeTextNode(ni,
                                                       mNameSpaceID,
                                                       mAttrName);
     if (it && aCloneText) {
       it->mText = mText;
--- a/dom/base/nsTextNode.h
+++ b/dom/base/nsTextNode.h
@@ -52,17 +52,17 @@ public:
   // nsIDOMCharacterData
   NS_FORWARD_NSIDOMCHARACTERDATA(nsGenericDOMDataNode::)
   using nsGenericDOMDataNode::SetData; // Prevent hiding overloaded virtual function.
 
   // nsIDOMText
   NS_FORWARD_NSIDOMTEXT(nsGenericDOMDataNode::)
 
   // nsINode
-  virtual bool IsNodeOfType(uint32_t aFlags) const;
+  virtual bool IsNodeOfType(uint32_t aFlags) const MOZ_OVERRIDE;
 
   virtual nsGenericDOMDataNode* CloneDataNode(mozilla::dom::NodeInfo *aNodeInfo,
                                               bool aCloneText) const MOZ_OVERRIDE;
 
   virtual nsresult BindToTree(nsIDocument* aDocument, nsIContent* aParent,
                               nsIContent* aBindingParent,
                               bool aCompileEventHandlers) MOZ_OVERRIDE;
   virtual void UnbindFromTree(bool aDeep = true,
--- a/dom/base/nsWindowMemoryReporter.h
+++ b/dom/base/nsWindowMemoryReporter.h
@@ -170,17 +170,17 @@ private:
     ~GhostWindowsReporter() {}
   public:
     NS_DECL_ISUPPORTS
 
     static int64_t DistinguishedAmount();
 
     NS_IMETHOD
     CollectReports(nsIHandleReportCallback* aHandleReport, nsISupports* aData,
-                   bool aAnonymize)
+                   bool aAnonymize) MOZ_OVERRIDE
     {
       return MOZ_COLLECT_REPORT(
         "ghost-windows", KIND_OTHER, UNITS_COUNT, DistinguishedAmount(),
 "The number of ghost windows present (the number of nodes underneath "
 "explicit/window-objects/top(none)/ghost, modulo race conditions).  A ghost "
 "window is not shown in any tab, does not share a domain with any non-detached "
 "windows, and has met these criteria for at least "
 "memory.ghost_window_timeout_seconds, or has survived a round of "
--- a/dom/base/nsXMLHttpRequest.cpp
+++ b/dom/base/nsXMLHttpRequest.cpp
@@ -3421,17 +3421,17 @@ public:
     : mXHR(xhr)
   {
   }
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS(AsyncVerifyRedirectCallbackForwarder)
 
   // nsIAsyncVerifyRedirectCallback implementation
-  NS_IMETHOD OnRedirectVerifyCallback(nsresult result)
+  NS_IMETHOD OnRedirectVerifyCallback(nsresult result) MOZ_OVERRIDE
   {
     mXHR->OnRedirectVerifyCallback(result);
 
     return NS_OK;
   }
 
 private:
   ~AsyncVerifyRedirectCallbackForwarder() {}
--- a/dom/base/nsXMLHttpRequest.h
+++ b/dom/base/nsXMLHttpRequest.h
@@ -138,17 +138,17 @@ public:
   IMPL_EVENT_HANDLER(loadstart)
   IMPL_EVENT_HANDLER(progress)
   IMPL_EVENT_HANDLER(abort)
   IMPL_EVENT_HANDLER(error)
   IMPL_EVENT_HANDLER(load)
   IMPL_EVENT_HANDLER(timeout)
   IMPL_EVENT_HANDLER(loadend)
   
-  virtual void DisconnectFromOwner();
+  virtual void DisconnectFromOwner() MOZ_OVERRIDE;
 };
 
 class nsXMLHttpRequestUpload MOZ_FINAL : public nsXHREventTarget,
                                          public nsIXMLHttpRequestUpload
 {
 public:
   explicit nsXMLHttpRequestUpload(mozilla::DOMEventTargetHelper* aOwner)
     : nsXHREventTarget(aOwner)
@@ -284,17 +284,17 @@ public:
   // nsIInterfaceRequestor
   NS_DECL_NSIINTERFACEREQUESTOR
 
   // nsITimerCallback
   NS_DECL_NSITIMERCALLBACK
 
   // nsISizeOfEventTarget
   virtual size_t
-    SizeOfEventTargetIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
+    SizeOfEventTargetIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const MOZ_OVERRIDE;
 
   NS_REALLY_FORWARD_NSIDOMEVENTTARGET(nsXHREventTarget)
 
 #ifdef DEBUG
   void StaticAssertions();
 #endif
 
   // event handler
--- a/dom/browser-element/BrowserElementChildPreload.js
+++ b/dom/browser-element/BrowserElementChildPreload.js
@@ -159,27 +159,27 @@ BrowserElementChild.prototype = {
 
     addEventListener('DOMMetaRemoved',
                      this._metaChangedHandler.bind(this),
                      /* useCapture = */ true,
                      /* wantsUntrusted = */ false);
 
     addEventListener('mozselectionstatechanged',
                      this._selectionStateChangedHandler.bind(this),
-                     /* useCapture = */ false,
+                     /* useCapture = */ true,
                      /* wantsUntrusted = */ false);
 
     addEventListener('scrollviewchange',
                      this._ScrollViewChangeHandler.bind(this),
-                     /* useCapture = */ false,
+                     /* useCapture = */ true,
                      /* wantsUntrusted = */ false);
 
     addEventListener('touchcarettap',
                      this._touchCaretTapHandler.bind(this),
-                     /* useCapture = */ false,
+                     /* useCapture = */ true,
                      /* wantsUntrusted = */ false);
 
 
     // This listens to unload events from our message manager, but /not/ from
     // the |content| window.  That's because the window's unload event doesn't
     // bubble, and we're not using a capturing listener.  If we'd used
     // useCapture == true, we /would/ hear unload events from the window, which
     // is not what we want!
@@ -654,23 +654,23 @@ BrowserElementChild.prototype = {
       zoomFactor: zoomFactor,
       states: e.states,
       isCollapsed: (e.selectedText.length == 0),
       visible: e.visible,
     };
 
     // Get correct geometry information if we have nested iframe.
     let currentWindow = e.target.defaultView;
-    while (currentWindow.top != currentWindow) {
-      let currentRect = currentWindow.frameElement.getBoundingClientRect();
+    while (currentWindow.realFrameElement) {
+      let currentRect = currentWindow.realFrameElement.getBoundingClientRect();
       detail.rect.top += currentRect.top;
       detail.rect.bottom += currentRect.top;
       detail.rect.left += currentRect.left;
       detail.rect.right += currentRect.left;
-      currentWindow = currentWindow.parent;
+      currentWindow = currentWindow.realFrameElement.ownerDocument.defaultView;
     }
 
     sendAsyncMsg('selectionstatechanged', detail);
   },
 
   _themeColorChangedHandler: function(eventType, target) {
     let meta = {
       name: 'theme-color',
--- a/dom/browser-element/mochitest/browserElement_CopyPaste.js
+++ b/dom/browser-element/mochitest/browserElement_CopyPaste.js
@@ -5,24 +5,27 @@
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 SimpleTest.requestFlakyTimeout("untriaged");
 browserElementTestHelpers.setEnabledPref(true);
 browserElementTestHelpers.setSelectionChangeEnabledPref(true);
 browserElementTestHelpers.addPermission();
 const { Services } = SpecialPowers.Cu.import('resource://gre/modules/Services.jsm');
+
 var gTextarea = null;
 var mm;
-var iframe;
+var iframeOuter;
+var iframeInner;
 var state = 0;
 var stateMeaning;
 var defaultData;
 var pasteData;
 var focusScript;
+var createEmbededFrame = false;
 
 function copyToClipboard(str) {
   gTextarea.value = str;
   SpecialPowers.wrap(gTextarea).editor.selectAll();
   SpecialPowers.wrap(gTextarea).editor.copy();
 }
 
 function getScriptForGetContent() {
@@ -41,127 +44,164 @@ function getScriptForGetContent() {
 }
 
 function getScriptForSetFocus() {
   var script = 'data:,' + focusScript + 'sendAsyncMessage("content-focus")';
   return script;
 }
 
 function runTest() {
-  iframe = document.createElement('iframe');
-  iframe.setAttribute('mozbrowser', 'true');
-  document.body.appendChild(iframe);
+  iframeOuter = document.createElement('iframe');
+  iframeOuter.setAttribute('mozbrowser', 'true');
+  if (createEmbededFrame) {
+    iframeOuter.src = "file_NestedFramesOuter_CopyPaste.html";
+  }
+  document.body.appendChild(iframeOuter);
 
   gTextarea = document.createElement('textarea');
   document.body.appendChild(gTextarea);
 
-  mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
+  iframeOuter.addEventListener("mozbrowserloadend", function onloadend(e) {
+    iframeOuter.removeEventListener("mozbrowserloadend", onloadend);
 
-  iframe.addEventListener("mozbrowserloadend", function onloadend(e) {
-    iframe.removeEventListener("mozbrowserloadend", onloadend);
-    dispatchTest(e);
+    if (createEmbededFrame) {
+      var contentWin = SpecialPowers.wrap(iframeOuter)
+                             .QueryInterface(SpecialPowers.Ci.nsIFrameLoaderOwner)
+                             .frameLoader.docShell.contentViewer.DOMDocument.defaultView;
+      var contentDoc = contentWin.document;
+      iframeInner = contentDoc.getElementById('iframeInner');
+      iframeInner.addEventListener("mozbrowserloadend", function onloadendinner(e) {
+        iframeInner.removeEventListener("mozbrowserloadend", onloadendinner);
+        mm = SpecialPowers.getBrowserFrameMessageManager(iframeInner);
+        dispatchTest(e);
+      });
+    } else {
+      iframeInner = iframeOuter;
+      mm = SpecialPowers.getBrowserFrameMessageManager(iframeInner);
+      dispatchTest(e);
+    }
   });
 }
 
 function doCommand(cmd) {
-  Services.obs.notifyObservers({wrappedJSObject: iframe},
+  Services.obs.notifyObservers({wrappedJSObject: SpecialPowers.unwrap(iframeInner)},
                                'copypaste-docommand', cmd);
 }
 
 function dispatchTest(e) {
-  iframe.addEventListener("mozbrowserloadend", function onloadend2(e) {
-    iframe.removeEventListener("mozbrowserloadend", onloadend2);
-    iframe.focus();
+  iframeInner.addEventListener("mozbrowserloadend", function onloadend2(e) {
+    iframeInner.removeEventListener("mozbrowserloadend", onloadend2);
+    iframeInner.focus();
     SimpleTest.executeSoon(function() { testSelectAll(e); });
   });
 
   switch (state) {
     case 0: // test for textarea
       defaultData = "Test for selection change event";
       pasteData = "from parent ";
-      iframe.src = "data:text/html,<html><body>" +
+      iframeInner.src = "data:text/html,<html><body>" +
                    "<textarea id='text'>" + defaultData + "</textarea>" +
                    "</body>" +
                    "</html>";
       stateMeaning = " (test: textarea)";
       focusScript = "var elt=content.document.getElementById('text');elt.focus();elt.select();";
       break;
     case 1: // test for input text
       defaultData = "Test for selection change event";
       pasteData = "from parent ";
-      iframe.src = "data:text/html,<html><body>" +
+      iframeInner.src = "data:text/html,<html><body>" +
                    "<input type='text' id='text' value='" + defaultData + "'>" +
                    "</body>" +
                    "</html>";
       stateMeaning = " (test: <input type=text>)";
       focusScript = "var elt=content.document.getElementById('text');elt.focus();elt.select();";
       break;
     case 2: // test for input number
       defaultData = "12345";
       pasteData = "67890";
-      iframe.src = "data:text/html,<html><body>" +
+      iframeInner.src = "data:text/html,<html><body>" +
                    "<input type='number' id='text' value='" + defaultData + "'>" +
                    "</body>" +
                    "</html>";
       stateMeaning = " (test: <input type=number>)";
       focusScript = "var elt=content.document.getElementById('text');elt.focus();elt.select();";
       break;
     case 3: // test for div contenteditable
       defaultData = "Test for selection change event";
       pasteData = "from parent ";
-      iframe.src = "data:text/html,<html><body>" +
+      iframeInner.src = "data:text/html,<html><body>" +
                    "<div contenteditable='true' id='text'>" + defaultData + "</div>" +
                    "</body>" +
                    "</html>";
       stateMeaning = " (test: content editable div)";
       focusScript = "var elt=content.document.getElementById('text');elt.focus();";
       break;
     case 4: // test for normal div
-      SimpleTest.finish();
-      return;
       defaultData = "Test for selection change event";
       pasteData = "from parent ";
-      iframe.src = "data:text/html,<html><body>" +
+      iframeInner.src = "data:text/html,<html><body>" +
                    "<div id='text'>" + defaultData + "</div>" +
                    "</body>" +
                    "</html>";
       stateMeaning = " (test: normal div)";
       focusScript = "var elt=content.document.getElementById('text');elt.focus();";
       break;
     case 5: // test for normal div with designMode:on
       defaultData = "Test for selection change event";
       pasteData = "from parent ";
-      iframe.src = "data:text/html,<html><body id='text'>" +
+      iframeInner.src = "data:text/html,<html><body id='text'>" +
                    defaultData +
                    "</body>" +
                    "<script>document.designMode='on';</script>" +
                    "</html>";
       stateMeaning = " (test: normal div with designMode:on)";
       focusScript = "var elt=content.document.getElementById('text');elt.focus();";
       break;
     default:
-      SimpleTest.finish();
+      if (createEmbededFrame || browserElementTestHelpers.getOOPByDefaultPref()) {
+        SimpleTest.finish();
+      } else {
+        createEmbededFrame = true;
+
+        // clean up and run test again.
+        document.body.removeChild(iframeOuter);
+        document.body.removeChild(gTextarea);
+        state = 0;
+        runTest();
+      }
       break;
   }
 }
 
+function isChildProcess() {
+  return SpecialPowers.Cc["@mozilla.org/xre/app-info;1"]
+                         .getService(SpecialPowers.Ci.nsIXULRuntime)
+                         .processType != SpecialPowers.Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
+}
+
 function testSelectAll(e) {
-  iframe.addEventListener("mozbrowserselectionstatechanged", function selectchangeforselectall(e) {
-    iframe.removeEventListener("mozbrowserselectionstatechanged", selectchangeforselectall, true);
-    ok(true, "got mozbrowserselectionstatechanged event." + stateMeaning);
-    ok(e.detail, "event.detail is not null." + stateMeaning);
-    ok(e.detail.width != 0, "event.detail.width is not zero" + stateMeaning);
-    ok(e.detail.height != 0, "event.detail.height is not zero" + stateMeaning);
-    SimpleTest.executeSoon(function() { testCopy1(e); });
-  }, true);
+  // Skip mozbrowser test if we're at child process.
+  if (!isChildProcess()) {
+    iframeOuter.addEventListener("mozbrowserselectionstatechanged", function selectchangeforselectall(e) {
+      iframeOuter.removeEventListener("mozbrowserselectionstatechanged", selectchangeforselectall, true);
+      ok(true, "got mozbrowserselectionstatechanged event." + stateMeaning);
+      ok(e.detail, "event.detail is not null." + stateMeaning);
+      ok(e.detail.width != 0, "event.detail.width is not zero" + stateMeaning);
+      ok(e.detail.height != 0, "event.detail.height is not zero" + stateMeaning);
+      SimpleTest.executeSoon(function() { testCopy1(e); });
+    }, true);
+  }
 
   mm.addMessageListener('content-focus', function messageforfocus(msg) {
     mm.removeMessageListener('content-focus', messageforfocus);
     // test selectall command, after calling this the selectionstatechanged event should be fired.
     doCommand('selectall');
+    if (isChildProcess()) {
+      SimpleTest.executeSoon(function() { testCopy1(e); });
+    }
   });
 
   mm.loadFrameScript(getScriptForSetFocus(), false);
 }
 
 function testCopy1(e) {
   // Right now we're at "selectall" state, so we can test copy commnad by
   // calling doCommand
@@ -237,19 +277,21 @@ function testCut1(e) {
     nextTest(true);
   }
 
   let fail = function() {
     nextTest(false);
   }
 
   let compareData = pasteData;
-  if (state == 3 && browserElementTestHelpers.getOOPByDefaultPref()) {
-    // Something weird when we doCommand with content editable element in OOP.
-    // Always true in this case
+  // Something weird when we doCommand with content editable element in OOP.
+  // Always true in this case
+  // Normal div case cannot cut, always true as well.
+  if ((state == 3 && browserElementTestHelpers.getOOPByDefaultPref()) ||
+      state == 4) {
     compareData = function() { return true; }
   }
 
   SimpleTest.waitForClipboard(compareData, setup, success, fail);
 }
 
 function testCut2(e) {
   mm.addMessageListener('content-text', function messageforcut(msg) {
@@ -266,9 +308,20 @@ function testCut2(e) {
 
     state++;
     dispatchTest(e);
   });
 
   mm.loadFrameScript(getScriptForGetContent(), false);
 }
 
-addEventListener('testready', runTest);
+// Give our origin permission to open browsers, and remove it when the test is complete.
+var principal = SpecialPowers.wrap(document).nodePrincipal;
+var context = { 'url': SpecialPowers.wrap(principal.URI).spec,
+                'appId': principal.appId,
+                'isInBrowserElement': true };
+
+addEventListener('testready', function() {
+  SpecialPowers.pushPermissions([
+    {'type': 'browser', 'allow': 1, 'context': context}
+  ], runTest);
+});
+
new file mode 100644
--- /dev/null
+++ b/dom/browser-element/mochitest/file_NestedFramesOuter_CopyPaste.html
@@ -0,0 +1,21 @@
+<html>
+<body>
+<p>file_NestedFramesOuter_CopyPaste.html</p>
+<script>
+
+addEventListener('load', function() {
+  setTimeout(createIframe, 0);
+});
+
+function createIframe()
+{
+  var iframe = document.createElement('iframe');
+  iframe.setAttribute('id', 'iframeInner');
+  iframe.setAttribute('mozbrowser', true);
+  iframe.setAttribute('remote', 'false');
+  document.body.appendChild(iframe);
+}
+
+</script>
+</body>
+</html>
--- a/dom/browser-element/mochitest/mochitest.ini
+++ b/dom/browser-element/mochitest/mochitest.ini
@@ -108,16 +108,17 @@ support-files =
   file_download_bin.sjs
   file_empty.html
   file_empty_script.js
   file_focus.html
   file_http_401_response.sjs
   file_inputmethod.html
   file_post_request.html
   file_wyciwyg.html
+  file_NestedFramesOuter_CopyPaste.html
 
 # Note: browserElementTestHelpers.js looks at the test's filename to determine
 # whether the test should be OOP.  "_oop_" signals OOP, "_inproc_" signals in
 # process.  Default is OOP.
 [test_browserElement_NoAttr.html]
 [test_browserElement_NoPref.html]
 [test_browserElement_NoPermission.html]
 [test_browserElement_inproc_Alert.html]
--- a/dom/canvas/CanvasRenderingContext2D.cpp
+++ b/dom/canvas/CanvasRenderingContext2D.cpp
@@ -573,17 +573,17 @@ public:
     mShadowTarget.reset();
   }
 
   operator DrawTarget*()
   {
     return mTarget;
   }
 
-  DrawTarget* operator->()
+  DrawTarget* operator->() MOZ_NO_ADDREF_RELEASE_ON_RETURN
   {
     return mTarget;
   }
 
 private:
 
   mgfx::Rect
   MaxSourceNeededBoundsForFilter(const mgfx::Rect& aDestBounds, CanvasRenderingContext2D *ctx)
@@ -3247,33 +3247,50 @@ CanvasRenderingContext2D::GetHitRegionRe
   return false;
 }
 
 /**
  * Used for nsBidiPresUtils::ProcessText
  */
 struct MOZ_STACK_CLASS CanvasBidiProcessor : public nsBidiPresUtils::BidiProcessor
 {
+  CanvasBidiProcessor()
+    : nsBidiPresUtils::BidiProcessor()
+  {
+    if (Preferences::GetBool(GFX_MISSING_FONTS_NOTIFY_PREF)) {
+      mMissingFonts = new gfxMissingFontRecorder();
+    }
+  }
+
+  ~CanvasBidiProcessor()
+  {
+    // notify front-end code if we encountered missing glyphs in any script
+    if (mMissingFonts) {
+      mMissingFonts->Flush();
+    }
+  }
+
   typedef CanvasRenderingContext2D::ContextState ContextState;
 
   virtual void SetText(const char16_t* text, int32_t length, nsBidiDirection direction)
   {
     mFontgrp->UpdateUserFonts(); // ensure user font generation is current
     // adjust flags for current direction run
     uint32_t flags = mTextRunFlags;
     if (direction == NSBIDI_RTL) {
       flags |= gfxTextRunFactory::TEXT_IS_RTL;
     } else {
       flags &= ~gfxTextRunFactory::TEXT_IS_RTL;
     }
     mTextRun = mFontgrp->MakeTextRun(text,
                                      length,
                                      mThebes,
                                      mAppUnitsPerDevPixel,
-                                     flags);
+                                     flags,
+                                     mMissingFonts);
   }
 
   virtual nscoord GetWidth()
   {
     gfxTextRun::Metrics textRunMetrics = mTextRun->MeasureText(0,
                                                                mTextRun->GetLength(),
                                                                mDoMeasureBoundingBox ?
                                                                  gfxFont::TIGHT_INK_EXTENTS :
@@ -3509,16 +3526,20 @@ struct MOZ_STACK_CLASS CanvasBidiProcess
   CanvasRenderingContext2D *mCtx;
 
   // position of the left side of the string, alphabetic baseline
   gfxPoint mPt;
 
   // current font
   gfxFontGroup* mFontgrp;
 
+  // to record any unsupported characters found in the text,
+  // and notify front-end if it is interested
+  nsAutoPtr<gfxMissingFontRecorder> mMissingFonts;
+
   // dev pixel conversion factor
   int32_t mAppUnitsPerDevPixel;
 
   // operation (fill or stroke)
   CanvasRenderingContext2D::TextDrawOperation mOp;
 
   // context state
   ContextState *mState;
--- a/dom/canvas/WebGLContextGL.cpp
+++ b/dom/canvas/WebGLContextGL.cpp
@@ -3370,19 +3370,21 @@ WebGLContext::CompileShader(WebGLShader*
 
         if (!lenWithNull) {
             // Error in ShGetInfo.
             shader->SetTranslationFailure(NS_LITERAL_CSTRING("Internal error: failed to get shader info log"));
         } else {
             size_t len = lenWithNull - 1;
 
             nsAutoCString info;
-            info.SetLength(len); // Allocates len+1, for the null-term.
-            ShGetInfoLog(compiler, info.BeginWriting());
-
+            if (len) {
+                // Don't allocate or try to write to zero length string
+                info.SetLength(len); // Allocates len+1, for the null-term.
+                ShGetInfoLog(compiler, info.BeginWriting());
+            }
             shader->SetTranslationFailure(info);
         }
         ShDestruct(compiler);
         shader->SetCompileStatus(false);
         return;
     }
 
     size_t num_attributes = 0;
--- a/dom/canvas/WebGLObjectModel.h
+++ b/dom/canvas/WebGLObjectModel.h
@@ -214,17 +214,17 @@ public:
     T* get() const {
         return static_cast<T*>(mRawPtr);
     }
 
     operator T*() const {
         return get();
     }
 
-    T* operator->() const {
+    T* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN {
         MOZ_ASSERT(mRawPtr != 0, "You can't dereference a nullptr WebGLRefPtr with operator->()!");
         return get();
     }
 
     T& operator*() const {
         MOZ_ASSERT(mRawPtr != 0, "You can't dereference a nullptr WebGLRefPtr with operator*()!");
         return *get();
     }
--- a/dom/datastore/DataStoreDB.cpp
+++ b/dom/datastore/DataStoreDB.cpp
@@ -38,17 +38,17 @@ class VersionChangeListener MOZ_FINAL : 
 public:
   NS_DECL_ISUPPORTS
 
   explicit VersionChangeListener(IDBDatabase* aDatabase)
     : mDatabase(aDatabase)
   {}
 
   // nsIDOMEventListener
-  NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent)
+  NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent) MOZ_OVERRIDE
   {
     nsString type;
     nsresult rv = aEvent->GetType(type);
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
 
     if (!type.EqualsASCII("versionchange")) {
--- a/dom/datastore/DataStoreDB.h
+++ b/dom/datastore/DataStoreDB.h
@@ -38,17 +38,17 @@ public:
   nsresult Open(IDBTransactionMode aMode, const Sequence<nsString>& aDb,
                 DataStoreDBCallback* aCallback);
 
   nsresult Delete();
 
   indexedDB::IDBTransaction* Transaction() const;
 
   // nsIDOMEventListener
-  NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent);
+  NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent) MOZ_OVERRIDE;
 
 private:
   ~DataStoreDB();
 
   nsresult CreateFactoryIfNeeded();
 
   nsresult UpgradeSchema(nsIDOMEvent* aEvent);
 
--- a/dom/datastore/DataStoreRevision.h
+++ b/dom/datastore/DataStoreRevision.h
@@ -33,17 +33,17 @@ public:
 
   nsresult AddRevision(JSContext* aCx,
                        indexedDB::IDBObjectStore* aStore,
                        uint32_t aObjectId,
                        RevisionType aRevisionType,
                        DataStoreRevisionCallback* aCallback);
 
   // nsIDOMEventListener
-  NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent);
+  NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent) MOZ_OVERRIDE;
 
 private:
   ~DataStoreRevision() {}
   nsRefPtr<DataStoreRevisionCallback> mCallback;
   nsRefPtr<indexedDB::IDBRequest> mRequest;
   nsString mRevisionID;
 };
 
--- a/dom/fetch/Headers.h
+++ b/dom/fetch/Headers.h
@@ -105,17 +105,17 @@ public:
     return mInternalHeaders->Guard();
   }
 
   void SetGuard(HeadersGuardEnum aGuard, ErrorResult& aRv)
   {
     mInternalHeaders->SetGuard(aGuard, aRv);
   }
 
-  virtual JSObject* WrapObject(JSContext* aCx);
+  virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE;
   nsISupports* GetParentObject() const { return mOwner; }
 
 private:
   virtual ~Headers();
 
   InternalHeaders*
   GetInternalHeaders() const
   {
--- a/dom/fetch/Request.h
+++ b/dom/fetch/Request.h
@@ -31,17 +31,17 @@ class Request MOZ_FINAL : public nsISupp
 {
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(Request)
 
 public:
   Request(nsIGlobalObject* aOwner, InternalRequest* aRequest);
 
   JSObject*
-  WrapObject(JSContext* aCx)
+  WrapObject(JSContext* aCx) MOZ_OVERRIDE
   {
     return RequestBinding::Wrap(aCx, this);
   }
 
   void
   GetUrl(DOMString& aUrl) const
   {
     aUrl.AsAString() = NS_ConvertUTF8toUTF16(mRequest->mURL);
--- a/dom/fetch/Response.h
+++ b/dom/fetch/Response.h
@@ -32,17 +32,17 @@ class Response MOZ_FINAL : public nsISup
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(Response)
 
 public:
   Response(nsIGlobalObject* aGlobal, InternalResponse* aInternalResponse);
 
   Response(const Response& aOther) MOZ_DELETE;
 
   JSObject*
-  WrapObject(JSContext* aCx)
+  WrapObject(JSContext* aCx) MOZ_OVERRIDE
   {
     return ResponseBinding::Wrap(aCx, this);
   }
 
   ResponseType
   Type() const
   {
     return mInternalResponse->Type();
--- a/dom/html/test/file_fullscreen-api.html
+++ b/dom/html/test/file_fullscreen-api.html
@@ -158,24 +158,66 @@ function enter4(event) {
 
   var n = container;
   do {
     ok(n.matches(":-moz-full-screen-ancestor"), "Ancestor " + n + " should match :-moz-full-screen-ancestor")
     n = n.parentNode;
   } while (n && n.matches);
     
   // Remove full-screen ancestor element from document, verify it stops being reported as current FSE.
-  addFullscreenChangeContinuation("exit", exit4);
+  addFullscreenChangeContinuation("exit", exit_to_arg_test_1);
   container.parentNode.removeChild(container);
   ok(!document.mozFullScreen, "36. Should exit full-screen mode after removing full-screen element ancestor from document");
   is(document.mozFullScreenElement, null, "37. Should not have a full-screen element again.");
 }
 
+function exit_to_arg_test_1(event) {
+  ok(!document.mozFullScreen, "Should have left full-screen mode (third time).");
+  addFullscreenChangeContinuation("enter", enter_from_arg_test_1);
+  var threw = false;
+  try {
+    fullScreenElement().mozRequestFullScreen(123);
+  } catch (e) {
+    threw = true;
+    // trigger normal fullscreen so that we continue
+    fullScreenElement().mozRequestFullScreen();
+  }
+  ok(!threw, "mozRequestFullScreen with bogus arg (123) shouldn't throw exception");
+}
+
+function enter_from_arg_test_1(event) {
+  ok(document.mozFullScreen, "Should have entered full-screen after calling with bogus (ignored) argument (fourth time)");
+  addFullscreenChangeContinuation("exit", exit_to_arg_test_2);
+  document.mozCancelFullScreen();
+  ok(!document.mozFullScreen, "Should have left full-screen mode.");
+}
+
+function exit_to_arg_test_2(event) {
+  ok(!document.mozFullScreen, "Should have left full-screen mode (fourth time).");
+  addFullscreenChangeContinuation("enter", enter_from_arg_test_2);
+  var threw = false;
+  try {
+    fullScreenElement().mozRequestFullScreen({ vrDisplay: null });
+  } catch (e) {
+    threw = true;
+    // trigger normal fullscreen so that we continue
+    fullScreenElement().mozRequestFullScreen();
+  }
+  ok(!threw, "mozRequestFullScreen with { vrDisplay: null } shouldn't throw exception");
+}
+
+function enter_from_arg_test_2(event) {
+  ok(document.mozFullScreen, "Should have entered full-screen after calling with vrDisplay null argument (fifth time)");
+  addFullscreenChangeContinuation("exit", exit4);
+  document.mozCancelFullScreen();
+  ok(!document.mozFullScreen, "Should have left full-screen mode.");
+}
+
 function exit4(event) {
-  ok(!document.mozFullScreen, "38. Should be back in non-full-screen mode (third time)");
+  ok(!document.mozFullScreen, "38. Should be back in non-full-screen mode (fifth time)");
   setRequireTrustedContext(true);
 
   addFullscreenErrorContinuation(error2);
   fullScreenElement().mozRequestFullScreen();
 }
 
 function error2(event) {
   ok(!document.mozFullScreen, "Should still be in normal mode, because calling context isn't trusted.");
--- a/dom/indexedDB/ActorsParent.cpp
+++ b/dom/indexedDB/ActorsParent.cpp
@@ -3662,17 +3662,17 @@ public:
   { }
 
   operator mozIStorageStatement*()
   {
     return mStatement;
   }
 
   mozIStorageStatement*
-  operator->()
+  operator->() MOZ_NO_ADDREF_RELEASE_ON_RETURN
   {
     MOZ_ASSERT(mStatement);
     return mStatement;
   }
 
   void
   Reset()
   {
@@ -4072,17 +4072,17 @@ struct FactoryOp::MaybeBlockedDatabaseIn
 
   bool
   operator<(const MaybeBlockedDatabaseInfo& aOther) const
   {
     return mDatabase < aOther.mDatabase;
   }
 
   Database*
-  operator->()
+  operator->() MOZ_NO_ADDREF_RELEASE_ON_RETURN
   {
     return mDatabase;
   }
 };
 
 class OpenDatabaseOp MOZ_FINAL
   : public FactoryOp
 {
--- a/dom/interfaces/core/nsIDOMElement.idl
+++ b/dom/interfaces/core/nsIDOMElement.idl
@@ -2,16 +2,25 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsIDOMNode.idl"
 
 interface nsIDOMMozNamedAttrMap;
 
+%{C++
+// Undo the windows.h damage
+#undef GetMessage
+#undef CreateEvent
+#undef GetClassName
+#undef GetBinaryType
+#undef RemoveDirectory
+%}
+
 /**
  * The nsIDOMElement interface represents an element in an HTML or 
  * XML document. 
  *
  * For more information on this interface please see 
  * http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#interface-element
  */
 
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -1602,16 +1602,35 @@ ContentParent::OnChannelError()
 #ifdef MOZ_NUWA_PROCESS
     // Handle app or Nuwa process exit before normal channel error handling.
     PreallocatedProcessManager::MaybeForgetSpare(this);
 #endif
     PContentParent::OnChannelError();
 }
 
 void
+ContentParent::OnBeginSyncTransaction() {
+    if (XRE_GetProcessType() == GeckoProcessType_Default) {
+        nsCOMPtr<nsIConsoleService> console(do_GetService(NS_CONSOLESERVICE_CONTRACTID));
+        JSContext *cx = nsContentUtils::GetCurrentJSContext();
+        if (console && cx) {
+            nsAutoString filename;
+            uint32_t lineno = 0;
+            nsJSUtils::GetCallingLocation(cx, filename, &lineno);
+            nsCOMPtr<nsIScriptError> error(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
+            error->Init(NS_LITERAL_STRING("unsafe CPOW usage"), filename, EmptyString(),
+                        lineno, 0, nsIScriptError::warningFlag, "chrome javascript");
+            console->LogMessage(error);
+        } else {
+            NS_WARNING("Unsafe synchronous IPC message");
+        }
+    }
+}
+
+void
 ContentParent::OnChannelConnected(int32_t pid)
 {
     ProcessHandle handle;
     if (!base::OpenPrivilegedProcessHandle(pid, &handle)) {
         NS_WARNING("Can't open handle to child process.");
     }
     else {
         // we need to close the existing handle before setting a new one.
--- a/dom/ipc/ContentParent.h
+++ b/dom/ipc/ContentParent.h
@@ -248,16 +248,18 @@ public:
      * about this name: It might not be unique, apps can spoof special names,
      * etc.  So please don't use this name to make any decisions about the
      * ContentParent based on the value returned here.
      */
     void FriendlyName(nsAString& aName, bool aAnonymize = false);
 
     virtual void OnChannelError() MOZ_OVERRIDE;
 
+    virtual void OnBeginSyncTransaction() MOZ_OVERRIDE;
+
     virtual PCrashReporterParent*
     AllocPCrashReporterParent(const NativeThreadId& tid,
                               const uint32_t& processType) MOZ_OVERRIDE;
     virtual bool
     RecvPCrashReporterConstructor(PCrashReporterParent* actor,
                                   const NativeThreadId& tid,
                                   const uint32_t& processType) MOZ_OVERRIDE;
 
--- a/dom/media/MediaDecoder.cpp
+++ b/dom/media/MediaDecoder.cpp
@@ -1556,17 +1556,20 @@ void MediaDecoder::UnpinForSeek()
   }
   mPinnedForSeek = false;
   resource->Unpin();
 }
 
 bool MediaDecoder::CanPlayThrough()
 {
   Statistics stats = GetStatistics();
-  if ((stats.mTotalBytes < 0 && stats.mDownloadRateReliable) ||
+
+  NS_ASSERTION(mDecoderStateMachine, "CanPlayThrough should have state machine!");
+  if (mDecoderStateMachine->IsRealTime() ||
+      (stats.mTotalBytes < 0 && stats.mDownloadRateReliable) ||
       (stats.mTotalBytes >= 0 && stats.mTotalBytes == stats.mDownloadPosition)) {
     return true;
   }
   if (!stats.mDownloadRateReliable || !stats.mPlaybackRateReliable) {
     return false;
   }
   int64_t bytesToDownload = stats.mTotalBytes - stats.mDownloadPosition;
   int64_t bytesToPlayback = stats.mTotalBytes - stats.mPlaybackPosition;
--- a/dom/media/MediaDecoderStateMachine.cpp
+++ b/dom/media/MediaDecoderStateMachine.cpp
@@ -224,18 +224,18 @@ MediaDecoderStateMachine::MediaDecoderSt
   mDecodingFrozenAtStateDecoding(false)
 {
   MOZ_COUNT_CTOR(MediaDecoderStateMachine);
   NS_ASSERTION(NS_IsMainThread(), "Should be on main thread.");
 
   mAmpleVideoFrames =
     std::max<uint32_t>(Preferences::GetUint("media.video-queue.default-size", 10), 3);
 
-  mBufferingWait = mScheduler->IsRealTime() ? 0 : 30;
-  mLowDataThresholdUsecs = mScheduler->IsRealTime() ? 0 : LOW_DATA_THRESHOLD_USECS;
+  mBufferingWait = IsRealTime() ? 0 : 30;
+  mLowDataThresholdUsecs = IsRealTime() ? 0 : LOW_DATA_THRESHOLD_USECS;
 
 #ifdef XP_WIN
   // Ensure high precision timers are enabled on Windows, otherwise the state
   // machine thread isn't woken up at reliable intervals to set the next frame,
   // and we drop frames while painting. Note that multiple calls to this
   // function per-process is OK, provided each call is matched by a corresponding
   // timeEndPeriod() call.
   timeBeginPeriod(1);
@@ -1346,16 +1346,20 @@ double MediaDecoderStateMachine::GetCurr
   NS_ASSERTION(NS_IsMainThread() ||
                OnStateMachineThread() ||
                OnDecodeThread(),
                "Should be on main, decode, or state machine thread.");
 
   return static_cast<double>(mCurrentFrameTime) / static_cast<double>(USECS_PER_S);
 }
 
+bool MediaDecoderStateMachine::IsRealTime() const {
+  return mScheduler->IsRealTime();
+}
+
 int64_t MediaDecoderStateMachine::GetDuration()
 {
   AssertCurrentThreadInMonitor();
 
   if (mEndTime == -1 || mStartTime == -1)
     return -1;
   return mEndTime - mStartTime;
 }
@@ -1983,16 +1987,22 @@ MediaDecoderStateMachine::StartAudioThre
 int64_t MediaDecoderStateMachine::AudioDecodedUsecs()
 {
   NS_ASSERTION(HasAudio(),
                "Should only call AudioDecodedUsecs() when we have audio");
   // The amount of audio we have decoded is the amount of audio data we've
   // already decoded and pushed to the hardware, plus the amount of audio
   // data waiting to be pushed to the hardware.
   int64_t pushed = (mAudioEndTime != -1) ? (mAudioEndTime - GetMediaTime()) : 0;
+
+  // Currently for real time streams, AudioQueue().Duration() produce
+  // wrong values (Bug 1114434), so we use frame counts to calculate duration.
+  if (IsRealTime()) {
+    return pushed + FramesToUsecs(AudioQueue().FrameCount(), mInfo.mAudio.mRate).value();
+  }
   return pushed + AudioQueue().Duration();
 }
 
 bool MediaDecoderStateMachine::HasLowDecodedData(int64_t aAudioUsecs)
 {
   AssertCurrentThreadInMonitor();
   MOZ_ASSERT(mReader->UseBufferingHeuristics());
   // We consider ourselves low on decoded data if we're low on audio,
@@ -2182,17 +2192,17 @@ MediaDecoderStateMachine::DecodeFirstFra
     AudioQueue().AddPopListener(decodeTask, DecodeTaskQueue());
   }
   if (HasVideo()) {
     RefPtr<nsIRunnable> decodeTask(
       NS_NewRunnableMethod(this, &MediaDecoderStateMachine::DispatchVideoDecodeTaskIfNeeded));
     VideoQueue().AddPopListener(decodeTask, DecodeTaskQueue());
   }
 
-  if (mScheduler->IsRealTime()) {
+  if (IsRealTime()) {
     SetStartTime(0);
     nsresult res = FinishDecodeFirstFrame();
     NS_ENSURE_SUCCESS(res, res);
   } else if (mDecodingFrozenAtStateMetadata) {
     SetStartTime(mStartTime);
     nsresult res = FinishDecodeFirstFrame();
     NS_ENSURE_SUCCESS(res, res);
   } else {
@@ -2221,17 +2231,17 @@ MediaDecoderStateMachine::FinishDecodeFi
   AssertCurrentThreadInMonitor();
   NS_ASSERTION(OnDecodeThread(), "Should be on decode thread.");
   DECODER_LOG("FinishDecodeFirstFrame");
 
   if (mState == DECODER_STATE_SHUTDOWN) {
     return NS_ERROR_FAILURE;
   }
 
-  if (!mScheduler->IsRealTime() && !mDecodingFrozenAtStateMetadata) {
+  if (!IsRealTime() && !mDecodingFrozenAtStateMetadata) {
     const VideoData* v = VideoQueue().PeekFront();
     const AudioData* a = AudioQueue().PeekFront();
     SetStartTime(mReader->ComputeStartTime(v, a));
     if (VideoQueue().GetSize()) {
       ReentrantMonitorAutoExit exitMon(mDecoder->GetReentrantMonitor());
       RenderVideoFrame(VideoQueue().PeekFront(), TimeStamp::Now());
     }
   }
@@ -2834,17 +2844,17 @@ void MediaDecoderStateMachine::RenderVid
   VERBOSE_LOG("playing video frame %lld (queued=%i, state-machine=%i, decoder-queued=%i)",
               aData->mTime, VideoQueue().GetSize() + mReader->SizeOfVideoQueueInFrames(),
               VideoQueue().GetSize(), mReader->SizeOfVideoQueueInFrames());
 
   VideoFrameContainer* container = mDecoder->GetVideoFrameContainer();
   if (container) {
     container->SetCurrentFrame(ThebesIntSize(aData->mDisplay), aData->mImage,
                                aTarget);
-    MOZ_ASSERT(container->GetFrameDelay() >= 0 || mScheduler->IsRealTime());
+    MOZ_ASSERT(container->GetFrameDelay() >= 0 || IsRealTime());
   }
 }
 
 void MediaDecoderStateMachine::ResyncAudioClock()
 {
   AssertCurrentThreadInMonitor();
   if (IsPlaying()) {
     SetPlayStartTime(TimeStamp::Now());
@@ -2932,17 +2942,17 @@ void MediaDecoderStateMachine::AdvanceFr
   int64_t remainingTime = AUDIO_DURATION_USECS;
   NS_ASSERTION(clock_time >= mStartTime, "Should have positive clock time.");
   nsRefPtr<VideoData> currentFrame;
   if (VideoQueue().GetSize() > 0) {
     VideoData* frame = VideoQueue().PeekFront();
 #ifdef PR_LOGGING
     int32_t droppedFrames = 0;
 #endif
-    while (mScheduler->IsRealTime() || clock_time >= frame->mTime) {
+    while (IsRealTime() || clock_time >= frame->mTime) {
       mVideoFrameEndTime = frame->GetEndTime();
 #ifdef PR_LOGGING
       if (currentFrame) {
         VERBOSE_LOG("discarding video frame mTime=%lld clock_time=%lld (%d so far)",
                     currentFrame->mTime, clock_time, ++droppedFrames);
       }
 #endif
       currentFrame = frame;
@@ -3001,17 +3011,17 @@ void MediaDecoderStateMachine::AdvanceFr
     // Decode one frame and display it.
     int64_t delta = currentFrame->mTime - clock_time;
     TimeStamp presTime = nowTime + TimeDuration::FromMicroseconds(delta / mPlaybackRate);
     NS_ASSERTION(currentFrame->mTime >= mStartTime, "Should have positive frame time");
     // Filter out invalid frames by checking the frame time. FrameTime could be
     // zero if it's a initial frame.
     int64_t frameTime = currentFrame->mTime - mStartTime;
     if (frameTime > 0  || (frameTime == 0 && mPlayDuration == 0) ||
-        mScheduler->IsRealTime()) {
+        IsRealTime()) {
       ReentrantMonitorAutoExit exitMon(mDecoder->GetReentrantMonitor());
       // If we have video, we want to increment the clock in steps of the frame
       // duration.
       RenderVideoFrame(currentFrame, presTime);
     }
     // If we're no longer playing after dropping and reacquiring the lock,
     // playback must've been stopped on the decode thread (by a seek, for
     // example).  In that case, the current frame is probably out of date.
--- a/dom/media/MediaDecoderStateMachine.h
+++ b/dom/media/MediaDecoderStateMachine.h
@@ -160,16 +160,18 @@ public:
   // Check if the decoder needs to become dormant state.
   bool IsDormantNeeded();
   // Set/Unset dormant state.
   void SetDormant(bool aDormant);
   void Shutdown();
   void ShutdownReader();
   void FinishShutdown();
 
+  bool IsRealTime() const;
+
   // Called from the main thread to get the duration. The decoder monitor
   // must be obtained before calling this. It is in units of microseconds.
   int64_t GetDuration();
 
   // Called from the main thread to set the duration of the media resource
   // if it is able to be obtained via HTTP headers. Called from the
   // state machine thread to set the duration if it is obtained from the
   // media metadata. The decoder monitor must be obtained before calling this.
--- a/dom/media/MediaResource.h
+++ b/dom/media/MediaResource.h
@@ -739,17 +739,17 @@ class MOZ_STACK_CLASS AutoPinned {
     mResource->Pin();
   }
 
   ~AutoPinned() {
     mResource->Unpin();
   }
 
   operator T*() const { return mResource; }
-  T* operator->() const { return mResource; }
+  T* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN { return mResource; }
 
 private:
   T* mResource;
   MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
 } // namespace mozilla
 
--- a/dom/media/eme/CDMProxy.h
+++ b/dom/media/eme/CDMProxy.h
@@ -275,17 +275,17 @@ private:
       return !mPtr;
     }
 
     void Clear() {
       MOZ_ASSERT(NS_IsMainThread());
       mPtr = nullptr;
     }
 
-    Type* operator->() const {
+    Type* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN {
       MOZ_ASSERT(NS_IsMainThread());
       return mPtr;
     }
   private:
     Type* mPtr;
   };
 
   // Our reference back to the MediaKeys object.
--- a/dom/media/gmp/GMPParent.cpp
+++ b/dom/media/gmp/GMPParent.cpp
@@ -57,17 +57,16 @@ namespace gmp {
 
 GMPParent::GMPParent()
   : mState(GMPStateNotLoaded)
   , mProcess(nullptr)
   , mDeleteProcessOnlyOnUnload(false)
   , mAbnormalShutdownInProgress(false)
   , mAsyncShutdownRequired(false)
   , mAsyncShutdownInProgress(false)
-  , mHasAccessedStorage(false)
 {
 }
 
 GMPParent::~GMPParent()
 {
   // Can't Close or Destroy the process here, since destruction is MainThread only
   MOZ_ASSERT(NS_IsMainThread());
 }
@@ -692,22 +691,16 @@ GMPParent::ActorDestroy(ActorDestroyReas
     // infinitely if we do.
     MOZ_ASSERT(mState == GMPStateClosing);
     DeleteProcess();
     // Note: final destruction will be Dispatched to ourself
     mService->ReAddOnGMPThread(self);
   }
 }
 
-bool
-GMPParent::HasAccessedStorage() const
-{
-  return mHasAccessedStorage;
-}
-
 mozilla::dom::PCrashReporterParent*
 GMPParent::AllocPCrashReporterParent(const NativeThreadId& aThread)
 {
 #ifndef MOZ_CRASHREPORTER
   MOZ_ASSERT(false, "Should only be sent if crash reporting is enabled.");
 #endif
   CrashReporterParent* cr = new CrashReporterParent();
   cr->SetChildData(aThread, GeckoProcessType_GMPlugin);
@@ -804,17 +797,16 @@ GMPParent::DeallocPGMPStorageParent(PGMP
 
 bool
 GMPParent::RecvPGMPStorageConstructor(PGMPStorageParent* aActor)
 {
   GMPStorageParent* p  = (GMPStorageParent*)aActor;
   if (NS_WARN_IF(NS_FAILED(p->Init()))) {
     return false;
   }
-  mHasAccessedStorage = true;
   return true;
 }
 
 bool
 GMPParent::RecvPGMPTimerConstructor(PGMPTimerParent* actor)
 {
   return true;
 }
--- a/dom/media/gmp/GMPParent.h
+++ b/dom/media/gmp/GMPParent.h
@@ -108,16 +108,17 @@ public:
   // Plugins are associated with an NodeIds by calling SetNodeId() before
   // loading.
   //
   // If a plugin has no NodeId specified and it is loaded, it is assumed to
   // be shared across NodeIds.
 
   // Specifies that a GMP can only work with the specified NodeIds.
   void SetNodeId(const nsACString& aNodeId);
+  const nsACString& GetNodeId() const { return mNodeId; }
 
   // Returns true if a plugin can be or is being used across multiple NodeIds.
   bool CanBeSharedCrossNodeIds() const;
 
   // A GMP can be used from a NodeId if it's already been set to work with
   // that NodeId, or if it's not been set to work with any NodeId and has
   // not yet been loaded (i.e. it's not shared across NodeIds).
   bool CanBeUsedFrom(const nsACString& aNodeId) const;
@@ -126,18 +127,16 @@ public:
     return nsCOMPtr<nsIFile>(mDirectory).forget();
   }
 
   // GMPSharedMem
   virtual void CheckThread() MOZ_OVERRIDE;
 
   void AbortAsyncShutdown();
 
-  bool HasAccessedStorage() const;
-
 private:
   ~GMPParent();
   nsRefPtr<GeckoMediaPluginService> mService;
   bool EnsureProcessLoaded();
   nsresult ReadGMPMetaData();
 #ifdef MOZ_CRASHREPORTER
   void WriteExtraDataForMinidump(CrashReporter::AnnotationTable& notes);
   void GetCrashID(nsString& aResult);
@@ -192,15 +191,14 @@ private:
   nsCOMPtr<nsIThread> mGMPThread;
   nsCOMPtr<nsITimer> mAsyncShutdownTimeout; // GMP Thread only.
   // NodeId the plugin is assigned to, or empty if the the plugin is not
   // assigned to a NodeId.
   nsAutoCString mNodeId;
 
   bool mAsyncShutdownRequired;
   bool mAsyncShutdownInProgress;
-  bool mHasAccessedStorage;
 };
 
 } // namespace gmp
 } // namespace mozilla
 
 #endif // GMPParent_h_
--- a/dom/media/gmp/GMPService.cpp
+++ b/dom/media/gmp/GMPService.cpp
@@ -27,16 +27,17 @@
 #if defined(XP_LINUX) && defined(MOZ_GMP_SANDBOX)
 #include "mozilla/SandboxInfo.h"
 #endif
 #include "nsAppDirectoryServiceDefs.h"
 #include "nsDirectoryServiceUtils.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsHashKeys.h"
 #include "nsIFile.h"
+#include "nsISimpleEnumerator.h"
 
 namespace mozilla {
 
 #ifdef LOG
 #undef LOG
 #endif
 
 #ifdef PR_LOGGING
@@ -58,16 +59,17 @@ GetGMPLog()
 
 #ifdef __CLASS__
 #undef __CLASS__
 #endif
 #define __CLASS__ "GMPService"
 
 namespace gmp {
 
+static const uint32_t NodeIdSaltLength = 32;
 static StaticRefPtr<GeckoMediaPluginService> sSingletonService;
 
 class GMPServiceCreateHelper MOZ_FINAL : public nsRunnable
 {
   nsRefPtr<GeckoMediaPluginService> mService;
 
 public:
   static already_AddRefed<GeckoMediaPluginService>
@@ -318,28 +320,35 @@ GeckoMediaPluginService::Observe(nsISupp
   } else if (!strcmp("last-pb-context-exited", aTopic)) {
     // When Private Browsing mode exits, all we need to do is clear
     // mTempNodeIds. This drops all the node ids we've cached in memory
     // for PB origin-pairs. If we try to open an origin-pair for non-PB
     // mode, we'll get the NodeId salt stored on-disk, and if we try to
     // open a PB mode origin-pair, we'll re-generate new salt.
     mTempNodeIds.Clear();
   } else if (!strcmp("gmp-clear-storage", aTopic)) {
-    nsCOMPtr<nsIThread> thread;
-    nsresult rv = GetThread(getter_AddRefs(thread));
-    if (NS_FAILED(rv)) {
-      return rv;
-    }
-    thread->Dispatch(
-      NS_NewRunnableMethod(this, &GeckoMediaPluginService::ClearStorage),
-      NS_DISPATCH_NORMAL);
+    nsresult rv = GMPDispatch(
+      NS_NewRunnableMethod(this, &GeckoMediaPluginService::ClearStorage));
+    NS_ENSURE_SUCCESS(rv, rv);
   }
   return NS_OK;
 }
 
+nsresult
+GeckoMediaPluginService::GMPDispatch(nsIRunnable* event, uint32_t flags)
+{
+  nsCOMPtr<nsIRunnable> r(event);
+  nsCOMPtr<nsIThread> thread;
+  nsresult rv = GetThread(getter_AddRefs(thread));
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+  return thread->Dispatch(r, flags);
+}
+
 // always call with getter_AddRefs, because it does
 NS_IMETHODIMP
 GeckoMediaPluginService::GetThread(nsIThread** aThread)
 {
   MOZ_ASSERT(aThread);
 
   // This can be called from any thread.
   MutexAutoLock lock(mMutex);
@@ -626,38 +635,24 @@ GeckoMediaPluginService::PathRunnable::R
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 GeckoMediaPluginService::AddPluginDirectory(const nsAString& aDirectory)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  nsCOMPtr<nsIThread> thread;
-  nsresult rv = GetThread(getter_AddRefs(thread));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-  nsCOMPtr<nsIRunnable> r = new PathRunnable(this, aDirectory, true);
-  thread->Dispatch(r, NS_DISPATCH_NORMAL);
-  return NS_OK;
+  return GMPDispatch(new PathRunnable(this, aDirectory, true));
 }
 
 NS_IMETHODIMP
 GeckoMediaPluginService::RemovePluginDirectory(const nsAString& aDirectory)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  nsCOMPtr<nsIThread> thread;
-  nsresult rv = GetThread(getter_AddRefs(thread));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-  nsCOMPtr<nsIRunnable> r = new PathRunnable(this, aDirectory, false);
-  thread->Dispatch(r, NS_DISPATCH_NORMAL);
-  return NS_OK;
+  return GMPDispatch(new PathRunnable(this, aDirectory, false));
 }
 
 class DummyRunnable : public nsRunnable {
 public:
   NS_IMETHOD Run() { return NS_OK; }
 };
 
 NS_IMETHODIMP
@@ -671,22 +666,18 @@ GeckoMediaPluginService::HasPluginForAPI
   const char* env = nullptr;
   if (!mScannedPluginOnDisk && (env = PR_GetEnv("MOZ_GMP_PATH")) && *env) {
     // We have a MOZ_GMP_PATH environment variable which may specify the
     // location of plugins to load, and we haven't yet scanned the disk to
     // see if there are plugins there. Get the GMP thread, which will
     // cause an event to be dispatched to which scans for plugins. We
     // dispatch a sync event to the GMP thread here in order to wait until
     // after the GMP thread has scanned any paths in MOZ_GMP_PATH.
-    nsCOMPtr<nsIThread> thread;
-    nsresult rv = GetThread(getter_AddRefs(thread));
-    if (NS_FAILED(rv)) {
-      return rv;
-    }
-    thread->Dispatch(new DummyRunnable(), NS_DISPATCH_SYNC);
+    nsresult rv = GMPDispatch(new DummyRunnable(), NS_DISPATCH_SYNC);
+    NS_ENSURE_SUCCESS(rv, rv);
     MOZ_ASSERT(mScannedPluginOnDisk, "Should have scanned MOZ_GMP_PATH by now");
   }
 
   {
     MutexAutoLock lock(mMutex);
     nsCString api(aAPI);
     GMPParent* gmp = FindPluginForAPIFrom(0, api, *aTags, nullptr);
     *aResult = (gmp != nullptr);
@@ -974,16 +965,24 @@ ReadFromFile(nsIFile* aPath,
   PR_Close(f);
   if (NS_WARN_IF(len != size)) {
     return NS_ERROR_FAILURE;
   }
 
   return NS_OK;
 }
 
+static nsresult
+ReadSalt(nsIFile* aPath, nsCString& aOutData)
+{
+  return ReadFromFile(aPath, NS_LITERAL_CSTRING("salt"),
+                      aOutData, NodeIdSaltLength);
+
+}
+
 NS_IMETHODIMP
 GeckoMediaPluginService::IsPersistentStorageAllowed(const nsACString& aNodeId,
                                                     bool* aOutAllowed)
 {
   MOZ_ASSERT(NS_GetCurrentThread() == mGMPThread);
   NS_ENSURE_ARG(aOutAllowed);
   *aOutAllowed = mPersistentStorageAllowed.Get(aNodeId);
   return NS_OK;
@@ -1002,17 +1001,16 @@ GeckoMediaPluginService::GetNodeId(const
        (aInPrivateBrowsing ? "PrivateBrowsing" : "NonPrivateBrowsing")));
 
 #ifdef MOZ_WIDGET_GONK
   NS_WARNING("GeckoMediaPluginService::GetNodeId Not implemented on B2G");
   return NS_ERROR_NOT_IMPLEMENTED;
 #endif
 
   nsresult rv;
-  const uint32_t NodeIdSaltLength = 32;
 
   if (aOrigin.EqualsLiteral("null") ||
       aOrigin.IsEmpty() ||
       aTopLevelOrigin.EqualsLiteral("null") ||
       aTopLevelOrigin.IsEmpty()) {
     // At least one of the (origin, topLevelOrigin) is null or empty;
     // probably a local file. Generate a random node id, and don't store
     // it so that the GMP's storage is temporary and not shared.
@@ -1126,89 +1124,221 @@ GeckoMediaPluginService::GetNodeId(const
     rv = WriteToFile(path,
                      NS_LITERAL_CSTRING("topLevelOrigin"),
                      NS_ConvertUTF16toUTF8(aTopLevelOrigin));
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
 
   } else {
-    rv = ReadFromFile(path,
-                      NS_LITERAL_CSTRING("salt"),
-                      salt,
-                      NodeIdSaltLength);
+    rv = ReadSalt(path, salt);
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
   }
 
   aOutId = salt;
   mPersistentStorageAllowed.Put(salt, true);
 
   return NS_OK;
 }
 
+static bool
+MatchOrigin(nsIFile* aPath, const nsACString& aOrigin)
+{
+  // http://en.wikipedia.org/wiki/Domain_Name_System#Domain_name_syntax
+  static const uint32_t MaxDomainLength = 253;
+
+  nsresult rv;
+  nsCString str;
+  rv = ReadFromFile(aPath, NS_LITERAL_CSTRING("origin"), str, MaxDomainLength);
+  if (NS_SUCCEEDED(rv) && aOrigin.Equals(str)) {
+    return true;
+  }
+  rv = ReadFromFile(aPath, NS_LITERAL_CSTRING("topLevelOrigin"), str, MaxDomainLength);
+  if (NS_SUCCEEDED(rv) && aOrigin.Equals(str)) {
+    return true;
+  }
+  return false;
+}
+
+template<typename T> static void
+KillPlugins(const nsTArray<nsRefPtr<GMPParent>>& aPlugins,
+            Mutex& aMutex, T&& aFilter)
+{
+  // Shutdown the plugins when |aFilter| evaluates to true.
+  // After we clear storage data, node IDs will become invalid and shouldn't be
+  // used anymore. We need to kill plugins with such nodeIDs.
+  // Note: we can't shut them down while holding the lock,
+  // as the lock is not re-entrant and shutdown requires taking the lock.
+  // The plugin list is only edited on the GMP thread, so this should be OK.
+  nsTArray<nsRefPtr<GMPParent>> pluginsToKill;
+  {
+    MutexAutoLock lock(aMutex);
+    for (size_t i = 0; i < aPlugins.Length(); i++) {
+      nsRefPtr<GMPParent> parent(aPlugins[i]);
+      if (aFilter(parent)) {
+        pluginsToKill.AppendElement(parent);
+      }
+    }
+  }
+
+  for (size_t i = 0; i < pluginsToKill.Length(); i++) {
+    pluginsToKill[i]->CloseActive(false);
+    // Abort async shutdown because we're going to wipe the plugin's storage,
+    // so we don't want it writing more data in its async shutdown path.
+    pluginsToKill[i]->AbortAsyncShutdown();
+  }
+}
+
+static nsresult
+DeleteDir(nsIFile* aPath)
+{
+  bool exists = false;
+  nsresult rv = aPath->Exists(&exists);
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+  if (exists) {
+    return aPath->Remove(true);
+  }
+  return NS_OK;
+}
+
+struct NodeFilter {
+  explicit NodeFilter(const nsTArray<nsCString>& nodeIDs) : mNodeIDs(nodeIDs) {}
+  bool operator()(GMPParent* aParent) {
+    return mNodeIDs.Contains(aParent->GetNodeId());
+  }
+private:
+  const nsTArray<nsCString>& mNodeIDs;
+};
+
+void
+GeckoMediaPluginService::ForgetThisSiteOnGMPThread(const nsACString& aOrigin)
+{
+#define ERR_RET(x) NS_ENSURE_SUCCESS_VOID(x)
+#define ERR_CONT(x) if (NS_FAILED(x)) { continue; }
+
+  MOZ_ASSERT(NS_GetCurrentThread() == mGMPThread);
+  LOGD(("%s::%s: origin=%s", __CLASS__, __FUNCTION__, aOrigin.Data()));
+
+  nsresult rv;
+  nsCOMPtr<nsIFile> path;
+
+  // $profileDir/gmp/
+  ERR_RET(GetStorageDir(getter_AddRefs(path)));
+
+  // $profileDir/gmp/id/
+  ERR_RET(path->AppendNative(NS_LITERAL_CSTRING("id")));
+
+  // Iterate all sub-folders of $profileDir/gmp/id/
+  nsCOMPtr<nsISimpleEnumerator> iter;
+  ERR_RET(path->GetDirectoryEntries(getter_AddRefs(iter)));
+
+  bool hasMore = false;
+  nsTArray<nsCString> nodeIDsToClear;
+  while (NS_SUCCEEDED(iter->HasMoreElements(&hasMore)) && hasMore) {
+    nsCOMPtr<nsISupports> supports;
+    ERR_CONT(iter->GetNext(getter_AddRefs(supports)));
+
+    // $profileDir/gmp/id/$hash
+    nsCOMPtr<nsIFile> dirEntry(do_QueryInterface(supports, &rv));
+    ERR_CONT(rv);
+
+    // Skip non-directory files.
+    bool isDirectory = false;
+    ERR_CONT(dirEntry->IsDirectory(&isDirectory));
+    if (!isDirectory) {
+      continue;
+    }
+
+    // Check if origin or topLevelOrigin match the origin being forgotten.
+    if (!MatchOrigin(dirEntry, aOrigin)) {
+      continue;
+    }
+
+    nsAutoCString salt;
+    if (NS_SUCCEEDED(ReadSalt(dirEntry, salt))) {
+      // Keep node IDs to clear data/plugins associated with them later.
+      nodeIDsToClear.AppendElement(salt);
+      // Also remove node IDs from the table.
+      mPersistentStorageAllowed.Remove(salt);
+    }
+    // Now we can remove the directory for the origin pair.
+    if (NS_FAILED(dirEntry->Remove(true))) {
+      NS_WARNING("Failed to delete the directory for the origin pair");
+    }
+  }
+
+  // Kill plugins that have node IDs to be cleared.
+  KillPlugins(mPlugins, mMutex, NodeFilter(nodeIDsToClear));
+
+  // Clear all matching $profileDir/gmp/storage/$nodeId/
+  ERR_RET(GetStorageDir(getter_AddRefs(path)));
+  ERR_RET(path->AppendNative(NS_LITERAL_CSTRING("storage")));
+  for (size_t i = 0; i < nodeIDsToClear.Length(); i++) {
+    nsCOMPtr<nsIFile> dirEntry;
+    ERR_CONT(path->Clone(getter_AddRefs(dirEntry)));
+    ERR_CONT(dirEntry->AppendNative(nodeIDsToClear[i]));
+    if (NS_FAILED(DeleteDir(dirEntry))) {
+      NS_WARNING("Failed to delete GMP storage directory for the node");
+    }
+  }
+
+#undef ERR_RET
+#undef ERR_CONT
+}
+
+NS_IMETHODIMP
+GeckoMediaPluginService::ForgetThisSite(const nsAString& aOrigin)
+{
+  MOZ_ASSERT(NS_IsMainThread());
+  return GMPDispatch(NS_NewRunnableMethodWithArg<nsCString>(
+      this, &GeckoMediaPluginService::ForgetThisSiteOnGMPThread,
+      NS_ConvertUTF16toUTF8(aOrigin)));
+}
+
 class StorageClearedTask : public nsRunnable {
 public:
   NS_IMETHOD Run() {
     MOZ_ASSERT(NS_IsMainThread());
     nsCOMPtr<nsIObserverService> obsService = mozilla::services::GetObserverService();
     MOZ_ASSERT(obsService);
     if (obsService) {
       obsService->NotifyObservers(nullptr, "gmp-clear-storage-complete", nullptr);
     }
     return NS_OK;
   }
 };
 
+static bool IsNodeIdValid(GMPParent* aParent) {
+  return !aParent->GetNodeId().IsEmpty();
+}
+
 void
 GeckoMediaPluginService::ClearStorage()
 {
   MOZ_ASSERT(NS_GetCurrentThread() == mGMPThread);
   LOGD(("%s::%s", __CLASS__, __FUNCTION__));
 
 #ifdef MOZ_WIDGET_GONK
   NS_WARNING("GeckoMediaPluginService::ClearStorage not implemented on B2G");
   return;
 #endif
 
-  // Shutdown plugins that have touched storage, as they could have
-  // state that depends on storage. We don't want them to write data
-  // after we've cleared storage, as they could end up in an inconsistent
-  // state, so we must ensure they're shutdown before we actually clear
-  // storage. Note: we can't shut them down while holding the lock,
-  // as the lock is not re-entrant and shutdown requires taking the lock.
-  // The plugin list is only edited on the GMP thread, so this should be OK.
-  nsTArray<nsRefPtr<GMPParent>> pluginsToKill;
-  {
-    MutexAutoLock lock(mMutex);
-    for (size_t i = 0; i < mPlugins.Length(); i++) {
-      nsRefPtr<GMPParent> parent(mPlugins[i]);
-      if (parent->HasAccessedStorage()) {
-        pluginsToKill.AppendElement(parent);
-      }
-    }
-  }
-
-  for (size_t i = 0; i < pluginsToKill.Length(); i++) {
-    pluginsToKill[i]->CloseActive(false);
-    // Abort async shutdown because we're going to wipe the plugin's storage,
-    // so we don't want it writing more data in its async shutdown path.
-    pluginsToKill[i]->AbortAsyncShutdown();
-  }
+  // Kill plugins with valid nodeIDs.
+  KillPlugins(mPlugins, mMutex, &IsNodeIdValid);
 
   nsCOMPtr<nsIFile> path; // $profileDir/gmp/
   nsresult rv = GetStorageDir(getter_AddRefs(path));
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return;
   }
 
-  bool exists = false;
-  if (NS_SUCCEEDED(path->Exists(&exists)) &&
-      exists &&
-      NS_FAILED(path->Remove(true))) {
+  if (NS_FAILED(DeleteDir(path))) {
     NS_WARNING("Failed to delete GMP storage directory");
   }
   NS_DispatchToMainThread(new StorageClearedTask(), NS_DISPATCH_NORMAL);
 }
 
 } // namespace gmp
 } // namespace mozilla
--- a/dom/media/gmp/GMPService.h
+++ b/dom/media/gmp/GMPService.h
@@ -47,16 +47,18 @@ public:
   void AsyncShutdownComplete(GMPParent* aParent);
   void AbortAsyncShutdown();
 
   int32_t AsyncShutdownTimeoutMs();
 
 private:
   ~GeckoMediaPluginService();
 
+  nsresult GMPDispatch(nsIRunnable* event, uint32_t flags = NS_DISPATCH_NORMAL);
+
   void ClearStorage();
 
   GMPParent* SelectPluginForAPI(const nsACString& aNodeId,
                                 const nsCString& aAPI,
                                 const nsTArray<nsCString>& aTags);
   GMPParent* FindPluginForAPIFrom(size_t aSearchStartIndex,
                                   const nsCString& aAPI,
                                   const nsTArray<nsCString>& aTags,
@@ -69,16 +71,18 @@ private:
   void LoadFromEnvironment();
   void ProcessPossiblePlugin(nsIFile* aDir);
 
   void AddOnGMPThread(const nsAString& aSearchDir);
   void RemoveOnGMPThread(const nsAString& aSearchDir);
 
   nsresult SetAsyncShutdownTimeout();
 
+  void ForgetThisSiteOnGMPThread(const nsACString& aOrigin);
+
 protected:
   friend class GMPParent;
   void ReAddOnGMPThread(nsRefPtr<GMPParent>& aOld);
 private:
   GMPParent* ClonePlugin(const GMPParent* aOriginal);
 
   class PathRunnable : public nsRunnable
   {
--- a/dom/media/gmp/mozIGeckoMediaPluginService.idl
+++ b/dom/media/gmp/mozIGeckoMediaPluginService.idl
@@ -21,17 +21,17 @@ class GMPVideoHost;
 [ptr] native GMPVideoDecoderProxy(GMPVideoDecoderProxy);
 [ptr] native GMPVideoEncoderProxy(GMPVideoEncoderProxy);
 [ptr] native GMPVideoHost(GMPVideoHost);
 [ptr] native MessageLoop(MessageLoop);
 [ptr] native TagArray(nsTArray<nsCString>);
 [ptr] native GMPDecryptorProxy(GMPDecryptorProxy);
 [ptr] native GMPAudioDecoderProxy(GMPAudioDecoderProxy);
 
-[scriptable, uuid(657443a4-6b5d-4181-98b0-56997b35bd57)]
+[scriptable, uuid(4aaf58d3-181f-4325-9a2f-41172d995a70)]
 interface mozIGeckoMediaPluginService : nsISupports
 {
 
   /**
    * The GMP thread. Callable from any thread.
    */
   readonly attribute nsIThread thread;
 
@@ -92,16 +92,21 @@ interface mozIGeckoMediaPluginService : 
   /**
    * Gets the NodeId for a (origin, urlbarOrigin, isInprivateBrowsing) tuple.
    */
   ACString getNodeId(in AString origin,
                      in AString topLevelOrigin,
                      in bool inPrivateBrowsingMode);
 
   /**
+   * Clears storage data associated with the origin.
+   */
+  void forgetThisSite(in AString origin);
+
+  /**
    * Returns true if the given node id is allowed to store things
    * persistently on disk. Private Browsing and local content are not
    * allowed to store persistent data.
    */
   bool isPersistentStorageAllowed(in ACString nodeId);
 
   /**
    * Returns the directory to use as the base for storing data about GMPs.
--- a/dom/media/webrtc/MediaEngineTabVideoSource.cpp
+++ b/dom/media/webrtc/MediaEngineTabVideoSource.cpp
@@ -130,16 +130,18 @@ MediaEngineTabVideoSource::Allocate(cons
 
   if (aConstraints.mAdvanced.WasPassed()) {
     const auto& advanced = aConstraints.mAdvanced.Value();
     for (uint32_t i = 0; i < advanced.Length(); i++) {
       if (cWidth.mMax >= advanced[i].mWidth.mMin && cWidth.mMin <= advanced[i].mWidth.mMax &&
          cHeight.mMax >= advanced[i].mHeight.mMin && cHeight.mMin <= advanced[i].mHeight.mMax) {
         cWidth.mMin = std::max(cWidth.mMin, advanced[i].mWidth.mMin);
         cHeight.mMin = std::max(cHeight.mMin, advanced[i].mHeight.mMin);
+        cWidth.mMax = std::min(cWidth.mMax, advanced[i].mWidth.mMax);
+        cHeight.mMax = std::min(cHeight.mMax, advanced[i].mHeight.mMax);
       }
 
       if (mWindowId == -1 && advanced[i].mBrowserWindow.WasPassed()) {
         mWindowId = advanced[i].mBrowserWindow.Value();
       }
 
       if (!haveScrollWithPage && advanced[i].mScrollWithPage.WasPassed()) {
         mScrollWithPage = advanced[i].mScrollWithPage.Value();
--- a/dom/mobilemessage/ipc/SmsIPCService.cpp
+++ b/dom/mobilemessage/ipc/SmsIPCService.cpp
@@ -9,16 +9,17 @@
 #include "mozilla/dom/mobilemessage/SmsChild.h"
 #include "SmsMessage.h"
 #include "nsJSUtils.h"
 #include "mozilla/dom/MozMobileMessageManagerBinding.h"
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/Preferences.h"
 #include "nsString.h"
 #include "mozilla/dom/ipc/BlobChild.h"
+#include "mozilla/unused.h"
 
 using namespace mozilla::dom;
 using namespace mozilla::dom::mobilemessage;
 
 namespace {
 
 #define kPrefMmsDefaultServiceId "dom.mms.defaultServiceId"
 #define kPrefSmsDefaultServiceId "dom.sms.defaultServiceId"
@@ -65,17 +66,18 @@ SendCursorRequest(const IPCMobileMessage
   PSmsChild* smsChild = GetSmsChild();
   NS_ENSURE_TRUE(smsChild, NS_ERROR_FAILURE);
 
   nsRefPtr<MobileMessageCursorChild> actor =
     new MobileMessageCursorChild(aRequestReply);
 
   // Add an extra ref for IPDL. Will be released in
   // SmsChild::DeallocPMobileMessageCursor().
-  actor->AddRef();
+  nsRefPtr<MobileMessageCursorChild> actorCopy(actor);
+  mozilla::unused << actorCopy.forget().take();
 
   smsChild->SendPMobileMessageCursorConstructor(actor, aRequest);
 
   actor.forget(aResult);
   return NS_OK;
 }
 
 uint32_t
--- a/dom/webidl/Element.webidl
+++ b/dom/webidl/Element.webidl
@@ -119,22 +119,23 @@ interface Element : Node {
    */
   void releaseCapture();
 
   // Mozilla extensions
   /**
    * Requests that this element be made the full-screen element, as per the DOM
    * full-screen api.
    *
-   * The fsOptions parameter is non-standard.
+   * The options parameter is non-standard. In Gecko, it can be:
+   *  a RequestFullscreenOptions object
    *
    * @see <https://wiki.mozilla.org/index.php?title=Gecko:FullScreenAPI>
    */
-  [UnsafeInPrerendering]
-  void mozRequestFullScreen(optional RequestFullscreenOptions fsOptions);
+  [Throws, UnsafeInPrerendering]
+  void mozRequestFullScreen(optional any options);
 
   /**
    * Requests that this element be made the pointer-locked element, as per the DOM
    * pointer lock api.
    *
    * @see <http://dvcs.w3.org/hg/pointerlock/raw-file/default/index.html>
    */
   [UnsafeInPrerendering]
--- a/dom/workers/ServiceWorkerContainer.h
+++ b/dom/workers/ServiceWorkerContainer.h
@@ -29,18 +29,18 @@ public:
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(ServiceWorkerContainer, DOMEventTargetHelper)
 
   IMPL_EVENT_HANDLER(controllerchange)
   IMPL_EVENT_HANDLER(reloadpage)
   IMPL_EVENT_HANDLER(error)
 
   explicit ServiceWorkerContainer(nsPIDOMWindow* aWindow);
 
-  JSObject*
-  WrapObject(JSContext* aCx);
+  virtual JSObject*
+  WrapObject(JSContext* aCx) MOZ_OVERRIDE;
 
   already_AddRefed<Promise>
   Register(const nsAString& aScriptURL,
            const RegistrationOptionList& aOptions,
            ErrorResult& aRv);
 
   already_AddRefed<workers::ServiceWorker>
   GetController();
--- a/dom/workers/ServiceWorkerRegistration.cpp
+++ b/dom/workers/ServiceWorkerRegistration.cpp
@@ -110,25 +110,25 @@ public:
 
   explicit UnregisterCallback(Promise* aPromise)
     : mPromise(aPromise)
   {
     MOZ_ASSERT(mPromise);
   }
 
   NS_IMETHODIMP
-  UnregisterSucceeded(bool aState)
+  UnregisterSucceeded(bool aState) MOZ_OVERRIDE
   {
     AssertIsOnMainThread();
     mPromise->MaybeResolve(aState);
     return NS_OK;
   }
 
   NS_IMETHODIMP
-  UnregisterFailed()
+  UnregisterFailed() MOZ_OVERRIDE
   {
     AssertIsOnMainThread();
 
     AutoJSAPI api;
     api.Init(mPromise->GetParentObject());
     mPromise->MaybeReject(api.cx(), JS::UndefinedHandleValue);
     return NS_OK;
   }
--- a/dom/workers/ServiceWorkerRegistration.h
+++ b/dom/workers/ServiceWorkerRegistration.h
@@ -29,17 +29,17 @@ public:
                                            DOMEventTargetHelper)
 
   IMPL_EVENT_HANDLER(updatefound)
 
   ServiceWorkerRegistration(nsPIDOMWindow* aWindow,
                             const nsAString& aScope);
 
   JSObject*
-  WrapObject(JSContext* aCx);
+  WrapObject(JSContext* aCx) MOZ_OVERRIDE;
 
   already_AddRefed<workers::ServiceWorker>
   GetInstalling();
 
   already_AddRefed<workers::ServiceWorker>
   GetWaiting();
 
   already_AddRefed<workers::ServiceWorker>
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -2020,17 +2020,17 @@ public:
     mAlreadyMappedToAddon(false)
   {
     aWorkerPrivate->AssertIsOnWorkerThread();
 
   }
 
   NS_IMETHOD
   CollectReports(nsIMemoryReporterCallback* aCallback,
-                 nsISupports* aClosure, bool aAnonymize)
+                 nsISupports* aClosure, bool aAnonymize) MOZ_OVERRIDE
   {
     AssertIsOnMainThread();
 
     // Assumes that WorkerJSRuntimeStats will hold a reference to |path|, and
     // not a copy, as TryToMapAddon() may later modify if.
     nsCString path;
     WorkerJSRuntimeStats rtStats(path);
 
--- a/dom/workers/test/mochitest.ini
+++ b/dom/workers/test/mochitest.ini
@@ -46,16 +46,17 @@ support-files =
   onLine_worker_head.js
   promise_worker.js
   recursion_worker.js
   recursiveOnerror_worker.js
   relativeLoad_import.js
   relativeLoad_worker.js
   relativeLoad_worker2.js
   rvals_worker.js
+  sharedWorker_console.js
   sharedWorker_sharedWorker.js
   simpleThread_worker.js
   suspend_iframe.html
   suspend_worker.js
   terminate_worker.js
   terminateSyncXHR_frame.html
   terminateSyncXHR_worker.js
   testXHR.txt
@@ -110,16 +111,17 @@ support-files =
 [test_bug998474.html]
 [test_bug1063538.html]
 [test_chromeWorker.html]
 [test_clearTimeouts.html]
 [test_close.html]
 [test_closeOnGC.html]
 [test_console.html]
 [test_consoleReplaceable.html]
+[test_consoleSharedWorkers.html]
 [test_contentWorker.html]
 [test_csp.html]
 skip-if = (toolkit == 'gonk' && debug) #debug-only failure
 [test_dataURLWorker.html]
 [test_errorPropagation.html]
 skip-if = buildapp == 'b2g' # b2g(times out) b2g-debug(times out) b2g-desktop(times out)
 [test_errorwarning.html]
 skip-if = buildapp == 'b2g' # b2g(Failed to load script: errorwarning_worker.js) b2g-debug(Failed to load script: errorwarning_worker.js) b2g-desktop(Failed to load script: errorwarning_worker.js)
new file mode 100644
--- /dev/null
+++ b/dom/workers/test/sharedWorker_console.js
@@ -0,0 +1,11 @@
+/**
+ * Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+"use strict";
+
+onconnect = function(evt) {
+  console.profile("Hello profiling from a SharedWorker!");
+  console.log("Hello world from a SharedWorker!");
+  evt.ports[0].postMessage('ok!');
+}
new file mode 100644
--- /dev/null
+++ b/dom/workers/test/test_consoleSharedWorkers.html
@@ -0,0 +1,58 @@
+<!--
+  Any copyright is dedicated to the Public Domain.
+  http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<!DOCTYPE HTML>
+<html>
+  <head>
+    <title>Test for console API in SharedWorker</title>
+    <script src="/tests/SimpleTest/SimpleTest.js">
+    </script>
+    <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
+  </head>
+  <body>
+    <script type="text/javascript">
+
+  function consoleListener() {
+    SpecialPowers.addObserver(this, "console-api-log-event", false);
+    SpecialPowers.addObserver(this, "console-api-profiler", false);
+  }
+
+  var order = 0;
+  consoleListener.prototype  = {
+    observe: function(aSubject, aTopic, aData) {
+      ok(true, "Something has been received");
+
+      if (aTopic == "console-api-profiler") {
+        var obj = aSubject.wrappedJSObject;
+        is (obj.arguments[0], "Hello profiling from a SharedWorker!", "A message from a SharedWorker \\o/");
+        is (order++, 0, "First a profiler message.");
+
+        SpecialPowers.removeObserver(this, "console-api-profiler");
+        return;
+      }
+
+      if (aTopic == "console-api-log-event") {
+        var obj = aSubject.wrappedJSObject;
+        is (obj.arguments[0], "Hello world from a SharedWorker!", "A message from a SharedWorker \\o/");
+        is (aData, "SharedWorker", "The ID is SharedWorker");
+        is (order++, 1, "Then a log message.");
+
+        SpecialPowers.removeObserver(this, "console-api-log-event");
+        SimpleTest.finish();
+        return;
+      }
+    }
+  }
+
+  var cl = new consoleListener();
+
+  SpecialPowers.pushPrefEnv({ set: [["dom.workers.sharedWorkers.enabled", true]] }, function() {
+    new SharedWorker('sharedWorker_console.js');
+  });
+
+  SimpleTest.waitForExplicitFinish();
+
+    </script>
+  </body>
+</html>
--- a/dom/xul/templates/nsResourceSet.h
+++ b/dom/xul/templates/nsResourceSet.h
@@ -55,17 +55,17 @@ public:
         ConstIterator operator++(int) {
             ConstIterator result(*this);
             ++mCurrent;
             return result; }
 
         /*const*/ nsIRDFResource* operator*() const {
             return *mCurrent; }
 
-        /*const*/ nsIRDFResource* operator->() const {
+        /*const*/ nsIRDFResource* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN {
             return *mCurrent; }
 
         bool operator==(const ConstIterator& aConstIterator) const {
             return mCurrent == aConstIterator.mCurrent; }
 
         bool operator!=(const ConstIterator& aConstIterator) const {
             return mCurrent != aConstIterator.mCurrent; }
 
--- a/embedding/components/printingui/unixshared/nsPrintingPromptService.cpp
+++ b/embedding/components/printingui/unixshared/nsPrintingPromptService.cpp
@@ -37,17 +37,17 @@ public:
     }
     ~ParamBlock() 
     {
         NS_IF_RELEASE(mBlock);
     }
     nsresult Init() {
       return CallCreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID, &mBlock);
     }
-    nsIDialogParamBlock * operator->() const { return mBlock; }
+    nsIDialogParamBlock * operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN { return mBlock; }
     operator nsIDialogParamBlock * const ()  { return mBlock; }
 
 private:
     nsIDialogParamBlock *mBlock;
 };
 
 /****************************************************************
  ***************** nsPrintingPromptService **********************
--- a/embedding/components/printingui/win/nsPrintingPromptService.cpp
+++ b/embedding/components/printingui/win/nsPrintingPromptService.cpp
@@ -54,17 +54,17 @@ public:
     }
     ~ParamBlock() 
     {
         NS_IF_RELEASE(mBlock);
     }
     nsresult Init() {
       return CallCreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID, &mBlock);
     }
-    nsIDialogParamBlock * operator->() const { return mBlock; }
+    nsIDialogParamBlock * operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN { return mBlock; }
     operator nsIDialogParamBlock * const ()  { return mBlock; }
 
 private:
     nsIDialogParamBlock *mBlock;
 };
 
 //*****************************************************************************   
 
--- a/extensions/spellcheck/locales/en-US/hunspell/dictionary-sources/upstream-hunspell.diff
+++ b/extensions/spellcheck/locales/en-US/hunspell/dictionary-sources/upstream-hunspell.diff
@@ -9599,1823 +9599,1829 @@ 18542,18543c24309
 < coup/AS
 ---
 > coup/ASM
 18545,18546c24311
 < couple's
 < couple/CUDSG
 ---
 > couple/CUDSGM
-18581,18582c24346
+18559a24325
+> court-martial/SGD
+18581,18582c24347
 < cover's
 < cover/AEUGDS
 ---
 > cover/AEUGDSM
-18585,18586c24349
+18585,18586c24350
 < covering's
 < coverings
 ---
 > covering/MS
-18739,18740c24502
+18739,18740c24503
 < creation's/K
 < creation/ASM
 ---
 > creation/ASMK
-18816a24579
+18816a24580
 > crimeware/M
-18880,18881c24643
+18880,18881c24644
 < cross's
 < cross/AUGTSD
 ---
 > cross/AUGTSDM
-18925a24688,24689
+18925a24689,24690
 > crowdfunded
 > crowdfunding
-18972,18973c24736
+18972,18973c24737
 < crust's
 < crust/ISDG
 ---
 > crust/ISDGM
-18988,18989c24751
+18988,18989c24752
 < crypt's
 < crypt/CS
 ---
 > crypt/CSM
-18999a24762
+18999a24763
 > cryptologist/MS
-19000a24764
+19000a24765
 > cryptosystem/S
-19035a24800
+19035a24801
 > cul-de-sac
-19104,19105c24869
+19104,19105c24870
 < cure's
 < cure/KZGBDRS
 ---
 > cure/KZGBDRSM
-19119,19120c24883
+19119,19120c24884
 < curl's
 < curl/UDGS
 ---
 > curl/UDGSM
-19131,19133c24894
+19131,19133c24895
 < current's
 < current/FAY
 < currents
 ---
 > current/FAYSM
-19142,19143c24903
+19142,19143c24904
 < cursive's
 < cursive/EAY
 ---
 > cursive/EAYM
-19167,19168c24927
+19167,19168c24928
 < cuss's
 < cuss/FEGSD
 ---
 > cuss/FEGSDM
-19246c25005
+19246c25006
 < cysteine
 ---
 > cysteine/M
-19536a25296
+19536a25297
 > decertify/DSGNX
-19759c25519
+19759c25520
 < deliverable/U
 ---
 > deliverable/US
-19935a25696
+19935a25697
 > dequeue/DSG
-19999a25761
+19999a25762
 > designated/U
-20196,20197c25958,25959
+20196,20197c25959,25960
 < dialog/SM
 < dialogue/SM
 ---
 > dialog/SMGD
 > dialogue/SMRGD
-20220a25983
+20220a25984
 > diatomaceous
-20481a26245
+20481a26246
 > disclose/DSG
-20633a26398
+20633a26399
 > dissentious
-20695,20696c26460
+20695,20696c26461
 < district's
 < district/AS
 ---
 > district/ASM
-20768c26532
+20768c26533
 < djinn's
 ---
 > djinn/M
-20830c26594
+20830c26595
 < dogie/M
 ---
 > dogie/SM
-20850,20851c26614
+20850,20851c26615
 < dole's
 < dole/FGDS
 ---
 > dole/FGDSM
-20895a26659
+20895a26660
 > donator/MS
-20918,20919c26682
+20918,20919c26683
 < door's
 < door/IS
 ---
 > door/ISM
-20975,20976c26738
+20975,20976c26739
 < double's
 < double/ADSG
 ---
 > double/ADSGM
-21067,21068c26829
+21067,21068c26830
 < draft's
 < draft/ASDG
 ---
 > draft/ASDGM
-21282,21283c27043
+21282,21283c27044
 < duct's
 < duct/CIFDG
 ---
 > duct/CIFDGM
-21291,21292c27051
+21291,21292c27052
 < due's
 < due/IS
 ---
 > due/ISM
-21355,21356c27114
+21355,21356c27115
 < duplicate's
 < duplicate/AGNDS
 ---
 > duplicate/AGNDSM
-21367a27126
+21367a27127
 > durian/SM
-21468,21469c27227
+21468,21469c27228
 < earth's
 < earth/UDYG
 ---
 > earth/UDYGM
-21523,21524c27281
+21523,21524c27282
 < echo's
 < echo/ADG
 ---
 > echo/ADGM
-21587,21588c27344
+21587,21588c27345
 < edit's
 < edit/ADGS
 ---
 > edit/ADGSM
-21735,21736c27491
+21735,21736c27492
 < elect's
 < elect/ASDGV
 ---
 > elect/ASDGVM
-21820a27576
+21820a27577
 > elicitor/MS
-21864,21865c27620
+21864,21865c27621
 < em's
 < em/S
 ---
 > em/SM
-21992,21993c27747
+21992,21993c27748
 < employ's
 < employ/ADGLS
 ---
 > employ/ADGLSM
-22071a27826
+22071a27827
 > encyclopaedia
-22196a27952
+22196a27953
 > enqueue/DSG
-22508a28265,28266
+22508a28266,28267
 > eschatological
 > eschatologist/SM
-22556a28315
+22556a28316
 > estoppel
-22638c28397
+22638c28398
 < euthanize
 ---
 > euthanize/DSG
-22719a28479
+22719a28480
 > exabyte/MS
-22722,22724c28482,28485
+22722,22724c28483,28486
 < exact/SPDRYTG
 < exacting/Y
 < exaction/M
 ---
 > exact/SPDRYTGB
 > exacta/S
 > exacting/YP
 > exaction/MS
-22726a28488
+22726a28489
 > exactor/MS
-22947a28710
+22947a28711
 > experimentalism
-23165,23166c28928
+23165,23166c28929
 < face's
 < face/ACSDG
 ---
 > face/ACSDGM
-23207,23208d28968
+23207,23208d28969
 < faecal
 < faeces/M
-23215c28975
+23215c28976
 < faggoting's
 ---
 > faggot/SMG
-23238,23239c28998
+23238,23239c28999
 < faithful's
 < faithful/UPY
 ---
 > faithful/UPYM
-23278,23279c29037
+23278,23279c29038
 < fame's
 < fame/D
 ---
 > fame/DM
-23418a29177
+23418a29178
 > faux
-23589,23590c29348
+23589,23590c29349
 < fetter's
 < fetter/USGD
 ---
 > fetter/USGDM
-23690,23691c29448
+23690,23691c29449
 < figure's
 < figure/FEGSD
 ---
 > figure/FEGSDM
-23699,23700c29456
+23699,23700c29457
 < file's/KC
 < file/CAKGDS
 ---
 > file/CAKGDSM
-23701a29458
+23701a29459
 > filesystem/MS
-23708,23711c29465,29466
+23708,23711c29466,29467
 < filing's
 < filings
 < fill's
 < fill/AIDGS
 ---
 > filing/SM
 > fill/AIDGSM
-23715,23716c29470
+23715,23716c29471
 < filling's
 < filling/S
 ---
 > filling/SM
-23733,23734c29487
+23733,23734c29488
 < filtrate's
 < filtrate/IGNDS
 ---
 > filtrate/IGNDSM
-23745,23746c29498
+23745,23746c29499
 < finance's
 < finance/ADSG
 ---
 > finance/ADSGM
-23755,23756c29507
+23755,23756c29508
 < fine's/F
 < fine/CAFTGDS
 ---
 > fine/CAFTGDSM
-23776,23777c29527
+23776,23777c29528
 < finish's
 < finish/ADSG
 ---
 > finish/ADSGM
-24131,24132c29881
+24131,24132c29882
 < flower's
 < flower/CSDG
 ---
 > flower/CSDGM
-24155c29904
+24155c29905
 < fluidized
 ---
 > fluidize/DSG
-24185,24186c29934
+24185,24186c29935
 < flux's
 < flux/ADG
 ---
 > flux/ADGM
-24217,24218c29965,29966
+24217,24218c29966,29967
 < focus's
 < focus/ADSG
 ---
 > foci
 > focus/ADSGM
-24223,24224c29971
+24223,24224c29972
 < fog's
 < fog/CS
 ---
 > fog/CSM
-24238,24239c29985
+24238,24239c29986
 < fold's
 < fold/IAUSGD
 ---
 > fold/IAUSGDM
-24414,24415c30160
+24414,24415c30161
 < forest's
 < forest/ACGDS
 ---
 > forest/ACGDSM
-24464,24465c30209
+24464,24465c30210
 < form's
 < form/CAIFDGS
 ---
 > form/CAIFDGSM
-24585a30330,30331
+24585a30331,30332
 > frack/DRGS
 > fracker/S
-24609,24610c30355
+24609,24610c30356
 < franchise's
 < franchise/EDSG
 ---
 > franchise/EDSGM
-24633,24634c30378
+24633,24634c30379
 < fraud's
 < fraud/S
 ---
 > fraud/SM
-24639,24640c30383
+24639,24640c30384
 < fray's
 < fray/CDGS
 ---
 > fray/CDGSM
-24657a30401
+24657a30402
 > freegan/S
-24681,24682c30425
+24681,24682c30426
 < freeze's
 < freeze/UAGS
 ---
 > freeze/UAGSM
-24684c30427
+24684c30428
 < freezing's
 ---
 > freezing/M
-24733,24734c30476
+24733,24734c30477
 < friendly's
 < friendly/UTPR
 ---
 > friendly/UTPRM
-24736d30477
+24736d30478
 < frier/M
-24752,24753c30493
+24752,24753c30494
 < fringe's
 < fringe/IDSG
 ---
 > fringe/IDSGM
-24771,24772c30511
+24771,24772c30512
 < frock's
 < frock/CUS
 ---
 > frock/CUSM
-24786,24787c30525
+24786,24787c30526
 < front's
 < front/FSDG
 ---
 > front/FSDGM
-24800,24801c30538
+24800,24801c30539
 < frost's
 < frost/CSDG
 ---
 > frost/CSDGM
-24855,24856c30592,30593
+24855,24856c30593,30594
 < fucker/M!
 < fuckhead/S!
 ---
 > fucker/SM!
 > fuckhead/SM!
-24860,24861c30597
+24860,24861c30598
 < fuel's
 < fuel/ADGS
 ---
 > fuel/ADGSM
-24941,24942c30677
+24941,24942c30678
 < furl's
 < furl/UDGS
 ---
 > furl/UDGSM
-24953d30687
+24953d30688
 < furore/MS
-24969,24970c30703
+24969,24970c30704
 < fuse's/A
 < fuse/CAIFGDS
 ---
 > fuse/CAIFGDSM
-25038,25039c30771
+25038,25039c30772
 < gain's
 < gain/ADGS
 ---
 > gain/ADGSM
-25051,25052c30783
+25051,25052c30784
 < gale's
 < gale/AS
 ---
 > gale/ASM
-25095a30827
+25095a30828
 > gamify/NGDS
-25125c30857
+25125c30858
 < gaolbird/S
 ---
 > gaolbirds
-25169,25170c30901
+25169,25170c30902
 < gas's
 < gas/CS
 ---
 > gas/CSM
-25180d30910
+25180d30911
 < gasolene/M
-25190a30921
+25190a30922
 > gastroenterologist/M
-25262c30993
+25262c30994
 < geezer/M
 ---
 > geezer/MS
-25297,25298c31028
+25297,25298c31029
 < generation's/C
 < generation/ASM
 ---
 > generation/ASMC
-25327c31057
+25327c31058
 < genomic
 ---
 > genomic/S
-25462a31193
+25462a31194
 > gigabit/MS
-25464a31196,31198
+25464a31197,31199
 > gigajoule/MS
 > gigapixel/MS
 > gigawatt/MS
-25560d31293
+25560d31294
 < glamourize/DSG
-25674c31407
+25674c31408
 < glycerine's
 ---
 > glycerine/M
-25816,25817c31549
+25816,25817c31550
 < gorge's
 < gorge/EDSG
 ---
 > gorge/EDSGM
-25884,25885c31616
+25884,25885c31617
 < grade's
 < grade/CADSG
 ---
 > grade/CADSGM
-25905c31636
+25905c31637
 < gram/MS
 ---
 > gram/KMS
-25909d31639
+25909d31640
 < gramme/SM
-26063c31793,31794
+26063c31794,31795
 < greybeard
 ---
 > grey/MDRTGSP
 > greybeard/SM
-26066c31797
+26066c31798
 < greyness
 ---
 > greyness/M
-26246,26247d31976
+26246,26247d31977
 < guerilla's
 < guerillas
-26403,26404c32132
+26403,26404c32133
 < habit's
 < habit/ISB
 ---
 > habit/ISBM
-26432,26436d32159
+26432,26436d32160
 < haemoglobin's
 < haemophilia/M
 < haemorrhage/DSMG
 < haemorrhoid/S
 < haemorrhoids/M
-26555,26556c32278
+26555,26556c32279
 < hand's
 < hand/UDGS
 ---
 > hand/UDGSM
-26702,26703c32424
+26702,26703c32425
 < harness's
 < harness/UDSG
 ---
 > harness/UDSGM
-26725a32447
+26725a32448
 > hashtag/S
-26888,26889c32610
+26888,26889c32611
 < hearse's
 < hearse/AS
 ---
 > hearse/ASM
-26915,26916c32636
+26915,26916c32637
 < heat's
 < heat/ADGS
 ---
 > heat/ADGSM
-27167c32887
+27167c32888
 < hexane
 ---
 > hexane/SM
-27227a32948
+27227a32949
 > hijab/S
-27256,27257c32977
+27256,27257c32978
 < hinge's
 < hinge/UDSG
 ---
 > hinge/UDSGM
-27273a32994
+27273a32995
 > hippopotami
-27276,27277c32997
+27276,27277c32998
 < hire's
 < hire/AGDS
 ---
 > hire/AGDSM
-27302,27303c33022
+27302,27303c33023
 < hitch's
 < hitch/UDSG
 ---
 > hitch/UDSGM
-27512,27513c33231
+27512,27513c33232
 < hook's
 < hook/UDSG
 ---
 > hook/UDSGM
-27575,27576c33293
+27575,27576c33294
 < horse's
 < horse/UDSG
 ---
 > horse/UDSGM
-27666,27667c33383
+27666,27667c33384
 < house's
 < house/ADSG
 ---
 > house/ADSGM
-27841c33557
+27841c33558
 < hurrah's
 ---
 > hurrah/M
-27875d33590
+27875d33591
 < hyaena/SM
-27883,27884c33598
+27883,27884c33599
 < hydrate's
 < hydrate/CGNDS
 ---
 > hydrate/CGNDSM
-28017c33731
+28017c33732
 < iPod/M
 ---
 > iPod/MS
-28029,28030c33743
+28029,28030c33744
 < ice's
 < ice/CDSG
 ---
 > ice/CDSGM
-28105a33819
+28105a33820
 > idolator/SM
-28227c33941
+28227c33942
 < immerse/XDSGN
 ---
 > immerse/XDSGNV
-28513c34227
+28513c34228
 < inbound
 ---
 > inbound/s
-28531,28532c34245,34246
+28531,28532c34246,34247
 < incentive's
 < incentive/ES
 ---
 > incentive/ESM
 > incentivize/SDG
-28560,28561c34274
+28560,28561c34275
 < incline's
 < incline/EGDS
 ---
 > incline/EGDSM
-28590,28591c34303
+28590,28591c34304
 < incorrigibility/M
 < incorrigible
 ---
 > incorrigibleness
-28593d34304
+28593d34305
 < incorruptibly
-28650a34362
+28650a34363
 > indices
-28812d34523
+28812d34524
 < inflexion/SM
-28981,28982c34692
+28981,28982c34693
 < insert's
 < insert/AGSD
 ---
 > insert/AGSDM
-29204a34915
+29204a34916
 > intermediacy/S
-29206c34917,34919
+29206c34918,34920
 < intermediate/SMY
 ---
 > intermediate/SMYPGD
 > intermediation/SE
 > intermediator/SM
-29216a34930
+29216a34931
 > intern/GDL
-29266a34981
+29266a34982
 > interruptible/U
-29272a34988,34991
+29272a34989,34992
 > intersex
 > intersexual/MS
 > intersexualism
 > intersexuality
-29446c35165
+29446c35166
 < ironic
 ---
 > ironic/U
-29447a35167
+29447a35168
 > ironically/U
-29724c35444
+29724c35445
 < jewellery's
 ---
 > jewellery/M
-29733,29734c35453
+29733,29734c35454
 < jig's
 < jig/AS
 ---
 > jig/ASM
-29736,29737c35455
+29736,29737c35456
 < jigger's
 < jigger/ASDG
 ---
 > jigger/ASDGM
-29799,29800c35517
+29799,29800c35518
 < join's
 < join/AFDSG
 ---
 > join/AFDSGM
-29803,29804c35520
+29803,29804c35521
 < joint's
 < joint/EGSD
 ---
 > joint/EGSDM
-29869,29870c35585,35586
+29869,29870c35586,35587
 < judge's
 < judge/ADSG
 ---
 > judge/ADSGM
 > judgement/MS
-30035a35752,35753
+30035a35753,35754
 > keylogger/MS
 > keylogging/MS
-30066c35784
+30066c35785
 < kiddie/M
 ---
 > kiddie/SM
-30102,30103c35820
+30102,30103c35821
 < kind's
 < kind/UPRYT
 ---
 > kind/UPRYTM
-30262,30263c35979
+30262,30263c35980
 < kraut's
 < kraut/S!
 ---
 > kraut/MS!
-30283,30284c35999
+30283,30284c36000
 < label's
 < label/ASDG
 ---
 > label/ASDGM
-30302,30303c36017
+30302,30303c36018
 < lace's
 < lace/UGDS
 ---
 > lace/UGDSM
-30497,30498c36211
+30497,30498c36212
 < latch's
 < latch/UDSG
 ---
 > latch/UDSGM
-30637c36350
+30637c36351
 < learning's
 ---
 > learning/M
-30643,30644c36356
+30643,30644c36357
 < leash's
 < leash/UDSG
 ---
 > leash/UDSGM
-30665a36378
+30665a36379
 > lector/MS
-30700c36413
+30700c36414
 < legation's/AC
 ---
 > legation/ACM
-30927,30928c36640
+30927,30928c36641
 < light's/C
 < light/CASTGD
 ---
 > light/CASTGDM
-30938c36650
+30938c36651
 < lighting's
 ---
 > lighting/M
-30981,30982c36693
+30981,30982c36694
 < limit's
 < limit/CSZGDR
 ---
 > limit/CSZGDRM
-30986c36697
+30986c36698
 < limiter's
 ---
 > limiter/M
-30990a36702,36704
+30990a36703,36705
 > limnological
 > limnologist/MS
 > limnology/M
-31031c36745
+31031c36746
 < linguini's
 ---
 > linguini/M
-31034c36748
+31034c36749
 < linguistically
 ---
 > linguistical/Y
-31047,31048c36761
+31047,31048c36762
 < lint's
 < lint/CDSG
 ---
 > lint/CDSGM
-31058a36772
+31058a36773
 > lepidopterist/SM
-31151,31152c36865
+31151,31152c36866
 < liver's
 < liver/S
 ---
 > liver/MS
-31170,31171c36883
+31170,31171c36884
 < load's
 < load/AUGSD
 ---
 > load/AUGSDM
-31211,31212c36923
+31211,31212c36924
 < location's/A
 < location/ESM
 ---
 > location/ESMA
-31291,31292c37002
+31291,31292c37003
 < long's
 < long/KDSTG
 ---
 > long/KDSTGM
-31379,31380c37089
+31379,31380c37090
 < louse's
 < louse/CDSG
 ---
 > louse/CDSGM
-31639a37349
+31639a37350
 > mage/SM
-31741,31742c37451
+31741,31742c37452
 < make's/A
 < make/UAGS
 ---
 > make/UAGSM
-31806a37516
+31806a37517
 > malware/MS
-31822,31823c37532
+31822,31823c37533
 < man's/F
 < man/USY
 ---
 > man/USYMF
-31924,31925c37633
+31924,31925c37634
 < mantle's
 < mantle/EGDS
 ---
 > mantle/EGDSM
-31940,31941c37648
+31940,31941c37649
 < map's
 < map/AS
 ---
 > map/ASM
-32061,32062c37768
+32061,32062c37769
 < mask's
 < mask/UDSG
 ---
 > mask/UDSGM
-32084,32085c37790
+32084,32085c37791
 < master's
 < master/ADGS
 ---
 > master/ADGSM
-32230c37935
+32230c37936
 < meanie/M
 ---
 > meanie/MS
-32246,32247c37951
+32246,32247c37952
 < measure's
 < measure/ADSG
 ---
 > measure/ADSGM
-32317,32318c38021
+32317,32318c38022
 < megadeath/M
 < megadeaths
 ---
 > megadeath/SM
-32320c38023
+32320c38024
 < megajoules
 ---
 > megajoule/SM
-32329c38032
+32329c38033
 < megapixel/S
 ---
 > megapixel/MS
-32361,32362c38064
+32361,32362c38065
 < melt's
 < melt/ADSG
 ---
 > melt/ADSGM
-32365,32366c38067
+32365,32366c38068
 < member's
 < member/EAS
 ---
 > member/EASM
-32386c38087
+32386c38088
 < men
 ---
 > men/M
-32708a38410
+32708a38411
 > might've
-32717a38420
+32717a38421
 > migrator/SM
-32760a38464
+32760a38465
 > millennia
-32777d38480
+32777d38481
 < millionnaire/M
-32806,32807c38509
+32806,32807c38510
 < mind's
 < mind/ADRSZG
 ---
 > mind/ADRSZGM
-32934a38637
+32934a38638
 > miscommunication/S
-32991a38695
+32991a38696
 > misjudgement/MS
-33027,33028c38731
+33027,33028c38732
 < miss's
 < miss/EDSGV
 ---
 > miss/EDSGVM
-33051,33052c38754
+33051,33052c38755
 < mist's
 < mist/CDRSZG
 ---
 > mist/CDRSZGM
-33056c38758
+33056c38759
 < mister's
 ---
 > mister/M
-33083c38785
+33083c38786
 < mitigation/M
 ---
 > mitigation/MS
-33107,33108c38809
+33107,33108c38810
 < mob's
 < mob/CS
 ---
 > mob/CSM
-33448,33449c39149
+33448,33449c39150
 < mortgage's
 < mortgage/AGDS
 ---
 > mortgage/AGDSM
-33471,33472c39171
+33471,33472c39172
 < mote's
 < mote/KCXSVN
 ---
 > mote/KCXSVNM
-33539,33540c39238
+33539,33540c39239
 < mounting's
 < mountings
 ---
 > mounting/MS
-33784a39483
+33784a39484
 > must've
-33887,33888c39586
+33887,33888c39587
 < name's
 < name/AGDS
 ---
 > name/AGDSM
-33963c39661
+33963c39662
 < native/MS
 ---
 > native/MSY
-33970,33971c39668
+33970,33971c39669
 < natural's
 < natural/UPY
 ---
 > natural/UPYM
-33979,33980c39676
+33979,33980c39677
 < nature's
 < nature/CS
 ---
 > nature/CSM
-34133,34134c39829
+34133,34134c39830
 < nerve's
 < nerve/UDSG
 ---
 > nerve/UDSGM
-34169,34171c39864,39866
+34169,34171c39865,39867
 < neurone/S
 < neurophysiology
 < neuroscience
 ---
 > neurophysiology/M
 > neuroscience/MS
 > neuroscientist/MS
-34175a39871
+34175a39872
 > neurosurgical
-34275c39971
+34275c39972
 < nightie/M
 ---
 > nightie/SM
-34388,34389c40084
+34388,34389c40085
 < nomination's/A
 < nomination/CSM
 ---
 > nomination/CSMA
-34755,34756c40450
+34755,34756c40451
 < note's
 < note/FCSDG
 ---
 > note/FCSDGM
-34840,34841c40534
+34840,34841c40535
 < number's
 < number/ASDG
 ---
 > number/ASDGM
-35104a40798
+35104a40799
 > octopi
-35137,35138c40831
+35137,35138c40832
 < offensive's
 < offensive/IYP
 ---
 > offensive/IYPM
-35219d40911
+35219d40912
 < oleomargarin/M
-35226a40919
+35226a40920
 > oligo
-35345c41038
+35345c41039
 < oppose/DSG
 ---
 > oppose/DSGRB
-35452,35453c41145
+35452,35453c41146
 < orient's
 < orient/AEDGS
 ---
 > orient/AEDGSM
-35913c41605
+35913c41606
 < oversize/D
 ---
 > oversize
-36031,36032c41723
+36031,36032c41724
 < pack's
 < pack/UADSG
 ---
 > pack/UADSGM
-36034,36035c41725
+36034,36035c41726
 < package's
 < package/AGDS
 ---
 > package/AGDSM
-36041c41731
+36041c41732
 < packing's
 ---
 > packing/M
-36056,36059d41745
+36056,36059d41746
 < paederast/S
 < paediatrician's
 < paediatricians
 < paediatrics/M
-36290a41977,41978
+36290a41978,41979
 > parallelization/SM
 > parallelize/SGD
-36291a41980
+36291a41981
 > paralyses
-36377a42067
+36377a42068
 > parkour
-36403d42092
+36403d42093
 < parrakeet/MS
-36418,36419c42107
+36418,36419c42108
 < part's
 < part/CDSG
 ---
 > part/CDSGM
-36445,36447c42133
+36445,36447c42134
 < partition's
 < partition/ADG
 < partitions
 ---
 > partition/ADGMS
-36449d42134
+36449d42135
 < partizan/SM
-36621,36622c42306
+36621,36622c42307
 < pay's
 < pay/ASGBL
 ---
 > pay/ASGBLM
-37093a42778
+37093a42779
 > petabyte/MS
-37102c42787
+37102c42788
 < petitioner/M
 ---
 > petitioner/MS
-37221a42907,42908
+37221a42908,42909
 > phlebotomist/SM
 > phlebotomize/SGD
-37228a42916
+37228a42917
 > pho
-37264a42953
+37264a42954
 > phosphorylate/DSGN
-37310,37311c42999
+37310,37311c43000
 < phrase's
 < phrase/AGDS
 ---
 > phrase/AGDSM
-37316d43003
+37316d43004
 < phrenetic
-37469,37470c43156
+37374c43062
+< picky/TR
+---
+> picky/TRP
+37469,37470c43157
 < pine's
 < pine/AGDS
 ---
 > pine/AGDSM
-37596,37597c43282
+37596,37597c43283
 < place's
 < place/EAGLDS
 ---
 > place/EAGLDSM
-37630a43316
+37630a43317
 > plaintext
-37636,37637c43322
+37636,37637c43323
 < plane's
 < plane/CGDS
 ---
 > plane/CGDSM
-37786,37787c43471
+37786,37787c43472
 < ploy's
 < ploy/S
 ---
 > ploy/SM
-37792,37793c43476
+37792,37793c43477
 < plug's
 < plug/US
 ---
 > plug/USM
-37796a43480
+37796a43481
 > plugin/MS
-37987c43671
+37987c43672
 < polypeptide/S
 ---
 > polypeptide/MS
-38106,38107c43790
+38106,38107c43791
 < port's
 < port/CAEGDS
 ---
 > port/CAEGDSM
-38134,38135c43817
+38134,38135c43818
 < pose's/A
 < pose/CAKEGDS
 ---
 > pose/CAKEGDSM
-38140,38141c43822
+38140,38141c43823
 < position's/KC
 < position/ACKES
 ---
 > position/ACKESM
-38260,38261c43941
+38260,38261c43942
 < pound's
 < pound/KDSG
 ---
 > pound/KDSGM
-38266a43947
+38266a43948
 > poutine/S
-38291d43971
+38291d43972
 < practise's
-38451a44132
+38451a44133
 > prejudgement/MS
-38568,38569c44249
+38568,38569c44250
 < press's
 < press/ACGSD
 ---
 > press/ACGSDM
-38638,38639c44318
+38638,38639c44319
 < price's
 < price/AGDS
 ---
 > price/AGDSM
-38756,38757c44435
+38756,38757c44436
 < process's
 < process/AGDS
 ---
 > process/AGDSM
-38780,38781c44458
+38780,38781c44459
 < produce's
 < produce/AZGDRS
 ---
 > produce/AZGDRSM
-38805a44483
+38805a44484
 > profiler/SM
-38835a44514
+38835a44515
 > programmatically
-38891a44571,44572
+38891a44572,44573
 > pronate/DSGN
 > pronator/MS
-38951c44632
+38951c44633
 < proprietorship/M
 ---
 > proprietorship/MS
-39039a44721
+39039a44722
 > provender/M
-39095a44778
+39095a44779
 > pseudorandom/Y
-39564a45248
+39564a45249
 > quinoa
-39581,39582c45265
+39581,39582c45266
 < quire's
 < quire/IAS
 ---
 > quire/IASM
-39614,39615c45297
+39614,39615c45298
 < quote's
 < quote/UDSG
 ---
 > quote/UDSGM
-39653,39654c45335
+39653,39654c45336
 < racoon's
 < racoons
 ---
 > racoon/MS
-39738,39739c45419
+39738,39739c45420
 < rail's
 < rail/CGDS
 ---
 > rail/CGDSM
-39816,39817c45496
+39816,39817c45497
 < range's
 < range/CGDS
 ---
 > range/CGDSM
-39873a45553,45554
+39873a45554,45555
 > rasterization/M
 > rasterize/SGDR
-39925,39926c45606
+39925,39926c45607
 < ravel's
 < ravel/UDSG
 ---
 > ravel/UDSGM
-40036a45717
+40036a45718
 > recency
-40140a45822
+40140a45823
 > recurse/DGSV
-40141a45824
+40141a45825
 > recuse/DGS
-40204,40205c45887
+40204,40205c45888
 < reel's
 < reel/UGDS
 ---
 > reel/UGDSM
-40208a45891
+40208a45892
 > refactor/SMDG
-40244d45926
+40244d45927
 < reflexion/SM
-40659d46340
+40659d46341
 < resizing
-40829c46510
+40829c46511
 < reverie/M
 ---
 > reverie/MS
-40895a46577,46579
+40895a46578,46580
 > rheumatological
 > rheumatology/M
 > rheumatologist/SM
-40944,40945c46628
+40944,40945c46629
 < ride's
 < ride/CZGS
 ---
 > ride/CZGSM
-41104,41105c46787
+41104,41105c46788
 < robe's
 < robe/EGDS
 ---
 > robe/EGDSM
-41132,41133c46814
+41132,41133c46815
 < rogue's
 < rogue/KS
 ---
 > rogue/KSM
-41185a46867
+41185a46868
 > rootkit/MS
-41258,41259c46940
+41258,41259c46941
 < route's
 < route/ADSG
 ---
 > route/ADSGM
-41415a47097
+41415a47098
 > sabre/MS
-41447,41448c47129
+41447,41448c47130
 < saddle's
 < saddle/UDSG
 ---
 > saddle/UDSGM
-41463,41464c47144
+41463,41464c47145
 < safe's
 < safe/UYTPR
 ---
 > safe/UYTPRM
-41544,41545c47224
+41544,41545c47225
 < salt's
 < salt/CTGDS
 ---
 > salt/CTGDSM
-41765,41766c47444
+41765,41766c47445
 < say's
 < say/USG
 ---
 > say/USGM
-41787,41788c47465
+41787,41788c47466
 < scale's
 < scale/ACSDG
 ---
 > scale/ACSDGM
-41806,41807c47483
+41806,41807c47484
 < scan's
 < scan/AS
 ---
 > scan/ASM
-41880,41881c47556
+41880,41881c47557
 < schedule's
 < schedule/ADSG
 ---
 > schedule/ADSGM
-41914c47589
+41914c47590
 < schnaps's
 ---
 > schnaps/M
-41949c47624
+41949c47625
 < schrod's
 ---
 > schrod/SM
-41998a47674
+41998a47675
 > scot-free
-42016,42017c47692
+42016,42017c47693
 < scramble's
 < scramble/UGDS
 ---
 > scramble/UGDSM
-42055,42056c47730
+42055,42056c47731
 < screw's
 < screw/UDSG
 ---
 > screw/UDSGM
-42065,42066c47739
+42065,42066c47740
 < scribe's
 < scribe/IKCGSD
 ---
 > scribe/IKCGSDM
-42170,42171c47843
+42170,42171c47844
 < seal's
 < seal/AUSDG
 ---
 > seal/AUSDGM
-42204,42205c47876
+42204,42205c47877
 < seat's
 < seat/UGDS
 ---
 > seat/UGDSM
-42288,42289c47959
+42288,42289c47960
 < seed's
 < seed/AGDS
 ---
 > seed/AGDSM
-42359c48029,48030
+42359c48030,48031
 < self/M
 ---
 > self/MG
 > selfie/S
-42361a48033,48034
+42361a48034,48035
 > selfism
 > selfist/S
-42365,42367c48038,48039
+42365,42367c48039,48040
 < sell's
 < sell/AZGRS
 < seller's
 ---
 > sell/AZGRSM
 > seller/M
-42524c48196
+42524c48197
 < seraphim's
 ---
 > seraphim/M
-42558,42559c48230
+42558,42559c48231
 < serve's/AF
 < serve/FACGDS
 ---
 > serve/FACGDSM
-42574,42575c48245
+42574,42575c48246
 < serving's
 < servings
 ---
 > serving/MS
-42594,42595c48264
+42594,42595c48265
 < settle's
 < settle/AUGDS
 ---
 > settle/AUGDSM
-42647,42648c48316
+42647,42648c48317
 < shackle's
 < shackle/UGDS
 ---
 > shackle/UGDSM
-42716,42717c48384
+42716,42717c48385
 < shape's
 < shape/AGDS
 ---
 > shape/AGDSM
-42851,42852c48518
+42851,42852c48519
 < ship's
 < ship/ALS
 ---
 > ship/ALSM
-42883,42885c48549
+42883,42885c48550
 < shit's
 < shit/S!
 < shite/S!
 ---
 > shit/MS!
-42887,42888c48551,48552
+42887,42888c48552,48553
 < shithead/S!
 < shitload/!
 ---
 > shithead/MS!
 > shitload/MS!
-42891c48555
+42891c48556
 < shitty/RT!
 ---
 > shitty/TR!
-42976a48641
+42976a48642
 > should've
-43008c48673
+43008c48674
 < showtime
 ---
 > showtime/MS
-43090,43091c48755
+43090,43091c48756
 < side's
 < side/AGDS
 ---
 > side/AGDSM
-43143,43144c48807
+43143,43144c48808
 < sign's
 < sign/AFCGDS
 ---
 > sign/AFCGDSM
-43163,43164c48826
+43163,43164c48827
 < signing's/C
 < signings
 ---
 > signing/MCS
-43328c48990
+43328c48991
 < size/MGBDRS
 ---
 > size/AMGBDRS
-43368,43369c49030
+43368,43369c49031
 < skill's
 < skill/CSD
 ---
 > skill/CSDM
-43724,43726c49385
+43724,43726c49386
 < smoulder's
 < smouldered
 < smoulders
 ---
 > smoulder/GSMD
-43752,43753c49411
+43752,43753c49412
 < snap's
 < snap/US
 ---
 > snap/USM
-43767,43768c49425,49427
+43767,43768c49426,49428
 < snarl's
 < snarl/USDG
 ---
 > snarkily
 > snarky/TR
 > snarl/USDGM
-44012,44013c49671
+44012,44013c49672
 < solute's
 < solute/XN
 ---
 > solute/XNM
-44015c49673
+44015c49674
 < solution's/EA
 ---
 > solution/EAM
-44021c49679
+44021c49680
 < solver's
 ---
 > solver/M
-44041a49700
+44041a49701
 > sommelier/SM
-44062c49721
+44062c49722
 < sonofabitch
 ---
 > sonofabitch/!
-44177,44178c49836
+44177,44178c49837
 < sow's
 < sow/ASGD
 ---
 > sow/ASGDM
-44346a50005
+44346a50006
 > spelled
-44348a50008
+44348a50009
 > spelt
-44371a50032
+44371a50033
 > spick/S!
-44383c50044
+44383c50045
 < spik/S
 ---
 > spik/S!
-44413,44414c50074
+44413,44414c50075
 < spire's
 < spire/IFAS
 ---
 > spire/IFASM
-44416,44417c50076
+44416,44417c50077
 < spirit's
 < spirit/ISGD
 ---
 > spirit/ISGDM
-44475,44476c50134
+44475,44476c50135
 < spoil's
 < spoil/CSDRZG
 ---
 > spoil/CSDRZGM
-44549,44550c50207
+44549,44550c50208
 < spray's
 < spray/ASDG
 ---
 > spray/ASDGM
-44688,44689c50345
+44688,44689c50346
 < staff's
 < staff/ASDG
 ---
 > staff/ASDGM
-44729,44730c50385
+44729,44730c50386
 < stall's
 < stall/SDG
 ---
 > stall/SDGM
-44871a50527
+44871a50528
 > steampunk
-44985,44986c50641
+44985,44986c50642
 < still's
 < still/ITGSD
 ---
 > still/ITGSDM
-45024,45025c50679
+45024,45025c50680
 < stitch's
 < stitch/ADSG
 ---
 > stitch/ADSGM
-45030,45031c50684
+45030,45031c50685
 < stock's
 < stock/AGSD
 ---
 > stock/AGSDM
-45090,45091c50743
+45090,45091c50744
 < stop's
 < stop/US
 ---
 > stop/USM
-45105,45106c50757
+45105,45106c50758
 < store's
 < store/ADSG
 ---
 > store/ADSGM
-45148,45149c50799
+45148,45149c50800
 < strain's
 < strain/FADSG
 ---
 > strain/FADSGM
-45164,45165c50814
+45164,45165c50815
 < strap's
 < strap/US
 ---
 > strap/USM
-45290,45291c50939
+45290,45291c50940
 < structure's
 < structure/AGDS
 ---
 > structure/AGDSM
-45330,45331c50978
+45330,45331c50979
 < study's
 < study/AGDS
 ---
 > study/AGDSM
-45368,45369c51015
+45368,45369c51016
 < style's
 < style/ADSG
 ---
 > style/ADSGM
-45455,45456c51101
+45455,45456c51102
 < submission's
 < submission/AS
 ---
 > submission/ASM
-45872,45873c51517
+45872,45873c51518
 < surface's
 < surface/AGDS
 ---
 > surface/AGDSM
-45918,45919c51562
+45918,45919c51563
 < survey's
 < survey/ADGS
 ---
 > survey/ADGSM
-46106a51750
+46106a51751
 > syllabi
-46160c51804
+46160c51805
 < synch/GMD
 ---
 > synch/GMDS
-46167d51810
+46167d51811
 < synchs
-46178a51822,51824
+46178a51823,51825
 > synesthesia
 > synesthete/S
 > synesthetic
-46203,46204c51849,51850
+46203,46204c51850,51851
 < sysadmin/S
 < sysop/S
 ---
 > sysadmin/MS
 > sysop/MS
-46363,46364c52009
+46363,46364c52010
 < tangle's
 < tangle/UDSG
 ---
 > tangle/UDSGM
-46632a52278,52279
+46632a52279,52280
 > teleport/SGD
 > teleportation
-46675,46676c52322
+46675,46676c52323
 < template's
 < template/S
 ---
 > template/SM
-46752a52399
+46752a52400
 > terabit/MS
-46753a52401,52402
+46753a52402,52403
 > terahertz/M
 > terapixel/MS
-46806,46807c52455
+46806,46807c52456
 < test's/AFK
 < test/AKFCDGS
 ---
 > test/AKFCDGSM
-46817a52466
+46817a52467
 > testcase/MS
-46831a52481
+46831a52482
 > testsuite/MS
-46845a52496
+46845a52497
 > textbox/SM
-46925a52577
+46925a52578
 > theremin/MS
-46999c52651
+46999c52652
 < thinking's
 ---
 > thinking/M
-47095,47096c52747
+47095,47096c52748
 < throne's
 < throne/CDS
 ---
 > throne/CDSM
-47188,47189c52839
+47188,47189c52840
 < tie's
 < tie/AUSD
 ---
 > tie/AUSDM
-47213,47214c52863
+47213,47214c52864
 < till's
 < till/EDRZGS
 ---
 > till/EDRZGSM
-47303,47304c52952
+47303,47304c52953
 < tire's
 < tire/AGDS
 ---
 > tire/AGDSM
-47433,47434c53081
+47433,47434c53082
 < tone's
 < tone/IZGDRS
 ---
 > tone/IZGDRSM
-47453,47455c53100,53101
+47453,47455c53101,53102
 < tool's
 < tool/ADGS
 < toolbar
 ---
 > tool/ADGSM
 > toolbar/MS
-47540,47541c53186
+47540,47541c53187
 < tort's
 < tort/FEAS
 ---
 > tort/FEASM
-47644a53290
+47644a53291
 > traceur/SM
-47657,47658c53303
+47657,47658c53304
 < tract's
 < tract/CEKFAS
 ---
 > tract/CEKFASM
-47755a53401
+47755a53402
 > transfect/DSMG
-47774a53421,53422
+47774a53422,53423
 > transgenderism
 > transgene/MS
-47807,47808c53455
+47807,47808c53456
 < transmission's
 < transmission/AS
 ---
 > transmission/ASM
-47928,47929c53575
+47928,47929c53576
 < trench's
 < trench/AIGSD
 ---
 > trench/AIGSDM
-47951c53597
+47951c53598
 < triage/M
 ---
 > triage/MGS
-47976,47977c53622
+47976,47977c53623
 < tribute's
 < tribute/FS
 ---
 > tribute/FSM
-47997a53643
+47997a53644
 > trifecta/S
-48165,48166c53811
+48165,48166c53812
 < trust's/E
 < trust/IESGD
 ---
 > trust/IESGDM
-48180,48181c53825
+48180,48181c53826
 < try's
 < try/AGDS
 ---
 > try/AGDSM
-48271a53916
+48271a53917
 > turducken
-48334a53980
+48334a53981
 > tweep/S
-48371,48372c54017
+48371,48372c54018
 < twist's
 < twist/USDG
 ---
 > twist/USDGM
-48396,48397c54041
+48396,48397c54042
 < type's
 < type/AGDS
 ---
 > type/AGDSM
-48869a54514
+48869a54515
 > unlikeable
-49163,49164c54808
+49163,49164c54809
 < usual's
 < usual/UY
 ---
 > usual/UYM
-49211c54855
+49211c54856
 < vagina/M
 ---
 > vagina/MS
-49249,49250c54893
+49249,49250c54894
 < value's
 < value/CAGSD
 ---
 > value/CAGSDM
-49292,49293c54935
+49292,49293c54936
 < variant's
 < variant/IS
 ---
 > variant/ISM
-49356,49357c54998
+49356,49357c54999
 < veil's
 < veil/UDGS
 ---
 > veil/UDGSM
-49368,49369c55009
+49368,49369c55010
 < velour's
 < velours's
 ---
 > velour/MS
-49398,49399c55038
+49398,49399c55039
 < vent's
 < vent/DGS
 ---
 > vent/DGSM
-49435,49436c55074
+49435,49436c55075
 < verge's
 < verge/FDSG
 ---
 > verge/FDSGM
-49478a55117
+49478a55118
 > vertices
-49488,49489c55127
+49488,49489c55128
 < vest's
 < vest/ILDGS
 ---
 > vest/ILDGSM
-49681,49682c55319
+49681,49682c55320
 < visit's
 < visit/ASGD
 ---
 > visit/ASGDM
-49772a55410,55412
+49772a55411,55413
 > volcanological
 > volcanologist/MS
 > volcanology/M
-49807,49808c55447
+49807,49808c55448
 < vote's
 < vote/CGVDS
 ---
 > vote/CGVDSM
-50148a55788
+50148a55789
 > weaponize/DSG
-50215,50216c55855
+50215,50216c55856
 < weigh's
 < weigh/AGD
 ---
 > weigh/AGDM
-50260,50261d55898
+50260,50261d55899
 < werwolf/M
 < werwolves
-50555,50556c56192
+50555,50556c56193
 < wind's
 < wind/UASG
 ---
 > wind/UASGM
-50626,50627c56262
+50626,50627c56263
 < wire's
 < wire/AGDS
 ---
 > wire/AGDSM
-50728c56363
+50728c56364
 < women
 ---
 > women/M
-50794,50796c56429,56430
+50794,50796c56430,56431
 < wop/S!
 < word's
 < word/AJDSG
 ---
 > wop/MS!
 > word/AJDSGM
-50801c56435
+50801c56436
 < wording's
 ---
 > wording/M
-50808,50809c56442
+50808,50809c56443
 < work's
 < work/ADJSG
 ---
 > work/ADJSGM
-50824c56457
+50824c56458
 < working's
 ---
 > working/M
-50884,50885c56517
+50884,50885c56518
 < worthy's
 < worthy/UPRT
 ---
 > worthy/UPRTM
-50903,50904c56535
+50903,50904c56536
 < wrap's
 < wrap/US
 ---
 > wrap/USM
-50945c56576
+50945c56577
 < writing's
 ---
 > writing/M
-51118,51119c56749
+51118,51119c56750
 < yoke's
 < yoke/UGDS
 ---
 > yoke/UGDSM
-51212,51213c56842
+51212,51213c56843
 < zip's
 < zip/US
 ---
 > zip/USM
-51228,51229c56857
+51228,51229c56858
 < zone's
 < zone/AGDS
 ---
 > zone/AGDSM
--- a/extensions/spellcheck/locales/en-US/hunspell/en-US.dic
+++ b/extensions/spellcheck/locales/en-US/hunspell/en-US.dic
@@ -1,9 +1,9 @@
-57244
+57245
 0/nm
 0th/pt
 1/n1
 1st/p
 1th/tc
 2/nm
 2nd/p
 2th/tc
@@ -24583,16 +24583,17 @@ courage/M
 courageous/YP
 courageousness/M
 courgette/S
 courier/MDSG
 course/EDGMS
 coursebook/S
 courser/MS
 coursework
+court-martial/SGD
 court/SMDYG
 courteous/EY
 courteousness/M
 courtesan/SM
 courtesy/ESM
 courthouse/MS
 courtier/SM
 courtliness/M
@@ -43375,17 +43376,17 @@ pickax/GMDS
 pickaxe/M
 picker/M
 pickerel/MS
 picket/ZGMDRS
 pickings/M
 pickle/MGDS
 pickpocket/SMG
 pickup/MS
-picky/TR
+picky/TRP
 picnic/MS
 picnicked
 picnicker/SM
 picnicking
 picoseconds
 picot/SM
 pictogram
 pictograph/M
--- a/gfx/layers/ImageContainer.cpp
+++ b/gfx/layers/ImageContainer.cpp
@@ -277,18 +277,18 @@ ImageContainer::LockCurrentImage()
 }
 
 TemporaryRef<gfx::SourceSurface>
 ImageContainer::LockCurrentAsSourceSurface(gfx::IntSize *aSize, Image** aCurrentImage)
 {
   ReentrantMonitorAutoEnter mon(mReentrantMonitor);
 
   if (aCurrentImage) {
-    NS_IF_ADDREF(mActiveImage);
-    *aCurrentImage = mActiveImage.get();
+    nsRefPtr<Image> activeImage(mActiveImage);
+    activeImage.forget(aCurrentImage);
   }
 
   if (!mActiveImage) {
     return nullptr;
   }
 
   *aSize = mActiveImage->GetSize();
   return mActiveImage->GetAsSourceSurface();
--- a/gfx/layers/basic/BasicLayersImpl.cpp
+++ b/gfx/layers/basic/BasicLayersImpl.cpp
@@ -26,17 +26,17 @@ GetMaskData(Layer* aMaskLayer,
   if (aMaskLayer) {
     RefPtr<SourceSurface> surface =
       static_cast<BasicImplData*>(aMaskLayer->ImplData())->GetAsSourceSurface();
     if (surface) {
       Matrix transform;
       Matrix4x4 effectiveTransform = aMaskLayer->GetEffectiveTransform();
       DebugOnly<bool> maskIs2D = effectiveTransform.CanDraw2D(&transform);
       NS_ASSERTION(maskIs2D, "How did we end up with a 3D transform here?!");
-      transform.PreTranslate(-aDeviceOffset.x, -aDeviceOffset.y);
+      transform.PostTranslate(-aDeviceOffset.x, -aDeviceOffset.y);
       aMaskData->Construct(transform, surface);
       return true;
     }
   }
   return false;
 }
 
 void
--- a/gfx/layers/client/TiledContentClient.cpp
+++ b/gfx/layers/client/TiledContentClient.cpp
@@ -786,17 +786,17 @@ TileClient::GetTileDescriptor()
   if (IsPlaceholderTile()) {
     return PlaceholderTileDescriptor();
   }
   MOZ_ASSERT(mFrontLock);
   if (mFrontLock->GetType() == gfxSharedReadLock::TYPE_MEMORY) {
     // AddRef here and Release when receiving on the host side to make sure the
     // reference count doesn't go to zero before the host receives the message.
     // see TiledLayerBufferComposite::TiledLayerBufferComposite
-    mFrontLock->AddRef();
+    mFrontLock.get()->AddRef();
   }
 
   if (mFrontLock->GetType() == gfxSharedReadLock::TYPE_MEMORY) {
     return TexturedTileDescriptor(nullptr, mFrontBuffer->GetIPDLActor(),
                                   mFrontBufferOnWhite ? MaybeTexture(mFrontBufferOnWhite->GetIPDLActor()) : MaybeTexture(null_t()),
                                   TileLock(uintptr_t(mFrontLock.get())));
   } else {
     gfxShmSharedReadLock *lock = static_cast<gfxShmSharedReadLock*>(mFrontLock.get());
--- a/gfx/layers/composite/TiledContentHost.cpp
+++ b/gfx/layers/composite/TiledContentHost.cpp
@@ -86,17 +86,17 @@ TiledLayerBufferComposite::TiledLayerBuf
             mIsValid = false;
 
             mRetainedTiles.Clear();
             return;
           }
           sharedLock = reinterpret_cast<gfxMemorySharedReadLock*>(ipcLock.get_uintptr_t());
           if (sharedLock) {
             // The corresponding AddRef is in TiledClient::GetTileDescriptor
-            sharedLock->Release();
+            sharedLock.get()->Release();
           }
         }
 
         CompositableTextureSourceRef textureSource;
         CompositableTextureSourceRef textureSourceOnWhite;
         if (texture) {
           texture->SetCompositor(aCompositor);
           texture->PrepareTextureSource(textureSource);
--- a/gfx/src/nsFontMetrics.cpp
+++ b/gfx/src/nsFontMetrics.cpp
@@ -28,38 +28,53 @@ class AutoTextRun {
 public:
     AutoTextRun(nsFontMetrics* aMetrics, nsRenderingContext* aRC,
                 const char* aString, int32_t aLength)
     {
         mTextRun = aMetrics->GetThebesFontGroup()->MakeTextRun(
             reinterpret_cast<const uint8_t*>(aString), aLength,
             aRC->ThebesContext(),
             aMetrics->AppUnitsPerDevPixel(),
-            ComputeFlags(aMetrics));
+            ComputeFlags(aMetrics),
+            nullptr);
     }
 
     AutoTextRun(nsFontMetrics* aMetrics, nsRenderingContext* aRC,
                 const char16_t* aString, int32_t aLength)
     {
         mTextRun = aMetrics->GetThebesFontGroup()->MakeTextRun(
             aString, aLength,
             aRC->ThebesContext(),
             aMetrics->AppUnitsPerDevPixel(),
-            ComputeFlags(aMetrics));
+            ComputeFlags(aMetrics),
+            nullptr);
     }
 
     gfxTextRun *get() { return mTextRun; }
     gfxTextRun *operator->() { return mTextRun; }
 
 private:
     static uint32_t ComputeFlags(nsFontMetrics* aMetrics) {
         uint32_t flags = 0;
         if (aMetrics->GetTextRunRTL()) {
             flags |= gfxTextRunFactory::TEXT_IS_RTL;
         }
+        if (aMetrics->GetVertical()) {
+            switch (aMetrics->GetTextOrientation()) {
+            case NS_STYLE_TEXT_ORIENTATION_MIXED:
+                flags |= gfxTextRunFactory::TEXT_ORIENT_VERTICAL_MIXED;
+                break;
+            case NS_STYLE_TEXT_ORIENTATION_UPRIGHT:
+                flags |= gfxTextRunFactory::TEXT_ORIENT_VERTICAL_UPRIGHT;
+                break;
+            case NS_STYLE_TEXT_ORIENTATION_SIDEWAYS_RIGHT:
+                flags |= gfxTextRunFactory::TEXT_ORIENT_VERTICAL_SIDEWAYS_RIGHT;
+                break;
+            }
+        }
         return flags;
     }
 
     nsAutoPtr<gfxTextRun> mTextRun;
 };
 
 class StubPropertyProvider : public gfxTextRun::PropertyProvider {
 public:
@@ -88,16 +103,17 @@ public:
         NS_ERROR("This shouldn't be called because we never enable spacing");
     }
 };
 
 } // anon namespace
 
 nsFontMetrics::nsFontMetrics()
     : mDeviceContext(nullptr), mP2A(0), mTextRunRTL(false)
+    , mVertical(false), mTextOrientation(0)
 {
 }
 
 nsFontMetrics::~nsFontMetrics()
 {
     if (mDeviceContext)
         mDeviceContext->FontMetricsDeleted(this);
 }
@@ -144,19 +160,20 @@ nsFontMetrics::Destroy()
 {
     mDeviceContext = nullptr;
 }
 
 // XXXTODO get rid of this macro
 #define ROUND_TO_TWIPS(x) (nscoord)floor(((x) * mP2A) + 0.5)
 #define CEIL_TO_TWIPS(x) (nscoord)ceil((x) * mP2A)
 
-const gfxFont::Metrics& nsFontMetrics::GetMetrics() const
+const gfxFont::Metrics&
+nsFontMetrics::GetMetrics(gfxFont::Orientation aOrientation) const
 {
-    return mFontGroup->GetFirstValidFont()->GetMetrics(mOrientation);
+    return mFontGroup->GetFirstValidFont()->GetMetrics(aOrientation);
 }
 
 nscoord
 nsFontMetrics::XHeight()
 {
     return ROUND_TO_TWIPS(GetMetrics().xHeight);
 }
 
@@ -267,17 +284,24 @@ nsFontMetrics::AveCharWidth()
 {
     // Use CEIL instead of ROUND for consistency with GetMaxAdvance
     return CEIL_TO_TWIPS(GetMetrics().aveCharWidth);
 }
 
 nscoord
 nsFontMetrics::SpaceWidth()
 {
-    return CEIL_TO_TWIPS(GetMetrics().spaceWidth);
+    // For vertical text with mixed or sideways orientation, we want the
+    // width of a horizontal space (even if we're using vertical line-spacing
+    // metrics, as with "writing-mode:vertical-*;text-orientation:mixed").
+    return CEIL_TO_TWIPS(
+        GetMetrics(mVertical &&
+                   mTextOrientation == NS_STYLE_TEXT_ORIENTATION_UPRIGHT
+                       ? gfxFont::eVertical
+                       : gfxFont::eHorizontal).spaceWidth);
 }
 
 int32_t
 nsFontMetrics::GetMaxStringLength()
 {
     const gfxFont::Metrics& m = GetMetrics();
     const double x = 32767.0 / m.maxAdvance;
     int32_t len = (int32_t)floor(x);
@@ -327,17 +351,21 @@ nsFontMetrics::DrawString(const char *aS
 
     StubPropertyProvider provider;
     AutoTextRun textRun(this, aContext, aString, aLength);
     if (!textRun.get()) {
         return;
     }
     gfxPoint pt(aX, aY);
     if (mTextRunRTL) {
-        pt.x += textRun->GetAdvanceWidth(0, aLength, &provider);
+        if (mVertical) {
+            pt.y += textRun->GetAdvanceWidth(0, aLength, &provider);
+        } else {
+            pt.x += textRun->GetAdvanceWidth(0, aLength, &provider);
+        }
     }
     textRun->Draw(aContext->ThebesContext(), pt, DrawMode::GLYPH_FILL, 0, aLength,
                   &provider, nullptr, nullptr);
 }
 
 void
 nsFontMetrics::DrawString(const char16_t* aString, uint32_t aLength,
                           nscoord aX, nscoord aY,
@@ -349,17 +377,21 @@ nsFontMetrics::DrawString(const char16_t
 
     StubPropertyProvider provider;
     AutoTextRun textRun(this, aTextRunConstructionContext, aString, aLength);
     if (!textRun.get()) {
         return;
     }
     gfxPoint pt(aX, aY);
     if (mTextRunRTL) {
-        pt.x += textRun->GetAdvanceWidth(0, aLength, &provider);
+        if (mVertical) {
+            pt.y += textRun->GetAdvanceWidth(0, aLength, &provider);
+        } else {
+            pt.x += textRun->GetAdvanceWidth(0, aLength, &provider);
+        }
     }
     textRun->Draw(aContext->ThebesContext(), pt, DrawMode::GLYPH_FILL, 0, aLength,
                   &provider, nullptr, nullptr);
 }
 
 static nsBoundingMetrics
 GetTextBoundingMetrics(nsFontMetrics* aMetrics, const char16_t *aString, uint32_t aLength,
                        nsRenderingContext *aContext, gfxFont::BoundingBoxType aType)
--- a/gfx/src/nsFontMetrics.h
+++ b/gfx/src/nsFontMetrics.h
@@ -164,27 +164,27 @@ public:
      * Returns the often needed width of the space character
      */
     nscoord SpaceWidth();
 
     /**
      * Returns the font associated with these metrics. The return value
      * is only defined after Init() has been called.
      */
-    const nsFont &Font() { return mFont; }
+    const nsFont &Font() const { return mFont; }
 
     /**
      * Returns the language associated with these metrics
      */
-    nsIAtom* Language() { return mLanguage; }
+    nsIAtom* Language() const { return mLanguage; }
 
     /**
      * Returns the orientation (horizontal/vertical) of these metrics.
      */
-    gfxFont::Orientation Orientation() { return mOrientation; }
+    gfxFont::Orientation Orientation() const { return mOrientation; }
 
     int32_t GetMaxStringLength();
 
     // Get the width for this string.  aWidth will be updated with the
     // width in points, not twips.  Callers must convert it if they
     // want it in another format.
     nscoord GetWidth(const char* aString, uint32_t aLength,
                      nsRenderingContext *aContext);
@@ -206,31 +206,58 @@ public:
 
     // Returns the LOOSE_INK_EXTENTS bounds of the text for determing the
     // overflow area of the string.
     nsBoundingMetrics GetInkBoundsForVisualOverflow(const char16_t *aString,
                                                     uint32_t aLength,
                                                     nsRenderingContext *aContext);
 
     void SetTextRunRTL(bool aIsRTL) { mTextRunRTL = aIsRTL; }
-    bool GetTextRunRTL() { return mTextRunRTL; }
+    bool GetTextRunRTL() const { return mTextRunRTL; }
+
+    void SetVertical(bool aVertical) { mVertical = aVertical; }
+    bool GetVertical() const { return mVertical; }
 
-    gfxFontGroup* GetThebesFontGroup() { return mFontGroup; }
-    gfxUserFontSet* GetUserFontSet() { return mFontGroup->GetUserFontSet(); }
+    void SetTextOrientation(uint8_t aTextOrientation)
+    {
+      mTextOrientation = aTextOrientation;
+    }
+    uint8_t GetTextOrientation() const { return mTextOrientation; }
 
-    int32_t AppUnitsPerDevPixel() { return mP2A; }
+    gfxFontGroup* GetThebesFontGroup() const { return mFontGroup; }
+    gfxUserFontSet* GetUserFontSet() const
+    {
+      return mFontGroup->GetUserFontSet();
+    }
+
+    int32_t AppUnitsPerDevPixel() const { return mP2A; }
 
 private:
     // Private destructor, to discourage deletion outside of Release():
     ~nsFontMetrics();
 
-    const gfxFont::Metrics& GetMetrics() const;
+    const gfxFont::Metrics& GetMetrics() const {
+      return GetMetrics(mOrientation);
+    }
+
+    const gfxFont::Metrics&
+    GetMetrics(const gfxFont::Orientation aFontOrientation) const;
 
     nsFont mFont;
     nsRefPtr<gfxFontGroup> mFontGroup;
     nsCOMPtr<nsIAtom> mLanguage;
     nsDeviceContext *mDeviceContext;
     int32_t mP2A;
+
+    // The font orientation (horizontal or vertical) for which these metrics
+    // have been initialized. This determines which line metrics (ascent and
+    // descent) they will return.
+    gfxFont::Orientation mOrientation;
+
+    // These fields may be set by clients to control the behavior of methods
+    // like GetWidth and DrawString according to the writing mode, direction
+    // and text-orientation desired.
     bool mTextRunRTL;
-    gfxFont::Orientation mOrientation;
+    bool mVertical;
+    uint8_t mTextOrientation;
 };
 
 #endif /* NSFONTMETRICS__H__ */
--- a/gfx/thebes/gfxFont.cpp
+++ b/gfx/thebes/gfxFont.cpp
@@ -3398,24 +3398,29 @@ gfxFont::CreateVerticalMetrics()
 
     gfxFontEntry::AutoTable os2Table(mFontEntry, kOS_2TableTag);
     if (os2Table && mFUnitsConvFactor > 0.0) {
         const OS2Table *os2 =
             reinterpret_cast<const OS2Table*>(hb_blob_get_data(os2Table, &len));
         // These fields should always be present in any valid OS/2 table
         if (len >= offsetof(OS2Table, sTypoLineGap) + sizeof(int16_t)) {
             SET_SIGNED(strikeoutSize, os2->yStrikeoutSize);
-            SET_SIGNED(aveCharWidth, int16_t(os2->sTypoAscender) -
-                                     int16_t(os2->sTypoDescender));
-            metrics->maxAscent =
-                std::max(metrics->maxAscent, int16_t(os2->xAvgCharWidth) *
-                                             gfxFloat(mFUnitsConvFactor));
-            metrics->maxDescent =
-                std::max(metrics->maxDescent, int16_t(os2->xAvgCharWidth) *
-                                              gfxFloat(mFUnitsConvFactor));
+            // Use ascent+descent from the horizontal metrics as the default
+            // advance (aveCharWidth) in vertical mode
+            gfxFloat ascentDescent = gfxFloat(mFUnitsConvFactor) *
+                (int16_t(os2->sTypoAscender) - int16_t(os2->sTypoDescender));
+            metrics->aveCharWidth =
+                std::max(metrics->emHeight, ascentDescent);
+            // Use xAvgCharWidth from horizontal metrics as minimum font extent
+            // for vertical layout, applying half of it to ascent and half to
+            // descent (to work with a default centered baseline).
+            gfxFloat halfCharWidth =
+                int16_t(os2->xAvgCharWidth) * gfxFloat(mFUnitsConvFactor) / 2;
+            metrics->maxAscent = std::max(metrics->maxAscent, halfCharWidth);
+            metrics->maxDescent = std::max(metrics->maxDescent, halfCharWidth);
         }
     }
 
     // If we didn't set aveCharWidth from OS/2, try to read 'hhea' metrics
     // and use the line height from its ascent/descent.
     if (!metrics->aveCharWidth) {
         gfxFontEntry::AutoTable hheaTable(mFontEntry, kHheaTableTag);
         if (hheaTable && mFUnitsConvFactor > 0.0) {
@@ -3435,18 +3440,22 @@ gfxFont::CreateVerticalMetrics()
     // Read real vertical metrics if available.
     gfxFontEntry::AutoTable vheaTable(mFontEntry, kVheaTableTag);
     if (vheaTable && mFUnitsConvFactor > 0.0) {
         const MetricsHeader* vhea =
             reinterpret_cast<const MetricsHeader*>
                 (hb_blob_get_data(vheaTable, &len));
         if (len >= sizeof(MetricsHeader)) {
             SET_UNSIGNED(maxAdvance, vhea->advanceWidthMax);
-            SET_SIGNED(maxAscent, vhea->ascender);
-            SET_SIGNED(maxDescent, -int16_t(vhea->descender));
+            // Redistribute space between ascent/descent because we want a
+            // centered vertical baseline by default.
+            gfxFloat halfExtent = 0.5 * gfxFloat(mFUnitsConvFactor) *
+                (int16_t(vhea->ascender) - int16_t(vhea->descender));
+            metrics->maxAscent = halfExtent;
+            metrics->maxDescent = halfExtent;
             SET_SIGNED(externalLeading, vhea->lineGap);
         }
     }
 
     // If we didn't set aveCharWidth above, we must be dealing with a non-sfnt
     // font of some kind (Type1, bitmap, vector, ...), so fall back to using
     // whatever the platform backend figured out for horizontal layout.
     // And if we haven't set externalLeading yet, then copy that from the
--- a/gfx/thebes/gfxHarfBuzzShaper.cpp
+++ b/gfx/thebes/gfxHarfBuzzShaper.cpp
@@ -248,20 +248,20 @@ gfxHarfBuzzShaper::HBGetGlyphHAdvance(hb
 
 /* static */
 hb_position_t
 gfxHarfBuzzShaper::HBGetGlyphVAdvance(hb_font_t *font, void *font_data,
                                       hb_codepoint_t glyph, void *user_data)
 {
     const gfxHarfBuzzShaper::FontCallbackData *fcd =
         static_cast<const gfxHarfBuzzShaper::FontCallbackData*>(font_data);
-    gfxFont *gfxfont = fcd->mShaper->GetFont();
-    if (gfxfont->ProvidesGlyphWidths()) {
-        return gfxfont->GetGlyphWidth(*fcd->mContext->GetDrawTarget(), glyph);
-    }
+    // Currently, we don't offer gfxFont subclasses a method to override this
+    // and provide hinted platform-specific vertical advances (analogous to the
+    // GetGlyphWidth method for horizontal advances). If that proves necessary,
+    // we'll add a new gfxFont method and call it from here.
     return fcd->mShaper->GetGlyphVAdvance(glyph);
 }
 
 /* static */
 hb_bool_t
 gfxHarfBuzzShaper::HBGetGlyphHOrigin(hb_font_t *font, void *font_data,
                                      hb_codepoint_t glyph,
                                      hb_position_t *x, hb_position_t *y,
--- a/gfx/thebes/gfxPlatform.cpp
+++ b/gfx/thebes/gfxPlatform.cpp
@@ -175,28 +175,32 @@ private:
   bool UpdateStringsVector(const std::string& aString);
   void UpdateCrashReport();
 
 private:
   std::vector<std::pair<int32_t,std::string> > mBuffer;
   nsCString mCrashCriticalKey;
   uint32_t mMaxCapacity;
   int32_t mIndex;
+  Mutex mMutex;
 };
 
 CrashStatsLogForwarder::CrashStatsLogForwarder(const char* aKey)
   : mBuffer()
   , mCrashCriticalKey(aKey)
   , mMaxCapacity(0)
   , mIndex(-1)
+  , mMutex("CrashStatsLogForwarder")
 {
 }
 
 void CrashStatsLogForwarder::SetCircularBufferSize(uint32_t aCapacity)
 {
+  MutexAutoLock lock(mMutex);
+
   mMaxCapacity = aCapacity;
   mBuffer.reserve(static_cast<size_t>(aCapacity));
 }
 
 bool
 CrashStatsLogForwarder::UpdateStringsVector(const std::string& aString)
 {
   // We want at least the first one and the last one.  Otherwise, no point.
@@ -239,16 +243,18 @@ void CrashStatsLogForwarder::UpdateCrash
   if (annotated != NS_OK) {
     printf("Crash Annotation %s: %s",
            mCrashCriticalKey.get(), message.str().c_str());
   }
 }
   
 void CrashStatsLogForwarder::Log(const std::string& aString)
 {
+  MutexAutoLock lock(mMutex);
+
   if (UpdateStringsVector(aString)) {
     UpdateCrashReport();
   }
 }
 
 NS_IMPL_ISUPPORTS(SRGBOverrideObserver, nsIObserver, nsISupportsWeakReference)
 
 #define GFX_DOWNLOADABLE_FONTS_ENABLED "gfx.downloadable_fonts.enabled"
--- a/gfx/thebes/gfxQuartzSurface.cpp
+++ b/gfx/thebes/gfxQuartzSurface.cpp
@@ -174,17 +174,17 @@ already_AddRefed<gfxImageSurface> gfxQua
         return nullptr;
 
     nsRefPtr<gfxASurface> img = Wrap(surface);
 
     // cairo_quartz_surface_get_image returns a referenced image, and thebes
     // shares the refcounts of Cairo surfaces. However, Wrap also adds a
     // reference to the image. We need to remove one of these references
     // explicitly so we don't leak.
-    img->Release();
+    img.get()->Release();
 
     img->SetOpaqueRect(GetOpaqueRect());
 
     return img.forget().downcast<gfxImageSurface>();
 }
 
 gfxQuartzSurface::~gfxQuartzSurface()
 {
--- a/gfx/thebes/gfxTextRun.cpp
+++ b/gfx/thebes/gfxTextRun.cpp
@@ -23,16 +23,17 @@
 #include "mozilla/Likely.h"
 #include "gfx2DGlue.h"
 
 #include "cairo.h"
 
 using namespace mozilla;
 using namespace mozilla::gfx;
 using namespace mozilla::unicode;
+using mozilla::services::GetObserverService;
 
 static const char16_t kEllipsisChar[] = { 0x2026, 0x0 };
 static const char16_t kASCIIPeriodsChar[] = { '.', '.', '.', 0x0 };
 
 #ifdef DEBUG_roc
 #define DEBUG_TEXT_RUN_STORAGE_METRICS
 #endif
 
@@ -2034,22 +2035,22 @@ gfxFontGroup::MakeHyphenTextRun(gfxConte
 {
     // only use U+2010 if it is supported by the first font in the group;
     // it's better to use ASCII '-' from the primary font than to fall back to
     // U+2010 from some other, possibly poorly-matching face
     static const char16_t hyphen = 0x2010;
     gfxFont *font = GetFirstValidFont(uint32_t(hyphen));
     if (font->HasCharacter(hyphen)) {
         return MakeTextRun(&hyphen, 1, aCtx, aAppUnitsPerDevUnit,
-                           gfxFontGroup::TEXT_IS_PERSISTENT);
+                           gfxFontGroup::TEXT_IS_PERSISTENT, nullptr);
     }
 
     static const uint8_t dash = '-';
     return MakeTextRun(&dash, 1, aCtx, aAppUnitsPerDevUnit,
-                       gfxFontGroup::TEXT_IS_PERSISTENT);
+                       gfxFontGroup::TEXT_IS_PERSISTENT, nullptr);
 }
 
 gfxFloat
 gfxFontGroup::GetHyphenWidth(gfxTextRun::PropertyProvider *aProvider)
 {
     if (mHyphenWidth < 0) {
         nsRefPtr<gfxContext> ctx(aProvider->GetContext());
         if (ctx) {
@@ -2060,17 +2061,18 @@ gfxFontGroup::GetHyphenWidth(gfxTextRun:
                 hyphRun->GetAdvanceWidth(0, hyphRun->GetLength(), nullptr) : 0;
         }
     }
     return mHyphenWidth;
 }
 
 gfxTextRun *
 gfxFontGroup::MakeTextRun(const uint8_t *aString, uint32_t aLength,
-                          const Parameters *aParams, uint32_t aFlags)
+                          const Parameters *aParams, uint32_t aFlags,
+                          gfxMissingFontRecorder *aMFR)
 {
     if (aLength == 0) {
         return MakeEmptyTextRun(aParams, aFlags);
     }
     if (aLength == 1 && aString[0] == ' ') {
         return MakeSpaceTextRun(aParams, aFlags);
     }
 
@@ -2084,26 +2086,27 @@ gfxFontGroup::MakeTextRun(const uint8_t 
     }
 
     gfxTextRun *textRun = gfxTextRun::Create(aParams, aLength,
                                              this, aFlags);
     if (!textRun) {
         return nullptr;
     }
 
-    InitTextRun(aParams->mContext, textRun, aString, aLength);
+    InitTextRun(aParams->mContext, textRun, aString, aLength, aMFR);
 
     textRun->FetchGlyphExtents(aParams->mContext);
 
     return textRun;
 }
 
 gfxTextRun *
 gfxFontGroup::MakeTextRun(const char16_t *aString, uint32_t aLength,
-                          const Parameters *aParams, uint32_t aFlags)
+                          const Parameters *aParams, uint32_t aFlags,
+                          gfxMissingFontRecorder *aMFR)
 {
     if (aLength == 0) {
         return MakeEmptyTextRun(aParams, aFlags);
     }
     if (aLength == 1 && aString[0] == ' ') {
         return MakeSpaceTextRun(aParams, aFlags);
     }
     if (GetStyle()->size == 0) {
@@ -2111,29 +2114,30 @@ gfxFontGroup::MakeTextRun(const char16_t
     }
 
     gfxTextRun *textRun = gfxTextRun::Create(aParams, aLength,
                                              this, aFlags);
     if (!textRun) {
         return nullptr;
     }
 
-    InitTextRun(aParams->mContext, textRun, aString, aLength);
+    InitTextRun(aParams->mContext, textRun, aString, aLength, aMFR);
 
     textRun->FetchGlyphExtents(aParams->mContext);
 
     return textRun;
 }
 
 template<typename T>
 void
 gfxFontGroup::InitTextRun(gfxContext *aContext,
                           gfxTextRun *aTextRun,
                           const T *aString,
-                          uint32_t aLength)
+                          uint32_t aLength,
+                          gfxMissingFontRecorder *aMFR)
 {
     NS_ASSERTION(aLength > 0, "don't call InitTextRun for a zero-length run");
 
     // we need to do numeral processing even on 8-bit text,
     // in case we're converting Western to Hindi/Arabic digits
     int32_t numOption = gfxPlatform::GetPlatform()->GetBidiNumeralOption();
     nsAutoArrayPtr<char16_t> transformedString;
     if (numOption != IBMBIDI_NUMERAL_NOMINAL) {
@@ -2203,17 +2207,17 @@ gfxFontGroup::InitTextRun(gfxContext *aC
                         sizeof(T),
                         str.get()));
             }
 #endif
 
             // the text is still purely 8-bit; bypass the script-run itemizer
             // and treat it as a single Latin run
             InitScriptRun(aContext, aTextRun, aString,
-                          0, aLength, MOZ_SCRIPT_LATIN);
+                          0, aLength, MOZ_SCRIPT_LATIN, aMFR);
         } else {
             const char16_t *textPtr;
             if (transformedString) {
                 textPtr = transformedString.get();
             } else {
                 // typecast to avoid compilation error for the 8-bit version,
                 // even though this is dead code in that case
                 textPtr = reinterpret_cast<const char16_t*>(aString);
@@ -2251,17 +2255,17 @@ gfxFontGroup::InitTextRun(gfxContext *aC
                                                                     "normal")),
                             mStyle.size,
                             sizeof(T),
                             NS_ConvertUTF16toUTF8(textPtr + runStart, runLen).get()));
                 }
     #endif
 
                 InitScriptRun(aContext, aTextRun, textPtr + runStart,
-                              runStart, runLimit - runStart, runScript);
+                              runStart, runLimit - runStart, runScript, aMFR);
             }
         }
 
         // if shaping was aborted due to lack of feature support, clear out
         // glyph runs and redo shaping with fallback forced on
         if (aTextRun->GetShapingState() == gfxTextRun::eShapingState_Aborted) {
             redo = true;
             aTextRun->SetShapingState(
@@ -2287,26 +2291,35 @@ gfxFontGroup::InitTextRun(gfxContext *aC
     // pathologically-bad perf in the case where a textrun contains many script
     // changes (see bug 680402) - we'd end up re-sanitizing all the earlier runs
     // every time a new script subrun is processed.
     aTextRun->SanitizeGlyphRuns();
 
     aTextRun->SortGlyphRuns();
 }
 
+static inline bool
+IsPUA(uint32_t aUSV)
+{
+    // We could look up the General Category of the codepoint here,
+    // but it's simpler to check PUA codepoint ranges.
+    return (aUSV >= 0xE000 && aUSV <= 0xF8FF) || (aUSV >= 0xF0000);
+}
+
 template<typename T>
 void
 gfxFontGroup::InitScriptRun(gfxContext *aContext,
                             gfxTextRun *aTextRun,
                             const T *aString, // text for this script run,
                                               // not the entire textrun
                             uint32_t aOffset, // position of the script run
                                               // within the textrun
                             uint32_t aLength, // length of the script run
-                            int32_t aRunScript)
+                            int32_t aRunScript,
+                            gfxMissingFontRecorder *aMFR)
 {
     NS_ASSERTION(aLength > 0, "don't call InitScriptRun for a 0-length run");
     NS_ASSERTION(aTextRun->GetShapingState() != gfxTextRun::eShapingState_Aborted,
                  "don't call InitScriptRun with aborted shaping state");
 
 #if defined(XP_MACOSX) || defined(XP_WIN) || defined(ANDROID)
     // non-linux platforms build the fontlist lazily and include userfonts
     // so need to confirm the load state of userfonts in the list
@@ -2317,16 +2330,17 @@ gfxFontGroup::InitScriptRun(gfxContext *
 
     gfxFont *mainFont = GetFirstValidFont();
 
     uint32_t runStart = 0;
     nsAutoTArray<gfxTextRange,3> fontRanges;
     ComputeRanges(fontRanges, aString, aLength, aRunScript,
                   aTextRun->GetFlags() & gfxTextRunFactory::TEXT_ORIENT_MASK);
     uint32_t numRanges = fontRanges.Length();
+    bool missingChars = false;
 
     for (uint32_t r = 0; r < numRanges; r++) {
         const gfxTextRange& range = fontRanges[r];
         uint32_t matchedLength = range.Length();
         gfxFont *matchedFont = range.font;
         bool vertical =
             range.orientation == gfxTextRunFactory::TEXT_ORIENT_VERTICAL_UPRIGHT;
         // create the glyph run for this range
@@ -2463,21 +2477,25 @@ gfxFontGroup::InitScriptRun(gfxContext *
 
                 // for 16-bit textruns only, check for surrogate pairs and
                 // special Unicode spaces; omit these checks in 8-bit runs
                 if (sizeof(T) == sizeof(char16_t)) {
                     if (NS_IS_HIGH_SURROGATE(ch) &&
                         index + 1 < aLength &&
                         NS_IS_LOW_SURROGATE(aString[index + 1]))
                     {
+                        uint32_t usv =
+                            SURROGATE_TO_UCS4(ch, aString[index + 1]);
                         aTextRun->SetMissingGlyph(aOffset + index,
-                                                  SURROGATE_TO_UCS4(ch,
-                                                                    aString[index + 1]),
+                                                  usv,
                                                   mainFont);
                         index++;
+                        if (!mSkipDrawing && !IsPUA(usv)) {
+                            missingChars = true;
+                        }
                         continue;
                     }
 
                     // check if this is a known Unicode whitespace character that
                     // we can render using the space glyph with a custom width
                     gfxFloat wid = mainFont->SynthesizeSpaceWidth(ch);
                     if (wid >= 0.0) {
                         nscoord advance =
@@ -2502,21 +2520,28 @@ gfxFontGroup::InitScriptRun(gfxContext *
 
                 if (IsInvalidChar(ch)) {
                     // invalid chars are left as zero-width/invisible
                     continue;
                 }
 
                 // record char code so we can draw a box with the Unicode value
                 aTextRun->SetMissingGlyph(aOffset + index, ch, mainFont);
+                if (!mSkipDrawing && !IsPUA(ch)) {
+                    missingChars = true;
+                }
             }
         }
 
         runStart += matchedLength;
     }
+
+    if (aMFR && missingChars) {
+        aMFR->RecordScript(aRunScript);
+    }
 }
 
 gfxTextRun *
 gfxFontGroup::GetEllipsisTextRun(int32_t aAppUnitsPerDevPixel,
                                  LazyReferenceContextGetter& aRefContextGetter)
 {
     if (mCachedEllipsisTextRun &&
         mCachedEllipsisTextRun->GetAppUnitsPerDevUnit() == aAppUnitsPerDevPixel) {
@@ -2532,17 +2557,18 @@ gfxFontGroup::GetEllipsisTextRun(int32_t
         : nsDependentString(kASCIIPeriodsChar,
                             ArrayLength(kASCIIPeriodsChar) - 1);
 
     nsRefPtr<gfxContext> refCtx = aRefContextGetter.GetRefContext();
     Parameters params = {
         refCtx, nullptr, nullptr, nullptr, 0, aAppUnitsPerDevPixel
     };
     gfxTextRun* textRun =
-        MakeTextRun(ellipsis.get(), ellipsis.Length(), &params, TEXT_IS_PERSISTENT);
+        MakeTextRun(ellipsis.get(), ellipsis.Length(), &params,
+                    TEXT_IS_PERSISTENT, nullptr);
     if (!textRun) {
         return nullptr;
     }
     mCachedEllipsisTextRun = textRun;
     textRun->ReleaseFontGroup(); // don't let the presence of a cached ellipsis
                                  // textrun prolong the fontgroup's life
     return textRun;
 }
@@ -3104,8 +3130,46 @@ gfxFontGroup::WhichSystemFontSupportsCha
 
 /*static*/ void
 gfxFontGroup::Shutdown()
 {
     NS_IF_RELEASE(gLangService);
 }
 
 nsILanguageAtomService* gfxFontGroup::gLangService = nullptr;
+
+void
+gfxMissingFontRecorder::Flush()
+{
+    static bool mNotifiedFontsInitialized = false;
+    static uint32_t mNotifiedFonts[gfxMissingFontRecorder::kNumScriptBitsWords];
+    if (!mNotifiedFontsInitialized) {
+        memset(&mNotifiedFonts, 0, sizeof(mNotifiedFonts));
+        mNotifiedFontsInitialized = true;
+    }
+
+    nsAutoString fontNeeded;
+    for (uint32_t i = 0; i < kNumScriptBitsWords; ++i) {
+        mMissingFonts[i] &= ~mNotifiedFonts[i];
+        if (!mMissingFonts[i]) {
+            continue;
+        }
+        for (uint32_t j = 0; j < 32; ++j) {
+            if (!(mMissingFonts[i] & (1 << j))) {
+                continue;
+            }
+            mNotifiedFonts[i] |= (1 << j);
+            if (!fontNeeded.IsEmpty()) {
+                fontNeeded.Append(PRUnichar(','));
+            }
+            uint32_t tag = GetScriptTagForCode(i * 32 + j);
+            fontNeeded.Append(char16_t(tag >> 24));
+            fontNeeded.Append(char16_t((tag >> 16) & 0xff));
+            fontNeeded.Append(char16_t((tag >> 8) & 0xff));
+            fontNeeded.Append(char16_t(tag & 0xff));
+        }
+        mMissingFonts[i] = 0;
+    }
+    if (!fontNeeded.IsEmpty()) {
+        nsCOMPtr<nsIObserverService> service = GetObserverService();
+        service->NotifyObservers(nullptr, "font-needed", fontNeeded.get());
+    }
+}
--- a/gfx/thebes/gfxTextRun.h
+++ b/gfx/thebes/gfxTextRun.h
@@ -11,27 +11,29 @@
 #include "gfxPoint.h"
 #include "gfxFont.h"
 #include "nsTArray.h"
 #include "gfxSkipChars.h"
 #include "gfxPlatform.h"
 #include "mozilla/MemoryReporting.h"
 #include "DrawMode.h"
 #include "harfbuzz/hb.h"
+#include "nsUnicodeScriptCodes.h"
 
 #ifdef DEBUG
 #include <stdio.h>
 #endif
 
 class gfxContext;
 class gfxFontGroup;
 class gfxUserFontSet;
 class gfxTextContextPaint;
 class nsIAtom;
 class nsILanguageAtomService;
+class gfxMissingFontRecorder;
 
 /**
  * Callback for Draw() to use when drawing text with mode
  * DrawMode::GLYPH_PATH.
  */
 struct gfxTextRunDrawCallbacks {
 
     /**
@@ -764,40 +766,43 @@ public:
 
     /**
      * Make a textrun for a given string.
      * If aText is not persistent (aFlags & TEXT_IS_PERSISTENT), the
      * textrun will copy it.
      * This calls FetchGlyphExtents on the textrun.
      */
     virtual gfxTextRun *MakeTextRun(const char16_t *aString, uint32_t aLength,
-                                    const Parameters *aParams, uint32_t aFlags);
+                                    const Parameters *aParams, uint32_t aFlags,
+                                    gfxMissingFontRecorder *aMFR);
     /**
      * Make a textrun for a given string.
      * If aText is not persistent (aFlags & TEXT_IS_PERSISTENT), the
      * textrun will copy it.
      * This calls FetchGlyphExtents on the textrun.
      */
     virtual gfxTextRun *MakeTextRun(const uint8_t *aString, uint32_t aLength,
-                                    const Parameters *aParams, uint32_t aFlags);
+                                    const Parameters *aParams, uint32_t aFlags,
+                                    gfxMissingFontRecorder *aMFR);
 
     /**
      * Textrun creation helper for clients that don't want to pass
      * a full Parameters record.
      */
     template<typename T>
     gfxTextRun *MakeTextRun(const T *aString, uint32_t aLength,
                             gfxContext *aRefContext,
                             int32_t aAppUnitsPerDevUnit,
-                            uint32_t aFlags)
+                            uint32_t aFlags,
+                            gfxMissingFontRecorder *aMFR)
     {
         gfxTextRunFactory::Parameters params = {
             aRefContext, nullptr, nullptr, nullptr, 0, aAppUnitsPerDevUnit
         };
-        return MakeTextRun(aString, aLength, &params, aFlags);
+        return MakeTextRun(aString, aLength, &params, aFlags, aMFR);
     }
 
     /**
      * Get the (possibly-cached) width of the hyphen character.
      * The aCtx and aAppUnitsPerDevUnit parameters will be used only if
      * needed to initialize the cached hyphen width; otherwise they are
      * ignored.
      */
@@ -1083,27 +1088,29 @@ protected:
     void InitMetricsForBadFont(gfxFont* aBadFont);
 
     // Set up the textrun glyphs for an entire text run:
     // find script runs, and then call InitScriptRun for each
     template<typename T>
     void InitTextRun(gfxContext *aContext,
                      gfxTextRun *aTextRun,
                      const T *aString,
-                     uint32_t aLength);
+                     uint32_t aLength,
+                     gfxMissingFontRecorder *aMFR);
 
     // InitTextRun helper to handle a single script run, by finding font ranges
     // and calling each font's InitTextRun() as appropriate
     template<typename T>
     void InitScriptRun(gfxContext *aContext,
                        gfxTextRun *aTextRun,
                        const T *aString,
                        uint32_t aScriptRunStart,
                        uint32_t aScriptRunEnd,
-                       int32_t aRunScript);
+                       int32_t aRunScript,
+                       gfxMissingFontRecorder *aMFR);
 
     // Helper for font-matching:
     // When matching the italic case, allow use of the regular face
     // if it supports a character but the italic one doesn't.
     // Return null if regular face doesn't support aCh
     already_AddRefed<gfxFont>
     FindNonItalicFaceForChar(gfxFontFamily* aFamily, uint32_t aCh);
 
@@ -1119,9 +1126,61 @@ protected:
 
     // lookup and add a font with a given name (i.e. *not* a generic!)
     virtual void FindPlatformFont(const nsAString& aName,
                                   bool aUseFontSet,
                                   void *aClosure);
 
     static nsILanguageAtomService* gLangService;
 };
+
+// A "missing font recorder" is to be used during text-run creation to keep
+// a record of any scripts encountered for which font coverage was lacking;
+// when Flush() is called, it sends a notification that front-end code can use
+// to download fonts on demand (or whatever else it wants to do).
+
+#define GFX_MISSING_FONTS_NOTIFY_PREF "gfx.missing_fonts.notify"
+
+class gfxMissingFontRecorder {
+public:
+    gfxMissingFontRecorder()
+    {
+        MOZ_COUNT_CTOR(gfxMissingFontRecorder);
+        memset(&mMissingFonts, 0, sizeof(mMissingFonts));
+    }
+
+    ~gfxMissingFontRecorder()
+    {
+#ifdef DEBUG
+        for (uint32_t i = 0; i < kNumScriptBitsWords; i++) {
+            NS_ASSERTION(mMissingFonts[i] == 0,
+                         "failed to flush the missing-font recorder");
+        }
 #endif
+        MOZ_COUNT_DTOR(gfxMissingFontRecorder);
+    }
+
+    // record this script code in our mMissingFonts bitset
+    void RecordScript(int32_t aScriptCode)
+    {
+        mMissingFonts[uint32_t(aScriptCode) >> 5] |=
+            (1 << (uint32_t(aScriptCode) & 0x1f));
+    }
+
+    // send a notification of any missing-scripts that have been
+    // recorded, and clear the mMissingFonts set for re-use
+    void Flush();
+
+    // forget any missing-scripts that have been recorded up to now;
+    // called before discarding a recorder we no longer care about
+    void Clear()
+    {
+        memset(&mMissingFonts, 0, sizeof(mMissingFonts));
+    }
+
+private:
+    // Number of 32-bit words needed for the missing-script flags
+    static const uint32_t kNumScriptBitsWords =
+        ((MOZ_NUM_SCRIPT_CODES + 31) / 32);
+    uint32_t mMissingFonts[kNumScriptBitsWords];
+};
+
+#endif
--- a/image/src/imgLoader.cpp
+++ b/image/src/imgLoader.cpp
@@ -2426,16 +2426,26 @@ ProxyListener::~ProxyListener()
 /* void onStartRequest (in nsIRequest request, in nsISupports ctxt); */
 NS_IMETHODIMP ProxyListener::OnStartRequest(nsIRequest *aRequest, nsISupports *ctxt)
 {
   if (!mDestListener)
     return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
   if (channel) {
+    // We need to set the initiator type for the image load
+    nsCOMPtr<nsITimedChannel> timedChannel = do_QueryInterface(channel);
+    if (timedChannel) {
+      nsAutoString type;
+      timedChannel->GetInitiatorType(type);
+      if (type.IsEmpty()) {
+        timedChannel->SetInitiatorType(NS_LITERAL_STRING("img"));
+      }
+    }
+
     nsAutoCString contentType;
     nsresult rv = channel->GetContentType(contentType);
 
     if (!contentType.IsEmpty()) {
      /* If multipart/x-mixed-replace content, we'll insert a MIME decoder
         in the pipeline to handle the content and pass it along to our
         original listener.
       */
--- a/ipc/glue/MessageChannel.cpp
+++ b/ipc/glue/MessageChannel.cpp
@@ -714,16 +714,19 @@ MessageChannel::Send(Message* aMsg, Mess
 {
     // See comment in DispatchSyncMessage.
     MaybeScriptBlocker scriptBlocker(this, true);
 
     // Sanity checks.
     AssertWorkerThread();
     mMonitor->AssertNotCurrentThreadOwns();
 
+    if (mCurrentTransaction == 0)
+        mListener->OnBeginSyncTransaction();
+
 #ifdef OS_WIN
     SyncStackFrame frame(this, false);
 #endif
 
     CxxStackFrame f(*this, OUT_MESSAGE, aMsg);
 
     MonitorAutoLock lock(*mMonitor);
 
--- a/ipc/glue/MessageLink.h
+++ b/ipc/glue/MessageLink.h
@@ -83,16 +83,20 @@ class MessageListener
         NS_RUNTIMEABORT("default impl shouldn't be invoked");
     }
     virtual void OnEnteredCall() {
         NS_RUNTIMEABORT("default impl shouldn't be invoked");
     }
     virtual void OnExitedCall() {
         NS_RUNTIMEABORT("default impl shouldn't be invoked");
     }
+    /* This callback is called when a sync message is sent that begins a new IPC transaction
+       (i.e., when it is not part of an existing sequence of nested messages). */
+    virtual void OnBeginSyncTransaction() {
+    }
     virtual RacyInterruptPolicy MediateInterruptRace(const Message& parent,
                                                      const Message& child)
     {
         return RIPChildWins;
     }
 
     virtual void ProcessRemoteNativeEventsInInterruptCall() {
     }
rename from js/src/vm/NumericConversions.h
rename to js/public/Conversions.h
--- a/js/src/vm/NumericConversions.h
+++ b/js/public/Conversions.h
@@ -1,25 +1,26 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * 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 vm_NumericConversions_h
-#define vm_NumericConversions_h
+/* ECMAScript conversion operations. */
 
-#include "mozilla/Assertions.h"
+#ifndef js_Conversions_h
+#define js_Conversions_h
+
 #include "mozilla/Casting.h"
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/TypeTraits.h"
 
 #include <math.h>
 
-namespace js {
+namespace JS {
 
 namespace detail {
 
 /*
  * Convert a double value to ResultType (an unsigned integral type) using
  * ECMAScript-style semantics (that is, in like manner to how ECMAScript's
  * ToInt32 converts to int32_t).
  *
@@ -119,17 +120,17 @@ ToIntWidth(double d)
 
     typedef typename mozilla::MakeUnsigned<ResultType>::Type UnsignedResult;
     UnsignedResult u = ToUintWidth<UnsignedResult>(d);
     if (u <= UnsignedResult(MaxValue))
         return static_cast<ResultType>(u);
     return (MinValue + static_cast<ResultType>(u - MaxValue)) - 1;
 }
 
-} /* namespace detail */
+} // namespace detail
 
 /* ES5 9.5 ToInt32 (specialized for doubles). */
 inline int32_t
 ToInt32(double d)
 {
 #if defined (__arm__) && defined (__GNUC__)
     int32_t i;
     uint32_t    tmp0;
@@ -288,11 +289,11 @@ ToInteger(double d)
         if (mozilla::IsNaN(d))
             return 0;
         return d;
     }
 
     return d < 0 ? ceil(d) : floor(d);
 }
 
-} /* namespace js */
+} // namespace JS
 
-#endif /* vm_NumericConversions_h */
+#endif /* js_Conversions_h */
--- a/js/src/asmjs/AsmJSModule.cpp
+++ b/js/src/asmjs/AsmJSModule.cpp
@@ -32,16 +32,17 @@
 #include "jsprf.h"
 #ifdef XP_WIN
 # include "jswin.h"
 #endif
 #include "prmjtime.h"
 
 #include "frontend/Parser.h"
 #include "jit/IonCode.h"
+#include "js/Conversions.h"
 #include "js/MemoryMetrics.h"
 
 #include "jsobjinlines.h"
 
 #include "frontend/ParseNode-inl.h"
 #include "vm/ArrayBufferObject-inl.h"
 #include "vm/Stack-inl.h"
 
@@ -666,17 +667,17 @@ AddressOf(AsmJSImmKind kind, ExclusiveCo
         return RedirectCall(FuncCast(InvokeFromAsmJS_ToInt32), Args_General3);
       case AsmJSImm_InvokeFromAsmJS_ToNumber:
         return RedirectCall(FuncCast(InvokeFromAsmJS_ToNumber), Args_General3);
       case AsmJSImm_CoerceInPlace_ToInt32:
         return RedirectCall(FuncCast(CoerceInPlace_ToInt32), Args_General1);
       case AsmJSImm_CoerceInPlace_ToNumber:
         return RedirectCall(FuncCast(CoerceInPlace_ToNumber), Args_General1);
       case AsmJSImm_ToInt32:
-        return RedirectCall(FuncCast<int32_t (double)>(js::ToInt32), Args_Int_Double);
+        return RedirectCall(FuncCast<int32_t (double)>(JS::ToInt32), Args_Int_Double);
 #if defined(JS_CODEGEN_ARM)
       case AsmJSImm_aeabi_idivmod:
         return RedirectCall(FuncCast(__aeabi_idivmod), Args_General2);
       case AsmJSImm_aeabi_uidivmod:
         return RedirectCall(FuncCast(__aeabi_uidivmod), Args_General2);
 #endif
       case AsmJSImm_ModD:
         return RedirectCall(FuncCast(NumberMod), Args_Double_DoubleDouble);
--- a/js/src/builtin/SIMD.h
+++ b/js/src/builtin/SIMD.h
@@ -4,17 +4,19 @@
  * 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 builtin_SIMD_h
 #define builtin_SIMD_h
 
 #include "jsapi.h"
 #include "jsobj.h"
+
 #include "builtin/TypedObject.h"
+#include "js/Conversions.h"
 #include "vm/GlobalObject.h"
 
 /*
  * JS SIMD functions.
  * Spec matching polyfill:
  * https://github.com/johnmccutchan/ecmascript_simd/blob/master/src/ecmascript_simd.js
  */
 
@@ -214,17 +216,17 @@ struct Int32x4 {
     typedef int32_t Elem;
     static const unsigned lanes = 4;
     static const SimdTypeDescr::Type type = SimdTypeDescr::TYPE_INT32;
 
     static TypeDescr &GetTypeDescr(GlobalObject &global) {
         return global.int32x4TypeDescr().as<TypeDescr>();
     }
     static Elem toType(Elem a) {
-        return ToInt32(a);
+        return JS::ToInt32(a);
     }
     static bool toType(JSContext *cx, JS::HandleValue v, Elem *out) {
         return ToInt32(cx, v, out);
     }
     static void setReturn(CallArgs &args, Elem value) {
         args.rval().setInt32(value);
     }
 };
--- a/js/src/builtin/TypedObject.h
+++ b/js/src/builtin/TypedObject.h
@@ -6,16 +6,17 @@
 
 #ifndef builtin_TypedObject_h
 #define builtin_TypedObject_h
 
 #include "jsobj.h"
 #include "jsweakmap.h"
 
 #include "builtin/TypedObjectConstants.h"
+#include "js/Conversions.h"
 #include "vm/ArrayBufferObject.h"
 
 /*
  * -------------
  * Typed Objects
  * -------------
  *
  * Typed objects are a special kind of JS object where the data is
@@ -99,20 +100,20 @@ namespace js {
  * for values like 0xF0000000.
  */
 template <typename T>
 static T ConvertScalar(double d)
 {
     if (TypeIsFloatingPoint<T>()) {
         return T(d);
     } else if (TypeIsUnsigned<T>()) {
-        uint32_t n = ToUint32(d);
+        uint32_t n = JS::ToUint32(d);
         return T(n);
     } else {
-        int32_t n = ToInt32(d);
+        int32_t n = JS::ToInt32(d);
         return T(n);
     }
 }
 
 namespace type {
 
 enum Kind {
     Scalar = JS_TYPEREPR_SCALAR_KIND,
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -332,23 +332,16 @@ else
         HOST_AR_FLAGS='$(AR_FLAGS)'
     fi
 fi
 
 MOZ_TOOL_VARIABLES
 
 MOZ_CHECK_COMPILER_WRAPPER
 
-if test -n "$GNU_CC" -a -z "$CLANG_CC" ; then
-    if test "$GCC_MAJOR_VERSION" -eq 4 -a "$GCC_MINOR_VERSION" -lt 4 ||
-       test "$GCC_MAJOR_VERSION" -lt 4; then
-        AC_MSG_ERROR([Only GCC 4.4 or newer supported])
-    fi
-fi
-
 dnl Special win32 checks
 dnl ========================================================
 
 MOZ_ARG_ENABLE_BOOL(metro,
 [  --enable-metro           Enable Windows Metro build targets],
     MOZ_METRO=1,
     MOZ_METRO=)
 if test -n "$MOZ_METRO"; then
@@ -422,19 +415,17 @@ case "$target" in
 
         if test "$_CC_MAJOR_VERSION" != "$_CXX_MAJOR_VERSION"; then
             AC_MSG_ERROR([The major versions of \$CC and \$CXX do not match.])
         fi
 
         AC_DEFINE(_CRT_SECURE_NO_WARNINGS)
         AC_DEFINE(_CRT_NONSTDC_NO_WARNINGS)
 
-        if test "$_CC_MAJOR_VERSION" = "17"; then
-            _CC_SUITE=11
-        elif test "$_CC_MAJOR_VERSION" = "18"; then
+        if test "$_CC_MAJOR_VERSION" = "18"; then
             _CC_SUITE=12
         else
             AC_MSG_ERROR([This version ($CC_VERSION) of the MSVC compiler is unsupported. See https://developer.mozilla.org/en/Windows_Build_Prerequisites.])
         fi
 
         dnl Ensure that mt.exe is 'Microsoft (R) Manifest Tool',
         dnl not something else like "magnetic tape manipulation utility".
         MSMT_TOOL=`mt 2>&1|grep 'Microsoft (R) Manifest Tool'`
@@ -1035,21 +1026,21 @@ dnl Android libstdc++, placed here so it
 dnl computed above.
 dnl ========================================================
 
 MOZ_ANDROID_STLPORT
 
 dnl ========================================================
 dnl Suppress Clang Argument Warnings
 dnl ========================================================
-if test -n "$CLANG_CC"; then
+if test -n "${CLANG_CC}${CLANG_CL}"; then
     _WARNINGS_CFLAGS="-Qunused-arguments ${_WARNINGS_CFLAGS}"
     CPPFLAGS="-Qunused-arguments ${CPPFLAGS}"
 fi
-if test -n "$CLANG_CXX"; then
+if test -n "${CLANG_CXX}${CLANG_CL}"; then
     _WARNINGS_CXXFLAGS="-Qunused-arguments ${_WARNINGS_CXXFLAGS}"
 fi
 
 dnl ========================================================
 dnl = Use Address Sanitizer
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(address-sanitizer,
 [  --enable-address-sanitizer       Enable Address Sanitizer (default=no)],
--- a/js/src/frontend/BytecodeCompiler.cpp
+++ b/js/src/frontend/BytecodeCompiler.cpp
@@ -504,18 +504,18 @@ frontend::CompileLazyFunction(JSContext 
                                                   sourceObject, lazy->begin(), lazy->end()));
     if (!script)
         return false;
 
     script->bindings = pn->pn_funbox->bindings;
 
     if (lazy->directlyInsideEval())
         script->setDirectlyInsideEval();
-    if (lazy->usesArgumentsAndApply())
-        script->setUsesArgumentsAndApply();
+    if (lazy->usesArgumentsApplyAndThis())
+        script->setUsesArgumentsApplyAndThis();
     if (lazy->hasBeenCloned())
         script->setHasBeenCloned();
 
     BytecodeEmitter bce(/* parent = */ nullptr, &parser, pn->pn_funbox, script, lazy,
                         options.forEval, /* evalCaller = */ js::NullPtr(),
                         /* hasGlobalScope = */ true, options.lineno,
                         BytecodeEmitter::LazyFunction);
     if (!bce.init())
--- a/js/src/frontend/BytecodeEmitter.cpp
+++ b/js/src/frontend/BytecodeEmitter.cpp
@@ -5381,18 +5381,18 @@ EmitFunc(ExclusiveContext *cx, BytecodeE
                                  bce->emitterMode);
             if (!bce2.init())
                 return false;
 
             /* We measured the max scope depth when we parsed the function. */
             if (!EmitFunctionScript(cx, &bce2, pn->pn_body))
                 return false;
 
-            if (funbox->usesArguments && funbox->usesApply)
-                script->setUsesArgumentsAndApply();
+            if (funbox->usesArguments && funbox->usesApply && funbox->usesThis)
+                script->setUsesArgumentsApplyAndThis();
         }
     } else {
         MOZ_ASSERT(IsAsmJSModuleNative(fun->native()));
     }
 
     /* Make the function object a literal in the outer script's pool. */
     unsigned index = bce->objectList.add(pn->pn_funbox);
 
--- a/js/src/frontend/FoldConstants.cpp
+++ b/js/src/frontend/FoldConstants.cpp
@@ -8,30 +8,32 @@
 
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/TypedEnum.h"
 
 #include "jslibmath.h"
 
 #include "frontend/ParseNode.h"
 #include "frontend/Parser.h"
-#include "vm/NumericConversions.h"
+#include "js/Conversions.h"
 
 #include "jscntxtinlines.h"
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 
 using namespace js;
 using namespace js::frontend;
 
 using mozilla::IsNaN;
 using mozilla::IsNegative;
 using mozilla::NegativeInfinity;
 using mozilla::PositiveInfinity;
 using JS::GenericNaN;
+using JS::ToInt32;
+using JS::ToUint32;
 
 static bool
 ContainsVarOrConst(ExclusiveContext *cx, ParseNode *pn, ParseNode **resultp)
 {
     JS_CHECK_RECURSION(cx, return false);
 
     if (!pn) {
         *resultp = nullptr;
--- a/js/src/frontend/Parser.cpp
+++ b/js/src/frontend/Parser.cpp
@@ -606,16 +606,17 @@ FunctionBox::FunctionBox(ExclusiveContex
     generatorKindBits_(GeneratorKindAsBits(generatorKind)),
     inWith(false),                  // initialized below
     inGenexpLambda(false),
     hasDestructuringArgs(false),
     useAsm(false),
     insideUseAsm(outerpc && outerpc->useAsmOrInsideUseAsm()),
     usesArguments(false),
     usesApply(false),
+    usesThis(false),
     funCxFlags()
 {
     // Functions created at parse time may be set singleton after parsing and
     // baked into JIT code, so they must be allocated tenured. They are held by
     // the JSScript so cannot be collected during a minor GC anyway.
     MOZ_ASSERT(fun->isTenured());
 
     if (!outerpc) {
@@ -2278,18 +2279,18 @@ Parser<SyntaxParseHandler>::finishFuncti
 
     HeapPtrFunction *innerFunctions = lazy->innerFunctions();
     for (size_t i = 0; i < numInnerFunctions; i++)
         innerFunctions[i].init(pc->innerFunctions[i]);
 
     if (pc->sc->strict)
         lazy->setStrict();
     lazy->setGeneratorKind(funbox->generatorKind());
-    if (funbox->usesArguments && funbox->usesApply)
-        lazy->setUsesArgumentsAndApply();
+    if (funbox->usesArguments && funbox->usesApply && funbox->usesThis)
+        lazy->setUsesArgumentsApplyAndThis();
     PropagateTransitiveParseFlags(funbox, lazy);
 
     fun->initLazyScript(lazy);
     return true;
 }
 
 template <>
 bool
@@ -8189,16 +8190,18 @@ Parser<ParseHandler>::primaryExpr(TokenK
       case TOK_NUMBER:
         return newNumber(tokenStream.currentToken());
 
       case TOK_TRUE:
         return handler.newBooleanLiteral(true, pos());
       case TOK_FALSE:
         return handler.newBooleanLiteral(false, pos());
       case TOK_THIS:
+        if (pc->sc->isFunctionBox())
+            pc->sc->asFunctionBox()->usesThis = true;
         return handler.newThisLiteral(pos());
       case TOK_NULL:
         return handler.newNullLiteral(pos());
 
       case TOK_TRIPLEDOT: {
         TokenKind next;
 
         // This isn't valid expression syntax, but it's valid in an arrow
--- a/js/src/frontend/SharedContext.h
+++ b/js/src/frontend/SharedContext.h
@@ -250,16 +250,17 @@ class FunctionBox : public ObjectBox, pu
     bool            inGenexpLambda:1;       /* lambda from generator expression */
     bool            hasDestructuringArgs:1; /* arguments list contains destructuring expression */
     bool            useAsm:1;               /* see useAsmOrInsideUseAsm */
     bool            insideUseAsm:1;         /* see useAsmOrInsideUseAsm */
 
     // Fields for use in heuristics.
     bool            usesArguments:1;  /* contains a free use of 'arguments' */
     bool            usesApply:1;      /* contains an f.apply() call */
+    bool            usesThis:1;       /* contains 'this' */
 
     FunctionContextFlags funCxFlags;
 
     template <typename ParseHandler>
     FunctionBox(ExclusiveContext *cx, ObjectBox* traceListHead, JSFunction *fun,
                 ParseContext<ParseHandler> *pc, Directives directives,
                 bool extraWarnings, GeneratorKind generatorKind);
 
--- a/js/src/frontend/TokenStream.cpp
+++ b/js/src/frontend/TokenStream.cpp
@@ -309,23 +309,16 @@ TokenStream::TokenStream(ExclusiveContex
     cx(cx),
     mutedErrors(options.mutedErrors()),
     strictModeGetter(smg)
 {
     // Nb: the following tables could be static, but initializing them here is
     // much easier.  Don't worry, the time to initialize them for each
     // TokenStream is trivial.  See bug 639420.
 
-    // See getChar() for an explanation of maybeEOL[].
-    memset(maybeEOL, 0, sizeof(maybeEOL));
-    maybeEOL[unsigned('\n')] = true;
-    maybeEOL[unsigned('\r')] = true;
-    maybeEOL[unsigned(LINE_SEPARATOR & 0xff)] = true;
-    maybeEOL[unsigned(PARA_SEPARATOR & 0xff)] = true;
-
     // See getTokenInternal() for an explanation of maybeStrSpecial[].
     memset(maybeStrSpecial, 0, sizeof(maybeStrSpecial));
     maybeStrSpecial[unsigned('"')] = true;
     maybeStrSpecial[unsigned('`')] = true;
     maybeStrSpecial[unsigned('$')] = true;
     maybeStrSpecial[unsigned('\'')] = true;
     maybeStrSpecial[unsigned('\\')] = true;
     maybeStrSpecial[unsigned('\n')] = true;
@@ -392,41 +385,28 @@ TokenStream::updateFlagsForEOL()
 // This gets the next char, normalizing all EOL sequences to '\n' as it goes.
 int32_t
 TokenStream::getChar()
 {
     int32_t c;
     if (MOZ_LIKELY(userbuf.hasRawChars())) {
         c = userbuf.getRawChar();
 
-        // Normalize the char16_t if it was a newline.  We need to detect any of
-        // these four characters:  '\n' (0x000a), '\r' (0x000d),
-        // LINE_SEPARATOR (0x2028), PARA_SEPARATOR (0x2029).  Testing for each
-        // one in turn is slow, so we use a single probabilistic check, and if
-        // that succeeds, test for them individually.
-        //
-        // We use the bottom 8 bits to index into a lookup table, succeeding
-        // when d&0xff is 0xa, 0xd, 0x28 or 0x29.  Among ASCII chars (which
-        // are by the far the most common) this gives false positives for '('
-        // (0x0028) and ')' (0x0029).  We could avoid those by incorporating
-        // the 13th bit of d into the lookup, but that requires extra shifting
-        // and masking and isn't worthwhile.  See TokenStream::TokenStream()
-        // for the initialization of the relevant entries in the table.
-        if (MOZ_UNLIKELY(maybeEOL[c & 0xff])) {
-            if (c == '\n')
-                goto eol;
-            if (c == '\r') {
-                // If it's a \r\n sequence: treat as a single EOL, skip over the \n.
-                if (userbuf.hasRawChars())
-                    userbuf.matchRawChar('\n');
-                goto eol;
-            }
-            if (c == LINE_SEPARATOR || c == PARA_SEPARATOR)
-                goto eol;
+        // Normalize the char16_t if it was a newline.
+        if (MOZ_UNLIKELY(c == '\n'))
+            goto eol;
+        if (MOZ_UNLIKELY(c == '\r')) {
+            // If it's a \r\n sequence: treat as a single EOL, skip over the \n.
+            if (MOZ_LIKELY(userbuf.hasRawChars()))
+                userbuf.matchRawChar('\n');
+            goto eol;
         }
+        if (MOZ_UNLIKELY(c == LINE_SEPARATOR || c == PARA_SEPARATOR))
+            goto eol;
+
         return c;
     }
 
     flags.isEOF = true;
     return EOF;
 
   eol:
     updateLineInfoForEOL();
@@ -1680,20 +1660,18 @@ TokenStream::getTokenInternal(TokenKind 
 bool TokenStream::getStringOrTemplateToken(int qc, Token **tp)
 {
     *tp = newToken(-1);
     int c;
     int nc = -1;
     tokenbuf.clear();
     while (true) {
         // We need to detect any of these chars:  " or ', \n (or its
-        // equivalents), \\, EOF.  We use maybeStrSpecial[] in a manner
-        // similar to maybeEOL[], see above.  Because we detect EOL
-        // sequences here and put them back immediately, we can use
-        // getCharIgnoreEOL().
+        // equivalents), \\, EOF.  Because we detect EOL sequences here and
+        // put them back immediately, we can use getCharIgnoreEOL().
         c = getCharIgnoreEOL();
         if (maybeStrSpecial[c & 0xff]) {
             if (c == qc)
                 break;
             if (c == '\\') {
                 switch (c = getChar()) {
                   case 'b': c = '\b'; break;
                   case 'f': c = '\f'; break;
--- a/js/src/frontend/TokenStream.h
+++ b/js/src/frontend/TokenStream.h
@@ -819,17 +819,16 @@ class MOZ_STACK_CLASS TokenStream
     Flags               flags;              // flags -- see above
     size_t              linebase;           // start of current line
     size_t              prevLinebase;       // start of previous line;  size_t(-1) if on the first line
     TokenBuf            userbuf;            // user input buffer
     const char          *filename;          // input filename or null
     mozilla::UniquePtr<char16_t[], JS::FreePolicy> displayURL_; // the user's requested source URL or null
     mozilla::UniquePtr<char16_t[], JS::FreePolicy> sourceMapURL_; // source map's filename or null
     CharBuffer          tokenbuf;           // current token string buffer
-    bool                maybeEOL[256];      // probabilistic EOL lookup table
     bool                maybeStrSpecial[256];   // speeds up string scanning
     uint8_t             isExprEnding[TOK_LIMIT];// which tokens definitely terminate exprs?
     ExclusiveContext    *const cx;
     bool                mutedErrors;
     StrictModeGetter    *strictModeGetter;  // used to test for strict mode
 };
 
 // Steal one JSREPORT_* bit (see jsapi.h) to tell that arguments to the error
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/ion/bug1060387.js
@@ -0,0 +1,12 @@
+function foo() {
+    var obj = new Object();
+    var index = [-0, 2147483648, 1073741825];
+    for (var j in index) {
+        testProperty(index[j]);
+    }
+    function testProperty(i) {
+        obj[i] = '' + i;
+    }
+    assertEq(JSON.stringify(obj), '{"0":"0","2147483648":"2147483648","1073741825":"1073741825"}');
+}
+foo();
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/ion/bug1117099.js
@@ -0,0 +1,10 @@
+// |jit-test| error: ReferenceError
+function reportCompare (expected, actual, description) {
+    if (expected != actual) {}
+}
+reportCompare(1);
+addThis();
+function addThis() {
+    for (var i=0; i<UBound; i++)
+	reportCompare( true | this && this );
+}
--- a/js/src/jit/BaselineIC.cpp
+++ b/js/src/jit/BaselineIC.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * 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 "jit/BaselineIC.h"
 
+#include "mozilla/Casting.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/TemplateLib.h"
 
 #include "jslibmath.h"
 #include "jstypes.h"
 
 #include "builtin/Eval.h"
 #include "jit/BaselineDebugModeOSR.h"
@@ -18,27 +19,29 @@
 #include "jit/BaselineJIT.h"
 #include "jit/JitSpewer.h"
 #include "jit/Linker.h"
 #include "jit/Lowering.h"
 #ifdef JS_ION_PERF
 # include "jit/PerfSpewer.h"
 #endif
 #include "jit/VMFunctions.h"
+#include "js/Conversions.h"
 #include "vm/Opcodes.h"
 #include "vm/TypedArrayCommon.h"
 
 #include "jsboolinlines.h"
 #include "jsscriptinlines.h"
 
 #include "jit/JitFrames-inl.h"
 #include "vm/Interpreter-inl.h"
 #include "vm/ScopeObject-inl.h"
 #include "vm/StringObject-inl.h"
 
+using mozilla::BitwiseCast;
 using mozilla::DebugOnly;
 
 namespace js {
 namespace jit {
 
 #ifdef DEBUG
 void
 FallbackICSpew(JSContext *cx, ICFallbackStub *stub, const char *fmt, ...)
@@ -2775,52 +2778,44 @@ ICBinaryArith_Fallback::Compiler::genera
     masm.pushValue(R0);
     masm.push(BaselineStubReg);
     masm.pushBaselineFramePtr(BaselineFrameReg, R0.scratchReg());
 
     return tailCallVM(DoBinaryArithFallbackInfo, masm);
 }
 
 static bool
-DoConcatStrings(JSContext *cx, HandleValue lhs, HandleValue rhs, MutableHandleValue res)
-{
-    MOZ_ASSERT(lhs.isString());
-    MOZ_ASSERT(rhs.isString());
-    JSString *lstr = lhs.toString();
-    JSString *rstr = rhs.toString();
-    JSString *result = ConcatStrings<NoGC>(cx, lstr, rstr);
-    if (result) {
-        res.set(StringValue(result));
-        return true;
-    }
-
-    RootedString rootedl(cx, lstr), rootedr(cx, rstr);
-    result = ConcatStrings<CanGC>(cx, rootedl, rootedr);
+DoConcatStrings(JSContext *cx, HandleString lhs, HandleString rhs, MutableHandleValue res)
+{
+    JSString *result = ConcatStrings<CanGC>(cx, lhs, rhs);
     if (!result)
         return false;
 
-    res.set(StringValue(result));
-    return true;
-}
-
-typedef bool (*DoConcatStringsFn)(JSContext *, HandleValue, HandleValue, MutableHandleValue);
+    res.setString(result);
+    return true;
+}
+
+typedef bool (*DoConcatStringsFn)(JSContext *, HandleString, HandleString, MutableHandleValue);
 static const VMFunction DoConcatStringsInfo = FunctionInfo<DoConcatStringsFn>(DoConcatStrings, TailCall);
 
 bool
 ICBinaryArith_StringConcat::Compiler::generateStubCode(MacroAssembler &masm)
 {
     Label failure;
     masm.branchTestString(Assembler::NotEqual, R0, &failure);
     masm.branchTestString(Assembler::NotEqual, R1, &failure);
 
     // Restore the tail call register.
     EmitRestoreTailCallReg(masm);
 
-    masm.pushValue(R1);
-    masm.pushValue(R0);
+    masm.unboxString(R0, R0.scratchReg());
+    masm.unboxString(R1, R1.scratchReg());
+
+    masm.push(R1.scratchReg());
+    masm.push(R0.scratchReg());
     if (!tailCallVM(DoConcatStringsInfo, masm))
         return false;
 
     // Failure case - jump to next stub
     masm.bind(&failure);
     EmitStubGuardFailure(masm);
     return true;
 }
@@ -3056,17 +3051,17 @@ ICBinaryArith_DoubleWithInt32::Compiler:
         Label truncateABICall;
         masm.branchTruncateDouble(FloatReg0, scratchReg, &truncateABICall);
         masm.jump(&doneTruncate);
 
         masm.bind(&truncateABICall);
         masm.push(intReg);
         masm.setupUnalignedABICall(1, scratchReg);
         masm.passABIArg(FloatReg0, MoveOp::DOUBLE);
-        masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, js::ToInt32));
+        masm.callWithABI(mozilla::BitwiseCast<void*, int32_t(*)(double)>(JS::ToInt32));
         masm.storeCallResult(scratchReg);
         masm.pop(intReg);
 
         masm.bind(&doneTruncate);
     }
 
     Register intReg2 = scratchReg;
     // All handled ops commute, so no need to worry about ordering.
@@ -3205,17 +3200,17 @@ ICUnaryArith_Double::Compiler::generateS
         Label doneTruncate;
         Label truncateABICall;
         masm.branchTruncateDouble(FloatReg0, scratchReg, &truncateABICall);
         masm.jump(&doneTruncate);
 
         masm.bind(&truncateABICall);
         masm.setupUnalignedABICall(1, scratchReg);
         masm.passABIArg(FloatReg0, MoveOp::DOUBLE);
-        masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, js::ToInt32));
+        masm.callWithABI(BitwiseCast<void*, int32_t(*)(double)>(JS::ToInt32));
         masm.storeCallResult(scratchReg);
 
         masm.bind(&doneTruncate);
         masm.not32(scratchReg);
         masm.tagValue(JSVAL_TYPE_INT32, scratchReg, R0);
     }
 
     EmitReturnFromIC(masm);
--- a/js/src/jit/MIR.cpp
+++ b/js/src/jit/MIR.cpp
@@ -14,24 +14,27 @@
 #include "jslibmath.h"
 #include "jsstr.h"
 
 #include "jit/BaselineInspector.h"
 #include "jit/IonBuilder.h"
 #include "jit/JitSpewer.h"
 #include "jit/MIRGraph.h"
 #include "jit/RangeAnalysis.h"
+#include "js/Conversions.h"
 
 #include "jsatominlines.h"
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 
 using namespace js;
 using namespace js::jit;
 
+using JS::ToInt32;
+
 using mozilla::NumbersAreIdentical;
 using mozilla::IsFloat32Representable;
 using mozilla::Maybe;
 using mozilla::DebugOnly;
 
 #ifdef DEBUG
 size_t MUse::index() const
 {
@@ -3056,17 +3059,17 @@ MCompare::tryFold(bool *result)
         } else {
             MOZ_ASSERT(op == JSOP_EQ || op == JSOP_NE);
             if (IsNullOrUndefined(lhs()->type())) {
                 *result = (op == JSOP_EQ);
                 return true;
             }
             if (!lhs()->mightBeType(MIRType_Null) &&
                 !lhs()->mightBeType(MIRType_Undefined) &&
-                !operandMightEmulateUndefined())
+                !(lhs()->mightBeType(MIRType_Object) && operandMightEmulateUndefined()))
             {
                 *result = (op == JSOP_NE);
                 return true;
             }
         }
         return false;
     }
 
--- a/js/src/jit/MacroAssembler.cpp
+++ b/js/src/jit/MacroAssembler.cpp
@@ -14,28 +14,30 @@
 #include "jit/AtomicOp.h"
 #include "jit/Bailouts.h"
 #include "jit/BaselineFrame.h"
 #include "jit/BaselineIC.h"
 #include "jit/BaselineJIT.h"
 #include "jit/Lowering.h"
 #include "jit/MIR.h"
 #include "jit/ParallelFunctions.h"
+#include "js/Conversions.h"
 #include "vm/ForkJoin.h"
 #include "vm/TraceLogging.h"
 
 #include "jsgcinlines.h"
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 #include "vm/Interpreter-inl.h"
 
 using namespace js;
 using namespace js::jit;
 
 using JS::GenericNaN;
+using JS::ToInt32;
 
 namespace {
 
 // Emulate a TypeSet logic from a Type object to avoid duplicating the guard
 // logic.
 class TypeWrapper {
     types::Type t_;
 
@@ -2094,17 +2096,17 @@ MacroAssembler::convertValueToInt(JSCont
             int i;
             if (mozilla::NumberIsInt32(d, &i))
                 move32(Imm32(i), output);
             else
                 jump(fail);
             break;
           }
           case IntConversion_Truncate:
-            move32(Imm32(js::ToInt32(d)), output);
+            move32(Imm32(ToInt32(d)), output);
             break;
           case IntConversion_ClampToUint8:
             move32(Imm32(ClampDoubleToUint8(d)), output);
             break;
         }
 
         return true;
     }
--- a/js/src/jit/RangeAnalysis.cpp
+++ b/js/src/jit/RangeAnalysis.cpp
@@ -9,17 +9,17 @@
 #include "mozilla/MathAlgorithms.h"
 
 #include "jit/Ion.h"
 #include "jit/IonAnalysis.h"
 #include "jit/JitSpewer.h"
 #include "jit/MIR.h"
 #include "jit/MIRGenerator.h"
 #include "jit/MIRGraph.h"
-#include "vm/NumericConversions.h"
+#include "js/Conversions.h"
 #include "vm/TypedArrayCommon.h"
 
 #include "jsopcodeinlines.h"
 
 using namespace js;
 using namespace js::jit;
 
 using mozilla::Abs;
@@ -30,16 +30,17 @@ using mozilla::FloorLog2;
 using mozilla::IsInfinite;
 using mozilla::IsNaN;
 using mozilla::IsNegative;
 using mozilla::IsNegativeZero;
 using mozilla::NegativeInfinity;
 using mozilla::PositiveInfinity;
 using mozilla::Swap;
 using JS::GenericNaN;
+using JS::ToInt32;
 
 // This algorithm is based on the paper "Eliminating Range Checks Using
 // Static Single Assignment Form" by Gough and Klaren.
 //
 // We associate a range object with each SSA name, and the ranges are consulted
 // in order to determine whether overflow is possible for arithmetic
 // computations.
 //
--- a/js/src/jit/VMFunctions.cpp
+++ b/js/src/jit/VMFunctions.cpp
@@ -1161,19 +1161,18 @@ Recompile(JSContext *cx)
     return RecompileImpl(cx, /* force = */ false);
 }
 
 bool
 SetDenseElement(JSContext *cx, HandleNativeObject obj, int32_t index, HandleValue value,
                 bool strict)
 {
     // This function is called from Ion code for StoreElementHole's OOL path.
-    // In this case we know the object is native, has no indexed properties
-    // and we can use setDenseElement instead of setDenseElementWithType.
-    MOZ_ASSERT(!obj->isIndexed());
+    // In this case we know the object is native and we can use setDenseElement
+    // instead of setDenseElementWithType.
 
     NativeObject::EnsureDenseResult result = NativeObject::ED_SPARSE;
     do {
         if (index < 0)
             break;
         bool isArray = obj->is<ArrayObject>();
         if (isArray && !obj->as<ArrayObject>().lengthIsWritable())
             break;
--- a/js/src/jit/arm/CodeGenerator-arm.cpp
+++ b/js/src/jit/arm/CodeGenerator-arm.cpp
@@ -12,29 +12,31 @@
 #include "jscompartment.h"
 #include "jsnum.h"
 
 #include "jit/CodeGenerator.h"
 #include "jit/JitCompartment.h"
 #include "jit/JitFrames.h"
 #include "jit/MIR.h"
 #include "jit/MIRGraph.h"
+#include "js/Conversions.h"
 #include "vm/Shape.h"
 #include "vm/TraceLogging.h"
 
 #include "jsscriptinlines.h"
 
 #include "jit/shared/CodeGenerator-shared-inl.h"
 
 using namespace js;
 using namespace js::jit;
 
 using mozilla::FloorLog2;
 using mozilla::NegativeInfinity;
 using JS::GenericNaN;
+using JS::ToInt32;
 
 // shared
 CodeGeneratorARM::CodeGeneratorARM(MIRGenerator *gen, LIRGraph *graph, MacroAssembler *masm)
   : CodeGeneratorShared(gen, graph, masm)
 {
 }
 
 bool
--- a/js/src/jit/mips/CodeGenerator-mips.cpp
+++ b/js/src/jit/mips/CodeGenerator-mips.cpp
@@ -12,29 +12,31 @@
 #include "jscompartment.h"
 #include "jsnum.h"
 
 #include "jit/CodeGenerator.h"
 #include "jit/JitCompartment.h"
 #include "jit/JitFrames.h"
 #include "jit/MIR.h"
 #include "jit/MIRGraph.h"
+#include "js/Conversions.h"
 #include "vm/Shape.h"
 #include "vm/TraceLogging.h"
 
 #include "jsscriptinlines.h"
 
 #include "jit/shared/CodeGenerator-shared-inl.h"
 
 using namespace js;
 using namespace js::jit;
 
 using mozilla::FloorLog2;
 using mozilla::NegativeInfinity;
 using JS::GenericNaN;
+using JS::ToInt32;
 
 // shared
 CodeGeneratorMIPS::CodeGeneratorMIPS(MIRGenerator *gen, LIRGraph *graph, MacroAssembler *masm)
   : CodeGeneratorShared(gen, graph, masm)
 {
 }
 
 bool
--- a/js/src/jit/shared/CodeGenerator-shared.cpp
+++ b/js/src/jit/shared/CodeGenerator-shared.cpp
@@ -11,23 +11,25 @@
 #include "jit/CompactBuffer.h"
 #include "jit/IonCaches.h"
 #include "jit/JitcodeMap.h"
 #include "jit/JitSpewer.h"
 #include "jit/MacroAssembler.h"
 #include "jit/MIR.h"
 #include "jit/MIRGenerator.h"
 #include "jit/ParallelFunctions.h"
+#include "js/Conversions.h"
 #include "vm/TraceLogging.h"
 
 #include "jit/JitFrames-inl.h"
 
 using namespace js;
 using namespace js::jit;
 
+using mozilla::BitwiseCast;
 using mozilla::DebugOnly;
 
 namespace js {
 namespace jit {
 
 MacroAssembler &
 CodeGeneratorShared::ensureMasm(MacroAssembler *masmArg)
 {
@@ -1141,17 +1143,17 @@ CodeGeneratorShared::visitOutOfLineTrunc
         masm.convertFloat32ToDouble(src, src);
     }
 #endif
     masm.setupUnalignedABICall(1, dest);
     masm.passABIArg(src, MoveOp::DOUBLE);
     if (gen->compilingAsmJS())
         masm.callWithABI(AsmJSImm_ToInt32);
     else
-        masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, js::ToInt32));
+        masm.callWithABI(BitwiseCast<void*, int32_t(*)(double)>(JS::ToInt32));
     masm.storeCallResult(dest);
 
 #ifndef JS_CODEGEN_ARM
     if (ool->needFloat32Conversion())
         masm.pop(src);
 #endif
     restoreVolatile(dest);
 
--- a/js/src/jit/x86/CodeGenerator-x86.cpp
+++ b/js/src/jit/x86/CodeGenerator-x86.cpp
@@ -1,33 +1,36 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * 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 "jit/x86/CodeGenerator-x86.h"
 
+#include "mozilla/Casting.h"
 #include "mozilla/DebugOnly.h"
 
 #include "jsnum.h"
 
 #include "jit/IonCaches.h"
 #include "jit/MIR.h"
 #include "jit/MIRGraph.h"
+#include "js/Conversions.h"
 #include "vm/Shape.h"
 
 #include "jsscriptinlines.h"
 
 #include "jit/ExecutionMode-inl.h"
 #include "jit/shared/CodeGenerator-shared-inl.h"
 
 using namespace js;
 using namespace js::jit;
 
+using mozilla::BitwiseCast;
 using mozilla::DebugOnly;
 using mozilla::FloatingPoint;
 using JS::GenericNaN;
 
 CodeGeneratorX86::CodeGeneratorX86(MIRGenerator *gen, LIRGraph *graph, MacroAssembler *masm)
   : CodeGeneratorX86Shared(gen, graph, masm)
 {
 }
@@ -875,17 +878,17 @@ CodeGeneratorX86::visitOutOfLineTruncate
     {
         saveVolatile(output);
 
         masm.setupUnalignedABICall(1, output);
         masm.passABIArg(input, MoveOp::DOUBLE);
         if (gen->compilingAsmJS())
             masm.callWithABI(AsmJSImm_ToInt32);
         else
-            masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, js::ToInt32));
+            masm.callWithABI(BitwiseCast<void*, int32_t(*)(double)>(JS::ToInt32));
         masm.storeCallResult(output);
 
         restoreVolatile(output);
     }
 
     masm.jump(ool->rejoin());
 }
 
@@ -967,17 +970,17 @@ CodeGeneratorX86::visitOutOfLineTruncate
         masm.push(input);
         masm.setupUnalignedABICall(1, output);
         masm.vcvtss2sd(input, input, input);
         masm.passABIArg(input, MoveOp::DOUBLE);
 
         if (gen->compilingAsmJS())
             masm.callWithABI(AsmJSImm_ToInt32);
         else
-            masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, js::ToInt32));
+            masm.callWithABI(BitwiseCast<void*, int32_t(*)(double)>(JS::ToInt32));
 
         masm.storeCallResult(output);
         masm.pop(input);
 
         restoreVolatile(output);
     }
 
     masm.jump(ool->rejoin());
--- a/js/src/jsapi-tests/testToIntWidth.cpp
+++ b/js/src/jsapi-tests/testToIntWidth.cpp
@@ -2,21 +2,22 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  */
 /* 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 <math.h>
 
-#include "jsapi-tests/tests.h"
-#include "vm/NumericConversions.h"
+#include "js/Conversions.h"
 
-using js::detail::ToIntWidth;
-using js::detail::ToUintWidth;
+#include "jsapi-tests/tests.h"
+
+using JS::detail::ToIntWidth;
+using JS::detail::ToUintWidth;
 
 BEGIN_TEST(testToUint8TwiceUint8Range)
 {
     double d = -256;
     uint8_t expected = 0;
     do {
         CHECK(ToUintWidth<uint8_t>(d) == expected);
 
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -56,28 +56,28 @@
 #include "builtin/TypedObject.h"
 #endif
 #include "frontend/BytecodeCompiler.h"
 #include "frontend/FullParseHandler.h"  // for JS_BufferIsCompileableUnit
 #include "frontend/Parser.h" // for JS_BufferIsCompileableUnit
 #include "gc/Marking.h"
 #include "jit/JitCommon.h"
 #include "js/CharacterEncoding.h"
+#include "js/Conversions.h"
 #include "js/SliceBudget.h"
 #include "js/StructuredClone.h"
 #if ENABLE_INTL_API
 #include "unicode/uclean.h"
 #include "unicode/utypes.h"
 #endif // ENABLE_INTL_API
 #include "vm/DateObject.h"
 #include "vm/Debugger.h"
 #include "vm/ErrorObject.h"
 #include "vm/HelperThreads.h"
 #include "vm/Interpreter.h"
-#include "vm/NumericConversions.h"
 #include "vm/RegExpStatics.h"
 #include "vm/Runtime.h"
 #include "vm/SavedStacks.h"
 #include "vm/ScopeObject.h"
 #include "vm/Shape.h"
 #include "vm/StopIterationObject.h"
 #include "vm/StringBuffer.h"
 #include "vm/Symbol.h"
@@ -100,16 +100,19 @@ using namespace js::gc;
 using namespace js::types;
 
 using mozilla::Maybe;
 using mozilla::PodCopy;
 using mozilla::PodZero;
 using mozilla::UniquePtr;
 
 using JS::AutoGCRooter;
+using JS::ToInt32;
+using JS::ToInteger;
+using JS::ToUint32;
 
 using js::frontend::Parser;
 
 #ifdef HAVE_VA_LIST_AS_ARRAY
 #define JS_ADDRESSOF_VA_LIST(ap) ((va_list *)(ap))
 #else
 #define JS_ADDRESSOF_VA_LIST(ap) (&(ap))
 #endif
--- a/js/src/jsarray.cpp
+++ b/js/src/jsarray.cpp
@@ -21,20 +21,20 @@
 #include "jsiter.h"
 #include "jsnum.h"
 #include "jsobj.h"
 #include "jstypes.h"
 #include "jsutil.h"
 
 #include "ds/Sort.h"
 #include "gc/Heap.h"
+#include "js/Conversions.h"
 #include "vm/ArgumentsObject.h"
 #include "vm/ForkJoin.h"
 #include "vm/Interpreter.h"
-#include "vm/NumericConversions.h"
 #include "vm/Shape.h"
 #include "vm/StringBuffer.h"
 #include "vm/TypedArrayCommon.h"
 
 #include "jsatominlines.h"
 
 #include "vm/ArgumentsObject-inl.h"
 #include "vm/ArrayObject-inl.h"
@@ -48,16 +48,17 @@ using namespace js::types;
 
 using mozilla::Abs;
 using mozilla::ArrayLength;
 using mozilla::CeilingLog2;
 using mozilla::DebugOnly;
 using mozilla::IsNaN;
 
 using JS::AutoCheckCannotGC;
+using JS::ToUint32;
 
 bool
 js::GetLengthProperty(JSContext *cx, HandleObject obj, uint32_t *lengthp)
 {
     if (obj->is<ArrayObject>()) {
         *lengthp = obj->as<ArrayObject>().length();
         return true;
     }
--- a/js/src/jsdate.cpp
+++ b/js/src/jsdate.cpp
@@ -30,35 +30,36 @@
 #include "jsobj.h"
 #include "jsprf.h"
 #include "jsstr.h"
 #include "jstypes.h"
 #include "jsutil.h"
 #include "jswrapper.h"
 #include "prmjtime.h"
 
+#include "js/Conversions.h"
 #include "js/Date.h"
 #include "vm/DateTime.h"
 #include "vm/GlobalObject.h"
 #include "vm/Interpreter.h"
-#include "vm/NumericConversions.h"
 #include "vm/String.h"
 #include "vm/StringBuffer.h"
 
 #include "jsobjinlines.h"
 
 using namespace js;
 using namespace js::types;
 
 using mozilla::ArrayLength;
 using mozilla::IsFinite;
 using mozilla::IsNaN;
 
 using JS::AutoCheckCannotGC;
 using JS::GenericNaN;
+using JS::ToInteger;
 
 /*
  * The JS 'Date' object is patterned after the Java 'Date' object.
  * Here is a script:
  *
  *    today = new Date();
  *
  *    print(today.toLocaleString());
--- a/js/src/jsinfer.cpp
+++ b/js/src/jsinfer.cpp
@@ -3670,22 +3670,22 @@ types::UseNewTypeForClone(JSFunction *fu
      * initialize method. We capture this, along with similar cases, by looking
      * for short scripts which use both .apply and arguments. For such scripts,
      * whenever creating a new instance of the function we both give that
      * instance a singleton type and clone the underlying script.
      */
 
     uint32_t begin, end;
     if (fun->hasScript()) {
-        if (!fun->nonLazyScript()->usesArgumentsAndApply())
+        if (!fun->nonLazyScript()->usesArgumentsApplyAndThis())
             return false;
         begin = fun->nonLazyScript()->sourceStart();
         end = fun->nonLazyScript()->sourceEnd();
     } else {
-        if (!fun->lazyScript()->usesArgumentsAndApply())
+        if (!fun->lazyScript()->usesArgumentsApplyAndThis())
             return false;
         begin = fun->lazyScript()->begin();
         end = fun->lazyScript()->end();
     }
 
     return end - begin <= 100;
 }
 
--- a/js/src/jsnum.cpp
+++ b/js/src/jsnum.cpp
@@ -23,18 +23,18 @@
 
 #include "jsatom.h"
 #include "jscntxt.h"
 #include "jsdtoa.h"
 #include "jsobj.h"
 #include "jsstr.h"
 #include "jstypes.h"
 
+#include "js/Conversions.h"
 #include "vm/GlobalObject.h"
-#include "vm/NumericConversions.h"
 #include "vm/StringBuffer.h"
 
 #include "jsatominlines.h"
 
 #include "vm/NativeObject-inl.h"
 #include "vm/NumberObject-inl.h"
 #include "vm/String-inl.h"
 
@@ -46,16 +46,20 @@ using mozilla::ArrayLength;
 using mozilla::MinNumberValue;
 using mozilla::NegativeInfinity;
 using mozilla::PodCopy;
 using mozilla::PositiveInfinity;
 using mozilla::RangedPtr;
 
 using JS::AutoCheckCannotGC;
 using JS::GenericNaN;
+using JS::ToInt32;
+using JS::ToInt64;
+using JS::ToUint32;
+using JS::ToUint64;
 
 /*
  * If we're accumulating a decimal number and the number is >= 2^53, then the
  * fast result from the loop in Get{Prefix,Decimal}Integer may be inaccurate.
  * Call js_strtod_harder to get the correct answer.
  */
 template <typename CharT>
 static bool
@@ -1017,17 +1021,17 @@ Number_isInteger(JSContext *cx, unsigned
     CallArgs args = CallArgsFromVp(argc, vp);
     if (args.length() < 1 || !args[0].isNumber()) {
         args.rval().setBoolean(false);
         return true;
     }
     Value val = args[0];
     args.rval().setBoolean(val.isInt32() ||
                            (mozilla::IsFinite(val.toDouble()) &&
-                            ToInteger(val.toDouble()) == val.toDouble()));
+                            JS::ToInteger(val.toDouble()) == val.toDouble()));
     return true;
 }
 
 
 static const JSFunctionSpec number_static_methods[] = {
     JS_SELF_HOSTED_FN("isFinite", "Number_isFinite", 1,0),
     JS_FN("isInteger", Number_isInteger, 1, 0),
     JS_SELF_HOSTED_FN("isNaN", "Number_isNaN", 1,0),
@@ -1715,17 +1719,17 @@ js::ToLengthClamped(T *cx, HandleValue v
     if (v.isDouble()) {
         d = v.toDouble();
     } else {
         if (!ToNumber(cx, v, &d)) {
             *overflow = false;
             return false;
         }
     }
-    d = ToInteger(d);
+    d = JS::ToInteger(d);
     if (d <= 0.0) {
         *out = 0;
         return true;
     }
     if (d >= (double)0xFFFFFFFEU) {
         *overflow = true;
         return false;
     }
--- a/js/src/jsnum.h
+++ b/js/src/jsnum.h
@@ -7,17 +7,17 @@
 #ifndef jsnum_h
 #define jsnum_h
 
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/Range.h"
 
 #include "NamespaceImports.h"
 
-#include "vm/NumericConversions.h"
+#include "js/Conversions.h"
 
 namespace js {
 
 class StringBuffer;
 
 extern bool
 InitRuntimeNumberState(JSRuntime *rt);
 
@@ -241,17 +241,17 @@ ToInteger(JSContext *cx, HandleValue v, 
     }
     if (v.isDouble()) {
         *dp = v.toDouble();
     } else {
         extern JS_PUBLIC_API(bool) ToNumberSlow(JSContext *cx, Value v, double *dp);
         if (!ToNumberSlow(cx, v, dp))
             return false;
     }
-    *dp = ToInteger(*dp);
+    *dp = JS::ToInteger(*dp);
     return true;
 }
 
 /* ES6 7.1.15 ToLength, but clamped to the [0,2^32-2] range.  If the
  * return value is false then *overflow will be true iff the value was
  * not clampable to uint32_t range.
  *
  * For JSContext and ExclusiveContext.
--- a/js/src/jsscript.cpp
+++ b/js/src/jsscript.cpp
@@ -3765,17 +3765,17 @@ LazyScript::CreateRaw(ExclusiveContext *
     p.version = version;
     p.numFreeVariables = numFreeVariables;
     p.numInnerFunctions = numInnerFunctions;
     p.generatorKindBits = GeneratorKindAsBits(NotGenerator);
     p.strict = false;
     p.bindingsAccessedDynamically = false;
     p.hasDebuggerStatement = false;
     p.directlyInsideEval = false;
-    p.usesArgumentsAndApply = false;
+    p.usesArgumentsApplyAndThis = false;
 
     LazyScript *res = LazyScript::CreateRaw(cx, fun, packedFields, begin, end, lineno, column);
     MOZ_ASSERT_IF(res, res->version() == version);
     return res;
 }
 
 /* static */ LazyScript *
 LazyScript::Create(ExclusiveContext *cx, HandleFunction fun,
--- a/js/src/jsscript.h
+++ b/js/src/jsscript.h
@@ -964,18 +964,18 @@ class JSScript : public js::gc::TenuredC
     bool isActiveEval_:1;
 
     // Script came from eval(), and is in eval cache.
     bool isCachedEval_:1;
 
     // Set for functions defined at the top level within an 'eval' script.
     bool directlyInsideEval_:1;
 
-    // Both 'arguments' and f.apply() are used. This is likely to be a wrapper.
-    bool usesArgumentsAndApply_:1;
+    // 'this', 'arguments' and f.apply() are used. This is likely to be a wrapper.
+    bool usesArgumentsApplyAndThis_:1;
 
     /* script is attempted to be cloned anew at each callsite. This is
        temporarily needed for ParallelArray selfhosted code until type
        information can be made context sensitive. See discussion in
        bug 826148. */
     bool shouldCloneAtCallsite_:1;
     bool isCallsiteClone_:1; /* is a callsite clone; has a link to the original function */
     bool shouldInline_:1;    /* hint to inline when possible */
@@ -1192,20 +1192,20 @@ class JSScript : public js::gc::TenuredC
         MOZ_ASSERT(isCachedEval() && !isActiveEval());
         isCachedEval_ = false;
         isActiveEval_ = true;
     }
 
     void setActiveEval() { isActiveEval_ = true; }
     void setDirectlyInsideEval() { directlyInsideEval_ = true; }
 
-    bool usesArgumentsAndApply() const {
-        return usesArgumentsAndApply_;
+    bool usesArgumentsApplyAndThis() const {
+        return usesArgumentsApplyAndThis_;
     }
-    void setUsesArgumentsAndApply() { usesArgumentsAndApply_ = true; }
+    void setUsesArgumentsApplyAndThis() { usesArgumentsApplyAndThis_ = true; }
 
     bool shouldCloneAtCallsite() const {
         return shouldCloneAtCallsite_;
     }
     bool shouldInline() const {
         return shouldInline_;
     }
 
@@ -1889,17 +1889,17 @@ class LazyScript : public gc::TenuredCel
 
         uint32_t generatorKindBits : 2;
 
         // N.B. These are booleans but need to be uint32_t to pack correctly on MSVC.
         uint32_t strict : 1;
         uint32_t bindingsAccessedDynamically : 1;
         uint32_t hasDebuggerStatement : 1;
         uint32_t directlyInsideEval : 1;
-        uint32_t usesArgumentsAndApply : 1;
+        uint32_t usesArgumentsApplyAndThis : 1;
         uint32_t hasBeenCloned : 1;
         uint32_t treatAsRunOnce : 1;
     };
 
     union {
         PackedView p_;
         uint64_t packedFields_;
     };
@@ -2020,21 +2020,21 @@ class LazyScript : public gc::TenuredCel
 
     bool directlyInsideEval() const {
         return p_.directlyInsideEval;
     }
     void setDirectlyInsideEval() {
         p_.directlyInsideEval = true;
     }
 
-    bool usesArgumentsAndApply() const {
-        return p_.usesArgumentsAndApply;
+    bool usesArgumentsApplyAndThis() const {
+        return p_.usesArgumentsApplyAndThis;
     }
-    void setUsesArgumentsAndApply() {
-        p_.usesArgumentsAndApply = true;
+    void setUsesArgumentsApplyAndThis() {
+        p_.usesArgumentsApplyAndThis = true;
     }
 
     bool hasBeenCloned() const {
         return p_.hasBeenCloned;
     }
     void setHasBeenCloned() {
         p_.hasBeenCloned = true;
     }
--- a/js/src/jsstr.cpp
+++ b/js/src/jsstr.cpp
@@ -27,22 +27,22 @@
 #include "jsnum.h"
 #include "jsobj.h"
 #include "jsopcode.h"
 #include "jstypes.h"
 #include "jsutil.h"
 
 #include "builtin/Intl.h"
 #include "builtin/RegExp.h"
+#include "js/Conversions.h"
 #if ENABLE_INTL_API
 #include "unicode/unorm.h"
 #endif
 #include "vm/GlobalObject.h"
 #include "vm/Interpreter.h"
-#include "vm/NumericConversions.h"
 #include "vm/Opcodes.h"
 #include "vm/RegExpObject.h"
 #include "vm/RegExpStatics.h"
 #include "vm/ScopeObject.h"
 #include "vm/StringBuffer.h"
 
 #include "jsinferinlines.h"
 
@@ -52,16 +52,18 @@
 
 using namespace js;
 using namespace js::gc;
 using namespace js::types;
 using namespace js::unicode;
 
 using JS::Symbol;
 using JS::SymbolCode;
+using JS::ToInt32;
+using JS::ToUint32;
 
 using mozilla::AssertedCast;
 using mozilla::CheckedInt;
 using mozilla::IsNaN;
 using mozilla::IsNegativeZero;
 using mozilla::IsSame;
 using mozilla::Move;
 using mozilla::PodCopy;
@@ -1657,17 +1659,17 @@ js::str_lastIndexOf(JSContext *cx, unsig
                 start = 0;
             else if (i < start)
                 start = i;
         } else {
             double d;
             if (!ToNumber(cx, args[1], &d))
                 return false;
             if (!IsNaN(d)) {
-                d = ToInteger(d);
+                d = JS::ToInteger(d);
                 if (d <= 0)
                     start = 0;
                 else if (d < start)
                     start = int(d);
             }
         }
     }
 
--- a/js/src/moz.build
+++ b/js/src/moz.build
@@ -62,16 +62,17 @@ EXPORTS += [
 # If you add a header here, add it to js/src/jsapi-tests/testIntTypesABI.cpp so
 # that we ensure we don't over-expose our internal integer typedefs.  Note that
 # LegacyIntTypes.h below is deliberately exempted from this requirement.
 EXPORTS.js += [
     '../public/CallArgs.h',
     '../public/CallNonGenericMethod.h',
     '../public/CharacterEncoding.h',
     '../public/Class.h',
+    '../public/Conversions.h',
     '../public/Date.h',
     '../public/Debug.h',
     '../public/GCAPI.h',
     '../public/HashTable.h',
     '../public/HeapAPI.h',
     '../public/Id.h',
     '../public/LegacyIntTypes.h',
     '../public/MemoryMetrics.h',
--- a/js/src/vm/ArrayBufferObject.cpp
+++ b/js/src/vm/ArrayBufferObject.cpp
@@ -33,29 +33,31 @@
 #endif
 #include "jswrapper.h"
 
 #include "asmjs/AsmJSModule.h"
 #include "asmjs/AsmJSValidate.h"
 #include "gc/Barrier.h"
 #include "gc/Marking.h"
 #include "gc/Memory.h"
+#include "js/Conversions.h"
 #include "js/MemoryMetrics.h"
 #include "vm/GlobalObject.h"
 #include "vm/Interpreter.h"
-#include "vm/NumericConversions.h"
 #include "vm/WrapperObject.h"
 
 #include "jsatominlines.h"
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 
 #include "vm/NativeObject-inl.h"
 #include "vm/Shape-inl.h"
 
+using JS::ToInt32;
+
 using mozilla::DebugOnly;
 using mozilla::UniquePtr;
 
 using namespace js;
 using namespace js::gc;
 using namespace js::types;
 
 /*
--- a/js/src/vm/DateTime.h
+++ b/js/src/vm/DateTime.h
@@ -7,18 +7,18 @@
 #ifndef vm_DateTime_h
 #define vm_DateTime_h
 
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/MathAlgorithms.h"
 
 #include <stdint.h>
 
+#include "js/Conversions.h"
 #include "js/Value.h"
-#include "vm/NumericConversions.h"
 
 namespace js {
 
 /* Constants defined by ES5 15.9.1.10. */
 const double HoursPerDay = 24;
 const double MinutesPerHour = 60;
 const double SecondsPerMinute = 60;
 const double msPerSecond = 1000;
@@ -45,17 +45,17 @@ const double MaxTimeMagnitude = 8.64e15;
 inline double
 TimeClip(double time)
 {
     /* Steps 1-2. */
     if (!mozilla::IsFinite(time) || mozilla::Abs(time) > MaxTimeMagnitude)
         return JS::GenericNaN();
 
     /* Step 3. */
-    return ToInteger(time + (+0.0));
+    return JS::ToInteger(time + (+0.0));
 }
 
 /*
  * Stores date/time information, particularly concerning the current local
  * time zone, and implements a small cache for daylight saving time offset
  * computation.
  *
  * The basic idea is premised upon this fact: the DST offset never changes more
--- a/js/src/vm/HelperThreads.cpp
+++ b/js/src/vm/HelperThreads.cpp
@@ -4,16 +4,17 @@
  * 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 "vm/HelperThreads.h"
 
 #include "mozilla/DebugOnly.h"
 
 #include "jsnativestack.h"
+#include "jsnum.h" // For FIX_FPU()
 #include "prmjtime.h"
 
 #include "frontend/BytecodeCompiler.h"
 #include "jit/IonBuilder.h"
 #include "vm/Debugger.h"
 #include "vm/TraceLogging.h"
 
 #include "jscntxtinlines.h"
@@ -978,16 +979,22 @@ HelperThread::ThreadMain(void *arg)
 
 #ifdef MOZ_NUWA_PROCESS
     if (IsNuwaProcess()) {
         MOZ_ASSERT(NuwaMarkCurrentThread != nullptr);
         NuwaMarkCurrentThread(nullptr, nullptr);
     }
 #endif
 
+    //See bug 1104658.
+    //Set the FPU control word to be the same as the main thread's, or math
+    //computations on this thread may use incorrect precision rules during
+    //Ion compilation.
+    FIX_FPU();
+
     static_cast<HelperThread *>(arg)->threadLoop();
 }
 
 void
 HelperThread::handleAsmJSWorkload()
 {
     MOZ_ASSERT(HelperThreadState().isLocked());
     MOZ_ASSERT(HelperThreadState().canStartAsmJSCompile());
--- a/js/src/vm/NativeObject.h
+++ b/js/src/vm/NativeObject.h
@@ -16,17 +16,16 @@
 #include "jsinfer.h"
 #include "jsobj.h"
 #include "NamespaceImports.h"
 
 #include "gc/Barrier.h"
 #include "gc/Heap.h"
 #include "gc/Marking.h"
 #include "js/Value.h"
-#include "vm/NumericConversions.h"
 #include "vm/Shape.h"
 #include "vm/String.h"
 
 namespace js {
 
 class Nursery;
 class Shape;
 
--- a/js/src/vm/SharedTypedArrayObject.cpp
+++ b/js/src/vm/SharedTypedArrayObject.cpp
@@ -26,20 +26,20 @@
 # include "jswin.h"
 #endif
 #include "jswrapper.h"
 
 #include "asmjs/AsmJSModule.h"
 #include "asmjs/AsmJSValidate.h"
 #include "gc/Barrier.h"
 #include "gc/Marking.h"
+#include "js/Conversions.h"
 #include "vm/ArrayBufferObject.h"
 #include "vm/GlobalObject.h"
 #include "vm/Interpreter.h"
-#include "vm/NumericConversions.h"
 #include "vm/SharedArrayObject.h"
 #include "vm/TypedArrayCommon.h"
 #include "vm/WrapperObject.h"
 
 #include "jsatominlines.h"
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 
@@ -50,16 +50,18 @@ using namespace js::gc;
 using namespace js::types;
 
 using mozilla::IsNaN;
 using mozilla::NegativeInfinity;
 using mozilla::PodCopy;
 using mozilla::PositiveInfinity;
 using JS::CanonicalizeNaN;
 using JS::GenericNaN;
+using JS::ToInt32;
+using JS::ToUint32;
 
 TypedArrayLayout SharedTypedArrayObject::layout_(true, // shared
                                                  false, // neuterable
                                                  &SharedTypedArrayObject::classes[0],
                                                  &SharedTypedArrayObject::classes[Scalar::MaxTypedArrayViewType]);
 
 inline void
 InitSharedArrayBufferViewDataPointer(SharedTypedArrayObject *obj, SharedArrayBufferObject *buffer, size_t byteOffset)
--- a/js/src/vm/TypedArrayCommon.h
+++ b/js/src/vm/TypedArrayCommon.h
@@ -8,16 +8,17 @@
 #define vm_TypedArrayCommon_h
 
 /* Utilities and common inline code for TypedArray and SharedTypedArray */
 
 #include "mozilla/Assertions.h"
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/PodOperations.h"
 
+#include "js/Conversions.h"
 #include "js/Value.h"
 
 #include "vm/SharedTypedArrayObject.h"
 #include "vm/TypedArrayObject.h"
 
 namespace js {
 
 // Definitions below are shared between TypedArrayObject and
@@ -439,18 +440,18 @@ class ElementSpecific
             // canonicalize NaN values in more-deterministic builds.
             d = JS::CanonicalizeNaN(d);
 #endif
             return T(d);
         }
         if (MOZ_UNLIKELY(mozilla::IsNaN(d)))
             return T(0);
         if (TypeIsUnsigned<T>())
-            return T(ToUint32(d));
-        return T(ToInt32(d));
+            return T(JS::ToUint32(d));
+        return T(JS::ToInt32(d));
     }
 };
 
 template<typename SomeTypedArray>
 class TypedArrayMethods
 {
     static_assert(mozilla::IsSame<SomeTypedArray, TypedArrayObject>::value ||
                   mozilla::IsSame<SomeTypedArray, SharedTypedArrayObject>::value,
--- a/js/src/vm/TypedArrayObject.cpp
+++ b/js/src/vm/TypedArrayObject.cpp
@@ -26,20 +26,20 @@
 #ifdef XP_WIN
 # include "jswin.h"
 #endif
 #include "jswrapper.h"
 
 #include "builtin/TypedObjectConstants.h"
 #include "gc/Barrier.h"
 #include "gc/Marking.h"
+#include "js/Conversions.h"
 #include "vm/ArrayBufferObject.h"
 #include "vm/GlobalObject.h"
 #include "vm/Interpreter.h"
-#include "vm/NumericConversions.h"
 #include "vm/TypedArrayCommon.h"
 #include "vm/WrapperObject.h"
 
 #include "jsatominlines.h"
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 
 #include "vm/NativeObject-inl.h"
@@ -50,16 +50,18 @@ using namespace js::gc;
 using namespace js::types;
 
 using mozilla::IsNaN;
 using mozilla::NegativeInfinity;
 using mozilla::PodCopy;
 using mozilla::PositiveInfinity;
 using JS::CanonicalizeNaN;
 using JS::GenericNaN;
+using JS::ToInt32;
+using JS::ToUint32;
 
 /*
  * TypedArrayObject
  *
  * The non-templated base class for the specific typed implementations.
  * This class holds all the member variables that are used by
  * the subclasses.
  */
--- a/layout/base/nsBidiPresUtils.cpp
+++ b/layout/base/nsBidiPresUtils.cpp
@@ -2085,20 +2085,26 @@ public:
   }
 
   virtual nscoord GetWidth() MOZ_OVERRIDE
   {
     return nsLayoutUtils::AppUnitWidthOfString(mText, mLength, *mFontMetrics,
                                                *mTextRunConstructionContext);
   }
 
-  virtual void DrawText(nscoord aXOffset,
+  virtual void DrawText(nscoord aIOffset,
                         nscoord) MOZ_OVERRIDE
   {
-    mFontMetrics->DrawString(mText, mLength, mPt.x + aXOffs