Merge inbound to m-c
authorWes Kocher <wkocher@mozilla.com>
Thu, 10 Oct 2013 18:59:58 -0700
changeset 164221 672cd63528d3143db4c5fc4fb3ee11fa697f8489
parent 164167 1209f651c2d59a53479a83b3fb7d250184fb41fb (current diff)
parent 164220 1a9233d029191015a71024344d24089565e07eb4 (diff)
child 164229 027a7386406ff2ce0fc59e6afda43fd1d5c78179
child 164242 98b44fcfebb272a8513d5a65598d18c7e3e5d9ee
child 164247 bf3aa9efc6480e2d2ddc2dbb0a713e1c2d25da33
child 170410 485938514513680125dd2f655de120f4686bf059
push id3066
push userakeybl@mozilla.com
push dateMon, 09 Dec 2013 19:58:46 +0000
treeherdermozilla-beta@a31a0dce83aa [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone27.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 inbound to m-c
--- a/CLOBBER
+++ b/CLOBBER
@@ -13,9 +13,9 @@
 #          |               |
 #          O <-- Clobber   O  <-- Clobber
 #
 # Note: The description below will be part of the error message shown to users.
 #
 # Modifying this file will now automatically clobber the buildbot machines \o/
 #
 
-Bug 899574 needed a clobber, at least on Windows.
+Bug 922461 needs a clobber to regenerate code and survive bug 925243's FAIL_ON_WARNINGS annotation.
--- a/accessible/src/mac/mozAccessible.mm
+++ b/accessible/src/mac/mozAccessible.mm
@@ -535,17 +535,18 @@ GetClosestInterestingAccessible(id anObj
 }
 
 - (id)value
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL;
 
   nsAutoString value;
   mGeckoAccessible->GetValue (value);
-  return value.IsEmpty() ? nil : [NSString stringWithCharacters:value.BeginReading() length:value.Length()];
+  return value.IsEmpty() ? nil : [NSString stringWithCharacters:reinterpret_cast<const unichar*>(value.BeginReading())
+                                                         length:value.Length()];
 
   NS_OBJC_END_TRY_ABORT_BLOCK_NIL;
 }
 
 - (void)valueDidChange
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
 
@@ -579,17 +580,18 @@ GetClosestInterestingAccessible(id anObj
 }
 
 - (NSString*)help
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL;
 
   nsAutoString helpText;
   mGeckoAccessible->GetHelp (helpText);
-  return helpText.IsEmpty() ? nil : [NSString stringWithCharacters:helpText.BeginReading() length:helpText.Length()];
+  return helpText.IsEmpty() ? nil : [NSString stringWithCharacters:reinterpret_cast<const unichar*>(helpText.BeginReading())
+                                                            length:helpText.Length()];
 
   NS_OBJC_END_TRY_ABORT_BLOCK_NIL;
 }
 
 // objc-style description (from NSObject); not to be confused with the accessible description above.
 - (NSString*)description
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL;
--- a/browser/components/sessionstore/content/content-sessionStore.js
+++ b/browser/components/sessionstore/content/content-sessionStore.js
@@ -3,16 +3,18 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
 function debug(msg) {
   Services.console.logStringMessage("SessionStoreContent: " + msg);
 }
 
+let Cu = Components.utils;
+
 Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
 
 XPCOMUtils.defineLazyModuleGetter(this, "DocShellCapabilities",
   "resource:///modules/sessionstore/DocShellCapabilities.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "SessionHistory",
   "resource:///modules/sessionstore/SessionHistory.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "SessionStorage",
   "resource:///modules/sessionstore/SessionStorage.jsm");
--- a/browser/components/sessionstore/src/SessionStore.jsm
+++ b/browser/components/sessionstore/src/SessionStore.jsm
@@ -2521,17 +2521,19 @@ let SessionStoreInternal = {
 
       // Make sure that set/getTabValue will set/read the correct data by
       // wiping out any current value in tab.__SS_extdata.
       delete tab.__SS_extdata;
 
       if (!tabData.entries || tabData.entries.length == 0) {
         // make sure to blank out this tab's content
         // (just purging the tab's history won't be enough)
-        browser.contentDocument.location = "about:blank";
+        browser.loadURIWithFlags("about:blank",
+                                 Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_HISTORY,
+                                 null, null, null);
         continue;
       }
 
       browser.stop(); // in case about:blank isn't done yet
 
       // wall-paper fix for bug 439675: make sure that the URL to be loaded
       // is always visible in the address bar
       let activeIndex = (tabData.index || tabData.entries.length) - 1;
--- a/config/baseconfig.mk
+++ b/config/baseconfig.mk
@@ -1,13 +1,18 @@
 includedir := $(includedir)/$(MOZ_APP_NAME)-$(MOZ_APP_VERSION)
 idldir = $(datadir)/idl/$(MOZ_APP_NAME)-$(MOZ_APP_VERSION)
 installdir = $(libdir)/$(MOZ_APP_NAME)-$(MOZ_APP_VERSION)
 sdkdir = $(libdir)/$(MOZ_APP_NAME)-devel-$(MOZ_APP_VERSION)
-DIST = $(DEPTH)/dist
+
+ifndef INCLUDED_FUNCTIONS_MK
+include $(topsrcdir)/config/makefiles/functions.mk
+endif
+
+DIST := $(call core_realpath,$(DEPTH)/dist)
 
 # We do magic with OBJ_SUFFIX in config.mk, the following ensures we don't
 # manually use it before config.mk inclusion
 _OBJ_SUFFIX := $(OBJ_SUFFIX)
 OBJ_SUFFIX = $(error config/config.mk needs to be included before using OBJ_SUFFIX)
 
 # We only want to do the pymake sanity on Windows, other os's can cope
 ifeq ($(HOST_OS_ARCH),WINNT)
--- a/config/config.mk
+++ b/config/config.mk
@@ -59,20 +59,16 @@ CHECK_VARS := \
  $(NULL)
 
 # checks for internal spaces or trailing spaces in the variable
 # named by $x
 check-variable = $(if $(filter-out 0 1,$(words $($(x))z)),$(error Spaces are not allowed in $(x)))
 
 $(foreach x,$(CHECK_VARS),$(check-variable))
 
-ifndef INCLUDED_FUNCTIONS_MK
-include $(topsrcdir)/config/makefiles/functions.mk
-endif
-
 RM = rm -f
 
 # LIBXUL_DIST is not defined under js/src, thus we make it mean DIST there.
 LIBXUL_DIST ?= $(DIST)
 
 # FINAL_TARGET specifies the location into which we copy end-user-shipped
 # build products (typelibs, components, chrome).
 #
--- a/configure.in
+++ b/configure.in
@@ -3499,17 +3499,16 @@ MALLOC_H=
 for file in $MALLOC_HEADERS; do
   MOZ_CHECK_HEADER($file, [MALLOC_H=$file])
   if test "$MALLOC_H" != ""; then
     AC_DEFINE_UNQUOTED(MALLOC_H, <$MALLOC_H>)
     break
   fi
 done
 
-MOZ_ALLOCATING_FUNCS="strndup posix_memalign memalign valloc"
 AC_CHECK_FUNCS(strndup posix_memalign memalign valloc)
 
 AC_CHECK_FUNCS(malloc_usable_size)
 
 dnl See if compiler supports some gcc-style attributes
 
 AC_CACHE_CHECK(for __attribute__((always_inline)),
                ac_cv_attribute_always_inline,
@@ -7148,17 +7147,17 @@ fi
 
 dnl ========================================================
 dnl Zealous JavaScript GC
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(gczeal,
 [  --enable-gczeal         Enable zealous JavaScript GCing],
     JS_GC_ZEAL=1,
     JS_GC_ZEAL= )
-if test -n "$JS_GC_ZEAL"; then
+if test -n "$JS_GC_ZEAL" -o -n "$MOZ_DEBUG"; then
     AC_DEFINE(JS_GC_ZEAL)
 fi
 
 dnl ========================================================
 dnl JS opt-mode assertions and minidump instrumentation
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(js-diagnostics,
 [  --enable-js-diagnostics
--- a/content/base/src/nsContentPolicy.cpp
+++ b/content/base/src/nsContentPolicy.cpp
@@ -112,17 +112,18 @@ nsContentPolicy::CheckPolicy(CPMethod   
         }
     }
 
     /* 
      * Enumerate mPolicies and ask each of them, taking the logical AND of
      * their permissions.
      */
     nsresult rv;
-    const nsCOMArray<nsIContentPolicy>& entries = mPolicies.GetEntries();
+    nsCOMArray<nsIContentPolicy> entries;
+    mPolicies.GetEntries(entries);
     int32_t count = entries.Count();
     for (int32_t i = 0; i < count; i++) {
         /* check the appropriate policy */
         rv = (entries[i]->*policyMethod)(contentType, contentLocation,
                                          requestingLocation, requestingContext,
                                          mimeType, extra, requestPrincipal,
                                          decision);
 
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -499,17 +499,18 @@ nsFrameLoader::ReallyStartLoadingInterna
   if (OwnerIsBrowserFrame()) {
     flags = nsIWebNavigation::LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP |
             nsIWebNavigation::LOAD_FLAGS_DISALLOW_INHERIT_OWNER;
   }
 
   // Kick off the load...
   bool tmpState = mNeedsAsyncDestroy;
   mNeedsAsyncDestroy = true;
-  rv = mDocShell->LoadURI(mURIToLoad, loadInfo, flags, false);
+  nsCOMPtr<nsIURI> uriToLoad = mURIToLoad;
+  rv = mDocShell->LoadURI(uriToLoad, loadInfo, flags, false);
   mNeedsAsyncDestroy = tmpState;
   mURIToLoad = nullptr;
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
 nsresult
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -264,81 +264,29 @@ struct DeltaValues
     deltaX(aEvent->deltaX), deltaY(aEvent->deltaY)
   {
   }
 
   double deltaX;
   double deltaY;
 };
 
-/******************************************************************/
-/* nsScrollbarsForWheel                                           */
-/******************************************************************/
-
-class nsScrollbarsForWheel {
-public:
-  static void PrepareToScrollText(nsEventStateManager* aESM,
-                                  nsIFrame* aTargetFrame,
-                                  WheelEvent* aEvent);
-  static void SetActiveScrollTarget(nsIScrollableFrame* aScrollTarget);
-  // Hide all scrollbars (both mActiveOwner's and mActivatedScrollTargets')
-  static void MayInactivate();
-  static void Inactivate();
-  static bool IsActive();
-  static void OwnWheelTransaction(bool aOwn);
-
-protected:
-  static const size_t         kNumberOfTargets = 4;
-  static const DeltaValues    directions[kNumberOfTargets];
-  static nsWeakFrame          sActiveOwner;
-  static nsWeakFrame          sActivatedScrollTargets[kNumberOfTargets];
-  static bool                 sHadWheelStart;
-  static bool                 sOwnWheelTransaction;
-
-
-  /**
-   * These two methods are called upon NS_WHEEL_START/NS_WHEEL_STOP events
-   * to show/hide the right scrollbars.
-   */
-  static void TemporarilyActivateAllPossibleScrollTargets(
-                                  nsEventStateManager* aESM,
-                                  nsIFrame* aTargetFrame,
-                                  WheelEvent* aEvent);
-  static void DeactivateAllTemporarilyActivatedScrollTargets();
-};
-
-const DeltaValues nsScrollbarsForWheel::directions[kNumberOfTargets] = {
-  DeltaValues(-1, 0), DeltaValues(+1, 0), DeltaValues(0, -1), DeltaValues(0, +1)
-};
-nsWeakFrame nsScrollbarsForWheel::sActiveOwner = nullptr;
-nsWeakFrame nsScrollbarsForWheel::sActivatedScrollTargets[kNumberOfTargets] = {
-  nullptr, nullptr, nullptr, nullptr
-};
-bool nsScrollbarsForWheel::sHadWheelStart = false;
-bool nsScrollbarsForWheel::sOwnWheelTransaction = false;
-
-/******************************************************************/
-/* nsMouseWheelTransaction                                        */
-/******************************************************************/
-
 class nsMouseWheelTransaction {
 public:
   static nsIFrame* GetTargetFrame() { return sTargetFrame; }
   static void BeginTransaction(nsIFrame* aTargetFrame,
                                WheelEvent* aEvent);
   // Be careful, UpdateTransaction may fire a DOM event, therefore, the target
   // frame might be destroyed in the event handler.
   static bool UpdateTransaction(WheelEvent* aEvent);
-  static void MayEndTransaction();
   static void EndTransaction();
   static void OnEvent(WidgetEvent* aEvent);
   static void Shutdown();
   static uint32_t GetTimeoutTime();
 
-  static void OwnScrollbars(bool aOwn);
 
   static DeltaValues AccelerateWheelDelta(WheelEvent* aEvent,
                                           bool aAllowScrollSpeedOverride);
 
   enum {
     kScrollSeriesTimeout = 80
   };
 protected:
@@ -346,78 +294,66 @@ protected:
   static void OnFailToScrollTarget();
   static void OnTimeout(nsITimer *aTimer, void *aClosure);
   static void SetTimeout();
   static uint32_t GetIgnoreMoveDelayTime();
   static int32_t GetAccelerationStart();
   static int32_t GetAccelerationFactor();
   static DeltaValues OverrideSystemScrollSpeed(WheelEvent* aEvent);
   static double ComputeAcceleratedWheelDelta(double aDelta, int32_t aFactor);
-  static bool OutOfTime(uint32_t aBaseTime, uint32_t aThreshold);
 
   static nsWeakFrame sTargetFrame;
   static uint32_t    sTime;        // in milliseconds
   static uint32_t    sMouseMoved;  // in milliseconds
   static nsITimer*   sTimer;
   static int32_t     sScrollSeriesCounter;
-  static bool        sOwnScrollbars;
 };
 
 nsWeakFrame nsMouseWheelTransaction::sTargetFrame(nullptr);
 uint32_t    nsMouseWheelTransaction::sTime        = 0;
 uint32_t    nsMouseWheelTransaction::sMouseMoved  = 0;
 nsITimer*   nsMouseWheelTransaction::sTimer       = nullptr;
 int32_t     nsMouseWheelTransaction::sScrollSeriesCounter = 0;
-bool        nsMouseWheelTransaction::sOwnScrollbars = false;
+
+static bool
+OutOfTime(uint32_t aBaseTime, uint32_t aThreshold)
+{
+  uint32_t now = PR_IntervalToMilliseconds(PR_IntervalNow());
+  return (now - aBaseTime > aThreshold);
+}
 
 static bool
 CanScrollInRange(nscoord aMin, nscoord aValue, nscoord aMax, double aDirection)
 {
   return aDirection > 0.0 ? aValue < static_cast<double>(aMax) :
                             static_cast<double>(aMin) < aValue;
 }
 
 static bool
-CanScrollOn(nsIScrollableFrame* aScrollFrame, double aDirectionX, double aDirectionY)
+CanScrollOn(nsIScrollableFrame* aScrollFrame, double aDeltaX, double aDeltaY)
 {
   MOZ_ASSERT(aScrollFrame);
-  NS_ASSERTION(aDirectionX || aDirectionY,
+  NS_ASSERTION(aDeltaX || aDeltaY,
                "One of the delta values must be non-zero at least");
 
   nsPoint scrollPt = aScrollFrame->GetScrollPosition();
   nsRect scrollRange = aScrollFrame->GetScrollRange();
   uint32_t directions = aScrollFrame->GetPerceivedScrollingDirections();
 
-  return (aDirectionX && (directions & nsIScrollableFrame::HORIZONTAL) &&
-          CanScrollInRange(scrollRange.x, scrollPt.x, scrollRange.XMost(), aDirectionX)) ||
-         (aDirectionY && (directions & nsIScrollableFrame::VERTICAL) &&
-          CanScrollInRange(scrollRange.y, scrollPt.y, scrollRange.YMost(), aDirectionY));
-}
-
-bool
-nsMouseWheelTransaction::OutOfTime(uint32_t aBaseTime, uint32_t aThreshold)
-{
-  uint32_t now = PR_IntervalToMilliseconds(PR_IntervalNow());
-  return (now - aBaseTime > aThreshold);
-}
-
-void
-nsMouseWheelTransaction::OwnScrollbars(bool aOwn)
-{
-  sOwnScrollbars = aOwn;
+  return (aDeltaX && (directions & nsIScrollableFrame::HORIZONTAL) &&
+          CanScrollInRange(scrollRange.x, scrollPt.x, scrollRange.XMost(), aDeltaX)) ||
+         (aDeltaY && (directions & nsIScrollableFrame::VERTICAL) &&
+          CanScrollInRange(scrollRange.y, scrollPt.y, scrollRange.YMost(), aDeltaY));
 }
 
 void
 nsMouseWheelTransaction::BeginTransaction(nsIFrame* aTargetFrame,
                                           WheelEvent* aEvent)
 {
   NS_ASSERTION(!sTargetFrame, "previous transaction is not finished!");
-  MOZ_ASSERT(aEvent->message == NS_WHEEL_WHEEL,
-             "Transaction must be started with a wheel event");
-  nsScrollbarsForWheel::OwnWheelTransaction(false);
   sTargetFrame = aTargetFrame;
   sScrollSeriesCounter = 0;
   if (!UpdateTransaction(aEvent)) {
     NS_ERROR("BeginTransaction is called even cannot scroll the frame");
     EndTransaction();
   }
 }
 
@@ -445,37 +381,22 @@ nsMouseWheelTransaction::UpdateTransacti
   // 2. If the computer runs slowly by other processes eating the CPU resource,
   //    the event creation time doesn't keep real time.
   sTime = PR_IntervalToMilliseconds(PR_IntervalNow());
   sMouseMoved = 0;
   return true;
 }
 
 void
-nsMouseWheelTransaction::MayEndTransaction()
-{
-  if (!sOwnScrollbars && nsScrollbarsForWheel::IsActive()) {
-    nsScrollbarsForWheel::OwnWheelTransaction(true);
-  } else {
-    EndTransaction();
-  }
-}
-
-void
 nsMouseWheelTransaction::EndTransaction()
 {
   if (sTimer)
     sTimer->Cancel();
   sTargetFrame = nullptr;
   sScrollSeriesCounter = 0;
-  if (sOwnScrollbars) {
-    sOwnScrollbars = false;
-    nsScrollbarsForWheel::OwnWheelTransaction(false);
-    nsScrollbarsForWheel::Inactivate();
-  }
 }
 
 void
 nsMouseWheelTransaction::OnEvent(WidgetEvent* aEvent)
 {
   if (!sTargetFrame)
     return;
 
@@ -489,28 +410,28 @@ nsMouseWheelTransaction::OnEvent(WidgetE
   }
 
   switch (aEvent->message) {
     case NS_WHEEL_WHEEL:
       if (sMouseMoved != 0 &&
           OutOfTime(sMouseMoved, GetIgnoreMoveDelayTime())) {
         // Terminate the current mousewheel transaction if the mouse moved more
         // than ignoremovedelay milliseconds ago
-        MayEndTransaction();
+        EndTransaction();
       }
       return;
     case NS_MOUSE_MOVE:
     case NS_DRAGDROP_OVER:
       if (IsMouseEventReal(aEvent)) {
         // If the cursor is moving to be outside the frame,
         // terminate the scrollwheel transaction.
         nsIntPoint pt = GetScreenPoint(static_cast<WidgetGUIEvent*>(aEvent));
         nsIntRect r = sTargetFrame->GetScreenRectExternal();
         if (!r.Contains(pt)) {
-          MayEndTransaction();
+          EndTransaction();
           return;
         }
 
         // If the cursor is moving inside the frame, and it is less than
         // ignoremovedelay milliseconds since the last scroll operation, ignore
         // the mouse move; otherwise, record the current mouse move time to be
         // checked later
         if (OutOfTime(sTime, GetIgnoreMoveDelayTime())) {
@@ -549,34 +470,33 @@ nsMouseWheelTransaction::OnFailToScrollT
     nsContentUtils::DispatchTrustedEvent(
                       sTargetFrame->GetContent()->OwnerDoc(),
                       sTargetFrame->GetContent(),
                       NS_LITERAL_STRING("MozMouseScrollFailed"),
                       true, true);
   }
   // The target frame might be destroyed in the event handler, at that time,
   // we need to finish the current transaction
-  if (!sTargetFrame) {
+  if (!sTargetFrame)
     EndTransaction();
-  }
 }
 
 void
 nsMouseWheelTransaction::OnTimeout(nsITimer* aTimer, void* aClosure)
 {
   if (!sTargetFrame) {
     // The transaction target was destroyed already
     EndTransaction();
     return;
   }
   // Store the sTargetFrame, the variable becomes null in EndTransaction.
   nsIFrame* frame = sTargetFrame;
   // We need to finish current transaction before DOM event firing. Because
   // the next DOM event might create strange situation for us.
-  MayEndTransaction();
+  EndTransaction();
 
   if (Preferences::GetBool("test.mousescroll", false)) {
     // This event is used for automated tests, see bug 442774.
     nsContentUtils::DispatchTrustedEvent(
                       frame->GetContent()->OwnerDoc(),
                       frame->GetContent(),
                       NS_LITERAL_STRING("MozMouseScrollTransactionTimeout"),
                       true, true);
@@ -701,137 +621,16 @@ nsMouseWheelTransaction::OverrideSystemS
   nsresult rv =
     widget->OverrideSystemMouseScrollSpeed(aEvent->deltaX, aEvent->deltaY,
                                            overriddenDeltaValues.deltaX,
                                            overriddenDeltaValues.deltaY);
   return NS_FAILED(rv) ? DeltaValues(aEvent) : overriddenDeltaValues;
 }
 
 /******************************************************************/
-/* nsScrollbarsForWheel                                           */
-/******************************************************************/
-
-void
-nsScrollbarsForWheel::PrepareToScrollText(
-                                  nsEventStateManager* aESM,
-                                  nsIFrame* aTargetFrame,
-                                  WheelEvent* aEvent)
-{
-  if (aEvent->message == NS_WHEEL_START) {
-    nsMouseWheelTransaction::OwnScrollbars(false);
-    if (!IsActive()) {
-      TemporarilyActivateAllPossibleScrollTargets(aESM, aTargetFrame, aEvent);
-      sHadWheelStart = true;
-    }
-  } else {
-    DeactivateAllTemporarilyActivatedScrollTargets();
-  }
-}
-
-void
-nsScrollbarsForWheel::SetActiveScrollTarget(nsIScrollableFrame* aScrollTarget)
-{
-  if (!sHadWheelStart) {
-    return;
-  }
-  nsIScrollbarOwner* scrollbarOwner = do_QueryFrame(aScrollTarget);
-  if (!scrollbarOwner) {
-    return;
-  }
-  sHadWheelStart = false;
-  sActiveOwner = do_QueryFrame(aScrollTarget);
-  scrollbarOwner->ScrollbarActivityStarted();
-}
-
-void
-nsScrollbarsForWheel::MayInactivate()
-{
-  if (!sOwnWheelTransaction && nsMouseWheelTransaction::GetTargetFrame()) {
-    nsMouseWheelTransaction::OwnScrollbars(true);
-  } else {
-    Inactivate();
-  }
-}
-
-void
-nsScrollbarsForWheel::Inactivate()
-{
-  nsIScrollbarOwner* scrollbarOwner = do_QueryFrame(sActiveOwner);
-  if (scrollbarOwner) {
-    scrollbarOwner->ScrollbarActivityStopped();
-  }
-  sActiveOwner = nullptr;
-  DeactivateAllTemporarilyActivatedScrollTargets();
-  if (sOwnWheelTransaction) {
-    sOwnWheelTransaction = false;
-    nsMouseWheelTransaction::OwnScrollbars(false);
-    nsMouseWheelTransaction::EndTransaction();
-  }
-}
-
-bool
-nsScrollbarsForWheel::IsActive()
-{
-  if (sActiveOwner) {
-    return true;
-  }
-  for (size_t i = 0; i < kNumberOfTargets; ++i) {
-    if (sActivatedScrollTargets[i]) {
-      return true;
-    }
-  }
-  return false;
-}
-
-void
-nsScrollbarsForWheel::OwnWheelTransaction(bool aOwn)
-{
-  sOwnWheelTransaction = aOwn;
-}
-
-void
-nsScrollbarsForWheel::TemporarilyActivateAllPossibleScrollTargets(
-                                               nsEventStateManager* aESM,
-                                               nsIFrame* aTargetFrame,
-                                               WheelEvent* aEvent)
-{
-  for (size_t i = 0; i < kNumberOfTargets; i++) {
-    const DeltaValues *dir = &directions[i];
-    nsWeakFrame* scrollTarget = &sActivatedScrollTargets[i];
-    MOZ_ASSERT(!*scrollTarget, "scroll target still temporarily activated!");
-    nsIScrollableFrame* target =
-      aESM->ComputeScrollTarget(aTargetFrame, dir->deltaX, dir->deltaY, aEvent, 
-                                nsEventStateManager::COMPUTE_DEFAULT_ACTION_TARGET);
-    if (target) {
-      nsIScrollbarOwner* scrollbarOwner = do_QueryFrame(target);
-      if (scrollbarOwner) {
-        nsIFrame* targetFrame = do_QueryFrame(target);
-        *scrollTarget = targetFrame;
-        scrollbarOwner->ScrollbarActivityStarted();
-      }
-    }
-  }
-}
-
-void
-nsScrollbarsForWheel::DeactivateAllTemporarilyActivatedScrollTargets()
-{
-  for (size_t i = 0; i < kNumberOfTargets; i++) {
-    nsWeakFrame* scrollTarget = &sActivatedScrollTargets[i];
-    if (*scrollTarget) {
-      nsIScrollbarOwner* scrollbarOwner = do_QueryFrame(*scrollTarget);
-      if (scrollbarOwner) {
-        scrollbarOwner->ScrollbarActivityStopped();
-      }
-      *scrollTarget = nullptr;
-    }
-  }
-}
-
-/******************************************************************/
 /* nsEventStateManager                                            */
 /******************************************************************/
 
 nsEventStateManager::nsEventStateManager()
   : mLockCursor(0),
     mPreLockPoint(0,0),
     mCurrentTarget(nullptr),
     mLastMouseOverFrame(nullptr),
@@ -1173,30 +972,23 @@ nsEventStateManager::PreHandleEvent(nsPr
   case NS_KEY_UP:
     {
       nsIContent* content = GetFocusedContent();
       if (content)
         mCurrentTargetContent = content;
     }
     break;
   case NS_WHEEL_WHEEL:
-  case NS_WHEEL_START:
-  case NS_WHEEL_STOP:
     {
       NS_ASSERTION(aEvent->mFlags.mIsTrusted,
                    "Untrusted wheel event shouldn't be here");
 
       nsIContent* content = GetFocusedContent();
-      if (content) {
+      if (content)
         mCurrentTargetContent = content;
-      }
-
-      if (aEvent->message != NS_WHEEL_WHEEL) {
-        break;
-      }
 
       WheelEvent* wheelEvent = static_cast<WheelEvent*>(aEvent);
       WheelPrefs::GetInstance()->ApplyUserPrefsToDelta(wheelEvent);
 
       // If we won't dispatch a DOM event for this event, nothing to do anymore.
       if (!wheelEvent->IsAllowedToDispatchDOMEvent()) {
         break;
       }
@@ -2749,30 +2541,16 @@ nsEventStateManager::SendPixelScrollEven
                               &event, nullptr, aStatus);
 }
 
 nsIScrollableFrame*
 nsEventStateManager::ComputeScrollTarget(nsIFrame* aTargetFrame,
                                          WheelEvent* aEvent,
                                          ComputeScrollTargetOptions aOptions)
 {
-  return ComputeScrollTarget(aTargetFrame, aEvent->deltaX, aEvent->deltaY,
-                             aEvent, aOptions);
-}
-
-// Overload ComputeScrollTarget method to allow passing "test" dx and dy when looking
-// for which scrollbarowners to activate when two finger down on trackpad
-// and before any actual motion
-nsIScrollableFrame*
-nsEventStateManager::ComputeScrollTarget(nsIFrame* aTargetFrame,
-                                         double aDirectionX,
-                                         double aDirectionY,
-                                         WheelEvent* aEvent,
-                                         ComputeScrollTargetOptions aOptions)
-{
   if (aOptions & PREFER_MOUSE_WHEEL_TRANSACTION) {
     // If the user recently scrolled with the mousewheel, then they probably
     // want to scroll the same view as before instead of the view under the
     // cursor.  nsMouseWheelTransaction tracks the frame currently being
     // scrolled with the mousewheel. We consider the transaction ended when the
     // mouse moves more than "mousewheel.transaction.ignoremovedelay"
     // milliseconds after the last scroll operation, or any time the mouse moves
     // out of the frame, or when more than "mousewheel.transaction.timeout"
@@ -2786,24 +2564,24 @@ nsEventStateManager::ComputeScrollTarget
         return frameToScroll;
       }
     }
   }
 
   // If the event doesn't cause scroll actually, we cannot find scroll target
   // because we check if the event can cause scroll actually on each found
   // scrollable frame.
-  if (!aDirectionX && !aDirectionY) {
+  if (!aEvent->deltaX && !aEvent->deltaY) {
     return nullptr;
   }
 
   bool checkIfScrollableX =
-    aDirectionX && (aOptions & PREFER_ACTUAL_SCROLLABLE_TARGET_ALONG_X_AXIS);
+    aEvent->deltaX && (aOptions & PREFER_ACTUAL_SCROLLABLE_TARGET_ALONG_X_AXIS);
   bool checkIfScrollableY =
-    aDirectionY && (aOptions & PREFER_ACTUAL_SCROLLABLE_TARGET_ALONG_Y_AXIS);
+    aEvent->deltaY && (aOptions & PREFER_ACTUAL_SCROLLABLE_TARGET_ALONG_Y_AXIS);
 
   nsIScrollableFrame* frameToScroll = nullptr;
   nsIFrame* scrollFrame =
     !(aOptions & START_FROM_PARENT) ? aTargetFrame :
                                       GetParentFrameToScroll(aTargetFrame);
   for (; scrollFrame; scrollFrame = GetParentFrameToScroll(scrollFrame)) {
     // Check whether the frame wants to provide us with a scrollable view.
     frameToScroll = scrollFrame->GetScrollTargetFrame();
@@ -2821,17 +2599,18 @@ nsEventStateManager::ComputeScrollTarget
     if ((hiddenForV && hiddenForH) ||
         (checkIfScrollableY && !checkIfScrollableX && hiddenForV) ||
         (checkIfScrollableX && !checkIfScrollableY && hiddenForH)) {
       continue;
     }
 
     // For default action, we should climb up the tree if cannot scroll it
     // by the event actually.
-    bool canScroll = CanScrollOn(frameToScroll, aDirectionX, aDirectionY);
+    bool canScroll = CanScrollOn(frameToScroll,
+                                 aEvent->deltaX, aEvent->deltaY);
     // Comboboxes need special care.
     nsIComboboxControlFrame* comboBox = do_QueryFrame(scrollFrame);
     if (comboBox) {
       if (comboBox->IsDroppedDown()) {
         // Don't propagate to parent when drop down menu is active.
         return canScroll ? frameToScroll : nullptr;
       }
       // Always propagate when not dropped down (even if focused).
@@ -3386,61 +3165,43 @@ nsEventStateManager::PostHandleEvent(nsP
 
       nsIPresShell *shell = presContext->GetPresShell();
       if (shell) {
         nsRefPtr<nsFrameSelection> frameSelection = shell->FrameSelection();
         frameSelection->SetMouseDownState(false);
       }
     }
     break;
-  case NS_WHEEL_STOP:
-    {
-      MOZ_ASSERT(aEvent->mFlags.mIsTrusted);
-      nsScrollbarsForWheel::MayInactivate();
-    }
-    break;
   case NS_WHEEL_WHEEL:
-  case NS_WHEEL_START:
     {
       MOZ_ASSERT(aEvent->mFlags.mIsTrusted);
 
       if (*aStatus == nsEventStatus_eConsumeNoDefault) {
-        nsScrollbarsForWheel::Inactivate();
         break;
       }
 
       WheelEvent* wheelEvent = static_cast<WheelEvent*>(aEvent);
       switch (WheelPrefs::GetInstance()->ComputeActionFor(wheelEvent)) {
         case WheelPrefs::ACTION_SCROLL: {
+          if (!wheelEvent->deltaX && !wheelEvent->deltaY) {
+            break;
+          }
           // For scrolling of default action, we should honor the mouse wheel
           // transaction.
-          
-          nsScrollbarsForWheel::PrepareToScrollText(this, aTargetFrame, wheelEvent);
-          
-          if (aEvent->message != NS_WHEEL_WHEEL ||
-              (!wheelEvent->deltaX && !wheelEvent->deltaY)) {
-            break;
-          }
-
           nsIScrollableFrame* scrollTarget =
             ComputeScrollTarget(aTargetFrame, wheelEvent,
                                 COMPUTE_DEFAULT_ACTION_TARGET);
-
-          nsScrollbarsForWheel::SetActiveScrollTarget(scrollTarget);
-
           wheelEvent->overflowDeltaX = wheelEvent->deltaX;
           wheelEvent->overflowDeltaY = wheelEvent->deltaY;
-
           WheelPrefs::GetInstance()->
             CancelApplyingUserPrefsFromOverflowDelta(wheelEvent);
           if (scrollTarget) {
             DoScrollText(scrollTarget, wheelEvent);
           } else {
             nsMouseWheelTransaction::EndTransaction();
-            nsScrollbarsForWheel::Inactivate();
           }
           break;
         }
         case WheelPrefs::ACTION_HISTORY: {
           // If this event doesn't cause NS_MOUSE_SCROLL event or the direction
           // is oblique, don't perform history back/forward.
           int32_t intDelta = wheelEvent->GetPreferredIntDelta();
           if (!intDelta) {
--- a/content/events/src/nsEventStateManager.h
+++ b/content/events/src/nsEventStateManager.h
@@ -41,17 +41,16 @@ class TabParent;
 /*
  * Event listener manager
  */
 
 class nsEventStateManager : public nsSupportsWeakReference,
                             public nsIObserver
 {
   friend class nsMouseWheelTransaction;
-  friend class nsScrollbarsForWheel;
 public:
 
   typedef mozilla::TimeStamp TimeStamp;
   typedef mozilla::TimeDuration TimeDuration;
   typedef mozilla::LayoutDeviceIntPoint LayoutDeviceIntPoint;
 
   nsEventStateManager();
   virtual ~nsEventStateManager();
@@ -553,22 +552,16 @@ protected:
       (PREFER_ACTUAL_SCROLLABLE_TARGET_ALONG_X_AXIS | START_FROM_PARENT),
     COMPUTE_SCROLLABLE_ANCESTOR_ALONG_Y_AXIS     =
       (PREFER_ACTUAL_SCROLLABLE_TARGET_ALONG_Y_AXIS | START_FROM_PARENT)
   };
   nsIScrollableFrame* ComputeScrollTarget(nsIFrame* aTargetFrame,
                                           mozilla::WheelEvent* aEvent,
                                           ComputeScrollTargetOptions aOptions);
 
-  nsIScrollableFrame* ComputeScrollTarget(nsIFrame* aTargetFrame,
-                                          double aDirectionX,
-                                          double aDirectionY,
-                                          mozilla::WheelEvent* aEvent,
-                                          ComputeScrollTargetOptions aOptions);
-
   /**
    * GetScrollAmount() returns the scroll amount in app uints of one line or
    * one page.  If the wheel event scrolls a page, returns the page width and
    * height.  Otherwise, returns line height for both its width and height.
    *
    * @param aScrollableFrame    A frame which will be scrolled by the event.
    *                            The result of ComputeScrollTarget() is
    *                            expected for this value.
--- a/content/html/content/src/HTMLImageElement.cpp
+++ b/content/html/content/src/HTMLImageElement.cpp
@@ -313,16 +313,59 @@ HTMLImageElement::AfterSetAttr(int32_t a
       aValue && !aValue->IsEmptyString()) {
     // add the image to the hashtable as needed
     NS_ABORT_IF_FALSE(aValue->Type() == nsAttrValue::eAtom,
       "Expected atom value for name/id");
     mForm->AddImageElementToTable(this,
       nsDependentAtomString(aValue->GetAtomValue()));
   }
 
+  if (aNameSpaceID == kNameSpaceID_None &&
+      aName == nsGkAtoms::src &&
+      !aValue) {
+    CancelImageRequests(aNotify);
+  }
+
+  // If we plan to call LoadImage, we want to do it first so that the image load
+  // kicks off. But if aNotify is false, we are coming from the parser or some
+  // such place; we'll get bound after all the attributes have been set, so
+  // we'll do the image load from BindToTree. Skip the LoadImage call in that case.
+  if (aNotify &&
+      aNameSpaceID == kNameSpaceID_None &&
+      aName == nsGkAtoms::crossorigin) {
+    // We want aForce == true in this LoadImage call, because we want to force
+    // a new load of the image with the new cross origin policy.
+    nsAutoString uri;
+    GetAttr(kNameSpaceID_None, nsGkAtoms::src, uri);
+    LoadImage(uri, true, aNotify);
+  }
+
+  if (aNotify &&
+      aNameSpaceID == kNameSpaceID_None &&
+      aName == nsGkAtoms::src &&
+      aValue) {
+
+    // Prevent setting image.src by exiting early
+    if (nsContentUtils::IsImageSrcSetDisabled()) {
+      return NS_OK;
+    }
+
+    // A hack to get animations to reset. See bug 594771.
+    mNewRequestsWillNeedAnimationReset = true;
+
+    // Force image loading here, so that we'll try to load the image from
+    // network if it's set to be not cacheable...  If we change things so that
+    // the state gets in Element's attr-setting happen around this
+    // LoadImage call, we could start passing false instead of aNotify
+    // here.
+    LoadImage(aValue->GetStringValue(), true, aNotify);
+
+    mNewRequestsWillNeedAnimationReset = false;
+  }
+
   return nsGenericHTMLElement::AfterSetAttr(aNameSpaceID, aName,
                                             aValue, aNotify);
 }
 
 
 nsresult
 HTMLImageElement::PreHandleEvent(nsEventChainPreVisitor& aVisitor)
 {
@@ -382,54 +425,24 @@ HTMLImageElement::IsHTMLFocusable(bool a
   return false;
 }
 
 nsresult
 HTMLImageElement::SetAttr(int32_t aNameSpaceID, nsIAtom* aName,
                           nsIAtom* aPrefix, const nsAString& aValue,
                           bool aNotify)
 {
-  // If we plan to call LoadImage, we want to do it first so that the
-  // image load kicks off _before_ the reflow triggered by the SetAttr.  But if
-  // aNotify is false, we are coming from the parser or some such place; we'll
-  // get bound after all the attributes have been set, so we'll do the
-  // image load from BindToTree.  Skip the LoadImage call in that case.
-  if (aNotify &&
-      aNameSpaceID == kNameSpaceID_None && aName == nsGkAtoms::src) {
-
-    // Prevent setting image.src by exiting early
-    if (nsContentUtils::IsImageSrcSetDisabled()) {
-      return NS_OK;
-    }
-
-    // A hack to get animations to reset. See bug 594771.
-    mNewRequestsWillNeedAnimationReset = true;
-
-    // Force image loading here, so that we'll try to load the image from
-    // network if it's set to be not cacheable...  If we change things so that
-    // the state gets in Element's attr-setting happen around this
-    // LoadImage call, we could start passing false instead of aNotify
-    // here.
-    LoadImage(aValue, true, aNotify);
-
-    mNewRequestsWillNeedAnimationReset = false;
-  }
-    
   return nsGenericHTMLElement::SetAttr(aNameSpaceID, aName, aPrefix, aValue,
                                        aNotify);
 }
 
 nsresult
 HTMLImageElement::UnsetAttr(int32_t aNameSpaceID, nsIAtom* aAttribute,
                             bool aNotify)
 {
-  if (aNameSpaceID == kNameSpaceID_None && aAttribute == nsGkAtoms::src) {
-    CancelImageRequests(aNotify);
-  }
-
   return nsGenericHTMLElement::UnsetAttr(aNameSpaceID, aAttribute, aNotify);
 }
 
 nsresult
 HTMLImageElement::BindToTree(nsIDocument* aDocument, nsIContent* aParent,
                              nsIContent* aBindingParent,
                              bool aCompileEventHandlers)
 {
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..df24ac6d3404325e473981930ade85065cf7fb9a
GIT binary patch
literal 844
zc$@)D1GD^zP)<h;3K|Lk000e1NJLTq000mG000mO1^@s6AM^iV00004b3#c}2nYxW
zd<bNS00009a7bBm000j<000lL0ajJ30{{R5?ny*JR5*=wlU-<Abr{Bf|C4iak|t@k
znyz1_UD|b9CpwyStJbl)wOETfHyJ}l1+P@RQUvu%@X{{?1uq7I;FT95IyVX`Q#a>W
zH*l4W#u<{PNz9VwG#}^W<0L1?t5qG#bM^8*@B6!Y9%v)~sZWR7dH<ET*YfDQ-@UD+
zw7tRIec8-L-Mt*iY#7<fwOXnA4VT_5w*{yN-Ve=&dp<aHa{PEAtBZKDNbK(-ZdJzT
zQE|zVCdrO>&b>bO@tq&Xo#Dw37Y`VD<Kh#CN5=CNOJw5(mJ@jtVdL&l@%vOP8+RtJ
z&-?ctbLE%5`f(HR;<r~jN?H9E>*5zZgOd|P&R*cpRtL#MfnqdAF}{lF@u3x}h-M2d
zU7YIQ_0*!aayBIc)N=ZX)vMQouRK=b_uDDdE|ux^&sgX-sRT#)>9+`tv>+u9Av<NN
zH&!Lt?|m7#A_FWft?lnDrFrzFXYnVh40Oei?E%6Er;(c#UOh3uYp1VZ$RV^?8d?IO
zDEj~*0VGy(s>c)Hp(D?+Cny*kpJ8n71zf|E=pEaMtqb<=?8Ppd$Yvc+rx&+J-U2uz
z01;V>&4(3AT8;+~%~LWAvbi!#=YJ*{T_H3YWP0WZTfGgoZNHzEaIlfcn1GN0gvI&w
zN*BH@U5I9l(LEzH^a4Bj2BEHF*LCd5I_~5-jNVg74nf&4Qh?<EFpbN})LQ@3xyYIR
zPFdqVpMu9JgK1#b%Gh-smzibpQk|8wO3N~-=l=MzS&e?b86;Qt!jxiGerS~A%I*=R
z@yu+m{`kRAU~H&cxUnde8-y2rWyAE+vdmhoa`|B>T>oDZ72o0K<(7D_Y2>a+IG1f<
z1;P(F$7ZLt?Xv8?z$c&I5RxR>Mm_V9#b0j#*4<qY;N0P0I3(fi5l8`OIrdGA%|vgd
z<`k!+naSNcZ4rM9(A$>jU)YfP$i(Ean>QmzT`s3}TZ?`T+8Lm6&oZ?KZQix+Hva+S
WQ#UA?9#7r?0000<MNUMnLSTYXW|E5l
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/image-allow-credentials.png^headers^
@@ -0,0 +1,2 @@
+Access-Control-Allow-Origin: http://mochi.test:8888
+Access-Control-Allow-Credentials: true
--- a/content/html/content/test/mochitest.ini
+++ b/content/html/content/test/mochitest.ini
@@ -122,16 +122,18 @@ support-files =
   file_iframe_sandbox_top_navigation_fail.html
   file_iframe_sandbox_top_navigation_pass.html
   file_iframe_sandbox_window_navigation_fail.html
   file_iframe_sandbox_worker.js
   file_srcdoc-2.html
   file_srcdoc.html
   form_submit_server.sjs
   image.png
+  image-allow-credentials.png
+  image-allow-credentials.png^headers^
   nnc_lockup.gif
   reflect.js
   wakelock.ogg
   wakelock.ogv
 
 [test_a_text.html]
 [test_anchor_href_cache_invalidation.html]
 [test_applet_attributes_reflection.html]
@@ -338,16 +340,17 @@ support-files =
 [test_bug840877.html]
 [test_bug841466.html]
 [test_bug869040.html]
 [test_bug870787.html]
 [test_bug874758.html]
 [test_bug879319.html]
 [test_bug885024.html]
 [test_bug893537.html]
+[test_change_crossorigin.html]
 [test_checked.html]
 [test_dir_attributes_reflection.html]
 [test_dl_attributes_reflection.html]
 [test_element_prototype.html]
 [test_embed_attributes_reflection.html]
 [test_formData.html]
 [test_formSubmission.html]
 [test_formSubmission2.html]
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_change_crossorigin.html
@@ -0,0 +1,89 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=696451
+-->
+<head>
+  <meta charset="utf-8">
+  <title>Test for Bug 696451</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript">
+
+  /** Test for Bug 696451 **/
+
+  SimpleTest.waitForExplicitFinish();
+
+  var img = new Image,
+      canvas = document.createElement("canvas"),
+      ctx = canvas.getContext("2d"),
+      src = "http://example.com/tests/content/html/content/test/image-allow-credentials.png",
+      imgDone = false,
+      imgNotAllowedToLoadDone = false;
+
+  img.src = src;
+  img.crossOrigin = "Anonymous";
+
+  img.addEventListener("load", function() {
+    canvas.width = img.width;
+    canvas.height = img.height;
+    ctx.drawImage( img, 0, 0 );
+    try {
+      canvas.toDataURL("image/png");
+      ok(true, "Image was refetched with setting crossOrigin.");
+    } catch (e) {
+      ok(false, "Image was not refetched after setting crossOrigin.");
+    }
+
+    imgDone = true;
+    if (imgDone && imgNotAllowedToLoadDone) {
+      SimpleTest.finish();
+    }
+  });
+
+  img.addEventListener("error", function (event) {
+    ok(false, "Should be able to load cross origin image with proper headers.");
+
+    imgDone = true;
+    if (imgDone && imgNotAllowedToLoadDone) {
+      SimpleTest.finish();
+    }
+  });
+
+  var imgNotAllowedToLoad = new Image;
+
+  imgNotAllowedToLoad.src = "http://example.com/tests/content/html/content/test/image.png";
+
+  imgNotAllowedToLoad.crossOrigin = "Anonymous";
+
+  imgNotAllowedToLoad.addEventListener("load", function() {
+      ok(false, "Image should not be allowed to load without " +
+                "allow-cross-origin-access headers.");
+
+      imgNotAllowedToLoadDone = true;
+      if (imgDone && imgNotAllowedToLoadDone) {
+        SimpleTest.finish();
+      }
+  });
+
+  imgNotAllowedToLoad.addEventListener("error", function() {
+      ok(true, "Image should not be allowed to load without " +
+               "allow-cross-origin-access headers.");
+      imgNotAllowedToLoadDone = true;
+      if (imgDone && imgNotAllowedToLoadDone) {
+        SimpleTest.finish();
+      }
+  });
+
+  </script>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=696451">Mozilla Bug 696451</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+
+</div>
+<pre id="test">
+</pre>
+</body>
+</html>
--- a/docshell/base/nsAboutRedirector.cpp
+++ b/docshell/base/nsAboutRedirector.cpp
@@ -45,17 +45,18 @@ static RedirEntry kRedirMap[] = {
       nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT },
     { "license", "chrome://global/content/license.html",
       nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT },
     { "neterror", "chrome://global/content/netError.xhtml",
       nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT |
       nsIAboutModule::ALLOW_SCRIPT |
       nsIAboutModule::HIDE_FROM_ABOUTABOUT },
     { "compartments", "chrome://global/content/aboutCompartments.xhtml",
-      nsIAboutModule::ALLOW_SCRIPT },
+      nsIAboutModule::ALLOW_SCRIPT |
+      nsIAboutModule::HIDE_FROM_ABOUTABOUT },
     { "memory", "chrome://global/content/aboutMemory.xhtml",
       nsIAboutModule::ALLOW_SCRIPT },
     { "addons", "chrome://mozapps/content/extensions/extensions.xul",
       nsIAboutModule::ALLOW_SCRIPT },
     { "newaddon", "chrome://mozapps/content/extensions/newaddon.xul",
       nsIAboutModule::ALLOW_SCRIPT |
       nsIAboutModule::HIDE_FROM_ABOUTABOUT },
     { "support", "chrome://global/content/aboutSupport.xhtml",
--- a/dom/workers/ScriptLoader.cpp
+++ b/dom/workers/ScriptLoader.cpp
@@ -435,18 +435,20 @@ public:
       }
     }
 
     // May be null.
     nsIDocument* parentDoc = mWorkerPrivate->GetDocument();
 
     // Use the regular nsScriptLoader for this grunt work! Should be just fine
     // because we're running on the main thread.
+    // Unlike <script> tags, Worker scripts are always decoded as UTF-8,
+    // per spec. So we explicitly pass in the charset hint.
     rv = nsScriptLoader::ConvertToUTF16(aLoadInfo.mChannel, aString, aStringLen,
-                                        EmptyString(), parentDoc,
+                                        NS_LITERAL_STRING("UTF-8"), parentDoc,
                                         aLoadInfo.mScriptText);
     if (NS_FAILED(rv)) {
       return rv;
     }
 
     if (aLoadInfo.mScriptText.IsEmpty()) {
       return NS_ERROR_FAILURE;
     }
new file mode 100644
--- /dev/null
+++ b/dom/workers/test/loadEncoding_worker.js
@@ -0,0 +1,7 @@
+/*
+  Any copyright is dedicated to the Public Domain.
+  http://creativecommons.org/publicdomain/zero/1.0/
+*/
+// Bug 484305 - Load workers as UTF-8.
+postMessage({ encoding: "KOI8-R", text: "" });
+postMessage({ encoding: "UTF-8", text: "Привет" });
--- a/dom/workers/test/mochitest.ini
+++ b/dom/workers/test/mochitest.ini
@@ -15,16 +15,17 @@ support-files =
   fibonacci_worker.js
   importScripts_worker.js
   importScripts_worker_imported1.js
   importScripts_worker_imported2.js
   importScripts_worker_imported3.js
   importScripts_worker_imported4.js
   instanceof_worker.js
   json_worker.js
+  loadEncoding_worker.js
   location_worker.js
   longThread_worker.js
   multi_sharedWorker_frame.html
   multi_sharedWorker_sharedWorker.js
   navigator_worker.js
   newError_worker.js
   recursion_worker.js
   recursiveOnerror_worker.js
@@ -68,16 +69,17 @@ support-files =
 [test_dataURLWorker.html]
 [test_errorPropagation.html]
 [test_errorwarning.html]
 [test_eventDispatch.html]
 [test_fibonacci.html]
 [test_importScripts.html]
 [test_instanceof.html]
 [test_json.html]
+[test_loadEncoding.html]
 [test_loadError.html]
 [test_location.html]
 [test_longThread.html]
 [test_multi_sharedWorker.html]
 [test_multi_sharedWorker_lifetimes.html]
 [test_navigator.html]
 [test_newError.html]
 [test_recursion.html]
new file mode 100644
--- /dev/null
+++ b/dom/workers/test/test_loadEncoding.html
@@ -0,0 +1,50 @@
+<!--
+  Any copyright is dedicated to the Public Domain.
+  http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Bug 484305 - Load workers as UTF-8</title>
+  <meta http-equiv="content-type" content="text/html; charset=KOI8-R">
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=484305">Bug 484305 - Load workers as UTF-8</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+
+SimpleTest.waitForExplicitFinish();
+
+var canonical = String.fromCharCode(0x41F, 0x440, 0x438, 0x432, 0x435, 0x442);
+ok(document.inputEncoding === "KOI8-R", "Document encoding is KOI8-R");
+
+// Worker sends two strings, one with `canonical` encoded in KOI8-R and one as UTF-8.
+// Since Worker scripts should always be decoded using UTF-8, even if the owning document's charset is different, the UTF-8 decode should match, while KOI8-R should fail.
+var counter = 0;
+var worker = new Worker("loadEncoding_worker.js");
+worker.onmessage = function(e) {
+  if (e.data.encoding === "KOI8-R") {
+    ok(e.data.text !== canonical, "KOI8-R decoded text should not match");
+  } else if (e.data.encoding === "UTF-8") {
+    ok(e.data.text === canonical, "UTF-8 decoded text should match");
+  }
+  counter++;
+  if (counter === 2)
+    SimpleTest.finish();
+}
+
+worker.onerror = function(e) {
+  ok(false, "Worker error");
+  SimpleTest.finish();
+}
+</script>
+
+</pre>
+</body>
+</html>
--- a/embedding/components/find/src/nsWebBrowserFind.cpp
+++ b/embedding/components/find/src/nsWebBrowserFind.cpp
@@ -40,22 +40,16 @@
 #include "mozilla/dom/Element.h"
 #include "nsISimpleEnumerator.h"
 
 #if DEBUG
 #include "nsIWebNavigation.h"
 #include "nsXPIDLString.h"
 #endif
 
-#if defined(XP_MACOSX) && !defined(__LP64__)
-#include "nsAutoPtr.h"
-#include <Carbon/Carbon.h>
-#endif
-
-
 //*****************************************************************************
 // nsWebBrowserFind
 //*****************************************************************************
 
 nsWebBrowserFind::nsWebBrowserFind() :
     mFindBackwards(false),
     mWrapFind(false),
     mEntireWord(false),
@@ -239,51 +233,23 @@ NS_IMETHODIMP nsWebBrowserFind::FindNext
     return rv;
 }
 
 
 /* attribute wstring searchString; */
 NS_IMETHODIMP nsWebBrowserFind::GetSearchString(PRUnichar * *aSearchString)
 {
     NS_ENSURE_ARG_POINTER(aSearchString);
-#if defined(XP_MACOSX) && !defined(__LP64__)
-    OSStatus err;
-    ScrapRef scrap;
-    err = ::GetScrapByName(kScrapFindScrap, kScrapGetNamedScrap, &scrap);
-    if (err == noErr) {
-        Size byteCount;
-        err = ::GetScrapFlavorSize(scrap, kScrapFlavorTypeUnicode, &byteCount);
-        if (err == noErr) {
-            NS_ASSERTION(byteCount%2 == 0, "byteCount not a multiple of 2");
-            nsAutoArrayPtr<PRUnichar> buffer(new PRUnichar[byteCount/2 + 1]);
-            NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY);
-            err = ::GetScrapFlavorData(scrap, kScrapFlavorTypeUnicode, &byteCount, buffer.get());
-            if (err == noErr) {
-                buffer[byteCount/2] = PRUnichar('\0');
-                mSearchString.Assign(buffer);
-            }
-        }
-    }    
-#endif
     *aSearchString = ToNewUnicode(mSearchString);
     return NS_OK;
 }
 
 NS_IMETHODIMP nsWebBrowserFind::SetSearchString(const PRUnichar * aSearchString)
 {
     mSearchString.Assign(aSearchString);
-#if defined(XP_MACOSX) && !defined(__LP64__)
-    OSStatus err;
-    ScrapRef scrap;
-    err = ::GetScrapByName(kScrapFindScrap, kScrapClearNamedScrap, &scrap);
-    if (err == noErr) {
-        ::PutScrapFlavor(scrap, kScrapFlavorTypeUnicode, kScrapFlavorMaskNone,
-        (mSearchString.Length()*2), aSearchString);
-    }
-#endif
     return NS_OK;
 }
 
 /* attribute boolean findBackwards; */
 NS_IMETHODIMP nsWebBrowserFind::GetFindBackwards(bool *aFindBackwards)
 {
     NS_ENSURE_ARG_POINTER(aFindBackwards);
     *aFindBackwards = mFindBackwards;
--- a/extensions/auth/nsAuthGSSAPI.cpp
+++ b/extensions/auth/nsAuthGSSAPI.cpp
@@ -353,18 +353,18 @@ nsAuthGSSAPI::Init(const char *serviceNa
        return NS_ERROR_NOT_INITIALIZED;
 
     mServiceName = serviceName;
     mServiceFlags = serviceFlags;
 
     static bool sTelemetrySent = false;
     if (!sTelemetrySent) {
         mozilla::Telemetry::Accumulate(
-            mozilla::Telemetry::NTLM_MODULE_USED,
-            serviceFlags | nsIAuthModule::REQ_PROXY_AUTH
+            mozilla::Telemetry::NTLM_MODULE_USED_2,
+            serviceFlags & nsIAuthModule::REQ_PROXY_AUTH
                 ? NTLM_MODULE_KERBEROS_PROXY
                 : NTLM_MODULE_KERBEROS_DIRECT);
         sTelemetrySent = true;
     }
 
     return NS_OK;
 }
 
--- a/extensions/auth/nsAuthSSPI.cpp
+++ b/extensions/auth/nsAuthSSPI.cpp
@@ -273,18 +273,18 @@ nsAuthSSPI::Init(const char *serviceName
                                            &mCred,
                                            &useBefore);
     if (rc != SEC_E_OK)
         return NS_ERROR_UNEXPECTED;
 
     static bool sTelemetrySent = false;
     if (!sTelemetrySent) {
         mozilla::Telemetry::Accumulate(
-            mozilla::Telemetry::NTLM_MODULE_USED,
-            serviceFlags | nsIAuthModule::REQ_PROXY_AUTH
+            mozilla::Telemetry::NTLM_MODULE_USED_2,
+            serviceFlags & nsIAuthModule::REQ_PROXY_AUTH
                 ? NTLM_MODULE_WIN_API_PROXY
                 : NTLM_MODULE_WIN_API_DIRECT);
         sTelemetrySent = true;
     }
 
     LOG(("AcquireCredentialsHandle() succeeded.\n"));
     return NS_OK;
 }
--- a/extensions/auth/nsAuthSambaNTLM.cpp
+++ b/extensions/auth/nsAuthSambaNTLM.cpp
@@ -210,18 +210,18 @@ nsAuthSambaNTLM::Init(const char *servic
                       const PRUnichar *username,
                       const PRUnichar *password)
 {
     NS_ASSERTION(!username && !domain && !password, "unexpected credentials");
 
     static bool sTelemetrySent = false;
     if (!sTelemetrySent) {
         mozilla::Telemetry::Accumulate(
-            mozilla::Telemetry::NTLM_MODULE_USED,
-            serviceFlags | nsIAuthModule::REQ_PROXY_AUTH
+            mozilla::Telemetry::NTLM_MODULE_USED_2,
+            serviceFlags & nsIAuthModule::REQ_PROXY_AUTH
                 ? NTLM_MODULE_SAMBA_AUTH_PROXY
                 : NTLM_MODULE_SAMBA_AUTH_DIRECT);
         sTelemetrySent = true;
     }
 
     return NS_OK;
 }
 
--- a/gfx/layers/Compositor.cpp
+++ b/gfx/layers/Compositor.cpp
@@ -34,35 +34,43 @@ Compositor::AssertOnCompositorThread()
 
 void
 Compositor::DrawDiagnostics(DiagnosticFlags aFlags,
                             const gfx::Rect& rect,
                             const gfx::Rect& aClipRect,
                             const gfx::Matrix4x4& aTransform,
                             const gfx::Point& aOffset)
 {
-  if (!(mDiagnosticTypes & DIAGNOSTIC_TILE_BORDERS) && (aFlags & DIAGNOSTIC_TILE)) {
+  if ((aFlags & DIAGNOSTIC_TILE) && !(mDiagnosticTypes & DIAGNOSTIC_TILE_BORDERS)) {
+    return;
+  }
+  if ((aFlags & DIAGNOSTIC_BIGIMAGE) && !(mDiagnosticTypes & DIAGNOSTIC_BIGIMAGE_BORDERS)) {
+    return;
+  }
+  if (!mDiagnosticTypes) {
     return;
   }
 
-  if (!(mDiagnosticTypes & DIAGNOSTIC_LAYER_BORDERS)) {
-    return;
-  }
-
+#ifdef MOZ_B2G
+  int lWidth = 4;
+#elif defined(ANDROID)
+  int lWidth = 10;
+#else
   int lWidth = 2;
+#endif
   float opacity = 0.7;
 
   gfx::Color color;
   if (aFlags & DIAGNOSTIC_CONTENT) {
     color = gfx::Color(0.0, 1.0, 0.0, 1.0); // green
     if (aFlags & DIAGNOSTIC_COMPONENT_ALPHA) {
       color = gfx::Color(0.0, 1.0, 1.0, 1.0); // greenish blue
     }
   } else if (aFlags & DIAGNOSTIC_IMAGE) {
-    color = gfx::Color(0.5, 0.0, 0.0, 1.0); // red
+    color = gfx::Color(1.0, 0.0, 0.0, 1.0); // red
   } else if (aFlags & DIAGNOSTIC_COLOR) {
     color = gfx::Color(0.0, 0.0, 1.0, 1.0); // blue
   } else if (aFlags & DIAGNOSTIC_CONTAINER) {
     color = gfx::Color(0.8, 0.0, 0.8, 1.0); // purple
   }
 
   // make tile borders a bit more transparent to keep layer borders readable.
   if (aFlags & DIAGNOSTIC_TILE || aFlags & DIAGNOSTIC_BIGIMAGE) {
--- a/gfx/layers/client/ClientLayerManager.cpp
+++ b/gfx/layers/client/ClientLayerManager.cpp
@@ -160,16 +160,17 @@ ClientLayerManager::EndTransactionIntern
                                            void* aCallbackData,
                                            EndTransactionFlags)
 {
   PROFILER_LABEL("ClientLayerManager", "EndTransactionInternal");
 #ifdef MOZ_LAYERS_HAVE_LOG
   MOZ_LAYERS_LOG(("  ----- (beginning paint)"));
   Log();
 #endif
+  profiler_tracing("Paint", "Rasterize", TRACING_INTERVAL_START);
 
   NS_ASSERTION(InConstruction(), "Should be in construction phase");
   mPhase = PHASE_DRAWING;
 
   ClientLayer* root = ClientLayer::ToClientLayer(GetRoot());
 
   mTransactionIncomplete = false;
       
--- a/gfx/layers/d3d10/ContainerLayerD3D10.cpp
+++ b/gfx/layers/d3d10/ContainerLayerD3D10.cpp
@@ -1,19 +1,15 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ContainerLayerD3D10.h"
-#include "nsAlgorithm.h"
-#include "gfxUtils.h"
-#include "nsRect.h"
 
-#include "../d3d9/Nv3DVUtils.h"
 #include "ThebesLayerD3D10.h"
 #include "ReadbackProcessor.h"
 
 namespace mozilla {
 namespace layers {
 
 ContainerLayerD3D10::ContainerLayerD3D10(LayerManagerD3D10 *aManager)
   : ContainerLayer(aManager, nullptr)
--- a/gfx/layers/d3d9/ContainerLayerD3D9.cpp
+++ b/gfx/layers/d3d9/ContainerLayerD3D9.cpp
@@ -1,16 +1,15 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ContainerLayerD3D9.h"
-#include "gfxUtils.h"
-#include "nsRect.h"
+
 #include "ThebesLayerD3D9.h"
 #include "ReadbackProcessor.h"
 
 namespace mozilla {
 namespace layers {
 
 ContainerLayerD3D9::ContainerLayerD3D9(LayerManagerD3D9 *aManager)
   : ContainerLayer(aManager, nullptr)
--- a/gfx/layers/ipc/CompositorChild.cpp
+++ b/gfx/layers/ipc/CompositorChild.cpp
@@ -96,19 +96,25 @@ CompositorChild::DeallocPLayerTransactio
   return true;
 }
 
 void
 CompositorChild::ActorDestroy(ActorDestroyReason aWhy)
 {
   MOZ_ASSERT(sCompositor == this);
 
+#ifdef MOZ_B2G
+  // Due to poor lifetime management of gralloc (and possibly shmems) we will
+  // crash at some point in the future when we get destroyed due to abnormal
+  // shutdown. Its better just to crash here. On desktop though, we have a chance
+  // of recovering.
   if (aWhy == AbnormalShutdown) {
     NS_RUNTIMEABORT("ActorDestroy by IPC channel failure at CompositorChild");
   }
+#endif
 
   sCompositor = nullptr;
   // We don't want to release the ref to sCompositor here, during
   // cleanup, because that will cause it to be deleted while it's
   // still being used.  So defer the deletion to after it's not in
   // use.
   MessageLoop::current()->PostTask(
     FROM_HERE,
--- a/gfx/layers/ipc/CompositorParent.cpp
+++ b/gfx/layers/ipc/CompositorParent.cpp
@@ -542,16 +542,17 @@ CompositorParent::Composite()
   mLayerManager->EndEmptyTransaction();
 
 #ifdef COMPOSITOR_PERFORMANCE_WARNING
   if (mExpectedComposeTime + TimeDuration::FromMilliseconds(15) < TimeStamp::Now()) {
     printf_stderr("Compositor: Composite took %i ms.\n",
                   15 + (int)(TimeStamp::Now() - mExpectedComposeTime).ToMilliseconds());
   }
 #endif
+  profiler_tracing("Paint", "Composite", TRACING_INTERVAL_END);
 }
 
 void
 CompositorParent::ComposeToTarget(DrawTarget* aTarget)
 {
   PROFILER_LABEL("CompositorParent", "ComposeToTarget");
   AutoRestore<bool> override(mOverrideComposeReadiness);
   mOverrideComposeReadiness = true;
--- a/gfx/layers/ipc/LayerTransactionChild.cpp
+++ b/gfx/layers/ipc/LayerTransactionChild.cpp
@@ -80,15 +80,21 @@ LayerTransactionChild::DeallocPComposita
 {
   delete actor;
   return true;
 }
 
 void
 LayerTransactionChild::ActorDestroy(ActorDestroyReason why)
 {
+#ifdef MOZ_B2G
+  // Due to poor lifetime management of gralloc (and possibly shmems) we will
+  // crash at some point in the future when we get destroyed due to abnormal
+  // shutdown. Its better just to crash here. On desktop though, we have a chance
+  // of recovering.
   if (why == AbnormalShutdown) {
     NS_RUNTIMEABORT("ActorDestroy by IPC channel failure at LayerTransactionChild");
   }
+#endif
 }
 
 }  // namespace layers
 }  // namespace mozilla
--- a/gfx/layers/ipc/LayerTransactionParent.cpp
+++ b/gfx/layers/ipc/LayerTransactionParent.cpp
@@ -182,16 +182,17 @@ LayerTransactionParent::RecvUpdateNoSwap
 }
 
 bool
 LayerTransactionParent::RecvUpdate(const InfallibleTArray<Edit>& cset,
                                    const TargetConfig& targetConfig,
                                    const bool& isFirstPaint,
                                    InfallibleTArray<EditReply>* reply)
 {
+  profiler_tracing("Paint", "Composite", TRACING_INTERVAL_START);
   PROFILER_LABEL("LayerTransactionParent", "RecvUpdate");
 #ifdef COMPOSITOR_PERFORMANCE_WARNING
   TimeStamp updateStart = TimeStamp::Now();
 #endif
 
   MOZ_LAYERS_LOG(("[ParentSide] received txn with %d edits", cset.Length()));
 
   if (mDestroyed || !layer_manager() || layer_manager()->IsDestroyed()) {
--- a/gfx/layers/ipc/ShadowLayers.cpp
+++ b/gfx/layers/ipc/ShadowLayers.cpp
@@ -534,16 +534,17 @@ ShadowLayerForwarder::EndTransaction(Inf
 
   mWindowOverlayChanged = false;
 
   TargetConfig targetConfig(mTxn->mTargetBounds, mTxn->mTargetRotation, mTxn->mClientBounds, mTxn->mTargetOrientation);
 
   MOZ_LAYERS_LOG(("[LayersForwarder] syncing before send..."));
   PlatformSyncBeforeUpdate();
 
+  profiler_tracing("Paint", "Rasterize", TRACING_INTERVAL_END);
   if (mTxn->mSwapRequired) {
     MOZ_LAYERS_LOG(("[LayersForwarder] sending transaction..."));
     RenderTraceScope rendertrace3("Forward Transaction", "000093");
     if (!mShadowManager->SendUpdate(cset, targetConfig, mIsFirstPaint,
                                     aReplies)) {
       MOZ_LAYERS_LOG(("[LayersForwarder] WARNING: sending transaction failed!"));
       return false;
     }
--- a/gfx/thebes/gfxCoreTextShaper.cpp
+++ b/gfx/thebes/gfxCoreTextShaper.cpp
@@ -83,25 +83,25 @@ gfxCoreTextShaper::ShapeText(gfxContext 
         startOffset = isRightToLeft ?
             mozilla::ArrayLength(beginRTL) : mozilla::ArrayLength(beginLTR);
         CFMutableStringRef mutableString =
             ::CFStringCreateMutable(kCFAllocatorDefault,
                                     length + startOffset + mozilla::ArrayLength(endBidiWrap));
         ::CFStringAppendCharacters(mutableString,
                                    isRightToLeft ? beginRTL : beginLTR,
                                    startOffset);
-        ::CFStringAppendCharacters(mutableString, aText, length);
+        ::CFStringAppendCharacters(mutableString, reinterpret_cast<const UniChar*>(aText), length);
         ::CFStringAppendCharacters(mutableString,
                                    endBidiWrap, mozilla::ArrayLength(endBidiWrap));
         stringObj = mutableString;
     } else {
         startOffset = 0;
         stringObj = ::CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
-                                                         aText, length,
-                                                         kCFAllocatorNull);
+                                                         reinterpret_cast<const UniChar*>(aText),
+                                                         length, kCFAllocatorNull);
     }
 
     CFDictionaryRef attrObj;
     if (aShapedText->DisableLigatures()) {
         // For letterspacing (or maybe other situations) we need to make a copy of the CTFont
         // with the ligature feature disabled
         CTFontRef ctFont =
             CreateCTFontWithDisabledLigatures(::CTFontGetSize(mCTFont));
--- a/gfx/thebes/gfxMacPlatformFontList.mm
+++ b/gfx/thebes/gfxMacPlatformFontList.mm
@@ -118,23 +118,23 @@ static const int gAppleWeightToCSSWeight
 };
 
 // cache Cocoa's "shared font manager" for performance
 static NSFontManager *sFontManager;
 
 static void GetStringForNSString(const NSString *aSrc, nsAString& aDist)
 {
     aDist.SetLength([aSrc length]);
-    [aSrc getCharacters:aDist.BeginWriting()];
+    [aSrc getCharacters:reinterpret_cast<unichar*>(aDist.BeginWriting())];
 }
 
 static NSString* GetNSStringForString(const nsAString& aSrc)
 {
-    return [NSString stringWithCharacters:aSrc.BeginReading()
-                     length:aSrc.Length()];
+    return [NSString stringWithCharacters:reinterpret_cast<const unichar*>(aSrc.BeginReading())
+                                   length:aSrc.Length()];
 }
 
 #ifdef PR_LOGGING
 
 #define LOG_FONTLIST(args) PR_LOG(gfxPlatform::GetLog(eGfxLog_fontlist), \
                                PR_LOG_DEBUG, args)
 #define LOG_FONTLIST_ENABLED() PR_LOG_TEST( \
                                    gfxPlatform::GetLog(eGfxLog_fontlist), \
@@ -882,17 +882,17 @@ gfxMacPlatformFontList::GlobalFontFallba
                               kCFCompareCaseInsensitive) != kCFCompareEqualTo)
         {
             nsAutoTArray<UniChar, 1024> buffer;
             CFIndex len = ::CFStringGetLength(familyName);
             buffer.SetLength(len+1);
             ::CFStringGetCharacters(familyName, ::CFRangeMake(0, len),
                                     buffer.Elements());
             buffer[len] = 0;
-            nsDependentString familyName(buffer.Elements(), len);
+            nsDependentString familyName(reinterpret_cast<PRUnichar*>(buffer.Elements()), len);
 
             bool needsBold;  // ignored in the system fallback case
 
             gfxFontFamily *family = FindFamily(familyName);
             if (family) {
                 fontEntry = family->FindFontForStyle(*aMatchStyle, needsBold);
                 if (fontEntry) {
                     if (fontEntry->TestCharacterMap(aCh)) {
--- a/intl/locale/src/mac/nsDateTimeFormatMac.cpp
+++ b/intl/locale/src/mac/nsDateTimeFormatMac.cpp
@@ -109,17 +109,17 @@ nsresult nsDateTimeFormatMac::FormatTMTi
   NS_ASSERTION(tmTime->tm_wday >= 0, "tm is not set correctly");
 
   // Got the locale for the formatter:
   CFLocaleRef formatterLocale;
   if (!locale) {
     formatterLocale = CFLocaleCopyCurrent();
   } else {
     CFStringRef localeStr = CFStringCreateWithCharacters(nullptr,
-                                                         mLocale.get(),
+                                                         reinterpret_cast<const UniChar*>(mLocale.get()),
                                                          mLocale.Length());
     formatterLocale = CFLocaleCreate(nullptr, localeStr);
     CFRelease(localeStr);
   }
 
   // Get the date style for the formatter:  
   CFDateFormatterStyle dateStyle;
   switch (dateFormatSelector) {
@@ -216,17 +216,17 @@ nsresult nsDateTimeFormatMac::FormatTMTi
                                                                           formatter,
                                                                           absTime);
   
   CFIndex stringLen = CFStringGetLength(formattedDate);
   
   nsAutoTArray<UniChar, 256> stringBuffer;
   if (stringBuffer.SetLength(stringLen + 1)) {
     CFStringGetCharacters(formattedDate, CFRangeMake(0, stringLen), stringBuffer.Elements());
-    stringOut.Assign(stringBuffer.Elements(), stringLen);
+    stringOut.Assign(reinterpret_cast<PRUnichar*>(stringBuffer.Elements()), stringLen);
   }
   
   CFRelease(formattedDate);
   CFRelease(formatter);
   
   return res;
 }
 
--- a/intl/locale/src/nsLocaleService.cpp
+++ b/intl/locale/src/nsLocaleService.cpp
@@ -225,17 +225,17 @@ nsLocaleService::nsLocaleService(void)
     int size = ::CFStringGetLength(userLocaleStr);
     if (buffer.SetLength(size + 1))
     {
         CFRange range = ::CFRangeMake(0, size);
         ::CFStringGetCharacters(userLocaleStr, range, buffer.Elements());
         buffer[size] = 0;
 
         // Convert the locale string to the format that Mozilla expects
-        nsAutoString xpLocale(buffer.Elements());
+        nsAutoString xpLocale(reinterpret_cast<PRUnichar*>(buffer.Elements()));
         xpLocale.ReplaceChar('_', '-');
 
         nsresult rv = NewLocale(xpLocale, getter_AddRefs(mSystemLocale));
         if (NS_SUCCEEDED(rv)) {
             mApplicationLocale = mSystemLocale;
         }
     }
 
--- a/intl/lwbrk/src/nsCarbonBreaker.cpp
+++ b/intl/lwbrk/src/nsCarbonBreaker.cpp
@@ -27,17 +27,17 @@ NS_GetComplexLineBreaks(const PRUnichar*
      
   for (UniCharArrayOffset position = 0; position < aLength;) {
     UniCharArrayOffset offset;
     status = UCFindTextBreak(breakLocator, 
                   kUCTextBreakLineMask, 
                   position == 0 ? kUCTextBreakLeadingEdgeMask : 
                                   (kUCTextBreakLeadingEdgeMask | 
                                    kUCTextBreakIterateMask),
-                  aText, 
+                  reinterpret_cast<const UniChar*>(aText),
                   aLength, 
                   position, 
                   &offset);
     if (status != noErr || offset >= aLength)
       break;        
     aBreakBefore[offset] = true;
     position = offset;
   }
--- a/ipc/ipdl/ipdl/lower.py
+++ b/ipc/ipdl/ipdl/lower.py
@@ -3724,22 +3724,25 @@ class _GenerateProtocolActorCode(ipdl.as
             _runtimeAbort('Clone() for ' +
                           p.name +
                           ' has not yet been implemented'),
             StmtReturn(ExprLiteral.NULL)
         ])
 
         othervar = ExprVar('other')
         managertype = Type(_actorName(p.name, self.side), ptr=1)
-        otherstmt = StmtDecl(Decl(managertype,
-                                  othervar.name),
-                             init=ExprCast(sourcevar,
-                                           managertype,
-                                           static=1))
-        clonemanagees.addstmt(otherstmt)
+
+        if len(p.managesStmts):
+            otherstmt = StmtDecl(Decl(managertype,
+                                      othervar.name),
+                                 init=ExprCast(sourcevar,
+                                               managertype,
+                                               static=1))
+            clonemanagees.addstmt(otherstmt)
+
         actorvar = ExprVar('actor')
         for managee in p.managesStmts:
             block = StmtBlock()
             manageeipdltype = managee.decl.type
             actortype = ipdl.type.ActorType(manageeipdltype)
             manageecxxtype = _cxxBareType(actortype, self.side)
             manageearray = p.managedVar(manageeipdltype, self.side)
             abortstmt = StmtIf(ExprBinary(actorvar, '==', ExprLiteral.NULL))
--- a/ipc/ipdl/moz.build
+++ b/ipc/ipdl/moz.build
@@ -4,14 +4,16 @@
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 if CONFIG['MOZ_IPDL_TESTS']:
     DIRS += ['test']
 
 MODULE = 'ipdlgen'
 
+FAIL_ON_WARNINGS = True
+
 LIBXUL_LIBRARY = True
 
 LIBRARY_NAME = 'mozipdlgen_s'
 
 EXPORT_LIBRARY = True
 
--- a/js/src/builtin/Object.cpp
+++ b/js/src/builtin/Object.cpp
@@ -479,17 +479,17 @@ obj_lookupSetter(JSContext *cx, unsigned
                 args.rval().set(shape->setterValue());
         }
     }
     return true;
 }
 #endif /* JS_OLD_GETTER_SETTER_METHODS */
 
 /* ES5 15.2.3.2. */
-bool
+static bool
 obj_getPrototypeOf(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     /* Step 1. */
     if (args.length() == 0) {
         js_ReportMissingArg(cx, args.calleev(), 0);
         return false;
--- a/js/src/builtin/TypedObject.cpp
+++ b/js/src/builtin/TypedObject.cpp
@@ -315,17 +315,17 @@ TypeEquivalent(JSContext *cx, unsigned i
     nullptr                                                                   \
 },
 
 const Class js::NumericTypeClasses[ScalarTypeRepresentation::TYPE_MAX] = {
     JS_FOR_EACH_SCALAR_TYPE_REPR(BINARYDATA_NUMERIC_CLASSES)
 };
 
 template <typename Domain, typename Input>
-bool
+static bool
 InRange(Input x)
 {
     return std::numeric_limits<Domain>::min() <= x &&
            x <= std::numeric_limits<Domain>::max();
 }
 
 template <>
 bool
@@ -512,17 +512,17 @@ NumericTypeToString(JSContext *cx, unsig
  *   var S = new StructType({...})
  *
  * A.prototype.__proto__ === ArrayType.prototype.prototype (and similar for
  * StructType).
  *
  * This function takes a reference to either ArrayType or StructType and
  * returns a JSObject which can be set as A.prototype.
  */
-JSObject *
+static JSObject *
 SetupAndGetPrototypeObjectForComplexTypeInstance(JSContext *cx,
                                                  HandleObject complexTypeGlobal)
 {
     RootedObject global(cx, cx->compartment()->maybeGlobal());
     RootedValue complexTypePrototypeVal(cx);
     RootedValue complexTypePrototypePrototypeVal(cx);
 
     if (!JSObject::getProperty(cx, complexTypeGlobal, complexTypeGlobal,
--- a/js/src/config/baseconfig.mk
+++ b/js/src/config/baseconfig.mk
@@ -1,18 +1,22 @@
 installdir = $(libdir)/$(MOZ_APP_NAME)-$(MOZ_APP_VERSION)
 sdkdir = $(libdir)/$(MOZ_APP_NAME)-devel-$(MOZ_APP_VERSION)
 
+ifndef INCLUDED_FUNCTIONS_MK
+include $(topsrcdir)/config/makefiles/functions.mk
+endif
+
 ifneq (,$(filter /%,$(TOP_DIST)))
-DIST = $(TOP_DIST)
+DIST := $(call core_realpath,$(TOP_DIST))
 else
 ifeq (.,$(DEPTH))
-DIST = $(TOP_DIST)
+DIST := $(call core_realpath,$(TOP_DIST))
 else
-DIST = $(DEPTH)/$(TOP_DIST)
+DIST := $(call core_realpath,$(DEPTH)/$(TOP_DIST))
 endif
 endif
 
 # We do magic with OBJ_SUFFIX in config.mk, the following ensures we don't
 # manually use it before config.mk inclusion
 _OBJ_SUFFIX := $(OBJ_SUFFIX)
 OBJ_SUFFIX = $(error config/config.mk needs to be included before using OBJ_SUFFIX)
 
--- a/js/src/config/config.mk
+++ b/js/src/config/config.mk
@@ -59,20 +59,16 @@ CHECK_VARS := \
  $(NULL)
 
 # checks for internal spaces or trailing spaces in the variable
 # named by $x
 check-variable = $(if $(filter-out 0 1,$(words $($(x))z)),$(error Spaces are not allowed in $(x)))
 
 $(foreach x,$(CHECK_VARS),$(check-variable))
 
-ifndef INCLUDED_FUNCTIONS_MK
-include $(topsrcdir)/config/makefiles/functions.mk
-endif
-
 RM = rm -f
 
 # LIBXUL_DIST is not defined under js/src, thus we make it mean DIST there.
 LIBXUL_DIST ?= $(DIST)
 
 # FINAL_TARGET specifies the location into which we copy end-user-shipped
 # build products (typelibs, components, chrome).
 #
--- a/js/src/ctypes/CTypes.cpp
+++ b/js/src/ctypes/CTypes.cpp
@@ -789,28 +789,28 @@ static const JSFunctionSpec sModuleFunct
   JS_FN("CDataFinalizer", CDataFinalizer::Construct, 2, CTYPESFN_FLAGS),
   JS_FN("open", Library::Open, 1, CTYPESFN_FLAGS),
   JS_FN("cast", CData::Cast, 2, CTYPESFN_FLAGS),
   JS_FN("getRuntime", CData::GetRuntime, 1, CTYPESFN_FLAGS),
   JS_FN("libraryName", Library::Name, 1, CTYPESFN_FLAGS),
   JS_FS_END
 };
 
-JS_ALWAYS_INLINE JSString*
+static JS_ALWAYS_INLINE JSString*
 NewUCString(JSContext* cx, const AutoString& from)
 {
   return JS_NewUCStringCopyN(cx, from.begin(), from.length());
 }
 
 /*
  * Return a size rounded up to a multiple of a power of two.
  *
  * Note: |align| must be a power of 2.
  */
-JS_ALWAYS_INLINE size_t
+static JS_ALWAYS_INLINE size_t
 Align(size_t val, size_t align)
 {
   // Ensure that align is a power of two.
   MOZ_ASSERT(align != 0 && (align & (align - 1)) == 0);
   return ((val - 1) | (align - 1)) + 1;
 }
 
 static ABICode
--- a/js/src/devtools/vprof/vprof.cpp
+++ b/js/src/devtools/vprof/vprof.cpp
@@ -73,17 +73,17 @@ static long glock = LOCK_IS_FREE;
 
 		printf(buf);
 		::OutputDebugStringA(buf);
 	}
 #else
 	#define vprof_printf printf
 #endif
 
-inline static entry* reverse (entry* s)
+static inline entry* reverse (entry* s)
 {
     entry_t e, n, p;
 
     p = NULL;
     for (e = s; e; e = n) {
         n = e->next;
         e->next = p;
         p = e;
@@ -146,17 +146,17 @@ static void dumpProfile (void)
                 }
             }
         }
         vprof_printf ("\n");
     }
     entries = reverse(entries);
 }
 
-inline static entry_t findEntry (char* file, int line)
+static inline entry_t findEntry (char* file, int line)
 {
     for (entry_t e =  entries; e; e = e->next) {
         if ((e->line == line) && (VMPI_strcmp (e->file, file) == 0)) {
             return e;
         }
     }
     return NULL;
 }
--- a/js/src/frontend/BytecodeCompiler.cpp
+++ b/js/src/frontend/BytecodeCompiler.cpp
@@ -131,17 +131,17 @@ MaybeCheckEvalFreeVariables(ExclusiveCon
             }
             scope = scope->enclosingScope();
         }
     }
 
     return true;
 }
 
-inline bool
+static inline bool
 CanLazilyParse(ExclusiveContext *cx, const CompileOptions &options)
 {
     return options.canLazilyParse &&
         options.compileAndGo &&
         options.sourcePolicy == CompileOptions::SAVE_SOURCE &&
         !cx->compartment()->debugMode();
 }
 
--- a/js/src/frontend/BytecodeEmitter.cpp
+++ b/js/src/frontend/BytecodeEmitter.cpp
@@ -3004,20 +3004,29 @@ EmitDestructuringOpsHelper(ExclusiveCont
         } else {
             JS_ASSERT(pn->isKind(PNK_OBJECT));
             JS_ASSERT(pn2->isKind(PNK_COLON));
             pn3 = pn2->pn_left;
             if (pn3->isKind(PNK_NUMBER)) {
                 if (!EmitNumberOp(cx, pn3->pn_dval, bce))
                     return false;
             } else {
+                // The parser already checked for atoms representing indexes and
+                // used PNK_NUMBER instead, but also watch for ids which TI treats
+                // as indexes for simpliciation of downstream analysis.
                 JS_ASSERT(pn3->isKind(PNK_STRING) || pn3->isKind(PNK_NAME));
-                if (!EmitAtomOp(cx, pn3, JSOP_GETPROP, bce))
-                    return false;
-                doElemOp = false;
+                jsid id = NameToId(pn3->pn_atom->asPropertyName());
+                if (id != types::IdToTypeId(id)) {
+                    if (!EmitTree(cx, bce, pn3))
+                        return false;
+                } else {
+                    if (!EmitAtomOp(cx, pn3, JSOP_GETPROP, bce))
+                        return false;
+                    doElemOp = false;
+                }
             }
             pn3 = pn2->pn_right;
         }
 
         if (doElemOp) {
             /*
              * Ok, get the value of the matching property name.  This leaves
              * that value on top of the value being destructured, so the stack
--- a/js/src/frontend/FoldConstants.cpp
+++ b/js/src/frontend/FoldConstants.cpp
@@ -186,17 +186,17 @@ FoldBinaryNumeric(ExclusiveContext *cx, 
 
 // Remove a ParseNode, **pnp, from a parse tree, putting another ParseNode,
 // *pn, in its place.
 //
 // pnp points to a ParseNode pointer. This must be the only pointer that points
 // to the parse node being replaced. The replacement, *pn, is unchanged except
 // for its pn_next pointer; updating that is necessary if *pn's new parent is a
 // list node.
-void
+static void
 ReplaceNode(ParseNode **pnp, ParseNode *pn)
 {
     pn->pn_next = (*pnp)->pn_next;
     *pnp = pn;
 }
 
 enum Truthiness { Truthy, Falsy, Unknown };
 
--- a/js/src/frontend/Parser.cpp
+++ b/js/src/frontend/Parser.cpp
@@ -2601,17 +2601,17 @@ Parser<ParseHandler>::maybeParseDirectiv
                     if (tokenStream.sawOctalEscape()) {
                         report(ParseError, false, null(), JSMSG_DEPRECATED_OCTAL);
                         return false;
                     }
                     pc->sc->strict = true;
                 }
             }
         } else if (directive == context->names().useAsm) {
-            if (pc->sc->isFunctionBox() && !pc->isGenerator())
+            if (pc->sc->isFunctionBox())
                 return asmJS(list);
             return report(ParseWarning, false, pn, JSMSG_USE_ASM_DIRECTIVE_FAIL);
         }
     }
     return true;
 }
 
 /*
--- a/js/src/frontend/TokenStream.cpp
+++ b/js/src/frontend/TokenStream.cpp
@@ -909,17 +909,17 @@ TokenStream::newToken(ptrdiff_t adjust)
 
 JS_ALWAYS_INLINE JSAtom *
 TokenStream::atomize(ExclusiveContext *cx, CharBuffer &cb)
 {
     return AtomizeChars<CanGC>(cx, cb.begin(), cb.length());
 }
 
 #ifdef DEBUG
-bool
+static bool
 IsTokenSane(Token *tp)
 {
     // Nb: TOK_EOL should never be used in an actual Token;  it should only be
     // returned as a TokenKind from peekTokenSameLine().
     if (tp->type < TOK_ERROR || tp->type >= TOK_LIMIT || tp->type == TOK_EOL)
         return false;
 
     if (tp->pos.end < tp->pos.begin)
--- a/js/src/gc/Verifier.cpp
+++ b/js/src/gc/Verifier.cpp
@@ -29,17 +29,17 @@ using namespace mozilla;
 
 template <typename T>
 bool
 CheckNonAddressThing(uintptr_t *w, Rooted<T> *rootp)
 {
     return w >= (uintptr_t*)rootp->address() && w < (uintptr_t*)(rootp->address() + 1);
 }
 
-JS_ALWAYS_INLINE bool
+static JS_ALWAYS_INLINE bool
 CheckStackRootThing(uintptr_t *w, Rooted<void *> *rootp, ThingRootKind kind)
 {
     if (kind == THING_ROOT_BINDINGS)
         return CheckNonAddressThing(w, reinterpret_cast<Rooted<Bindings> *>(rootp));
 
     if (kind == THING_ROOT_PROPERTY_DESCRIPTOR)
         return CheckNonAddressThing(w, reinterpret_cast<Rooted<PropertyDescriptor> *>(rootp));
 
--- a/js/src/gdb/gdb-tests.cpp
+++ b/js/src/gdb/gdb-tests.cpp
@@ -15,25 +15,25 @@ using namespace JS;
 /* The class of the global object. */
 const JSClass global_class = {
     "global", JSCLASS_GLOBAL_FLAGS,
     JS_PropertyStub,  JS_DeletePropertyStub, JS_PropertyStub,  JS_StrictPropertyStub,
     JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub
 };
 
 template<typename T>
-inline T *
+static inline T *
 checkPtr(T *ptr)
 {
   if (! ptr)
     abort();
   return ptr;
 }
 
-void
+static void
 checkBool(bool success)
 {
   if (! success)
     abort();
 }
 
 /* The error reporter callback. */
 void reportError(JSContext *cx, const char *message, JSErrorReport *report)
--- a/js/src/jit-test/tests/asm.js/testBasic.js
+++ b/js/src/jit-test/tests/asm.js/testBasic.js
@@ -100,16 +100,17 @@ function assertTypeFailInEval(str)
     }
     assertEq(caught, true);
     options("werror");
 }
 assertTypeFailInEval('function f({}) { "use asm"; function g() {} return g }');
 assertTypeFailInEval('function f({global}) { "use asm"; function g() {} return g }');
 assertTypeFailInEval('function f(global, {imports}) { "use asm"; function g() {} return g }');
 assertTypeFailInEval('function f(g = 2) { "use asm"; function g() {} return g }');
+assertTypeFailInEval('function *f() { "use asm"; function g() {} return g }');
 
 function assertLinkFailInEval(str)
 {
     if (!isAsmJSCompilationAvailable())
         return;
 
     var caught = false;
     var oldOpts = options("werror");
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/gc/bug-924690.js
@@ -0,0 +1,25 @@
+x = []
+try {
+    (function() {
+        schedulegc(1);
+        ((function() {
+            return {
+                y: function() {
+                    u() = []
+                }
+            }
+        })())
+    })()
+    watch.call(x, "valueOf", function() {})
+    gc()
+} catch (e) { print(e); }
+try {
+    (function() {
+        x.valueOf =
+        (function() {
+                y();
+        })
+    })()
+    x + 2
+    print('foo')
+} catch (e) { print(e); }
--- a/js/src/jit-test/tests/generators/es6-syntax.js
+++ b/js/src/jit-test/tests/generators/es6-syntax.js
@@ -27,12 +27,8 @@ assertSyntaxError("function* f(...yield)
 // For each.
 assertSyntaxError("for yield");
 assertSyntaxError("for yield (;;) {}");
 assertSyntaxError("for yield (x of y) {}");
 assertSyntaxError("for yield (var i in o) {}");
 
 // Expression bodies.
 assertSyntaxError("function* f() yield 7");
-
-// Asm.js.
-load(libdir + "asm.js");
-assertAsmDirectiveFail("function* f() { 'use asm'; function g() { return 0; } return g; })()")
--- a/js/src/jit/AsmJS.cpp
+++ b/js/src/jit/AsmJS.cpp
@@ -6477,16 +6477,19 @@ EstablishPreconditions(ExclusiveContext 
         return Warn(parser, JSMSG_USE_ASM_TYPE_FAIL, "Disabled by javascript.options.asmjs in about:config");
 
     if (!parser.options().compileAndGo)
         return Warn(parser, JSMSG_USE_ASM_TYPE_FAIL, "Temporarily disabled for event-handler and other cloneable scripts");
 
     if (cx->compartment()->debugMode())
         return Warn(parser, JSMSG_USE_ASM_TYPE_FAIL, "Disabled by debugger");
 
+    if (parser.pc->isGenerator())
+        return Warn(parser, JSMSG_USE_ASM_TYPE_FAIL, "Disabled by generator context");
+
 #ifdef JS_WORKER_THREADS
     if (ParallelCompilationEnabled(cx)) {
         if (!EnsureWorkerThreadsInitialized(cx))
             return Warn(parser, JSMSG_USE_ASM_TYPE_FAIL, "Failed compilation thread initialization");
     }
 #endif
 
     return true;
--- a/js/src/jit/CodeGenerator.cpp
+++ b/js/src/jit/CodeGenerator.cpp
@@ -4499,19 +4499,18 @@ CodeGenerator::visitCharCodeAt(LCharCode
     Register index = ToRegister(lir->index());
     Register output = ToRegister(lir->output());
 
     OutOfLineCode *ool = oolCallVM(CharCodeAtInfo, lir, (ArgList(), str, index), StoreRegisterTo(output));
     if (!ool)
         return false;
 
     Address lengthAndFlagsAddr(str, JSString::offsetOfLengthAndFlags());
-    masm.loadPtr(lengthAndFlagsAddr, output);
-
-    masm.branchTest32(Assembler::Zero, output, Imm32(JSString::FLAGS_MASK), ool->entry());
+
+    masm.branchTest32(Assembler::Zero, lengthAndFlagsAddr, Imm32(JSString::FLAGS_MASK), ool->entry());
 
     // getChars
     Address charsAddr(str, JSString::offsetOfChars());
     masm.loadPtr(charsAddr, output);
     masm.load16ZeroExtend(BaseIndex(output, index, TimesTwo, 0), output);
 
     masm.bind(ool->rejoin());
     return true;
--- a/js/src/jit/IonAnalysis.cpp
+++ b/js/src/jit/IonAnalysis.cpp
@@ -229,17 +229,17 @@ IsPhiObservable(MPhi *phi, Observability
         }
     }
     return false;
 }
 
 // Handles cases like:
 //    x is phi(a, x) --> a
 //    x is phi(a, a) --> a
-inline MDefinition *
+static inline MDefinition *
 IsPhiRedundant(MPhi *phi)
 {
     MDefinition *first = phi->operandIfRedundant();
     if (first == nullptr)
         return nullptr;
 
     // Propagate the Folded flag if |phi| is replaced with another phi.
     if (phi->isFolded())
--- a/js/src/jit/IonBuilder.cpp
+++ b/js/src/jit/IonBuilder.cpp
@@ -3955,17 +3955,17 @@ IonBuilder::makeInliningDecision(JSFunct
             IonSpew(IonSpew_Inlining, "%s:%d - Vetoed: callee is not hot.",
                     targetScript->filename(), targetScript->lineno);
             return false;
         }
     }
 
     // TI calls ObjectStateChange to trigger invalidation of the caller.
     types::TypeObjectKey *targetType = types::TypeObjectKey::get(target);
-    targetType->watchStateChange(constraints());
+    targetType->watchStateChangeForInlinedCall(constraints());
 
     return true;
 }
 
 uint32_t
 IonBuilder::selectInliningTargets(ObjectVector &targets, CallInfo &callInfo, BoolVector &choiceSet)
 {
     uint32_t totalSize = 0;
@@ -4638,17 +4638,17 @@ IonBuilder::createThisScriptedSingleton(
     RootedObject targetRoot(cx, target);
     JSObject *templateObject = CreateThisForFunctionWithProto(cx, targetRoot, proto, TenuredObject);
     if (!templateObject)
         return nullptr;
 
     // Trigger recompilation if the templateObject changes.
     types::TypeObjectKey *templateType = types::TypeObjectKey::get(templateObject);
     if (templateType->newScript())
-        templateType->watchStateChange(constraints());
+        templateType->watchStateChangeForNewScriptTemplate(constraints());
 
     MCreateThisWithTemplate *createThis = MCreateThisWithTemplate::New(templateObject);
     current->add(createThis);
 
     return createThis;
 }
 
 MDefinition *
@@ -6881,17 +6881,17 @@ IonBuilder::getTypedArrayElements(MDefin
 {
     if (obj->isConstant() && obj->toConstant()->value().isObject()) {
         TypedArrayObject *tarr = &obj->toConstant()->value().toObject().as<TypedArrayObject>();
         void *data = tarr->viewData();
 
         // The 'data' pointer can change in rare circumstances
         // (ArrayBufferObject::changeContents).
         types::TypeObjectKey *tarrType = types::TypeObjectKey::get(tarr);
-        tarrType->watchStateChange(constraints());
+        tarrType->watchStateChangeForTypedArrayBuffer(constraints());
 
         obj->setFoldedUnchecked();
         return MConstantElements::New(data);
     }
     return MTypedArrayElements::New(obj);
 }
 
 MDefinition *
@@ -7595,38 +7595,38 @@ IonBuilder::jsop_not()
 
     MNot *ins = new MNot(value);
     current->add(ins);
     current->push(ins);
     ins->infer();
     return true;
 }
 
-inline bool
+static inline bool
 TestClassHasAccessorHook(const Class *clasp, bool isGetter)
 {
     if (isGetter && clasp->ops.getGeneric)
         return true;
     if (!isGetter && clasp->ops.setGeneric)
         return true;
     return false;
 }
 
-inline bool
+static inline bool
 TestTypeHasOwnProperty(types::TypeObjectKey *typeObj, PropertyName *name, bool &cont)
 {
     cont = true;
     types::HeapTypeSetKey propSet = typeObj->property(NameToId(name));
     if (!propSet.actualTypes->empty())
         cont = false;
     // Note: Callers must explicitly freeze the property type set later on if optimizing.
     return true;
 }
 
-inline bool
+static inline bool
 TestCommonAccessorProtoChain(JSContext *cx, PropertyName *name,
                              bool isGetter, JSObject *foundProto,
                              JSObject *obj, bool &cont)
 {
     cont = false;
     JSObject *curObj = obj;
     JSObject *stopAt = foundProto->getProto();
     while (curObj != stopAt) {
@@ -7662,17 +7662,17 @@ TestCommonAccessorProtoChain(JSContext *
         }
 
         curObj = curObj->getProto();
     }
     cont = true;
     return true;
 }
 
-inline bool
+static inline bool
 SearchCommonPropFunc(JSContext *cx, types::TemporaryTypeSet *types,
                      PropertyName *name, bool isGetter,
                      JSObject *&found, JSObject *&foundProto, bool &cont)
 {
     cont = false;
     for (unsigned i = 0; i < types->getObjectCount(); i++) {
         RootedObject curObj(cx, types->getSingleObject(i));
 
--- a/js/src/jit/IonCaches.cpp
+++ b/js/src/jit/IonCaches.cpp
@@ -2390,17 +2390,17 @@ GenerateCallSetter(JSContext *cx, IonScr
     JS_ASSERT(masm.framePushed() == initialStack);
 
     // restoreLive()
     masm.PopRegsInMask(liveRegs);
 
     return true;
 }
 
-bool
+static bool
 IsCacheableDOMProxyUnshadowedSetterCall(JSContext *cx, HandleObject obj, HandlePropertyName name,
                                         MutableHandleObject holder, MutableHandleShape shape,
                                         bool *isSetter)
 {
     JS_ASSERT(IsCacheableDOMProxy(obj));
 
     *isSetter = false;
 
--- a/js/src/jit/IonMacroAssembler.cpp
+++ b/js/src/jit/IonMacroAssembler.cpp
@@ -897,21 +897,20 @@ MacroAssembler::compareStrings(JSOp op, 
     branchPtr(Assembler::Equal, result, temp, fail);
     move32(Imm32(op == JSOP_NE || op == JSOP_STRICTNE), result);
 
     bind(&done);
 }
 
 void
 MacroAssembler::checkInterruptFlagsPar(const Register &tempReg,
-                                            Label *fail)
+                                       Label *fail)
 {
     movePtr(ImmPtr(&GetIonContext()->runtime->interrupt), tempReg);
-    load32(Address(tempReg, 0), tempReg);
-    branchTest32(Assembler::NonZero, tempReg, tempReg, fail);
+    branch32(Assembler::NonZero, Address(tempReg, 0), Imm32(0), fail);
 }
 
 void
 MacroAssembler::maybeRemoveOsrFrame(Register scratch)
 {
     // Before we link an exit frame, check for an OSR frame, which is
     // indicative of working inside an existing bailout. In this case, remove
     // the OSR frame, so we don't explode the stack with repeated bailouts.
@@ -1356,17 +1355,17 @@ MacroAssembler::clearCalleeTag(Register 
       case ParallelExecution:
         andPtr(Imm32(~0x3), callee);
         return;
       default:
         MOZ_ASSUME_UNREACHABLE("No such execution mode");
     }
 }
 
-void printf0_(const char *output) {
+static void printf0_(const char *output) {
     printf("%s", output);
 }
 
 void
 MacroAssembler::printf(const char *output)
 {
     RegisterSet regs = RegisterSet::Volatile();
     PushRegsInMask(regs);
@@ -1376,17 +1375,17 @@ MacroAssembler::printf(const char *outpu
     setupUnalignedABICall(1, temp);
     movePtr(ImmPtr(output), temp);
     passABIArg(temp);
     callWithABI(JS_FUNC_TO_DATA_PTR(void *, printf0_));
 
     PopRegsInMask(RegisterSet::Volatile());
 }
 
-void printf1_(const char *output, uintptr_t value) {
+static void printf1_(const char *output, uintptr_t value) {
     char *line = JS_sprintf_append(nullptr, output, value);
     printf("%s", line);
     js_free(line);
 }
 
 void
 MacroAssembler::printf(const char *output, Register value)
 {
--- a/js/src/jit/LiveRangeAllocator.cpp
+++ b/js/src/jit/LiveRangeAllocator.cpp
@@ -627,19 +627,38 @@ LiveRangeAllocator<VREG>::buildLivenessI
                         if (LSafepoint *safepoint = ins->safepoint())
                             AddRegisterToSafepoint(safepoint, reg, *temp);
                     } else {
                         JS_ASSERT(!ins->isCall());
                         if (!vregs[temp].getInterval(0)->addRangeAtHead(inputOf(*ins), outputOf(*ins)))
                             return false;
                     }
                 } else {
+                    // Normally temps are considered to cover both the input
+                    // and output of the associated instruction. In some cases
+                    // though we want to use a fixed register as both an input
+                    // and clobbered register in the instruction, so watch for
+                    // this and shorten the temp to cover only the output.
+                    CodePosition from = inputOf(*ins);
+                    if (temp->policy() == LDefinition::PRESET) {
+                        AnyRegister reg = temp->output()->toRegister();
+                        for (LInstruction::InputIterator alloc(**ins); alloc.more(); alloc.next()) {
+                            if (alloc->isUse()) {
+                                LUse *use = alloc->toUse();
+                                if (use->isFixedRegister()) {
+                                    if (GetFixedRegister(vregs[use].def(), use) == reg)
+                                        from = outputOf(*ins);
+                                }
+                            }
+                        }
+                    }
+
                     CodePosition to =
                         ins->isCall() ? outputOf(*ins) : outputOf(*ins).next();
-                    if (!vregs[temp].getInterval(0)->addRangeAtHead(inputOf(*ins), to))
+                    if (!vregs[temp].getInterval(0)->addRangeAtHead(from, to))
                         return false;
                 }
             }
 
             DebugOnly<bool> hasUseRegister = false;
             DebugOnly<bool> hasUseRegisterAtStart = false;
 
             for (LInstruction::InputIterator alloc(**ins); alloc.more(); alloc.next()) {
@@ -679,17 +698,16 @@ LiveRangeAllocator<VREG>::buildLivenessI
 
                     // Don't treat RECOVERED_INPUT uses as keeping the vreg alive.
                     if (use->policy() == LUse::RECOVERED_INPUT)
                         continue;
 
                     CodePosition to;
                     if (forLSRA) {
                         if (use->isFixedRegister()) {
-                            JS_ASSERT(!use->usedAtStart());
                             AnyRegister reg = GetFixedRegister(vregs[use].def(), use);
                             if (!addFixedRangeAtHead(reg, inputOf(*ins), outputOf(*ins)))
                                 return false;
                             to = inputOf(*ins);
 
                             // Fixed intervals are not added to safepoints, so do it
                             // here.
                             LSafepoint *safepoint = ins->safepoint();
--- a/js/src/jit/ParallelFunctions.cpp
+++ b/js/src/jit/ParallelFunctions.cpp
@@ -50,17 +50,17 @@ jit::IsThreadLocalObject(ForkJoinSlice *
 static void
 printTrace(const char *prefix, struct IonLIRTraceData *cached)
 {
     fprintf(stderr, "%s / Block %3u / LIR %3u / Mode %u / LIR %s\n",
             prefix,
             cached->blockIndex, cached->lirIndex, cached->execModeInt, cached->lirOpName);
 }
 
-struct IonLIRTraceData seqTraceData;
+static struct IonLIRTraceData seqTraceData;
 #endif
 
 void
 jit::TraceLIR(IonLIRTraceData *current)
 {
 #ifdef DEBUG
     static enum { NotSet, All, Bailouts } traceMode;
 
--- a/js/src/jit/RangeAnalysis.cpp
+++ b/js/src/jit/RangeAnalysis.cpp
@@ -2162,17 +2162,17 @@ RemoveTruncatesOnOutput(MInstruction *tr
         MDefinition *def = use.def();
         if (!def->isTruncateToInt32() || !def->isToInt32())
             continue;
 
         def->replaceAllUsesWith(truncated);
     }
 }
 
-void
+static void
 AdjustTruncatedInputs(MInstruction *truncated)
 {
     MBasicBlock *block = truncated->block();
     for (size_t i = 0, e = truncated->numOperands(); i < e; i++) {
         if (!truncated->isOperandTruncated(i))
             continue;
         if (truncated->getOperand(i)->type() == MIRType_Int32)
             continue;
--- a/js/src/jit/arm/Assembler-arm.cpp
+++ b/js/src/jit/arm/Assembler-arm.cpp
@@ -1490,17 +1490,17 @@ Assembler::as_movw(Register dest, Imm16 
 }
 BufferOffset
 Assembler::as_movt(Register dest, Imm16 imm, Condition c, Instruction *pos)
 {
     JS_ASSERT(hasMOVWT());
     return writeInst(0x03400000 | c | imm.encode() | RD(dest), (uint32_t*)pos);
 }
 
-const int mull_tag = 0x90;
+static const int mull_tag = 0x90;
 
 BufferOffset
 Assembler::as_genmul(Register dhi, Register dlo, Register rm, Register rn,
                      MULOp op, SetCond_ sc, Condition c)
 {
 
     return writeInst(RN(dhi) | maybeRD(dlo) | RM(rm) | rn.code() | op | sc | c | mull_tag);
 }
--- a/js/src/jit/shared/Lowering-shared-inl.h
+++ b/js/src/jit/shared/Lowering-shared-inl.h
@@ -337,16 +337,22 @@ LIRGeneratorShared::useKeepaliveOrConsta
 
 LUse
 LIRGeneratorShared::useFixed(MDefinition *mir, Register reg)
 {
     return use(mir, LUse(reg));
 }
 
 LUse
+LIRGeneratorShared::useFixedAtStart(MDefinition *mir, Register reg)
+{
+    return use(mir, LUse(reg, true));
+}
+
+LUse
 LIRGeneratorShared::useFixed(MDefinition *mir, FloatRegister reg)
 {
     return use(mir, LUse(reg));
 }
 
 LUse
 LIRGeneratorShared::useFixed(MDefinition *mir, AnyRegister reg)
 {
--- a/js/src/jit/shared/Lowering-shared.h
+++ b/js/src/jit/shared/Lowering-shared.h
@@ -67,16 +67,17 @@ class LIRGeneratorShared : public MInstr
     inline LUse use(MDefinition *mir, LUse policy);
     inline LUse use(MDefinition *mir);
     inline LUse useAtStart(MDefinition *mir);
     inline LUse useRegister(MDefinition *mir);
     inline LUse useRegisterAtStart(MDefinition *mir);
     inline LUse useFixed(MDefinition *mir, Register reg);
     inline LUse useFixed(MDefinition *mir, FloatRegister reg);
     inline LUse useFixed(MDefinition *mir, AnyRegister reg);
+    inline LUse useFixedAtStart(MDefinition *mir, Register reg);
     inline LAllocation useOrConstant(MDefinition *mir);
     // "Any" is architecture dependent, and will include registers and stack slots on X86,
     // and only registers on ARM.
     inline LAllocation useAny(MDefinition *mir);
     inline LAllocation useAnyOrConstant(MDefinition *mir);
     // "Storable" is architecture dependend, and will include registers and constants on X86
     // and only registers on ARM.
     // this is a generic "things we can expect to write into memory in 1 instruction"
--- a/js/src/jit/shared/Lowering-x86-shared.cpp
+++ b/js/src/jit/shared/Lowering-x86-shared.cpp
@@ -219,19 +219,19 @@ bool
 LIRGeneratorX86Shared::visitAsmJSUDiv(MAsmJSUDiv *div)
 {
     return lowerUDiv(div);
 }
 
 bool
 LIRGeneratorX86Shared::lowerUMod(MInstruction *mod)
 {
-    LUDivOrMod *lir = new LUDivOrMod(useFixed(mod->getOperand(0), eax),
+    LUDivOrMod *lir = new LUDivOrMod(useFixedAtStart(mod->getOperand(0), eax),
                                      useRegister(mod->getOperand(1)),
-                                     LDefinition::BogusTemp());
+                                     tempFixed(eax));
     return defineFixed(lir, mod, LAllocation(AnyRegister(edx)));
 }
 
 bool
 LIRGeneratorX86Shared::visitAsmJSUMod(MAsmJSUMod *mod)
 {
     return lowerUMod(mod);
 }
--- a/js/src/jit/x64/MacroAssembler-x64.h
+++ b/js/src/jit/x64/MacroAssembler-x64.h
@@ -1035,41 +1035,40 @@ class MacroAssemblerX64 : public MacroAs
     void int32ValueToFloat32(const ValueOperand &operand, const FloatRegister &dest) {
         convertInt32ToFloat32(operand.valueReg(), dest);
     }
 
     void loadConstantDouble(double d, const FloatRegister &dest);
     void loadConstantFloat32(float f, const FloatRegister &dest);
 
     void branchTruncateDouble(const FloatRegister &src, const Register &dest, Label *fail) {
-        const uint64_t IndefiniteIntegerValue = 0x8000000000000000;
-        JS_ASSERT(dest != ScratchReg);
         cvttsd2sq(src, dest);
-        movq(ImmWord(IndefiniteIntegerValue), ScratchReg);
-        cmpq(dest, ScratchReg);
-        j(Assembler::Equal, fail);
+
+        // cvttsd2sq returns 0x8000000000000000 on failure. Test for it by
+        // subtracting 1 and testing overflow (this avoids the need to
+        // materialize that value in a register).
+        cmpq(dest, Imm32(1));
+        j(Assembler::Overflow, fail);
+
         movl(dest, dest); // Zero upper 32-bits.
     }
 
     Condition testInt32Truthy(bool truthy, const ValueOperand &operand) {
         testl(operand.valueReg(), operand.valueReg());
         return truthy ? NonZero : Zero;
     }
     void branchTestBooleanTruthy(bool truthy, const ValueOperand &operand, Label *label) {
         testl(operand.valueReg(), operand.valueReg());
         j(truthy ? NonZero : Zero, label);
     }
-    // This returns the tag in ScratchReg.
     Condition testStringTruthy(bool truthy, const ValueOperand &value) {
         unboxString(value, ScratchReg);
 
         Operand lengthAndFlags(ScratchReg, JSString::offsetOfLengthAndFlags());
-        movq(lengthAndFlags, ScratchReg);
-        shrq(Imm32(JSString::LENGTH_SHIFT), ScratchReg);
-        testq(ScratchReg, ScratchReg);
+        testq(lengthAndFlags, Imm32(-1 << JSString::LENGTH_SHIFT));
         return truthy ? Assembler::NonZero : Assembler::Zero;
     }
 
 
     void loadInt32OrDouble(const Operand &operand, const FloatRegister &dest) {
         Label notInt32, end;
         branchTestInt32(Assembler::NotEqual, operand, &notInt32);
         convertInt32ToDouble(operand, dest);
--- a/js/src/jit/x86/MacroAssembler-x86.h
+++ b/js/src/jit/x86/MacroAssembler-x86.h
@@ -874,26 +874,32 @@ class MacroAssemblerX86 : public MacroAs
     }
 
     void loadConstantDouble(double d, const FloatRegister &dest);
     void addConstantDouble(double d, const FloatRegister &dest);
     void loadConstantFloat32(float f, const FloatRegister &dest);
     void addConstantFloat32(float f, const FloatRegister &dest);
 
     void branchTruncateDouble(const FloatRegister &src, const Register &dest, Label *fail) {
-        const uint32_t IndefiniteIntegerValue = 0x80000000;
         cvttsd2si(src, dest);
-        cmpl(dest, Imm32(IndefiniteIntegerValue));
-        j(Assembler::Equal, fail);
+
+        // cvttsd2si returns 0x80000000 on failure. Test for it by
+        // subtracting 1 and testing overflow (this permits the use of a
+        // smaller immediate field).
+        cmpl(dest, Imm32(1));
+        j(Assembler::Overflow, fail);
     }
     void branchTruncateFloat32(const FloatRegister &src, const Register &dest, Label *fail) {
-        const uint32_t IndefiniteIntegerValue = 0x80000000;
         cvttss2si(src, dest);
-        cmpl(dest, Imm32(IndefiniteIntegerValue));
-        j(Assembler::Equal, fail);
+
+        // cvttss2si returns 0x80000000 on failure. Test for it by
+        // subtracting 1 and testing overflow (this permits the use of a
+        // smaller immediate field).
+        cmpl(dest, Imm32(1));
+        j(Assembler::Overflow, fail);
     }
 
     Condition testInt32Truthy(bool truthy, const ValueOperand &operand) {
         testl(operand.payloadReg(), operand.payloadReg());
         return truthy ? NonZero : Zero;
     }
     void branchTestBooleanTruthy(bool truthy, const ValueOperand &operand, Label *label) {
         testl(operand.payloadReg(), operand.payloadReg());
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -3762,17 +3762,17 @@ JS_Enumerate(JSContext *cx, JSObject *ob
 
 /*
  * XXX reverse iterator for properties, unreverse and meld with jsinterp.c's
  *     prop_iterator_class somehow...
  * + preserve the obj->enumerate API while optimizing the native object case
  * + native case here uses a JSShape *, but that iterates in reverse!
  * + so we make non-native match, by reverse-iterating after JS_Enumerating
  */
-const uint32_t JSSLOT_ITER_INDEX = 0;
+static const uint32_t JSSLOT_ITER_INDEX = 0;
 
 static void
 prop_iter_finalize(FreeOp *fop, JSObject *obj)
 {
     void *pdata = obj->getPrivate();
     if (!pdata)
         return;
 
--- a/js/src/jsarray.cpp
+++ b/js/src/jsarray.cpp
@@ -128,17 +128,17 @@ js::StringIsArrayIndex(JSLinearString *s
         JS_ASSERT(index <= MAX_ARRAY_INDEX);
         *indexp = index;
         return true;
     }
 
     return false;
 }
 
-bool
+static bool
 DoubleIndexToId(JSContext *cx, double index, MutableHandleId id)
 {
     if (index == uint32_t(index))
         return IndexToId(cx, uint32_t(index), id);
 
     Value tmp = DoubleValue(index);
     return ValueToId<CanGC>(cx, HandleValue::fromMarkedLocation(&tmp), id);
 }
@@ -1432,17 +1432,17 @@ NumDigitsBase10(uint32_t n)
      * Algorithm taken from
      * http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
      */
     uint32_t log2 = CeilingLog2(n);
     uint32_t t = log2 * 1233 >> 12;
     return t - (n < powersOf10[t]) + 1;
 }
 
-inline bool
+static inline bool
 CompareLexicographicInt32(JSContext *cx, const Value &a, const Value &b, bool *lessOrEqualp)
 {
     int32_t aint = a.toInt32();
     int32_t bint = b.toInt32();
 
     /*
      * If both numbers are equal ... trivial
      * If only one of both is negative --> arithmetic comparison as char code
@@ -1477,17 +1477,17 @@ CompareLexicographicInt32(JSContext *cx,
             JS_ASSERT((digitsb - digitsa) < ArrayLength(powersOf10));
             *lessOrEqualp = (uint64_t(auint) * powersOf10[digitsb - digitsa] <= uint64_t(buint));
         }
     }
 
     return true;
 }
 
-inline bool
+static inline bool
 CompareSubStringValues(JSContext *cx, const jschar *s1, size_t l1,
                        const jschar *s2, size_t l2, bool *lessOrEqualp)
 {
     if (!JS_CHECK_OPERATION_LIMIT(cx))
         return false;
 
     int32_t result;
     if (!s1 || !s2 || !CompareChars(s1, l1, s2, l2, &result))
@@ -1704,17 +1704,17 @@ MatchNumericComparator(JSContext *cx, co
 
     if (arg0 == 1 && arg1 == 0)
         return Match_RightMinusLeft;
 
     return Match_None;
 }
 
 template<typename K, typename C>
-inline bool
+static inline bool
 MergeSortByKey(K keys, size_t len, K scratch, C comparator, AutoValueVector *vec)
 {
     MOZ_ASSERT(vec->length() >= len);
 
     /* Sort keys. */
     if (!MergeSort(keys, len, scratch, comparator))
         return false;
 
@@ -1997,17 +1997,17 @@ js::array_sort(JSContext *cx, unsigned a
     while (len > n) {
         if (!JS_CHECK_OPERATION_LIMIT(cx) || !DeletePropertyOrThrow(cx, obj, --len))
             return false;
     }
     args.rval().setObject(*obj);
     return true;
 }
 
-JS_ALWAYS_INLINE bool
+static JS_ALWAYS_INLINE bool
 NewbornArrayPushImpl(JSContext *cx, HandleObject obj, const Value &v)
 {
     Rooted<ArrayObject*> arr(cx, &obj->as<ArrayObject>());
 
     JS_ASSERT(!v.isMagic());
     JS_ASSERT(arr->lengthIsWritable());
 
     uint32_t length = arr->length();
--- a/js/src/jsbool.cpp
+++ b/js/src/jsbool.cpp
@@ -58,17 +58,17 @@ bool_toSource_impl(JSContext *cx, CallAr
 
     JSString *str = sb.finishString();
     if (!str)
         return false;
     args.rval().setString(str);
     return true;
 }
 
-bool
+static bool
 bool_toSource(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsBoolean, bool_toSource_impl>(cx, args);
 }
 #endif
 
 JS_ALWAYS_INLINE bool
@@ -77,17 +77,17 @@ bool_toString_impl(JSContext *cx, CallAr
     HandleValue thisv = args.thisv();
     JS_ASSERT(IsBoolean(thisv));
 
     bool b = thisv.isBoolean() ? thisv.toBoolean() : thisv.toObject().as<BooleanObject>().unbox();
     args.rval().setString(js_BooleanToString(cx, b));
     return true;
 }
 
-bool
+static bool
 bool_toString(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsBoolean, bool_toString_impl>(cx, args);
 }
 
 JS_ALWAYS_INLINE bool
 bool_valueOf_impl(JSContext *cx, CallArgs args)
@@ -95,17 +95,17 @@ bool_valueOf_impl(JSContext *cx, CallArg
     HandleValue thisv = args.thisv();
     JS_ASSERT(IsBoolean(thisv));
 
     bool b = thisv.isBoolean() ? thisv.toBoolean() : thisv.toObject().as<BooleanObject>().unbox();
     args.rval().setBoolean(b);
     return true;
 }
 
-bool
+static bool
 bool_valueOf(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsBoolean, bool_valueOf_impl>(cx, args);
 }
 
 static const JSFunctionSpec boolean_methods[] = {
 #if JS_HAS_TOSOURCE
--- a/js/src/jsdate.cpp
+++ b/js/src/jsdate.cpp
@@ -95,57 +95,57 @@ using JS::GenericNaN;
  *
  *     setDay
  *     before
  *     after
  *     equals
  *     hashCode
  */
 
-inline double
+static inline double
 Day(double t)
 {
     return floor(t / msPerDay);
 }
 
 static double
 TimeWithinDay(double t)
 {
     double result = fmod(t, msPerDay);
     if (result < 0)
         result += msPerDay;
     return result;
 }
 
 /* ES5 15.9.1.3. */
-inline bool
+static inline bool
 IsLeapYear(double year)
 {
     JS_ASSERT(ToInteger(year) == year);
     return fmod(year, 4) == 0 && (fmod(year, 100) != 0 || fmod(year, 400) == 0);
 }
 
-inline double
+static inline double
 DaysInYear(double year)
 {
     if (!IsFinite(year))
         return GenericNaN();
     return IsLeapYear(year) ? 366 : 365;
 }
 
-inline double
+static inline double
 DayFromYear(double y)
 {
     return 365 * (y - 1970) +
            floor((y - 1969) / 4.0) -
            floor((y - 1901) / 100.0) +
            floor((y - 1601) / 400.0);
 }
 
-inline double
+static inline double
 TimeFromYear(double y)
 {
     return DayFromYear(y) * msPerDay;
 }
 
 static double
 YearFromTime(double t)
 {
@@ -166,24 +166,24 @@ YearFromTime(double t)
         y--;
     } else {
         if (t2 + msPerDay * DaysInYear(y) <= t)
             y++;
     }
     return y;
 }
 
-inline int
+static inline int
 DaysInFebruary(double year)
 {
     return IsLeapYear(year) ? 29 : 28;
 }
 
 /* ES5 15.9.1.4. */
-inline double
+static inline double
 DayWithinYear(double t, double year)
 {
     JS_ASSERT_IF(IsFinite(t), YearFromTime(t) == year);
     return Day(t) - DayFromYear(year);
 }
 
 static double
 MonthFromTime(double t)
@@ -277,34 +277,34 @@ WeekDay(double t)
      */
     JS_ASSERT(ToInteger(t) == t);
     int result = (int(Day(t)) + 4) % 7;
     if (result < 0)
         result += 7;
     return result;
 }
 
-inline int
+static inline int
 DayFromMonth(int month, bool isLeapYear)
 {
     /*
      * The following array contains the day of year for the first day of
      * each month, where index 0 is January, and day 0 is January 1.
      */
     static const int firstDayOfMonth[2][13] = {
         {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
         {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}
     };
 
     JS_ASSERT(0 <= month && month <= 12);
     return firstDayOfMonth[isLeapYear][month];
 }
 
 template<typename T>
-inline int
+static inline int
 DayFromMonth(T month, bool isLeapYear) MOZ_DELETE;
 
 /* ES5 15.9.1.12 (out of order to accommodate DaylightSavingTA). */
 static double
 MakeDay(double year, double month, double date)
 {
     /* Step 1. */
     if (!IsFinite(year) || !IsFinite(month) || !IsFinite(date))
@@ -328,17 +328,17 @@ MakeDay(double year, double month, doubl
 
     double yearday = floor(TimeFromYear(ym) / msPerDay);
     double monthday = DayFromMonth(mn, leap);
 
     return yearday + monthday + dt - 1;
 }
 
 /* ES5 15.9.1.13 (out of order to accommodate DaylightSavingTA). */
-inline double
+static inline double
 MakeDate(double day, double time)
 {
     /* Step 1. */
     if (!IsFinite(day) || !IsFinite(time))
         return GenericNaN();
 
     /* Step 2. */
     return day * msPerDay + time;
--- a/js/src/jsdtoa.cpp
+++ b/js/src/jsdtoa.cpp
@@ -39,18 +39,18 @@ using namespace js;
 #define ULlong uint64_t
 #endif
 */
 
 /*
  * MALLOC gets declared external, and that doesn't work for class members, so
  * wrap.
  */
-inline void* dtoa_malloc(size_t size) { return js_malloc(size); }
-inline void dtoa_free(void* p) { return js_free(p); }
+static inline void* dtoa_malloc(size_t size) { return js_malloc(size); }
+static inline void dtoa_free(void* p) { return js_free(p); }
 
 #define NO_GLOBAL_STATE
 #define NO_ERRNO
 #define MALLOC dtoa_malloc
 #define FREE dtoa_free
 #include "dtoa.c"
 
 /* Mapping of JSDToStrMode -> js_dtoa mode */
--- a/js/src/jsinfer.cpp
+++ b/js/src/jsinfer.cpp
@@ -623,26 +623,32 @@ class TypeCompilerConstraint : public Ty
             cx->compartment()->types.addPendingRecompile(cx, compilation);
     }
 
     void newPropertyState(JSContext *cx, TypeSet *source) {
         if (data.invalidateOnNewPropertyState(source))
             cx->compartment()->types.addPendingRecompile(cx, compilation);
     }
 
-    void newObjectState(JSContext *cx, TypeObject *object, bool force) {
-        if (data.invalidateOnNewObjectState(object, force))
+    void newObjectState(JSContext *cx, TypeObject *object) {
+        // Note: Once the object has unknown properties, no more notifications
+        // will be sent on changes to its state, so always invalidate any
+        // associated compilations.
+        if (object->unknownProperties() || data.invalidateOnNewObjectState(object))
             cx->compartment()->types.addPendingRecompile(cx, compilation);
     }
 };
 
 template <typename T>
 bool
 CompilerConstraintInstance<T>::generateTypeConstraint(JSContext *cx, RecompileInfo recompileInfo)
 {
+    if (property.actualObject->unknownProperties())
+        return false;
+
     if (!data.constraintHolds(cx, property, expected))
         return false;
 
     property.actualTypes->add(cx, cx->typeLifoAlloc().new_<TypeCompilerConstraint<T> >(recompileInfo, data),
                               /* callExisting = */ false);
     return true;
 }
 
@@ -695,16 +701,17 @@ HeapTypeSetKey
 TypeObjectKey::property(jsid id)
 {
 #ifdef JS_ION
     JSContext *cx = jit::GetIonContext()->cx;
     TypeObject *type = isSingleObject() ? asSingleObject()->getType(cx) : asTypeObject();
     if (!type)
         MOZ_CRASH();
     HeapTypeSetKey property;
+    property.actualObject = type;
     property.actualTypes = type->getProperty(cx, id);
     if (!property.actualTypes)
         MOZ_CRASH();
     return property;
 #else
     MOZ_CRASH();
 #endif
 }
@@ -749,17 +756,17 @@ class ConstraintDataFreeze
 {
   public:
     ConstraintDataFreeze() {}
 
     const char *kind() { return "freeze"; }
 
     bool invalidateOnNewType(Type type) { return true; }
     bool invalidateOnNewPropertyState(TypeSet *property) { return false; }
-    bool invalidateOnNewObjectState(TypeObject *object, bool force) { return false; }
+    bool invalidateOnNewObjectState(TypeObject *object) { return false; }
 
     bool constraintHolds(JSContext *cx,
                          const HeapTypeSetKey &property, TemporaryTypeSet *expected)
     {
         return property.actualTypes->isSubset(expected);
     }
 };
 
@@ -914,43 +921,37 @@ HeapTypeSetKey::needsBarrier(CompilerCon
 }
 
 namespace {
 
 // Constraint which triggers recompilation if an object acquires particular flags.
 class ConstraintDataFreezeObjectFlags
 {
   public:
-    // Object being queried.
-    TypeObjectKey *object;
-
     // Flags we are watching for on this object.
     TypeObjectFlags flags;
 
-    ConstraintDataFreezeObjectFlags(TypeObjectKey *object, TypeObjectFlags flags)
-      : object(object), flags(flags)
-    {}
+    ConstraintDataFreezeObjectFlags(TypeObjectFlags flags)
+      : flags(flags)
+    {
+        JS_ASSERT(flags);
+    }
 
     const char *kind() { return "freezeObjectFlags"; }
 
     bool invalidateOnNewType(Type type) { return false; }
     bool invalidateOnNewPropertyState(TypeSet *property) { return false; }
-    bool invalidateOnNewObjectState(TypeObject *object, bool force) {
-        return flags ? object->hasAnyFlags(flags) : force;
+    bool invalidateOnNewObjectState(TypeObject *object) {
+        return object->hasAnyFlags(flags);
     }
 
     bool constraintHolds(JSContext *cx,
                          const HeapTypeSetKey &property, TemporaryTypeSet *expected)
     {
-        // FIXME: There is not yet any way to test if constraints with no
-        // associated flags (i.e. those invalidated via |force|) still hold.
-        TypeObject *type = object->isSingleObject()
-                           ? object->asSingleObject()->type()
-                           : object->asTypeObject();
-        return !type->hasAnyFlags(flags);
+        return !invalidateOnNewObjectState(property.actualObject);
     }
 };
 
 } /* anonymous namespace */
 
 bool
 TypeObjectKey::hasFlags(CompilerConstraintList *constraints, TypeObjectFlags flags)
 {
@@ -960,30 +961,23 @@ TypeObjectKey::hasFlags(CompilerConstrai
     JSContext *cx = jit::GetIonContext()->cx;
     TypeObject *type = isSingleObject() ? asSingleObject()->getType(cx) : asTypeObject();
     if (!type)
         MOZ_CRASH();
     if (type->hasAnyFlags(flags))
         return true;
 
     HeapTypeSetKey objectProperty = property(JSID_EMPTY);
-    constraints->add(IonAlloc()->new_<CompilerConstraintInstance<ConstraintDataFreezeObjectFlags> >(objectProperty, ConstraintDataFreezeObjectFlags(this, flags)));
+    constraints->add(IonAlloc()->new_<CompilerConstraintInstance<ConstraintDataFreezeObjectFlags> >(objectProperty, ConstraintDataFreezeObjectFlags(flags)));
     return false;
 #else
     MOZ_CRASH();
 #endif
 }
 
-void
-TypeObjectKey::watchStateChange(CompilerConstraintList *constraints)
-{
-    HeapTypeSetKey objectProperty = property(JSID_EMPTY);
-    constraints->add(IonAlloc()->new_<CompilerConstraintInstance<ConstraintDataFreezeObjectFlags> >(objectProperty, ConstraintDataFreezeObjectFlags(this, 0)));
-}
-
 bool
 TemporaryTypeSet::hasObjectFlags(CompilerConstraintList *constraints, TypeObjectFlags flags)
 {
     if (unknownObject())
         return true;
 
     /*
      * Treat type sets containing no objects as having all object flags,
@@ -997,34 +991,140 @@ TemporaryTypeSet::hasObjectFlags(Compile
         TypeObjectKey *object = getObject(i);
         if (object && object->hasFlags(constraints, flags))
             return true;
     }
 
     return false;
 }
 
-static inline void
-ObjectStateChange(ExclusiveContext *cxArg, TypeObject *object, bool markingUnknown, bool force)
+namespace {
+
+// Constraint which triggers recompilation on any type change in an inlined
+// script. The freeze constraints added to stack type sets will only directly
+// invalidate the script containing those stack type sets. To invalidate code
+// for scripts into which the base script was inlined, ObjectStateChange is used.
+class ConstraintDataFreezeObjectForInlinedCall
+{
+  public:
+    ConstraintDataFreezeObjectForInlinedCall()
+    {}
+
+    const char *kind() { return "freezeObjectForInlinedCall"; }
+
+    bool invalidateOnNewType(Type type) { return false; }
+    bool invalidateOnNewPropertyState(TypeSet *property) { return false; }
+    bool invalidateOnNewObjectState(TypeObject *object) {
+        // We don't keep track of the exact dependencies the caller has on its
+        // inlined scripts' type sets, so always invalidate the caller.
+        return true;
+    }
+
+    bool constraintHolds(JSContext *cx,
+                         const HeapTypeSetKey &property, TemporaryTypeSet *expected)
+    {
+        return true;
+    }
+};
+
+// Constraint which triggers recompilation when the allocation kind of the
+// template object for a type's new script changes.
+class ConstraintDataFreezeObjectForNewScriptTemplate
+{
+    gc::AllocKind allocKind;
+
+  public:
+    ConstraintDataFreezeObjectForNewScriptTemplate(gc::AllocKind allocKind)
+      : allocKind(allocKind)
+    {}
+
+    const char *kind() { return "freezeObjectForNewScriptTemplate"; }
+
+    bool invalidateOnNewType(Type type) { return false; }
+    bool invalidateOnNewPropertyState(TypeSet *property) { return false; }
+    bool invalidateOnNewObjectState(TypeObject *object) {
+        return !object->hasNewScript() || object->newScript()->allocKind != allocKind;
+    }
+
+    bool constraintHolds(JSContext *cx,
+                         const HeapTypeSetKey &property, TemporaryTypeSet *expected)
+    {
+        return !invalidateOnNewObjectState(property.actualObject);
+    }
+};
+
+// Constraint which triggers recompilation when the underlying data pointer for
+// a typed array changes.
+class ConstraintDataFreezeObjectForTypedArrayBuffer
+{
+    void *viewData;
+
+  public:
+    ConstraintDataFreezeObjectForTypedArrayBuffer(void *viewData)
+      : viewData(viewData)
+    {}
+
+    const char *kind() { return "freezeObjectForTypedArrayBuffer"; }
+
+    bool invalidateOnNewType(Type type) { return false; }
+    bool invalidateOnNewPropertyState(TypeSet *property) { return false; }
+    bool invalidateOnNewObjectState(TypeObject *object) {
+        return object->singleton->as<TypedArrayObject>().viewData() != viewData;
+    }
+
+    bool constraintHolds(JSContext *cx,
+                         const HeapTypeSetKey &property, TemporaryTypeSet *expected)
+    {
+        return !invalidateOnNewObjectState(property.actualObject);
+    }
+};
+
+} /* anonymous namespace */
+
+void
+TypeObjectKey::watchStateChangeForInlinedCall(CompilerConstraintList *constraints)
+{
+    HeapTypeSetKey objectProperty = property(JSID_EMPTY);
+    constraints->add(IonAlloc()->new_<CompilerConstraintInstance<ConstraintDataFreezeObjectForInlinedCall> >(objectProperty, ConstraintDataFreezeObjectForInlinedCall()));
+}
+
+void
+TypeObjectKey::watchStateChangeForNewScriptTemplate(CompilerConstraintList *constraints)
+{
+    gc::AllocKind kind = asTypeObject()->newScript()->allocKind;
+    HeapTypeSetKey objectProperty = property(JSID_EMPTY);
+    constraints->add(IonAlloc()->new_<CompilerConstraintInstance<ConstraintDataFreezeObjectForNewScriptTemplate> >(objectProperty, ConstraintDataFreezeObjectForNewScriptTemplate(kind)));
+}
+
+void
+TypeObjectKey::watchStateChangeForTypedArrayBuffer(CompilerConstraintList *constraints)
+{
+    void *viewData = asSingleObject()->as<TypedArrayObject>().viewData();
+    HeapTypeSetKey objectProperty = property(JSID_EMPTY);
+    constraints->add(IonAlloc()->new_<CompilerConstraintInstance<ConstraintDataFreezeObjectForTypedArrayBuffer> >(objectProperty, ConstraintDataFreezeObjectForTypedArrayBuffer(viewData)));
+}
+
+static void
+ObjectStateChange(ExclusiveContext *cxArg, TypeObject *object, bool markingUnknown)
 {
     if (object->unknownProperties())
         return;
 
     /* All constraints listening to state changes are on the empty id. */
     TypeSet *types = object->maybeGetProperty(JSID_EMPTY);
 
     /* Mark as unknown after getting the types, to avoid assertion. */
     if (markingUnknown)
         object->flags |= OBJECT_FLAG_DYNAMIC_MASK | OBJECT_FLAG_UNKNOWN_PROPERTIES;
 
     if (types) {
         if (JSContext *cx = cxArg->maybeJSContext()) {
             TypeConstraint *constraint = types->constraintList;
             while (constraint) {
-                constraint->newObjectState(cx, object, force);
+                constraint->newObjectState(cx, object);
                 constraint = constraint->next;
             }
         } else {
             JS_ASSERT(!types->constraintList);
         }
     }
 }
 
@@ -1043,17 +1143,17 @@ class ConstraintDataFreezeConfiguredProp
     {}
 
     const char *kind() { return "freezeConfiguredProperty"; }
 
     bool invalidateOnNewType(Type type) { return false; }
     bool invalidateOnNewPropertyState(TypeSet *property) {
         return property->configuredProperty();
     }
-    bool invalidateOnNewObjectState(TypeObject *object, bool force) { return false; }
+    bool invalidateOnNewObjectState(TypeObject *object) { return false; }
 
     bool constraintHolds(JSContext *cx,
                          const HeapTypeSetKey &property, TemporaryTypeSet *expected)
     {
         // Everywhere compiled code depends on definite properties associated
         // with a type object's newScript, we need to make sure there are
         // constraints in place which will mark those properties as configured
         // should the definite properties be invalidated.
@@ -1323,26 +1423,16 @@ TemporaryTypeSet::propertyNeedsBarrier(C
         HeapTypeSetKey property = type->property(id);
         if (property.needsBarrier(constraints))
             return true;
     }
 
     return false;
 }
 
-/*
- * Force recompilation of any jitcode for the script, or of any other script
- * which this script was inlined into.
- */
-static inline void
-AddPendingRecompile(JSContext *cx, JSScript *script)
-{
-    cx->compartment()->types.addPendingRecompile(cx, script);
-}
-
 namespace {
 
 /*
  * As for TypeConstraintFreeze, but describes an implicit freeze constraint
  * added for stack types within a script. Applies to all compilations of the
  * script, not just a single one.
  */
 class TypeConstraintFreezeStack : public TypeConstraint
@@ -1357,17 +1447,17 @@ class TypeConstraintFreezeStack : public
     const char *kind() { return "freezeStack"; }
 
     void newType(JSContext *cx, TypeSet *source, Type type)
     {
         /*
          * Unlike TypeConstraintFreeze, triggering this constraint once does
          * not disable it on future changes to the type set.
          */
-        AddPendingRecompile(cx, script_);
+        cx->compartment()->types.addPendingRecompile(cx, script_);
     }
 };
 
 } /* anonymous namespace */
 
 /////////////////////////////////////////////////////////////////////
 // TypeCompartment
 /////////////////////////////////////////////////////////////////////
@@ -1825,18 +1915,16 @@ TypeCompartment::addPendingRecompile(JSC
 
     co->setPendingInvalidation();
 }
 
 void
 TypeCompartment::addPendingRecompile(JSContext *cx, JSScript *script)
 {
     JS_ASSERT(script);
-    if (!constrainedOutputs)
-        return;
 
 #ifdef JS_ION
     CancelOffThreadIonCompile(cx->compartment(), script);
 
     // Let the script warm up again before attempting another compile.
     if (jit::IsBaselineEnabled(cx))
         script->resetUseCount();
 
@@ -1846,17 +1934,17 @@ TypeCompartment::addPendingRecompile(JSC
     if (script->hasParallelIonScript())
         addPendingRecompile(cx, script->parallelIonScript()->recompileInfo());
 #endif
 
     // When one script is inlined into another the caller listens to state
     // changes on the callee's script, so trigger these to force recompilation
     // of any such callers.
     if (script->function() && !script->function()->hasLazyType())
-        ObjectStateChange(cx, script->function()->type(), false, true);
+        ObjectStateChange(cx, script->function()->type(), false);
 }
 
 void
 TypeCompartment::markSetsUnknown(JSContext *cx, TypeObject *target)
 {
     JS_ASSERT(this == &cx->compartment()->types);
     JS_ASSERT(!(target->flags & OBJECT_FLAG_SETS_MARKED_UNKNOWN));
     JS_ASSERT(!target->singleton);
@@ -2450,17 +2538,17 @@ TypeObject::matchDefiniteProperties(Hand
             if (!found)
                 return false;
         }
     }
 
     return true;
 }
 
-inline void
+static inline void
 InlineAddTypeProperty(ExclusiveContext *cx, TypeObject *obj, jsid id, Type type)
 {
     JS_ASSERT(id == IdToTypeId(id));
 
     AutoEnterAnalysis enter(cx);
 
     TypeSet *types = obj->getProperty(cx, id);
     if (!types || types->hasType(type))
@@ -2533,17 +2621,17 @@ TypeObject::markStateChange(ExclusiveCon
         return;
 
     AutoEnterAnalysis enter(cxArg);
     TypeSet *types = maybeGetProperty(JSID_EMPTY);
     if (types) {
         if (JSContext *cx = cxArg->maybeJSContext()) {
             TypeConstraint *constraint = types->constraintList;
             while (constraint) {
-                constraint->newObjectState(cx, this, true);
+                constraint->newObjectState(cx, this);
                 constraint = constraint->next;
             }
         } else {
             JS_ASSERT(!types->constraintList);
         }
     }
 }
 
@@ -2560,33 +2648,33 @@ TypeObject::setFlags(ExclusiveContext *c
         JS_ASSERT_IF(flags & OBJECT_FLAG_ITERATED,
                      singleton->lastProperty()->hasObjectFlag(BaseShape::ITERATED_SINGLETON));
     }
 
     this->flags |= flags;
 
     InferSpew(ISpewOps, "%s: setFlags 0x%x", TypeObjectString(this), flags);
 
-    ObjectStateChange(cx, this, false, false);
+    ObjectStateChange(cx, this, false);
 }
 
 void
 TypeObject::markUnknown(ExclusiveContext *cx)
 {
     AutoEnterAnalysis enter(cx);
 
     JS_ASSERT(cx->compartment()->activeAnalysis);
     JS_ASSERT(!unknownProperties());
 
     if (!(flags & OBJECT_FLAG_ADDENDUM_CLEARED))
         clearAddendum(cx);
 
     InferSpew(ISpewOps, "UnknownProperties: %s", TypeObjectString(this));
 
-    ObjectStateChange(cx, this, true, true);
+    ObjectStateChange(cx, this, true);
 
     /*
      * Existing constraints may have already been added to this object, which we need
      * to do the right thing for. We can't ensure that we will mark all unknown
      * objects before they have been accessed, as the __proto__ of a known object
      * could be dynamically set to an unknown object, and we can decide to ignore
      * properties of an object during analysis (i.e. hashmaps). Adding unknown for
      * any properties accessed already accounts for possible values read from them.
--- a/js/src/jsinfer.h
+++ b/js/src/jsinfer.h
@@ -319,21 +319,21 @@ public:
 
     /*
      * For constraints attached to an object property's type set, mark the
      * property as having been configured.
      */
     virtual void newPropertyState(JSContext *cx, TypeSet *source) {}
 
     /*
-     * For constraints attached to the JSID_EMPTY type set on an object, mark a
-     * change in one of the object's dynamic property flags. If force is set,
-     * recompilation is always triggered.
+     * For constraints attached to the JSID_EMPTY type set on an object,
+     * indicate a change in one of the object's dynamic property flags or other
+     * state.
      */
-    virtual void newObjectState(JSContext *cx, TypeObject *object, bool force) {}
+    virtual void newObjectState(JSContext *cx, TypeObject *object) {}
 };
 
 /* Flags and other state stored in TypeSet::flags */
 enum {
     TYPE_FLAG_UNDEFINED =  0x1,
     TYPE_FLAG_NULL      =  0x2,
     TYPE_FLAG_BOOLEAN   =  0x4,
     TYPE_FLAG_INT32     =  0x8,
@@ -1251,23 +1251,26 @@ struct TypeObjectKey {
 
     const Class *clasp();
     TaggedProto proto();
     JSObject *singleton();
     TypeNewScript *newScript();
 
     bool unknownProperties();
     bool hasFlags(CompilerConstraintList *constraints, TypeObjectFlags flags);
-    void watchStateChange(CompilerConstraintList *constraints);
+    void watchStateChangeForInlinedCall(CompilerConstraintList *constraints);
+    void watchStateChangeForNewScriptTemplate(CompilerConstraintList *constraints);
+    void watchStateChangeForTypedArrayBuffer(CompilerConstraintList *constraints);
     HeapTypeSetKey property(jsid id);
 };
 
 class HeapTypeSetKey
 {
   public:
+    TypeObject *actualObject;
     HeapTypeSet *actualTypes;
 
     void freeze(CompilerConstraintList *constraints);
     JSValueType knownTypeTag(CompilerConstraintList *constraints);
     bool configured(CompilerConstraintList *constraints, TypeObjectKey *type);
     bool notEmpty(CompilerConstraintList *constraints);
     bool knownSubset(CompilerConstraintList *constraints, const HeapTypeSetKey &other);
     JSObject *singleton(CompilerConstraintList *constraints);
--- a/js/src/jsiter.cpp
+++ b/js/src/jsiter.cpp
@@ -802,17 +802,17 @@ iterator_next_impl(JSContext *cx, CallAr
     if (!args.rval().toBoolean()) {
         js_ThrowStopIteration(cx);
         return false;
     }
 
     return js_IteratorNext(cx, thisObj, args.rval());
 }
 
-bool
+static bool
 iterator_next(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsIterator, iterator_next_impl>(cx, args);
 }
 
 static const JSFunctionSpec iterator_methods[] = {
     JS_SELF_HOSTED_FN("@@iterator", "LegacyIteratorShim", 0, 0),
@@ -867,17 +867,17 @@ const Class PropertyIteratorObject::clas
     trace,
     {
         nullptr,             /* outerObject    */
         nullptr,             /* innerObject    */
         iterator_iteratorObject,
     }
 };
 
-const uint32_t CLOSED_INDEX = UINT32_MAX;
+static const uint32_t CLOSED_INDEX = UINT32_MAX;
 
 JSObject *
 ElementIteratorObject::create(JSContext *cx, Handle<Value> target)
 {
     RootedObject proto(cx, cx->global()->getOrCreateElementIteratorPrototype(cx));
     if (!proto)
         return nullptr;
     RootedObject iterobj(cx, NewObjectWithGivenProto(cx, &class_, proto, cx->global()));
--- a/js/src/jsmath.cpp
+++ b/js/src/jsmath.cpp
@@ -895,17 +895,17 @@ js::math_tan(JSContext *cx, unsigned arg
     args.rval().setDouble(z);
     return true;
 }
 
 
 typedef double (*UnaryMathFunctionType)(MathCache *cache, double);
 
 template <UnaryMathFunctionType F>
-bool math_function(JSContext *cx, unsigned argc, Value *vp)
+static bool math_function(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     if (args.length() == 0) {
         args.rval().setNumber(GenericNaN());
         return true;
     }
 
     double x;
@@ -1362,17 +1362,17 @@ js::math_trunc_uncached(double x)
 }
 
 bool
 js::math_trunc(JSContext *cx, unsigned argc, Value *vp)
 {
     return math_function<math_trunc_impl>(cx, argc, vp);
 }
 
-double sign(double x)
+static double sign(double x)
 {
     if (mozilla::IsNaN(x))
         return GenericNaN();
 
     return x == 0 ? x : x < 0 ? -1 : 1;
 }
 
 double
--- a/js/src/jsnum.cpp
+++ b/js/src/jsnum.cpp
@@ -489,17 +489,17 @@ Number(JSContext *cx, unsigned argc, Val
 }
 
 JS_ALWAYS_INLINE bool
 IsNumber(HandleValue v)
 {
     return v.isNumber() || (v.isObject() && v.toObject().is<NumberObject>());
 }
 
-inline double
+static inline double
 Extract(const Value &v)
 {
     if (v.isNumber())
         return v.toNumber();
     return v.toObject().as<NumberObject>().unbox();
 }
 
 #if JS_HAS_TOSOURCE
@@ -848,17 +848,17 @@ num_toLocaleString_impl(JSContext *cx, C
     js_free(buf);
     if (!str)
         return false;
 
     args.rval().setString(str);
     return true;
 }
 
-bool
+static bool
 num_toLocaleString(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsNumber, num_toLocaleString_impl>(cx, args);
 }
 #endif /* !EXPOSE_INTL_API */
 
 JS_ALWAYS_INLINE bool
@@ -871,17 +871,17 @@ num_valueOf_impl(JSContext *cx, CallArgs
 
 bool
 js_num_valueOf(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsNumber, num_valueOf_impl>(cx, args);
 }
 
-const unsigned MAX_PRECISION = 100;
+static const unsigned MAX_PRECISION = 100;
 
 static bool
 ComputePrecisionInRange(JSContext *cx, int minPrecision, int maxPrecision, HandleValue v,
                         int *precision)
 {
     double prec;
     if (!ToInteger(cx, v, &prec))
         return false;
@@ -927,17 +927,17 @@ num_toFixed_impl(JSContext *cx, CallArgs
     } else {
         if (!ComputePrecisionInRange(cx, -20, MAX_PRECISION, args[0], &precision))
             return false;
     }
 
     return DToStrResult(cx, Extract(args.thisv()), DTOSTR_FIXED, precision, args);
 }
 
-bool
+static bool
 num_toFixed(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsNumber, num_toFixed_impl>(cx, args);
 }
 
 JS_ALWAYS_INLINE bool
 num_toExponential_impl(JSContext *cx, CallArgs args)
@@ -953,17 +953,17 @@ num_toExponential_impl(JSContext *cx, Ca
         mode = DTOSTR_EXPONENTIAL;
         if (!ComputePrecisionInRange(cx, 0, MAX_PRECISION, args[0], &precision))
             return false;
     }
 
     return DToStrResult(cx, Extract(args.thisv()), mode, precision + 1, args);
 }
 
-bool
+static bool
 num_toExponential(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsNumber, num_toExponential_impl>(cx, args);
 }
 
 JS_ALWAYS_INLINE bool
 num_toPrecision_impl(JSContext *cx, CallArgs args)
@@ -991,17 +991,17 @@ num_toPrecision_impl(JSContext *cx, Call
         mode = DTOSTR_PRECISION;
         if (!ComputePrecisionInRange(cx, 1, MAX_PRECISION, args[0], &precision))
             return false;
     }
 
     return DToStrResult(cx, d, mode, precision, args);
 }
 
-bool
+static bool
 num_toPrecision(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsNumber, num_toPrecision_impl>(cx, args);
 }
 
 static const JSFunctionSpec number_methods[] = {
 #if JS_HAS_TOSOURCE
@@ -1122,17 +1122,17 @@ static JSConstDoubleSpec number_constant
 
 #if (defined __GNUC__ && defined __i386__) || \
     (defined __SUNPRO_CC && defined __i386)
 
 /*
  * Set the exception mask to mask all exceptions and set the FPU precision
  * to 53 bit mantissa (64 bit doubles).
  */
-inline void FIX_FPU() {
+static inline void FIX_FPU() {
     short control;
     asm("fstcw %0" : "=m" (control) : );
     control &= ~0x300; // Lower bits 8 and 9 (precision control).
     control |= 0x2f3;  // Raise bits 0-5 (exception masks) and 9 (64-bit precision).
     asm("fldcw %0" : : "m" (control) );
 }
 
 #else
--- a/js/src/jsobj.cpp
+++ b/js/src/jsobj.cpp
@@ -2812,28 +2812,28 @@ JSObject::maybeDensifySparseElements(js:
      * to grow the object.
      */
     if (!obj->clearFlag(cx, BaseShape::INDEXED))
         return ED_FAILED;
 
     return ED_OK;
 }
 
-ObjectElements *
+static ObjectElements *
 AllocateElements(ThreadSafeContext *cx, JSObject *obj, uint32_t nelems)
 {
 #ifdef JSGC_GENERATIONAL
     if (cx->isJSContext())
         return cx->asJSContext()->runtime()->gcNursery.allocateElements(cx->asJSContext(), obj, nelems);
 #endif
 
     return static_cast<js::ObjectElements *>(cx->malloc_(nelems * sizeof(HeapValue)));
 }
 
-ObjectElements *
+static ObjectElements *
 ReallocateElements(ThreadSafeContext *cx, JSObject *obj, ObjectElements *oldHeader,
                    uint32_t oldCount, uint32_t newCount)
 {
 #ifdef JSGC_GENERATIONAL
     if (cx->isJSContext()) {
         return cx->asJSContext()->runtime()-> gcNursery.reallocateElements(cx->asJSContext(), obj, oldHeader,
                                                                            oldCount, newCount);
     }
@@ -5376,17 +5376,17 @@ js_GetterOnlyPropertyStub(JSContext *cx,
 #ifdef DEBUG
 
 /*
  * Routines to print out values during debugging.  These are FRIEND_API to help
  * the debugger find them and to support temporarily hacking js_Dump* calls
  * into other code.
  */
 
-void
+static void
 dumpValue(const Value &v)
 {
     if (v.isNull())
         fprintf(stderr, "null");
     else if (v.isUndefined())
         fprintf(stderr, "undefined");
     else if (v.isInt32())
         fprintf(stderr, "%d", v.toInt32());
--- a/js/src/jsstr.cpp
+++ b/js/src/jsstr.cpp
@@ -503,17 +503,17 @@ str_toSource_impl(JSContext *cx, CallArg
 
     str = sb.finishString();
     if (!str)
         return false;
     args.rval().setString(str);
     return true;
 }
 
-bool
+static bool
 str_toSource(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsString, str_toSource_impl>(cx, args);
 }
 
 #endif /* JS_HAS_TOSOURCE */
 
@@ -534,17 +534,17 @@ js_str_toString(JSContext *cx, unsigned 
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsString, str_toString_impl>(cx, args);
 }
 
 /*
  * Java-like string native methods.
  */
 
-JS_ALWAYS_INLINE bool
+static JS_ALWAYS_INLINE bool
 ValueToIntegerRange(JSContext *cx, HandleValue v, int32_t *out)
 {
     if (v.isInt32()) {
         *out = v.toInt32();
     } else {
         double d;
         if (!ToInteger(cx, v, &d))
             return false;
--- a/js/src/jsutil.h
+++ b/js/src/jsutil.h
@@ -191,17 +191,17 @@ ComputeByteAlignment(T bytes, U alignmen
 
 template <typename T, typename U>
 static inline T
 AlignBytes(T bytes, U alignment)
 {
     return bytes + ComputeByteAlignment(bytes, alignment);
 }
 
-JS_ALWAYS_INLINE static size_t
+static JS_ALWAYS_INLINE size_t
 UnsignedPtrDiff(const void *bigger, const void *smaller)
 {
     return size_t(bigger) - size_t(smaller);
 }
 
 /*****************************************************************************/
 
 /* A bit array is an array of bits represented by an array of words (size_t). */
--- a/js/src/jswatchpoint.cpp
+++ b/js/src/jswatchpoint.cpp
@@ -45,65 +45,66 @@ class AutoEntryHolder {
             p = map.lookup(WatchKey(obj, id));
         if (p)
             p->value.held = false;
     }
 };
 
 } /* anonymous namespace */
 
+/*
+ * Watchpoint contains a RelocatablePtrObject member, which is conceptually a
+ * heap-only class. It's preferable not to allocate these on the stack as they
+ * cause unnecessary adding and removal of store buffer entries, so
+ * WatchpointStackValue can be used instead.
+ */
+struct js::WatchpointStackValue {
+    JSWatchPointHandler handler;
+    HandleObject closure;
+    bool held;
+
+    WatchpointStackValue(JSWatchPointHandler handler, HandleObject closure, bool held)
+      : handler(handler), closure(closure), held(held) {}
+};
+
+inline js::Watchpoint::Watchpoint(const js::WatchpointStackValue& w)
+  : handler(w.handler), closure(w.closure), held(w.held) {}
+
+inline js::Watchpoint &js::Watchpoint::operator=(const js::WatchpointStackValue& w) {
+    handler = w.handler;
+    closure = w.closure;
+    held = w.held;
+    return *this;
+}
+
 bool
 WatchpointMap::init()
 {
     return map.init();
 }
 
-#ifdef JSGC_GENERATIONAL
-void
-Mark(JSTracer *trc, WatchKey *key, const char *name)
-{
-    MarkId(trc, &key->id, "WatchKey id");
-    MarkObject(trc, &key->object, "WatchKey id");
-}
-#endif
-
-static void
-WatchpointWriteBarrierPost(JSRuntime *rt, WatchpointMap::Map *map, const WatchKey &key,
-                           const Watchpoint &val)
-{
-#ifdef JSGC_GENERATIONAL
-    if ((JSID_IS_OBJECT(key.id) && IsInsideNursery(rt, JSID_TO_OBJECT(key.id))) ||
-        (JSID_IS_STRING(key.id) && IsInsideNursery(rt, JSID_TO_STRING(key.id))) ||
-        IsInsideNursery(rt, key.object) ||
-        IsInsideNursery(rt, val.closure))
-    {
-        typedef HashKeyRef<WatchpointMap::Map, WatchKey> WatchKeyRef;
-        rt->gcStoreBuffer.putGeneric(WatchKeyRef(map, key));
-    }
-#endif
-}
-
 bool
 WatchpointMap::watch(JSContext *cx, HandleObject obj, HandleId id,
                      JSWatchPointHandler handler, HandleObject closure)
 {
     JS_ASSERT(JSID_IS_STRING(id) || JSID_IS_INT(id));
 
     if (!obj->setWatched(cx))
         return false;
 
-    Watchpoint w;
-    w.handler = handler;
-    w.closure = closure;
-    w.held = false;
+    WatchpointStackValue w(handler, closure, false);
     if (!map.put(WatchKey(obj, id), w)) {
         js_ReportOutOfMemory(cx);
         return false;
     }
-    WatchpointWriteBarrierPost(cx->runtime(), &map, WatchKey(obj, id), w);
+    /*
+     * For generational GC, we don't need to post-barrier writes to the
+     * hashtable here because we mark all watchpoints as part of root marking in
+     * markAll().
+     */
     return true;
 }
 
 void
 WatchpointMap::unwatch(JSObject *obj, jsid id,
                        JSWatchPointHandler *handlerp, JSObject **closurep)
 {
     if (Map::Ptr p = map.lookup(WatchKey(obj, id))) {
@@ -216,17 +217,17 @@ WatchpointMap::markAll(JSTracer *trc)
         JS_ASSERT(JSID_IS_STRING(prior.id) || JSID_IS_INT(prior.id));
 
         MarkObject(trc, const_cast<EncapsulatedPtrObject *>(&key.object),
                    "held Watchpoint object");
         MarkId(trc, const_cast<EncapsulatedId *>(&key.id), "WatchKey::id");
         MarkObject(trc, &entry.value.closure, "Watchpoint::closure");
 
         if (prior.object != key.object || prior.id != key.id)
-            e.rekeyFront(prior, key);
+            e.rekeyFront(key);
     }
 }
 
 void
 WatchpointMap::sweepAll(JSRuntime *rt)
 {
     for (GCCompartmentsIter c(rt); !c.done(); c.next()) {
         if (WatchpointMap *wpmap = c->watchpointMap)
@@ -234,17 +235,17 @@ WatchpointMap::sweepAll(JSRuntime *rt)
     }
 }
 
 void
 WatchpointMap::sweep()
 {
     for (Map::Enum e(map); !e.empty(); e.popFront()) {
         Map::Entry &entry = e.front();
-        RelocatablePtrObject obj(entry.key.object);
+        JSObject *obj(entry.key.object);
         if (IsObjectAboutToBeFinalized(&obj)) {
             JS_ASSERT(!entry.value.held);
             e.removeFront();
         } else if (obj != entry.key.object) {
             e.rekeyFront(WatchKey(obj, entry.key.id));
         }
     }
 }
--- a/js/src/jswatchpoint.h
+++ b/js/src/jswatchpoint.h
@@ -24,20 +24,24 @@ struct WatchKey {
     EncapsulatedPtrObject object;
     EncapsulatedId id;
 
     bool operator!=(const WatchKey &other) const {
         return object != other.object || id != other.id;
     }
 };
 
+struct WatchpointStackValue;
 struct Watchpoint {
     JSWatchPointHandler handler;
     RelocatablePtrObject closure;
     bool held;  /* true if currently running handler */
+
+    inline Watchpoint(const WatchpointStackValue& w);
+    inline Watchpoint &operator=(const WatchpointStackValue& w);
 };
 
 template <>
 struct DefaultHasher<WatchKey>
 {
     typedef WatchKey Lookup;
     static inline js::HashNumber hash(const Lookup &key);
 
--- a/js/src/perf/jsperf.cpp
+++ b/js/src/perf/jsperf.cpp
@@ -91,26 +91,26 @@ pm_canMeasureSomething(JSContext* cx, un
     PerfMeasurement* p = GetPM(cx, args.thisv(), "canMeasureSomething");
     if (!p)
         return false;
 
     args.rval().setBoolean(p->canMeasureSomething());
     return true;
 }
 
-const uint8_t PM_FATTRS = JSPROP_READONLY | JSPROP_PERMANENT;
+static const uint8_t PM_FATTRS = JSPROP_READONLY | JSPROP_PERMANENT;
 static const JSFunctionSpec pm_fns[] = {
     JS_FN("start",               pm_start,               0, PM_FATTRS),
     JS_FN("stop",                pm_stop,                0, PM_FATTRS),
     JS_FN("reset",               pm_reset,               0, PM_FATTRS),
     JS_FN("canMeasureSomething", pm_canMeasureSomething, 0, PM_FATTRS),
     JS_FS_END
 };
 
-const uint8_t PM_PATTRS =
+static const uint8_t PM_PATTRS =
     JSPROP_ENUMERATE | JSPROP_PERMANENT;
 
 #define GETTER(name)                            \
     JS_PSG(#name, pm_get_##name, PM_PATTRS)
 
 static const JSPropertySpec pm_props[] = {
     GETTER(cpu_cycles),
     GETTER(instructions),
@@ -126,17 +126,17 @@ static const JSPropertySpec pm_props[] =
     GETTER(eventsMeasured),
     JS_PS_END
 };
 
 #undef GETTER
 
 // If this were C++ these would be "static const" members.
 
-const uint8_t PM_CATTRS = JSPROP_ENUMERATE|JSPROP_READONLY|JSPROP_PERMANENT;
+static const uint8_t PM_CATTRS = JSPROP_ENUMERATE|JSPROP_READONLY|JSPROP_PERMANENT;
 
 #define CONSTANT(name) { #name, PerfMeasurement::name }
 
 static const struct pm_const {
     const char *name;
     PerfMeasurement::EventMask value;
 } pm_consts[] = {
     CONSTANT(CPU_CYCLES),
--- a/js/src/vm/Debugger.cpp
+++ b/js/src/vm/Debugger.cpp
@@ -80,17 +80,17 @@ extern const Class DebuggerSource_class;
 enum {
     JSSLOT_DEBUGSOURCE_OWNER,
     JSSLOT_DEBUGSOURCE_COUNT
 };
 
 
 /*** Utils ***************************************************************************************/
 
-bool
+static bool
 ReportMoreArgsNeeded(JSContext *cx, const char *name, unsigned required)
 {
     JS_ASSERT(required > 0);
     JS_ASSERT(required <= 10);
     char s[2];
     s[0] = '0' + (required - 1);
     s[1] = '\0';
     JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED,
@@ -99,24 +99,24 @@ ReportMoreArgsNeeded(JSContext *cx, cons
 }
 
 #define REQUIRE_ARGC(name, n)                                                 \
     JS_BEGIN_MACRO                                                            \
         if (argc < (n))                                                       \
             return ReportMoreArgsNeeded(cx, name, n);                         \
     JS_END_MACRO
 
-bool
+static bool
 ReportObjectRequired(JSContext *cx)
 {
     JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NOT_NONNULL_OBJECT);
     return false;
 }
 
-bool
+static bool
 ValueToIdentifier(JSContext *cx, HandleValue v, MutableHandleId id)
 {
     if (!ValueToId<CanGC>(cx, v, id))
         return false;
     if (!JSID_IS_ATOM(id) || !IsIdentifier(JSID_TO_ATOM(id))) {
         RootedValue val(cx, v);
         js_ReportValueErrorFlags(cx, JSREPORT_ERROR, JSMSG_UNEXPECTED_TYPE,
                                  JSDVG_SEARCH_STACK, val, NullPtr(), "not an identifier",
--- a/js/src/vm/Interpreter.cpp
+++ b/js/src/vm/Interpreter.cpp
@@ -220,17 +220,17 @@ NoSuchMethod(JSContext *cx, unsigned arg
     args[1].setObject(*argsobj);
     bool ok = Invoke(cx, args);
     vp[0] = args.rval();
     return ok;
 }
 
 #endif /* JS_HAS_NO_SUCH_METHOD */
 
-inline bool
+static inline bool
 GetPropertyOperation(JSContext *cx, StackFrame *fp, HandleScript script, jsbytecode *pc,
                      MutableHandleValue lval, MutableHandleValue vp)
 {
     JSOp op = JSOp(*pc);
 
     if (op == JSOP_LENGTH) {
         if (IsOptimizedArguments(fp, lval.address())) {
             vp.setInt32(fp->numActualArgs());
@@ -311,17 +311,17 @@ NameOperation(JSContext *cx, StackFrame 
 
     /* Kludge to allow (typeof foo == "undefined") tests. */
     JSOp op2 = JSOp(pc[JSOP_NAME_LENGTH]);
     if (op2 == JSOP_TYPEOF)
         return FetchName<true>(cx, scopeRoot, pobjRoot, nameRoot, shapeRoot, vp);
     return FetchName<false>(cx, scopeRoot, pobjRoot, nameRoot, shapeRoot, vp);
 }
 
-inline bool
+static inline bool
 SetPropertyOperation(JSContext *cx, HandleScript script, jsbytecode *pc, HandleValue lval,
                      HandleValue rval)
 {
     JS_ASSERT(*pc == JSOP_SETPROP);
 
     RootedObject obj(cx, ToObjectFromStack(cx, lval));
     if (!obj)
         return false;
@@ -1056,17 +1056,17 @@ FrameGuard::~FrameGuard()
  * If the callee is a strict mode function, then code implementing JSOP_THIS
  * in the interpreter and JITs will leave undefined as |this|. If funval is a
  * function not in strict mode, JSOP_THIS code replaces undefined with funval's
  * global.
  *
  * We set *vp to undefined early to reduce code size and bias this code for the
  * common and future-friendly cases.
  */
-inline bool
+static inline bool
 ComputeImplicitThis(JSContext *cx, HandleObject obj, MutableHandleValue vp)
 {
     vp.setUndefined();
 
     if (obj->is<GlobalObject>())
         return true;
 
     if (IsCacheableNonGlobalScope(obj))
--- a/js/src/vm/SelfHosting.cpp
+++ b/js/src/vm/SelfHosting.cpp
@@ -525,17 +525,17 @@ intrinsic_RuntimeDefaultLocale(JSContext
     RootedString jslocale(cx, JS_NewStringCopyZ(cx, locale));
     if (!jslocale)
         return false;
 
     args.rval().setString(jslocale);
     return true;
 }
 
-const JSFunctionSpec intrinsic_functions[] = {
+static const JSFunctionSpec intrinsic_functions[] = {
     JS_FN("ToObject",                intrinsic_ToObject,                1,0),
     JS_FN("ToInteger",               intrinsic_ToInteger,               1,0),
     JS_FN("IsCallable",              intrinsic_IsCallable,              1,0),
     JS_FN("ThrowError",              intrinsic_ThrowError,              4,0),
     JS_FN("AssertionFailed",         intrinsic_AssertionFailed,         1,0),
     JS_FN("SetScriptHints",          intrinsic_SetScriptHints,          2,0),
     JS_FN("MakeConstructible",       intrinsic_MakeConstructible,       1,0),
     JS_FN("MakeWrappable",           intrinsic_MakeWrappable,           1,0),
--- a/js/src/vm/Shape.cpp
+++ b/js/src/vm/Shape.cpp
@@ -674,17 +674,17 @@ JSObject::addPropertyInternal<ParallelEx
                                                  unsigned flags, int shortid, Shape **spp,
                                                  bool allowDictionary);
 
 /*
  * Check and adjust the new attributes for the shape to make sure that our
  * slot access optimizations are sound. It is responsibility of the callers to
  * enforce all restrictions from ECMA-262 v5 8.12.9 [[DefineOwnProperty]].
  */
-inline bool
+static inline bool
 CheckCanChangeAttrs(ThreadSafeContext *cx, JSObject *obj, Shape *shape, unsigned *attrsp)
 {
     if (shape->configurable())
         return true;
 
     /* A permanent property must stay permanent. */
     *attrsp |= JSPROP_PERMANENT;
 
--- a/js/xpconnect/loader/mozJSComponentLoader.cpp
+++ b/js/xpconnect/loader/mozJSComponentLoader.cpp
@@ -403,117 +403,117 @@ mozJSComponentLoader::LoadModule(FileLoc
     nsCOMPtr<nsIFile> file = aFile.GetBaseFile();
 
     nsCString spec;
     aFile.GetURIString(spec);
 
     nsCOMPtr<nsIURI> uri;
     nsresult rv = NS_NewURI(getter_AddRefs(uri), spec);
     if (NS_FAILED(rv))
-        return NULL;
+        return nullptr;
 
     if (!mInitialized) {
         rv = ReallyInit();
         if (NS_FAILED(rv))
-            return NULL;
+            return nullptr;
     }
 
     ModuleEntry* mod;
     if (mModules.Get(spec, &mod))
     return mod;
 
     nsAutoPtr<ModuleEntry> entry(new ModuleEntry);
 
     JSAutoRequest ar(mContext);
     RootedValue dummy(mContext);
     rv = ObjectForLocation(file, uri, &entry->obj,
                            &entry->location, false, &dummy);
     if (NS_FAILED(rv)) {
-        return NULL;
+        return nullptr;
     }
 
     nsCOMPtr<nsIXPConnect> xpc = do_GetService(kXPConnectServiceContractID,
                                                &rv);
     if (NS_FAILED(rv))
-        return NULL;
+        return nullptr;
 
     nsCOMPtr<nsIComponentManager> cm;
     rv = NS_GetComponentManager(getter_AddRefs(cm));
     if (NS_FAILED(rv))
-        return NULL;
+        return nullptr;
 
     JSCLContextHelper cx(mContext);
     JSAutoCompartment ac(cx, entry->obj);
 
     nsCOMPtr<nsIXPConnectJSObjectHolder> cm_holder;
     rv = xpc->WrapNative(cx, entry->obj, cm,
                          NS_GET_IID(nsIComponentManager),
                          getter_AddRefs(cm_holder));
 
     if (NS_FAILED(rv)) {
 #ifdef DEBUG_shaver
         fprintf(stderr, "WrapNative(%p,%p,nsIComponentManager) failed: %x\n",
                 (void *)(JSContext*)cx, (void *)mCompMgr, rv);
 #endif
-        return NULL;
+        return nullptr;
     }
 
     JSObject* cm_jsobj = cm_holder->GetJSObject();
     if (!cm_jsobj) {
 #ifdef DEBUG_shaver
         fprintf(stderr, "GetJSObject of ComponentManager failed\n");
 #endif
-        return NULL;
+        return nullptr;
     }
 
     nsCOMPtr<nsIXPConnectJSObjectHolder> file_holder;
     rv = xpc->WrapNative(cx, entry->obj, file,
                          NS_GET_IID(nsIFile),
                          getter_AddRefs(file_holder));
 
     if (NS_FAILED(rv)) {
-        return NULL;
+        return nullptr;
     }
 
     JSObject* file_jsobj = file_holder->GetJSObject();
     if (!file_jsobj) {
-        return NULL;
+        return nullptr;
     }
 
     JSCLAutoErrorReporterSetter aers(cx, xpc::SystemErrorReporter);
 
     RootedValue NSGetFactory_val(cx);
     if (!JS_GetProperty(cx, entry->obj, "NSGetFactory", &NSGetFactory_val) ||
         JSVAL_IS_VOID(NSGetFactory_val)) {
-        return NULL;
+        return nullptr;
     }
 
     if (JS_TypeOfValue(cx, NSGetFactory_val) != JSTYPE_FUNCTION) {
         nsAutoCString spec;
         uri->GetSpec(spec);
         JS_ReportError(cx, "%s has NSGetFactory property that is not a function",
                        spec.get());
-        return NULL;
+        return nullptr;
     }
 
     RootedObject jsGetFactoryObj(cx);
     if (!JS_ValueToObject(cx, NSGetFactory_val, &jsGetFactoryObj) ||
         !jsGetFactoryObj) {
         /* XXX report error properly */
-        return NULL;
+        return nullptr;
     }
 
     rv = xpc->WrapJS(cx, jsGetFactoryObj,
                      NS_GET_IID(xpcIJSGetFactory), getter_AddRefs(entry->getfactoryobj));
     if (NS_FAILED(rv)) {
         /* XXX report error properly */
 #ifdef DEBUG
         fprintf(stderr, "mJCL: couldn't get nsIModule from jsval\n");
 #endif
-        return NULL;
+        return nullptr;
     }
 
     // Cache this module for later
     mModules.Put(spec, entry);
 
     // Set the location information for the new global, so that tools like
     // about:memory may use that information
     if (!mReuseLoaderGlobal) {
@@ -987,17 +987,17 @@ mozJSComponentLoader::ObjectForLocation(
     }
 
     mThisObjects.Put(tableScript, obj);
 
     uint32_t oldopts = JS_GetOptions(cx);
     JS_SetOptions(cx, oldopts | (aPropagateExceptions ? JSOPTION_DONT_REPORT_UNCAUGHT : 0));
     bool ok = false;
     if (script) {
-        ok = JS_ExecuteScriptVersion(cx, obj, script, NULL, JSVERSION_LATEST);
+        ok = JS_ExecuteScriptVersion(cx, obj, script, nullptr, JSVERSION_LATEST);
     } else {
         jsval rval;
         ok = JS_CallFunction(cx, obj, function, 0, nullptr, &rval);
     }
     JS_SetOptions(cx, oldopts);
 
     if (!ok) {
         if (aPropagateExceptions) {
@@ -1045,17 +1045,17 @@ mozJSComponentLoader::UnloadModules()
 
         mLoaderGlobal = nullptr;
     }
 
     mInProgressImports.Clear();
     mImports.Clear();
     mThisObjects.Clear();
 
-    mModules.Enumerate(ClearModules, NULL);
+    mModules.Enumerate(ClearModules, nullptr);
 
     JS_DestroyContextNoGC(mContext);
     mContext = nullptr;
 
     mRuntimeService = nullptr;
 #ifdef DEBUG_shaver_off
     fprintf(stderr, "mJCL: UnloadAll(%d)\n", aWhen);
 #endif
--- a/js/xpconnect/loader/mozJSComponentLoader.h
+++ b/js/xpconnect/loader/mozJSComponentLoader.h
@@ -82,48 +82,48 @@ class mozJSComponentLoader : public mozi
     JSRuntime *mRuntime;
     JSContext *mContext;
 
     class ModuleEntry : public mozilla::Module
     {
     public:
         ModuleEntry() : mozilla::Module() {
             mVersion = mozilla::Module::kVersion;
-            mCIDs = NULL;
-            mContractIDs = NULL;
-            mCategoryEntries = NULL;
+            mCIDs = nullptr;
+            mContractIDs = nullptr;
+            mCategoryEntries = nullptr;
             getFactoryProc = GetFactory;
-            loadProc = NULL;
-            unloadProc = NULL;
+            loadProc = nullptr;
+            unloadProc = nullptr;
 
             obj = nullptr;
             location = nullptr;
         }
 
         ~ModuleEntry() {
             Clear();
         }
 
         void Clear() {
-            getfactoryobj = NULL;
+            getfactoryobj = nullptr;
 
             if (obj) {
                 JSAutoRequest ar(sSelf->mContext);
 
                 JSAutoCompartment ac(sSelf->mContext, obj);
 
                 JS_SetAllNonReservedSlotsToUndefined(sSelf->mContext, obj);
                 JS_RemoveObjectRoot(sSelf->mContext, &obj);
             }
 
             if (location)
                 NS_Free(location);
 
-            obj = NULL;
-            location = NULL;
+            obj = nullptr;
+            location = nullptr;
         }
 
         static already_AddRefed<nsIFactory> GetFactory(const mozilla::Module& module,
                                                        const mozilla::Module::CIDEntry& entry);
 
         nsCOMPtr<xpcIJSGetFactory> getfactoryobj;
         JSObject            *obj;
         char                *location;
--- a/js/xpconnect/public/SandboxPrivate.h
+++ b/js/xpconnect/public/SandboxPrivate.h
@@ -34,16 +34,16 @@ public:
 
     JSObject *GetGlobalJSObject()
     {
         return mGlobalJSObject;
     }
 
     void ForgetGlobalObject()
     {
-        mGlobalJSObject = NULL;
+        mGlobalJSObject = nullptr;
     }
 private:
     nsCOMPtr<nsIPrincipal> mPrincipal;
     JSObject *mGlobalJSObject;
 };
 
 #endif // __SANDBOXPRIVATE_H__
--- a/js/xpconnect/src/BackstagePass.h
+++ b/js/xpconnect/src/BackstagePass.h
@@ -27,17 +27,17 @@ public:
     return mPrincipal;
   }
 
   virtual JSObject* GetGlobalJSObject() {
     return mGlobal;
   }
 
   virtual void ForgetGlobalObject() {
-    mGlobal = NULL;
+    mGlobal = nullptr;
   }
 
   virtual void SetGlobalObject(JSObject* global) {
     mGlobal = global;
   }
 
   BackstagePass(nsIPrincipal *prin) :
     mPrincipal(prin)
--- a/js/xpconnect/src/Sandbox.cpp
+++ b/js/xpconnect/src/Sandbox.cpp
@@ -379,29 +379,29 @@ CloneNonReflectorsWrite(JSContext *cx, J
             return true;
         }
     }
 
     JS_ReportError(cx, "CloneNonReflectorsWrite error");
     return false;
 }
 
-const JSStructuredCloneCallbacks gForwarderStructuredCloneCallbacks = {
+static const JSStructuredCloneCallbacks gForwarderStructuredCloneCallbacks = {
     CloneNonReflectorsRead,
     CloneNonReflectorsWrite,
     nullptr
 };
 
 /*
  * This is a special structured cloning, that clones only non-reflectors.
  * The function assumes the cx is already entered the compartment we want
  * to clone to, and that if val is an object is from the compartment we
  * clone from.
  */
-bool
+static bool
 CloneNonReflectors(JSContext *cx, MutableHandleValue val)
 {
     JSAutoStructuredCloneBuffer buffer;
     AutoObjectVector rootedReflectors(cx);
     {
         // For parsing val we have to enter its compartment.
         // (unless it's a primitive)
         Maybe<JSAutoCompartment> ac;
@@ -591,17 +591,17 @@ sandbox_convert(JSContext *cx, HandleObj
 
 #define XPCONNECT_SANDBOX_CLASS_METADATA_SLOT (XPCONNECT_GLOBAL_EXTRA_SLOT_OFFSET)
 
 static const JSClass SandboxClass = {
     "Sandbox",
     XPCONNECT_GLOBAL_FLAGS_WITH_EXTRA_SLOTS(1),
     JS_PropertyStub,   JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
     sandbox_enumerate, sandbox_resolve, sandbox_convert,  sandbox_finalize,
-    NULL, NULL, NULL, NULL, TraceXPCGlobal
+    nullptr, nullptr, nullptr, nullptr, TraceXPCGlobal
 };
 
 static const JSFunctionSpec SandboxFunctions[] = {
     JS_FS("dump",    SandboxDump,    1,0),
     JS_FS("debug",   SandboxDebug,   1,0),
     JS_FS("importFunction", SandboxImport, 1,0),
     JS_FS_END
 };
@@ -1147,17 +1147,17 @@ GetPrincipalFromString(JSContext *cx, Ha
 /*
  * For sandbox constructor the first argument can be a principal object or
  * a script object principal (Document, Window).
  */
 static nsresult
 GetPrincipalOrSOP(JSContext *cx, HandleObject from, nsISupports **out)
 {
     MOZ_ASSERT(out);
-    *out = NULL;
+    *out = nullptr;
 
     nsXPConnect* xpc = nsXPConnect::XPConnect();
     nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
     xpc->GetWrappedNativeOfJSObject(cx, from,
                                     getter_AddRefs(wrapper));
 
     NS_ENSURE_TRUE(wrapper, NS_ERROR_INVALID_ARG);
 
@@ -1288,17 +1288,17 @@ GetObjPropFromOptions(JSContext *cx, Han
     MOZ_ASSERT(prop);
 
     RootedValue value(cx);
     bool found;
     nsresult rv = GetPropFromOptions(cx, from, name, &value, &found);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!found) {
-        *prop = NULL;
+        *prop = nullptr;
         return NS_OK;
     }
 
     NS_ENSURE_TRUE(value.isObject(), NS_ERROR_INVALID_ARG);
     *prop = &value.toObject();
     return NS_OK;
 }
 
@@ -1624,17 +1624,17 @@ xpc::EvalInSandbox(JSContext *cx, Handle
     }
     NS_ENSURE_TRUE(ok, NS_ERROR_FAILURE);
 
     // Whew!
     rval.set(v);
     return NS_OK;
 }
 
-bool
+static bool
 NonCloningFunctionForwarder(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     RootedValue v(cx, js::GetFunctionNativeReserved(&args.callee(), 0));
     MOZ_ASSERT(v.isObject(), "weird function");
 
     JSObject *obj = JS_THIS_OBJECT(cx, vp);
@@ -1643,17 +1643,17 @@ NonCloningFunctionForwarder(JSContext *c
     }
     return JS_CallFunctionValue(cx, obj, v, args.length(), args.array(), vp);
 }
 
 /*
  * Forwards the call to the exported function. Clones all the non reflectors, ignores
  * the |this| argument.
  */
-bool
+static bool
 CloningFunctionForwarder(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     RootedValue v(cx, js::GetFunctionNativeReserved(&args.callee(), 0));
     NS_ASSERTION(v.isObject(), "weird function");
     RootedObject origFunObj(cx, UncheckedUnwrap(&v.toObject()));
     {
@@ -1720,15 +1720,15 @@ nsresult
 xpc::SetSandboxMetadata(JSContext *cx, HandleObject sandbox, HandleValue metadataArg)
 {
     MOZ_ASSERT(NS_IsMainThread());
     MOZ_ASSERT(IsSandbox(sandbox));
 
     RootedValue metadata(cx);
 
     JSAutoCompartment ac(cx, sandbox);
-    if (!JS_StructuredClone(cx, metadataArg, metadata.address(), NULL, NULL))
+    if (!JS_StructuredClone(cx, metadataArg, metadata.address(), nullptr, nullptr))
         return NS_ERROR_UNEXPECTED;
 
     JS_SetReservedSlot(sandbox, XPCONNECT_SANDBOX_CLASS_METADATA_SLOT, metadata);
 
     return NS_OK;
 }
--- a/js/xpconnect/src/XPCComponents.cpp
+++ b/js/xpconnect/src/XPCComponents.cpp
@@ -1791,18 +1791,18 @@ struct MOZ_STACK_CLASS ExceptionArgParse
         /*
          * The Components.Exception takes a series of arguments, all of them
          * optional:
          *
          * Argument 0: Exception message (defaults to 'exception').
          * Argument 1: Result code (defaults to NS_ERROR_FAILURE) _or_ options
          *             object (see below).
          * Argument 2: Stack (defaults to the current stack, which we trigger
-         *                    by leaving this NULL in the parser).
-         * Argument 3: Optional user data (defaults to NULL).
+         *                    by leaving this nullptr in the parser).
+         * Argument 3: Optional user data (defaults to nullptr).
          *
          * To dig our way out of this clunky API, we now support passing an
          * options object as the second parameter (as opposed to a result code).
          * If this is the case, all subsequent arguments are ignored, and the
          * following properties are parsed out of the object (using the
          * associated default if the property does not exist):
          *
          *   result:    Result code (see argument 1).
@@ -2905,17 +2905,17 @@ class PreciseGCRunnable : public nsRunna
     : mCallback(aCallback), mShrinking(aShrinking) {}
 
     NS_IMETHOD Run()
     {
         JSRuntime* rt = nsXPConnect::GetRuntimeInstance()->Runtime();
 
         JSContext *cx;
         JSContext *iter = nullptr;
-        while ((cx = JS_ContextIterator(rt, &iter)) != NULL) {
+        while ((cx = JS_ContextIterator(rt, &iter)) != nullptr) {
             if (JS_IsRunning(cx)) {
                 return NS_DispatchToMainThread(this);
             }
         }
 
         JS::PrepareForFullGC(rt);
         if (mShrinking)
             JS::ShrinkingGC(rt, JS::gcreason::COMPONENT_UTILS);
@@ -3044,17 +3044,17 @@ nsXPCComponents_Utils::CreateArrayIn(con
     // first argument must be an object
     if (vobj.isPrimitive())
         return NS_ERROR_XPC_BAD_CONVERT_JS;
 
     RootedObject scope(cx, js::UncheckedUnwrap(&vobj.toObject()));
     RootedObject obj(cx);
     {
         JSAutoCompartment ac(cx, scope);
-        obj =  JS_NewArrayObject(cx, 0, NULL);
+        obj =  JS_NewArrayObject(cx, 0, nullptr);
         if (!obj)
             return NS_ERROR_FAILURE;
     }
 
     if (!JS_WrapObject(cx, obj.address()))
         return NS_ERROR_FAILURE;
 
     *rval = ObjectValue(*obj);
@@ -3144,17 +3144,17 @@ nsXPCComponents_Utils::IsDeadWrapper(con
 
 /* void recomputerWrappers(jsval vobj); */
 NS_IMETHODIMP
 nsXPCComponents_Utils::RecomputeWrappers(const jsval &vobj, JSContext *cx)
 {
     // Determine the compartment of the given object, if any.
     JSCompartment *c = vobj.isObject()
                        ? js::GetObjectCompartment(js::UncheckedUnwrap(&vobj.toObject()))
-                       : NULL;
+                       : nullptr;
 
     // If no compartment was given, recompute all.
     if (!c)
         js::RecomputeWrappers(cx, js::AllCompartments(), js::AllCompartments());
     // Otherwise, recompute wrappers for the given compartment.
     else
         js::RecomputeWrappers(cx, js::SingleCompartment(c), js::AllCompartments()) &&
         js::RecomputeWrappers(cx, js::AllCompartments(), js::SingleCompartment(c));
@@ -3256,24 +3256,24 @@ nsXPCComponents_Utils::CanGetProperty(co
 NS_IMETHODIMP
 nsXPCComponents_Utils::CanSetProperty(const nsIID * iid, const PRUnichar *propertyName, char **_retval)
 {
     // If you have to ask, then the answer is NO
     *_retval = nullptr;
     return NS_OK;
 }
 
-nsresult
+static nsresult
 GetBoolOption(JSContext* cx, uint32_t aOption, bool* aValue)
 {
     *aValue = !!(JS_GetOptions(cx) & aOption);
     return NS_OK;
 }
 
-nsresult
+static nsresult
 SetBoolOption(JSContext* cx, uint32_t aOption, bool aValue)
 {
     uint32_t options = JS_GetOptions(cx);
     if (aValue) {
         options |= aOption;
     } else {
         options &= ~aOption;
     }
--- a/js/xpconnect/src/XPCConvert.cpp
+++ b/js/xpconnect/src/XPCConvert.cpp
@@ -765,17 +765,17 @@ XPCConvert::JSData2Native(void* d, Handl
     }
     default:
         NS_ERROR("bad type");
         return false;
     }
     return true;
 }
 
-inline bool
+static inline bool
 CreateHolderIfNeeded(HandleObject obj, jsval* d,
                      nsIXPConnectJSObjectHolder** dest)
 {
     if (dest) {
         XPCJSObjectHolder* objHolder = XPCJSObjectHolder::newHolder(obj);
         if (!objHolder)
             return false;
 
--- a/js/xpconnect/src/XPCJSContextStack.cpp
+++ b/js/xpconnect/src/XPCJSContextStack.cpp
@@ -123,17 +123,17 @@ SafeFinalize(JSFreeOp *fop, JSObject* ob
     DestroyProtoAndIfaceCache(obj);
 }
 
 const JSClass xpc::SafeJSContextGlobalClass = {
     "global_for_XPCJSContextStack_SafeJSContext",
     XPCONNECT_GLOBAL_FLAGS,
     JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
     JS_EnumerateStub, SafeGlobalResolve, JS_ConvertStub, SafeFinalize,
-    NULL, NULL, NULL, NULL, TraceXPCGlobal
+    nullptr, nullptr, nullptr, nullptr, TraceXPCGlobal
 };
 
 JSContext*
 XPCJSContextStack::GetSafeJSContext()
 {
     if (mSafeJSContext)
         return mSafeJSContext;
 
--- a/js/xpconnect/src/XPCJSID.cpp
+++ b/js/xpconnect/src/XPCJSID.cpp
@@ -261,17 +261,17 @@ NS_METHOD GetSharedScriptableHelperForJS
 { 0x00000000, 0x0000, 0x0000,                                                 \
   { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }
 
 NS_DECL_CI_INTERFACE_GETTER(nsJSIID)
 NS_IMPL_CLASSINFO(nsJSIID, GetSharedScriptableHelperForJSIID,
                   nsIClassInfo::THREADSAFE, NULL_CID)
 
 NS_DECL_CI_INTERFACE_GETTER(nsJSCID)
-NS_IMPL_CLASSINFO(nsJSCID, NULL, nsIClassInfo::THREADSAFE, NULL_CID)
+NS_IMPL_CLASSINFO(nsJSCID, nullptr, nsIClassInfo::THREADSAFE, NULL_CID)
 
 void xpc_DestroyJSxIDClassObjects()
 {
     if (gClassObjectsWereInited) {
         NS_IF_RELEASE(NS_CLASSINFO_NAME(nsJSIID));
         NS_IF_RELEASE(NS_CLASSINFO_NAME(nsJSCID));
         NS_IF_RELEASE(gSharedScriptableHelperForJSIID);
 
@@ -702,19 +702,19 @@ GetIIDArg(uint32_t argc, const JS::Value
         iid = &NS_GET_IID(nsISupports);
 
     return iid;
 }
 
 static void
 GetWrapperObject(MutableHandleObject obj)
 {
-    obj.set(NULL);
+    obj.set(nullptr);
     nsXPConnect* xpc = nsXPConnect::XPConnect();
-    nsAXPCNativeCallContext *ccxp = NULL;
+    nsAXPCNativeCallContext *ccxp = nullptr;
     xpc->GetCurrentNativeCallContext(&ccxp);
     if (!ccxp)
         return;
 
     nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
     ccxp->GetCalleeWrapper(getter_AddRefs(wrapper));
     obj.set(wrapper->GetJSObject());
 }
--- a/js/xpconnect/src/XPCJSRuntime.cpp
+++ b/js/xpconnect/src/XPCJSRuntime.cpp
@@ -1747,17 +1747,17 @@ private:
 NS_MEMORY_REPORTER_MALLOC_SIZEOF_FUN(JSMallocSizeOf)
 
 namespace xpc {
 
 static nsresult
 ReportZoneStats(const JS::ZoneStats &zStats,
                 const xpc::ZoneStatsExtras &extras,
                 nsIMemoryReporterCallback *cb,
-                nsISupports *closure, size_t *gcTotalOut = NULL)
+                nsISupports *closure, size_t *gcTotalOut = nullptr)
 {
     const nsAutoCString& pathPrefix = extras.pathPrefix;
     size_t gcTotal = 0, sundriesGCHeap = 0, sundriesMallocHeap = 0;
 
     ZCREPORT_GC_BYTES(pathPrefix + NS_LITERAL_CSTRING("gc-heap-arena-admin"),
                       zStats.gcHeapArenaAdmin,
                       "Memory on the garbage-collected JavaScript "
                       "heap, within arenas, that is used (a) to hold internal "
@@ -1931,17 +1931,17 @@ ReportZoneStats(const JS::ZoneStats &zSt
 #   undef STRING_LENGTH
 }
 
 static nsresult
 ReportCompartmentStats(const JS::CompartmentStats &cStats,
                        const xpc::CompartmentStatsExtras &extras,
                        amIAddonManager *addonManager,
                        nsIMemoryReporterCallback *cb,
-                       nsISupports *closure, size_t *gcTotalOut = NULL)
+                       nsISupports *closure, size_t *gcTotalOut = nullptr)
 {
     static const nsDependentCString addonPrefix("explicit/add-ons/");
 
     size_t gcTotal = 0, sundriesGCHeap = 0, sundriesMallocHeap = 0;
     nsAutoCString cJSPathPrefix = extras.jsPathPrefix;
     nsAutoCString cDOMPathPrefix = extras.domPathPrefix;
 
     // Only attempt to prefix if we got a location and the path wasn't already
@@ -2814,17 +2814,18 @@ ReadSourceFromFilename(JSContext *cx, co
         rv = scriptStream->Read(reinterpret_cast<char *>(ptr), end - ptr, &bytesRead);
         if (NS_FAILED(rv))
             return rv;
         MOZ_ASSERT(bytesRead > 0, "stream promised more bytes before EOF");
         ptr += bytesRead;
     }
 
     nsString decoded;
-    rv = nsScriptLoader::ConvertToUTF16(scriptChannel, buf, rawLen, EmptyString(), NULL, decoded);
+    rv = nsScriptLoader::ConvertToUTF16(scriptChannel, buf, rawLen, EmptyString(),
+                                        nullptr, decoded);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Copy to JS engine.
     *len = decoded.Length();
     *src = static_cast<jschar *>(JS_malloc(cx, decoded.Length()*sizeof(jschar)));
     if (!*src)
         return NS_ERROR_FAILURE;
     memcpy(*src, decoded.get(), decoded.Length()*sizeof(jschar));
@@ -2832,17 +2833,17 @@ ReadSourceFromFilename(JSContext *cx, co
     return NS_OK;
 }
 
 // The JS engine calls this object's 'load' member function when it needs
 // the source for a chrome JS function. See the comment in the XPCJSRuntime
 // constructor.
 class XPCJSSourceHook: public js::SourceHook {
     bool load(JSContext *cx, const char *filename, jschar **src, size_t *length) {
-        *src = NULL;
+        *src = nullptr;
         *length = 0;
 
         if (!nsContentUtils::IsCallerChrome())
             return true;
 
         if (!filename)
             return true;
 
--- a/js/xpconnect/src/XPCMaps.cpp
+++ b/js/xpconnect/src/XPCMaps.cpp
@@ -114,19 +114,19 @@ JSObject2WrappedJSMap::ShutdownMarker()
 // static
 Native2WrappedNativeMap*
 Native2WrappedNativeMap::newMap(int size)
 {
     Native2WrappedNativeMap* map = new Native2WrappedNativeMap(size);
     if (map && map->mTable)
         return map;
     // Allocation of the map or the creation of its hash table has
-    // failed. This will cause a NULL deref later when we attempt to
-    // use the map, so we abort immediately to provide a more useful
-    // crash stack.
+    // failed. This will cause a nullptr deref later when we attempt
+    // to use the map, so we abort immediately to provide a more
+    // useful crash stack.
     NS_RUNTIMEABORT("Ran out of memory.");
     return nullptr;
 }
 
 Native2WrappedNativeMap::Native2WrappedNativeMap(int size)
 {
     mTable = PL_NewDHashTable(PL_DHashGetStubOps(), nullptr,
                               sizeof(Entry), size);
@@ -286,19 +286,19 @@ ClassInfo2NativeSetMap::ShallowSizeOfInc
 // static
 ClassInfo2WrappedNativeProtoMap*
 ClassInfo2WrappedNativeProtoMap::newMap(int size)
 {
     ClassInfo2WrappedNativeProtoMap* map = new ClassInfo2WrappedNativeProtoMap(size);
     if (map && map->mTable)
         return map;
     // Allocation of the map or the creation of its hash table has
-    // failed. This will cause a NULL deref later when we attempt to
-    // use the map, so we abort immediately to provide a more useful
-    // crash stack.
+    // failed. This will cause a nullptr deref later when we attempt
+    // to use the map, so we abort immediately to provide a more
+    // useful crash stack.
     NS_RUNTIMEABORT("Ran out of memory.");
     return nullptr;
 }
 
 ClassInfo2WrappedNativeProtoMap::ClassInfo2WrappedNativeProtoMap(int size)
 {
     mTable = PL_NewDHashTable(PL_DHashGetStubOps(), nullptr,
                               sizeof(Entry), size);
--- a/js/xpconnect/src/XPCModule.h
+++ b/js/xpconnect/src/XPCModule.h
@@ -31,21 +31,21 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(mozJSSubS
 NS_DEFINE_NAMED_CID(NS_JS_ID_CID);
 NS_DEFINE_NAMED_CID(NS_XPCONNECT_CID);
 NS_DEFINE_NAMED_CID(NS_XPCEXCEPTION_CID);
 NS_DEFINE_NAMED_CID(NS_SCRIPTERROR_CID);
 NS_DEFINE_NAMED_CID(MOZJSCOMPONENTLOADER_CID);
 NS_DEFINE_NAMED_CID(MOZ_JSSUBSCRIPTLOADER_CID);
 
 #define XPCONNECT_CIDENTRIES                                                  \
-  { &kNS_JS_ID_CID, false, NULL,  nsJSIDConstructor },                        \
-  { &kNS_XPCONNECT_CID, false, NULL,  nsIXPConnectConstructor },              \
-  { &kNS_SCRIPTERROR_CID, false, NULL, nsScriptErrorConstructor },            \
-  { &kMOZJSCOMPONENTLOADER_CID, false, NULL, mozJSComponentLoaderConstructor },\
-  { &kMOZ_JSSUBSCRIPTLOADER_CID, false, NULL, mozJSSubScriptLoaderConstructor },
+  { &kNS_JS_ID_CID, false, nullptr,  nsJSIDConstructor },                     \
+  { &kNS_XPCONNECT_CID, false, nullptr,  nsIXPConnectConstructor },           \
+  { &kNS_SCRIPTERROR_CID, false, nullptr, nsScriptErrorConstructor },         \
+  { &kMOZJSCOMPONENTLOADER_CID, false, nullptr, mozJSComponentLoaderConstructor },\
+  { &kMOZ_JSSUBSCRIPTLOADER_CID, false, nullptr, mozJSSubScriptLoaderConstructor },
 
 #define XPCONNECT_CONTRACTS                                                   \
   { XPC_ID_CONTRACTID, &kNS_JS_ID_CID },                                      \
   { XPC_XPCONNECT_CONTRACTID, &kNS_XPCONNECT_CID },                           \
   { XPC_CONTEXT_STACK_CONTRACTID, &kNS_XPCONNECT_CID },                       \
   { XPC_RUNTIME_CONTRACTID, &kNS_XPCONNECT_CID },                             \
   { NS_SCRIPTERROR_CONTRACTID, &kNS_SCRIPTERROR_CID },                        \
   { MOZJSCOMPONENTLOADER_CONTRACTID, &kMOZJSCOMPONENTLOADER_CID },            \
--- a/js/xpconnect/src/XPCQuickStubs.cpp
+++ b/js/xpconnect/src/XPCQuickStubs.cpp
@@ -259,17 +259,17 @@ ThrowCallFailed(JSContext *cx, nsresult 
 
 bool
 xpc_qsThrowGetterSetterFailed(JSContext *cx, nsresult rv, JSObject *obj,
                               jsid memberIdArg)
 {
     RootedId memberId(cx, memberIdArg);
     const char *ifaceName;
     GetMemberInfo(obj, memberId, &ifaceName);
-    return ThrowCallFailed(cx, rv, ifaceName, memberId, NULL);
+    return ThrowCallFailed(cx, rv, ifaceName, memberId, nullptr);
 }
 
 bool
 xpc_qsThrowGetterSetterFailed(JSContext *cx, nsresult rv, JSObject *objArg,
                               const char* memberName)
 {
     RootedObject obj(cx, objArg);
     JSString *str = JS_InternString(cx, memberName);
@@ -289,17 +289,17 @@ xpc_qsThrowGetterSetterFailed(JSContext 
 }
 
 bool
 xpc_qsThrowMethodFailed(JSContext *cx, nsresult rv, jsval *vp)
 {
     const char *ifaceName;
     RootedId memberId(cx);
     GetMethodInfo(cx, vp, &ifaceName, memberId.address());
-    return ThrowCallFailed(cx, rv, ifaceName, memberId, NULL);
+    return ThrowCallFailed(cx, rv, ifaceName, memberId, nullptr);
 }
 
 bool
 xpc_qsThrowMethodFailedWithCcx(XPCCallContext &ccx, nsresult rv)
 {
     ThrowBadResult(rv, ccx);
     return false;
 }
@@ -342,17 +342,17 @@ ThrowBadArg(JSContext *cx, nsresult rv, 
 }
 
 void
 xpc_qsThrowBadArg(JSContext *cx, nsresult rv, jsval *vp, unsigned paramnum)
 {
     const char *ifaceName;
     RootedId memberId(cx);
     GetMethodInfo(cx, vp, &ifaceName, memberId.address());
-    ThrowBadArg(cx, rv, ifaceName, memberId, NULL, paramnum);
+    ThrowBadArg(cx, rv, ifaceName, memberId, nullptr, paramnum);
 }
 
 void
 xpc_qsThrowBadArgWithCcx(XPCCallContext &ccx, nsresult rv, unsigned paramnum)
 {
     XPCThrower::ThrowBadParam(rv, paramnum, ccx);
 }
 
@@ -365,17 +365,17 @@ xpc_qsThrowBadArgWithDetails(JSContext *
 
 void
 xpc_qsThrowBadSetterValue(JSContext *cx, nsresult rv,
                           JSObject *obj, jsid propIdArg)
 {
     RootedId propId(cx, propIdArg);
     const char *ifaceName;
     GetMemberInfo(obj, propId, &ifaceName);
-    ThrowBadArg(cx, rv, ifaceName, propId, NULL, 0);
+    ThrowBadArg(cx, rv, ifaceName, propId, nullptr, 0);
 }
 
 void
 xpc_qsThrowBadSetterValue(JSContext *cx, nsresult rv,
                           JSObject *objArg, const char* propName)
 {
     RootedObject obj(cx, objArg);
     JSString *str = JS_InternString(cx, propName);
@@ -394,27 +394,27 @@ xpc_qsThrowBadSetterValue(JSContext *cx,
 
 bool
 xpc_qsGetterOnlyPropertyStub(JSContext *cx, HandleObject obj, HandleId id, bool strict,
                              MutableHandleValue vp)
 {
     return JS_ReportErrorFlagsAndNumber(cx,
                                         JSREPORT_WARNING | JSREPORT_STRICT |
                                         JSREPORT_STRICT_MODE_ERROR,
-                                        js_GetErrorMessage, NULL,
+                                        js_GetErrorMessage, nullptr,
                                         JSMSG_GETTER_ONLY);
 }
 
 bool
 xpc_qsGetterOnlyNativeStub(JSContext *cx, unsigned argc, jsval *vp)
 {
     return JS_ReportErrorFlagsAndNumber(cx,
                                         JSREPORT_WARNING | JSREPORT_STRICT |
                                         JSREPORT_STRICT_MODE_ERROR,
-                                        js_GetErrorMessage, NULL,
+                                        js_GetErrorMessage, nullptr,
                                         JSMSG_GETTER_ONLY);
 }
 
 xpc_qsDOMString::xpc_qsDOMString(JSContext *cx, jsval v, jsval *pval,
                                  StringificationBehavior nullBehavior,
                                  StringificationBehavior undefinedBehavior)
 {
     typedef implementation_type::char_traits traits;
@@ -491,17 +491,17 @@ getNative(nsISupports *idobj,
 {
     nsresult rv = idobj->QueryInterface(iid, ppThis);
     *pThisRef = static_cast<nsISupports*>(*ppThis);
     if (NS_SUCCEEDED(rv))
         *vp = OBJECT_TO_JSVAL(obj);
     return rv;
 }
 
-inline nsresult
+static inline nsresult
 getNativeFromWrapper(JSContext *cx,
                      XPCWrappedNative *wrapper,
                      const nsIID &iid,
                      void **ppThis,
                      nsISupports **pThisRef,
                      jsval *vp)
 {
     RootedObject obj(cx, wrapper->GetFlatJSObject());
@@ -761,17 +761,17 @@ xpc_qsJsvalToCharStr(JSContext *cx, jsva
 bool
 xpc_qsJsvalToWcharStr(JSContext *cx, jsval v, jsval *pval, const PRUnichar **pstr)
 {
     JSString *str;
 
     if (JSVAL_IS_STRING(v)) {
         str = JSVAL_TO_STRING(v);
     } else if (JSVAL_IS_VOID(v) || JSVAL_IS_NULL(v)) {
-        *pstr = NULL;
+        *pstr = nullptr;
         return true;
     } else {
         if (!(str = JS_ValueToString(cx, v)))
             return false;
         *pval = STRING_TO_JSVAL(str);  // Root the new string.
     }
 
     const jschar *chars = JS_GetStringCharsZ(cx, str);
--- a/js/xpconnect/src/XPCShellImpl.cpp
+++ b/js/xpconnect/src/XPCShellImpl.cpp
@@ -96,49 +96,49 @@ private:
 #define DoEndRequest(cx)   ((void)0)
 #endif
 
 static const char kXPConnectServiceContractID[] = "@mozilla.org/js/xpc/XPConnect;1";
 
 #define EXITCODE_RUNTIME_ERROR 3
 #define EXITCODE_FILE_NOT_FOUND 4
 
-FILE *gOutFile = NULL;
-FILE *gErrFile = NULL;
-FILE *gInFile = NULL;
+static FILE *gOutFile = nullptr;
+static FILE *gErrFile = nullptr;
+static FILE *gInFile = nullptr;
 
-int gExitCode = 0;
-bool gIgnoreReportedErrors = false;
-bool gQuitting = false;
+static int gExitCode = 0;
+static bool gIgnoreReportedErrors = false;
+static bool gQuitting = false;
 static bool reportWarnings = true;
 static bool compileOnly = false;
 
-JSPrincipals *gJSPrincipals = nullptr;
-nsAutoString *gWorkingDirectory = nullptr;
+static JSPrincipals *gJSPrincipals = nullptr;
+static nsAutoString *gWorkingDirectory = nullptr;
 
 static bool
 GetLocationProperty(JSContext *cx, HandleObject obj, HandleId id, MutableHandleValue vp)
 {
 #if !defined(XP_WIN) && !defined(XP_UNIX)
     //XXX: your platform should really implement this
     return false;
 #else
     JS::RootedScript script(cx);
-    JS_DescribeScriptedCaller(cx, &script, NULL);
+    JS_DescribeScriptedCaller(cx, &script, nullptr);
     const char *filename = JS_GetScriptFilename(cx, script);
 
     if (filename) {
         nsresult rv;
         nsCOMPtr<nsIXPConnect> xpc =
             do_GetService(kXPConnectServiceContractID, &rv);
 
 #if defined(XP_WIN)
         // convert from the system codepage to UTF-16
         int bufferSize = MultiByteToWideChar(CP_ACP, 0, filename,
-                                             -1, NULL, 0);
+                                             -1, nullptr, 0);
         nsAutoString filenameString;
         filenameString.SetLength(bufferSize);
         MultiByteToWideChar(CP_ACP, 0, filename,
                             -1, (LPWSTR)filenameString.BeginWriting(),
                             filenameString.Length());
         // remove the null terminator
         filenameString.SetLength(bufferSize - 1);
 
@@ -427,21 +427,21 @@ GCZeal(JSContext *cx, unsigned argc, jsv
 }
 #endif
 
 #ifdef DEBUG
 
 static bool
 DumpHeap(JSContext *cx, unsigned argc, jsval *vp)
 {
-    void* startThing = NULL;
+    void* startThing = nullptr;
     JSGCTraceKind startTraceKind = JSTRACE_OBJECT;
-    void *thingToFind = NULL;
+    void *thingToFind = nullptr;
     size_t maxDepth = (size_t)-1;
-    void *thingToIgnore = NULL;
+    void *thingToIgnore = nullptr;
     FILE *dumpFile;
     bool ok;
 
     jsval *argv = JS_ARGV(cx, vp);
     JS_SET_RVAL(cx, vp, JSVAL_VOID);
 
     vp = argv + 0;
     JSAutoByteString fileName;
@@ -562,17 +562,17 @@ static const struct JSOption {
 static uint32_t
 MapContextOptionNameToFlag(JSContext* cx, const char* name)
 {
     for (size_t i = 0; i < ArrayLength(js_options); ++i) {
         if (strcmp(name, js_options[i].name) == 0)
             return js_options[i].flag;
     }
 
-    char* msg = JS_sprintf_append(NULL,
+    char* msg = JS_sprintf_append(nullptr,
                                   "unknown option name '%s'."
                                   " The valid names are ", name);
     for (size_t i = 0; i < ArrayLength(js_options); ++i) {
         if (!msg)
             break;
         msg = JS_sprintf_append(msg, "%s%s", js_options[i].name,
                                 (i + 2 < ArrayLength(js_options)
                                  ? ", "
@@ -609,17 +609,17 @@ Options(JSContext *cx, unsigned argc, js
             return false;
         flag = MapContextOptionNameToFlag(cx,  opt.ptr());
         if (!flag)
             return false;
         optset |= flag;
     }
     optset = JS_ToggleOptions(cx, optset);
 
-    names = NULL;
+    names = nullptr;
     found = false;
     for (size_t i = 0; i < ArrayLength(js_options); i++) {
         if (js_options[i].flag & optset) {
             found = true;
             names = JS_sprintf_append(names, "%s%s",
                                       names ? "," : "", js_options[i].name);
             if (!names)
                 break;
@@ -748,17 +748,17 @@ File(JSContext *cx, unsigned argc, jsval
   if (NS_FAILED(rv)) {
     JS_ReportError(cx, "Could not wrap native object!");
     return false;
   }
 
   return true;
 }
 
-Value sScriptedOperationCallback = UndefinedValue();
+static Value sScriptedOperationCallback = UndefinedValue();
 
 static bool
 XPCShellOperationCallback(JSContext *cx)
 {
     // If no operation callback was set by script, no-op.
     if (sScriptedOperationCallback.isUndefined())
         return true;
 
@@ -904,27 +904,27 @@ env_enumerate(JSContext *cx, HandleObjec
     static bool reflected;
     char **evp, *name, *value;
     JSString *valstr;
     bool ok;
 
     if (reflected)
         return true;
 
-    for (evp = (char **)JS_GetPrivate(obj); (name = *evp) != NULL; evp++) {
+    for (evp = (char **)JS_GetPrivate(obj); (name = *evp) != nullptr; evp++) {
         value = strchr(name, '=');
         if (!value)
             continue;
         *value++ = '\0';
         valstr = JS_NewStringCopyZ(cx, value);
         if (!valstr) {
             ok = false;
         } else {
             ok = JS_DefineProperty(cx, obj, name, STRING_TO_JSVAL(valstr),
-                                   NULL, NULL, JSPROP_ENUMERATE);
+                                   nullptr, nullptr, JSPROP_ENUMERATE);
         }
         value[-1] = '=';
         if (!ok)
             return false;
     }
 
     reflected = true;
     return true;
@@ -947,17 +947,17 @@ env_resolve(JSContext *cx, HandleObject 
     if (!name)
         return false;
     const char *value = getenv(name.ptr());
     if (value) {
         valstr = JS_NewStringCopyZ(cx, value);
         if (!valstr)
             return false;
         if (!JS_DefinePropertyById(cx, obj, id, STRING_TO_JSVAL(valstr),
-                                   NULL, NULL, JSPROP_ENUMERATE)) {
+                                   nullptr, nullptr, JSPROP_ENUMERATE)) {
             return false;
         }
         objp.set(obj);
     }
     return true;
 }
 
 static const JSClass env_class = {
@@ -973,28 +973,28 @@ static const JSClass env_class = {
 typedef enum JSShellErrNum {
 #define MSG_DEF(name, number, count, exception, format) \
     name = number,
 #include "jsshell.msg"
 #undef MSG_DEF
     JSShellErr_Limit
 } JSShellErrNum;
 
-const JSErrorFormatString jsShell_ErrorFormatString[JSShellErr_Limit] = {
+static const JSErrorFormatString jsShell_ErrorFormatString[JSShellErr_Limit] = {
 #define MSG_DEF(name, number, count, exception, format) \
     { format, count } ,
 #include "jsshell.msg"
 #undef MSG_DEF
 };
 
 static const JSErrorFormatString *
 my_GetErrorMessage(void *userRef, const char *locale, const unsigned errorNumber)
 {
     if (errorNumber == 0 || errorNumber >= JSShellErr_Limit)
-        return NULL;
+        return nullptr;
 
     return &jsShell_ErrorFormatString[errorNumber];
 }
 
 static void
 ProcessFile(JSContext *cx, JS::Handle<JSObject*> obj, const char *filename, FILE *file,
             bool forceTTY)
 {
@@ -1072,17 +1072,17 @@ ProcessFile(JSContext *cx, JS::Handle<JS
                                                strlen(buffer), "typein", startline);
         if (script) {
             JSErrorReporter older;
 
             if (!compileOnly) {
                 ok = JS_ExecuteScript(cx, obj, script, result.address());
                 if (ok && result != JSVAL_VOID) {
                     /* Suppress error reports from JS_ValueToString(). */
-                    older = JS_SetErrorReporter(cx, NULL);
+                    older = JS_SetErrorReporter(cx, nullptr);
                     str = JS_ValueToString(cx, result);
                     JS_SetErrorReporter(cx, older);
                     JSAutoByteString bytes;
                     if (str && bytes.encodeLatin1(cx, str))
                         fprintf(gOutFile, "%s\n", bytes.ptr());
                     else
                         ok = false;
                 }
@@ -1099,17 +1099,17 @@ Process(JSContext *cx, JS::Handle<JSObje
 {
     FILE *file;
 
     if (forceTTY || !filename || strcmp(filename, "-") == 0) {
         file = stdin;
     } else {
         file = fopen(filename, "r");
         if (!file) {
-            JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL,
+            JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr,
                                  JSSMSG_CANT_OPEN,
                                  filename, strerror(errno));
             gExitCode = EXITCODE_FILE_NOT_FOUND;
             return;
         }
     }
 
     ProcessFile(cx, obj, filename, file, forceTTY);
@@ -1158,17 +1158,17 @@ ProcessArgsForCompartment(JSContext *cx,
 
 static int
 ProcessArgs(JSContext *cx, JS::Handle<JSObject*> obj, char **argv, int argc, XPCShellDirProvider* aDirProvider)
 {
     const char rcfilename[] = "xpcshell.js";
     FILE *rcfile;
     int i;
     JS::Rooted<JSObject*> argsObj(cx);
-    char *filename = NULL;
+    char *filename = nullptr;
     bool isInteractive = true;
     bool forceTTY = false;
 
     rcfile = fopen(rcfilename, "r");
     if (rcfile) {
         printf("[loading '%s'...]\n", rcfilename);
         ProcessFile(cx, obj, rcfilename, rcfile, false);
         fclose(rcfile);
@@ -1194,30 +1194,30 @@ ProcessArgs(JSContext *cx, JS::Handle<JS
           default:;
         }
     }
 
     /*
      * Create arguments early and define it to root it, so it's safe from any
      * GC calls nested below, and so it is available to -f <file> arguments.
      */
-    argsObj = JS_NewArrayObject(cx, 0, NULL);
+    argsObj = JS_NewArrayObject(cx, 0, nullptr);
     if (!argsObj)
         return 1;
     if (!JS_DefineProperty(cx, obj, "arguments", OBJECT_TO_JSVAL(argsObj),
-                           NULL, NULL, 0)) {
+                           nullptr, nullptr, 0)) {
         return 1;
     }
 
     for (size_t j = 0, length = argc - i; j < length; j++) {
         JSString *str = JS_NewStringCopyZ(cx, argv[i++]);
         if (!str)
             return 1;
         if (!JS_DefineElement(cx, argsObj, j, STRING_TO_JSVAL(str),
-                              NULL, NULL, JSPROP_ENUMERATE)) {
+                              nullptr, nullptr, JSPROP_ENUMERATE)) {
             return 1;
         }
     }
 
     for (i = 0; i < argc; i++) {
         if (argv[i][0] != '-' || argv[i][1] == '\0') {
             filename = argv[i++];
             isInteractive = false;
@@ -1378,17 +1378,17 @@ nsXPCFunctionThisTranslator::TranslateTh
 {
     NS_IF_ADDREF(aInitialThis);
     *_retval = aInitialThis;
     return NS_OK;
 }
 
 #endif
 
-void
+static void
 XPCShellErrorReporter(JSContext *cx, const char *message, JSErrorReport *rep)
 {
     if (gIgnoreReportedErrors)
         return;
 
     if (!JSREPORT_IS_WARNING(rep->flags))
         gExitCode = EXITCODE_RUNTIME_ERROR;
 
@@ -1406,17 +1406,17 @@ ContextCallback(JSContext *cx, unsigned 
 
 static bool
 GetCurrentWorkingDirectory(nsAString& workingDirectory)
 {
 #if !defined(XP_WIN) && !defined(XP_UNIX)
     //XXX: your platform should really implement this
     return false;
 #elif XP_WIN
-    DWORD requiredLength = GetCurrentDirectoryW(0, NULL);
+    DWORD requiredLength = GetCurrentDirectoryW(0, nullptr);
     workingDirectory.SetLength(requiredLength);
     GetCurrentDirectoryW(workingDirectory.Length(),
                          (LPWSTR)workingDirectory.BeginWriting());
     // we got a trailing null there
     workingDirectory.SetLength(requiredLength);
     workingDirectory.Replace(workingDirectory.Length() - 1, 1, L'\\');
 #elif defined(XP_UNIX)
     nsAutoCString cwd;
@@ -1669,30 +1669,30 @@ XRE_XPCShellMain(int argc, char **argv, 
 
             if (!JS_DefineFunctions(cx, glob, glob_functions) ||
                 !JS_DefineProfilingFunctions(cx, glob)) {
                 JS_EndRequest(cx);
                 return 1;
             }
 
             JS::Rooted<JSObject*> envobj(cx);
-            envobj = JS_DefineObject(cx, glob, "environment", &env_class, NULL, 0);
+            envobj = JS_DefineObject(cx, glob, "environment", &env_class, nullptr, 0);
             if (!envobj) {
                 JS_EndRequest(cx);
                 return 1;
             }
 
             JS_SetPrivate(envobj, envp);
 
             nsAutoString workingDirectory;
             if (GetCurrentWorkingDirectory(workingDirectory))
                 gWorkingDirectory = &workingDirectory;
 
             JS_DefineProperty(cx, glob, "__LOCATION__", JSVAL_VOID,
-                              GetLocationProperty, NULL, 0);
+                              GetLocationProperty, nullptr, 0);
 
             JS_AddValueRoot(cx, &sScriptedOperationCallback);
             result = ProcessArgs(cx, glob, argv, argc, &dirprovider);
             JS_RemoveValueRoot(cx, &sScriptedOperationCallback);
 
             JS_DropPrincipals(rt, gJSPrincipals);
             JS_SetAllNonReservedSlotsToUndefined(cx, glob);
             JS_GC(rt);
@@ -1701,17 +1701,17 @@ XRE_XPCShellMain(int argc, char **argv, 
         JS_GC(rt);
         JS_DestroyContext(cx);
     } // this scopes the nsCOMPtrs
 
     if (!XRE_ShutdownTestShell())
         NS_ERROR("problem shutting down testshell");
 
     // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
-    rv = NS_ShutdownXPCOM( NULL );
+    rv = NS_ShutdownXPCOM( nullptr );
     MOZ_ASSERT(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");
 
 #ifdef TEST_CALL_ON_WRAPPED_JS_AFTER_SHUTDOWN
     // test of late call and release (see above)
     JSContext* bogusCX;
     bogus->Peek(&bogusCX);
     bogus = nullptr;
 #endif
@@ -1800,17 +1800,17 @@ XPCShellDirProvider::GetFile(const char 
         // For xpcshell, we pretend that the update root directory is always
         // the same as the GRE directory, except for Windows, where we immitate
         // the algorithm defined in nsXREDirProvider::GetUpdateRootDir.
         *persistent = true;
 #ifdef XP_WIN
         char appData[MAX_PATH] = {'\0'};
         char path[MAX_PATH] = {'\0'};
         LPITEMIDLIST pItemIDList;
-        if (FAILED(SHGetSpecialFolderLocation(NULL, CSIDL_LOCAL_APPDATA, &pItemIDList)) ||
+        if (FAILED(SHGetSpecialFolderLocation(nullptr, CSIDL_LOCAL_APPDATA, &pItemIDList)) ||
             FAILED(SHGetPathFromIDListA(pItemIDList, appData))) {
             return NS_ERROR_FAILURE;
         }
         nsAutoString pathName;
         pathName.AssignASCII(appData);
         nsCOMPtr<nsIFile> localFile;
         nsresult rv = NS_NewLocalFile(pathName, true, getter_AddRefs(localFile));
         if (NS_FAILED(rv)) {
--- a/js/xpconnect/src/XPCVariant.cpp
+++ b/js/xpconnect/src/XPCVariant.cpp
@@ -11,17 +11,17 @@
 
 #include "jsfriendapi.h"
 #include "jsprf.h"
 #include "jswrapper.h"
 
 using namespace JS;
 using namespace mozilla;
 
-NS_IMPL_CLASSINFO(XPCVariant, NULL, 0, XPCVARIANT_CID)
+NS_IMPL_CLASSINFO(XPCVariant, nullptr, 0, XPCVARIANT_CID)
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(XPCVariant)
   NS_INTERFACE_MAP_ENTRY(XPCVariant)
   NS_INTERFACE_MAP_ENTRY(nsIVariant)
   NS_INTERFACE_MAP_ENTRY(nsISupports)
   NS_IMPL_QUERY_CLASSINFO(XPCVariant)
 NS_INTERFACE_MAP_END
 NS_IMPL_CI_INTERFACE_GETTER2(XPCVariant, XPCVariant, nsIVariant)
 
--- a/js/xpconnect/src/XPCWrappedJS.cpp
+++ b/js/xpconnect/src/XPCWrappedJS.cpp
@@ -342,17 +342,17 @@ nsXPCWrappedJS::GetNewOrUsed(JS::HandleO
                 XPCAutoLock lock(rt->GetMapLock());
                 map->Add(cx, root);
             }
 
             if (!CheckMainThreadOnly(root)) {
                 XPCAutoLock lock(rt->GetMapLock());
                 map->Remove(root);
 
-                wrapper = NULL;
+                wrapper = nullptr;
             }
 
             goto return_wrapper;
         } else {
             // just a root wrapper
             nsXPCWrappedJSClass* rootClazz = nullptr;
             nsXPCWrappedJSClass::GetNewOrUsed(cx, NS_GET_IID(nsISupports),
                                               &rootClazz);
--- a/js/xpconnect/src/XPCWrappedJSClass.cpp
+++ b/js/xpconnect/src/XPCWrappedJSClass.cpp
@@ -71,17 +71,17 @@ AutoScriptEvaluate::~AutoScriptEvaluate(
     if (mState)
         JS_RestoreExceptionState(mJSContext, mState);
     else
         JS_ClearPendingException(mJSContext);
 
     JS_EndRequest(mJSContext);
 
     if (mErrorReporterSet)
-        JS_SetErrorReporter(mJSContext, NULL);
+        JS_SetErrorReporter(mJSContext, nullptr);
 }
 
 // It turns out that some errors may be not worth reporting. So, this
 // function is factored out to manage that.
 bool xpc_IsReportableErrorCode(nsresult code)
 {
     if (NS_SUCCEEDED(code))
         return false;
@@ -1648,21 +1648,21 @@ static const JSClass XPCOutParamClass = 
     JS_PropertyStub,
     JS_DeletePropertyStub,
     JS_PropertyStub,
     JS_StrictPropertyStub,
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub,
     FinalizeStub,
-    NULL,   /* checkAccess */
-    NULL,   /* call */
-    NULL,   /* hasInstance */
-    NULL,   /* construct */
-    NULL    /* trace */
+    nullptr,   /* checkAccess */
+    nullptr,   /* call */
+    nullptr,   /* hasInstance */
+    nullptr,   /* construct */
+    nullptr    /* trace */
 };
 
 bool
 xpc::IsOutObject(JSContext* cx, JSObject* obj)
 {
     return js::GetObjectJSClass(obj) == &XPCOutParamClass;
 }
 
--- a/js/xpconnect/src/XPCWrappedNative.cpp
+++ b/js/xpconnect/src/XPCWrappedNative.cpp
@@ -830,20 +830,21 @@ XPCWrappedNative::Destroy()
             nsContentUtils::DeferredFinalize(mIdentity);
             mIdentity = nullptr;
         } else {
             NS_RELEASE(mIdentity);
         }
     }
 
     /*
-     * The only time GetRuntime() will be NULL is if Destroy is called a second
-     * time on a wrapped native. Since we already unregistered the pointer the
-     * first time, there's no need to unregister again. Unregistration is safe
-     * the first time because mWrapper isn't used afterwards.
+     * The only time GetRuntime() will be nullptr is if Destroy is called a
+     * second time on a wrapped native. Since we already unregistered the
+     * pointer the first time, there's no need to unregister again.
+     * Unregistration is safe the first time because mWrapper isn't used
+     * afterwards.
      */
     if (XPCJSRuntime *rt = GetRuntime()) {
         if (IsIncrementalBarrierNeeded(rt->Runtime()))
             IncrementalObjectBarrier(GetWrapperPreserveColor());
         mWrapper.setToCrashOnTouch();
     } else {
         MOZ_ASSERT(mWrapper.isSetToCrashOnTouch());
     }
@@ -1376,24 +1377,25 @@ XPCWrappedNative::ReparentWrapperIfFound
                                                aNewParent));
         if (!newobj)
             return NS_ERROR_FAILURE;
 
         // At this point, both |flat| and |newobj| point to the same wrapped
         // native, which is bad, because one of them will end up finalizing
         // a wrapped native it does not own. |cloneGuard| ensures that if we
         // exit before calling clearing |flat|'s private the private of
-        // |newobj| will be set to NULL. |flat| will go away soon, because
+        // |newobj| will be set to nullptr. |flat| will go away soon, because
         // we swap it with another object during the transplant and let that
         // object die.
         RootedObject propertyHolder(cx);
         {
             AutoClonePrivateGuard cloneGuard(cx, flat, newobj);
 
-            propertyHolder = JS_NewObjectWithGivenProto(cx, NULL, NULL, aNewParent);
+            propertyHolder = JS_NewObjectWithGivenProto(cx, nullptr, nullptr,
+                                                        aNewParent);
             if (!propertyHolder)
                 return NS_ERROR_OUT_OF_MEMORY;
             if (!JS_CopyPropertiesFrom(cx, propertyHolder, flat))
                 return NS_ERROR_FAILURE;
 
             // Expandos from other compartments are attached to the target JS object.
             // Copy them over, and let the old ones die a natural death.
             SetWNExpandoChain(newobj, nullptr);
@@ -1929,34 +1931,34 @@ XPCWrappedNative::GetSameCompartmentSecu
     // If we already have a wrapper, it must be what we want.
     if (wrapper)
         return wrapper;
 
     // Chrome callers don't need same-compartment security wrappers.
     JSCompartment *cxCompartment = js::GetContextCompartment(cx);
     MOZ_ASSERT(cxCompartment == js::GetObjectCompartment(flat));
     if (xpc::AccessCheck::isChrome(cxCompartment)) {
-        MOZ_ASSERT(wrapper == NULL);
+        MOZ_ASSERT(wrapper == nullptr);
         return flat;
     }
 
     // Check the possibilities. Note that we need to check for null in each
     // case in order to distinguish between the 'no need for wrapper' and
     // 'wrapping failed' cases.
     //
     // NB: We don't make SOWs for remote XUL domains where XBL scopes are
     // disallowed.
     if (NeedsSOW() && xpc::AllowXBLScope(js::GetContextCompartment(cx))) {
         wrapper = xpc::WrapperFactory::WrapSOWObject(cx, flat);
         if (!wrapper)
-            return NULL;
+            return nullptr;
     } else if (xpc::WrapperFactory::IsComponentsObject(flat)) {
         wrapper = xpc::WrapperFactory::WrapComponentsObject(cx, flat);
         if (!wrapper)
-            return NULL;
+            return nullptr;
     }
 
     // If we made a wrapper, cache it and return it.
     if (wrapper) {
         SetWrapper(wrapper);
         return wrapper;
     }
 
@@ -2886,22 +2888,16 @@ NS_IMETHODIMP XPCWrappedNative::FindInte
 NS_IMETHODIMP_(bool)
 XPCWrappedNative::HasNativeMember(HandleId name)
 {
     XPCNativeMember *member = nullptr;
     uint16_t ignored;
     return GetSet()->FindMember(name, &member, &ignored) && !!member;
 }
 
-inline nsresult UnexpectedFailure(nsresult rv)
-{
-    NS_ERROR("This is not supposed to fail!");
-    return rv;
-}
-
 /* void finishInitForWrappedGlobal (); */
 NS_IMETHODIMP XPCWrappedNative::FinishInitForWrappedGlobal()
 {
     // We can only be called under certain conditions.
     MOZ_ASSERT(mScriptableInfo);
     MOZ_ASSERT(mScriptableInfo->GetFlags().IsGlobalObject());
     MOZ_ASSERT(HasProto());
 
--- a/js/xpconnect/src/nsDOMQS.h
+++ b/js/xpconnect/src/nsDOMQS.h
@@ -71,17 +71,17 @@ xpc_qsUnwrapThis<_interface>(JSContext *
                              bool failureFatal)                               \
 {                                                                             \
     nsresult rv;                                                              \
     nsISupports *native =                                                     \
         castNativeFromWrapper(cx, obj, _bit,                                  \
                               ProtoIDAndDepth<_interface>::PrototypeID,       \
                               ProtoIDAndDepth<_interface>::Depth,             \
                               pThisRef, pThisVal, &rv);                       \
-    *ppThis = NULL;  /* avoids uninitialized warnings in callers */           \
+    *ppThis = nullptr;  /* avoids uninitialized warnings in callers */        \
     if (failureFatal && !native)                                              \
         return xpc_qsThrow(cx, rv);                                           \
     *ppThis = static_cast<_interface*>(static_cast<_base*>(native));          \
     return true;                                                              \
 }                                                                             \
                                                                               \
 template <>                                                                   \
 MOZ_ALWAYS_INLINE nsresult                                                    \
--- a/js/xpconnect/src/nsXPConnect.cpp
+++ b/js/xpconnect/src/nsXPConnect.cpp
@@ -328,17 +328,17 @@ xpc_TryUnmarkWrappedGrayObject(nsISuppor
         static_cast<nsXPCWrappedJS*>(wjs.get())->GetJSObject();
     }
 }
 
 /***************************************************************************/
 /***************************************************************************/
 // nsIXPConnect interface methods...
 
-inline nsresult UnexpectedFailure(nsresult rv)
+static inline nsresult UnexpectedFailure(nsresult rv)
 {
     NS_ERROR("This is not supposed to fail!");
     return rv;
 }
 
 /* void initClasses (in JSContextPtr aJSContext, in JSObjectPtr aGlobalJSObj); */
 NS_IMETHODIMP
 nsXPConnect::InitClasses(JSContext * aJSContext, JSObject * aGlobalJSObj)
@@ -1437,45 +1437,45 @@ nsXPConnect::SetDebugModeWhenPossible(bo
     if (!mode && allowSyncDisable)
         CheckForDebugMode(mRuntime->Runtime());
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXPConnect::GetTelemetryValue(JSContext *cx, jsval *rval)
 {
-    RootedObject obj(cx, JS_NewObject(cx, NULL, NULL, NULL));
+    RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
     if (!obj)
         return NS_ERROR_OUT_OF_MEMORY;
 
     unsigned attrs = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT;
 
     size_t i = JS_SetProtoCalled(cx);
     RootedValue v(cx, DOUBLE_TO_JSVAL(i));
-    if (!JS_DefineProperty(cx, obj, "setProto", v, NULL, NULL, attrs))
+    if (!JS_DefineProperty(cx, obj, "setProto", v, nullptr, nullptr, attrs))
         return NS_ERROR_OUT_OF_MEMORY;
 
     i = JS_GetCustomIteratorCount(cx);
     v = DOUBLE_TO_JSVAL(i);
-    if (!JS_DefineProperty(cx, obj, "customIter", v, NULL, NULL, attrs))
+    if (!JS_DefineProperty(cx, obj, "customIter", v, nullptr, nullptr, attrs))
         return NS_ERROR_OUT_OF_MEMORY;
 
     *rval = OBJECT_TO_JSVAL(obj);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXPConnect::NotifyDidPaint()
 {
     JS::NotifyDidPaint(GetRuntime()->Runtime());
     return NS_OK;
 }
 
-const uint8_t HAS_PRINCIPALS_FLAG               = 1;
-const uint8_t HAS_ORIGIN_PRINCIPALS_FLAG        = 2;
+static const uint8_t HAS_PRINCIPALS_FLAG               = 1;
+static const uint8_t HAS_ORIGIN_PRINCIPALS_FLAG        = 2;
 
 static nsresult
 WriteScriptOrFunction(nsIObjectOutputStream *stream, JSContext *cx,
                       JSScript *scriptArg, HandleObject functionObj)
 {
     // Exactly one of script or functionObj must be given
     MOZ_ASSERT(!scriptArg != !functionObj);
 
--- a/js/xpconnect/src/xpcObjectHelper.h
+++ b/js/xpconnect/src/xpcObjectHelper.h
@@ -19,26 +19,26 @@
 #include "nsIClassInfo.h"
 #include "nsISupports.h"
 #include "nsIXPCScriptable.h"
 #include "nsWrapperCache.h"
 
 class xpcObjectHelper
 {
 public:
-    xpcObjectHelper(nsISupports *aObject, nsWrapperCache *aCache = NULL)
-      : mCanonical(NULL)
+    xpcObjectHelper(nsISupports *aObject, nsWrapperCache *aCache = nullptr)
+      : mCanonical(nullptr)
       , mObject(aObject)
       , mCache(aCache)
     {
         if (!mCache) {
             if (aObject)
                 CallQueryInterface(aObject, &mCache);
             else
-                mCache = NULL;
+                mCache = nullptr;
         }
     }
 
     nsISupports *Object()
     {
         return mObject;
     }
 
@@ -52,17 +52,17 @@ public:
     }
 
     already_AddRefed<nsISupports> forgetCanonical()
     {
         MOZ_ASSERT(mCanonical, "Huh, no canonical to forget?");
 
         if (!mCanonicalStrong)
             mCanonicalStrong = mCanonical;
-        mCanonical = NULL;
+        mCanonical = nullptr;
         return mCanonicalStrong.forget();
     }
 
     nsIClassInfo *GetClassInfo()
     {
         if (mXPCClassInfo)
           return mXPCClassInfo;
         if (!mClassInfo)
--- a/js/xpconnect/src/xpcprivate.h
+++ b/js/xpconnect/src/xpcprivate.h
@@ -3080,29 +3080,29 @@ bool PushJSContextNoScriptContext(JSCont
 void PopJSContextNoScriptContext();
 
 } /* namespace xpc */
 
 class XPCJSContextStack
 {
 public:
     XPCJSContextStack()
-      : mSafeJSContext(NULL)
+      : mSafeJSContext(nullptr)
     { }
 
     virtual ~XPCJSContextStack();
 
     uint32_t Count()
     {
         return mStack.Length();
     }
 
     JSContext *Peek()
     {
-        return mStack.IsEmpty() ? NULL : mStack[mStack.Length() - 1].cx;
+        return mStack.IsEmpty() ? nullptr : mStack[mStack.Length() - 1].cx;
     }
 
     JSContext *GetSafeJSContext();
     bool HasJSContext(JSContext *cx);
 
     const InfallibleTArray<XPCJSContextInfo>* GetStack()
     { return &mStack; }
 
--- a/js/xpconnect/src/xpcpublic.h
+++ b/js/xpconnect/src/xpcpublic.h
@@ -355,17 +355,17 @@ private:
 // This reports all the stats in |rtStats| that belong in the "explicit" tree,
 // (which isn't all of them).
 // @see ZoneStatsExtras
 // @see CompartmentStatsExtras
 nsresult
 ReportJSRuntimeExplicitTreeStats(const JS::RuntimeStats &rtStats,
                                  const nsACString &rtPath,
                                  nsIMemoryReporterCallback *cb,
-                                 nsISupports *closure, size_t *rtTotal = NULL);
+                                 nsISupports *closure, size_t *rtTotal = nullptr);
 
 /**
  * Throws an exception on cx and returns false.
  */
 bool
 Throw(JSContext *cx, nsresult rv);
 
 /**
--- a/js/xpconnect/tests/components/native/xpctest_module.cpp
+++ b/js/xpconnect/tests/components/native/xpctest_module.cpp
@@ -24,27 +24,27 @@
 NS_GENERIC_FACTORY_CONSTRUCTOR(xpcTestObjectReadOnly)
 NS_GENERIC_FACTORY_CONSTRUCTOR(xpcTestObjectReadWrite)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsXPCTestParams)
 NS_DEFINE_NAMED_CID(NS_XPCTESTOBJECTREADONLY_CID);
 NS_DEFINE_NAMED_CID(NS_XPCTESTOBJECTREADWRITE_CID);
 NS_DEFINE_NAMED_CID(NS_XPCTESTPARAMS_CID);
 
 static const mozilla::Module::CIDEntry kXPCTestCIDs[] = {
-    { &kNS_XPCTESTOBJECTREADONLY_CID, false, NULL, xpcTestObjectReadOnlyConstructor },
-    { &kNS_XPCTESTOBJECTREADWRITE_CID, false, NULL, xpcTestObjectReadWriteConstructor },
-    { &kNS_XPCTESTPARAMS_CID, false, NULL, nsXPCTestParamsConstructor },
-    { NULL }
+    { &kNS_XPCTESTOBJECTREADONLY_CID, false, nullptr, xpcTestObjectReadOnlyConstructor },
+    { &kNS_XPCTESTOBJECTREADWRITE_CID, false, nullptr, xpcTestObjectReadWriteConstructor },
+    { &kNS_XPCTESTPARAMS_CID, false, nullptr, nsXPCTestParamsConstructor },
+    { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kXPCTestContracts[] = {
     { "@mozilla.org/js/xpc/test/native/ObjectReadOnly;1", &kNS_XPCTESTOBJECTREADONLY_CID },
     { "@mozilla.org/js/xpc/test/native/ObjectReadWrite;1", &kNS_XPCTESTOBJECTREADWRITE_CID },
     { "@mozilla.org/js/xpc/test/native/Params;1", &kNS_XPCTESTPARAMS_CID },
-    { NULL }
+    { nullptr }
 };
 
 static const mozilla::Module kXPCTestModule = {
     mozilla::Module::kVersion,
     kXPCTestCIDs,
     kXPCTestContracts
 };
 
--- a/js/xpconnect/wrappers/ChromeObjectWrapper.cpp
+++ b/js/xpconnect/wrappers/ChromeObjectWrapper.cpp
@@ -64,28 +64,28 @@ bool
 ChromeObjectWrapper::getPropertyDescriptor(JSContext *cx,
                                            HandleObject wrapper,
                                            HandleId id,
                                            JS::MutableHandle<JSPropertyDescriptor> desc,
                                            unsigned flags)
 {
     assertEnteredPolicy(cx, wrapper, id);
     // First, try a lookup on the base wrapper if permitted.
-    desc.object().set(NULL);
+    desc.object().set(nullptr);
     if (AllowedByBase(cx, wrapper, id, Wrapper::GET) &&
         !ChromeObjectWrapperBase::getPropertyDescriptor(cx, wrapper, id,
                                                         desc, flags)) {
         return false;
     }
 
     // If the property is something that can be found on a standard prototype,
     // prefer the one we'll get via the prototype chain in the content
     // compartment.
     if (desc.object() && PropIsFromStandardPrototype(cx, desc))
-        desc.object().set(NULL);
+        desc.object().set(nullptr);
 
     // If we found something or have no proto, we're done.
     RootedObject wrapperProto(cx);
     if (!JS_GetPrototype(cx, wrapper, &wrapperProto))
       return false;
     if (desc.object() || !wrapperProto)
         return true;
 
--- a/js/xpconnect/wrappers/WrapperFactory.cpp
+++ b/js/xpconnect/wrappers/WrapperFactory.cpp
@@ -53,17 +53,17 @@ WrapperFactory::GetXrayWaiver(JSObject *
 {
     // Object should come fully unwrapped but outerized.
     MOZ_ASSERT(obj == UncheckedUnwrap(obj));
     MOZ_ASSERT(!js::GetObjectClass(obj)->ext.outerObject);
     XPCWrappedNativeScope *scope = GetObjectScope(obj);
     MOZ_ASSERT(scope);
 
     if (!scope->mWaiverWrapperMap)
-        return NULL;
+        return nullptr;
 
     JSObject* xrayWaiver = scope->mWaiverWrapperMap->Find(obj);
     if (xrayWaiver)
         JS::ExposeObjectToActiveJS(xrayWaiver);
 
     return xrayWaiver;
 }
 
@@ -580,17 +580,17 @@ WrapperFactory::WrapSOWObject(JSContext 
     RootedObject obj(cx, objArg);
     RootedObject proto(cx);
 
     // If we're not allowing XBL scopes, that means we're running as a remote
     // XUL domain, in which we can't have SOWs. We should never be called in
     // that case.
     MOZ_ASSERT(xpc::AllowXBLScope(js::GetContextCompartment(cx)));
     if (!JS_GetPrototype(cx, obj, &proto))
-        return NULL;
+        return nullptr;
     JSObject *wrapperObj =
         Wrapper::New(cx, obj, proto, JS_GetGlobalForObject(cx, obj),
                      &FilteringWrapper<SameCompartmentSecurityWrapper,
                      Opaque>::singleton);
     return wrapperObj;
 }
 
 bool
@@ -600,17 +600,17 @@ WrapperFactory::IsComponentsObject(JSObj
     return name[0] == 'n' && !strcmp(name, "nsXPCComponents");
 }
 
 JSObject *
 WrapperFactory::WrapComponentsObject(JSContext *cx, HandleObject obj)
 {
     RootedObject proto(cx);
     if (!JS_GetPrototype(cx, obj, &proto))
-        return NULL;
+        return nullptr;
     JSObject *wrapperObj =
         Wrapper::New(cx, obj, proto, JS_GetGlobalForObject(cx, obj),
                      &FilteringWrapper<SameCompartmentSecurityWrapper, ComponentsObjectPolicy>::singleton);
 
     return wrapperObj;
 }
 
 bool
@@ -658,17 +658,17 @@ JSObject *
 TransplantObject(JSContext *cx, JS::HandleObject origobj, JS::HandleObject target)
 {
     RootedObject oldWaiver(cx, WrapperFactory::GetXrayWaiver(origobj));
     RootedObject newIdentity(cx, JS_TransplantObject(cx, origobj, target));
     if (!newIdentity || !oldWaiver)
        return newIdentity;
 
     if (!FixWaiverAfterTransplant(cx, oldWaiver, newIdentity))
-        return NULL;
+        return nullptr;
     return newIdentity;
 }
 
 JSObject *
 TransplantObjectWithWrapper(JSContext *cx,
                             HandleObject origobj, HandleObject origwrapper,
                             HandleObject targetobj, HandleObject targetwrapper)
 {
@@ -677,17 +677,17 @@ TransplantObjectWithWrapper(JSContext *c
       js_TransplantObjectWithWrapper(cx, origobj, origwrapper, targetobj,
                                      targetwrapper));
     if (!newSameCompartmentWrapper || !oldWaiver)
         return newSameCompartmentWrapper;
 
     RootedObject newIdentity(cx, Wrapper::wrappedObject(newSameCompartmentWrapper));
     MOZ_ASSERT(!js::IsWrapper(newIdentity));
     if (!FixWaiverAfterTransplant(cx, oldWaiver, newIdentity))
-        return NULL;
+        return nullptr;
     return newSameCompartmentWrapper;
 }
 
 nsIGlobalObject *
 GetNativeForGlobal(JSObject *obj)
 {
     MOZ_ASSERT(JS_IsGlobalObject(obj));
     if (!EnsureCompartmentPrivate(obj)->scope)
--- a/js/xpconnect/wrappers/XrayWrapper.cpp
+++ b/js/xpconnect/wrappers/XrayWrapper.cpp
@@ -375,17 +375,17 @@ XrayTraits::getExpandoObjectInternal(JSC
                                      nsIPrincipal *origin,
                                      JSObject *exclusiveGlobalArg)
 {
     // The expando object lives in the compartment of the target, so all our
     // work needs to happen there.
     RootedObject exclusiveGlobal(cx, exclusiveGlobalArg);
     JSAutoCompartment ac(cx, target);
     if (!JS_WrapObject(cx, exclusiveGlobal.address()))
-        return NULL;
+        return nullptr;
 
     // Iterate through the chain, looking for a same-origin object.
     RootedObject head(cx, getExpandoChain(target));
     while (head) {
         if (expandoObjectMatchesConsumer(cx, head, origin, exclusiveGlobal))
             return head;
         head = JS_GetReservedSlot(head, JSSLOT_EXPANDO_NEXT).toObjectOrNull();
     }
@@ -453,17 +453,17 @@ XrayTraits::ensureExpandoObject(JSContex
         // If the object is a sandbox, we don't want it to share expandos with
         // anyone else, so we tag it with the sandbox global.
         //
         // NB: We first need to check the class, _then_ wrap for the target's
         // compartment.
         RootedObject consumerGlobal(cx, js::GetGlobalForObjectCrossCompartment(wrapper));
         bool isSandbox = !strcmp(js::GetObjectJSClass(consumerGlobal)->name, "Sandbox");
         if (!JS_WrapObject(cx, consumerGlobal.address()))
-            return NULL;
+            return nullptr;
         expandoObject = attachExpandoObject(cx, target, ObjectPrincipal(wrapper),
                                             isSandbox ? (HandleObject)consumerGlobal : NullPtr());
     }
     return expandoObject;
 }
 
 bool
 XrayTraits::cloneExpandoChain(JSContext *cx, HandleObject dst, HandleObject src)
@@ -692,17 +692,17 @@ XPCWrappedNativeXrayTraits::preserveWrap
 
 bool
 XPCWrappedNativeXrayTraits::resolveNativeProperty(JSContext *cx, HandleObject wrapper,
                                                   HandleObject holder, HandleId id,
                                                   MutableHandle<JSPropertyDescriptor> desc, unsigned flags)
 {
     MOZ_ASSERT(js::GetObjectJSClass(holder) == &HolderClass);
 
-    desc.object().set(NULL);
+    desc.object().set(nullptr);
 
     // This will do verification and the method lookup for us.
     RootedObject target(cx, getTargetObject(wrapper));
     XPCCallContext ccx(JS_CALLER, cx, target, NullPtr(), id);
 
     // There are no native numeric properties, so we can shortcut here. We will
     // not find the property. However we want to support non shadowing dom
     // specific collection properties like window.frames, so we still have to
@@ -723,18 +723,18 @@ XPCWrappedNativeXrayTraits::resolveNativ
     } else if (!(iface = ccx.GetInterface()) ||
                !(member = ccx.GetMember())) {
         /* Not found */
         return resolveDOMCollectionProperty(cx, wrapper, holder, id, desc, flags);
     }
 
     desc.object().set(holder);
     desc.setAttributes(JSPROP_ENUMERATE);
-    desc.setGetter(NULL);
-    desc.setSetter(NULL);
+    desc.setGetter(nullptr);
+    desc.setSetter(nullptr);
     desc.setShortId(0);
     desc.value().set(JSVAL_VOID);
 
     RootedValue fval(cx, JSVAL_VOID);
     if (member->IsConstant()) {
         if (!member->GetConstantValue(ccx, iface, desc.value().address())) {
             JS_ReportError(cx, "Failed to convert constant native property to JS value");
             return false;
@@ -796,17 +796,17 @@ wrappedJSObject_getter(JSContext *cx, Ha
     return WrapperFactory::WaiveXrayAndWrap(cx, vp.address());
 }
 
 bool
 XrayTraits::resolveOwnProperty(JSContext *cx, Wrapper &jsWrapper,
                                HandleObject wrapper, HandleObject holder, HandleId id,
                                MutableHandle<JSPropertyDescriptor> desc, unsigned flags)
 {
-    desc.object().set(NULL);
+    desc.object().set(nullptr);
     RootedObject target(cx, getTargetObject(wrapper));
     RootedObject expando(cx, getExpandoObject(cx, target, wrapper));
 
     // Check for expando properties first. Note that the expando object lives
     // in the target compartment.
     if (expando) {
         JSAutoCompartment ac(cx, expando);
         if (!JS_GetPropertyDescriptorById(cx, expando, id, 0, desc))
@@ -964,17 +964,17 @@ JSObject *
 XPCWrappedNativeXrayTraits::createHolder(JSContext *cx, JSObject *wrapper)
 {
     JSObject *global = JS_GetGlobalForObject(cx, wrapper);
     JSObject *holder = JS_NewObjectWithGivenProto(cx, &HolderClass, nullptr,
                                                   global);
     if (!holder)
         return nullptr;
 
-    js::SetReservedSlot(holder, JSSLOT_RESOLVING, PrivateValue(NULL));
+    js::SetReservedSlot(holder, JSSLOT_RESOLVING, PrivateValue(nullptr));
     return holder;
 }
 
 bool
 XPCWrappedNativeXrayTraits::call(JSContext *cx, HandleObject wrapper,
                                  const JS::CallArgs &args,
                                  js::Wrapper& baseInstance)
 {
@@ -1325,30 +1325,30 @@ XrayWrapper<Base, Traits>::isExtensible(
     return true;
 }
 
 template <typename Base, typename Traits>
 bool
 XrayWrapper<Base, Traits>::preventExtensions(JSContext *cx, HandleObject wrapper)
 {
     // See above.
-    JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CHANGE_EXTENSIBILITY);
+    JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CHANGE_EXTENSIBILITY);
     return false;
 }
 
 template <typename Base, typename Traits>
 bool
 XrayWrapper<Base, Traits>::getPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id,
                                                  JS::MutableHandle<JSPropertyDescriptor> desc,
                                                  unsigned flags)
 {
     assertEnteredPolicy(cx, wrapper, id);
     RootedObject holder(cx, Traits::singleton.ensureHolder(cx, wrapper));
     if (Traits::isResolving(cx, holder, id)) {
-        desc.object().set(NULL);
+        desc.object().set(nullptr);
         return true;
     }
 
     typename Traits::ResolvingIdImpl resolving(cx, wrapper, id);
 
     if (!holder)
         return false;
 
@@ -1356,17 +1356,17 @@ XrayWrapper<Base, Traits>::getPropertyDe
     // get .wrappedJSObject. We can check this by determining if the compartment
     // of the wrapper subsumes that of the wrappee.
     XPCJSRuntime* rt = nsXPConnect::GetRuntimeInstance();
     if (AccessCheck::wrapperSubsumes(wrapper) &&
         id == rt->GetStringID(XPCJSRuntime::IDX_WRAPPED_JSOBJECT)) {
         desc.object().set(wrapper);
         desc.setAttributes(JSPROP_ENUMERATE|JSPROP_SHARED);
         desc.setGetter(wrappedJSObject_getter);
-        desc.setSetter(NULL);
+        desc.setSetter(nullptr);
         desc.setShortId(0);
         desc.value().set(JSVAL_VOID);
         return true;
     }
 
     // Ordering is important here.
     //
     // We first need to call resolveOwnProperty, even before checking the holder,
@@ -1431,18 +1431,18 @@ XrayWrapper<Base, Traits>::getPropertyDe
     {
 
         JSFunction *toString = JS_NewFunction(cx, XrayToString, 0, 0, holder, "toString");
         if (!toString)
             return false;
 
         desc.object().set(wrapper);
         desc.setAttributes(0);
-        desc.setGetter(NULL);
-        desc.setSetter(NULL);
+        desc.setGetter(nullptr);
+        desc.setSetter(nullptr);
         desc.setShortId(0);
         desc.value().setObject(*JS_GetFunctionObject(toString));
     }
 
     // If we're a special scope for in-content XBL, our script expects to see
     // the bound XBL methods and attributes when accessing content. However,
     // these members are implemented in content via custom-spliced prototypes,
     // and thus aren't visible through Xray wrappers unless we handle them
@@ -1485,17 +1485,17 @@ template <typename Base, typename Traits
 bool
 XrayWrapper<Base, Traits>::getOwnPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id,
                                                     JS::MutableHandle<JSPropertyDescriptor> desc,
                                                     unsigned flags)
 {
     assertEnteredPolicy(cx, wrapper, id);
     RootedObject holder(cx, Traits::singleton.ensureHolder(cx, wrapper));
     if (Traits::isResolving(cx, holder, id)) {
-        desc.object().set(NULL);
+        desc.object().set(nullptr);
         return true;
     }
 
     typename Traits::ResolvingIdImpl resolving(cx, wrapper, id);
 
     // NB: Nothing we do here acts on the wrapped native itself, so we don't
     // enter our policy.
 
--- a/layout/base/nsRefreshDriver.cpp
+++ b/layout/base/nsRefreshDriver.cpp
@@ -1054,30 +1054,33 @@ nsRefreshDriver::Tick(int64_t aNowEpoch,
     // often depending on what other things are going on and in that
     // situation we don't want to thrash our timer.  So instead we
     // wait until we get a Notify() call when we have no observers
     // before stopping the timer.
     StopTimer();
     return;
   }
 
+  profiler_tracing("Paint", "RD", TRACING_INTERVAL_START);
+
   /*
    * The timer holds a reference to |this| while calling |Notify|.
    * However, implementations of |WillRefresh| are permitted to destroy
    * the pres context, which will cause our |mPresContext| to become
    * null.  If this happens, we must stop notifying observers.
    */
   for (uint32_t i = 0; i < ArrayLength(mObservers); ++i) {
     ObserverArray::EndLimitedIterator etor(mObservers[i]);
     while (etor.HasMore()) {
       nsRefPtr<nsARefreshObserver> obs = etor.GetNext();
       obs->WillRefresh(aNowTime);
       
       if (!mPresContext || !mPresContext->GetPresShell()) {
         StopTimer();
+        profiler_tracing("Paint", "RD", TRACING_INTERVAL_END);
         return;
       }
     }
 
     if (i == 0) {
       // Grab all of our frame request callbacks up front.
       nsTArray<DocumentFrameCallbacks>
         frameRequestCallbacks(mFrameRequestCallbackDocs.Length());
@@ -1085,16 +1088,17 @@ nsRefreshDriver::Tick(int64_t aNowEpoch,
         frameRequestCallbacks.AppendElement(mFrameRequestCallbackDocs[i]);
         mFrameRequestCallbackDocs[i]->
           TakeFrameRequestCallbacks(frameRequestCallbacks.LastElement().mCallbacks);
       }
       // OK, now reset mFrameRequestCallbackDocs so they can be
       // readded as needed.
       mFrameRequestCallbackDocs.Clear();
 
+      profiler_tracing("Paint", "Scripts", TRACING_INTERVAL_START);
       int64_t eventTime = aNowEpoch / PR_USEC_PER_MSEC;
       for (uint32_t i = 0; i < frameRequestCallbacks.Length(); ++i) {
         const DocumentFrameCallbacks& docCallbacks = frameRequestCallbacks[i];
         // XXXbz Bug 863140: GetInnerWindow can return the outer
         // window in some cases.
         nsPIDOMWindow* innerWindow = docCallbacks.mDocument->GetInnerWindow();
         DOMHighResTimeStamp timeStamp = 0;
         if (innerWindow && innerWindow->IsInnerWindow()) {
@@ -1111,16 +1115,17 @@ nsRefreshDriver::Tick(int64_t aNowEpoch,
           if (holder.HasWebIDLCallback()) {
             ErrorResult ignored;
             holder.GetWebIDLCallback()->Call(timeStamp, ignored);
           } else {
             holder.GetXPCOMCallback()->Sample(eventTime);
           }
         }
       }
+      profiler_tracing("Paint", "Scripts", TRACING_INTERVAL_END);
 
       // This is the Flush_Style case.
       if (mPresContext && mPresContext->GetPresShell()) {
         nsAutoTArray<nsIPresShell*, 16> observers;
         observers.AppendElements(mStyleFlushObservers);
         for (uint32_t j = observers.Length();
              j && mPresContext && mPresContext->GetPresShell(); --j) {
           // Make sure to not process observers which might have been removed
@@ -1209,16 +1214,17 @@ nsRefreshDriver::Tick(int64_t aNowEpoch,
       printf("Ending ProcessPendingUpdates\n");
     }
 #endif
   }
 
   for (uint32_t i = 0; i < mPostRefreshObservers.Length(); ++i) {
     mPostRefreshObservers[i]->DidRefresh();
   }
+  profiler_tracing("Paint", "RD", TRACING_INTERVAL_END);
 }
 
 /* static */ PLDHashOperator
 nsRefreshDriver::ImageRequestEnumerator(nsISupportsHashKey* aEntry,
                                         void* aUserArg)
 {
   nsCOMArray<imgIContainer>* imagesToRefresh =
     static_cast<nsCOMArray<imgIContainer>*> (aUserArg);
--- a/layout/generic/nsGfxScrollFrame.cpp
+++ b/layout/generic/nsGfxScrollFrame.cpp
@@ -72,32 +72,16 @@ NS_NewHTMLScrollFrame(nsIPresShell* aPre
 NS_IMPL_FRAMEARENA_HELPERS(nsHTMLScrollFrame)
 
 nsHTMLScrollFrame::nsHTMLScrollFrame(nsIPresShell* aShell, nsStyleContext* aContext, bool aIsRoot)
   : nsContainerFrame(aContext),
     mInner(ALLOW_THIS_IN_INITIALIZER_LIST(this), aIsRoot)
 {
 }
 
-void
-nsHTMLScrollFrame::ScrollbarActivityStarted() const
-{
-  if (mInner.mScrollbarActivity) {
-    mInner.mScrollbarActivity->ActivityStarted();
-  }
-}
- 
-void
-nsHTMLScrollFrame::ScrollbarActivityStopped() const
-{
-  if (mInner.mScrollbarActivity) {
-    mInner.mScrollbarActivity->ActivityStopped();
-  }
-}
- 
 nsresult
 nsHTMLScrollFrame::CreateAnonymousContent(nsTArray<ContentInfo>& aElements)
 {
   return mInner.CreateAnonymousContent(aElements);
 }
 
 void
 nsHTMLScrollFrame::AppendAnonymousContentTo(nsBaseContentList& aElements,
@@ -913,32 +897,16 @@ nsXULScrollFrame::nsXULScrollFrame(nsIPr
                                    bool aIsRoot, bool aClipAllDescendants)
   : nsBoxFrame(aShell, aContext, aIsRoot),
     mInner(ALLOW_THIS_IN_INITIALIZER_LIST(this), aIsRoot)
 {
   SetLayoutManager(nullptr);
   mInner.mClipAllDescendants = aClipAllDescendants;
 }
 
-void
-nsXULScrollFrame::ScrollbarActivityStarted() const
-{
-  if (mInner.mScrollbarActivity) {
-    mInner.mScrollbarActivity->ActivityStarted();
-  }
-}
- 
-void
-nsXULScrollFrame::ScrollbarActivityStopped() const
-{
-  if (mInner.mScrollbarActivity) {
-    mInner.mScrollbarActivity->ActivityStopped();
-  }
-}
- 
 nsMargin
 nsGfxScrollFrameInner::GetDesiredScrollbarSizes(nsBoxLayoutState* aState)
 {
   NS_ASSERTION(aState && aState->GetRenderingContext(),
                "Must have rendering context in layout state for size "
                "computations");
 
   nsMargin result(0, 0, 0, 0);
--- a/layout/generic/nsGfxScrollFrame.h
+++ b/layout/generic/nsGfxScrollFrame.h
@@ -515,19 +515,16 @@ public:
   virtual void AppendAnonymousContentTo(nsBaseContentList& aElements,
                                         uint32_t aFilter) MOZ_OVERRIDE;
 
   // nsIScrollbarOwner
   virtual nsIFrame* GetScrollbarBox(bool aVertical) MOZ_OVERRIDE {
     return mInner.GetScrollbarBox(aVertical);
   }
 
-  virtual void ScrollbarActivityStarted() const MOZ_OVERRIDE;
-  virtual void ScrollbarActivityStopped() const MOZ_OVERRIDE;
-
   // nsIScrollableFrame
   virtual nsIFrame* GetScrolledFrame() const MOZ_OVERRIDE {
     return mInner.GetScrolledFrame();
   }
   virtual mozilla::ScrollbarStyles GetScrollbarStyles() const {
     return mInner.GetScrollbarStylesFromFrame();
   }
   virtual uint32_t GetScrollbarVisibility() const MOZ_OVERRIDE {
@@ -808,19 +805,16 @@ public:
   static void AdjustReflowStateForPrintPreview(nsBoxLayoutState& aState, bool& aSetBack);
   static void AdjustReflowStateBack(nsBoxLayoutState& aState, bool aSetBack);
 
   // nsIScrollbarOwner
   virtual nsIFrame* GetScrollbarBox(bool aVertical) MOZ_OVERRIDE {
     return mInner.GetScrollbarBox(aVertical);
   }
 
-  virtual void ScrollbarActivityStarted() const MOZ_OVERRIDE;
-  virtual void ScrollbarActivityStopped() const MOZ_OVERRIDE;
-
   // nsIScrollableFrame
   virtual nsIFrame* GetScrolledFrame() const MOZ_OVERRIDE {
     return mInner.GetScrolledFrame();
   }
   virtual mozilla::ScrollbarStyles GetScrollbarStyles() const {
     return mInner.GetScrollbarStylesFromFrame();
   }
   virtual uint32_t GetScrollbarVisibility() const MOZ_OVERRIDE {
--- a/layout/generic/nsIScrollbarOwner.h
+++ b/layout/generic/nsIScrollbarOwner.h
@@ -18,18 +18,11 @@ class nsIScrollbarOwner : public nsQuery
 public:
   NS_DECL_QUERYFRAME_TARGET(nsIScrollbarOwner)
 
   /**
    * Obtain the frame for the horizontal or vertical scrollbar, or null
    * if there is no such box.
    */
   virtual nsIFrame* GetScrollbarBox(bool aVertical) = 0;
-
-  /**
-   * Show or hide scrollbars on 2 fingers touch.
-   * Subclasses should call their ScrollbarActivity's corresponding methods.
-   */
-  virtual void ScrollbarActivityStarted() const = 0;
-  virtual void ScrollbarActivityStopped() const = 0;
 };
 
 #endif
--- a/layout/xul/tree/nsTreeBodyFrame.cpp
+++ b/layout/xul/tree/nsTreeBodyFrame.cpp
@@ -4491,32 +4491,16 @@ nsTreeBodyFrame::PostScrollEvent()
   if (NS_FAILED(NS_DispatchToCurrentThread(ev))) {
     NS_WARNING("failed to dispatch ScrollEvent");
   } else {
     mScrollEvent = ev;
   }
 }
 
 void
-nsTreeBodyFrame::ScrollbarActivityStarted() const
-{
-  if (mScrollbarActivity) {
-    mScrollbarActivity->ActivityStarted();
-  }
-}
- 
-void
-nsTreeBodyFrame::ScrollbarActivityStopped() const
-{
-  if (mScrollbarActivity) {
-    mScrollbarActivity->ActivityStopped();
-  }
-}
- 
-void
 nsTreeBodyFrame::DetachImageListeners()
 {
   mCreatedListeners.Clear();
 }
 
 void
 nsTreeBodyFrame::RemoveTreeImageListener(nsTreeImageListener* aListener)
 {
--- a/layout/xul/tree/nsTreeBodyFrame.h
+++ b/layout/xul/tree/nsTreeBodyFrame.h
@@ -459,19 +459,16 @@ protected:
     ScrollEvent(nsTreeBodyFrame *aInner) : mInner(aInner) {}
     void Revoke() { mInner = nullptr; }
   private:
     nsTreeBodyFrame* mInner;
   };
 
   void PostScrollEvent();
   void FireScrollEvent();
-  
-  virtual void ScrollbarActivityStarted() const MOZ_OVERRIDE;
-  virtual void ScrollbarActivityStopped() const MOZ_OVERRIDE;
 
   /**
    * Clear the pointer to this frame for all nsTreeImageListeners that were
    * created by this frame.
    */
   void DetachImageListeners();
 
 #ifdef ACCESSIBILITY
--- a/media/mtransport/test/stunserver.cpp
+++ b/media/mtransport/test/stunserver.cpp
@@ -181,33 +181,55 @@ int nr_socket_wrapped_create(nr_socket *
 // we have no reason to expect this will be initted to a nullptr yet.
 TestStunServer* TestStunServer::instance;
 uint16_t TestStunServer::instance_port = 3478;
 
 TestStunServer::~TestStunServer() {
   // TODO(ekr@rtfm.com): Put this on the right thread.
 
   // Unhook callback from our listen socket.
-  NR_SOCKET fd;
-  if (!nr_socket_getfd(listen_sock_, &fd)) {
-    NR_ASYNC_CANCEL(fd, NR_ASYNC_WAIT_READ);
+  if (listen_sock_) {
+    NR_SOCKET fd;
+    if (!nr_socket_getfd(listen_sock_, &fd)) {
+      NR_ASYNC_CANCEL(fd, NR_ASYNC_WAIT_READ);
+    }
   }
 
   // Free up stun context and network resources
   nr_stun_server_ctx_destroy(&stun_server_);
   nr_socket_destroy(&listen_sock_);
   nr_socket_destroy(&send_sock_);
 
   // Make sure we aren't still waiting on a deferred response timer to pop
   if (timer_handle_)
     NR_async_timer_cancel(timer_handle_);
 
   delete response_addr_;
 }
 
+int TestStunServer::TryOpenListenSocket(nr_local_addr* addr, uint16_t port) {
+
+    if (nr_transport_addr_set_port(&addr->addr, port)) {
+      MOZ_MTLOG(ML_ERROR, "Couldn't set port");
+      return R_INTERNAL;
+    }
+
+    if (nr_transport_addr_fmt_addr_string(&addr->addr)) {
+      MOZ_MTLOG(ML_ERROR, "Couldn't re-set addr string");
+      return R_INTERNAL;
+    }
+
+    if (nr_socket_local_create(&addr->addr, &listen_sock_)) {
+      MOZ_MTLOG(ML_ERROR, "Couldn't create listen socket");
+      return R_ALREADY;
+    }
+
+    return 0;
+}
+
 TestStunServer* TestStunServer::Create() {
   NR_reg_init(NR_REG_MODE_LOCAL);
 
   ScopedDeletePtr<TestStunServer> server(new TestStunServer());
 
   nr_local_addr addrs[100];
   int addr_ct;
   int r;
@@ -218,36 +240,33 @@ TestStunServer* TestStunServer::Create()
     return nullptr;
   }
 
   if (addr_ct < 1) {
     MOZ_MTLOG(ML_ERROR, "No local addresses");
     return nullptr;
   }
 
-  // Bind to the first address (arbitrarily) on configured port (default 3478)
-  r = nr_transport_addr_set_port(&addrs[0].addr, instance_port);
+  NR_SOCKET fd;
+  int tries = 10;
+  while (tries--) {
+    // Bind to the first address (arbitrarily) on configured port (default 3478)
+    r = server->TryOpenListenSocket(&addrs[0], instance_port);
+    // We interpret R_ALREADY to mean the addr is probably in use. Try another.
+    // Otherwise, it either worked or it didn't, and we check below.
+    if (r != R_ALREADY) {
+      break;
+    }
+    ++instance_port;
+  }
+
   if (r) {
-    MOZ_MTLOG(ML_ERROR, "Couldn't set port");
     return nullptr;
   }
 
-  r = nr_transport_addr_fmt_addr_string(&addrs[0].addr);
-  if (r) {
-    MOZ_MTLOG(ML_ERROR, "Couldn't re-set addr string");
-    return nullptr;
-  }
-
-  r = nr_socket_local_create(&addrs[0].addr, &server->listen_sock_);
-  if (r) {
-    MOZ_MTLOG(ML_ERROR, "Couldn't create listen socket");
-    return nullptr;
-  }
-
-  NR_SOCKET fd;
   r = nr_socket_getfd(server->listen_sock_, &fd);
   if (r) {
     MOZ_MTLOG(ML_ERROR, "Couldn't get fd");
     return nullptr;
   }
 
   r = nr_socket_wrapped_create(server->listen_sock_, &server->send_sock_);
   if (r) {
@@ -283,16 +302,17 @@ TestStunServer* TestStunServer::Create()
 void TestStunServer::ConfigurePort(uint16_t port) {
   instance_port = port;
 }
 
 TestStunServer* TestStunServer::GetInstance() {
   if (!instance)
     instance = Create();
 
+  MOZ_ASSERT(instance);
   return instance;
 }
 
 void TestStunServer::ShutdownInstance() {
   delete instance;
 
   instance = nullptr;
 }
--- a/media/mtransport/test/stunserver.h
+++ b/media/mtransport/test/stunserver.h
@@ -11,16 +11,17 @@
 
 #include <map>
 #include <string>
 #include "prio.h"
 #include "nsError.h"
 
 typedef struct nr_stun_server_ctx_ nr_stun_server_ctx;
 typedef struct nr_socket_ nr_socket;
+typedef struct nr_local_addr_ nr_local_addr;
 
 namespace mozilla {
 
 class TestStunServer {
  public:
   // Generally, you should only call API in this class from the same thread that
   // the initial |GetInstance| call was made from.
   static TestStunServer *GetInstance();
@@ -53,16 +54,17 @@ class TestStunServer {
         active_(true),
         delay_ms_(0),
         initial_ct_(0),
         response_addr_(nullptr),
         timer_handle_(nullptr),
         listen_port_(0) {}
 
   void Process(const uint8_t *msg, size_t len, nr_transport_addr *addr_in);
+  int TryOpenListenSocket(nr_local_addr* addr, uint16_t port);
 
   static void readable_cb(NR_SOCKET sock, int how, void *cb_arg);
   static void process_cb(NR_SOCKET sock, int how, void *cb_arg);
 
   nr_socket *listen_sock_;
   nr_socket *send_sock_;
   nr_stun_server_ctx *stun_server_;
   bool active_;
--- a/mobile/android/base/tests/robocop.ini
+++ b/mobile/android/base/tests/robocop.ini
@@ -1,24 +1,24 @@
 [testAwesomebar]
 # [testAwesomebarSwipes] # disabled on fig - bug 880060
 [testBookmark]
 # [testBookmarklets] # see bug 915350
 # [testBookmarkKeyword] # see bug 915350
 [testBrowserSearchVisibility]
 [testJNI]
-# [testLoad] # see bug 851861
+[testLoad]
 [testNewTab]
 [testOrderedBroadcast]
 [testPrefsObserver]
-# [testPanCorrectness] # see bug 851861
+[testPanCorrectness]
 # [test_bug720538] # disabled on fig - bug 897072
-# [testFlingCorrectness] # see bug 851861
-# [testOverscroll] # see bug 851861
-# [testAxisLocking] # see bug 851861
+[testFlingCorrectness]
+[testOverscroll]
+[testAxisLocking]
 [testAboutPage]
 [testLinkContextMenu]
 [testMailToContextMenu]
 [testPictureLinkContextMenu]
 [testPasswordProvider]
 # [testPasswordEncrypt] # see bug 824067
 [testFormHistory]
 [testBrowserProvider]
--- a/modules/libpref/src/Preferences.cpp
+++ b/modules/libpref/src/Preferences.cpp
@@ -10,16 +10,17 @@
 #include "mozilla/Attributes.h"
 #include "mozilla/Util.h"
 #include "mozilla/HashFunctions.h"
 
 #include "nsXULAppAPI.h"
 
 #include "mozilla/Preferences.h"
 #include "nsAppDirectoryServiceDefs.h"
+#include "nsDataHashtable.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsICategoryManager.h"
 #include "nsCategoryManagerUtils.h"
 #include "nsNetUtil.h"
 #include "nsIFile.h"
 #include "nsIInputStream.h"
 #include "nsIObserverService.h"
 #include "nsIStringEnumerator.h"
--- a/netwerk/base/public/nsNetUtil.h
+++ b/netwerk/base/public/nsNetUtil.h
@@ -2321,17 +2321,18 @@ NS_SniffContent(const char* aSnifferType
     }
     cache = gDataSniffers;
   } else {
     // Invalid content sniffer type was requested
     MOZ_ASSERT(false);
     return;
   }
 
-  const nsCOMArray<nsIContentSniffer>& sniffers = cache->GetEntries();
+  nsCOMArray<nsIContentSniffer> sniffers;
+  cache->GetEntries(sniffers);
   for (int32_t i = 0; i < sniffers.Count(); ++i) {
     nsresult rv = sniffers[i]->GetMIMETypeFromContent(aRequest, aData, aLength, aSniffedType);
     if (NS_SUCCEEDED(rv) && !aSniffedType.IsEmpty()) {
       return;
     }
   }
 
   aSniffedType.Truncate();
--- a/netwerk/base/src/nsIOService.cpp
+++ b/netwerk/base/src/nsIOService.cpp
@@ -314,18 +314,18 @@ nsIOService::AsyncOnChannelRedirect(nsIC
     if (sink) {
         nsresult rv = helper->DelegateOnChannelRedirect(sink, oldChan,
                                                         newChan, flags);
         if (NS_FAILED(rv))
             return rv;
     }
 
     // Finally, our category
-    const nsCOMArray<nsIChannelEventSink>& entries =
-        mChannelEventSinks.GetEntries();
+    nsCOMArray<nsIChannelEventSink> entries;
+    mChannelEventSinks.GetEntries(entries);
     int32_t len = entries.Count();
     for (int32_t i = 0; i < len; ++i) {
         nsresult rv = helper->DelegateOnChannelRedirect(entries[i], oldChan,
                                                         newChan, flags);
         if (NS_FAILED(rv))
             return rv;
     }
     return NS_OK;
--- a/netwerk/test/httpserver/httpd.js
+++ b/netwerk/test/httpserver/httpd.js
@@ -577,17 +577,17 @@ nsHttpServer.prototype =
             " pending connections");
       socket.asyncListen(this);
       this._port = socket.port;
       this._identity._initialize(socket.port, host, true);
       this._socket = socket;
     }
     catch (e)
     {
-      dumpn("!!! could not start server on port " + port + ": " + e);
+      dump("\n!!! could not start server on port " + port + ": " + e + "\n\n");
       throw Cr.NS_ERROR_NOT_AVAILABLE;
     }
   },
 
   //
   // see nsIHttpServer.stop
   //
   stop: function(callback)
--- a/security/build/Makefile.in
+++ b/security/build/Makefile.in
@@ -7,18 +7,16 @@ CC_WRAPPER =
 CXX_WRAPPER =
 
 ifdef MOZ_FOLD_LIBS
 FORCE_SHARED_LIB = 1
 endif
 
 default::
 
-include $(topsrcdir)/config/makefiles/functions.mk
-
 NSS_LIBS = \
   nss3 \
   nssutil3 \
   smime3 \
   ssl3 \
   $(NULL)
 
 ifdef MOZ_FOLD_LIBS
--- a/security/manager/ssl/src/nsNTLMAuthModule.cpp
+++ b/security/manager/ssl/src/nsNTLMAuthModule.cpp
@@ -773,18 +773,18 @@ nsNTLMAuthModule::Init(const char      *
 
   mDomain = domain;
   mUsername = username;
   mPassword = password;
 
   static bool sTelemetrySent = false;
   if (!sTelemetrySent) {
       mozilla::Telemetry::Accumulate(
-          mozilla::Telemetry::NTLM_MODULE_USED,
-          serviceFlags | nsIAuthModule::REQ_PROXY_AUTH
+          mozilla::Telemetry::NTLM_MODULE_USED_2,
+          serviceFlags & nsIAuthModule::REQ_PROXY_AUTH
               ? NTLM_MODULE_GENERIC_PROXY
               : NTLM_MODULE_GENERIC_DIRECT);
       sTelemetrySent = true;
   }
 
   return NS_OK;
 }
 
--- a/storage/src/VacuumManager.cpp
+++ b/storage/src/VacuumManager.cpp
@@ -359,18 +359,18 @@ VacuumManager::~VacuumManager()
 NS_IMETHODIMP
 VacuumManager::Observe(nsISupports *aSubject,
                        const char *aTopic,
                        const PRUnichar *aData)
 {
   if (strcmp(aTopic, OBSERVER_TOPIC_IDLE_DAILY) == 0) {
     // Try to run vacuum on all registered entries.  Will stop at the first
     // successful one.
-    const nsCOMArray<mozIStorageVacuumParticipant> &entries =
-      mParticipants.GetEntries();
+    nsCOMArray<mozIStorageVacuumParticipant> entries;
+    mParticipants.GetEntries(entries);
     // If there are more entries than what a month can contain, we could end up
     // skipping some, since we run daily.  So we use a starting index.
     static const char* kPrefName = PREF_VACUUM_BRANCH "index";
     int32_t startIndex = Preferences::GetInt(kPrefName, 0);
     if (startIndex >= entries.Count()) {
       startIndex = 0;
     }
     int32_t index;
--- a/testing/mochitest/runtestsb2g.py
+++ b/testing/mochitest/runtestsb2g.py
@@ -339,19 +339,20 @@ def run_desktop_mochitests(parser, optio
     kwargs = {}
     if options.marionette:
         host, port = options.marionette.split(':')
         kwargs['host'] = host
         kwargs['port'] = int(port)
     marionette = Marionette.getMarionetteOrExit(**kwargs)
     mochitest = B2GDesktopMochitest(marionette, options.profile_data_dir)
 
-    # b2g desktop builds don't always have a b2g-bin file
-    if options.app[-4:] == '-bin':
-        options.app = options.app[:-4]
+    # add a -bin suffix if b2g-bin exists, but just b2g was specified
+    if options.app[-4:] != '-bin':
+        if os.path.isfile("%s-bin" % options.app):
+            options.app = "%s-bin" % options.app
 
     options = MochitestOptions.verifyOptions(parser, options, mochitest)
     if options == None:
         sys.exit(1)
 
     if options.desktop and not options.profile:
         raise Exception("must specify --profile when specifying --desktop")
 
--- a/toolkit/components/alerts/nsAlertsService.cpp
+++ b/toolkit/components/alerts/nsAlertsService.cpp
@@ -97,17 +97,17 @@ NS_IMETHODIMP nsAlertsService::ShowAlert
     return sysAlerts->ShowAlertNotification(aImageUrl, aAlertTitle, aAlertText, aAlertTextClickable,
                                             aAlertCookie, aAlertListener, aAlertName,
                                             aBidi, aLang);
   }
 
   if (!ShouldShowAlert()) {
     // Do not display the alert. Instead call alertfinished and get out.
     if (aAlertListener)
-      aAlertListener->Observe(NULL, "alertfinished", PromiseFlatString(aAlertCookie).get());
+      aAlertListener->Observe(nullptr, "alertfinished", PromiseFlatString(aAlertCookie).get());
     return NS_OK;
   }
 
   // Use XUL notifications as a fallback if above methods have failed.
   rv = mXULAlerts.ShowAlertNotification(aImageUrl, aAlertTitle, aAlertText, aAlertTextClickable,
                                         aAlertCookie, aAlertListener, aAlertName,
                                         aBidi, aLang);
   return rv;
--- a/toolkit/components/autocomplete/nsAutoCompleteController.cpp
+++ b/toolkit/components/autocomplete/nsAutoCompleteController.cpp
@@ -1722,25 +1722,25 @@ nsAutoCompleteController::RowIndexToSear
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsAutoCompleteController)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsAutoCompleteSimpleResult)
 
 NS_DEFINE_NAMED_CID(NS_AUTOCOMPLETECONTROLLER_CID);
 NS_DEFINE_NAMED_CID(NS_AUTOCOMPLETESIMPLERESULT_CID);
 
 static const mozilla::Module::CIDEntry kAutoCompleteCIDs[] = {
-  { &kNS_AUTOCOMPLETECONTROLLER_CID, false, NULL, nsAutoCompleteControllerConstructor },
-  { &kNS_AUTOCOMPLETESIMPLERESULT_CID, false, NULL, nsAutoCompleteSimpleResultConstructor },
-  { NULL }
+  { &kNS_AUTOCOMPLETECONTROLLER_CID, false, nullptr, nsAutoCompleteControllerConstructor },
+  { &kNS_AUTOCOMPLETESIMPLERESULT_CID, false, nullptr, nsAutoCompleteSimpleResultConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kAutoCompleteContracts[] = {
   { NS_AUTOCOMPLETECONTROLLER_CONTRACTID, &kNS_AUTOCOMPLETECONTROLLER_CID },
   { NS_AUTOCOMPLETESIMPLERESULT_CONTRACTID, &kNS_AUTOCOMPLETESIMPLERESULT_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kAutoCompleteModule = {
   mozilla::Module::kVersion,
   kAutoCompleteCIDs,
   kAutoCompleteContracts
 };
 
--- a/toolkit/components/build/nsToolkitCompsModule.cpp
+++ b/toolkit/components/build/nsToolkitCompsModule.cpp
@@ -65,17 +65,17 @@ static nsresult
 nsUrlClassifierDBServiceConstructor(nsISupports *aOuter, REFNSIID aIID,
                                     void **aResult)
 {
     nsresult rv;
     NS_ENSURE_ARG_POINTER(aResult);
     NS_ENSURE_NO_AGGREGATION(aOuter);
 
     nsUrlClassifierDBService *inst = nsUrlClassifierDBService::GetInstance(&rv);
-    if (NULL == inst) {
+    if (nullptr == inst) {
         return rv;
     }
     /* NS_ADDREF(inst); */
     rv = inst->QueryInterface(aIID, aResult);
     NS_RELEASE(inst);
 
     return rv;
 }
@@ -106,40 +106,40 @@ NS_DEFINE_NAMED_CID(NS_URLCLASSIFIERUTIL
 #endif
 NS_DEFINE_NAMED_CID(NS_BROWSERSTATUSFILTER_CID);
 NS_DEFINE_NAMED_CID(NS_CHARSETMENU_CID);
 #if defined(USE_MOZ_UPDATER)
 NS_DEFINE_NAMED_CID(NS_UPDATEPROCESSOR_CID);
 #endif
 
 static const mozilla::Module::CIDEntry kToolkitCIDs[] = {
-  { &kNS_TOOLKIT_APPSTARTUP_CID, false, NULL, nsAppStartupConstructor },
-  { &kNS_USERINFO_CID, false, NULL, nsUserInfoConstructor },
-  { &kNS_ALERTSSERVICE_CID, false, NULL, nsAlertsServiceConstructor },
+  { &kNS_TOOLKIT_APPSTARTUP_CID, false, nullptr, nsAppStartupConstructor },
+  { &kNS_USERINFO_CID, false, nullptr, nsUserInfoConstructor },
+  { &kNS_ALERTSSERVICE_CID, false, nullptr, nsAlertsServiceConstructor },
 #if defined(XP_WIN) && !defined(MOZ_DISABLE_PARENTAL_CONTROLS)
-  { &kNS_PARENTALCONTROLSSERVICE_CID, false, NULL, nsParentalControlsServiceWinConstructor },
+  { &kNS_PARENTALCONTROLSSERVICE_CID, false, nullptr, nsParentalControlsServiceWinConstructor },
 #endif
-  { &kNS_DOWNLOADMANAGER_CID, false, NULL, nsDownloadManagerConstructor },
-  { &kNS_DOWNLOADPLATFORM_CID, false, NULL, DownloadPlatformConstructor },
-  { &kNS_DOWNLOAD_CID, false, NULL, nsDownloadProxyConstructor },
-  { &kNS_FIND_SERVICE_CID, false, NULL, nsFindServiceConstructor },
-  { &kNS_TYPEAHEADFIND_CID, false, NULL, nsTypeAheadFindConstructor },
+  { &kNS_DOWNLOADMANAGER_CID, false, nullptr, nsDownloadManagerConstructor },
+  { &kNS_DOWNLOADPLATFORM_CID, false, nullptr, DownloadPlatformConstructor },
+  { &kNS_DOWNLOAD_CID, false, nullptr, nsDownloadProxyConstructor },
+  { &kNS_FIND_SERVICE_CID, false, nullptr, nsFindServiceConstructor },
+  { &kNS_TYPEAHEADFIND_CID, false, nullptr, nsTypeAheadFindConstructor },
 #ifdef MOZ_URL_CLASSIFIER
-  { &kNS_APPLICATION_REPUTATION_SERVICE_CID, false, NULL, ApplicationReputationServiceConstructor },
-  { &kNS_URLCLASSIFIERPREFIXSET_CID, false, NULL, nsUrlClassifierPrefixSetConstructor },
-  { &kNS_URLCLASSIFIERDBSERVICE_CID, false, NULL, nsUrlClassifierDBServiceConstructor },
-  { &kNS_URLCLASSIFIERSTREAMUPDATER_CID, false, NULL, nsUrlClassifierStreamUpdaterConstructor },
-  { &kNS_URLCLASSIFIERUTILS_CID, false, NULL, nsUrlClassifierUtilsConstructor },
+  { &kNS_APPLICATION_REPUTATION_SERVICE_CID, false, nullptr, ApplicationReputationServiceConstructor },
+  { &kNS_URLCLASSIFIERPREFIXSET_CID, false, nullptr, nsUrlClassifierPrefixSetConstructor },
+  { &kNS_URLCLASSIFIERDBSERVICE_CID, false, nullptr, nsUrlClassifierDBServiceConstructor },
+  { &kNS_URLCLASSIFIERSTREAMUPDATER_CID, false, nullptr, nsUrlClassifierStreamUpdaterConstructor },
+  { &kNS_URLCLASSIFIERUTILS_CID, false, nullptr, nsUrlClassifierUtilsConstructor },
 #endif
-  { &kNS_BROWSERSTATUSFILTER_CID, false, NULL, nsBrowserStatusFilterConstructor },
-  { &kNS_CHARSETMENU_CID, false, NULL, NS_NewCharsetMenu },
+  { &kNS_BROWSERSTATUSFILTER_CID, false, nullptr, nsBrowserStatusFilterConstructor },
+  { &kNS_CHARSETMENU_CID, false, nullptr, NS_NewCharsetMenu },
 #if defined(USE_MOZ_UPDATER)
-  { &kNS_UPDATEPROCESSOR_CID, false, NULL, nsUpdateProcessorConstructor },
+  { &kNS_UPDATEPROCESSOR_CID, false, nullptr, nsUpdateProcessorConstructor },
 #endif
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kToolkitContracts[] = {
   { NS_APPSTARTUP_CONTRACTID, &kNS_TOOLKIT_APPSTARTUP_CID },
   { NS_USERINFO_CONTRACTID, &kNS_USERINFO_CID },
   { NS_ALERTSERVICE_CONTRACTID, &kNS_ALERTSSERVICE_CID },
 #if defined(XP_WIN) && !defined(MOZ_DISABLE_PARENTAL_CONTROLS)
   { NS_PARENTALCONTROLSSERVICE_CONTRACTID, &kNS_PARENTALCONTROLSSERVICE_CID },
@@ -157,17 +157,17 @@ static const mozilla::Module::ContractID
   { NS_URLCLASSIFIERSTREAMUPDATER_CONTRACTID, &kNS_URLCLASSIFIERSTREAMUPDATER_CID },
   { NS_URLCLASSIFIERUTILS_CONTRACTID, &kNS_URLCLASSIFIERUTILS_CID },
 #endif
   { NS_BROWSERSTATUSFILTER_CONTRACTID, &kNS_BROWSERSTATUSFILTER_CID },
   { NS_RDF_DATASOURCE_CONTRACTID_PREFIX NS_CHARSETMENU_PID, &kNS_CHARSETMENU_CID },
 #if defined(USE_MOZ_UPDATER)
   { NS_UPDATEPROCESSOR_CONTRACTID, &kNS_UPDATEPROCESSOR_CID },
 #endif
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kToolkitModule = {
   mozilla::Module::kVersion,
   kToolkitCIDs,
   kToolkitContracts
 };
 
--- a/toolkit/components/commandlines/nsCommandLine.cpp
+++ b/toolkit/components/commandlines/nsCommandLine.cpp
@@ -79,17 +79,17 @@ protected:
 nsCommandLine::nsCommandLine() :
   mState(STATE_INITIAL_LAUNCH),
   mPreventDefault(false)
 {
 
 }
 
 
-NS_IMPL_CLASSINFO(nsCommandLine, NULL, 0, NS_COMMANDLINE_CID)
+NS_IMPL_CLASSINFO(nsCommandLine, nullptr, 0, NS_COMMANDLINE_CID)
 NS_IMPL_ISUPPORTS2_CI(nsCommandLine,
                       nsICommandLine,
                       nsICommandLineRunner)
 
 NS_IMETHODIMP
 nsCommandLine::GetLength(int32_t *aResult)
 {
   *aResult = int32_t(mArgs.Length());
@@ -262,17 +262,17 @@ nsCommandLine::ResolveFile(const nsAStri
   CFURLRef baseurl;
   rv = lfm->GetCFURL(&baseurl);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsAutoCString path;
   NS_CopyUnicodeToNative(aArgument, path);
 
   CFURLRef newurl =
-    CFURLCreateFromFileSystemRepresentationRelativeToBase(NULL, (const UInt8*) path.get(),
+    CFURLCreateFromFileSystemRepresentationRelativeToBase(nullptr, (const UInt8*) path.get(),
                                                           path.Length(),
                                                           true, baseurl);
 
   CFRelease(baseurl);
 
   rv = newfile->InitWithCFURL(newurl);
   CFRelease(newurl);
   if (NS_FAILED(rv)) return rv;
@@ -663,23 +663,23 @@ nsCommandLine::GetHelpText(nsACString& a
   return NS_OK;
 }
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsCommandLine)
 
 NS_DEFINE_NAMED_CID(NS_COMMANDLINE_CID);
 
 static const mozilla::Module::CIDEntry kCommandLineCIDs[] = {
-  { &kNS_COMMANDLINE_CID, false, NULL, nsCommandLineConstructor },
-  { NULL }
+  { &kNS_COMMANDLINE_CID, false, nullptr, nsCommandLineConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kCommandLineContracts[] = {
   { "@mozilla.org/toolkit/command-line;1", &kNS_COMMANDLINE_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kCommandLineModule = {
   mozilla::Module::kVersion,
   kCommandLineCIDs,
   kCommandLineContracts
 };
 
--- a/toolkit/components/ctypes/ctypes.cpp
+++ b/toolkit/components/ctypes/ctypes.cpp
@@ -26,22 +26,22 @@ namespace ctypes {
 static char*
 UnicodeToNative(JSContext *cx, const jschar *source, size_t slen)
 {
   nsAutoCString native;
   nsDependentString unicode(reinterpret_cast<const PRUnichar*>(source), slen);
   nsresult rv = NS_CopyUnicodeToNative(unicode, native);
   if (NS_FAILED(rv)) {
     JS_ReportError(cx, "could not convert string to native charset");
-    return NULL;
+    return nullptr;
   }
 
   char* result = static_cast<char*>(JS_malloc(cx, native.Length() + 1));
   if (!result)
-    return NULL;
+    return nullptr;
 
   memcpy(result, native.get(), native.Length() + 1);
   return result;
 }
 
 static JSCTypesCallbacks sCallbacks = {
   UnicodeToNative
 };
@@ -129,23 +129,23 @@ Module::Call(nsIXPConnectWrappedNative* 
 }
 
 }
 }
 
 NS_DEFINE_NAMED_CID(JSCTYPES_CID);
 
 static const mozilla::Module::CIDEntry kCTypesCIDs[] = {
-  { &kJSCTYPES_CID, false, NULL, mozilla::ctypes::ModuleConstructor },
-  { NULL }
+  { &kJSCTYPES_CID, false, nullptr, mozilla::ctypes::ModuleConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kCTypesContracts[] = {
   { JSCTYPES_CONTRACTID, &kJSCTYPES_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kCTypesModule = {
   mozilla::Module::kVersion,
   kCTypesCIDs,
   kCTypesContracts
 };
 
--- a/toolkit/components/ctypes/tests/jsctypes-test-errno.cpp
+++ b/toolkit/components/ctypes/tests/jsctypes-test-errno.cpp
@@ -11,17 +11,17 @@
 
 #include "jsctypes-test-errno.h"
 
 
 
 #define FAIL \
 { \
   fprintf(stderr, "Assertion failed at line %i\n", __LINE__); \
-  (*(int*)NULL)++; \
+  (*(int*)nullptr)++; \
 }
 
 
 void set_errno(int status)
 {
   errno = status;
 }
 int get_errno()
--- a/toolkit/components/ctypes/tests/jsctypes-test-finalizer.cpp
+++ b/toolkit/components/ctypes/tests/jsctypes-test-finalizer.cpp
@@ -14,29 +14,29 @@
 
 
 /**
  * An array of integers representing resources.
  * - 0: unacquired
  * - 1: acquired
  * - < 0: error, resource has been released several times.
  */
-int *gFinalizerTestResources = NULL;
-char **gFinalizerTestNames = NULL;
+int *gFinalizerTestResources = nullptr;
+char **gFinalizerTestNames = nullptr;
 size_t gFinalizerTestSize;
 
 void
 test_finalizer_start(size_t size)
 {
   gFinalizerTestResources = new int[size];
   gFinalizerTestNames = new char*[size];
   gFinalizerTestSize = size;
   for (size_t i = 0; i < size; ++i) {
     gFinalizerTestResources[i] = 0;
-    gFinalizerTestNames[i] = NULL;
+    gFinalizerTestNames[i] = nullptr;
   }
 }
 
 void
 test_finalizer_stop()
 {
   delete[] gFinalizerTestResources;
 }
@@ -192,31 +192,31 @@ test_finalizer_rel_int32_ptr_t(int32_t *
 }
 
 bool
 test_finalizer_cmp_int32_ptr_t(int32_t *a, int32_t *b)
 {
   return a==b;
 }
 
-// Resource type: NULL
+// Resource type: nullptr
 
 // Acquire resource i
 void*
 test_finalizer_acq_null_t(size_t i)
 {
   gFinalizerTestResources[0] = 1;//Always index 0
-  return NULL;
+  return nullptr;
 }
 
 // Release resource i
 void
 test_finalizer_rel_null_t(void *i)
 {
-  if (i != NULL) {
+  if (i != nullptr) {
     MOZ_CRASH("Assertion failed");
   }
   gFinalizerTestResources[0] --;
 }
 
 bool
 test_finalizer_null_resource_is_acquired(size_t)
 {
@@ -301,20 +301,20 @@ test_finalizer_struct_resource_is_acquir
 }
 
 bool
 test_finalizer_cmp_struct_t(RECT a, RECT b)
 {
   return a.top == b.top;
 }
 
-// Support for checking that we reject NULL finalizer
+// Support for checking that we reject nullptr finalizer
 afun* test_finalizer_rel_null_function()
 {
-  return NULL;
+  return nullptr;
 }
 
 void
 test_finalizer_rel_size_t_set_errno(size_t i)
 {
   if (-- gFinalizerTestResources[i] < 0) {
     MOZ_CRASH("Assertion failed");
   }
--- a/toolkit/components/downloads/SQLFunctions.cpp
+++ b/toolkit/components/downloads/SQLFunctions.cpp
@@ -58,18 +58,18 @@ NS_IMPL_ISUPPORTS1(
 )
 
 static
 nsresult
 Base64urlEncode(const uint8_t* aBytes,
                 uint32_t aNumBytes,
                 nsCString& _result)
 {
-  // SetLength does not set aside space for NULL termination.  PL_Base64Encode
-  // will not NULL terminate, however, nsCStrings must be NULL terminated.  As a
+  // SetLength does not set aside space for null termination.  PL_Base64Encode
+  // will not null terminate, however, nsCStrings must be null terminated.  As a
   // result, we set the capacity to be one greater than what we need, and the
   // length to our desired length.
   uint32_t length = (aNumBytes + 2) / 3 * 4; // +2 due to integer math.
   NS_ENSURE_TRUE(_result.SetCapacity(length + 1, mozilla::fallible_t()),
                  NS_ERROR_OUT_OF_MEMORY);
   _result.SetLength(length);
   (void)PL_Base64Encode(reinterpret_cast<const char*>(aBytes), aNumBytes,
                         _result.BeginWriting());
--- a/toolkit/components/downloads/nsDownloadManager.cpp
+++ b/toolkit/components/downloads/nsDownloadManager.cpp
@@ -2547,17 +2547,17 @@ nsDownloadManager::ConfirmCancelDownload
 
     aCancelDownloads->SetData(button == 1);
   }
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 //// nsDownload
 
-NS_IMPL_CLASSINFO(nsDownload, NULL, 0, NS_DOWNLOAD_CID)
+NS_IMPL_CLASSINFO(nsDownload, nullptr, 0, NS_DOWNLOAD_CID)
 NS_IMPL_ISUPPORTS4_CI(
     nsDownload
   , nsIDownload
   , nsITransfer
   , nsIWebProgressListener
   , nsIWebProgressListener2
 )
 
@@ -2585,18 +2585,18 @@ NS_IMETHODIMP nsDownload::SetSha256Hash(
   // This will be used later to query the application reputation service.
   mHash = aHash;
   return NS_OK;
 }
 
 #ifdef MOZ_ENABLE_GIO
 static void gio_set_metadata_done(GObject *source_obj, GAsyncResult *res, gpointer user_data)
 {
-  GError *err = NULL;
-  g_file_set_attributes_finish(G_FILE(source_obj), res, NULL, &err);
+  GError *err = nullptr;
+  g_file_set_attributes_finish(G_FILE(source_obj), res, nullptr, &err);
   if (err) {
 #ifdef DEBUG
     NS_DebugBreak(NS_DEBUG_WARNING, "Set file metadata failed: ", err->message, __FILE__, __LINE__);
 #endif
     g_error_free(err);
   }
 }
 #endif
@@ -2728,17 +2728,17 @@ nsDownload::SetState(DownloadState aStat
 
           if (addToRecentDocs && !mPrivate) {
 #ifdef XP_WIN
             ::SHAddToRecentDocs(SHARD_PATHW, path.get());
 #elif defined(MOZ_WIDGET_GTK)
             GtkRecentManager* manager = gtk_recent_manager_get_default();
 
             gchar* uri = g_filename_to_uri(NS_ConvertUTF16toUTF8(path).get(),
-                                           NULL, NULL);
+                                           nullptr, nullptr);
             if (uri) {
               gtk_recent_manager_add_item(manager, uri);
               g_free(uri);
             }
 #endif
           }
 #ifdef MOZ_ENABLE_GIO
           // Use GIO to store the source URI for later display in the file manager.
@@ -2746,30 +2746,30 @@ nsDownload::SetState(DownloadState aStat
           nsCString source_uri;
           mSource->GetSpec(source_uri);
           GFileInfo *file_info = g_file_info_new();
           g_file_info_set_attribute_string(file_info, "metadata::download-uri", source_uri.get());
           g_file_set_attributes_async(gio_file,
                                       file_info,
                                       G_FILE_QUERY_INFO_NONE,
                                       G_PRIORITY_DEFAULT,
-                                      NULL, gio_set_metadata_done, NULL);
+                                      nullptr, gio_set_metadata_done, nullptr);
           g_object_unref(file_info);
           g_object_unref(gio_file);
 #endif
         }
 #endif
 #ifdef XP_MACOSX
         // On OS X, make the downloads stack bounce.
         CFStringRef observedObject = ::CFStringCreateWithCString(kCFAllocatorDefault,
                                                  NS_ConvertUTF16toUTF8(path).get(),
                                                  kCFStringEncodingUTF8);
         CFNotificationCenterRef center = ::CFNotificationCenterGetDistributedCenter();
         ::CFNotificationCenterPostNotification(center, CFSTR("com.apple.DownloadFileFinished"),
-                                               observedObject, NULL, TRUE);
+                                               observedObject, nullptr, TRUE);
         ::CFRelease(observedObject);
 #endif
 #ifdef MOZ_WIDGET_ANDROID
         nsCOMPtr<nsIMIMEInfo> mimeInfo;
         nsAutoCString contentType;
         GetMIMEInfo(getter_AddRefs(mimeInfo));
 
         if (mimeInfo)
--- a/toolkit/components/downloads/nsDownloadScanner.cpp
+++ b/toolkit/components/downloads/nsDownloadScanner.cpp
@@ -156,17 +156,17 @@ nsDownloadScanner::~nsDownloadScanner() 
 }
 
 nsresult
 nsDownloadScanner::Init()
 {
   // This CoInitialize/CoUninitialize pattern seems to be common in the Mozilla
   // codebase. All other COM calls/objects are made on different threads.
   nsresult rv = NS_OK;
-  CoInitialize(NULL);
+  CoInitialize(nullptr);
 
   if (!IsAESAvailable()) {
     CoUninitialize();
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   mAESExists = true;
 
@@ -187,17 +187,17 @@ nsDownloadScanner::Init()
 }
 
 bool
 nsDownloadScanner::IsAESAvailable()
 {
   // Try to instantiate IAE to see if it's available.    
   nsRefPtr<IAttachmentExecute> ae;
   HRESULT hr;
-  hr = CoCreateInstance(CLSID_AttachmentServices, NULL, CLSCTX_INPROC,
+  hr = CoCreateInstance(CLSID_AttachmentServices, nullptr, CLSCTX_INPROC,
                         IID_IAttachmentExecute, getter_AddRefs(ae));
   if (FAILED(hr)) {
     NS_WARNING("Could not instantiate attachment execution service\n");
     return false;
   }
   return true;
 }
 
@@ -233,17 +233,17 @@ nsDownloadScanner::CheckPolicy(nsIURI *a
   nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(aSource);
   if (innerURI)
     (void)innerURI->SchemeIs("data", &isDataScheme);
   if (isDataScheme)
     return AVPOLICY_DOWNLOAD;
 
   nsRefPtr<IAttachmentExecute> ae;
   HRESULT hr;
-  hr = CoCreateInstance(CLSID_AttachmentServices, NULL, CLSCTX_INPROC,
+  hr = CoCreateInstance(CLSID_AttachmentServices, nullptr, CLSCTX_INPROC,
                         IID_IAttachmentExecute, getter_AddRefs(ae));
   if (FAILED(hr))
     return AVPOLICY_DOWNLOAD;
 
   (void)ae->SetClientGuid(GUID_MozillaVirusScannerPromptGeneric);
   (void)ae->SetSource(NS_ConvertUTF8toUTF16(source).get());
   (void)ae->SetFileName(aFileName.get());
 
@@ -300,34 +300,34 @@ private:
 nsresult ReleaseDispatcher::Run() {
   NS_ASSERTION(NS_IsMainThread(), "Antivirus scan release dispatch should be run on the main thread");
   NS_RELEASE(mPtr);
   NS_RELEASE_THIS();
   return NS_OK;
 }
 
 nsDownloadScanner::Scan::Scan(nsDownloadScanner *scanner, nsDownload *download)
-  : mDLScanner(scanner), mThread(NULL), 
+  : mDLScanner(scanner), mThread(nullptr), 
     mDownload(download), mStatus(AVSCAN_NOTSTARTED),
     mSkipSource(false)
 {
   InitializeCriticalSection(&mStateSync);
 }
 
 nsDownloadScanner::Scan::~Scan() {
   DeleteCriticalSection(&mStateSync);
 }
 
 nsresult
 nsDownloadScanner::Scan::Start()
 {
   mStartTime = PR_Now();
 
-  mThread = (HANDLE)_beginthreadex(NULL, 0, ScannerThreadFunction,
-      this, CREATE_SUSPENDED, NULL);
+  mThread = (HANDLE)_beginthreadex(nullptr, 0, ScannerThreadFunction,
+      this, CREATE_SUSPENDED, nullptr);
   if (!mThread)
     return NS_ERROR_OUT_OF_MEMORY;
 
   nsresult rv = NS_OK;
 
   // Get the path to the file on disk
   nsCOMPtr<nsIFile> file;
   rv = mDownload->GetTargetFile(getter_AddRefs(file));
@@ -441,17 +441,17 @@ bool
 nsDownloadScanner::Scan::DoScanAES()
 {
   // This warning is for the destructor of ae which will not be invoked in the
   // event of a win32 exception
 #pragma warning(disable: 4509)
   HRESULT hr;
   nsRefPtr<IAttachmentExecute> ae;
   MOZ_SEH_TRY {
-    hr = CoCreateInstance(CLSID_AttachmentServices, NULL, CLSCTX_ALL,
+    hr = CoCreateInstance(CLSID_AttachmentServices, nullptr, CLSCTX_ALL,
                           IID_IAttachmentExecute, getter_AddRefs(ae));
   } MOZ_SEH_EXCEPT(ExceptionFilterFunction(GetExceptionCode())) {
     return CheckAndSetState(AVSCAN_NOTSTARTED,AVSCAN_FAILED);
   }
 
   // If we (somehow) already timed out, then don't bother scanning
   if (CheckAndSetState(AVSCAN_SCANNING, AVSCAN_NOTSTARTED)) {
     AVScanState newState;
@@ -466,17 +466,17 @@ nsDownloadScanner::Scan::DoScanAES()
 
         // Save() will invoke the scanner
         hr = ae->Save();
       } MOZ_SEH_EXCEPT(ExceptionFilterFunction(GetExceptionCode())) {
         gotException = true;
       }
 
       MOZ_SEH_TRY {
-        ae = NULL;
+        ae = nullptr;
       } MOZ_SEH_EXCEPT(ExceptionFilterFunction(GetExceptionCode())) {
         gotException = true;
       }
 
       if(gotException) {
         newState = AVSCAN_FAILED;
       }
       else if (SUCCEEDED(hr)) { // Passed the scan
@@ -501,17 +501,17 @@ nsDownloadScanner::Scan::DoScanAES()
   }
   return false;
 }
 #pragma warning(default: 4509)
 
 void
 nsDownloadScanner::Scan::DoScan()
 {
-  CoInitialize(NULL);
+  CoInitialize(nullptr);
 
   if (DoScanAES()) {
     // We need to do a few more things on the main thread
     NS_DispatchToMainThread(this);
   } else {
     // We timed out, so just release
     ReleaseDispatcher* releaser = new ReleaseDispatcher(this);
     if(releaser) {
@@ -583,39 +583,39 @@ nsDownloadScanner::ScanDownload(nsDownlo
   else
     // Notify the watchdog
     mWatchdog->Watch(scan);
 
   return rv;
 }
 
 nsDownloadScannerWatchdog::nsDownloadScannerWatchdog() 
-  : mNewItemEvent(NULL), mQuitEvent(NULL) {
+  : mNewItemEvent(nullptr), mQuitEvent(nullptr) {
   InitializeCriticalSection(&mQueueSync);
 }
 nsDownloadScannerWatchdog::~nsDownloadScannerWatchdog() {
   DeleteCriticalSection(&mQueueSync);
 }
 
 nsresult
 nsDownloadScannerWatchdog::Init() {
   // Both events are auto-reset
-  mNewItemEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+  mNewItemEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
   if (INVALID_HANDLE_VALUE == mNewItemEvent)
     return NS_ERROR_OUT_OF_MEMORY;
-  mQuitEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+  mQuitEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
   if (INVALID_HANDLE_VALUE == mQuitEvent) {
     (void)CloseHandle(mNewItemEvent);
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   // This thread is always running, however it will be asleep
   // for most of the dlmgr's lifetime
-  mThread = (HANDLE)_beginthreadex(NULL, 0, WatchdogThread,
-                                   this, 0, NULL);
+  mThread = (HANDLE)_beginthreadex(nullptr, 0, WatchdogThread,
+                                   this, 0, nullptr);
   if (!mThread) {
     (void)CloseHandle(mNewItemEvent);
     (void)CloseHandle(mQuitEvent);
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   return NS_OK;
 }
@@ -662,17 +662,17 @@ nsDownloadScannerWatchdog::WatchdogThrea
   DWORD waitStatus;
   DWORD queueItemsLeft = 0;
   // Loop until quit event or error
   while (0 != queueItemsLeft ||
          (WAIT_OBJECT_0 + 1) !=
            (waitStatus =
               WaitForMultipleObjects(2, waitHandles, FALSE, INFINITE)) &&
          waitStatus != WAIT_FAILED) {
-    Scan *scan = NULL;
+    Scan *scan = nullptr;
     PRTime startTime, expectedEndTime, now;
     DWORD waitTime;
 
     // Pop scan from queue
     EnterCriticalSection(&watchdog->mQueueSync);
     scan = reinterpret_cast<Scan*>(watchdog->mScanQueue.Pop());
     queueItemsLeft = watchdog->mScanQueue.GetSize();
     LeaveCriticalSection(&watchdog->mQueueSync);
--- a/toolkit/components/filepicker/nsFileView.cpp
+++ b/toolkit/components/filepicker/nsFileView.cpp
@@ -248,25 +248,25 @@ protected:
 
 // Factory constructor
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsFileComplete)
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsFileView, Init)
 NS_DEFINE_NAMED_CID(NS_FILECOMPLETE_CID);
 NS_DEFINE_NAMED_CID(NS_FILEVIEW_CID);
 
 static const mozilla::Module::CIDEntry kFileViewCIDs[] = {
-  { &kNS_FILECOMPLETE_CID, false, NULL, nsFileCompleteConstructor },
-  { &kNS_FILEVIEW_CID, false, NULL, nsFileViewConstructor },
-  { NULL }
+  { &kNS_FILECOMPLETE_CID, false, nullptr, nsFileCompleteConstructor },
+  { &kNS_FILEVIEW_CID, false, nullptr, nsFileViewConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kFileViewContracts[] = {
   { NS_FILECOMPLETE_CONTRACTID, &kNS_FILECOMPLETE_CID },
   { NS_FILEVIEW_CONTRACTID, &kNS_FILEVIEW_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kFileViewModule = {
   mozilla::Module::kVersion,
   kFileViewCIDs,
   kFileViewContracts
 };
 
--- a/toolkit/components/intl/nsCharsetMenu.cpp
+++ b/toolkit/components/intl/nsCharsetMenu.cpp
@@ -441,34 +441,34 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsCharsetMenu)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsCharsetMenu)
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsCharsetMenu)
   NS_INTERFACE_MAP_ENTRY(nsIRDFDataSource)
   NS_INTERFACE_MAP_ENTRY(nsICurrentCharsetListener)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIRDFDataSource)
 NS_INTERFACE_MAP_END
 
-nsIRDFDataSource * nsCharsetMenu::mInner = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_BrowserAutodetMenuRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_BrowserCharsetMenuRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_BrowserMoreCharsetMenuRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_BrowserMore1CharsetMenuRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_BrowserMore2CharsetMenuRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_BrowserMore3CharsetMenuRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_BrowserMore4CharsetMenuRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_BrowserMore5CharsetMenuRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_MaileditCharsetMenuRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_MailviewCharsetMenuRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_ComposerCharsetMenuRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_DecodersRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_EncodersRoot = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_Name = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_CharsetDetector = NULL;
-nsIRDFResource * nsCharsetMenu::kNC_BookmarkSeparator = NULL;
-nsIRDFResource * nsCharsetMenu::kRDF_type = NULL;
+nsIRDFDataSource * nsCharsetMenu::mInner = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_BrowserAutodetMenuRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_BrowserCharsetMenuRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_BrowserMoreCharsetMenuRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_BrowserMore1CharsetMenuRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_BrowserMore2CharsetMenuRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_BrowserMore3CharsetMenuRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_BrowserMore4CharsetMenuRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_BrowserMore5CharsetMenuRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_MaileditCharsetMenuRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_MailviewCharsetMenuRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_ComposerCharsetMenuRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_DecodersRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_EncodersRoot = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_Name = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_CharsetDetector = nullptr;
+nsIRDFResource * nsCharsetMenu::kNC_BookmarkSeparator = nullptr;
+nsIRDFResource * nsCharsetMenu::kRDF_type = nullptr;
 
 nsCharsetMenu::nsCharsetMenu() 
 : mInitialized(false), 
   mBrowserMenuInitialized(false),
   mMailviewMenuInitialized(false),
   mComposerMenuInitialized(false),
   mMaileditMenuInitialized(false),
   mSecondaryTiersInitialized(false),
@@ -624,17 +624,17 @@ nsresult nsCharsetMenu::RefreshMaileditM
   nsCOMPtr<nsIUTF8StringEnumerator> encoders;
   res = mCCManager->GetEncoderList(getter_AddRefs(encoders));
   NS_ENSURE_SUCCESS(res, res);
 
   nsTArray<nsCString> encs;
   SetArrayFromEnumerator(encoders, encs);
   
   // add menu items from pref
-  res = AddFromPrefsToMenu(NULL, container, kMaileditPrefKey, encs, NULL);
+  res = AddFromPrefsToMenu(nullptr, container, kMaileditPrefKey, encs, nullptr);
   NS_ASSERTION(NS_SUCCEEDED(res), "error initializing mailedit charset menu from prefs");
 
   return res;
 }
 
 nsresult nsCharsetMenu::RefreshComposerMenu()
 {
   nsresult res = NS_OK;
@@ -709,45 +709,45 @@ nsresult nsCharsetMenu::Init()
     mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_Name),
                              &kNC_Name);
     mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_CharsetDetector),
                              &kNC_CharsetDetector);
     mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_BookmarkSeparator),
                              &kNC_BookmarkSeparator);
     mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_type), &kRDF_type);
 
-    nsIRDFContainerUtils * rdfUtil = NULL;
+    nsIRDFContainerUtils * rdfUtil = nullptr;
     res = CallGetService(kRDFContainerUtilsCID, &rdfUtil);
     if (NS_FAILED(res)) goto done;
 
-    res = rdfUtil->MakeSeq(mInner, kNC_BrowserAutodetMenuRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_BrowserAutodetMenuRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_BrowserCharsetMenuRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_BrowserCharsetMenuRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMoreCharsetMenuRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMoreCharsetMenuRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore1CharsetMenuRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore1CharsetMenuRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore2CharsetMenuRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore2CharsetMenuRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore3CharsetMenuRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore3CharsetMenuRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore4CharsetMenuRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore4CharsetMenuRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore5CharsetMenuRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore5CharsetMenuRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_MaileditCharsetMenuRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_MaileditCharsetMenuRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_MailviewCharsetMenuRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_MailviewCharsetMenuRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_ComposerCharsetMenuRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_ComposerCharsetMenuRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_DecodersRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_DecodersRoot, nullptr);
     if (NS_FAILED(res)) goto done;
-    res = rdfUtil->MakeSeq(mInner, kNC_EncodersRoot, NULL);
+    res = rdfUtil->MakeSeq(mInner, kNC_EncodersRoot, nullptr);
     if (NS_FAILED(res)) goto done;
 
   done:
     NS_IF_RELEASE(rdfUtil);
     if (NS_FAILED(res)) return res;
   }
   mInitialized = NS_SUCCEEDED(res);
   return res;
@@ -788,19 +788,19 @@ nsresult nsCharsetMenu::FreeResources()
   nsresult res = NS_OK;
 
   if (mCharsetMenuObserver) {
     mPrefs->RemoveObserver(kBrowserStaticPrefKey, mCharsetMenuObserver);
     mPrefs->RemoveObserver(kMaileditPrefKey, mCharsetMenuObserver);
     /* nsIObserverService has to have released nsCharsetMenu already */
   }
 
-  mRDFService = NULL;
-  mCCManager  = NULL;
-  mPrefs      = NULL;
+  mRDFService = nullptr;
+  mCCManager  = nullptr;
+  mPrefs      = nullptr;
 
   return res;
 }
 
 nsresult nsCharsetMenu::InitBrowserMenu() 
 {
   nsresult res = NS_OK;
 
@@ -859,17 +859,18 @@ nsresult nsCharsetMenu::InitMaileditMenu
     // encoders further guarding  against  'font encoders' sneaking in. 
     nsCOMPtr<nsIUTF8StringEnumerator> encoders;
     res = mCCManager->GetEncoderList(getter_AddRefs(encoders));
     if (NS_FAILED(res))  return res;
 
     nsTArray<nsCString> maileditEncoderList;
     SetArrayFromEnumerator(encoders, maileditEncoderList);
   
-    res = AddFromPrefsToMenu(NULL, container, kMaileditPrefKey, maileditEncoderList, NULL);
+    res = AddFromPrefsToMenu(nullptr, container, kMaileditPrefKey,
+                             maileditEncoderList, nullptr);
     NS_ASSERTION(NS_SUCCEEDED(res), "error initializing mailedit charset menu from prefs");
 
     // register prefs callback
     mPrefs->AddObserver(kMaileditPrefKey, mCharsetMenuObserver, false);
   }
 
   mMaileditMenuInitialized = NS_SUCCEEDED(res);
 
@@ -1093,17 +1094,17 @@ nsresult nsCharsetMenu::InitMoreMenu(nsT
 
   res = AddCharsetArrayToItemArray(moreMenu, aDecs);
   if (NS_FAILED(res)) goto done;
 
   // reorder the array
   res = ReorderMenuItemArray(&moreMenu);
   if (NS_FAILED(res)) goto done;
 
-  res = AddMenuItemArrayToContainer(container, &moreMenu, NULL);
+  res = AddMenuItemArrayToContainer(container, &moreMenu, nullptr);
   if (NS_FAILED(res)) goto done;
 
 done:
   // free the elements in the VoidArray
   FreeMenuItemArray(&moreMenu);
 
   return res;
 }
@@ -1122,92 +1123,92 @@ nsresult nsCharsetMenu::InitMoreSubmenus
   const char key2[] = "intl.charsetmenu.browser.more2";
   const char key3[] = "intl.charsetmenu.browser.more3";
   const char key4[] = "intl.charsetmenu.browser.more4";
   const char key5[] = "intl.charsetmenu.browser.more5";
 
   res = NewRDFContainer(mInner, kNC_BrowserMore1CharsetMenuRoot, 
     getter_AddRefs(container1));
   if (NS_FAILED(res)) return res;
-  AddFromNolocPrefsToMenu(NULL, container1, key1, aDecs, NULL);
+  AddFromNolocPrefsToMenu(nullptr, container1, key1, aDecs, nullptr);
 
   res = NewRDFContainer(mInner, kNC_BrowserMore2CharsetMenuRoot, 
     getter_AddRefs(container2));
   if (NS_FAILED(res)) return res;
-  AddFromNolocPrefsToMenu(NULL, container2, key2, aDecs, NULL);
+  AddFromNolocPrefsToMenu(nullptr, container2, key2, aDecs, nullptr);
 
   res = NewRDFContainer(mInner, kNC_BrowserMore3CharsetMenuRoot, 
     getter_AddRefs(container3));
   if (NS_FAILED(res)) return res;
-  AddFromNolocPrefsToMenu(NULL, container3, key3, aDecs, NULL);
+  AddFromNolocPrefsToMenu(nullptr, container3, key3, aDecs, nullptr);
 
   res = NewRDFContainer(mInner, kNC_BrowserMore4CharsetMenuRoot, 
     getter_AddRefs(container4));
   if (NS_FAILED(res)) return res;
-  AddFromNolocPrefsToMenu(NULL, container4, key4, aDecs, NULL);
+  AddFromNolocPrefsToMenu(nullptr, container4, key4, aDecs, nullptr);
 
   res = NewRDFContainer(mInner, kNC_BrowserMore5CharsetMenuRoot, 
     getter_AddRefs(container5));
   if (NS_FAILED(res)) return res;
-  AddFromNolocPrefsToMenu(NULL, container5, key5, aDecs, NULL);
+  AddFromNolocPrefsToMenu(nullptr, container5, key5, aDecs, nullptr);
 
   return res;
 }
 
 nsresult nsCharsetMenu::AddCharsetToItemArray(nsTArray<nsMenuEntry*> *aArray,
                                               const nsAFlatCString& aCharset,
                                               nsMenuEntry ** aResult,
                                               int32_t aPlace)
 {
   nsresult res = NS_OK;
-  nsMenuEntry * item = NULL; 
+  nsMenuEntry * item = nullptr; 
 
-  if (aResult != NULL) *aResult = NULL;
+  if (aResult != nullptr) *aResult = nullptr;
   
   item = new nsMenuEntry();
-  if (item == NULL) {
+  if (item == nullptr) {
     res = NS_ERROR_OUT_OF_MEMORY;
     goto done;
   }
 
   item->mCharset = aCharset;
 
   if (NS_FAILED(mCCManager->GetCharsetTitle(aCharset.get(), item->mTitle))) {
     item->mTitle.AssignWithConversion(aCharset.get());
   }
 
-  if (aArray != NULL) {
+  if (aArray != nullptr) {
     if (aPlace < 0) {
       aArray->AppendElement(item);
     } else {
       aArray->InsertElementsAt(aPlace, 1, item);
     }
   }
 
-  if (aResult != NULL) *aResult = item;
+  if (aResult != nullptr) *aResult = item;
 
   // if we have made another reference to "item", do not delete it 
-  if ((aArray != NULL) || (aResult != NULL)) item = NULL; 
+  if ((aArray != nullptr) || (aResult != nullptr)) item = nullptr; 
 
 done:
-  if (item != NULL) delete item;
+  if (item != nullptr) delete item;
 
   return res;
 }
 
 nsresult
 nsCharsetMenu::AddCharsetArrayToItemArray(nsTArray<nsMenuEntry*>& aArray,
                                           const nsTArray<nsCString>& aCharsets)
 {
   uint32_t count = aCharsets.Length();
 
   for (uint32_t i = 0; i < count; i++) {
 
     const nsCString& str = aCharsets[i];
-    nsresult res = AddCharsetToItemArray(&aArray, str, NULL, -1);
+    nsresult res = AddCharsetToItemArray(&aArray, str, nullptr, -1);
     
     if (NS_FAILED(res))
       return res;
   }
 
   return NS_OK;
 }
 
@@ -1219,17 +1220,17 @@ nsresult nsCharsetMenu::AddMenuItemToCon
                         nsIRDFResource * aType,
                         const char * aIDPrefix,
                         int32_t aPlace) 
 {
   nsresult res = NS_OK;
   nsCOMPtr<nsIRDFResource> node;
 
   nsAutoCString id;
-  if (aIDPrefix != NULL) id.Assign(aIDPrefix);
+  if (aIDPrefix != nullptr) id.Assign(aIDPrefix);
   id.Append(aItem->mCharset);
 
   // Make up a unique ID and create the RDF NODE
   res = mRDFService->GetResource(id, getter_AddRefs(node));
   if (NS_FAILED(res)) return res;
 
   const PRUnichar * title = aItem->mTitle.get();
 
@@ -1241,17 +1242,17 @@ nsresult nsCharsetMenu::AddMenuItemToCon
   if (aPlace < -1) {
     res = Unassert(node, kNC_Name, titleLiteral);
     if (NS_FAILED(res)) return res;
   } else {
     res = Assert(node, kNC_Name, titleLiteral, true);
     if (NS_FAILED(res)) return res;
   }
 
-  if (aType != NULL) {
+  if (aType != nullptr) {
     if (aPlace < -1) {
       res = Unassert(node, kRDF_type, aType);
       if (NS_FAILED(res)) return res;
     } else {
       res = Assert(node, kRDF_type, aType, true);
       if (NS_FAILED(res)) return res;
     }
   }
@@ -1276,47 +1277,47 @@ nsresult nsCharsetMenu::AddMenuItemArray
                         nsTArray<nsMenuEntry*> * aArray,
                         nsIRDFResource * aType) 
 {
   uint32_t count = aArray->Length();
   nsresult res = NS_OK;
 
   for (uint32_t i = 0; i < count; i++) {
     nsMenuEntry * item = aArray->ElementAt(i);
-    if (item == NULL) return NS_ERROR_UNEXPECTED;
+    if (item == nullptr) return NS_ERROR_UNEXPECTED;
 
-    res = AddMenuItemToContainer(aContainer, item, aType, NULL, -1);
+    res = AddMenuItemToContainer(aContainer, item, aType, nullptr, -1);
     if (NS_FAILED(res)) return res;
   }
 
   return NS_OK;
 }
 
 nsresult nsCharsetMenu::AddCharsetToContainer(nsTArray<nsMenuEntry*> *aArray,
                                               nsIRDFContainer * aContainer,
                                               const nsAFlatCString& aCharset,
                                               const char * aIDPrefix,
                                               int32_t aPlace,
                                               int32_t aRDFPlace)
 {
   nsresult res = NS_OK;
-  nsMenuEntry * item = NULL; 
+  nsMenuEntry * item = nullptr; 
   
   res = AddCharsetToItemArray(aArray, aCharset, &item, aPlace);
   if (NS_FAILED(res)) goto done;
 
-  res = AddMenuItemToContainer(aContainer, item, NULL, aIDPrefix, 
+  res = AddMenuItemToContainer(aContainer, item, nullptr, aIDPrefix, 
     aPlace + aRDFPlace);
   if (NS_FAILED(res)) goto done;
 
   // if we have made another reference to "item", do not delete it 
-  if (aArray != NULL) item = NULL; 
+  if (aArray != nullptr) item = nullptr; 
 
 done:
-  if (item != NULL) delete item;
+  if (item != nullptr) delete item;
 
   return res;
 }
 
 nsresult nsCharsetMenu::AddFromPrefsToMenu(
                         nsTArray<nsMenuEntry*> * aArray,
                         nsIRDFContainer * aContainer,
                         const char * aKey,
@@ -1345,21 +1346,21 @@ nsresult
 nsCharsetMenu::AddFromNolocPrefsToMenu(nsTArray<nsMenuEntry*> * aArray,
                                        nsIRDFContainer * aContainer,
                                        const char * aKey,
                                        nsTArray<nsCString>& aDecs,
                                        const char * aIDPrefix)
 {
   nsresult res = NS_OK;
 
-  char * value = NULL;
+  char * value = nullptr;
   res = mPrefs->GetCharPref(aKey, &value);
   if (NS_FAILED(res)) return res;
 
-  if (value != NULL) {
+  if (value != nullptr) {
     res = AddFromStringToMenu(value, aArray, aContainer, aDecs, aIDPrefix);
     nsMemory::Free(value);
   }
 
   return res;
 }
 
 nsresult nsCharsetMenu::AddFromStringToMenu(
@@ -1409,31 +1410,31 @@ nsresult nsCharsetMenu::AddSeparatorToCo
   u++;
   str.AppendInt(u);
 
   nsMenuEntry item;
   item.mCharset = str;
   item.mTitle.AssignWithConversion(str.get());
 
   return AddMenuItemToContainer(aContainer, &item, kNC_BookmarkSeparator, 
-    NULL, -1);
+    nullptr, -1);
 }
 
 nsresult
 nsCharsetMenu::AddCharsetToCache(const nsAFlatCString& aCharset,
                                  nsTArray<nsMenuEntry*> * aArray,
                                  nsIRDFResource * aRDFResource,
                                  uint32_t aCacheStart,
                                  uint32_t aCacheSize,
                                  int32_t aRDFPlace)
 {
   int32_t i;
   nsresult res = NS_OK;
 
-  i = FindMenuItemInArray(aArray, aCharset, NULL);
+  i = FindMenuItemInArray(aArray, aCharset, nullptr);
   if (i >= 0) return res;
 
   nsCOMPtr<nsIRDFContainer> container;
   res = NewRDFContainer(mInner, aRDFResource, getter_AddRefs(container));
   if (NS_FAILED(res)) return res;
 
   // if too many items, remove last one
   if (aArray->Length() - aCacheStart >= aCacheSize){
@@ -1455,17 +1456,17 @@ nsresult nsCharsetMenu::WriteCacheToPref
 
   // create together the cache string
   nsAutoCString cache;
   nsAutoCString sep(NS_LITERAL_CSTRING(", "));
   uint32_t count = aArray->Length();
 
   for (uint32_t i = aCacheStart; i < count; i++) {
     nsMenuEntry * item = aArray->ElementAt(i);
-    if (item != NULL) {    
+    if (item != nullptr) {    
       cache.Append(item->mCharset);
       if (i < count - 1) {
         cache.Append(sep);
       }
     }
   }
 
   // write the pref
@@ -1512,18 +1513,18 @@ nsresult nsCharsetMenu::ClearMenu(nsIRDF
                                   nsTArray<nsMenuEntry*> * aArray)
 {
   nsresult res = NS_OK;
 
   // clean the RDF data source
   uint32_t count = aArray->Length();
   for (uint32_t i = 0; i < count; i++) {
     nsMenuEntry * item = aArray->ElementAt(i);
-    if (item != NULL) {    
-      res = AddMenuItemToContainer(aContainer, item, NULL, "charset.", -2);
+    if (item != nullptr) {    
+      res = AddMenuItemToContainer(aContainer, item, nullptr, "charset.", -2);
       if (NS_FAILED(res)) return res;
     }
   }
 
   // clean the internal data structures
   FreeMenuItemArray(aArray);
 
   return res;
@@ -1532,18 +1533,18 @@ nsresult nsCharsetMenu::ClearMenu(nsIRDF
 nsresult nsCharsetMenu::RemoveLastMenuItem(nsIRDFContainer * aContainer,
                                            nsTArray<nsMenuEntry*> * aArray)
 {
   nsresult res = NS_OK;
 
   int32_t last = aArray->Length() - 1;
   if (last >= 0) {
     nsMenuEntry * item = aArray->ElementAt(last);
-    if (item != NULL) {    
-      res = AddMenuItemToContainer(aContainer, item, NULL, "charset.", -2);
+    if (item != nullptr) {    
+      res = AddMenuItemToContainer(aContainer, item, nullptr, "charset.", -2);
       if (NS_FAILED(res)) return res;
 
       aArray->RemoveElementAt(last);
     }
   }
 
   return res;
 }
@@ -1585,38 +1586,38 @@ nsresult nsCharsetMenu::NewRDFContainer(
   return res;
 }
 
 void nsCharsetMenu::FreeMenuItemArray(nsTArray<nsMenuEntry*> * aArray)
 {
   uint32_t count = aArray->Length();
   for (uint32_t i = 0; i < count; i++) {
     nsMenuEntry * item = aArray->ElementAt(i);
-    if (item != NULL) {
+    if (item != nullptr) {
       delete item;
     }
   }
   aArray->Clear();
 }
 
 int32_t nsCharsetMenu::FindMenuItemInArray(const nsTArray<nsMenuEntry*>* aArray,
                                            const nsAFlatCString& aCharset,
                                            nsMenuEntry ** aResult)
 {
   uint32_t count = aArray->Length();
 
   for (uint32_t i=0; i < count; i++) {
     nsMenuEntry * item = aArray->ElementAt(i);
     if (item->mCharset == aCharset) {
-      if (aResult != NULL) *aResult = item;
+      if (aResult != nullptr) *aResult = item;
       return i;
     }
   }
 
-  if (aResult != NULL) *aResult = NULL;
+  if (aResult != nullptr) *aResult = nullptr;
   return -1;
 }
 
 nsresult nsCharsetMenu::ReorderMenuItemArray(nsTArray<nsMenuEntry*> * aArray)
 {
   nsresult res = NS_OK;
   nsCOMPtr<nsICollation> collation;
   uint32_t count = aArray->Length();
--- a/toolkit/components/jsdownloads/src/DownloadPlatform.cpp
+++ b/toolkit/components/jsdownloads/src/DownloadPlatform.cpp
@@ -48,18 +48,18 @@ DownloadPlatform* DownloadPlatform::GetD
 #endif
 
   return gDownloadPlatformService;
 }
 
 #ifdef MOZ_ENABLE_GIO
 static void gio_set_metadata_done(GObject *source_obj, GAsyncResult *res, gpointer user_data)
 {
-  GError *err = NULL;
-  g_file_set_attributes_finish(G_FILE(source_obj), res, NULL, &err);
+  GError *err = nullptr;
+  g_file_set_attributes_finish(G_FILE(source_obj), res, nullptr, &err);
   if (err) {
 #ifdef DEBUG
     NS_DebugBreak(NS_DEBUG_WARNING, "Set file metadata failed: ", err->message, __FILE__, __LINE__);
 #endif
     g_error_free(err);
   }
 }
 #endif
@@ -77,17 +77,17 @@ nsresult DownloadPlatform::DownloadDone(
       bool addToRecentDocs = Preferences::GetBool(PREF_BDM_ADDTORECENTDOCS);
       if (addToRecentDocs && !aIsPrivate) {
 #ifdef XP_WIN
         ::SHAddToRecentDocs(SHARD_PATHW, path.get());
 #elif defined(MOZ_WIDGET_GTK)
         GtkRecentManager* manager = gtk_recent_manager_get_default();
 
         gchar* uri = g_filename_to_uri(NS_ConvertUTF16toUTF8(path).get(),
-                                       NULL, NULL);
+                                       nullptr, nullptr);
         if (uri) {
           gtk_recent_manager_add_item(manager, uri);
           g_free(uri);
         }
 #endif
       }
 #ifdef MOZ_ENABLE_GIO
       // Use GIO to store the source URI for later display in the file manager.
@@ -95,30 +95,30 @@ nsresult DownloadPlatform::DownloadDone(
       nsCString source_uri;
       aSource->GetSpec(source_uri);
       GFileInfo *file_info = g_file_info_new();
       g_file_info_set_attribute_string(file_info, "metadata::download-uri", source_uri.get());
       g_file_set_attributes_async(gio_file,
                                   file_info,
                                   G_FILE_QUERY_INFO_NONE,
                                   G_PRIORITY_DEFAULT,
-                                  NULL, gio_set_metadata_done, NULL);
+                                  nullptr, gio_set_metadata_done, nullptr);
       g_object_unref(file_info);
       g_object_unref(gio_file);
 #endif
     }
 #endif
 #ifdef XP_MACOSX
     // On OS X, make the downloads stack bounce.
     CFStringRef observedObject = ::CFStringCreateWithCString(kCFAllocatorDefault,
                                              NS_ConvertUTF16toUTF8(path).get(),
                                              kCFStringEncodingUTF8);
     CFNotificationCenterRef center = ::CFNotificationCenterGetDistributedCenter();
     ::CFNotificationCenterPostNotification(center, CFSTR("com.apple.DownloadFileFinished"),
-                                           observedObject, NULL, TRUE);
+                                           observedObject, nullptr, TRUE);
     ::CFRelease(observedObject);
 #endif
 #ifdef MOZ_WIDGET_ANDROID
     if (!aContentType.IsEmpty()) {
       mozilla::AndroidBridge::Bridge()->ScanMedia(path, NS_ConvertUTF8toUTF16(aContentType));
     }
 #endif
   }
--- a/toolkit/components/maintenanceservice/certificatecheck.cpp
+++ b/toolkit/components/maintenanceservice/certificatecheck.cpp
@@ -23,40 +23,40 @@ static const int ENCODING = X509_ASN_ENC
  * @param  infoToMatch The acceptable information to match
  * @return ERROR_SUCCESS if successful, ERROR_NOT_FOUND if the info 
  *         does not match, or the last error otherwise.
  */
 DWORD
 CheckCertificateForPEFile(LPCWSTR filePath, 
                           CertificateCheckInfo &infoToMatch)
 {
-  HCERTSTORE certStore = NULL;
-  HCRYPTMSG cryptMsg = NULL; 
-  PCCERT_CONTEXT certContext = NULL;
-  PCMSG_SIGNER_INFO signerInfo = NULL;
+  HCERTSTORE certStore = nullptr;
+  HCRYPTMSG cryptMsg = nullptr; 
+  PCCERT_CONTEXT certContext = nullptr;
+  PCMSG_SIGNER_INFO signerInfo = nullptr;
   DWORD lastError = ERROR_SUCCESS;
 
   // Get the HCERTSTORE and HCRYPTMSG from the signed file.
   DWORD encoding, contentType, formatType;
   BOOL result = CryptQueryObject(CERT_QUERY_OBJECT_FILE,
                                   filePath, 
                                   CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
                                   CERT_QUERY_CONTENT_FLAG_ALL, 
                                   0, &encoding, &contentType,
-                                  &formatType, &certStore, &cryptMsg, NULL);
+                                  &formatType, &certStore, &cryptMsg, nullptr);
   if (!result) {
     lastError = GetLastError();
     LOG_WARN(("CryptQueryObject failed.  (%d)", lastError));
     goto cleanup;
   }
 
-  // Pass in NULL to get the needed signer information size.
+  // Pass in nullptr to get the needed signer information size.
   DWORD signerInfoSize;
   result = CryptMsgGetParam(cryptMsg, CMSG_SIGNER_INFO_PARAM, 0, 
-                            NULL, &signerInfoSize);
+                            nullptr, &signerInfoSize);
   if (!result) {
     lastError = GetLastError();
     LOG_WARN(("CryptMsgGetParam failed.  (%d)", lastError));
     goto cleanup;
   }
 
   // Allocate the needed size for the signer information.
   signerInfo = (PCMSG_SIGNER_INFO)LocalAlloc(LPTR, signerInfoSize);
@@ -77,17 +77,17 @@ CheckCertificateForPEFile(LPCWSTR filePa
   }
 
   // Search for the signer certificate in the certificate store.
   CERT_INFO certInfo;     
   certInfo.Issuer = signerInfo->Issuer;
   certInfo.SerialNumber = signerInfo->SerialNumber;
   certContext = CertFindCertificateInStore(certStore, ENCODING, 0, 
                                            CERT_FIND_SUBJECT_CERT,
-                                           (PVOID)&certInfo, NULL);
+                                           (PVOID)&certInfo, nullptr);
   if (!certContext) {
     lastError = GetLastError();
     LOG_WARN(("CertFindCertificateInStore failed.  (%d)", lastError));
     goto cleanup;
   }
 
   if (!DoCertificateAttributesMatch(certContext, infoToMatch)) {
     lastError = ERROR_NOT_FOUND;
@@ -118,77 +118,77 @@ cleanup:
  * @param  infoToMatch  The acceptable information to match
  * @return FALSE if the info does not match or if any error occurs in the check
  */
 BOOL 
 DoCertificateAttributesMatch(PCCERT_CONTEXT certContext, 
                              CertificateCheckInfo &infoToMatch)
 {
   DWORD dwData;
-  LPTSTR szName = NULL;
+  LPTSTR szName = nullptr;
 
   if (infoToMatch.issuer) {
-    // Pass in NULL to get the needed size of the issuer buffer.
+    // Pass in nullptr to get the needed size of the issuer buffer.
     dwData = CertGetNameString(certContext, 
                                CERT_NAME_SIMPLE_DISPLAY_TYPE,
-                               CERT_NAME_ISSUER_FLAG, NULL,
-                               NULL, 0);
+                               CERT_NAME_ISSUER_FLAG, nullptr,
+                               nullptr, 0);
 
     if (!dwData) {
       LOG_WARN(("CertGetNameString failed.  (%d)", GetLastError()));
       return FALSE;
     }
 
     // Allocate memory for Issuer name buffer.
     LPTSTR szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(WCHAR));
     if (!szName) {
       LOG_WARN(("Unable to allocate memory for issuer name.  (%d)",
                 GetLastError()));
       return FALSE;
     }
 
     // Get Issuer name.
     if (!CertGetNameString(certContext, CERT_NAME_SIMPLE_DISPLAY_TYPE,
-                           CERT_NAME_ISSUER_FLAG, NULL, szName, dwData)) {
+                           CERT_NAME_ISSUER_FLAG, nullptr, szName, dwData)) {
       LOG_WARN(("CertGetNameString failed.  (%d)", GetLastError()));
       LocalFree(szName);
       return FALSE;
     }
 
     // If the issuer does not match, return a failure.
     if (!infoToMatch.issuer ||
         wcscmp(szName, infoToMatch.issuer)) {
       LocalFree(szName);
       return FALSE;
     }
 
     LocalFree(szName);
-    szName = NULL;
+    szName = nullptr;
   }
 
   if (infoToMatch.name) {
-    // Pass in NULL to get the needed size of the name buffer.
+    // Pass in nullptr to get the needed size of the name buffer.
     dwData = CertGetNameString(certContext, CERT_NAME_SIMPLE_DISPLAY_TYPE,
-                               0, NULL, NULL, 0);
+                               0, nullptr, nullptr, 0);
     if (!dwData) {
       LOG_WARN(("CertGetNameString failed.  (%d)", GetLastError()));
       return FALSE;
     }
 
     // Allocate memory for the name buffer.
     szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(WCHAR));
     if (!szName) {
       LOG_WARN(("Unable to allocate memory for subject name.  (%d)",
                 GetLastError()));
       return FALSE;
     }
 
     // Obtain the name.
     if (!(CertGetNameString(certContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0,
-                            NULL, szName, dwData))) {
+                            nullptr, szName, dwData))) {
       LOG_WARN(("CertGetNameString failed.  (%d)", GetLastError()));
       LocalFree(szName);
       return FALSE;
     }
 
     // If the issuer does not match, return a failure.
     if (!infoToMatch.name || 
         wcscmp(szName, infoToMatch.name)) {
@@ -235,31 +235,31 @@ VerifyCertificateTrustForFile(LPCWSTR fi
   ZeroMemory(&fileToCheck, sizeof(fileToCheck));
   fileToCheck.cbStruct = sizeof(WINTRUST_FILE_INFO);
   fileToCheck.pcwszFilePath = filePath;
 
   // Setup what to check, we want to check it is signed and trusted.
   WINTRUST_DATA trustData;
   ZeroMemory(&trustData, sizeof(trustData));
   trustData.cbStruct = sizeof(trustData);
-  trustData.pPolicyCallbackData = NULL;
-  trustData.pSIPClientData = NULL;
+  trustData.pPolicyCallbackData = nullptr;
+  trustData.pSIPClientData = nullptr;
   trustData.dwUIChoice = WTD_UI_NONE;
   trustData.fdwRevocationChecks = WTD_REVOKE_NONE; 
   trustData.dwUnionChoice = WTD_CHOICE_FILE;
   trustData.dwStateAction = 0;
-  trustData.hWVTStateData = NULL;
-  trustData.pwszURLReference = NULL;
+  trustData.hWVTStateData = nullptr;
+  trustData.pwszURLReference = nullptr;
   // no UI
   trustData.dwUIContext = 0;
   trustData.pFile = &fileToCheck;
 
   GUID policyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
   // Check if the file is signed by something that is trusted.
-  LONG ret = WinVerifyTrust(NULL, &policyGUID, &trustData);
+  LONG ret = WinVerifyTrust(nullptr, &policyGUID, &trustData);
   if (ERROR_SUCCESS == ret) {
     // The hash that represents the subject is trusted and there were no
     // verification errors.  No publisher nor time stamp chain errors.
     LOG(("The file \"%ls\" is signed and the signature was verified.",
          filePath));
       return ERROR_SUCCESS;
   }
 
--- a/toolkit/components/maintenanceservice/maintenanceservice.cpp
+++ b/toolkit/components/maintenanceservice/maintenanceservice.cpp
@@ -11,19 +11,19 @@
 #include "serviceinstall.h"
 #include "maintenanceservice.h"
 #include "servicebase.h"
 #include "workmonitor.h"
 #include "uachelper.h"
 #include "updatehelper.h"
 
 SERVICE_STATUS gSvcStatus = { 0 }; 
-SERVICE_STATUS_HANDLE gSvcStatusHandle = NULL; 
-HANDLE gWorkDoneEvent = NULL;
-HANDLE gThread = NULL;
+SERVICE_STATUS_HANDLE gSvcStatusHandle = nullptr; 
+HANDLE gWorkDoneEvent = nullptr;
+HANDLE gThread = nullptr;
 bool gServiceControlStopping = false;
 
 // logs are pretty small, about 20 lines, so 10 seems reasonable.
 #define LOGS_TO_KEEP 10
 
 BOOL GetLogDirectoryPath(WCHAR *path);
 
 int 
@@ -95,17 +95,17 @@ wmain(int argc, WCHAR **argv)
     }
     LOG(("The service was uninstalled successfully"));
     LogFinish();
     return 0;
   }
 
   SERVICE_TABLE_ENTRYW DispatchTable[] = { 
     { SVC_NAME, (LPSERVICE_MAIN_FUNCTIONW) SvcMain }, 
-    { NULL, NULL } 
+    { nullptr, nullptr } 
   }; 
 
   // This call returns when the service has stopped. 
   // The process should simply terminate when the call returns.
   if (!StartServiceCtrlDispatcherW(DispatchTable)) {
     LOG_WARN(("StartServiceCtrlDispatcher failed.  (%d)", GetLastError()));
   }
 
@@ -116,33 +116,33 @@ wmain(int argc, WCHAR **argv)
  * Obtains the base path where logs should be stored
  *
  * @param  path The out buffer for the backup log path of size MAX_PATH + 1
  * @return TRUE if successful.
  */
 BOOL
 GetLogDirectoryPath(WCHAR *path)
 {
-  HRESULT hr = SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, 
+  HRESULT hr = SHGetFolderPathW(nullptr, CSIDL_COMMON_APPDATA, nullptr, 
     SHGFP_TYPE_CURRENT, path);
   if (FAILED(hr)) {
     return FALSE;
   }
 
   if (!PathAppendSafe(path, L"Mozilla")) {
     return FALSE;
   }
   // The directory should already be created from the installer, but
   // just to be safe in case someone deletes.
-  CreateDirectoryW(path, NULL);
+  CreateDirectoryW(path, nullptr);
 
   if (!PathAppendSafe(path, L"logs")) {
     return FALSE;
   }
-  CreateDirectoryW(path, NULL);
+  CreateDirectoryW(path, nullptr);
   return TRUE;
 }
 
 /**
  * Calculated a backup path based on the log number.
  *
  * @param  path      The out buffer to store the log path of size MAX_PATH + 1
  * @param  basePath  The base directory where the calculated path should go
@@ -217,18 +217,18 @@ EnsureProcessTerminatedThread(LPVOID)
   return 0;
 }
 
 void
 StartTerminationThread()
 {
   // If the process does not self terminate like it should, this thread 
   // will terminate the process after 5 seconds.
-  HANDLE thread = CreateThread(NULL, 0, EnsureProcessTerminatedThread, 
-                               NULL, 0, NULL);
+  HANDLE thread = CreateThread(nullptr, 0, EnsureProcessTerminatedThread,
+                               nullptr, 0, nullptr);
   if (thread) {
     CloseHandle(thread);
   }
 }
 
 /**
  * Main entry point when running as a service.
  */
@@ -239,17 +239,17 @@ SvcMain(DWORD argc, LPWSTR *argv)
   WCHAR updatePath[MAX_PATH + 1];
   if (GetLogDirectoryPath(updatePath)) {
     BackupOldLogs(updatePath, LOGS_TO_KEEP);
     LogInit(updatePath, L"maintenanceservice.log");
   }
 
   // Disable every privilege we don't need. Processes started using
   // CreateProcess will use the same token as this process.
-  UACHelper::DisablePrivileges(NULL);
+  UACHelper::DisablePrivileges(nullptr);
 
   // Register the handler function for the service
   gSvcStatusHandle = RegisterServiceCtrlHandlerW(SVC_NAME, SvcCtrlHandler);
   if (!gSvcStatusHandle) {
     LOG_WARN(("RegisterServiceCtrlHandler failed.  (%d)", GetLastError()));
     ExecuteServiceCommand(argc, argv);  
     LogFinish();
     exit(1);
@@ -259,17 +259,17 @@ SvcMain(DWORD argc, LPWSTR *argv)
   gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
   gSvcStatus.dwServiceSpecificExitCode = 0;
 
   // Report initial status to the SCM
   ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000);
 
   // This event will be used to tell the SvcCtrlHandler when the work is
   // done for when a stop comamnd is manually issued.
-  gWorkDoneEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
+  gWorkDoneEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);
   if (!gWorkDoneEvent) {
     ReportSvcStatus(SERVICE_STOPPED, 1, 0);
     StartTerminationThread();
     return;
   }
 
   // Initialization complete and we're about to start working on
   // the actual command.  Report the service state as running to the SCM.
@@ -335,17 +335,17 @@ ReportSvcStatus(DWORD currentState,
 */
 DWORD WINAPI
 StopServiceAndWaitForCommandThread(LPVOID)
 {
   do {
     ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 1000);
   } while(WaitForSingleObject(gWorkDoneEvent, 100) == WAIT_TIMEOUT);
   CloseHandle(gWorkDoneEvent);
-  gWorkDoneEvent = NULL;
+  gWorkDoneEvent = nullptr;
   ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
   StartTerminationThread();
   return 0;
 }
 
 /**
  * Called by SCM whenever a control code is sent to the service
  * using the ControlService function.
@@ -363,24 +363,25 @@ SvcCtrlHandler(DWORD dwCtrl)
   switch(dwCtrl) {
   case SERVICE_CONTROL_SHUTDOWN:
   case SERVICE_CONTROL_STOP: {
       gServiceControlStopping = true;
       ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 1000);
 
       // The SvcCtrlHandler thread should not spend more than 30 seconds in 
       // shutdown so we spawn a new thread for stopping the service 
-      HANDLE thread = CreateThread(NULL, 0, StopServiceAndWaitForCommandThread, 
-                                   NULL, 0, NULL);
+      HANDLE thread = CreateThread(nullptr, 0,
+                                   StopServiceAndWaitForCommandThread,
+                                   nullptr, 0, nullptr);
       if (thread) {
         CloseHandle(thread);
       } else {
         // Couldn't start the thread so just call the stop ourselves.
         // If it happens to take longer than 30 seconds the caller will
         // get an error.
-        StopServiceAndWaitForCommandThread(NULL);
+        StopServiceAndWaitForCommandThread(nullptr);
       }
     }
     break;
   default:
     break;
   }
 }
--- a/toolkit/components/maintenanceservice/registrycertificates.cpp
+++ b/toolkit/components/maintenanceservice/registrycertificates.cpp
@@ -50,30 +50,31 @@ DoesBinaryMatchAllowedCertificates(LPCWS
       LOG_WARN(("Could not open fallback key.  (%d)", retCode));
       return FALSE;
     }
   }
   nsAutoRegKey baseKey(baseKeyRaw);
 
   // Get the number of subkeys.
   DWORD subkeyCount = 0;
-  retCode = RegQueryInfoKeyW(baseKey, NULL, NULL, NULL, &subkeyCount, NULL,
-                             NULL, NULL, NULL, NULL, NULL, NULL);
+  retCode = RegQueryInfoKeyW(baseKey, nullptr, nullptr, nullptr, &subkeyCount,
+                             nullptr, nullptr, nullptr, nullptr, nullptr,
+                             nullptr, nullptr);
   if (retCode != ERROR_SUCCESS) {
     LOG_WARN(("Could not query info key.  (%d)", retCode));
     return FALSE;
   }
 
   // Enumerate the subkeys, each subkey represents an allowed certificate.
   for (DWORD i = 0; i < subkeyCount; i++) { 
     WCHAR subkeyBuffer[MAX_KEY_LENGTH];
     DWORD subkeyBufferCount = MAX_KEY_LENGTH;  
     retCode = RegEnumKeyExW(baseKey, i, subkeyBuffer, 
-                            &subkeyBufferCount, NULL, 
-                            NULL, NULL, NULL); 
+                            &subkeyBufferCount, nullptr, 
+                            nullptr, nullptr, nullptr); 
     if (retCode != ERROR_SUCCESS) {
       LOG_WARN(("Could not enum certs.  (%d)", retCode));
       return FALSE;
     }
 
     // Open the subkey for the current certificate
     HKEY subKeyRaw;
     retCode = RegOpenKeyExW(baseKey, 
@@ -88,26 +89,26 @@ DoesBinaryMatchAllowedCertificates(LPCWS
     }
 
     const int MAX_CHAR_COUNT = 256;
     DWORD valueBufSize = MAX_CHAR_COUNT * sizeof(WCHAR);
     WCHAR name[MAX_CHAR_COUNT] = { L'\0' };
     WCHAR issuer[MAX_CHAR_COUNT] = { L'\0' };
 
     // Get the name from the registry
-    retCode = RegQueryValueExW(subKey, L"name", 0, NULL, 
+    retCode = RegQueryValueExW(subKey, L"name", 0, nullptr, 
                                (LPBYTE)name, &valueBufSize);
     if (retCode != ERROR_SUCCESS) {
       LOG_WARN(("Could not obtain name from registry.  (%d)", retCode));
       continue; // Try the next subkey
     }
 
     // Get the issuer from the registry
     valueBufSize = MAX_CHAR_COUNT * sizeof(WCHAR);
-    retCode = RegQueryValueExW(subKey, L"issuer", 0, NULL, 
+    retCode = RegQueryValueExW(subKey, L"issuer", 0, nullptr, 
                                (LPBYTE)issuer, &valueBufSize);
     if (retCode != ERROR_SUCCESS) {
       LOG_WARN(("Could not obtain issuer from registry.  (%d)", retCode));
       continue; // Try the next subkey
     }
 
     CertificateCheckInfo allowedCertificate = {
       name, 
--- a/toolkit/components/maintenanceservice/servicebase.cpp
+++ b/toolkit/components/maintenanceservice/servicebase.cpp
@@ -16,66 +16,66 @@
  * @param  sameContent Out parameter, TRUE if the files are equal
  * @return TRUE If there was no error checking the files.
  */
 BOOL
 VerifySameFiles(LPCWSTR file1Path, LPCWSTR file2Path, BOOL &sameContent)
 {
   sameContent = FALSE;
   nsAutoHandle file1(CreateFileW(file1Path, GENERIC_READ, FILE_SHARE_READ, 
-                                 NULL, OPEN_EXISTING, 0, NULL));
+                                 nullptr, OPEN_EXISTING, 0, nullptr));
   if (INVALID_HANDLE_VALUE == file1) {
     return FALSE;
   }
   nsAutoHandle file2(CreateFileW(file2Path, GENERIC_READ, FILE_SHARE_READ, 
-                                 NULL, OPEN_EXISTING, 0, NULL));
+                                 nullptr, OPEN_EXISTING, 0, nullptr));
   if (INVALID_HANDLE_VALUE == file2) {
     return FALSE;
   }
 
-  DWORD fileSize1 = GetFileSize(file1, NULL);
-  DWORD fileSize2 = GetFileSize(file2, NULL);
+  DWORD fileSize1 = GetFileSize(file1, nullptr);
+  DWORD fileSize2 = GetFileSize(file2, nullptr);
   if (INVALID_FILE_SIZE == fileSize1 || INVALID_FILE_SIZE == fileSize2) {
     return FALSE;
   }
 
   if (fileSize1 != fileSize2) {
     // sameContent is already set to FALSE
     return TRUE;
   }
 
   char buf1[COMPARE_BLOCKSIZE];
   char buf2[COMPARE_BLOCKSIZE];
   DWORD numBlocks = fileSize1 / COMPARE_BLOCKSIZE;
   DWORD leftOver = fileSize1 % COMPARE_BLOCKSIZE;
   DWORD readAmount;
   for (DWORD i = 0; i < numBlocks; i++) {
-    if (!ReadFile(file1, buf1, COMPARE_BLOCKSIZE, &readAmount, NULL) || 
+    if (!ReadFile(file1, buf1, COMPARE_BLOCKSIZE, &readAmount, nullptr) ||
         readAmount != COMPARE_BLOCKSIZE) {
       return FALSE;
     }
 
-    if (!ReadFile(file2, buf2, COMPARE_BLOCKSIZE, &readAmount, NULL) || 
+    if (!ReadFile(file2, buf2, COMPARE_BLOCKSIZE, &readAmount, nullptr) ||
         readAmount != COMPARE_BLOCKSIZE) {
       return FALSE;
     }
 
     if (memcmp(buf1, buf2, COMPARE_BLOCKSIZE)) {
       // sameContent is already set to FALSE
       return TRUE;
     }
   }
 
   if (leftOver) {
-    if (!ReadFile(file1, buf1, leftOver, &readAmount, NULL) || 
+    if (!ReadFile(file1, buf1, leftOver, &readAmount, nullptr) ||
         readAmount != leftOver) {
       return FALSE;
     }
 
-    if (!ReadFile(file2, buf2, leftOver, &readAmount, NULL) || 
+    if (!ReadFile(file2, buf2, leftOver, &readAmount, nullptr) ||
         readAmount != leftOver) {
       return FALSE;
     }
 
     if (memcmp(buf1, buf2, leftOver)) {
       // sameContent is already set to FALSE
       return TRUE;
     }
--- a/toolkit/components/maintenanceservice/serviceinstall.cpp
+++ b/toolkit/components/maintenanceservice/serviceinstall.cpp
@@ -96,17 +96,17 @@ GetVersionNumberFromPath(LPWSTR path, DW
  * @param serviceHandle A handle to an opened service with 
  *                      SERVICE_CHANGE_CONFIG access right
  * @param TRUE on succcess.
 */
 BOOL
 UpdateServiceDescription(SC_HANDLE serviceHandle)
 {
   WCHAR updaterINIPath[MAX_PATH + 1];
-  if (!GetModuleFileNameW(NULL, updaterINIPath, 
+  if (!GetModuleFileNameW(nullptr, updaterINIPath, 
                           sizeof(updaterINIPath) /
                           sizeof(updaterINIPath[0]))) {
     LOG_WARN(("Could not obtain module filename when attempting to "
               "modify service description.  (%d)", GetLastError()));
     return FALSE;
   }
 
   if (!PathRemoveFileSpecW(updaterINIPath)) {
@@ -208,18 +208,18 @@ FixServicePath(SC_HANDLE service,
   if (!PathAppendSafe(fixedPath, L"maintenanceservice.exe")) {
     LOG_WARN(("Couldn't append file spec.  (%d)", GetLastError()));
     return FALSE;
   }
   PathQuoteSpacesW(fixedPath);
 
 
   if (!ChangeServiceConfigW(service, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE,
-                            SERVICE_NO_CHANGE, fixedPath, NULL, NULL, NULL,
-                            NULL, NULL, NULL)) {
+                            SERVICE_NO_CHANGE, fixedPath, nullptr, nullptr,
+                            nullptr, nullptr, nullptr, nullptr)) {
     LOG_WARN(("Could not fix service path.  (%d)", GetLastError()));
     return FALSE;
   }
 
   LOG(("Fixed service path to: %ls.", fixedPath));
   return TRUE;
 }
 
@@ -230,25 +230,25 @@ FixServicePath(SC_HANDLE service,
  *
  * @param  action The action to perform.
  * @return TRUE if the service was installed/upgraded
  */
 BOOL
 SvcInstall(SvcInstallAction action)
 {
   // Get a handle to the local computer SCM database with full access rights.
-  nsAutoServiceHandle schSCManager(OpenSCManager(NULL, NULL, 
+  nsAutoServiceHandle schSCManager(OpenSCManager(nullptr, nullptr, 
                                                  SC_MANAGER_ALL_ACCESS));
   if (!schSCManager) {
     LOG_WARN(("Could not open service manager.  (%d)", GetLastError()));
     return FALSE;
   }
 
   WCHAR newServiceBinaryPath[MAX_PATH + 1];
-  if (!GetModuleFileNameW(NULL, newServiceBinaryPath, 
+  if (!GetModuleFileNameW(nullptr, newServiceBinaryPath, 
                           sizeof(newServiceBinaryPath) / 
                           sizeof(newServiceBinaryPath[0]))) {
     LOG_WARN(("Could not obtain module filename when attempting to "
               "install service.  (%d)",
               GetLastError()));
     return FALSE;
   }
 
@@ -271,17 +271,17 @@ SvcInstall(SvcInstallAction action)
     if (!SetUserAccessServiceDACL(schService)) {
       LOG_WARN(("Could not reset security ACE on service handle. It might not be "
                 "possible to start the service. This error should never "
                 "happen.  (%d)", GetLastError()));
     }
 
     // The service exists and we opened it
     DWORD bytesNeeded;
-    if (!QueryServiceConfigW(schService, NULL, 0, &bytesNeeded) && 
+    if (!QueryServiceConfigW(schService, nullptr, 0, &bytesNeeded) && 
         GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
       LOG_WARN(("Could not determine buffer size for query service config.  (%d)",
                 GetLastError()));
       return FALSE;
     }
 
     // Get the service config information, in particular we want the binary 
     // path of the service.
@@ -434,31 +434,32 @@ SvcInstall(SvcInstallAction action)
         }
       } else {
         LOG(("The new service binary was copied in."));
       }
 
       // We made a copy of ourselves to the existing location.
       // The tmp file (the process of which we are executing right now) will be
       // left over.  Attempt to delete the file on the next reboot.
-      if (MoveFileExW(newServiceBinaryPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT)) {
+      if (MoveFileExW(newServiceBinaryPath, nullptr,
+                      MOVEFILE_DELAY_UNTIL_REBOOT)) {
         LOG(("Deleting the old file path on the next reboot: %ls.",
              newServiceBinaryPath));
       } else {
         LOG_WARN(("Call to delete the old file path failed: %ls.",
                   newServiceBinaryPath));
       }
       
       return result;
     }
 
     // We don't need to copy ourselves to the existing location.
     // The tmp file (the process of which we are executing right now) will be
     // left over.  Attempt to delete the file on the next reboot.
-    MoveFileExW(newServiceBinaryPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
+    MoveFileExW(newServiceBinaryPath, nullptr, MOVEFILE_DELAY_UNTIL_REBOOT);
     
     // nothing to do, we already have a newer service installed
     return TRUE; 
   }
   
   // If the service does not exist and we are upgrading, don't install it.
   if (UpgradeSvc == action) {
     // The service does not exist and we are upgrading, so don't install it
@@ -466,18 +467,18 @@ SvcInstall(SvcInstallAction action)
   }
 
   // Quote the path only if it contains spaces.
   PathQuoteSpacesW(newServiceBinaryPath);
   // The service does not already exist so create the service as on demand
   schService.own(CreateServiceW(schSCManager, SVC_NAME, SVC_DISPLAY_NAME,
                                 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
                                 SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
-                                newServiceBinaryPath, NULL, NULL, NULL, 
-                                NULL, NULL));
+                                newServiceBinaryPath, nullptr, nullptr,
+                                nullptr, nullptr, nullptr));
   if (!schService) {
     LOG_WARN(("Could not create Windows service. "
               "This error should never happen since a service install "
               "should only be called when elevated.  (%d)", GetLastError()));
     return FALSE;
   } 
 
   if (!SetUserAccessServiceDACL(schService)) {
@@ -496,17 +497,17 @@ SvcInstall(SvcInstallAction action)
  * Stops the Maintenance service.
  *
  * @return TRUE if successful.
  */
 BOOL
 StopService()
 {
   // Get a handle to the local computer SCM database with full access rights.
-  nsAutoServiceHandle schSCManager(OpenSCManager(NULL, NULL, 
+  nsAutoServiceHandle schSCManager(OpenSCManager(nullptr, nullptr, 
                                                  SC_MANAGER_ALL_ACCESS));
   if (!schSCManager) {
     LOG_WARN(("Could not open service manager.  (%d)", GetLastError()));
     return FALSE;
   }
 
   // Open the service
   nsAutoServiceHandle schService(OpenServiceW(schSCManager, SVC_NAME, 
@@ -542,17 +543,17 @@ StopService()
  * Uninstalls the Maintenance service.
  *
  * @return TRUE if successful.
  */
 BOOL
 SvcUninstall()
 {
   // Get a handle to the local computer SCM database with full access rights.
-  nsAutoServiceHandle schSCManager(OpenSCManager(NULL, NULL, 
+  nsAutoServiceHandle schSCManager(OpenSCManager(nullptr, nullptr, 
                                                  SC_MANAGER_ALL_ACCESS));
   if (!schSCManager) {
     LOG_WARN(("Could not open service manager.  (%d)", GetLastError()));
     return FALSE;
   }
 
   // Open the service
   nsAutoServiceHandle schService(OpenServiceW(schSCManager, SVC_NAME, 
@@ -592,18 +593,18 @@ SvcUninstall()
  * Sets the access control list for user access for the specified service.
  *
  * @param  hService The service to set the access control list on
  * @return TRUE if successful
  */
 BOOL
 SetUserAccessServiceDACL(SC_HANDLE hService)
 {
-  PACL pNewAcl = NULL;
-  PSECURITY_DESCRIPTOR psd = NULL;
+  PACL pNewAcl = nullptr;
+  PSECURITY_DESCRIPTOR psd = nullptr;
   DWORD lastError = SetUserAccessServiceDACL(hService, pNewAcl, psd);
   if (pNewAcl) {
     LocalFree((HLOCAL)pNewAcl);
   }
   if (psd) {
     LocalFree((LPVOID)psd);
   }
   return ERROR_SUCCESS == lastError;
@@ -644,59 +645,59 @@ SetUserAccessServiceDACL(SC_HANDLE hServ
                                     psd, size, &needed)) {
       LOG_WARN(("Could not allocate security descriptor.  (%d)",
                 GetLastError()));
       return GetLastError();
     }
   }
 
   // Get the current DACL from the security descriptor.
-  PACL pacl = NULL;
+  PACL pacl = nullptr;
   BOOL bDaclPresent = FALSE;
   BOOL bDaclDefaulted = FALSE;
   if ( !GetSecurityDescriptorDacl(psd, &bDaclPresent, &pacl, 
                                   &bDaclDefaulted)) {
     LOG_WARN(("Could not obtain DACL.  (%d)", GetLastError()));
     return GetLastError();
   }
 
   PSID sid;
   DWORD SIDSize = SECURITY_MAX_SID_SIZE;
   sid = LocalAlloc(LMEM_FIXED, SIDSize);
   if (!sid) {
     LOG_WARN(("Could not allocate SID memory.  (%d)", GetLastError()));
     return GetLastError();
   }
 
-  if (!CreateWellKnownSid(WinBuiltinUsersSid, NULL, sid, &SIDSize)) {
+  if (!CreateWellKnownSid(WinBuiltinUsersSid, nullptr, sid, &SIDSize)) {
     DWORD lastError = GetLastError();
     LOG_WARN(("Could not create well known SID.  (%d)", lastError));
     LocalFree(sid);
     return lastError;
   }
 
   // Lookup the account name, the function fails if you don't pass in
   // a buffer for the domain name but it's not used since we're using
   // the built in account Sid.
   SID_NAME_USE accountType;
   WCHAR accountName[UNLEN + 1] = { L'\0' };
   WCHAR domainName[DNLEN + 1] = { L'\0' };
   DWORD accountNameSize = UNLEN + 1;
   DWORD domainNameSize = DNLEN + 1;
-  if (!LookupAccountSidW(NULL, sid, accountName, 
+  if (!LookupAccountSidW(nullptr, sid, accountName, 
                          &accountNameSize, 
                          domainName, &domainNameSize, &accountType)) {
     LOG_WARN(("Could not lookup account Sid, will try Users.  (%d)",
               GetLastError()));
     wcsncpy(accountName, L"Users", UNLEN);
   }
 
   // We already have the group name so we can get rid of the SID
   FreeSid(sid);
-  sid = NULL;
+  sid = nullptr;
 
   // Build the ACE, BuildExplicitAccessWithName cannot fail so it is not logged.
   EXPLICIT_ACCESS ea;
   BuildExplicitAccessWithNameW(&ea, accountName, 
                               SERVICE_START | SERVICE_STOP | GENERIC_READ, 
                               SET_ACCESS, NO_INHERITANCE);
   DWORD lastError = SetEntriesInAclW(1, (PEXPLICIT_ACCESS)&ea, pacl, &pNewAcl);
   if (ERROR_SUCCESS != lastError) {
--- a/toolkit/components/maintenanceservice/workmonitor.cpp
+++ b/toolkit/components/maintenanceservice/workmonitor.cpp
@@ -52,26 +52,26 @@ IsStatusApplying(LPCWSTR updateDirPath, 
     LOG_WARN(("Could not append path for update.status file"));
     return FALSE;
   }
 
   nsAutoHandle statusFile(CreateFileW(updateStatusFilePath, GENERIC_READ,
                                       FILE_SHARE_READ | 
                                       FILE_SHARE_WRITE | 
                                       FILE_SHARE_DELETE,
-                                      NULL, OPEN_EXISTING, 0, NULL));
+                                      nullptr, OPEN_EXISTING, 0, nullptr));
 
   if (INVALID_HANDLE_VALUE == statusFile) {
     LOG_WARN(("Could not open update.status file"));
     return FALSE;
   }
 
   char buf[32] = { 0 };
   DWORD read;
-  if (!ReadFile(statusFile, buf, sizeof(buf), &read, NULL)) {
+  if (!ReadFile(statusFile, buf, sizeof(buf), &read, nullptr)) {
     LOG_WARN(("Could not read from update.status file"));
     return FALSE;
   }
 
   LOG(("updater.exe returned status: %s", buf));
 
   const char kApplying[] = "applying";
   isApplying = strncmp(buf, kApplying, 
@@ -174,20 +174,20 @@ StartUpdateProcess(int argc,
   }
 
   // Add an env var for MOZ_USING_SERVICE so the updater.exe can
   // do anything special that it needs to do for service updates.
   // Search in updater.cpp for more info on MOZ_USING_SERVICE.
   putenv(const_cast<char*>("MOZ_USING_SERVICE=1"));
   LOG(("Starting service with cmdline: %ls", cmdLine));
   processStarted = CreateProcessW(argv[0], cmdLine, 
-                                  NULL, NULL, FALSE, 
+                                  nullptr, nullptr, FALSE, 
                                   CREATE_DEFAULT_ERROR_MODE, 
-                                  NULL, 
-                                  NULL, &si, &pi);
+                                  nullptr, 
+                                  nullptr, &si, &pi);
   // Empty value on putenv is how you remove an env variable in Windows
   putenv(const_cast<char*>("MOZ_USING_SERVICE="));
   
   BOOL updateWasSuccessful = FALSE;
   if (processStarted) {
     // Wait for the updater process to finish
     LOG(("Process was started... waiting on result."));
     DWORD waitRes = WaitForSingleObject(pi.hProcess, TIME_TO_WAIT_ON_UPDATER);
@@ -258,17 +258,17 @@ StartUpdateProcess(int argc,
       // the unelevated updater.exe after the update process is complete
       // from the service.  We don't know here which session to start
       // the user PostUpdate process from.
       // Note that we don't need to do this if we're just staging the
       // update in the background, as the PostUpdate step runs when
       // performing the replacing in that case.
       if (!backgroundUpdate) {
         LOG(("Launching post update process as the service in session 0."));
-        if (!LaunchWinPostProcess(installDir, updateInfoDir, true, NULL)) {
+        if (!LaunchWinPostProcess(installDir, updateInfoDir, true, nullptr)) {
           LOG_WARN(("The post update process could not be launched."
                     " installDir: %ls, updateInfoDir: %ls",
                     installDir, updateInfoDir));
         }
       }
     }
   }
 
@@ -324,17 +324,17 @@ ProcessSoftwareUpdateCommand(DWORD argc,
                             SERVICE_UPDATER_NOT_FIXED_DRIVE)) {
       LOG_WARN(("Could not write update.status service update failure.  (%d)",
                 GetLastError()));
     }
     return FALSE;
   }
 
   nsAutoHandle noWriteLock(CreateFileW(argv[0], GENERIC_READ, FILE_SHARE_READ, 
-                                       NULL, OPEN_EXISTING, 0, NULL));
+                                       nullptr, OPEN_EXISTING, 0, nullptr));
   if (INVALID_HANDLE_VALUE == noWriteLock) {
       LOG_WARN(("Could not set no write sharing access on file.  (%d)",
                 GetLastError()));
     if (!WriteStatusFailure(argv[1], 
                             SERVICE_COULD_NOT_LOCK_UPDATER)) {
       LOG_WARN(("Could not write update.status service update failure.  (%d)",
                 GetLastError()));
     }
@@ -373,17 +373,17 @@ ProcessSoftwareUpdateCommand(DWORD argc,
       LOG_WARN(("Could not write update.status updater compare failure."));
     }
     return FALSE;
   }
 
   // Check to make sure the updater.exe module has the unique updater identity.
   // This is a security measure to make sure that the signed executable that
   // we will run is actually an updater.
-  HMODULE updaterModule = LoadLibraryEx(argv[0], NULL, 
+  HMODULE updaterModule = LoadLibraryEx(argv[0], nullptr, 
                                         LOAD_LIBRARY_AS_DATAFILE);
   if (!updaterModule) {
     LOG_WARN(("updater.exe module could not be loaded. (%d)", GetLastError()));
     result = FALSE;
   } else {
     char updaterIdentity[64];
     if (!LoadStringA(updaterModule, IDS_UPDATER_IDENTITY, 
                      updaterIdentity, sizeof(updaterIdentity))) {
@@ -474,17 +474,17 @@ ProcessSoftwareUpdateCommand(DWORD argc,
  *
  * @param serviceUpdaterPath Out parameter for the path where the updater
  *                           should be copied to.
  * @return TRUE if a file path was obtained.
  */
 BOOL
 GetSecureUpdaterPath(WCHAR serviceUpdaterPath[MAX_PATH + 1])
 {
-  if (!GetModuleFileNameW(NULL, serviceUpdaterPath, MAX_PATH)) {
+  if (!GetModuleFileNameW(nullptr, serviceUpdaterPath, MAX_PATH)) {
     LOG_WARN(("Could not obtain module filename when attempting to "
               "use a secure updater path.  (%d)", GetLastError()));
     return FALSE;
   }
 
   if (!PathRemoveFileSpecW(serviceUpdaterPath)) {
     LOG_WARN(("Couldn't remove file spec when attempting to use a secure "
               "updater path.  (%d)", GetLastError()));
@@ -492,17 +492,17 @@ GetSecureUpdaterPath(WCHAR serviceUpdate
   }
 
   if (!PathAppendSafe(serviceUpdaterPath, L"update")) {
     LOG_WARN(("Couldn't append file spec when attempting to use a secure "
               "updater path.  (%d)", GetLastError()));
     return FALSE;
   }
 
-  CreateDirectoryW(serviceUpdaterPath, NULL);
+  CreateDirectoryW(serviceUpdaterPath, nullptr);
 
   if (!PathAppendSafe(serviceUpdaterPath, L"updater.exe")) {
     LOG_WARN(("Couldn't append file spec when attempting to use a secure "
               "updater path.  (%d)", GetLastError()));
     return FALSE;
   }
 
   return TRUE;
--- a/toolkit/components/mediasniffer/nsMediaSnifferModule.cpp
+++ b/toolkit/components/mediasniffer/nsMediaSnifferModule.cpp
@@ -7,29 +7,29 @@
 
 #include "nsMediaSniffer.h"
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsMediaSniffer)
 
 NS_DEFINE_NAMED_CID(NS_MEDIA_SNIFFER_CID);
 
 static const mozilla::Module::CIDEntry kMediaSnifferCIDs[] = {
-    { &kNS_MEDIA_SNIFFER_CID, false, NULL, nsMediaSnifferConstructor },
-    { NULL }
+    { &kNS_MEDIA_SNIFFER_CID, false, nullptr, nsMediaSnifferConstructor },
+    { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kMediaSnifferContracts[] = {
     { NS_MEDIA_SNIFFER_CONTRACTID, &kNS_MEDIA_SNIFFER_CID },
-    { NULL }
+    { nullptr }
 };
 
 static const mozilla::Module::CategoryEntry kMediaSnifferCategories[] = {
     { "content-sniffing-services", NS_MEDIA_SNIFFER_CONTRACTID, NS_MEDIA_SNIFFER_CONTRACTID},
     { "net-content-sniffers", NS_MEDIA_SNIFFER_CONTRACTID, NS_MEDIA_SNIFFER_CONTRACTID},
-    { NULL }
+    { nullptr }
 };
 
 static const mozilla::Module kMediaSnifferModule = {
     mozilla::Module::kVersion,
     kMediaSnifferCIDs,
     kMediaSnifferContracts,
     kMediaSnifferCategories
 };
--- a/toolkit/components/parentalcontrols/nsParentalControlsServiceWin.cpp
+++ b/toolkit/components/parentalcontrols/nsParentalControlsServiceWin.cpp
@@ -14,51 +14,51 @@
 #include "nsArrayUtils.h"
 #include "nsIXULAppInfo.h"
 
 static const CLSID CLSID_WinParentalControls = {0xE77CC89B,0x7401,0x4C04,{0x8C,0xED,0x14,0x9D,0xB3,0x5A,0xDD,0x04}};
 static const IID IID_IWinParentalControls  = {0x28B4D88B,0xE072,0x49E6,{0x80,0x4D,0x26,0xED,0xBE,0x21,0xA7,0xB9}};
 
 NS_IMPL_ISUPPORTS1(nsParentalControlsServiceWin, nsIParentalControlsService)
 
-static HINSTANCE gAdvAPIDLLInst = NULL;
+static HINSTANCE gAdvAPIDLLInst = nullptr;
 
 typedef ULONG (STDMETHODCALLTYPE *MyEventWrite)(
   REGHANDLE RegHandle,
   PCEVENT_DESCRIPTOR EventDescriptor,
   ULONG UserDataCount,
   PEVENT_DATA_DESCRIPTOR UserData);
 
 typedef ULONG (STDMETHODCALLTYPE *MyEventRegister)(
   LPCGUID ProviderId,
   PENABLECALLBACK EnableCallback,
   PVOID CallbackContext,
   PREGHANDLE RegHandle);
 
 typedef ULONG (STDMETHODCALLTYPE *MyEventUnregister)(
   REGHANDLE RegHandle);
 
-MyEventWrite gEventWrite = NULL;
-MyEventRegister gEventRegister = NULL;
-MyEventUnregister gEventUnregister = NULL;
+MyEventWrite gEventWrite = nullptr;
+MyEventRegister gEventRegister = nullptr;
+MyEventUnregister gEventUnregister = nullptr;
 
 nsParentalControlsServiceWin::nsParentalControlsServiceWin() :
   mEnabled(false)
 , mProvider(0)
 , mPC(nullptr)
 {
   HRESULT hr;
-  CoInitialize(NULL);
-  hr = CoCreateInstance(CLSID_WinParentalControls, NULL, CLSCTX_INPROC,
+  CoInitialize(nullptr);
+  hr = CoCreateInstance(CLSID_WinParentalControls, nullptr, CLSCTX_INPROC,
                         IID_IWinParentalControls, (void**)&mPC);
   if (FAILED(hr))
     return;
 
   nsRefPtr<IWPCSettings> wpcs;
-  if (FAILED(mPC->GetUserSettings(NULL, getter_AddRefs(wpcs)))) {
+  if (FAILED(mPC->GetUserSettings(nullptr, getter_AddRefs(wpcs)))) {
     // Not available on this os or not enabled for this user account or we're running as admin
     mPC->Release();
     mPC = nullptr;
     return;
   }
 
   DWORD settings = 0;
   wpcs->GetRestrictions(&settings);
@@ -104,17 +104,17 @@ NS_IMETHODIMP
 nsParentalControlsServiceWin::GetBlockFileDownloadsEnabled(bool *aResult)
 {
   *aResult = false;
 
   if (!mEnabled)
     return NS_ERROR_NOT_AVAILABLE;
 
   nsRefPtr<IWPCWebSettings> wpcws;
-  if (SUCCEEDED(mPC->GetWebSettings(NULL, getter_AddRefs(wpcws)))) {
+  if (SUCCEEDED(mPC->GetWebSettings(nullptr, getter_AddRefs(wpcws)))) {
     DWORD settings = 0;
     wpcws->GetSettings(&settings);
     if (settings == WPCFLAG_WEB_SETTING_DOWNLOADSBLOCKED)
       *aResult = true;
   }
 
   return NS_OK;
 }
@@ -124,17 +124,17 @@ nsParentalControlsServiceWin::GetLogging
 {
   *aResult = false;
 
   if (!mEnabled)
     return NS_ERROR_NOT_AVAILABLE;
 
   // Check the general purpose logging flag
   nsRefPtr<IWPCSettings> wpcs;
-  if (SUCCEEDED(mPC->GetUserSettings(NULL, getter_AddRefs(wpcs)))) {
+  if (SUCCEEDED(mPC->GetUserSettings(nullptr, getter_AddRefs(wpcs)))) {
     BOOL enabled = FALSE;
     wpcs->IsLoggingRequired(&enabled);
     if (enabled)
       *aResult = true;
   }
 
   return NS_OK;
 }
@@ -153,17 +153,17 @@ nsParentalControlsServiceWin::Log(int16_
   GetLoggingEnabled(&enabled);
   if (!enabled)
     return NS_ERROR_NOT_AVAILABLE;
 
   // Register a Vista log event provider associated with the parental controls channel.
   if (!mProvider) {
     if (!gEventRegister)
       return NS_ERROR_NOT_AVAILABLE;
-    if (gEventRegister(&WPCPROV, NULL, NULL, &mProvider) != ERROR_SUCCESS)
+    if (gEventRegister(&WPCPROV, nullptr, nullptr, &mProvider) != ERROR_SUCCESS)
       return NS_ERROR_OUT_OF_MEMORY;
   }
 
   switch(aEntryType) {
     case ePCLog_URIVisit:
       // Not needed, Vista's web content filter handles this for us
       break;
     case ePCLog_FileDownload:
@@ -197,19 +197,19 @@ nsParentalControlsServiceWin::RequestURI
   nsCOMPtr<nsIWidget> widget(do_GetInterface(aWindowContext));
   if (widget)
     hWnd = (HWND)widget->GetNativeData(NS_NATIVE_WINDOW);
   if (hWnd == nullptr)
     hWnd = GetDesktopWindow();
 
   BOOL ret;
   nsRefPtr<IWPCWebSettings> wpcws;
-  if (SUCCEEDED(mPC->GetWebSettings(NULL, getter_AddRefs(wpcws)))) {
+  if (SUCCEEDED(mPC->GetWebSettings(nullptr, getter_AddRefs(wpcws)))) {
     wpcws->RequestURLOverride(hWnd, NS_ConvertUTF8toUTF16(spec).get(),
-                              0, NULL, &ret);
+                              0, nullptr, &ret);
     *_retval = ret;
   }
 
 
   return NS_OK;
 }
 
 // Override a web page
@@ -277,17 +277,17 @@ nsParentalControlsServiceWin::RequestURI
     uriIdx++;
   }
 
   if (!uriIdx)
     return NS_ERROR_INVALID_ARG;
 
   BOOL ret; 
   nsRefPtr<IWPCWebSettings> wpcws;
-  if (SUCCEEDED(mPC->GetWebSettings(NULL, getter_AddRefs(wpcws)))) {
+  if (SUCCEEDED(mPC->GetWebSettings(nullptr, getter_AddRefs(wpcws)))) {
     wpcws->RequestURLOverride(hWnd, NS_ConvertUTF8toUTF16(rootSpec).get(),
                              uriIdx, (LPCWSTR*)arrUrls.get(), &ret);
    *_retval = ret;
   }
 
   // Free up the allocated strings in our array
   for (idx = 0; idx < uriIdx; idx++)
     NS_Free((void*)arrUrls[idx]);
--- a/toolkit/components/perf/PerfMeasurement.cpp
+++ b/toolkit/components/perf/PerfMeasurement.cpp
@@ -96,23 +96,23 @@ Module::Call(nsIXPConnectWrappedNative* 
 }
 
 }
 }
 
 NS_DEFINE_NAMED_CID(JSPERF_CID);
 
 static const mozilla::Module::CIDEntry kPerfCIDs[] = {
-  { &kJSPERF_CID, false, NULL, mozilla::jsperf::ModuleConstructor },
-  { NULL }
+  { &kJSPERF_CID, false, nullptr, mozilla::jsperf::ModuleConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kPerfContracts[] = {
   { JSPERF_CONTRACTID, &kJSPERF_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kPerfModule = {
   mozilla::Module::kVersion,
   kPerfCIDs,
   kPerfContracts
 };
 
--- a/toolkit/components/places/AsyncFaviconHelpers.cpp
+++ b/toolkit/components/places/AsyncFaviconHelpers.cpp
@@ -84,17 +84,17 @@ FetchPageInfo(nsRefPtr<Database>& aDB,
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   rv = stmt->GetInt64(0, &_page.id);
   NS_ENSURE_SUCCESS(rv, rv);
   bool isNull;
   rv = stmt->GetIsNull(1, &isNull);
   NS_ENSURE_SUCCESS(rv, rv);
-  // favicon_id can be NULL.
+  // favicon_id can be nullptr.
   if (!isNull) {
     rv = stmt->GetInt64(1, &_page.iconId);
     NS_ENSURE_SUCCESS(rv, rv);
   }
   rv = stmt->GetUTF8String(2, _page.guid);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = stmt->GetIsNull(3, &isNull);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -219,26 +219,26 @@ FetchIconInfo(nsRefPtr<Database>& aDB,
   if (!hasResult) {
     // The icon does not exist yet, bail out.
     return NS_OK;
   }
 
   rv = stmt->GetInt64(0, &_icon.id);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  // Expiration can be NULL.
+  // Expiration can be nullptr.
   bool isNull;
   rv = stmt->GetIsNull(1, &isNull);
   NS_ENSURE_SUCCESS(rv, rv);
   if (!isNull) {
     rv = stmt->GetInt64(1, reinterpret_cast<int64_t*>(&_icon.expiration));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  // Data can be NULL.
+  // Data can be nullptr.
   rv = stmt->GetIsNull(2, &isNull);
   NS_ENSURE_SUCCESS(rv, rv);
   if (!isNull) {
     uint8_t* data;
     uint32_t dataLen = 0;
     rv = stmt->GetBlob(2, &dataLen, &data);
     NS_ENSURE_SUCCESS(rv, rv);
     _icon.data.Adopt(TO_CHARBUFFER(data), dataLen);
--- a/toolkit/components/places/Helpers.cpp
+++ b/toolkit/components/places/Helpers.cpp
@@ -205,18 +205,18 @@ ReverseString(const nsString& aInput, ns
 }
 
 static
 nsresult
 Base64urlEncode(const uint8_t* aBytes,
                 uint32_t aNumBytes,
                 nsCString& _result)
 {
-  // SetLength does not set aside space for NULL termination.  PL_Base64Encode
-  // will not NULL terminate, however, nsCStrings must be NULL terminated.  As a
+  // SetLength does not set aside space for null termination.  PL_Base64Encode
+  // will not null terminate, however, nsCStrings must be null terminated.  As a
   // result, we set the capacity to be one greater than what we need, and the
   // length to our desired length.
   uint32_t length = (aNumBytes + 2) / 3 * 4; // +2 due to integer math.
   NS_ENSURE_TRUE(_result.SetCapacity(length + 1, fallible_t()),
                  NS_ERROR_OUT_OF_MEMORY);
   _result.SetLength(length);
   (void)PL_Base64Encode(reinterpret_cast<const char*>(aBytes), aNumBytes,
                         _result.BeginWriting());
--- a/toolkit/components/places/History.cpp
+++ b/toolkit/components/places/History.cpp
@@ -79,17 +79,17 @@ struct VisitData {
   , titleChanged(false)
   , shouldUpdateFrecency(true)
   {
     guid.SetIsVoid(true);
     title.SetIsVoid(true);
   }
 
   VisitData(nsIURI* aURI,
-            nsIURI* aReferrer = NULL)
+            nsIURI* aReferrer = nullptr)
   : placeId(0)
   , visitId(0)
   , hidden(true)
   , typed(false)
   , transitionType(UINT32_MAX)
   , visitTime(0)
   , frecency(-1)
   , titleChanged(false)
@@ -782,17 +782,17 @@ private:
  *        The guid of the URI to check.  This is passed back to the callback.
  * @param [optional] aCallback
  *        The callback to notify if the URI cannot be added to history.
  * @return true if the URI can be added to history, false otherwise.
  */
 bool
 CanAddURI(nsIURI* aURI,
           const nsCString& aGUID = EmptyCString(),
-          mozIVisitInfoCallback* aCallback = NULL)
+          mozIVisitInfoCallback* aCallback = nullptr)
 {
   nsNavHistory* navHistory = nsNavHistory::GetHistoryService();
   NS_ENSURE_TRUE(navHistory, false);
 
   bool canAdd;
   nsresult rv = navHistory->CanAddURI(aURI, &canAdd);
   if (NS_SUCCEEDED(rv) && canAdd) {
     return true;
@@ -833,17 +833,17 @@ public:
    *        The database connection to use for these operations.
    * @param aPlaces
    *        The locations to record visits.
    * @param [optional] aCallback
    *        The callback to notify about the visit.
    */
   static nsresult Start(mozIStorageConnection* aConnection,
                         nsTArray<VisitData>& aPlaces,
-                        mozIVisitInfoCallback* aCallback = NULL)
+                        mozIVisitInfoCallback* aCallback = nullptr)
   {
     MOZ_ASSERT(NS_IsMainThread(), "This should be called on the main thread");
     MOZ_ASSERT(aPlaces.Length() > 0, "Must pass a non-empty array!");
 
     nsRefPtr<InsertVisitedURIs> event =
       new InsertVisitedURIs(aConnection, aPlaces, aCallback);
 
     // Get the target thread, and then start the work!
@@ -864,17 +864,17 @@ public:
     if (mHistory->IsShuttingDown()) {
       // If we were already shutting down, we cannot insert the URIs.
       return NS_OK;
     }
 
     mozStorageTransaction transaction(mDBConn, false,
                                       mozIStorageConnection::TRANSACTION_IMMEDIATE);
 
-    VisitData* lastPlace = NULL;
+    VisitData* lastPlace = nullptr;
     for (nsTArray<VisitData>::size_type i = 0; i < mPlaces.Length(); i++) {
       VisitData& place = mPlaces.ElementAt(i);
       VisitData& referrer = mReferrers.ElementAt(i);
 
       // We can avoid a database lookup if it's the same place as the last
       // visit we added.
       bool known = lastPlace && lastPlace->IsSamePlaceAs(place);
       if (!known) {
@@ -1867,17 +1867,17 @@ private:
  *
  * @param aPlace
  *        The VisitData of the visit to store as an embed visit.
  * @param [optional] aCallback
  *        The mozIVisitInfoCallback to notify, if provided.
  */
 void
 StoreAndNotifyEmbedVisit(VisitData& aPlace,
-                         mozIVisitInfoCallback* aCallback = NULL)
+                         mozIVisitInfoCallback* aCallback = nullptr)
 {
   MOZ_ASSERT(aPlace.transitionType == nsINavHistoryService::TRANSITION_EMBED,
              "Must only pass TRANSITION_EMBED visits to this!");
   MOZ_ASSERT(NS_IsMainThread(), "Must be called on the main thread!");
 
   nsCOMPtr<nsIURI> uri;
   (void)NS_NewURI(getter_AddRefs(uri), aPlace.spec);
 
@@ -1925,17 +1925,17 @@ private:
   }
 };
 
 } // anonymous namespace
 
 ////////////////////////////////////////////////////////////////////////////////
 //// History
 
-History* History::gService = NULL;
+History* History::gService = nullptr;
 
 History::History()
   : mShuttingDown(false)
   , mShutdownMutex("History::mShutdownMutex")
   , mObservers(VISIT_OBSERVERS_INITIAL_CACHE_SIZE)
   , mRecentlyVisitedURIsNextIndex(0)
 {
   NS_ASSERTION(!gService, "Ruh-roh!  This service has already been created!");
@@ -2466,29 +2466,29 @@ History::RegisterVisitedCallback(nsIURI*
     NS_ASSERTION(!keyAlreadyExists,
                  "An empty key was kept around in our hashtable!");
 
     // We are the first Link node to ask about this URI, or there are no pending
     // Links wanting to know about this URI.  Therefore, we should query the
     // database now.
     nsresult rv = VisitedQuery::Start(aURI);
 
-    // In IPC builds, we are passed a NULL Link from
-    // ContentParent::RecvStartVisitedQuery.  Since we won't be adding a NULL
-    // entry to our list of observers, and the code after this point assumes
-    // that aLink is non-NULL, we will need to return now.
+    // In IPC builds, we are passed a nullptr Link from
+    // ContentParent::RecvStartVisitedQuery.  Since we won't be adding a
+    // nullptr entry to our list of observers, and the code after this point
+    // assumes that aLink is non-nullptr, we will need to return now.
     if (NS_FAILED(rv) || !aLink) {
       // Remove our array from the hashtable so we don't keep it around.
       mObservers.RemoveEntry(aURI);
       return rv;
     }
   }
-  // In IPC builds, we are passed a NULL Link from
+  // In IPC builds, we are passed a nullptr Link from
   // ContentParent::RecvStartVisitedQuery.  All of our code after this point
-  // assumes aLink is non-NULL, so we have to return now.
+  // assumes aLink is non-nullptr, so we have to return now.
   else if (!aLink) {
     NS_ASSERTION(XRE_GetProcessType() == GeckoProcessType_Default,
                  "We should only ever get a null Link in the default process!");
     return NS_OK;
   }
 
   // Sanity check that Links are not registered more than once for a given URI.
   // This will not catch a case where it is registered for two different URIs.
--- a/toolkit/components/places/PlaceInfo.cpp
+++ b/toolkit/components/places/PlaceInfo.cpp
@@ -95,17 +95,18 @@ PlaceInfo::GetVisits(JSContext* aContext
   // of a place without any visit.
   if (!mVisitsAvailable) {
     *_visits = JSVAL_NULL;
     return NS_OK;
   }
 
   // TODO bug 625913 when we use this in situations that have more than one
   // visit here, we will likely want to make this cache the value.
-  JS::Rooted<JSObject*> visits(aContext, JS_NewArrayObject(aContext, 0, NULL));
+  JS::Rooted<JSObject*> visits(aContext,
+                               JS_NewArrayObject(aContext, 0, nullptr));
   NS_ENSURE_TRUE(visits, NS_ERROR_OUT_OF_MEMORY);
 
   JS::Rooted<JSObject*> global(aContext, JS::CurrentGlobalOrNull(aContext));
   NS_ENSURE_TRUE(global, NS_ERROR_UNEXPECTED);
 
   nsCOMPtr<nsIXPConnect> xpc = mozilla::services::GetXPConnect();
 
   for (VisitsArray::size_type idx = 0; idx < mVisits.Length(); idx++) {
--- a/toolkit/components/places/nsFaviconService.cpp
+++ b/toolkit/components/places/nsFaviconService.cpp
@@ -61,17 +61,17 @@ class ExpireFaviconsStatementCallbackNot
 public:
   ExpireFaviconsStatementCallbackNotifier();
   NS_IMETHOD HandleCompletion(uint16_t aReason);
 };
 
 
 PLACES_FACTORY_SINGLETON_IMPLEMENTATION(nsFaviconService, gFaviconService)
 
-NS_IMPL_CLASSINFO(nsFaviconService, NULL, 0, NS_FAVICONSERVICE_CID)
+NS_IMPL_CLASSINFO(nsFaviconService, nullptr, 0, NS_FAVICONSERVICE_CID)
 NS_IMPL_ISUPPORTS3_CI(
   nsFaviconService
 , nsIFaviconService
 , mozIAsyncFavicons
 , nsITimerCallback
 )
 
 nsFaviconService::nsFaviconService()
--- a/toolkit/components/places/nsNavHistory.cpp
+++ b/toolkit/components/places/nsNavHistory.cpp
@@ -157,17 +157,17 @@ static const char* kObservedPrefs[] = {
 , PREF_FREC_UNVISITED_BOOKMARK_BONUS
 , PREF_FREC_UNVISITED_TYPED_BONUS
 , nullptr
 };
 
 NS_IMPL_ADDREF(nsNavHistory)
 NS_IMPL_RELEASE(nsNavHistory)
 
-NS_IMPL_CLASSINFO(nsNavHistory, NULL, nsIClassInfo::SINGLETON,
+NS_IMPL_CLASSINFO(nsNavHistory, nullptr, nsIClassInfo::SINGLETON,
                   NS_NAVHISTORYSERVICE_CID)
 NS_INTERFACE_MAP_BEGIN(nsNavHistory)
   NS_INTERFACE_MAP_ENTRY(nsINavHistoryService)
   NS_INTERFACE_MAP_ENTRY(nsIBrowserHistory)
   NS_INTERFACE_MAP_ENTRY(nsIObserver)
   NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
   NS_INTERFACE_MAP_ENTRY(nsPIPlacesDatabase)
   NS_INTERFACE_MAP_ENTRY(nsPIPlacesHistoryListenersNotifier)
--- a/toolkit/components/places/nsNavHistory.h
+++ b/toolkit/components/places/nsNavHistory.h
@@ -91,17 +91,17 @@ public:
   /**
    * Initializes the nsNavHistory object.  This should only be called once.
    */
   nsresult Init();
 
   /**
    * Used by other components in the places directory such as the annotation
    * service to get a reference to this history object. Returns a pointer to
-   * the service if it exists. Otherwise creates one. Returns NULL on error.
+   * the service if it exists. Otherwise creates one. Returns nullptr on error.
    */
   static nsNavHistory* GetHistoryService()
   {
     if (!gHistoryService) {
       nsCOMPtr<nsINavHistoryService> serv =
         do_GetService(NS_NAVHISTORYSERVICE_CONTRACTID);
       NS_ENSURE_TRUE(serv, nullptr);
       NS_ASSERTION(gHistoryService, "Should have static instance pointer now");
@@ -109,17 +109,17 @@ public:
     return gHistoryService;
   }
 
   /**
    * Used by other components in the places directory to get a reference to a
    * const version of this history object.
    *
    * @return A pointer to a const version of the service if it exists,
-   *         NULL otherwise.
+   *         nullptr otherwise.
    */
   static const nsNavHistory* GetConstHistoryService()
   {
     const nsNavHistory* const history = gHistoryService;
     return history;
   }
 
   /**
@@ -442,17 +442,17 @@ protected:
   nsresult CalculateFrecencyInternal(int64_t aPageID, int32_t aTyped, int32_t aVisitCount, bool aIsBookmarked, int32_t *aFrecency);
 
   nsresult RemovePagesInternal(const nsCString& aPlaceIdsQueryString);
   nsresult CleanupPlacesOnVisitsDelete(const nsCString& aPlaceIdsQueryString);
 
   /**
    * Loads all of the preferences that we use into member variables.
    *
-   * @note If mPrefBranch is NULL, this does nothing.
+   * @note If mPrefBranch is nullptr, this does nothing.
    */
   void LoadPrefs();
 
   /**
    * Calculates and returns value for mCachedNow.
    * This is an hack to avoid calling PR_Now() too often, as is the case when
    * we're asked the ageindays of many history entries in a row.  A timer is
    * set which will clear our valid flag after a short timeout.
--- a/toolkit/components/places/nsNavHistoryQuery.cpp
+++ b/toolkit/components/places/nsNavHistoryQuery.cpp
@@ -25,17 +25,17 @@ class QueryKeyValuePair
 {
 public:
 
   // QueryKeyValuePair
   //
   //                  01234567890
   //    input : qwerty&key=value&qwerty
   //                  ^   ^     ^
-  //          aKeyBegin   |     aPastEnd (may point to NULL terminator)
+  //          aKeyBegin   |     aPastEnd (may point to null terminator)
   //                      aEquals
   //
   //    Special case: if aKeyBegin == aEquals, then there is only one string
   //    and no equal sign, so we treat the entire thing as a key with no value
 
   QueryKeyValuePair(const nsCSubstring& aSource, int32_t aKeyBegin,
                     int32_t aEquals, int32_t aPastEnd)
   {
--- a/toolkit/components/places/nsNavHistoryResult.cpp
+++ b/toolkit/components/places/nsNavHistoryResult.cpp
@@ -1628,18 +1628,18 @@ nsNavHistoryContainerResultNode::ChangeT
                                               bool aOnlyOne)
 {
   // uri string
   nsAutoCString uriString;
   nsresult rv = aURI->GetSpec(uriString);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // The recursive function will update the result's tree nodes, but only if we
-  // give it a non-null pointer.  So if there isn't a tree, just pass NULL so
-  // it doesn't bother trying to call the result.
+  // give it a non-null pointer.  So if there isn't a tree, just pass nullptr
+  // so it doesn't bother trying to call the result.
   nsNavHistoryResult* result = GetResult();
   NS_ENSURE_STATE(result);
 
   uint16_t sortType = GetSortType();
   bool updateSorting =
     (sortType == nsINavHistoryQueryOptions::SORT_BY_TITLE_ASCENDING ||
      sortType == nsINavHistoryQueryOptions::SORT_BY_TITLE_DESCENDING);
 
--- a/toolkit/components/places/nsPlacesMacros.h
+++ b/toolkit/components/places/nsPlacesMacros.h
@@ -11,17 +11,18 @@
 #define __FUNCTION__ __func__
 #endif
 
 // Call a method on each observer in a category cache, then call the same
 // method on the observer array.
 #define NOTIFY_OBSERVERS(canFire, cache, array, type, method)                  \
   PR_BEGIN_MACRO                                                               \
   if (canFire) {                                                               \
-    const nsCOMArray<type> &entries = cache.GetEntries();                      \
+    nsCOMArray<type> entries;                                                  \
+    cache.GetEntries(entries);                                                 \
     for (int32_t idx = 0; idx < entries.Count(); ++idx)                        \
         entries[idx]->method;                                                  \
     ENUMERATE_WEAKARRAY(array, type, method)                                   \
   }                                                                            \
   PR_END_MACRO;
 
 #define PLACES_FACTORY_SINGLETON_IMPLEMENTATION(_className, _sInstance)        \
   _className * _className::_sInstance = nullptr;                                \
--- a/toolkit/components/places/nsPlacesModule.cpp
+++ b/toolkit/components/places/nsPlacesModule.cpp
@@ -29,40 +29,40 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(nsAnnoPro
 NS_DEFINE_NAMED_CID(NS_NAVHISTORYSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_ANNOTATIONSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_ANNOPROTOCOLHANDLER_CID);
 NS_DEFINE_NAMED_CID(NS_NAVBOOKMARKSSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_FAVICONSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_HISTORYSERVICE_CID);
 
 const mozilla::Module::CIDEntry kPlacesCIDs[] = {
-  { &kNS_NAVHISTORYSERVICE_CID, false, NULL, nsNavHistoryConstructor },
-  { &kNS_ANNOTATIONSERVICE_CID, false, NULL, nsAnnotationServiceConstructor },
-  { &kNS_ANNOPROTOCOLHANDLER_CID, false, NULL, nsAnnoProtocolHandlerConstructor },
-  { &kNS_NAVBOOKMARKSSERVICE_CID, false, NULL, nsNavBookmarksConstructor },
-  { &kNS_FAVICONSERVICE_CID, false, NULL, nsFaviconServiceConstructor },
-  { &kNS_HISTORYSERVICE_CID, false, NULL, HistoryConstructor },
-  { NULL }
+  { &kNS_NAVHISTORYSERVICE_CID, false, nullptr, nsNavHistoryConstructor },
+  { &kNS_ANNOTATIONSERVICE_CID, false, nullptr, nsAnnotationServiceConstructor },
+  { &kNS_ANNOPROTOCOLHANDLER_CID, false, nullptr, nsAnnoProtocolHandlerConstructor },
+  { &kNS_NAVBOOKMARKSSERVICE_CID, false, nullptr, nsNavBookmarksConstructor },
+  { &kNS_FAVICONSERVICE_CID, false, nullptr, nsFaviconServiceConstructor },
+  { &kNS_HISTORYSERVICE_CID, false, nullptr, HistoryConstructor },
+  { nullptr }
 };
 
 const mozilla::Module::ContractIDEntry kPlacesContracts[] = {
   { NS_NAVHISTORYSERVICE_CONTRACTID, &kNS_NAVHISTORYSERVICE_CID },
   { NS_ANNOTATIONSERVICE_CONTRACTID, &kNS_ANNOTATIONSERVICE_CID },
   { NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "moz-anno", &kNS_ANNOPROTOCOLHANDLER_CID },
   { NS_NAVBOOKMARKSSERVICE_CONTRACTID, &kNS_NAVBOOKMARKSSERVICE_CID },
   { NS_FAVICONSERVICE_CONTRACTID, &kNS_FAVICONSERVICE_CID },
   { "@mozilla.org/embeddor.implemented/bookmark-charset-resolver;1", &kNS_NAVHISTORYSERVICE_CID },
   { NS_IHISTORY_CONTRACTID, &kNS_HISTORYSERVICE_CID },
   { NS_DOWNLOADHISTORY_CONTRACTID, &kNS_HISTORYSERVICE_CID },
-  { NULL }
+  { nullptr }
 };
 
 const mozilla::Module::CategoryEntry kPlacesCategories[] = {
   { "vacuum-participant", "Places", NS_NAVHISTORYSERVICE_CONTRACTID },
-  { NULL }
+  { nullptr }
 };
 
 const mozilla::Module kPlacesModule = {
   mozilla::Module::kVersion,
   kPlacesCIDs,
   kPlacesContracts,
   kPlacesCategories
 };
--- a/toolkit/components/places/tests/cpp/test_IHistory.cpp
+++ b/toolkit/components/places/tests/cpp/test_IHistory.cpp
@@ -553,17 +553,17 @@ test_visituri_transition_embed()
 }
 
 void
 test_new_visit_adds_place_guid()
 {
   // First, add a visit and wait.  This will also add a place.
   nsCOMPtr<nsIURI> visitedURI = new_test_uri();
   nsCOMPtr<IHistory> history = do_get_IHistory();
-  nsresult rv = history->VisitURI(visitedURI, NULL,
+  nsresult rv = history->VisitURI(visitedURI, nullptr,
                                   mozilla::IHistory::TOP_LEVEL);
   do_check_success(rv);
   nsRefPtr<VisitURIObserver> finisher = new VisitURIObserver();
   finisher->WaitForNotification();
 
   // Check that we have a guid for our visit.
   PlaceRecord place;
   do_get_place(visitedURI, place);
@@ -574,28 +574,28 @@ test_new_visit_adds_place_guid()
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 //// IPC-only Tests
 
 void
 test_two_null_links_same_uri()
 {
-  // Tests that we do not crash when we have had two NULL Links passed to
+  // Tests that we do not crash when we have had two nullptr Links passed to
   // RegisterVisitedCallback and then the visit occurs (bug 607469).  This only
   // happens in IPC builds.
   nsCOMPtr<nsIURI> testURI = new_test_uri();
 
   nsCOMPtr<IHistory> history = do_get_IHistory();
-  nsresult rv = history->RegisterVisitedCallback(testURI, NULL);
+  nsresult rv = history->RegisterVisitedCallback(testURI, nullptr);
   do_check_success(rv);
-  rv = history->RegisterVisitedCallback(testURI, NULL);
+  rv = history->RegisterVisitedCallback(testURI, nullptr);
   do_check_success(rv);
 
-  rv = history->VisitURI(testURI, NULL, mozilla::IHistory::TOP_LEVEL);
+  rv = history->VisitURI(testURI, nullptr, mozilla::IHistory::TOP_LEVEL);
   do_check_success(rv);
 
   nsRefPtr<VisitURIObserver> finisher = new VisitURIObserver();
   finisher->WaitForNotification();
 
   run_next_test();
 }
 
--- a/toolkit/components/reflect/reflect.cpp
+++ b/toolkit/components/reflect/reflect.cpp
@@ -53,23 +53,23 @@ Module::Call(nsIXPConnectWrappedNative* 
 }
 
 }
 }
 
 NS_DEFINE_NAMED_CID(JSREFLECT_CID);
 
 static const mozilla::Module::CIDEntry kReflectCIDs[] = {
-  { &kJSREFLECT_CID, false, NULL, mozilla::reflect::ModuleConstructor },
-  { NULL }
+  { &kJSREFLECT_CID, false, nullptr, mozilla::reflect::ModuleConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kReflectContracts[] = {
   { JSREFLECT_CONTRACTID, &kJSREFLECT_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kReflectModule = {
   mozilla::Module::kVersion,
   kReflectCIDs,
   kReflectContracts
 };
 
--- a/toolkit/components/remote/nsGTKRemoteService.cpp
+++ b/toolkit/components/remote/nsGTKRemoteService.cpp
@@ -171,23 +171,23 @@ nsGTKRemoteService::HandlePropertyChange
 // {C0773E90-5799-4eff-AD03-3EBCD85624AC}
 #define NS_REMOTESERVICE_CID \
   { 0xc0773e90, 0x5799, 0x4eff, { 0xad, 0x3, 0x3e, 0xbc, 0xd8, 0x56, 0x24, 0xac } }
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsGTKRemoteService)
 NS_DEFINE_NAMED_CID(NS_REMOTESERVICE_CID);
 
 static const mozilla::Module::CIDEntry kRemoteCIDs[] = {
-  { &kNS_REMOTESERVICE_CID, false, NULL, nsGTKRemoteServiceConstructor },
-  { NULL }
+  { &kNS_REMOTESERVICE_CID, false, nullptr, nsGTKRemoteServiceConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kRemoteContracts[] = {
   { "@mozilla.org/toolkit/remote-service;1", &kNS_REMOTESERVICE_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kRemoteModule = {
   mozilla::Module::kVersion,
   kRemoteCIDs,
   kRemoteContracts
 };
 
--- a/toolkit/components/remote/nsGTKRemoteService.h
+++ b/toolkit/components/remote/nsGTKRemoteService.h
@@ -20,17 +20,17 @@ class nsGTKRemoteService MOZ_FINAL : pub
 {
 public:
   // We will be a static singleton, so don't use the ordinary methods.
   NS_DECL_ISUPPORTS
   NS_DECL_NSIREMOTESERVICE
 
 
   nsGTKRemoteService() :
-    mServerWindow(NULL) { }
+    mServerWindow(nullptr) { }
 
 private:
   ~nsGTKRemoteService() { }
 
   void HandleCommandsFor(GtkWidget* aWidget,
                          nsIWeakReference* aWindow);
 
 
--- a/toolkit/components/remote/nsQtRemoteService.cpp
+++ b/toolkit/components/remote/nsQtRemoteService.cpp
@@ -114,23 +114,23 @@ nsQtRemoteService::SetDesktopStartupIDOr
 // {C0773E90-5799-4eff-AD03-3EBCD85624AC}
 #define NS_REMOTESERVICE_CID \
   { 0xc0773e90, 0x5799, 0x4eff, { 0xad, 0x3, 0x3e, 0xbc, 0xd8, 0x56, 0x24, 0xac } }
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsQtRemoteService)
 NS_DEFINE_NAMED_CID(NS_REMOTESERVICE_CID);
 
 static const mozilla::Module::CIDEntry kRemoteCIDs[] = {
-  { &kNS_REMOTESERVICE_CID, false, NULL, nsQtRemoteServiceConstructor },
-  { NULL }
+  { &kNS_REMOTESERVICE_CID, false, nullptr, nsQtRemoteServiceConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kRemoteContracts[] = {
   { "@mozilla.org/toolkit/remote-service;1", &kNS_REMOTESERVICE_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kRemoteModule = {
   mozilla::Module::kVersion,
   kRemoteCIDs,
   kRemoteContracts
 };
 
--- a/toolkit/components/remote/nsXRemoteService.cpp
+++ b/toolkit/components/remote/nsXRemoteService.cpp
@@ -209,17 +209,17 @@ nsXRemoteService::HandleNewProperty(XID 
     if (result != Success)
       return false;
 
     // Failed to get the data off the window or it was the wrong type?
     if (!data || !TO_LITTLE_ENDIAN32(*reinterpret_cast<int32_t*>(data)))
       return false;
 
     // cool, we got the property data.
-    const char *response = NULL;
+    const char *response = nullptr;
     if (aChangedAtom == sMozCommandAtom)
       response = HandleCommand(data, window, aEventTime);
     else if (aChangedAtom == sMozCommandLineAtom)
       response = HandleCommandLine(data, window, aEventTime);
 
     // put the property onto the window as the response
     XChangeProperty (aDisplay, aWindowId,
                      sMozResponseAtom, XA_STRING,
--- a/toolkit/components/satchel/nsFormFillController.cpp
+++ b/toolkit/components/satchel/nsFormFillController.cpp
@@ -1199,24 +1199,24 @@ nsFormFillController::GetIndexOfDocShell
   return -1;
 }
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsFormFillController)
 
 NS_DEFINE_NAMED_CID(NS_FORMFILLCONTROLLER_CID);
 
 static const mozilla::Module::CIDEntry kSatchelCIDs[] = {
-  { &kNS_FORMFILLCONTROLLER_CID, false, NULL, nsFormFillControllerConstructor },
-  { NULL }
+  { &kNS_FORMFILLCONTROLLER_CID, false, nullptr, nsFormFillControllerConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kSatchelContracts[] = {
   { "@mozilla.org/satchel/form-fill-controller;1", &kNS_FORMFILLCONTROLLER_CID },
   { NS_FORMHISTORYAUTOCOMPLETE_CONTRACTID, &kNS_FORMFILLCONTROLLER_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kSatchelModule = {
   mozilla::Module::kVersion,
   kSatchelCIDs,
   kSatchelContracts
 };
 
--- a/toolkit/components/startup/nsAppStartup.cpp
+++ b/toolkit/components/startup/nsAppStartup.cpp
@@ -666,17 +666,17 @@ nsAppStartup::Observe(nsISupports *aSubj
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsAppStartup::GetStartupInfo(JSContext* aCx, JS::Value* aRetval)
 {
-  JS::Rooted<JSObject*> obj(aCx, JS_NewObject(aCx, NULL, NULL, NULL));
+  JS::Rooted<JSObject*> obj(aCx, JS_NewObject(aCx, nullptr, nullptr, nullptr));
   *aRetval = OBJECT_TO_JSVAL(obj);
 
   TimeStamp procTime = StartupTimeline::Get(StartupTimeline::PROCESS_CREATION);
   TimeStamp now = TimeStamp::Now();
   PRTime absNow = PR_Now();
 
   if (procTime.IsNull()) {
     bool error = false;
@@ -707,17 +707,17 @@ nsAppStartup::GetStartupInfo(JSContext* 
     }
 
     if (!stamp.IsNull()) {
       if (stamp >= procTime) {
         PRTime prStamp = ComputeAbsoluteTimestamp(absNow, now, stamp)
           / PR_USEC_PER_MSEC;
         JS::Rooted<JSObject*> date(aCx, JS_NewDateObjectMsec(aCx, prStamp));
         JS_DefineProperty(aCx, obj, StartupTimeline::Describe(ev),
-          OBJECT_TO_JSVAL(date), NULL, NULL, JSPROP_ENUMERATE);
+          OBJECT_TO_JSVAL(date), nullptr, nullptr, JSPROP_ENUMERATE);
       } else {
         Telemetry::Accumulate(Telemetry::STARTUP_MEASUREMENT_ERRORS, ev);
       }
     }
   }
 
   return NS_OK;
 }
--- a/toolkit/components/startup/nsUserInfoWin.cpp
+++ b/toolkit/components/startup/nsUserInfoWin.cpp
@@ -96,17 +96,17 @@ nsUserInfo::GetFullname(PRUnichar **aFul
 NS_IMETHODIMP
 nsUserInfo::GetDomain(char **aDomain)
 {
   NS_ENSURE_ARG_POINTER(aDomain);
   *aDomain = nullptr;
 
   const DWORD level = 100;
   LPBYTE info;
-  NET_API_STATUS status = NetWkstaGetInfo(NULL, level, &info);
+  NET_API_STATUS status = NetWkstaGetInfo(nullptr, level, &info);
   if (status == NERR_Success) {
     *aDomain =
       ToNewUTF8String(nsDependentString(reinterpret_cast<WKSTA_INFO_100 *>(info)->
                                         wki100_langroup));
     NetApiBufferFree(info);
   }
 
   return (*aDomain) ? NS_OK : NS_ERROR_FAILURE;
--- a/toolkit/components/telemetry/Histograms.json
+++ b/toolkit/components/telemetry/Histograms.json
@@ -4083,20 +4083,20 @@
     "n_values": 4,
     "description": "Accumulates type of content (mixed, mixed passive, unmixed) per page load"
   },
   "MIXED_CONTENT_UNBLOCK_COUNTER": {
     "kind": "enumerated",
     "n_values": 3,
     "description": "A simple counter of daily mixed-content unblock operations and top documents loaded"
   },
-  "NTLM_MODULE_USED": {
+  "NTLM_MODULE_USED_2": {
     "kind": "enumerated",
     "n_values": 8,
-    "description": "The module used for the NTLM protocol (Windows_API, Kerberos, Samba_auth or Generic) and whether or not the authentication was used to connect to a proxy server. This data is collected only once per session (at first NTLM authentification)."
+    "description": "The module used for the NTLM protocol (Windows_API, Kerberos, Samba_auth or Generic) and whether or not the authentication was used to connect to a proxy server. This data is collected only once per session (at first NTLM authentification) ; fixed version."
   },
   "FX_THUMBNAILS_BG_QUEUE_SIZE_ON_CAPTURE": {
     "kind": "exponential",
     "high": 100,
     "n_buckets": 15,
     "extended_statistics_ok": true,
     "description": "BACKGROUND THUMBNAILS: Size of capture queue when a capture request is received"
   },
--- a/toolkit/components/telemetry/Telemetry.cpp
+++ b/toolkit/components/telemetry/Telemetry.cpp
@@ -324,17 +324,17 @@ private:
   CombinedStacks mLateWritesStacks; // This is collected out of the main thread.
   bool mCachedTelemetryData;
   uint32_t mLastShutdownTime;
   uint32_t mFailedLockCount;
   nsCOMArray<nsIFetchTelemetryDataCallback> mCallbacks;
   friend class nsFetchTelemetryData;
 };
 
-TelemetryImpl*  TelemetryImpl::sTelemetry = NULL;
+TelemetryImpl*  TelemetryImpl::sTelemetry = nullptr;
 
 size_t
 TelemetryImpl::SizeOfIncludingThisHelper(mozilla::MallocSizeOf aMallocSizeOf)
 {
   size_t n = aMallocSizeOf(this);
   // Ignore the hashtables in mAddonMap; they are not significant.
   n += mAddonMap.SizeOfExcludingThis(nullptr, aMallocSizeOf);
   n += mHistogramMap.SizeOfExcludingThis(nullptr, aMallocSizeOf);
@@ -526,63 +526,63 @@ enum reflectStatus
 ReflectHistogramAndSamples(JSContext *cx, JS::Handle<JSObject*> obj, Histogram *h,
                            const Histogram::SampleSet &ss)
 {
   // We don't want to reflect corrupt histograms.
   if (h->FindCorruption(ss) != Histogram::NO_INCONSISTENCIES) {
     return REFLECT_CORRUPT;
   }
 
-  if (!(JS_DefineProperty(cx, obj, "min", INT_TO_JSVAL(h->declared_min()), NULL, NULL, JSPROP_ENUMERATE)
-        && JS_DefineProperty(cx, obj, "max", INT_TO_JSVAL(h->declared_max()), NULL, NULL, JSPROP_ENUMERATE)
-        && JS_DefineProperty(cx, obj, "histogram_type", INT_TO_JSVAL(h->histogram_type()), NULL, NULL, JSPROP_ENUMERATE)
-        && JS_DefineProperty(cx, obj, "sum", DOUBLE_TO_JSVAL(ss.sum()), NULL, NULL, JSPROP_ENUMERATE))) {
+  if (!(JS_DefineProperty(cx, obj, "min", INT_TO_JSVAL(h->declared_min()), nullptr, nullptr, JSPROP_ENUMERATE)
+        && JS_DefineProperty(cx, obj, "max", INT_TO_JSVAL(h->declared_max()), nullptr, nullptr, JSPROP_ENUMERATE)
+        && JS_DefineProperty(cx, obj, "histogram_type", INT_TO_JSVAL(h->histogram_type()), nullptr, nullptr, JSPROP_ENUMERATE)
+        && JS_DefineProperty(cx, obj, "sum", DOUBLE_TO_JSVAL(ss.sum()), nullptr, nullptr, JSPROP_ENUMERATE))) {
     return REFLECT_FAILURE;
   }
 
   if (h->histogram_type() == Histogram::HISTOGRAM) {
-    if (!(JS_DefineProperty(cx, obj, "log_sum", DOUBLE_TO_JSVAL(ss.log_sum()), NULL, NULL, JSPROP_ENUMERATE)
-          && JS_DefineProperty(cx, obj, "log_sum_squares", DOUBLE_TO_JSVAL(ss.log_sum_squares()), NULL, NULL, JSPROP_ENUMERATE))) {
+    if (!(JS_DefineProperty(cx, obj, "log_sum", DOUBLE_TO_JSVAL(ss.log_sum()), nullptr, nullptr, JSPROP_ENUMERATE)
+          && JS_DefineProperty(cx, obj, "log_sum_squares", DOUBLE_TO_JSVAL(ss.log_sum_squares()), nullptr, nullptr, JSPROP_ENUMERATE))) {
       return REFLECT_FAILURE;
     }
   } else {
     // Export |sum_squares| as two separate 32-bit properties so that we
     // can accurately reconstruct it on the analysis side.
     uint64_t sum_squares = ss.sum_squares();
     // Cast to avoid implicit truncation warnings.
     uint32_t lo = static_cast<uint32_t>(sum_squares);
     uint32_t hi = static_cast<uint32_t>(sum_squares >> 32);
-    if (!(JS_DefineProperty(cx, obj, "sum_squares_lo", INT_TO_JSVAL(lo), NULL, NULL, JSPROP_ENUMERATE)
-          && JS_DefineProperty(cx, obj, "sum_squares_hi", INT_TO_JSVAL(hi), NULL, NULL, JSPROP_ENUMERATE))) {
+    if (!(JS_DefineProperty(cx, obj, "sum_squares_lo", INT_TO_JSVAL(lo), nullptr, nullptr, JSPROP_ENUMERATE)
+          && JS_DefineProperty(cx, obj, "sum_squares_hi", INT_TO_JSVAL(hi), nullptr, nullptr, JSPROP_ENUMERATE))) {
       return REFLECT_FAILURE;
     }
   }
 
   const size_t count = h->bucket_count();
   JS::Rooted<JSObject*> rarray(cx, JS_NewArrayObject(cx, count, nullptr));
   if (!rarray) {
     return REFLECT_FAILURE;
   }
   if (!(FillRanges(cx, rarray, h)
         && JS_DefineProperty(cx, obj, "ranges", OBJECT_TO_JSVAL(rarray),
-                             NULL, NULL, JSPROP_ENUMERATE))) {
+                             nullptr, nullptr, JSPROP_ENUMERATE))) {
     return REFLECT_FAILURE;
   }
 
   JS::Rooted<JSObject*> counts_array(cx, JS_NewArrayObject(cx, count, nullptr));
   if (!counts_array) {
     return REFLECT_FAILURE;
   }
   if (!JS_DefineProperty(cx, obj, "counts", OBJECT_TO_JSVAL(counts_array),
-                         NULL, NULL, JSPROP_ENUMERATE)) {
+                         nullptr, nullptr, JSPROP_ENUMERATE)) {
     return REFLECT_FAILURE;
   }
   for (size_t i = 0; i < count; i++) {
     if (!JS_DefineElement(cx, counts_array, i, INT_TO_JSVAL(ss.counts(i)),
-                          NULL, NULL, JSPROP_ENUMERATE)) {
+                          nullptr, nullptr, JSPROP_ENUMERATE)) {
       return REFLECT_FAILURE;
     }
   }
 
   return REFLECT_OK;
 }
 
 enum reflectStatus
@@ -999,17 +999,17 @@ TelemetryImpl::ReflectSQL(const SlowSQLE
   if (!arrayObj) {
     return false;
   }
   return (JS_SetElement(cx, arrayObj, 0, &hitCount)
           && JS_SetElement(cx, arrayObj, 1, &totalTime)
           && JS_DefineProperty(cx, obj,
                                sql.BeginReading(),
                                OBJECT_TO_JSVAL(arrayObj),
-                               NULL, NULL, JSPROP_ENUMERATE));
+                               nullptr, nullptr, JSPROP_ENUMERATE));
 }
 
 bool
 TelemetryImpl::ReflectMainThreadSQL(SlowSQLEntryType *entry, JSContext *cx,
                                     JS::Handle<JSObject*> obj)
 {
   return ReflectSQL(entry, &entry->mData.mainThread, cx, obj);
 }
@@ -1035,17 +1035,17 @@ TelemetryImpl::AddSQLInfo(JSContext *cx,
     (mainThread ? ReflectMainThreadSQL : ReflectOtherThreadsSQL);
   if(!sqlMap.ReflectIntoJS(reflectFunction, cx, statsObj)) {
     return false;
   }
 
   return JS_DefineProperty(cx, rootObj,
                            mainThread ? "mainThread" : "otherThreads",
                            OBJECT_TO_JSVAL(statsObj),
-                           NULL, NULL, JSPROP_ENUMERATE);
+                           nullptr, nullptr, JSPROP_ENUMERATE);
 }
 
 nsresult
 TelemetryImpl::GetHistogramEnumId(const char *name, Telemetry::ID *id)
 {
   if (!sTelemetry) {
     return NS_ERROR_FAILURE;
   }
@@ -1318,17 +1318,17 @@ TelemetryImpl::GetHistogramSnapshots(JSC
       // We can still hit this case even if ShouldReflectHistograms
       // returns true.  The histogram lies outside of our control
       // somehow; just skip it.
       continue;
     case REFLECT_FAILURE:
       return NS_ERROR_FAILURE;
     case REFLECT_OK:
       if (!JS_DefineProperty(cx, root_obj, h->histogram_name().c_str(),
-                             OBJECT_TO_JSVAL(hobj), NULL, NULL, JSPROP_ENUMERATE)) {
+                             OBJECT_TO_JSVAL(hobj), nullptr, nullptr, JSPROP_ENUMERATE)) {
         return NS_ERROR_FAILURE;
       }
     }
   }
   return NS_OK;
 }
 
 bool
@@ -1379,17 +1379,17 @@ TelemetryImpl::AddonHistogramReflector(A
   switch (ReflectHistogramSnapshot(cx, snapshot, info.h)) {
   case REFLECT_FAILURE:
   case REFLECT_CORRUPT:
     return false;
   case REFLECT_OK:
     const nsACString &histogramName = entry->GetKey();
     if (!JS_DefineProperty(cx, obj,
                            PromiseFlatCString(histogramName).get(),
-                           OBJECT_TO_JSVAL(snapshot), NULL, NULL,
+                           OBJECT_TO_JSVAL(snapshot), nullptr, nullptr,
                            JSPROP_ENUMERATE)) {
       return false;
     }
     break;
   }
   return true;
 }
 
@@ -1402,17 +1402,17 @@ TelemetryImpl::AddonReflector(AddonEntry
   if (!subobj) {
     return false;
   }
 
   AddonHistogramMapType *map = entry->mData;
   if (!(map->ReflectIntoJS(AddonHistogramReflector, cx, subobj)
         && JS_DefineProperty(cx, obj,
                              PromiseFlatCString(addonId).get(),
-                             OBJECT_TO_JSVAL(subobj), NULL, NULL,
+                             OBJECT_TO_JSVAL(subobj), nullptr, nullptr,
                              JSPROP_ENUMERATE))) {
     return false;
   }
   return true;
 }
 
 NS_IMETHODIMP
 TelemetryImpl::GetAddonHistogramSnapshots(JSContext *cx, JS::Value *ret)
@@ -1488,17 +1488,17 @@ TelemetryImpl::GetChromeHangs(JSContext 
   *ret = OBJECT_TO_JSVAL(fullReportObj);
 
   JS::Rooted<JSObject*> durationArray(cx, JS_NewArrayObject(cx, 0, nullptr));
   if (!durationArray) {
     return NS_ERROR_FAILURE;
   }
   bool ok = JS_DefineProperty(cx, fullReportObj, "durations",
                               OBJECT_TO_JSVAL(durationArray),
-                              NULL, NULL, JSPROP_ENUMERATE);
+                              nullptr, nullptr, JSPROP_ENUMERATE);
   if (!ok) {
     return NS_ERROR_FAILURE;
   }
 
   const size_t length = stacks.GetStackCount();
   for (size_t i = 0; i < length; ++i) {
     JS::Rooted<JS::Value> duration(cx, INT_TO_JSVAL(mHangReports.GetDuration(i)));
     if (!JS_SetElement(cx, durationArray, i, &duration)) {
@@ -1517,17 +1517,17 @@ CreateJSStackObject(JSContext *cx, const
   }
 
   JS::Rooted<JSObject*> moduleArray(cx, JS_NewArrayObject(cx, 0, nullptr));
   if (!moduleArray) {
     return nullptr;
   }
   bool ok = JS_DefineProperty(cx, ret, "memoryMap",
                               OBJECT_TO_JSVAL(moduleArray),
-                              NULL, NULL, JSPROP_ENUMERATE);
+                              nullptr, nullptr, JSPROP_ENUMERATE);
   if (!ok) {
     return nullptr;
   }
 
   const size_t moduleCount = stacks.GetModuleCount();
   for (size_t moduleIndex = 0; moduleIndex < moduleCount; ++moduleIndex) {
     // Current module
     const Telemetry::ProcessedStack::Module& module =
@@ -1566,17 +1566,17 @@ CreateJSStackObject(JSContext *cx, const
   }
 
   JS::Rooted<JSObject*> reportArray(cx, JS_NewArrayObject(cx, 0, nullptr));
   if (!reportArray) {
     return nullptr;
   }
   ok = JS_DefineProperty(cx, ret, "stacks",
                          OBJECT_TO_JSVAL(reportArray),
-                         NULL, NULL, JSPROP_ENUMERATE);
+                         nullptr, nullptr, JSPROP_ENUMERATE);
   if (!ok) {
     return nullptr;
   }
 
   const size_t length = stacks.GetStackCount();
   for (size_t i = 0; i < length; ++i) {
     // Represent call stack PCs as (module index, offset) pairs.
     JS::Rooted<JSObject*> pcArray(cx, JS_NewArrayObject(cx, 0, nullptr));
@@ -1783,17 +1783,17 @@ TelemetryImpl::GetRegisteredHistograms(J
   if (!info)
     return NS_ERROR_FAILURE;
 
   for (size_t i = 0; i < count; ++i) {
     JSString *comment = JS_InternString(cx, gHistograms[i].comment());
 
     if (!(comment
           && JS_DefineProperty(cx, info, gHistograms[i].id(),
-                               STRING_TO_JSVAL(comment), NULL, NULL,
+                               STRING_TO_JSVAL(comment), nullptr, nullptr,
                                JSPROP_ENUMERATE))) {
       return NS_ERROR_FAILURE;
     }
   }
 
   *ret = OBJECT_TO_JSVAL(info);
   return NS_OK;
 }
@@ -1834,17 +1834,17 @@ TelemetryImpl::GetCanSend(bool *ret) {
   *ret = false;
 #endif
   return NS_OK;
 }
 
 already_AddRefed<nsITelemetry>
 TelemetryImpl::CreateTelemetryInstance()
 {
-  NS_ABORT_IF_FALSE(sTelemetry == NULL, "CreateTelemetryInstance may only be called once, via GetService()");
+  NS_ABORT_IF_FALSE(sTelemetry == nullptr, "CreateTelemetryInstance may only be called once, via GetService()");
   sTelemetry = new TelemetryImpl();
   // AddRef for the local reference
   NS_ADDREF(sTelemetry);
   // AddRef for the caller
   nsCOMPtr<nsITelemetry> ret = sTelemetry;
   return ret.forget();
 }
 
@@ -1853,17 +1853,17 @@ TelemetryImpl::ShutdownTelemetry()
 {
   NS_IF_RELEASE(sTelemetry);
 }
 
 void
 TelemetryImpl::StoreSlowSQL(const nsACString &sql, uint32_t delay,
                             SanitizedState state)
 {
-  AutoHashtable<SlowSQLEntryType> *slowSQLMap = NULL;
+  AutoHashtable<SlowSQLEntryType> *slowSQLMap = nullptr;
   if (state == Sanitized)
     slowSQLMap = &(sTelemetry->mSanitizedSQL);
   else
     slowSQLMap = &(sTelemetry->mPrivateSQL);
 
   MutexAutoLock hashMutex(sTelemetry->mHashMutex);
 
   SlowSQLEntryType *entry = slowSQLMap->GetEntry(sql);
@@ -2061,32 +2061,32 @@ TelemetryImpl::RecordChromeHang(uint32_t
 NS_IMPL_ISUPPORTS1(TelemetryImpl, nsITelemetry)
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsITelemetry, TelemetryImpl::CreateTelemetryInstance)
 
 #define NS_TELEMETRY_CID \
   {0xaea477f2, 0xb3a2, 0x469c, {0xaa, 0x29, 0x0a, 0x82, 0xd1, 0x32, 0xb8, 0x29}}
 NS_DEFINE_NAMED_CID(NS_TELEMETRY_CID);
 
 const Module::CIDEntry kTelemetryCIDs[] = {
-  { &kNS_TELEMETRY_CID, false, NULL, nsITelemetryConstructor },
-  { NULL }
+  { &kNS_TELEMETRY_CID, false, nullptr, nsITelemetryConstructor },
+  { nullptr }
 };
 
 const Module::ContractIDEntry kTelemetryContracts[] = {
   { "@mozilla.org/base/telemetry;1", &kNS_TELEMETRY_CID },
-  { NULL }
+  { nullptr }
 };
 
 const Module kTelemetryModule = {
   Module::kVersion,
   kTelemetryCIDs,
   kTelemetryContracts,
-  NULL,
-  NULL,
-  NULL,
+  nullptr,
+  nullptr,
+  nullptr,
   TelemetryImpl::ShutdownTelemetry
 };
 
 } // anonymous namespace
 
 namespace mozilla {
 void
 RecordShutdownStartTimeStamp() {
@@ -2190,17 +2190,17 @@ bool
 CanRecord()
 {
   return TelemetryImpl::CanRecord();
 }
 
 base::Histogram*
 GetHistogramById(ID id)
 {
-  Histogram *h = NULL;
+  Histogram *h = nullptr;
   GetHistogramByEnumId(id, &h);
   return h;
 }
 
 void
 RecordSlowSQLStatement(const nsACString &statement,
                        const nsACString &dbName,
                        uint32_t delay)
--- a/toolkit/crashreporter/InjectCrashReporter.cpp
+++ b/toolkit/crashreporter/InjectCrashReporter.cpp
@@ -56,19 +56,19 @@ InjectCrashRunnable::Run()
     CrashGenerationClient::DuplicatePipeToClientProcess(
       NS_ConvertASCIItoUTF16(GetChildNotificationPipe()).get(),
       hProcess);
   if (INVALID_HANDLE_VALUE == hRemotePipe) {
     NS_WARNING("Unable to duplicate crash reporter pipe to process.");
     return NS_OK;
   }
 
-  nsAutoHandle hThread(CreateRemoteThread(hProcess, NULL, 0,
+  nsAutoHandle hThread(CreateRemoteThread(hProcess, nullptr, 0,
                                           (LPTHREAD_START_ROUTINE) proc,
-                                          (void*) hRemotePipe, 0, NULL));
+                                          (void*) hRemotePipe, 0, nullptr));
   if (!hThread) {
     NS_WARNING("Unable to CreateRemoteThread");
 
     // We have to close the remote pipe or else our crash generation client
     // will be stuck unable to accept other remote requests.
     HANDLE toClose = INVALID_HANDLE_VALUE;
     if (DuplicateHandle(hProcess, hRemotePipe, ::GetCurrentProcess(),
                         &toClose, 0, FALSE,
--- a/toolkit/crashreporter/LoadLibraryRemote.cpp
+++ b/toolkit/crashreporter/LoadLibraryRemote.cpp
@@ -26,22 +26,22 @@ typedef const unsigned char* FileView;
 
 template<>
 class nsAutoRefTraits<FileView>
 {
 public:
   typedef FileView RawRef;
   static FileView Void()
   {
-    return NULL;
+    return nullptr;
   }
 
   static void Release(RawRef aView)
   {
-    if (NULL != aView)
+    if (nullptr != aView)
       UnmapViewOfFile(aView);
   }
 };
 
 #ifndef IMAGE_SIZEOF_BASE_RELOCATION
 // Vista SDKs no longer define IMAGE_SIZEOF_BASE_RELOCATION!?
 #define IMAGE_SIZEOF_BASE_RELOCATION (sizeof(IMAGE_BASE_RELOCATION))
 #endif
@@ -62,17 +62,19 @@ typedef BOOL (WINAPI *DllEntryProc)(HINS
 
 #ifdef DEBUG_OUTPUT
 static void
 OutputLastError(const char *msg)
 {
   char* tmp;
   char *tmpmsg;
   FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
-                 NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &tmp, 0, NULL);
+                 nullptr, GetLastError(),
+                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+                 (LPSTR) &tmp, 0, nullptr);
   tmpmsg = (char *)LocalAlloc(LPTR, strlen(msg) + strlen(tmp) + 3);
   sprintf(tmpmsg, "%s: %s", msg, tmp);
   OutputDebugStringA(tmpmsg);
   LocalFree(tmpmsg);
   LocalFree(tmp);
 }
 #endif
 
@@ -144,17 +146,17 @@ FinalizeSections(PMEMORYMODULE module, H
       // Copy the data from local->remote and set the memory protection
       if (!VirtualAllocEx(hRemoteProcess, remoteAddress, size, MEM_COMMIT, PAGE_READWRITE))
         return false;
 
       if (!WriteProcessMemory(hRemoteProcess,
                               remoteAddress,
                               localAddress,
                               size,
-                              NULL)) {
+                              nullptr)) {
 #ifdef DEBUG_OUTPUT
         OutputLastError("Error writing remote memory.\n");
 #endif
         return false;
       }
 
       if (VirtualProtectEx(hRemoteProcess, remoteAddress, size, protect, &oldProtect) == 0) {
 #ifdef DEBUG_OUTPUT
@@ -232,26 +234,26 @@ BuildImportTable(PMEMORYMODULE module)
   if (directory->Size > 0) {
     PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR) (codeBase + directory->VirtualAddress);
     PIMAGE_IMPORT_DESCRIPTOR importEnd = (PIMAGE_IMPORT_DESCRIPTOR) (codeBase + directory->VirtualAddress + directory->Size);
 
     for (; importDesc < importEnd && importDesc->Name; importDesc++) {
       POINTER_TYPE *thunkRef;
       FARPROC *funcRef;
       HMODULE handle = GetModuleHandleA((LPCSTR) (codeBase + importDesc->Name));
-      if (handle == NULL) {
+      if (handle == nullptr) {
 #if DEBUG_OUTPUT
         OutputLastError("Can't load library");
 #endif
         result = 0;
         break;
       }
 
       module->modules = (HMODULE *)realloc(module->modules, (module->numModules+1)*(sizeof(HMODULE)));
-      if (module->modules == NULL) {
+      if (module->modules == nullptr) {
         result = 0;
         break;
       }
 
       module->modules[module->numModules++] = handle;
       if (importDesc->OriginalFirstThunk) {
         thunkRef = (POINTER_TYPE *) (codeBase + importDesc->OriginalFirstThunk);
         funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk);
@@ -285,87 +287,87 @@ BuildImportTable(PMEMORYMODULE module)
 static void* MemoryGetProcAddress(PMEMORYMODULE module, const char *name);
 
 void* LoadRemoteLibraryAndGetAddress(HANDLE hRemoteProcess,
                                      const WCHAR* library,
                                      const char* symbol)
 {
   // Map the DLL into memory
   nsAutoHandle hLibrary(
-    CreateFile(library, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
-               FILE_ATTRIBUTE_NORMAL, NULL));
+    CreateFile(library, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
+               FILE_ATTRIBUTE_NORMAL, nullptr));
   if (INVALID_HANDLE_VALUE == hLibrary) {
 #if DEBUG_OUTPUT
     OutputLastError("Couldn't CreateFile the library.\n");
 #endif
-    return NULL;
+    return nullptr;
   }
 
   nsAutoHandle hMapping(
-    CreateFileMapping(hLibrary, NULL, PAGE_READONLY, 0, 0, NULL));
+    CreateFileMapping(hLibrary, nullptr, PAGE_READONLY, 0, 0, nullptr));
   if (!hMapping) {
 #if DEBUG_OUTPUT
     OutputLastError("Couldn't CreateFileMapping.\n");
 #endif
-    return NULL;
+    return nullptr;
   }
 
   nsAutoRef<FileView> data(
     (const unsigned char*) MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0));
   if (!data) {
 #if DEBUG_OUTPUT
     OutputLastError("Couldn't MapViewOfFile.\n");
 #endif
-    return NULL;
+    return nullptr;
   }
 
   SIZE_T locationDelta;
 
   PIMAGE_DOS_HEADER dos_header = (PIMAGE_DOS_HEADER)data.get();
   if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
 #if DEBUG_OUTPUT
     OutputDebugStringA("Not a valid executable file.\n");
 #endif
-    return NULL;
+    return nullptr;
   }
 
   PIMAGE_NT_HEADERS old_header = (PIMAGE_NT_HEADERS)(data + dos_header->e_lfanew);
   if (old_header->Signature != IMAGE_NT_SIGNATURE) {
 #if DEBUG_OUTPUT
     OutputDebugStringA("No PE header found.\n");
 #endif
-    return NULL;
+    return nullptr;
   }
 
   // reserve memory for image of library in this process and the target process
-  unsigned char* localCode = (unsigned char*) VirtualAlloc(NULL,
+  unsigned char* localCode = (unsigned char*) VirtualAlloc(nullptr,
     old_header->OptionalHeader.SizeOfImage,
     MEM_RESERVE | MEM_COMMIT,
     PAGE_READWRITE);
   if (!localCode) {
 #if DEBUG_OUTPUT
     OutputLastError("Can't reserve local memory.");
 #endif
   }
 
-  unsigned char* remoteCode = (unsigned char*) VirtualAllocEx(hRemoteProcess, NULL,
+  unsigned char* remoteCode = (unsigned char*) VirtualAllocEx(hRemoteProcess, nullptr,
     old_header->OptionalHeader.SizeOfImage,
     MEM_RESERVE,
     PAGE_EXECUTE_READ);
   if (!remoteCode) {
 #if DEBUG_OUTPUT
     OutputLastError("Can't reserve remote memory.");
 #endif
   }
 
   MEMORYMODULE result;
   result.localCodeBase = localCode;
   result.remoteCodeBase = remoteCode;
   result.numModules = 0;
-  result.modules = NULL;
+  result.modules = nullptr;
 
   // copy PE header to code
   memcpy(localCode, dos_header, dos_header->e_lfanew + old_header->OptionalHeader.SizeOfHeaders);
   result.headers = reinterpret_cast<PIMAGE_NT_HEADERS>(localCode + dos_header->e_lfanew);
 
   // update position
   result.headers->OptionalHeader.ImageBase = (POINTER_TYPE)remoteCode;
 
@@ -375,62 +377,62 @@ void* LoadRemoteLibraryAndGetAddress(HAN
   // adjust base address of imported data
   locationDelta = (SIZE_T)(remoteCode - old_header->OptionalHeader.ImageBase);
   if (locationDelta != 0) {
     PerformBaseRelocation(&result, locationDelta);
   }
 
   // load required dlls and adjust function table of imports
   if (!BuildImportTable(&result)) {
-    return NULL;
+    return nullptr;
   }
 
   // mark memory pages depending on section headers and release
   // sections that are marked as "discardable"
   if (!FinalizeSections(&result, hRemoteProcess)) {
-    return NULL;
+    return nullptr;
   }
 
   return MemoryGetProcAddress(&result, symbol);
 }
 
 static void* MemoryGetProcAddress(PMEMORYMODULE module, const char *name)
 {
   unsigned char *localCodeBase = module->localCodeBase;
   int idx=-1;
   DWORD i, *nameRef;
   WORD *ordinal;
   PIMAGE_EXPORT_DIRECTORY exports;
   PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_EXPORT);
   if (directory->Size == 0) {
     // no export table found
-    return NULL;
+    return nullptr;
   }
 
   exports = (PIMAGE_EXPORT_DIRECTORY) (localCodeBase + directory->VirtualAddress);
   if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) {
     // DLL doesn't export anything
-    return NULL;
+    return nullptr;
   }
 
   // search function name in list of exported names
   nameRef = (DWORD *) (localCodeBase + exports->AddressOfNames);
   ordinal = (WORD *) (localCodeBase + exports->AddressOfNameOrdinals);
   for (i=0; i<exports->NumberOfNames; i++, nameRef++, ordinal++) {
     if (stricmp(name, (const char *) (localCodeBase + (*nameRef))) == 0) {
       idx = *ordinal;
       break;
     }
   }
 
   if (idx == -1) {
     // exported symbol not found
-    return NULL;
+    return nullptr;
   }
 
   if ((DWORD)idx > exports->NumberOfFunctions) {
     // name <-> ordinal number don't match
-    return NULL;
+    return nullptr;
   }
 
   // AddressOfFunctions contains the RVAs to the "real" functions
   return module->remoteCodeBase + (*(DWORD *) (localCodeBase + exports->AddressOfFunctions + (idx*4)));
 }
--- a/toolkit/crashreporter/client/crashreporter.cpp
+++ b/toolkit/crashreporter/client/crashreporter.cpp
@@ -29,17 +29,17 @@ using std::auto_ptr;
 
 namespace CrashReporter {
 
 StringTable  gStrings;
 string       gSettingsPath;
 int          gArgc;
 char**       gArgv;
 
-static auto_ptr<ofstream> gLogStream(NULL);
+static auto_ptr<ofstream> gLogStream(nullptr);
 static string             gDumpFile;
 static string             gExtraFile;
 
 static string kExtraDataExtension = ".extra";
 
 void UIError(const string& message)
 {
   string errorMessage;
@@ -589,23 +589,23 @@ int main(int argc, char** argv)
 // We need WinMain in order to not be a console app.  This function is unused
 // if we are a console application.
 int WINAPI wWinMain( HINSTANCE, HINSTANCE, LPWSTR args, int )
 {
   // Remove everything except close window from the context menu
   {
     HKEY hkApp;
     RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Classes\\Applications", 0,
-                    NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hkApp,
-                    NULL);
+                    nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, nullptr,
+                    &hkApp, nullptr);
     RegCloseKey(hkApp);
     if (RegCreateKeyExW(HKEY_CURRENT_USER,
                         L"Software\\Classes\\Applications\\crashreporter.exe",
-                        0, NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE, NULL,
-                        &hkApp, NULL) == ERROR_SUCCESS) {
+                        0, nullptr, REG_OPTION_VOLATILE, KEY_SET_VALUE,
+                        nullptr, &hkApp, nullptr) == ERROR_SUCCESS) {
       RegSetValueExW(hkApp, L"IsHostApp", 0, REG_NONE, 0, 0);
       RegSetValueExW(hkApp, L"NoOpenWith", 0, REG_NONE, 0, 0);
       RegSetValueExW(hkApp, L"NoStartPage", 0, REG_NONE, 0, 0);
       RegCloseKey(hkApp);
     }
   }
 
   char** argv = static_cast<char**>(malloc(__argc * sizeof(char*)));
--- a/toolkit/crashreporter/client/crashreporter_gtk_common.cpp
+++ b/toolkit/crashreporter/client/crashreporter_gtk_common.cpp
@@ -133,41 +133,42 @@ void LoadProxyinfo()
        gconf_client_get_int &&
        gconf_client_get_string)) {
     dlclose(gconfLib);
     return;
   }
 
   GConfClient *conf = gconf_client_get_default();
 
-  if (gconf_client_get_bool(conf, HTTP_PROXY_DIR "/use_http_proxy", NULL)) {
+  if (gconf_client_get_bool(conf, HTTP_PROXY_DIR "/use_http_proxy", nullptr)) {
     gint port;
-    gchar *host = NULL, *httpproxy = NULL;
+    gchar *host = nullptr, *httpproxy = nullptr;
 
-    host = gconf_client_get_string(conf, HTTP_PROXY_DIR "/host", NULL);
-    port = gconf_client_get_int(conf, HTTP_PROXY_DIR "/port", NULL);
+    host = gconf_client_get_string(conf, HTTP_PROXY_DIR "/host", nullptr);
+    port = gconf_client_get_int(conf, HTTP_PROXY_DIR "/port", nullptr);
 
     if (port && host && *host != '\0') {
       httpproxy = g_strdup_printf("http://%s:%d/", host, port);
       gHttpProxy = httpproxy;
     }
 
     g_free(host);
     g_free(httpproxy);
 
-    if(gconf_client_get_bool(conf, HTTP_PROXY_DIR "/use_authentication", NULL)) {
-      gchar *user, *password, *auth = NULL;
+    if (gconf_client_get_bool(conf, HTTP_PROXY_DIR "/use_authentication",
+                              nullptr)) {
+      gchar *user, *password, *auth = nullptr;
 
       user = gconf_client_get_string(conf,
                                      HTTP_PROXY_DIR "/authentication_user",
-                                     NULL);
+                                     nullptr);
       password = gconf_client_get_string(conf,
                                          HTTP_PROXY_DIR
                                          "/authentication_password",
-                                         NULL);
+                                         nullptr);
 
       if (user && password) {
         auth = g_strdup_printf("%s:%s", user, password);
         gAuth = auth;
       }
 
       g_free(user);
       g_free(password);
@@ -204,17 +205,17 @@ gpointer SendThread(gpointer args)
   }
 
   SendCompleted(success, response);
   // Apparently glib is threadsafe, and will schedule this
   // on the main thread, see:
   // http://library.gnome.org/devel/gtk-faq/stable/x499.html
   g_idle_add(ReportCompleted, (gpointer)success);
 
-  return NULL;
+  return nullptr;
 }
 
 gboolean WindowDeleted(GtkWidget* window,
                               GdkEvent* event,
                               gpointer userData)
 {
   SaveSettings();
   gtk_main_quit();
@@ -270,17 +271,17 @@ void IncludeURLClicked(GtkButton* sender
 bool UIInit()
 {
   // breakpad probably left us with blocked signals, unblock them here
   sigset_t signals, old;
   sigfillset(&signals);
   sigprocmask(SIG_UNBLOCK, &signals, &old);
 
   // tell glib we're going to use threads
-  g_thread_init(NULL);
+  g_thread_init(nullptr);
 
   if (gtk_init_check(&gArgc, &gArgv)) {
     gInitialized = true;
 
     if (gStrings.find("isRTL") != gStrings.end() &&
         gStrings["isRTL"] == "yes")
       gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);
 
@@ -288,17 +289,17 @@ bool UIInit()
   }
 
   return false;
 }
 
 void UIShowDefaultUI()
 {
   GtkWidget* errorDialog =
-    gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
+    gtk_message_dialog_new(nullptr, GTK_DIALOG_M