Merge the last PGO-green inbound changeset to m-c.
authorRyan VanderMeulen <ryanvm@gmail.com>
Wed, 25 Sep 2013 14:51:55 -0400
changeset 148663 39f30376058cf20823534f2d510430eaa31844bf
parent 148605 fa0e6916f88cb81d11296d9dbbf6b63df189f451 (current diff)
parent 148662 3408740409b3855818e68fee460bbb71415e6c55 (diff)
child 148664 f8c3f242c115dbbf448e947ed05a1a68cb605783
child 148696 c8d86292e455feaea218dd0bc7a18082eefd98de
child 148724 856134aa09a46ac1adfc3db567dabaa1c47bf9e0
child 148731 9118a1fdd187a26ffb74fc89f129efeb2284ac0a
push id25349
push userryanvm@gmail.com
push dateWed, 25 Sep 2013 18:52:12 +0000
treeherdermozilla-central@39f30376058c [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 the last PGO-green inbound changeset to m-c.
widget/nsGUIEvent.h
--- 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 785884 - Implement support for temporary storage (aka shared pool) 
+Bug 913260 needed a clobber to not break tons of tests 
--- a/accessible/src/base/nsCoreUtils.cpp
+++ b/accessible/src/base/nsCoreUtils.cpp
@@ -19,17 +19,18 @@
 #include "nsIDocShell.h"
 #include "nsEventListenerManager.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIScrollableFrame.h"
 #include "nsEventStateManager.h"
 #include "nsISelectionPrivate.h"
 #include "nsISelectionController.h"
-#include "nsGUIEvent.h"
+#include "mozilla/MouseEvents.h"
+#include "mozilla/TouchEvents.h"
 #include "nsView.h"
 #include "nsGkAtoms.h"
 #include "nsDOMTouchEvent.h"
 
 #include "nsComponentManagerUtils.h"
 
 #include "nsITreeBoxObject.h"
 #include "nsITreeColumns.h"
--- a/accessible/src/base/nsCoreUtils.h
+++ b/accessible/src/base/nsCoreUtils.h
@@ -44,32 +44,32 @@ public:
    */
   static void DispatchClickEvent(nsITreeBoxObject *aTreeBoxObj,
                                  int32_t aRowIndex, nsITreeColumn *aColumn,
                                  const nsCString& aPseudoElt = EmptyCString());
 
   /**
    * Send mouse event to the given element.
    *
-   * @param aEventType   [in] an event type (see nsGUIEvent.h for constants)
+   * @param aEventType   [in] an event type (see BasicEvents.h for constants)
    * @param aX           [in] x coordinate in dev pixels
    * @param aY           [in] y coordinate in dev pixels
    * @param aContent     [in] the element
    * @param aFrame       [in] frame of the element
    * @param aPresShell   [in] the presshell for the element
    * @param aRootWidget  [in] the root widget of the element
    */
   static void DispatchMouseEvent(uint32_t aEventType, int32_t aX, int32_t aY,
                                  nsIContent *aContent, nsIFrame *aFrame,
                                  nsIPresShell *aPresShell, nsIWidget *aRootWidget);
 
   /**
    * Send a touch event with a single touch point to the given element.
    *
-   * @param aEventType   [in] an event type (see nsGUIEvent.h for constants)
+   * @param aEventType   [in] an event type (see BasicEvents.h for constants)
    * @param aX           [in] x coordinate in dev pixels
    * @param aY           [in] y coordinate in dev pixels
    * @param aContent     [in] the element
    * @param aFrame       [in] frame of the element
    * @param aPresShell   [in] the presshell for the element
    * @param aRootWidget  [in] the root widget of the element
    */
   static void DispatchTouchEvent(uint32_t aEventType, int32_t aX, int32_t aY,
--- a/accessible/src/generic/Accessible.cpp
+++ b/accessible/src/generic/Accessible.cpp
@@ -70,16 +70,17 @@
 #include "nsNetUtil.h"
 #include "nsEventStates.h"
 
 #ifdef DEBUG
 #include "nsIDOMCharacterData.h"
 #endif
 
 #include "mozilla/Assertions.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/unused.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/Element.h"
 
 using namespace mozilla;
 using namespace mozilla::a11y;
 
 
--- a/accessible/src/generic/BaseAccessibles.cpp
+++ b/accessible/src/generic/BaseAccessibles.cpp
@@ -7,18 +7,16 @@
 
 #include "Accessible-inl.h"
 #include "HyperTextAccessibleWrap.h"
 #include "nsAccessibilityService.h"
 #include "nsAccUtils.h"
 #include "nsCoreUtils.h"
 #include "Role.h"
 #include "States.h"
-
-#include "nsGUIEvent.h"
 #include "nsINameSpaceManager.h"
 #include "nsIURI.h"
 
 using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
 // LeafAccessible
 ////////////////////////////////////////////////////////////////////////////////
--- a/accessible/src/generic/HyperTextAccessible.cpp
+++ b/accessible/src/generic/HyperTextAccessible.cpp
@@ -770,17 +770,17 @@ HyperTextAccessible::FindOffset(int32_t 
       if (accAtOffset)
         frameAtOffset = accAtOffset->GetFrame();
     }
     NS_ASSERTION(frameAtOffset, "No start frame for text getting!");
     if (!frameAtOffset)
       return -1;
 
     // We're on the last continuation since we're on the last character.
-    frameAtOffset = frameAtOffset->GetLastContinuation();
+    frameAtOffset = frameAtOffset->LastContinuation();
   }
 
   // Return hypertext offset of the boundary of the found word.
   return GetRelativeOffset(mDoc->PresShell(), frameAtOffset, offsetInFrame,
                            accAtOffset, aAmount, aDirection,
                            (aWordMovementType == eStartWord || aAmount == eSelectBeginLine),
                            aWordMovementType);
 }
--- a/accessible/src/jsat/TraversalRules.jsm
+++ b/accessible/src/jsat/TraversalRules.jsm
@@ -103,16 +103,18 @@ var gSimpleTraversalRoles =
    ROLE_CHECK_MENU_ITEM,
    ROLE_PASSWORD_TEXT,
    ROLE_RADIO_MENU_ITEM,
    ROLE_TOGGLE_BUTTON,
    ROLE_ENTRY,
    ROLE_KEY,
    ROLE_HEADER,
    ROLE_HEADING,
+   ROLE_SLIDER,
+   ROLE_SPINBUTTON,
    // Used for traversing in to child OOP frames.
    ROLE_INTERNAL_FRAME];
 
 this.TraversalRules = {
   Simple: new BaseTraversalRule(
     gSimpleTraversalRoles,
     function Simple_match(aAccessible) {
       function hasZeroOrSingleChildDescendants () {
--- a/accessible/src/jsat/Utils.jsm
+++ b/accessible/src/jsat/Utils.jsm
@@ -552,17 +552,17 @@ PivotContext.prototype = {
     }
     let child = aAccessible.firstChild;
     while (child) {
       let include;
       if (this._includeInvisible) {
         include = true;
       } else {
         let [state,] = Utils.getStates(child);
-        include = !(state.value & Ci.nsIAccessibleStates.STATE_INVISIBLE);
+        include = !(state & Ci.nsIAccessibleStates.STATE_INVISIBLE);
       }
       if (include) {
         if (aPreorder) {
           yield child;
           [yield node for (node of this._traverse(child, aPreorder, aStop))];
         } else {
           [yield node for (node of this._traverse(child, aPreorder, aStop))];
           yield child;
--- a/accessible/src/xul/XULMenuAccessible.cpp
+++ b/accessible/src/xul/XULMenuAccessible.cpp
@@ -18,17 +18,16 @@
 #include "nsIMutableArray.h"
 #include "nsIDOMXULContainerElement.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIDOMKeyEvent.h"
 #include "nsIServiceManager.h"
 #include "nsIPresShell.h"
 #include "nsIContent.h"
-#include "nsGUIEvent.h"
 #include "nsMenuBarFrame.h"
 #include "nsMenuPopupFrame.h"
 
 #include "mozilla/Preferences.h"
 #include "mozilla/LookAndFeel.h"
 #include "mozilla/dom/Element.h"
 
 using namespace mozilla;
--- a/content/base/src/DOMImplementation.cpp
+++ b/content/base/src/DOMImplementation.cpp
@@ -1,14 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/dom/DOMImplementation.h"
 
+#include "mozilla/ContentEvents.h"
 #include "mozilla/dom/DOMImplementationBinding.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsContentUtils.h"
 #include "nsDOMClassInfoID.h"
 #include "nsIDOMDocument.h"
 #include "DocumentType.h"
 #include "nsTextNode.h"
 
--- a/content/base/src/Element.cpp
+++ b/content/base/src/Element.cpp
@@ -43,17 +43,20 @@
 #include "nsINameSpaceManager.h"
 #include "nsContentList.h"
 #include "nsDOMTokenList.h"
 #include "nsXBLPrototypeBinding.h"
 #include "nsError.h"
 #include "nsDOMString.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIDOMMutationEvent.h"
+#include "mozilla/ContentEvents.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/MutationEvent.h"
+#include "mozilla/TextEvents.h"
 #include "nsNodeUtils.h"
 #include "mozilla/dom/DirectionalityUtils.h"
 #include "nsDocument.h"
 #include "nsAttrValueOrString.h"
 #include "nsAttrValueInlines.h"
 #ifdef MOZ_XUL
 #include "nsXULElement.h"
 #endif /* MOZ_XUL */
--- a/content/base/src/FragmentOrElement.cpp
+++ b/content/base/src/FragmentOrElement.cpp
@@ -46,16 +46,17 @@
 #include "nsINameSpaceManager.h"
 #include "nsContentList.h"
 #include "nsDOMTokenList.h"
 #include "nsXBLPrototypeBinding.h"
 #include "nsError.h"
 #include "nsDOMString.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIDOMMutationEvent.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/MutationEvent.h"
 #include "nsNodeUtils.h"
 #include "nsDocument.h"
 #include "nsAttrValueOrString.h"
 #ifdef MOZ_XUL
 #include "nsXULElement.h"
 #endif /* MOZ_XUL */
 #include "nsFrameManager.h"
--- a/content/base/src/nsContentList.cpp
+++ b/content/base/src/nsContentList.cpp
@@ -39,17 +39,27 @@
 #endif
 
 using namespace mozilla::dom;
 
 nsBaseContentList::~nsBaseContentList()
 {
 }
 
-NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_1(nsBaseContentList, mElements)
+NS_IMPL_CYCLE_COLLECTION_CLASS(nsBaseContentList)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsBaseContentList)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK(mElements)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
+  tmp->RemoveFromCaches();
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsBaseContentList)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mElements)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(nsBaseContentList)
 
 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_BEGIN(nsBaseContentList)
   if (nsCCUncollectableMarker::sGeneration && tmp->IsBlack()) {
     for (uint32_t i = 0; i < tmp->mElements.Length(); ++i) {
       nsIContent* c = tmp->mElements[i];
       if (c->IsPurple()) {
         c->RemovePurple();
       }
--- a/content/base/src/nsContentList.h
+++ b/content/base/src/nsContentList.h
@@ -91,16 +91,24 @@ public:
   }
 
   virtual int32_t IndexOf(nsIContent *aContent, bool aDoFlush);
 
   virtual JSObject* WrapObject(JSContext *cx, JS::Handle<JSObject*> scope)
     MOZ_OVERRIDE = 0;
 
 protected:
+  /**
+   * To be called from non-destructor locations (e.g. unlink) that want to
+   * remove from caches.  Cacheable subclasses should override.
+   */
+  virtual void RemoveFromCaches()
+  {
+  }
+
   nsTArray< nsCOMPtr<nsIContent> > mElements;
 };
 
 
 class nsSimpleContentList : public nsBaseContentList
 {
 public:
   nsSimpleContentList(nsINode *aRoot) : nsBaseContentList(),
@@ -360,17 +368,18 @@ protected:
    */
   inline void BringSelfUpToDate(bool aDoFlush);
 
   /**
    * To be called from non-destructor locations that want to remove from caches.
    * Needed because if subclasses want to have cache behavior they can't just
    * override RemoveFromHashtable(), since we call that in our destructor.
    */
-  virtual void RemoveFromCaches() {
+  virtual void RemoveFromCaches() MOZ_OVERRIDE
+  {
     RemoveFromHashtable();
   }
 
   nsINode* mRootNode; // Weak ref
   int32_t mMatchNameSpaceId;
   nsCOMPtr<nsIAtom> mHTMLMatchAtom;
   nsCOMPtr<nsIAtom> mXMLMatchAtom;
 
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -33,19 +33,21 @@
 #include "mozilla/Base64.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/dom/DocumentFragment.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/HTMLMediaElement.h"
 #include "mozilla/dom/HTMLTemplateElement.h"
 #include "mozilla/dom/TextDecoder.h"
 #include "mozilla/Likely.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/MutationEvent.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Selection.h"
+#include "mozilla/TextEvents.h"
 #include "mozilla/Util.h"
 #include "nsAString.h"
 #include "nsAttrName.h"
 #include "nsAttrValue.h"
 #include "nsAttrValueInlines.h"
 #include "nsBindingManager.h"
 #include "nsCCUncollectableMarker.h"
 #include "nsChannelPolicy.h"
--- a/content/base/src/nsCopySupport.cpp
+++ b/content/base/src/nsCopySupport.cpp
@@ -31,27 +31,27 @@
 
 #include "nsPIDOMWindow.h"
 #include "nsIDocument.h"
 #include "nsIDOMNode.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMDocument.h"
 #include "nsIHTMLDocument.h"
 #include "nsGkAtoms.h"
-#include "nsGUIEvent.h"
 #include "nsIFrame.h"
 #include "nsIURI.h"
 #include "nsISimpleEnumerator.h"
 
 // image copy stuff
 #include "nsIImageLoadingContent.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsContentUtils.h"
 #include "nsContentCID.h"
 
+#include "mozilla/ContentEvents.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/Selection.h"
 
 #include "mozilla/Preferences.h"
 
 using namespace mozilla;
 
 nsresult NS_NewDomSelection(nsISelection **aDomSelection);
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -34,17 +34,17 @@
 #include "mozilla/css/Loader.h"
 #include "mozilla/css/ImageLoader.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsCOMArray.h"
 #include "nsDOMClassInfo.h"
 #include "nsCxPusher.h"
 
-#include "nsGUIEvent.h"
+#include "mozilla/BasicEvents.h"
 #include "nsAsyncDOMEvent.h"
 #include "nsIDOMNodeFilter.h"
 
 #include "nsIDOMStyleSheet.h"
 #include "mozilla/dom/Attr.h"
 #include "nsIDOMDOMStringList.h"
 #include "nsIDOMDOMImplementation.h"
 #include "nsIDOMDocumentXBL.h"
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -40,17 +40,16 @@
 #include "nsIScriptSecurityManager.h"
 #include "nsIScrollable.h"
 #include "nsFrameLoader.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIFrame.h"
 #include "nsIScrollableFrame.h"
 #include "nsSubDocumentFrame.h"
 #include "nsError.h"
-#include "nsGUIEvent.h"
 #include "nsEventDispatcher.h"
 #include "nsISHistory.h"
 #include "nsISHistoryInternal.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsIXULWindow.h"
 #include "nsIEditor.h"
 #include "nsIMozBrowserFrame.h"
 #include "nsIPermissionManager.h"
--- a/content/base/src/nsGenConImageContent.cpp
+++ b/content/base/src/nsGenConImageContent.cpp
@@ -11,17 +11,17 @@
  */
 
 #include "nsContentCreatorFunctions.h"
 #include "nsXMLElement.h"
 #include "nsImageLoadingContent.h"
 #include "imgIRequest.h"
 #include "nsEventStates.h"
 #include "nsEventDispatcher.h"
-#include "nsGUIEvent.h"
+#include "mozilla/BasicEvents.h"
 
 class nsGenConImageContent MOZ_FINAL : public nsXMLElement,
                                        public nsImageLoadingContent
 {
 public:
   nsGenConImageContent(already_AddRefed<nsINodeInfo> aNodeInfo)
     : nsXMLElement(aNodeInfo)
   {
--- a/content/base/src/nsImageLoadingContent.cpp
+++ b/content/base/src/nsImageLoadingContent.cpp
@@ -26,17 +26,16 @@
 #include "imgRequestProxy.h"
 #include "nsThreadUtils.h"
 #include "nsNetUtil.h"
 #include "nsAsyncDOMEvent.h"
 #include "nsImageFrame.h"
 
 #include "nsIPresShell.h"
 #include "nsEventStates.h"
-#include "nsGUIEvent.h"
 
 #include "nsIChannel.h"
 #include "nsIStreamListener.h"
 
 #include "nsIFrame.h"
 #include "nsIDOMNode.h"
 
 #include "nsContentUtils.h"
--- a/content/base/src/nsObjectLoadingContent.cpp
+++ b/content/base/src/nsObjectLoadingContent.cpp
@@ -53,17 +53,16 @@
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsDocShellCID.h"
 #include "nsGkAtoms.h"
 #include "nsThreadUtils.h"
 #include "nsNetUtil.h"
 #include "nsMimeTypes.h"
 #include "nsStyleUtil.h"
-#include "nsGUIEvent.h"
 #include "nsUnicharUtils.h"
 #include "mozilla/Preferences.h"
 #include "nsSandboxFlags.h"
 
 // Concrete classes
 #include "nsFrameLoader.h"
 
 #include "nsObjectLoadingContent.h"
--- a/content/base/src/nsScriptElement.cpp
+++ b/content/base/src/nsScriptElement.cpp
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsScriptElement.h"
+#include "mozilla/BasicEvents.h"
 #include "mozilla/dom/Element.h"
 #include "nsContentUtils.h"
-#include "nsGUIEvent.h"
 #include "nsEventDispatcher.h"
 #include "nsPresContext.h"
 #include "nsScriptLoader.h"
 #include "nsIParser.h"
 #include "nsAutoPtr.h"
 #include "nsGkAtoms.h"
 #include "nsContentSink.h"
 
--- a/content/base/src/nsXMLHttpRequest.cpp
+++ b/content/base/src/nsXMLHttpRequest.cpp
@@ -21,17 +21,16 @@
 #include "nsILoadGroup.h"
 #include "nsNetUtil.h"
 #include "nsStreamUtils.h"
 #include "nsThreadUtils.h"
 #include "nsIUploadChannel.h"
 #include "nsIUploadChannel2.h"
 #include "nsIDOMSerializer.h"
 #include "nsXPCOM.h"
-#include "nsGUIEvent.h"
 #include "nsIDOMEventListener.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIDOMWindow.h"
 #include "nsIVariant.h"
 #include "nsVariant.h"
 #include "nsIScriptError.h"
 #include "nsIStreamConverterService.h"
 #include "nsICachingChannel.h"
--- a/content/events/public/nsEventNameList.h
+++ b/content/events/public/nsEventNameList.h
@@ -5,17 +5,17 @@
 
 /*
  * This file contains the list of event names that are exposed via IDL
  * on various objects.  It is designed to be used as inline input to
  * various consumers through the magic of C preprocessing.
  *
  * Each entry consists of 4 pieces of information:
  * 1) The name of the event
- * 2) The event ID (see nsGUIEvent.h)
+ * 2) The event ID (see BasicEvents.h)
  * 3) The event type (see the EventNameType enum in nsContentUtils.h)
  * 4) The event struct type for this event.
  * Items 2-4 might be empty strings for events for which they don't make sense.
  *
  * Event names that are exposed as content attributes on HTML elements
  * and as IDL attributes on Elements, Documents and Windows and have
  * no forwarding behavior should be enclosed in the EVENT macro.
  *
--- a/content/events/public/nsVKList.h
+++ b/content/events/public/nsVKList.h
@@ -1,14 +1,14 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 et sw=2 tw=80: */
 /* 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/. */
-// IWYU pragma: private, include "nsGUIEvent.h"
+// IWYU pragma: private, include "mozilla/KeyTextEvents.h"
 
 /**
  * This header file defines all DOM keys which are defined in nsIDOMKeyEvent.
  * You must define NS_DEFINE_VK macro before including this.
  *
  * It must have two arguments, (aDOMKeyName, aDOMKeyCode)
  * aDOMKeyName is a key name in DOM.
  * aDOMKeyCode is one of nsIDOMKeyEvent::DOM_VK_*.
--- a/content/events/src/DOMWheelEvent.cpp
+++ b/content/events/src/DOMWheelEvent.cpp
@@ -1,16 +1,16 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 et sw=2 tw=80: */
 /* 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 "DOMWheelEvent.h"
-#include "nsGUIEvent.h"
+#include "mozilla/MouseEvents.h"
 #include "prtime.h"
 
 namespace mozilla {
 namespace dom {
 
 DOMWheelEvent::DOMWheelEvent(EventTarget* aOwner,
                              nsPresContext* aPresContext,
                              WheelEvent* aWheelEvent)
--- a/content/events/src/DOMWheelEvent.h
+++ b/content/events/src/DOMWheelEvent.h
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_DOMWheelEvent_h__
 #define mozilla_dom_DOMWheelEvent_h__
 
 #include "nsIDOMWheelEvent.h"
 #include "nsDOMMouseEvent.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/dom/WheelEventBinding.h"
 
 namespace mozilla {
 namespace dom {
 
 class DOMWheelEvent : public nsDOMMouseEvent,
                       public nsIDOMWheelEvent
 {
--- a/content/events/src/TextComposition.cpp
+++ b/content/events/src/TextComposition.cpp
@@ -3,21 +3,22 @@
 /* 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 "TextComposition.h"
 #include "nsContentEventHandler.h"
 #include "nsContentUtils.h"
 #include "nsEventDispatcher.h"
-#include "nsGUIEvent.h"
 #include "nsIContent.h"
 #include "nsIMEStateManager.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
+#include "mozilla/MiscEvents.h"
+#include "mozilla/TextEvents.h"
 
 namespace mozilla {
 
 /******************************************************************************
  * TextComposition
  ******************************************************************************/
 
 TextComposition::TextComposition(nsPresContext* aPresContext,
--- a/content/events/src/nsAsyncDOMEvent.cpp
+++ b/content/events/src/nsAsyncDOMEvent.cpp
@@ -2,18 +2,18 @@
 /* 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 "nsAsyncDOMEvent.h"
 #include "nsIDOMEvent.h"
 #include "nsContentUtils.h"
 #include "nsEventDispatcher.h"
-#include "nsGUIEvent.h"
 #include "nsDOMEvent.h"
+#include "mozilla/BasicEvents.h"
 #include "mozilla/dom/EventTarget.h"
 
 using namespace mozilla::dom;
 
 nsAsyncDOMEvent::nsAsyncDOMEvent(nsINode *aEventNode, nsEvent &aEvent)
   : mEventNode(aEventNode), mDispatchChromeOnly(false)
 {
   MOZ_ASSERT(mEventNode);
--- a/content/events/src/nsContentEventHandler.cpp
+++ b/content/events/src/nsContentEventHandler.cpp
@@ -6,17 +6,16 @@
 
 #include "nsContentEventHandler.h"
 #include "nsCOMPtr.h"
 #include "nsPresContext.h"
 #include "nsIPresShell.h"
 #include "nsISelection.h"
 #include "nsIDOMRange.h"
 #include "nsRange.h"
-#include "nsGUIEvent.h"
 #include "nsCaret.h"
 #include "nsCopySupport.h"
 #include "nsFrameSelection.h"
 #include "nsIFrame.h"
 #include "nsView.h"
 #include "nsIContentIterator.h"
 #include "nsTextFragment.h"
 #include "nsTextFrame.h"
--- a/content/events/src/nsDOMAnimationEvent.cpp
+++ b/content/events/src/nsDOMAnimationEvent.cpp
@@ -1,16 +1,16 @@
 /* vim: set shiftwidth=2 tabstop=8 autoindent cindent expandtab: */
 /* 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 "nsDOMAnimationEvent.h"
-#include "nsGUIEvent.h"
 #include "prtime.h"
+#include "mozilla/ContentEvents.h"
 
 nsDOMAnimationEvent::nsDOMAnimationEvent(mozilla::dom::EventTarget* aOwner,
                                          nsPresContext *aPresContext,
                                          nsAnimationEvent *aEvent)
   : nsDOMEvent(aOwner, aPresContext,
                aEvent ? aEvent : new nsAnimationEvent(false, 0,
                                                       EmptyString(),
                                                       0.0,
--- a/content/events/src/nsDOMAnimationEvent.h
+++ b/content/events/src/nsDOMAnimationEvent.h
@@ -2,16 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsDOMAnimationEvent_h_
 #define nsDOMAnimationEvent_h_
 
 #include "nsDOMEvent.h"
 #include "nsIDOMAnimationEvent.h"
+#include "mozilla/ContentEvents.h"
 #include "mozilla/dom/AnimationEventBinding.h"
 
 class nsAString;
 
 class nsDOMAnimationEvent : public nsDOMEvent,
                             public nsIDOMAnimationEvent
 {
 public:
--- a/content/events/src/nsDOMClipboardEvent.cpp
+++ b/content/events/src/nsDOMClipboardEvent.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMClipboardEvent.h"
 #include "nsDOMDataTransfer.h"
 #include "nsIClipboard.h"
+#include "mozilla/ContentEvents.h"
 
 nsDOMClipboardEvent::nsDOMClipboardEvent(mozilla::dom::EventTarget* aOwner,
                                          nsPresContext* aPresContext,
                                          nsClipboardEvent* aEvent)
   : nsDOMEvent(aOwner, aPresContext, aEvent ? aEvent :
                new nsClipboardEvent(false, 0))
 {
   if (aEvent) {
--- a/content/events/src/nsDOMClipboardEvent.h
+++ b/content/events/src/nsDOMClipboardEvent.h
@@ -3,16 +3,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsDOMClipboardEvent_h_
 #define nsDOMClipboardEvent_h_
 
 #include "nsIDOMClipboardEvent.h"
 #include "nsDOMEvent.h"
+#include "mozilla/EventForwards.h"
 #include "mozilla/dom/ClipboardEventBinding.h"
 
 class nsDOMClipboardEvent : public nsDOMEvent,
                             public nsIDOMClipboardEvent
 {
 public:
   nsDOMClipboardEvent(mozilla::dom::EventTarget* aOwner,
                       nsPresContext* aPresContext,
--- a/content/events/src/nsDOMCommandEvent.cpp
+++ b/content/events/src/nsDOMCommandEvent.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMCommandEvent.h"
 #include "prtime.h"
+#include "mozilla/MiscEvents.h"
 
 nsDOMCommandEvent::nsDOMCommandEvent(mozilla::dom::EventTarget* aOwner,
                                      nsPresContext* aPresContext,
                                      nsCommandEvent* aEvent)
   : nsDOMEvent(aOwner, aPresContext, aEvent ? aEvent :
                new nsCommandEvent(false, nullptr, nullptr, nullptr))
 {
   mEvent->time = PR_Now();
--- a/content/events/src/nsDOMCommandEvent.h
+++ b/content/events/src/nsDOMCommandEvent.h
@@ -4,16 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsDOMCommandEvent_h__
 #define nsDOMCommandEvent_h__
 
 #include "nsIDOMCommandEvent.h"
 #include "nsDOMEvent.h"
 #include "mozilla/dom/CommandEventBinding.h"
+#include "mozilla/EventForwards.h"
 
 class nsDOMCommandEvent : public nsDOMEvent,
                           public nsIDOMCommandEvent
 {
 public:
   nsDOMCommandEvent(mozilla::dom::EventTarget* aOwner,
                     nsPresContext* aPresContext,
                     nsCommandEvent* aEvent);
--- a/content/events/src/nsDOMCompositionEvent.cpp
+++ b/content/events/src/nsDOMCompositionEvent.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 et sw=2 tw=80: */
 /* 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 "nsDOMCompositionEvent.h"
 #include "prtime.h"
+#include "mozilla/TextEvents.h"
 
 nsDOMCompositionEvent::nsDOMCompositionEvent(mozilla::dom::EventTarget* aOwner,
                                              nsPresContext* aPresContext,
                                              nsCompositionEvent* aEvent)
   : nsDOMUIEvent(aOwner, aPresContext, aEvent ? aEvent :
                  new nsCompositionEvent(false, 0, nullptr))
 {
   NS_ASSERTION(mEvent->eventStructType == NS_COMPOSITION_EVENT,
--- a/content/events/src/nsDOMCompositionEvent.h
+++ b/content/events/src/nsDOMCompositionEvent.h
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsDOMCompositionEvent_h__
 #define nsDOMCompositionEvent_h__
 
 #include "nsDOMUIEvent.h"
 #include "nsIDOMCompositionEvent.h"
 #include "mozilla/dom/CompositionEventBinding.h"
+#include "mozilla/TextEvents.h"
 
 class nsDOMCompositionEvent : public nsDOMUIEvent,
                               public nsIDOMCompositionEvent
 {
 public:
   nsDOMCompositionEvent(mozilla::dom::EventTarget* aOwner,
                         nsPresContext* aPresContext,
                         nsCompositionEvent* aEvent);
--- a/content/events/src/nsDOMDataTransfer.cpp
+++ b/content/events/src/nsDOMDataTransfer.cpp
@@ -1,24 +1,24 @@
 /* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "mozilla/BasicEvents.h"
 #include "mozilla/Util.h"
 
 #include "nsDOMDataTransfer.h"
 
 #include "nsIDOMDocument.h"
 #include "nsIVariant.h"
 #include "nsISupportsPrimitives.h"
 #include "nsDOMClassInfoID.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsDOMLists.h"
-#include "nsGUIEvent.h"
 #include "nsError.h"
 #include "nsIDragService.h"
 #include "nsIClipboard.h"
 #include "nsContentUtils.h"
 #include "nsIContent.h"
 #include "nsCRT.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsIScriptContext.h"
--- a/content/events/src/nsDOMDragEvent.cpp
+++ b/content/events/src/nsDOMDragEvent.cpp
@@ -1,18 +1,18 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMDragEvent.h"
-#include "nsGUIEvent.h"
 #include "nsContentUtils.h"
 #include "nsIDOMDataTransfer.h"
 #include "prtime.h"
+#include "mozilla/MouseEvents.h"
 
 nsDOMDragEvent::nsDOMDragEvent(mozilla::dom::EventTarget* aOwner,
                                nsPresContext* aPresContext,
                                nsInputEvent* aEvent)
   : nsDOMMouseEvent(aOwner, aPresContext, aEvent ? aEvent :
                     new nsDragEvent(false, 0, nullptr))
 {
   if (aEvent) {
--- a/content/events/src/nsDOMDragEvent.h
+++ b/content/events/src/nsDOMDragEvent.h
@@ -4,16 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsDOMDragEvent_h__
 #define nsDOMDragEvent_h__
 
 #include "nsIDOMDragEvent.h"
 #include "nsDOMMouseEvent.h"
 #include "mozilla/dom/DragEventBinding.h"
+#include "mozilla/EventForwards.h"
 
 class nsDOMDragEvent : public nsDOMMouseEvent,
                        public nsIDOMDragEvent
 {
 public:
   nsDOMDragEvent(mozilla::dom::EventTarget* aOwner,
                  nsPresContext* aPresContext, nsInputEvent* aEvent);
   virtual ~nsDOMDragEvent();
--- a/content/events/src/nsDOMEvent.cpp
+++ b/content/events/src/nsDOMEvent.cpp
@@ -9,17 +9,22 @@
 #include "nsCOMPtr.h"
 #include "nsError.h"
 #include "nsDOMEvent.h"
 #include "nsEventStateManager.h"
 #include "nsIFrame.h"
 #include "nsIContent.h"
 #include "nsIPresShell.h"
 #include "nsIDocument.h"
+#include "mozilla/ContentEvents.h"
+#include "mozilla/MiscEvents.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/MutationEvent.h"
+#include "mozilla/TextEvents.h"
+#include "mozilla/TouchEvents.h"
 #include "nsContentUtils.h"
 #include "nsJSEnvironment.h"
 #include "mozilla/Preferences.h"
 #include "nsLayoutUtils.h"
 #include "nsIScrollableFrame.h"
 #include "nsDOMEventTargetHelper.h"
 #include "nsPIWindowRoot.h"
 #include "nsGlobalWindow.h"
--- a/content/events/src/nsDOMEvent.h
+++ b/content/events/src/nsDOMEvent.h
@@ -2,22 +2,22 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsDOMEvent_h__
 #define nsDOMEvent_h__
 
 #include "mozilla/Attributes.h"
+#include "mozilla/BasicEvents.h"
 #include "nsIDOMEvent.h"
 #include "nsISupports.h"
 #include "nsCOMPtr.h"
 #include "nsPIDOMWindow.h"
 #include "nsPoint.h"
-#include "nsGUIEvent.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsAutoPtr.h"
 #include "mozilla/dom/EventBinding.h"
 #include "nsIScriptGlobalObject.h"
 #include "Units.h"
 #include "js/TypeDecls.h"
 
 class nsIContent;
--- a/content/events/src/nsDOMFocusEvent.cpp
+++ b/content/events/src/nsDOMFocusEvent.cpp
@@ -1,15 +1,16 @@
 /* vim: set shiftwidth=2 tabstop=8 autoindent cindent expandtab: */
 /* 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 "nsDOMFocusEvent.h"
 #include "prtime.h"
+#include "mozilla/ContentEvents.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 NS_IMPL_ISUPPORTS_INHERITED1(nsDOMFocusEvent, nsDOMUIEvent, nsIDOMFocusEvent)
 
 nsDOMFocusEvent::nsDOMFocusEvent(mozilla::dom::EventTarget* aOwner,
                                  nsPresContext* aPresContext, nsFocusEvent* aEvent)
--- a/content/events/src/nsDOMFocusEvent.h
+++ b/content/events/src/nsDOMFocusEvent.h
@@ -2,16 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsDOMFocusEvent_h_
 #define nsDOMFocusEvent_h_
 
 #include "nsDOMUIEvent.h"
 #include "nsIDOMFocusEvent.h"
+#include "mozilla/EventForwards.h"
 #include "mozilla/dom/FocusEventBinding.h"
 
 class nsDOMFocusEvent : public nsDOMUIEvent,
                         public nsIDOMFocusEvent
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMFOCUSEVENT
--- a/content/events/src/nsDOMKeyboardEvent.cpp
+++ b/content/events/src/nsDOMKeyboardEvent.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMKeyboardEvent.h"
 #include "prtime.h"
+#include "mozilla/TextEvents.h"
 
 nsDOMKeyboardEvent::nsDOMKeyboardEvent(mozilla::dom::EventTarget* aOwner,
                                        nsPresContext* aPresContext,
                                        nsKeyEvent* aEvent)
   : nsDOMUIEvent(aOwner, aPresContext, aEvent ? aEvent :
                  new nsKeyEvent(false, 0, nullptr))
 {
   NS_ASSERTION(mEvent->eventStructType == NS_KEY_EVENT, "event type mismatch");
--- a/content/events/src/nsDOMKeyboardEvent.h
+++ b/content/events/src/nsDOMKeyboardEvent.h
@@ -3,17 +3,19 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsDOMKeyboardEvent_h__
 #define nsDOMKeyboardEvent_h__
 
 #include "nsIDOMKeyEvent.h"
 #include "nsDOMUIEvent.h"
+#include "mozilla/EventForwards.h"
 #include "mozilla/dom/KeyboardEventBinding.h"
+#include "mozilla/TextEvents.h"
 
 class nsDOMKeyboardEvent : public nsDOMUIEvent,
                            public nsIDOMKeyEvent
 {
 public:
   nsDOMKeyboardEvent(mozilla::dom::EventTarget* aOwner,
                      nsPresContext* aPresContext, nsKeyEvent* aEvent);
   virtual ~nsDOMKeyboardEvent();
--- a/content/events/src/nsDOMMouseEvent.cpp
+++ b/content/events/src/nsDOMMouseEvent.cpp
@@ -1,18 +1,18 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMMouseEvent.h"
-#include "nsGUIEvent.h"
 #include "nsIContent.h"
 #include "nsContentUtils.h"
 #include "prtime.h"
+#include "mozilla/MouseEvents.h"
 
 using namespace mozilla;
 
 nsDOMMouseEvent::nsDOMMouseEvent(mozilla::dom::EventTarget* aOwner,
                                  nsPresContext* aPresContext,
                                  nsInputEvent* aEvent)
   : nsDOMUIEvent(aOwner, aPresContext, aEvent ? aEvent :
                  new nsMouseEvent(false, 0, nullptr,
--- a/content/events/src/nsDOMMouseEvent.h
+++ b/content/events/src/nsDOMMouseEvent.h
@@ -4,16 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsDOMMouseEvent_h__
 #define nsDOMMouseEvent_h__
 
 #include "nsIDOMMouseEvent.h"
 #include "nsDOMUIEvent.h"
 #include "mozilla/dom/MouseEventBinding.h"
+#include "mozilla/MouseEvents.h"
 
 class nsDOMMouseEvent : public nsDOMUIEvent,
                         public nsIDOMMouseEvent
 {
 public:
   nsDOMMouseEvent(mozilla::dom::EventTarget* aOwner,
                   nsPresContext* aPresContext, nsInputEvent* aEvent);
   virtual ~nsDOMMouseEvent();
--- a/content/events/src/nsDOMMouseScrollEvent.cpp
+++ b/content/events/src/nsDOMMouseScrollEvent.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMMouseScrollEvent.h"
 #include "prtime.h"
+#include "mozilla/MouseEvents.h"
 
 nsDOMMouseScrollEvent::nsDOMMouseScrollEvent(mozilla::dom::EventTarget* aOwner,
                                              nsPresContext* aPresContext,
                                              nsInputEvent* aEvent)
   : nsDOMMouseEvent(aOwner, aPresContext,
                     aEvent ? aEvent : new nsMouseScrollEvent(false, 0, nullptr))
 {
   if (aEvent) {
--- a/content/events/src/nsDOMScrollAreaEvent.cpp
+++ b/content/events/src/nsDOMScrollAreaEvent.cpp
@@ -1,18 +1,18 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "base/basictypes.h"
 #include "ipc/IPCMessageUtils.h"
+#include "mozilla/ContentEvents.h"
 
 #include "nsDOMScrollAreaEvent.h"
-#include "nsGUIEvent.h"
 #include "nsClientRect.h"
 
 nsDOMScrollAreaEvent::nsDOMScrollAreaEvent(mozilla::dom::EventTarget* aOwner,
                                            nsPresContext *aPresContext,
                                            nsScrollAreaEvent *aEvent)
   : nsDOMUIEvent(aOwner, aPresContext, aEvent)
   , mClientArea(nullptr)
 {
--- a/content/events/src/nsDOMScrollAreaEvent.h
+++ b/content/events/src/nsDOMScrollAreaEvent.h
@@ -2,16 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsDOMScrollAreaEvent_h__
 #define nsDOMScrollAreaEvent_h__
 
 #include "mozilla/Attributes.h"
+#include "mozilla/EventForwards.h"
 #include "nsIDOMScrollAreaEvent.h"
 #include "nsDOMUIEvent.h"
 
 #include "nsClientRect.h"
 #include "mozilla/dom/ScrollAreaEventBinding.h"
 
 class nsDOMScrollAreaEvent : public nsDOMUIEvent,
                              public nsIDOMScrollAreaEvent
--- a/content/events/src/nsDOMSimpleGestureEvent.cpp
+++ b/content/events/src/nsDOMSimpleGestureEvent.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMSimpleGestureEvent.h"
 #include "prtime.h"
+#include "mozilla/TouchEvents.h"
 
 nsDOMSimpleGestureEvent::nsDOMSimpleGestureEvent(mozilla::dom::EventTarget* aOwner,
                                                  nsPresContext* aPresContext,
                                                  nsSimpleGestureEvent* aEvent)
   : nsDOMMouseEvent(aOwner, aPresContext,
                     aEvent ? aEvent : new nsSimpleGestureEvent(false, 0, nullptr, 0, 0.0))
 {
   NS_ASSERTION(mEvent->eventStructType == NS_SIMPLE_GESTURE_EVENT, "event type mismatch");
--- a/content/events/src/nsDOMSimpleGestureEvent.h
+++ b/content/events/src/nsDOMSimpleGestureEvent.h
@@ -2,16 +2,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsDOMSimpleGestureEvent_h__
 #define nsDOMSimpleGestureEvent_h__
 
 #include "nsIDOMSimpleGestureEvent.h"
 #include "nsDOMMouseEvent.h"
+#include "mozilla/TouchEvents.h"
 #include "mozilla/dom/SimpleGestureEventBinding.h"
 
 class nsPresContext;
 
 class nsDOMSimpleGestureEvent : public nsDOMMouseEvent,
                                 public nsIDOMSimpleGestureEvent
 {
 public:
--- a/content/events/src/nsDOMTextEvent.cpp
+++ b/content/events/src/nsDOMTextEvent.cpp
@@ -2,16 +2,17 @@
 /* vim: set ts=2 sw=2 et tw=78: */
 /* 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 "nsDOMTextEvent.h"
 #include "nsPrivateTextRange.h"
 #include "prtime.h"
+#include "mozilla/TextEvents.h"
 
 nsDOMTextEvent::nsDOMTextEvent(mozilla::dom::EventTarget* aOwner,
                                nsPresContext* aPresContext,
                                nsTextEvent* aEvent)
   : nsDOMUIEvent(aOwner, aPresContext,
                  aEvent ? aEvent : new nsTextEvent(false, 0, nullptr))
 {
   NS_ASSERTION(mEvent->eventStructType == NS_TEXT_EVENT, "event type mismatch");
--- a/content/events/src/nsDOMTextEvent.h
+++ b/content/events/src/nsDOMTextEvent.h
@@ -2,16 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsDOMTextEvent_h__
 #define nsDOMTextEvent_h__
 
 #include "mozilla/Attributes.h"
+#include "mozilla/EventForwards.h"
 #include "nsDOMUIEvent.h"
 #include "nsIPrivateTextEvent.h"
 #include "nsPrivateTextRange.h"
 
 class nsDOMTextEvent : public nsDOMUIEvent,
                        public nsIPrivateTextEvent
 {
 public:
--- a/content/events/src/nsDOMTouchEvent.cpp
+++ b/content/events/src/nsDOMTouchEvent.cpp
@@ -1,20 +1,20 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* 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 "nsDOMTouchEvent.h"
-#include "nsGUIEvent.h"
 #include "nsContentUtils.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/Touch.h"
 #include "mozilla/dom/TouchListBinding.h"
+#include "mozilla/TouchEvents.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 // TouchList
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMTouchList)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
--- a/content/events/src/nsDOMTouchEvent.h
+++ b/content/events/src/nsDOMTouchEvent.h
@@ -3,20 +3,22 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsDOMTouchEvent_h_
 #define nsDOMTouchEvent_h_
 
 #include "nsDOMUIEvent.h"
 #include "nsTArray.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/TouchEvents.h"
 #include "nsJSEnvironment.h"
 #include "mozilla/dom/TouchEventBinding.h"
 #include "nsWrapperCache.h"
 
+
 class nsAString;
 
 class nsDOMTouchList MOZ_FINAL : public nsISupports
                                , public nsWrapperCache
 {
   typedef mozilla::dom::Touch Touch;
 
 public:
--- a/content/events/src/nsDOMTransitionEvent.cpp
+++ b/content/events/src/nsDOMTransitionEvent.cpp
@@ -1,16 +1,16 @@
 /* vim: set shiftwidth=2 tabstop=8 autoindent cindent expandtab: */
 /* 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 "nsDOMTransitionEvent.h"
-#include "nsGUIEvent.h"
 #include "prtime.h"
+#include "mozilla/ContentEvents.h"
 
 nsDOMTransitionEvent::nsDOMTransitionEvent(mozilla::dom::EventTarget* aOwner,
                                            nsPresContext *aPresContext,
                                            nsTransitionEvent *aEvent)
   : nsDOMEvent(aOwner, aPresContext,
                aEvent ? aEvent : new nsTransitionEvent(false, 0,
                                                        EmptyString(),
                                                        0.0,
--- a/content/events/src/nsDOMTransitionEvent.h
+++ b/content/events/src/nsDOMTransitionEvent.h
@@ -2,16 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsDOMTransitionEvent_h_
 #define nsDOMTransitionEvent_h_
 
 #include "nsDOMEvent.h"
 #include "nsIDOMTransitionEvent.h"
+#include "mozilla/ContentEvents.h"
 #include "mozilla/dom/TransitionEventBinding.h"
 
 class nsAString;
 
 class nsDOMTransitionEvent : public nsDOMEvent,
                              public nsIDOMTransitionEvent
 {
 public:
--- a/content/events/src/nsDOMUIEvent.cpp
+++ b/content/events/src/nsDOMUIEvent.cpp
@@ -11,16 +11,18 @@
 #include "nsIDOMWindow.h"
 #include "nsIDOMNode.h"
 #include "nsIContent.h"
 #include "nsContentUtils.h"
 #include "nsEventStateManager.h"
 #include "nsIFrame.h"
 #include "mozilla/Util.h"
 #include "mozilla/Assertions.h"
+#include "mozilla/ContentEvents.h"
+#include "mozilla/TextEvents.h"
 #include "prtime.h"
 
 using namespace mozilla;
 
 nsDOMUIEvent::nsDOMUIEvent(mozilla::dom::EventTarget* aOwner,
                            nsPresContext* aPresContext, nsGUIEvent* aEvent)
   : nsDOMEvent(aOwner, aPresContext, aEvent ?
                static_cast<nsEvent *>(aEvent) :
--- a/content/events/src/nsEventDispatcher.cpp
+++ b/content/events/src/nsEventDispatcher.cpp
@@ -11,18 +11,23 @@
 #include "nsCxPusher.h"
 #include "nsError.h"
 #include <new>
 #include "nsINode.h"
 #include "nsPIDOMWindow.h"
 #include "nsDOMTouchEvent.h"
 #include "GeckoProfiler.h"
 #include "GeneratedEvents.h"
+#include "mozilla/ContentEvents.h"
 #include "mozilla/dom/EventTarget.h"
+#include "mozilla/MiscEvents.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/MutationEvent.h"
+#include "mozilla/TextEvents.h"
+#include "mozilla/TouchEvents.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 class ELMCreationDetector
 {
 public:
   ELMCreationDetector() :
--- a/content/events/src/nsEventListenerManager.cpp
+++ b/content/events/src/nsEventListenerManager.cpp
@@ -1,23 +1,23 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "mozilla/BasicEvents.h"
 #ifdef MOZ_B2G
 #include "mozilla/Hal.h"
 #endif
 #include "mozilla/HalSensor.h"
 
 // Microsoft's API Name hackery sucks
 #undef CreateEvent
 
 #include "nsISupports.h"
-#include "nsGUIEvent.h"
 #include "nsDOMEvent.h"
 #include "nsEventListenerManager.h"
 #include "nsIDOMEventListener.h"
 #include "nsGkAtoms.h"
 #include "nsPIDOMWindow.h"
 #include "nsIJSEventListener.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsINameSpaceManager.h"
--- a/content/events/src/nsEventListenerManager.h
+++ b/content/events/src/nsEventListenerManager.h
@@ -1,22 +1,22 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsEventListenerManager_h__
 #define nsEventListenerManager_h__
 
+#include "mozilla/BasicEvents.h"
 #include "mozilla/dom/EventListenerBinding.h"
 #include "mozilla/MemoryReporting.h"
 #include "nsCOMPtr.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsGkAtoms.h"
-#include "nsGUIEvent.h"
 #include "nsIDOMEventListener.h"
 #include "nsIJSEventListener.h"
 #include "nsTObserverArray.h"
 
 class nsIDOMEvent;
 struct EventTypeData;
 class nsEventTargetChainItem;
 class nsPIDOMWindow;
--- a/content/events/src/nsEventListenerService.cpp
+++ b/content/events/src/nsEventListenerService.cpp
@@ -4,23 +4,23 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #include "nsEventListenerService.h"
 #include "nsCOMArray.h"
 #include "nsEventListenerManager.h"
 #include "nsMemory.h"
 #include "nsCxPusher.h"
 #include "nsIXPConnect.h"
 #include "nsJSUtils.h"
-#include "nsGUIEvent.h"
 #include "nsEventDispatcher.h"
 #include "nsIJSEventListener.h"
 #ifdef MOZ_JSDEBUGGER
 #include "jsdIDebuggerService.h"
 #endif
 #include "nsDOMClassInfoID.h"
+#include "mozilla/BasicEvents.h"
 #include "mozilla/Maybe.h"
 #include "nsServiceManagerUtils.h"
 
 using namespace mozilla::dom;
 using mozilla::AutoSafeJSContext;
 
 NS_IMPL_CYCLE_COLLECTION_1(nsEventListenerInfo, mListener)
 
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -1,16 +1,20 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 sw=2 et tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/Attributes.h"
+#include "mozilla/MiscEvents.h"
 #include "mozilla/MathAlgorithms.h"
+#include "mozilla/MouseEvents.h"
+#include "mozilla/TextEvents.h"
+#include "mozilla/TouchEvents.h"
 #include "mozilla/dom/TabParent.h"
 
 #include "nsCOMPtr.h"
 #include "nsEventStateManager.h"
 #include "nsIMEStateManager.h"
 #include "nsContentEventHandler.h"
 #include "nsIContent.h"
 #include "nsINodeInfo.h"
--- a/content/events/src/nsEventStateManager.h
+++ b/content/events/src/nsEventStateManager.h
@@ -1,19 +1,20 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsEventStateManager_h__
 #define nsEventStateManager_h__
 
+#include "mozilla/BasicEvents.h"
+#include "mozilla/EventForwards.h"
 #include "mozilla/TypedEnum.h"
 
-#include "nsGUIEvent.h"
 #include "nsIObserver.h"
 #include "nsWeakReference.h"
 #include "nsCOMPtr.h"
 #include "nsCOMArray.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsFocusManager.h"
 #include "mozilla/TimeStamp.h"
 #include "nsIFrame.h"
--- a/content/events/src/nsIMEStateManager.cpp
+++ b/content/events/src/nsIMEStateManager.cpp
@@ -24,20 +24,20 @@
 #include "nsIMutationObserver.h"
 #include "nsContentEventHandler.h"
 #include "nsIObserverService.h"
 #include "mozilla/Services.h"
 #include "nsIFormControl.h"
 #include "nsIForm.h"
 #include "mozilla/dom/HTMLFormElement.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/TextEvents.h"
 #include "TextComposition.h"
 #include "mozilla/Preferences.h"
 #include "nsAsyncDOMEvent.h"
-#include "nsGUIEvent.h"
 
 using namespace mozilla;
 using namespace mozilla::widget;
 
 // nsTextStateManager notifies widget of any text and selection changes
 //  in the currently focused editor
 // sTextStateObserver points to the currently active nsTextStateManager
 // sTextStateObserver is null if there is no focused editor
--- a/content/events/src/nsPrivateTextRange.cpp
+++ b/content/events/src/nsPrivateTextRange.cpp
@@ -1,15 +1,15 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsPrivateTextRange.h"
-
+#include "mozilla/TextEvents.h"
 
 nsPrivateTextRange::nsPrivateTextRange(const nsTextRange &aTextRange)
   : mRangeStart(uint16_t(aTextRange.mStartOffset)),
     mRangeEnd(uint16_t(aTextRange.mEndOffset)),
     mRangeType(uint16_t(aTextRange.mRangeType)),
     mRangeStyle(aTextRange.mRangeStyle)
 {
 }
--- a/content/html/content/src/HTMLButtonElement.cpp
+++ b/content/html/content/src/HTMLButtonElement.cpp
@@ -17,17 +17,19 @@
 #include "nsFormSubmission.h"
 #include "nsFormSubmissionConstants.h"
 #include "nsIURL.h"
 #include "nsEventStateManager.h"
 #include "nsIFrame.h"
 #include "nsIFormControlFrame.h"
 #include "nsIDOMEvent.h"
 #include "nsIDocument.h"
-#include "nsGUIEvent.h"
+#include "mozilla/ContentEvents.h"
+#include "mozilla/MouseEvents.h"
+#include "mozilla/TextEvents.h"
 #include "nsUnicharUtils.h"
 #include "nsLayoutUtils.h"
 #include "nsEventDispatcher.h"
 #include "nsPresState.h"
 #include "nsError.h"
 #include "nsFocusManager.h"
 #include "mozilla/dom/HTMLFormElement.h"
 #include "mozAutoDocUpdate.h"
--- a/content/html/content/src/HTMLFieldSetElement.cpp
+++ b/content/html/content/src/HTMLFieldSetElement.cpp
@@ -1,18 +1,18 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "mozilla/BasicEvents.h"
 #include "mozilla/dom/HTMLFieldSetElement.h"
 #include "mozilla/dom/HTMLFieldSetElementBinding.h"
 #include "nsContentList.h"
 #include "nsEventDispatcher.h"
-#include "nsGUIEvent.h"
 
 NS_IMPL_NS_NEW_HTML_ELEMENT(FieldSet)
 
 namespace mozilla {
 namespace dom {
 
 HTMLFieldSetElement::HTMLFieldSetElement(already_AddRefed<nsINodeInfo> aNodeInfo)
   : nsGenericHTMLFormElement(aNodeInfo)
--- a/content/html/content/src/HTMLFormElement.cpp
+++ b/content/html/content/src/HTMLFormElement.cpp
@@ -1,28 +1,28 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "mozilla/ContentEvents.h"
 #include "mozilla/dom/HTMLFormElement.h"
 #include "mozilla/dom/HTMLFormElementBinding.h"
 #include "nsIHTMLDocument.h"
 #include "nsEventStateManager.h"
 #include "nsEventStates.h"
 #include "nsGkAtoms.h"
 #include "nsStyleConsts.h"
 #include "nsPresContext.h"
 #include "nsIDocument.h"
 #include "nsIFormControlFrame.h"
 #include "nsError.h"
 #include "nsContentUtils.h"
 #include "nsInterfaceHashtable.h"
 #include "nsContentList.h"
-#include "nsGUIEvent.h"
 #include "nsCOMArray.h"
 #include "nsAutoPtr.h"
 #include "nsTArray.h"
 #include "nsIMutableArray.h"
 
 // form submission
 #include "nsIFormSubmitObserver.h"
 #include "nsIObserverService.h"
--- a/content/html/content/src/HTMLImageElement.cpp
+++ b/content/html/content/src/HTMLImageElement.cpp
@@ -17,17 +17,17 @@
 #include "nsIScriptContext.h"
 #include "nsIURL.h"
 #include "nsIIOService.h"
 #include "nsIServiceManager.h"
 #include "nsNetUtil.h"
 #include "nsContentUtils.h"
 #include "nsIFrame.h"
 #include "nsNodeInfoManager.h"
-#include "nsGUIEvent.h"
+#include "mozilla/MouseEvents.h"
 #include "nsContentPolicyUtils.h"
 #include "nsIDOMWindow.h"
 #include "nsFocusManager.h"
 #include "mozilla/dom/HTMLFormElement.h"
 
 #include "imgIContainer.h"
 #include "imgILoader.h"
 #include "imgINotificationObserver.h"
--- a/content/html/content/src/HTMLInputElement.cpp
+++ b/content/html/content/src/HTMLInputElement.cpp
@@ -37,33 +37,35 @@
 #include "nsIFormControlFrame.h"
 #include "nsITextControlFrame.h"
 #include "nsIFrame.h"
 #include "nsRangeFrame.h"
 #include "nsEventStates.h"
 #include "nsIServiceManager.h"
 #include "nsError.h"
 #include "nsIEditor.h"
-#include "nsGUIEvent.h"
 #include "nsIIOService.h"
 #include "nsDocument.h"
 #include "nsAttrValueOrString.h"
 
 #include "nsPresState.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMNodeList.h"
 #include "nsIDOMHTMLCollection.h"
 #include "nsLinebreakConverter.h" //to strip out carriage returns
 #include "nsReadableUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsEventDispatcher.h"
 #include "nsLayoutUtils.h"
 
 #include "nsIDOMMutationEvent.h"
+#include "mozilla/ContentEvents.h"
 #include "mozilla/MutationEvent.h"
+#include "mozilla/TextEvents.h"
+#include "mozilla/TouchEvents.h"
 #include "nsEventListenerManager.h"
 
 #include "nsRuleData.h"
 #include <algorithm>
 
 // input type=radio
 #include "nsIRadioGroupContainer.h"
 
--- a/content/html/content/src/HTMLLabelElement.cpp
+++ b/content/html/content/src/HTMLLabelElement.cpp
@@ -5,17 +5,17 @@
 
 /**
  * Implementation of HTML <label> elements.
  */
 #include "HTMLLabelElement.h"
 #include "mozilla/dom/HTMLLabelElementBinding.h"
 #include "nsEventDispatcher.h"
 #include "nsFocusManager.h"
-#include "nsGUIEvent.h"
+#include "mozilla/MouseEvents.h"
 #include "nsIDOMMouseEvent.h"
 
 // construction, destruction
 
 NS_IMPL_NS_NEW_HTML_ELEMENT(Label)
 
 namespace mozilla {
 namespace dom {
--- a/content/html/content/src/HTMLMenuElement.cpp
+++ b/content/html/content/src/HTMLMenuElement.cpp
@@ -1,21 +1,21 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/dom/HTMLMenuElement.h"
 
+#include "mozilla/BasicEvents.h"
 #include "mozilla/dom/HTMLMenuElementBinding.h"
 #include "mozilla/dom/HTMLMenuItemElement.h"
 #include "nsAttrValueInlines.h"
 #include "nsContentUtils.h"
 #include "nsEventDispatcher.h"
-#include "nsGUIEvent.h"
 #include "nsXULContextMenuBuilder.h"
 #include "nsIURI.h"
 
 NS_IMPL_NS_NEW_HTML_ELEMENT(Menu)
 
 namespace mozilla {
 namespace dom {
 
--- a/content/html/content/src/HTMLMenuItemElement.cpp
+++ b/content/html/content/src/HTMLMenuItemElement.cpp
@@ -1,20 +1,20 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/dom/HTMLMenuItemElement.h"
 
+#include "mozilla/BasicEvents.h"
 #include "mozilla/dom/HTMLMenuItemElementBinding.h"
 #include "nsAttrValueInlines.h"
 #include "nsContentUtils.h"
 #include "nsEventDispatcher.h"
-#include "nsGUIEvent.h"
 
 
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(MenuItem)
 
 namespace mozilla {
 namespace dom {
 
 // First bits are needed for the menuitem type.
--- a/content/html/content/src/HTMLOptionsCollection.cpp
+++ b/content/html/content/src/HTMLOptionsCollection.cpp
@@ -14,17 +14,16 @@
 #include "mozilla/dom/HTMLSelectElement.h"
 #include "mozilla/Util.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsError.h"
 #include "nsEventDispatcher.h"
 #include "nsEventStates.h"
 #include "nsFormSubmission.h"
 #include "nsGkAtoms.h"
-#include "nsGUIEvent.h"
 #include "nsIComboboxControlFrame.h"
 #include "nsIDocument.h"
 #include "nsIDOMHTMLOptGroupElement.h"
 #include "nsIFormControlFrame.h"
 #include "nsIForm.h"
 #include "nsIFormProcessor.h"
 #include "nsIListControlFrame.h"
 #include "nsLayoutUtils.h"
--- a/content/html/content/src/HTMLSelectElement.cpp
+++ b/content/html/content/src/HTMLSelectElement.cpp
@@ -14,17 +14,16 @@
 #include "mozilla/Util.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsContentList.h"
 #include "nsError.h"
 #include "nsEventDispatcher.h"
 #include "nsEventStates.h"
 #include "nsFormSubmission.h"
 #include "nsGkAtoms.h"
-#include "nsGUIEvent.h"
 #include "nsIComboboxControlFrame.h"
 #include "nsIDocument.h"
 #include "nsIFormControlFrame.h"
 #include "nsIForm.h"
 #include "nsIFormProcessor.h"
 #include "nsIFrame.h"
 #include "nsIListControlFrame.h"
 #include "nsISelectControlFrame.h"
--- a/content/html/content/src/HTMLTextAreaElement.cpp
+++ b/content/html/content/src/HTMLTextAreaElement.cpp
@@ -4,25 +4,25 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/dom/HTMLTextAreaElement.h"
 
 #include "mozAutoDocUpdate.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/dom/HTMLTextAreaElementBinding.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/Util.h"
 #include "nsAttrValueInlines.h"
 #include "nsContentCID.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsError.h"
 #include "nsEventDispatcher.h"
 #include "nsFocusManager.h"
 #include "nsFormSubmission.h"
-#include "nsGUIEvent.h"
 #include "nsIComponentManager.h"
 #include "nsIConstraintValidation.h"
 #include "nsIControllers.h"
 #include "nsIDocument.h"
 #include "nsIDOMHTMLFormElement.h"
 #include "nsIFormControlFrame.h"
 #include "nsIFormControl.h"
 #include "nsIForm.h"
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -1,14 +1,15 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set tw=80 expandtab softtabstop=2 ts=2 sw=2: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "mozilla/MouseEvents.h"
 #include "mozilla/Util.h"
 #include "mozilla/Likely.h"
 
 #include "nscore.h"
 #include "nsGenericHTMLElement.h"
 #include "nsAttrValueInlines.h"
 #include "nsCOMPtr.h"
 #include "nsIAtom.h"
--- a/content/html/content/src/nsTextEditorState.cpp
+++ b/content/html/content/src/nsTextEditorState.cpp
@@ -37,16 +37,17 @@
 #include "nsTextEditRules.h"
 #include "mozilla/Selection.h"
 #include "nsEventListenerManager.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "mozilla/Preferences.h"
 #include "nsTextNode.h"
 #include "nsIController.h"
+#include "mozilla/TextEvents.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 static NS_DEFINE_CID(kTextEditorCID, NS_TEXTEDITOR_CID);
 
 static nsINativeKeyBindings *sNativeInputBindings = nullptr;
 static nsINativeKeyBindings *sNativeTextAreaBindings = nullptr;
--- a/content/media/AudioStream.cpp
+++ b/content/media/AudioStream.cpp
@@ -900,18 +900,18 @@ BufferedAudioStream::DataCallback(void* 
   }
 
   WriteDumpFile(mDumpFile, this, aFrames, aBuffer);
   if (PR_LOG_TEST(GetLatencyLog(), PR_LOG_DEBUG)) {
     uint32_t latency = UINT32_MAX;
     if (cubeb_stream_get_latency(mCubebStream, &latency)) {
       NS_WARNING("Could not get latency from cubeb.");
     }
-    LogLatency(AsyncLatencyLogger::AudioStream, 0, (mBuffer.Length() * 1000) / mOutRate);
-    LogLatency(AsyncLatencyLogger::Cubeb, 0, (latency * 1000) / mOutRate);
+    mLatencyLog->Log(AsyncLatencyLogger::AudioStream, 0, (mBuffer.Length() * 1000) / mOutRate);
+    mLatencyLog->Log(AsyncLatencyLogger::Cubeb, 0, (latency * 1000) / mOutRate);
   }
 
   mAudioClock.UpdateWritePosition(servicedFrames);
   return servicedFrames;
 }
 
 void
 BufferedAudioStream::StateCallback(cubeb_state aState)
--- a/content/media/AudioStream.h
+++ b/content/media/AudioStream.h
@@ -4,16 +4,18 @@
  * 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 !defined(AudioStream_h_)
 #define AudioStream_h_
 
 #include "AudioSampleFormat.h"
 #include "AudioChannelCommon.h"
 #include "nsAutoPtr.h"
+#include "nsCOMPtr.h"
+#include "Latency.h"
 
 namespace soundtouch {
 class SoundTouch;
 }
 
 namespace mozilla {
 
 class AudioStream;
@@ -180,13 +182,14 @@ protected:
   int mInRate;
   // Output rate in Hz (characteristic of the playback rate)
   int mOutRate;
   int mChannels;
   // Number of frames written to the buffers.
   int64_t mWritten;
   AudioClock mAudioClock;
   nsAutoPtr<soundtouch::SoundTouch> mTimeStretcher;
+  nsRefPtr<AsyncLatencyLogger> mLatencyLog;
 };
 
 } // namespace mozilla
 
 #endif
--- a/content/media/Latency.cpp
+++ b/content/media/Latency.cpp
@@ -8,17 +8,19 @@
 #define FORCE_PR_LOG
 
 #include "Latency.h"
 #include "nsThreadUtils.h"
 #include <prlog.h>
 #include <cmath>
 #include <algorithm>
 
+#include <mozilla/Services.h>
 #include <mozilla/StaticPtr.h>
+#include "nsContentUtils.h"
 
 using namespace mozilla;
 
 const char* LatencyLogIndex2Strings[] = {
   "Audio MediaStreamTrack",
   "Video MediaStreamTrack",
   "Cubeb",
   "AudioStream",
@@ -54,67 +56,94 @@ public:
   }
 
 protected:
   AsyncLatencyLogger::LatencyLogIndex mIndex;
   uint64_t mID;
   int64_t mValue;
 };
 
-// This is the only function that clients should use.
 void LogLatency(AsyncLatencyLogger::LatencyLogIndex aIndex, uint64_t aID, int64_t aValue)
 {
   AsyncLatencyLogger::Get()->Log(aIndex, aID, aValue);
 }
 
+/* static */
 void AsyncLatencyLogger::InitializeStatics()
 {
   NS_ASSERTION(NS_IsMainThread(), "Main thread only");
   GetLatencyLog();
   gAsyncLogger = new AsyncLatencyLogger();
 }
 
-void AsyncLatencyLogger::Shutdown()
+/* static */
+void AsyncLatencyLogger::ShutdownLogger()
 {
   gAsyncLogger = nullptr;
 }
 
 /* static */
 AsyncLatencyLogger* AsyncLatencyLogger::Get(bool aStartTimer)
 {
+  // Users don't generally null-check the result since we should live longer than they
+  MOZ_ASSERT(gAsyncLogger);
+
   if (aStartTimer) {
     gAsyncLogger->Init();
   }
   return gAsyncLogger;
 }
 
+NS_IMPL_ISUPPORTS1(AsyncLatencyLogger, nsIObserver)
+
 AsyncLatencyLogger::AsyncLatencyLogger()
   : mThread(nullptr),
     mMutex("AsyncLatencyLogger")
-{ }
+{
+  NS_ASSERTION(NS_IsMainThread(), "Main thread only");
+  nsContentUtils::RegisterShutdownObserver(this);
+}
 
 AsyncLatencyLogger::~AsyncLatencyLogger()
 {
+  AsyncLatencyLogger::Shutdown();
+}
+
+void AsyncLatencyLogger::Shutdown()
+{
+  nsContentUtils::UnregisterShutdownObserver(this);
+
   MutexAutoLock lock(mMutex);
   if (mThread) {
     mThread->Shutdown();
   }
-  mStart = TimeStamp();
+  mStart = TimeStamp(); // make sure we don't try to restart it for any reason
 }
 
 void AsyncLatencyLogger::Init()
 {
   MutexAutoLock lock(mMutex);
   if (mStart.IsNull()) {
-    mStart = TimeStamp::Now();
     nsresult rv = NS_NewNamedThread("Latency Logger", getter_AddRefs(mThread));
     NS_ENSURE_SUCCESS_VOID(rv);
+    mStart = TimeStamp::Now();
   }
 }
 
+nsresult
+AsyncLatencyLogger::Observe(nsISupports* aSubject, const char* aTopic,
+                            const PRUnichar* aData)
+{
+  MOZ_ASSERT(NS_IsMainThread());
+  if (strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0) {
+    Shutdown();
+  }
+  return NS_OK;
+}
+
 // aID is a sub-identifier (in particular a specific MediaStramTrack)
 void AsyncLatencyLogger::WriteLog(LatencyLogIndex aIndex, uint64_t aID, int64_t aValue)
 {
   PR_LOG(GetLatencyLog(), PR_LOG_DEBUG,
          ("%s,%llu,%lld.,%lld.",
           LatencyLogIndex2Strings[aIndex], aID, GetTimeStamp(), aValue));
 }
 
@@ -128,9 +157,8 @@ void AsyncLatencyLogger::Log(LatencyLogI
 {
   if (PR_LOG_TEST(GetLatencyLog(), PR_LOG_DEBUG)) {
     nsCOMPtr<nsIRunnable> event = new LogEvent(aIndex, aID, aValue);
     if (mThread) {
       mThread->Dispatch(event, NS_DISPATCH_NORMAL);
     }
   }
 }
-
--- a/content/media/Latency.h
+++ b/content/media/Latency.h
@@ -8,46 +8,54 @@
 #define MOZILLA_LATENCY_H
 
 #include "mozilla/TimeStamp.h"
 #include "prlog.h"
 #include "nsCOMPtr.h"
 #include "nsIThread.h"
 #include "mozilla/Monitor.h"
 #include "nsISupportsImpl.h"
+#include "nsObserverService.h"
 
 class AsyncLatencyLogger;
 class LogEvent;
 
 PRLogModuleInfo* GetLatencyLog();
 
 // This class is a singleton. It is refcounted.
-class AsyncLatencyLogger
+class AsyncLatencyLogger : public nsIObserver
 {
-  NS_INLINE_DECL_THREADSAFE_REFCOUNTING(AsyncLatencyLogger);
+  NS_DECL_THREADSAFE_ISUPPORTS
+  NS_DECL_NSIOBSERVER
+
 public:
+
   enum LatencyLogIndex {
     AudioMediaStreamTrack,
     VideoMediaStreamTrack,
     Cubeb,
     AudioStream,
     NetEQ,
     _MAX_INDEX
   };
   void Log(LatencyLogIndex index, uint64_t aID, int64_t value);
   void WriteLog(LatencyLogIndex index, uint64_t aID, int64_t value);
 
   static AsyncLatencyLogger* Get(bool aStartTimer = false);
   static void InitializeStatics();
-  static void Shutdown();
+  // After this is called, the global log object may go away
+  static void ShutdownLogger();
 private:
   AsyncLatencyLogger();
-  ~AsyncLatencyLogger();
+  virtual ~AsyncLatencyLogger();
   int64_t GetTimeStamp();
   void Init();
+  // Shut down the thread associated with this, and make sure it doesn't
+  // start up again.
+  void Shutdown();
   // The thread on which the IO happens
   nsCOMPtr<nsIThread> mThread;
   // This can be initialized on multiple threads, but is protected by a
   // monitor. After the initialization phase, it is accessed on the log
   // thread only.
   mozilla::TimeStamp mStart;
   // This monitor protects mStart and mMediaLatencyLog for the
   // initialization sequence. It is initialized at layout startup, and
--- a/content/media/MediaStreamGraph.cpp
+++ b/content/media/MediaStreamGraph.cpp
@@ -2320,16 +2320,17 @@ MediaStreamGraphImpl::MediaStreamGraphIm
   , mForceShutDown(false)
   , mPostedRunInStableStateEvent(false)
   , mNonRealtimeIsRunning(false)
   , mDetectedNotRunning(false)
   , mPostedRunInStableState(false)
   , mRealtime(aRealtime)
   , mNonRealtimeProcessing(false)
   , mStreamOrderDirty(false)
+  , mLatencyLog(AsyncLatencyLogger::Get())
 {
 #ifdef PR_LOGGING
   if (!gMediaStreamGraphLog) {
     gMediaStreamGraphLog = PR_NewLogModule("MediaStreamGraph");
   }
 #endif
 
   mCurrentTimeStamp = mInitialTimeStamp = mLastMainThreadUpdate = TimeStamp::Now();
--- a/content/media/MediaStreamGraphImpl.h
+++ b/content/media/MediaStreamGraphImpl.h
@@ -7,16 +7,17 @@
 #define MOZILLA_MEDIASTREAMGRAPHIMPL_H_
 
 #include "MediaStreamGraph.h"
 
 #include "mozilla/Monitor.h"
 #include "mozilla/TimeStamp.h"
 #include "nsIThread.h"
 #include "nsIRunnable.h"
+#include "Latency.h"
 
 namespace mozilla {
 
 template <typename T>
 class LinkedList;
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gMediaStreamGraphLog;
@@ -561,13 +562,17 @@ public:
    * value is only accessed on the main thread.
    */
   bool mNonRealtimeProcessing;
   /**
    * True when a change has happened which requires us to recompute the stream
    * blocking order.
    */
   bool mStreamOrderDirty;
+  /**
+   * Hold a ref to the Latency logger
+   */
+  nsRefPtr<AsyncLatencyLogger> mLatencyLog;
 };
 
 }
 
 #endif /* MEDIASTREAMGRAPHIMPL_H_ */
--- a/content/media/test/crashtests/crashtests.list
+++ b/content/media/test/crashtests/crashtests.list
@@ -51,10 +51,10 @@ test-pref(media.webvtt.enabled,true) loa
 load 884459.html
 load 889042.html
 test-pref(media.webvtt.enabled,true) load 894104.html
 load 907986-1.html
 load 907986-2.html
 load 907986-3.html
 load 907986-4.html
 load 910171-1.html
-load oscillator-ended-1.html
-load oscillator-ended-2.html
+skip-if(B2G) load oscillator-ended-1.html # intermittent B2G timeouts, bug 920338
+skip-if(B2G) load oscillator-ended-2.html # intermittent B2G timeouts, bug 920338
--- a/content/media/webrtc/MediaEngineWebRTC.cpp
+++ b/content/media/webrtc/MediaEngineWebRTC.cpp
@@ -89,25 +89,20 @@ MediaEngineWebRTC::EnumerateVideoDevices
   MutexAutoLock lock(mMutex);
 
 #ifdef MOZ_WIDGET_ANDROID
   jobject context = mozilla::AndroidBridge::Bridge()->GetGlobalContextRef();
 
   // get the JVM
   JavaVM *jvm = mozilla::AndroidBridge::Bridge()->GetVM();
 
-  JNIEnv *env;
-  jint res = jvm->AttachCurrentThread(&env, NULL);
-
   if (webrtc::VideoEngine::SetAndroidObjects(jvm, (void*)context) != 0) {
     LOG(("VieCapture:SetAndroidObjects Failed"));
     return;
   }
-
-  env->DeleteGlobalRef(context);
 #endif
 
   if (!mVideoEngine) {
     if (!(mVideoEngine = webrtc::VideoEngine::Create())) {
       return;
     }
   }
 
--- a/content/media/webspeech/synth/pico/PicoModule.cpp
+++ b/content/media/webspeech/synth/pico/PicoModule.cpp
@@ -29,17 +29,17 @@ static const mozilla::Module::CIDEntry k
 };
 
 static const mozilla::Module::ContractIDEntry kContracts[] = {
   { PICOSERVICE_CONTRACTID, &kPICOSERVICE_CID },
   { NULL }
 };
 
 static const mozilla::Module::CategoryEntry kCategories[] = {
-  { "app-startup", "Pico Speech Synth", "service," PICOSERVICE_CONTRACTID },
+  { "profile-after-change", "Pico Speech Synth", PICOSERVICE_CONTRACTID },
   { NULL }
 };
 
 static void
 UnloadPicoModule()
 {
   nsPicoService::Shutdown();
 }
--- a/content/media/webspeech/synth/pico/nsPicoService.cpp
+++ b/content/media/webspeech/synth/pico/nsPicoService.cpp
@@ -694,16 +694,20 @@ nsPicoService::CurrentVoice()
 }
 
 // static methods
 
 nsPicoService*
 nsPicoService::GetInstance()
 {
   MOZ_ASSERT(NS_IsMainThread());
+  if (XRE_GetProcessType() != GeckoProcessType_Default) {
+    MOZ_ASSERT(false, "nsPicoService can only be started on main gecko process");
+    return nullptr;
+  }
 
   if (!sSingleton) {
     sSingleton = new nsPicoService();
   }
 
   return sSingleton;
 }
 
--- a/content/smil/nsDOMTimeEvent.cpp
+++ b/content/smil/nsDOMTimeEvent.cpp
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMTimeEvent.h"
-#include "nsGUIEvent.h"
 #include "nsPresContext.h"
 #include "nsIInterfaceRequestorUtils.h"
+#include "mozilla/BasicEvents.h"
 
 nsDOMTimeEvent::nsDOMTimeEvent(mozilla::dom::EventTarget* aOwner,
                                nsPresContext* aPresContext, nsEvent* aEvent)
   : nsDOMEvent(aOwner, aPresContext, aEvent ? aEvent : new nsUIEvent(false, 0, 0)),
     mDetail(0)
 {
   SetIsDOMBinding();
   if (aEvent) {
--- a/content/smil/nsSMILTimeValueSpec.cpp
+++ b/content/smil/nsSMILTimeValueSpec.cpp
@@ -7,17 +7,17 @@
 #include "nsSMILTimeValueSpec.h"
 #include "nsSMILInterval.h"
 #include "nsSMILTimeContainer.h"
 #include "nsSMILTimeValue.h"
 #include "nsSMILTimedElement.h"
 #include "nsSMILInstanceTime.h"
 #include "nsSMILParserUtils.h"
 #include "nsEventListenerManager.h"
-#include "nsGUIEvent.h"
+#include "nsIDOMKeyEvent.h"
 #include "nsIDOMTimeEvent.h"
 #include "nsString.h"
 #include <limits>
 
 using namespace mozilla::dom;
 
 //----------------------------------------------------------------------
 // Nested class: EventListener
--- a/content/smil/nsSMILTimedElement.cpp
+++ b/content/smil/nsSMILTimedElement.cpp
@@ -1,26 +1,26 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/DebugOnly.h"
 
+#include "mozilla/BasicEvents.h"
 #include "mozilla/dom/SVGAnimationElement.h"
 #include "nsSMILTimedElement.h"
 #include "nsAttrValueInlines.h"
 #include "nsSMILAnimationFunction.h"
 #include "nsSMILTimeValue.h"
 #include "nsSMILTimeValueSpec.h"
 #include "nsSMILInstanceTime.h"
 #include "nsSMILParserUtils.h"
 #include "nsSMILTimeContainer.h"
 #include "nsGkAtoms.h"
-#include "nsGUIEvent.h"
 #include "nsEventDispatcher.h"
 #include "nsReadableUtils.h"
 #include "nsMathUtils.h"
 #include "nsThreadUtils.h"
 #include "nsIPresShell.h"
 #include "prdtoa.h"
 #include "plstr.h"
 #include "prtime.h"
--- a/content/svg/content/src/SVGSVGElement.cpp
+++ b/content/svg/content/src/SVGSVGElement.cpp
@@ -1,14 +1,15 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <stdint.h>
+#include "mozilla/BasicEvents.h"
 #include "mozilla/Util.h"
 #include "mozilla/Likely.h"
 
 #include "nsGkAtoms.h"
 #include "nsLayoutUtils.h"
 #include "DOMSVGNumber.h"
 #include "DOMSVGLength.h"
 #include "nsSVGAngle.h"
@@ -19,17 +20,16 @@
 #include "mozilla/dom/SVGMatrix.h"
 #include "DOMSVGPoint.h"
 #include "nsIFrame.h"
 #include "nsFrameSelection.h"
 #include "nsISVGSVGFrame.h" //XXX
 #include "mozilla/dom/SVGRect.h"
 #include "nsError.h"
 #include "nsISVGChildFrame.h"
-#include "nsGUIEvent.h"
 #include "mozilla/dom/SVGSVGElement.h"
 #include "mozilla/dom/SVGSVGElementBinding.h"
 #include "nsSVGUtils.h"
 #include "mozilla/dom/SVGViewElement.h"
 #include "nsStyleUtil.h"
 #include "SVGContentUtils.h"
 
 #include "nsEventDispatcher.h"
--- a/content/xbl/src/nsXBLBinding.cpp
+++ b/content/xbl/src/nsXBLBinding.cpp
@@ -42,17 +42,16 @@
 #include "nsGkAtoms.h"
 
 #include "nsXBLPrototypeHandler.h"
 
 #include "nsXBLPrototypeBinding.h"
 #include "nsXBLBinding.h"
 #include "nsIPrincipal.h"
 #include "nsIScriptSecurityManager.h"
-#include "nsGUIEvent.h"
 #include "mozilla/dom/XBLChildrenElement.h"
 
 #include "prprf.h"
 #include "nsNodeUtils.h"
 #include "nsJSUtils.h"
 
 // Nasty hack.  Maybe we could move some of the classinfo utility methods
 // (e.g. WrapNative) over to nsContentUtils?
--- a/content/xbl/src/nsXBLEventHandler.cpp
+++ b/content/xbl/src/nsXBLEventHandler.cpp
@@ -5,17 +5,16 @@
 
 #include "nsCOMPtr.h"
 #include "nsDOMEvent.h"
 #include "nsIAtom.h"
 #include "nsIDOMEventListener.h"
 #include "nsIDOMKeyEvent.h"
 #include "nsIDOMMouseEvent.h"
 #include "nsXBLPrototypeHandler.h"
-#include "nsGUIEvent.h"
 #include "nsContentUtils.h"
 #include "mozilla/dom/EventTarget.h"
 
 using namespace mozilla::dom;
 
 nsXBLEventHandler::nsXBLEventHandler(nsXBLPrototypeHandler* aHandler)
   : mProtoHandler(aHandler)
 {
--- a/content/xbl/src/nsXBLPrototypeHandler.cpp
+++ b/content/xbl/src/nsXBLPrototypeHandler.cpp
@@ -30,26 +30,26 @@
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowRoot.h"
 #include "nsIDOMWindow.h"
 #include "nsIServiceManager.h"
 #include "nsIScriptError.h"
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
 #include "nsGkAtoms.h"
-#include "nsGUIEvent.h"
 #include "nsIXPConnect.h"
 #include "nsIDOMScriptObjectFactory.h"
 #include "nsDOMCID.h"
 #include "nsUnicharUtils.h"
 #include "nsCRT.h"
 #include "nsXBLEventHandler.h"
 #include "nsXBLSerialize.h"
 #include "nsEventDispatcher.h"
 #include "nsJSUtils.h"
+#include "mozilla/BasicEvents.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/EventHandlerBinding.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 uint32_t nsXBLPrototypeHandler::gRefCnt = 0;
 
--- a/content/xbl/src/nsXBLWindowKeyHandler.cpp
+++ b/content/xbl/src/nsXBLWindowKeyHandler.cpp
@@ -22,18 +22,18 @@
 #include "nsIURI.h"
 #include "nsNetUtil.h"
 #include "nsContentUtils.h"
 #include "nsXBLPrototypeBinding.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDocShell.h"
 #include "nsIPresShell.h"
 #include "nsISelectionController.h"
-#include "nsGUIEvent.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/TextEvents.h"
 #include "mozilla/dom/Element.h"
 #include "nsEventStateManager.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 static nsINativeKeyBindings *sNativeEditorBindings = nullptr;
 
--- a/content/xml/document/src/XMLDocument.cpp
+++ b/content/xml/document/src/XMLDocument.cpp
@@ -27,17 +27,16 @@
 #include "nsIURI.h"
 #include "nsIServiceManager.h"
 #include "nsNetUtil.h"
 #include "nsError.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIPrincipal.h"
 #include "nsLayoutCID.h"
 #include "mozilla/dom/Attr.h"
-#include "nsGUIEvent.h"
 #include "nsCExternalHandlerService.h"
 #include "nsMimeTypes.h"
 #include "nsEventListenerManager.h"
 #include "nsContentUtils.h"
 #include "nsThreadUtils.h"
 #include "nsJSUtils.h"
 #include "nsCRT.h"
 #include "nsIAuthPrompt.h"
@@ -45,16 +44,17 @@
 #include "nsContentCreatorFunctions.h"
 #include "nsContentPolicyUtils.h"
 #include "nsIDOMUserDataHandler.h"
 #include "nsEventDispatcher.h"
 #include "nsNodeUtils.h"
 #include "nsIConsoleService.h"
 #include "nsIScriptError.h"
 #include "nsIHTMLDocument.h"
+#include "mozilla/BasicEvents.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/XMLDocumentBinding.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 // ==================================================================
 // =
--- a/content/xul/content/src/nsXULElement.cpp
+++ b/content/xul/content/src/nsXULElement.cpp
@@ -68,16 +68,17 @@
 #include "XULDocument.h"
 #include "nsXULPopupListener.h"
 #include "nsRuleWalker.h"
 #include "nsIDOMCSSStyleDeclaration.h"
 #include "nsCSSParser.h"
 #include "nsIListBoxObject.h"
 #include "nsContentUtils.h"
 #include "nsContentList.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/MutationEvent.h"
 #include "nsAsyncDOMEvent.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsPIDOMWindow.h"
 #include "nsJSPrincipals.h"
 #include "nsDOMAttributeMap.h"
 #include "nsGkAtoms.h"
 #include "nsXULContentUtils.h"
--- a/content/xul/document/src/XULDocument.cpp
+++ b/content/xul/document/src/XULDocument.cpp
@@ -27,17 +27,16 @@
 #include "XULDocument.h"
 
 #include "nsError.h"
 #include "nsIBoxObject.h"
 #include "nsIChromeRegistry.h"
 #include "nsView.h"
 #include "nsViewManager.h"
 #include "nsIContentViewer.h"
-#include "nsGUIEvent.h"
 #include "nsIDOMXULElement.h"
 #include "nsIRDFNode.h"
 #include "nsIRDFRemoteDataSource.h"
 #include "nsIRDFService.h"
 #include "nsIStreamListener.h"
 #include "nsITimer.h"
 #include "nsIDocShell.h"
 #include "nsGkAtoms.h"
@@ -79,16 +78,17 @@
 #include "nsEventDispatcher.h"
 #include "nsIObserverService.h"
 #include "nsNodeUtils.h"
 #include "nsIDocShellTreeOwner.h"
 #include "nsIXULWindow.h"
 #include "nsXULPopupManager.h"
 #include "nsCCUncollectableMarker.h"
 #include "nsURILoader.h"
+#include "mozilla/BasicEvents.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/ProcessingInstruction.h"
 #include "mozilla/dom/XULDocumentBinding.h"
 #include "mozilla/Preferences.h"
 #include "nsTextNode.h"
 #include "nsJSUtils.h"
 
 using namespace mozilla;
--- a/content/xul/document/src/nsXULCommandDispatcher.cpp
+++ b/content/xul/document/src/nsXULCommandDispatcher.cpp
@@ -21,23 +21,23 @@
 #include "nsPresContext.h"
 #include "nsIPresShell.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowRoot.h"
 #include "nsRDFCID.h"
 #include "nsXULCommandDispatcher.h"
 #include "prlog.h"
-#include "nsGUIEvent.h"
 #include "nsContentUtils.h"
 #include "nsReadableUtils.h"
 #include "nsCRT.h"
 #include "nsError.h"
 #include "nsEventDispatcher.h"
 #include "nsDOMClassInfoID.h"
+#include "mozilla/BasicEvents.h"
 #include "mozilla/dom/Element.h"
 
 #ifdef PR_LOGGING
 static PRLogModuleInfo* gLog;
 #endif
 
 ////////////////////////////////////////////////////////////////////////
 
--- a/dom/base/CompositionStringSynthesizer.cpp
+++ b/dom/base/CompositionStringSynthesizer.cpp
@@ -6,16 +6,17 @@
 #include "CompositionStringSynthesizer.h"
 #include "nsContentUtils.h"
 #include "nsIDocShell.h"
 #include "nsIFrame.h"
 #include "nsIPresShell.h"
 #include "nsIWidget.h"
 #include "nsPIDOMWindow.h"
 #include "nsView.h"
+#include "mozilla/TextEvents.h"
 
 namespace mozilla {
 namespace dom {
 
 NS_IMPL_ISUPPORTS1(CompositionStringSynthesizer,
                    nsICompositionStringSynthesizer)
 
 CompositionStringSynthesizer::CompositionStringSynthesizer(
--- a/dom/base/CompositionStringSynthesizer.h
+++ b/dom/base/CompositionStringSynthesizer.h
@@ -2,21 +2,21 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_compositionstringsynthesizer_h__
 #define mozilla_dom_compositionstringsynthesizer_h__
 
 #include "nsICompositionStringSynthesizer.h"
-#include "nsGUIEvent.h"
 #include "nsString.h"
 #include "nsTArray.h"
 #include "nsWeakReference.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/TextEvents.h"
 
 class nsIWidget;
 class nsPIDOMWindow;
 
 namespace mozilla {
 namespace dom {
 
 class CompositionStringSynthesizer MOZ_FINAL :
--- a/dom/base/DOMRequest.cpp
+++ b/dom/base/DOMRequest.cpp
@@ -5,16 +5,17 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "DOMRequest.h"
 
 #include "DOMError.h"
 #include "nsCxPusher.h"
 #include "nsThreadUtils.h"
 #include "DOMCursor.h"
+#include "nsIDOMEvent.h"
 
 using mozilla::dom::DOMRequest;
 using mozilla::dom::DOMRequestService;
 using mozilla::dom::DOMCursor;
 using mozilla::AutoPushJSContext;
 
 DOMRequest::DOMRequest(nsIDOMWindow* aWindow)
   : mResult(JSVAL_VOID)
--- a/dom/base/WindowNamedPropertiesHandler.cpp
+++ b/dom/base/WindowNamedPropertiesHandler.cpp
@@ -9,16 +9,69 @@
 #include "nsGlobalWindow.h"
 #include "nsHTMLDocument.h"
 #include "nsJSUtils.h"
 #include "xpcprivate.h"
 
 namespace mozilla {
 namespace dom {
 
+static bool
+ShouldExposeChildWindow(nsString& aNameBeingResolved, nsIDOMWindow *aChild)
+{
+  // If we're same-origin with the child, go ahead and expose it.
+  nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(aChild);
+  NS_ENSURE_TRUE(sop, false);
+  if (nsContentUtils::GetSubjectPrincipal()->Equals(sop->GetPrincipal())) {
+    return true;
+  }
+
+  // If we're not same-origin, expose it _only_ if the name of the browsing
+  // context matches the 'name' attribute of the frame element in the parent.
+  // The motivations behind this heuristic are worth explaining here.
+  //
+  // Historically, all UAs supported global named access to any child browsing
+  // context (that is to say, window.dolske returns a child frame where either
+  // the "name" attribute on the frame element was set to "dolske", or where
+  // the child explicitly set window.name = "dolske").
+  //
+  // This is problematic because it allows possibly-malicious and unrelated
+  // cross-origin subframes to pollute the global namespace of their parent in
+  // unpredictable ways (see bug 860494). This is also problematic for browser
+  // engines like Servo that want to run cross-origin script on different
+  // threads.
+  //
+  // The naive solution here would be to filter out any cross-origin subframes
+  // obtained when doing named lookup in global scope. But that is unlikely to
+  // be web-compatible, since it will break named access for consumers that do
+  // <iframe name="dolske" src="http://cross-origin.com/sadtrombone.html"> and
+  // expect to be able to access the cross-origin subframe via named lookup on
+  // the global.
+  //
+  // The optimal behavior would be to do the following:
+  // (a) Look for any child browsing context with name="dolske".
+  // (b) If the result is cross-origin, null it out.
+  // (c) If we have null, look for a frame element whose 'name' attribute is
+  //     "dolske".
+  //
+  // Unfortunately, (c) would require some engineering effort to be performant
+  // in Gecko, and probably in other UAs as well. So we go with a simpler
+  // approximation of the above. This approximation will only break sites that
+  // rely on their cross-origin subframes setting window.name to a known value,
+  // which is unlikely to be very common. And while it does introduce a
+  // dependency on cross-origin state when doing global lookups, it doesn't
+  // allow the child to arbitrarily pollute the parent namespace, and requires
+  // cross-origin communication only in a limited set of cases that can be
+  // computed independently by the parent.
+  nsCOMPtr<nsPIDOMWindow> piWin = do_QueryInterface(aChild);
+  NS_ENSURE_TRUE(piWin, false);
+  return piWin->GetFrameElementInternal()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::name,
+                                                       aNameBeingResolved, eCaseMatters);
+}
+
 bool
 WindowNamedPropertiesHandler::getOwnPropertyDescriptor(JSContext* aCx,
                                                        JS::Handle<JSObject*> aProxy,
                                                        JS::Handle<jsid> aId,
                                                        JS::MutableHandle<JSPropertyDescriptor> aDesc,
                                                        unsigned aFlags)
 {
   if (!JSID_IS_STRING(aId)) {
@@ -35,17 +88,17 @@ WindowNamedPropertiesHandler::getOwnProp
 
   // Grab the DOM window.
   XPCWrappedNative* wrapper = XPCWrappedNative::Get(global);
   nsCOMPtr<nsPIDOMWindow> piWin = do_QueryWrappedNative(wrapper);
   MOZ_ASSERT(piWin);
   nsGlobalWindow* win = static_cast<nsGlobalWindow*>(piWin.get());
   if (win->GetLength() > 0) {
     nsCOMPtr<nsIDOMWindow> childWin = win->GetChildWindow(str);
-    if (childWin) {
+    if (childWin && ShouldExposeChildWindow(str, childWin)) {
       // We found a subframe of the right name. Shadowing via |var foo| in
       // global scope is still allowed, since |var| only looks up |own|
       // properties. But unqualified shadowing will fail, per-spec.
       JS::Rooted<JS::Value> v(aCx);
       if (!WrapObject(aCx, aProxy, childWin, &v)) {
         return false;
       }
       aDesc.object().set(aProxy);
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -24,21 +24,25 @@
 #include "mozilla/layers/ShadowLayers.h"
 
 #include "nsIScrollableFrame.h"
 
 #include "nsContentUtils.h"
 
 #include "nsIFrame.h"
 #include "nsIWidget.h"
-#include "nsGUIEvent.h"
 #include "nsCharsetSource.h"
 #include "nsJSEnvironment.h"
 #include "nsJSUtils.h"
 
+#include "mozilla/MiscEvents.h"
+#include "mozilla/MouseEvents.h"
+#include "mozilla/TextEvents.h"
+#include "mozilla/TouchEvents.h"
+
 #include "nsViewManager.h"
 
 #include "nsIDOMHTMLCanvasElement.h"
 #include "gfxImageSurface.h"
 #include "nsLayoutUtils.h"
 #include "nsComputedDOMStyle.h"
 #include "nsIPresShell.h"
 #include "nsStyleAnimation.h"
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -33,16 +33,17 @@
 #include "mozilla/Selection.h"
 #include "nsXULPopupManager.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsIPrincipal.h"
 #include "nsIObserverService.h"
 #include "nsIObjectFrame.h"
 #include "nsBindingManager.h"
 
+#include "mozilla/ContentEvents.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/LookAndFeel.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
 #include <algorithm>
 
 #ifdef MOZ_XUL
 #include "nsIDOMXULTextboxElement.h"
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -62,16 +62,17 @@
 #include "nsEventListenerManager.h"
 #include "mozilla/dom/BarProps.h"
 #include "nsContentCID.h"
 #include "nsLayoutStatics.h"
 #include "nsCCUncollectableMarker.h"
 #include "mozilla/dom/workers/Workers.h"
 #include "nsJSPrincipals.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/MouseEvents.h"
 
 // Interfaces Needed
 #include "nsIFrame.h"
 #include "nsCanvasFrame.h"
 #include "nsIWidget.h"
 #include "nsIWidgetListener.h"
 #include "nsIBaseWindow.h"
 #include "nsDeviceSensors.h"
--- a/dom/base/nsGlobalWindowCommands.cpp
+++ b/dom/base/nsGlobalWindowCommands.cpp
@@ -22,18 +22,18 @@
 #include "nsIDocShell.h"
 #include "nsISelectionController.h"
 #include "nsIWebNavigation.h"
 #include "nsIContentViewerEdit.h"
 #include "nsIContentViewer.h"
 #include "nsFocusManager.h"
 #include "nsCopySupport.h"
 #include "nsIClipboard.h"
-#include "nsGUIEvent.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/BasicEvents.h"
 
 #include "nsIClipboardDragDropHooks.h"
 #include "nsIClipboardDragDropHookList.h"
 
 using namespace mozilla;
 
 const char * const sSelectAllString = "cmd_selectAll";
 const char * const sSelectNoneString = "cmd_selectNone";
--- a/dom/base/nsIScriptContext.h
+++ b/dom/base/nsIScriptContext.h
@@ -2,17 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsIScriptContext_h__
 #define nsIScriptContext_h__
 
 #include "nscore.h"
-#include "nsString.h"
+#include "nsStringGlue.h"
 #include "nsISupports.h"
 #include "nsCOMPtr.h"
 #include "nsIProgrammingLanguage.h"
 #include "jspubtd.h"
 #include "js/GCAPI.h"
 
 class nsIScriptGlobalObject;
 class nsIScriptSecurityManager;
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -23,17 +23,16 @@
 #include "nsIDocShellTreeItem.h"
 #include "nsPresContext.h"
 #include "nsIConsoleService.h"
 #include "nsIScriptError.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIPrompt.h"
 #include "nsIObserverService.h"
-#include "nsGUIEvent.h"
 #include "nsITimer.h"
 #include "nsIAtom.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsEventDispatcher.h"
 #include "nsIContent.h"
 #include "nsCycleCollector.h"
 #include "nsNetUtil.h"
@@ -76,16 +75,17 @@
 #include "prthread.h"
 
 #include "mozilla/Preferences.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/dom/CanvasRenderingContext2DBinding.h"
 #include "mozilla/CycleCollectedJSRuntime.h"
+#include "mozilla/ContentEvents.h"
 
 #include "nsCycleCollectionNoteRootCallback.h"
 #include "GeckoProfiler.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 const size_t gStackSize = 8192;
--- a/dom/base/nsQueryContentEventResult.cpp
+++ b/dom/base/nsQueryContentEventResult.cpp
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsQueryContentEventResult.h"
-#include "nsGUIEvent.h"
 #include "nsIWidget.h"
 #include "nsPoint.h"
+#include "mozilla/TextEvents.h"
 
 NS_INTERFACE_MAP_BEGIN(nsQueryContentEventResult)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIQueryContentEventResult)
   NS_INTERFACE_MAP_ENTRY(nsIQueryContentEventResult)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_ADDREF(nsQueryContentEventResult)
 NS_IMPL_RELEASE(nsQueryContentEventResult)
--- a/dom/base/nsWindowMemoryReporter.cpp
+++ b/dom/base/nsWindowMemoryReporter.cpp
@@ -4,59 +4,59 @@
  * 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 "amIAddonManager.h"
 #include "nsWindowMemoryReporter.h"
 #include "nsGlobalWindow.h"
 #include "nsIDocument.h"
 #include "nsIEffectiveTLDService.h"
+#include "mozilla/ClearOnShutdown.h"
+#include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
-#include "mozilla/Preferences.h"
+#include "mozilla/StaticPtr.h"
 #include "nsNetCID.h"
 #include "nsPrintfCString.h"
 #include "XPCJSMemoryReporter.h"
 #include "js/MemoryMetrics.h"
 #include "nsServiceManagerUtils.h"
 
 using namespace mozilla;
 
+StaticRefPtr<nsWindowMemoryReporter> sWindowReporter;
+
 nsWindowMemoryReporter::nsWindowMemoryReporter()
   : mCheckForGhostWindowsCallbackPending(false)
 {
 }
 
 NS_IMPL_ISUPPORTS3(nsWindowMemoryReporter, nsIMemoryReporter, nsIObserver,
                    nsSupportsWeakReference)
 
 /* static */
 void
 nsWindowMemoryReporter::Init()
 {
-  // The memory reporter manager will own this object.
-  nsRefPtr<nsWindowMemoryReporter> windowReporter = new nsWindowMemoryReporter();
-  NS_RegisterMemoryReporter(windowReporter);
+  MOZ_ASSERT(!sWindowReporter);
+  sWindowReporter = new nsWindowMemoryReporter();
+  ClearOnShutdown(&sWindowReporter);
+  NS_RegisterMemoryReporter(sWindowReporter);
 
   nsCOMPtr<nsIObserverService> os = services::GetObserverService();
   if (os) {
     // DOM_WINDOW_DESTROYED_TOPIC announces what we call window "detachment",
     // when a window's docshell is set to NULL.
-    os->AddObserver(windowReporter, DOM_WINDOW_DESTROYED_TOPIC,
+    os->AddObserver(sWindowReporter, DOM_WINDOW_DESTROYED_TOPIC,
                     /* weakRef = */ true);
-    os->AddObserver(windowReporter, "after-minimize-memory-usage",
+    os->AddObserver(sWindowReporter, "after-minimize-memory-usage",
                     /* weakRef = */ true);
   }
 
-  nsRefPtr<GhostURLsReporter> ghostURLsReporter =
-    new GhostURLsReporter(windowReporter);
-  NS_RegisterMemoryReporter(ghostURLsReporter);
-
-  nsRefPtr<NumGhostsReporter> numGhostsReporter =
-    new NumGhostsReporter(windowReporter);
-  NS_RegisterMemoryReporter(numGhostsReporter);
+  NS_RegisterMemoryReporter(new GhostWindowsReporter());
+  RegisterGhostWindowsDistinguishedAmount(GhostWindowsReporter::DistinguishedAmount);
 }
 
 static already_AddRefed<nsIURI>
 GetWindowURI(nsIDOMWindow *aWindow)
 {
   nsCOMPtr<nsPIDOMWindow> pWindow = do_QueryInterface(aWindow);
   NS_ENSURE_TRUE(pWindow, nullptr);
 
@@ -306,16 +306,62 @@ static
 PLDHashOperator
 GetWindows(const uint64_t& aId, nsGlobalWindow*& aWindow, void* aClosure)
 {
   ((WindowArray *)aClosure)->AppendElement(aWindow);
 
   return PL_DHASH_NEXT;
 }
 
+struct ReportGhostWindowsEnumeratorData
+{
+  nsIMemoryReporterCallback* callback;
+  nsISupports* closure;
+  nsresult rv;
+};
+
+static PLDHashOperator
+ReportGhostWindowsEnumerator(nsUint64HashKey* aIDHashKey, void* aClosure)
+{
+  ReportGhostWindowsEnumeratorData *data =
+    static_cast<ReportGhostWindowsEnumeratorData*>(aClosure);
+
+  nsGlobalWindow::WindowByIdTable* windowsById =
+    nsGlobalWindow::GetWindowsTable();
+  if (!windowsById) {
+    NS_WARNING("Couldn't get window-by-id hashtable?");
+    return PL_DHASH_NEXT;
+  }
+
+  nsGlobalWindow* window = windowsById->Get(aIDHashKey->GetKey());
+  if (!window) {
+    NS_WARNING("Could not look up window?");
+    return PL_DHASH_NEXT;
+  }
+
+  nsAutoCString path;
+  path.AppendLiteral("ghost-windows/");
+  AppendWindowURI(window, path);
+
+  nsresult rv = data->callback->Callback(
+    /* process = */ EmptyCString(),
+    path,
+    nsIMemoryReporter::KIND_OTHER,
+    nsIMemoryReporter::UNITS_COUNT,
+    /* amount = */ 1,
+    /* description = */ NS_LITERAL_CSTRING("A ghost window."),
+    data->closure);
+
+  if (NS_FAILED(rv) && NS_SUCCEEDED(data->rv)) {
+    data->rv = rv;
+  }
+
+  return PL_DHASH_NEXT;
+}
+
 NS_IMETHODIMP
 nsWindowMemoryReporter::GetName(nsACString &aName)
 {
   aName.AssignLiteral("window-objects");
   return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -326,40 +372,46 @@ nsWindowMemoryReporter::CollectReports(n
     nsGlobalWindow::GetWindowsTable();
   NS_ENSURE_TRUE(windowsById, NS_OK);
 
   // Hold on to every window in memory so that window objects can't be
   // destroyed while we're calling the memory reporter callback.
   WindowArray windows;
   windowsById->Enumerate(GetWindows, &windows);
 
-  // Get the IDs of all the "ghost" windows.
+  // Get the IDs of all the "ghost" windows, and call aCb->Callback() for each
+  // one.
   nsTHashtable<nsUint64HashKey> ghostWindows;
   CheckForGhostWindows(&ghostWindows);
+  ReportGhostWindowsEnumeratorData reportGhostWindowsEnumData =
+    { aCb, aClosure, NS_OK };
+  ghostWindows.EnumerateEntries(ReportGhostWindowsEnumerator,
+                                &reportGhostWindowsEnumData);
+  nsresult rv = reportGhostWindowsEnumData.rv;
+  NS_ENSURE_SUCCESS(rv, rv);
 
   WindowPaths windowPaths;
-
   WindowPaths topWindowPaths;
 
   // Collect window memory usage.
   nsWindowSizes windowTotalSizes(NULL);
   nsCOMPtr<amIAddonManager> addonManager =
     do_GetService("@mozilla.org/addons/integration;1");
   for (uint32_t i = 0; i < windows.Length(); i++) {
-    nsresult rv = CollectWindowReports(windows[i], addonManager,
-                                       &windowTotalSizes, &ghostWindows,
-                                       &windowPaths, &topWindowPaths, aCb,
-                                       aClosure);
+    rv = CollectWindowReports(windows[i], addonManager,
+                              &windowTotalSizes, &ghostWindows,
+                              &windowPaths, &topWindowPaths, aCb,
+                              aClosure);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Report JS memory usage.  We do this from here because the JS memory
   // reporter needs to be passed |windowPaths|.
-  nsresult rv = xpc::JSReporter::CollectReports(&windowPaths, &topWindowPaths,
-                                                aCb, aClosure);
+  rv = xpc::JSReporter::CollectReports(&windowPaths, &topWindowPaths,
+                                       aCb, aClosure);
   NS_ENSURE_SUCCESS(rv, rv);
 
 #define REPORT(_path, _amount, _desc)                                         \
   do {                                                                        \
     nsresult rv;                                                              \
     rv = aCb->Callback(EmptyCString(), NS_LITERAL_CSTRING(_path),             \
                        nsIMemoryReporter::KIND_OTHER,                         \
                        nsIMemoryReporter::UNITS_BYTES, _amount,               \
@@ -657,99 +709,16 @@ nsWindowMemoryReporter::CheckForGhostWin
   // if it's not null.
   CheckForGhostWindowsEnumeratorData ghostEnumData =
     { &nonDetachedWindowDomains, aOutGhostIDs, tldService,
       GetGhostTimeout(), TimeStamp::Now() };
   mDetachedWindows.Enumerate(CheckForGhostWindowsEnumerator,
                              &ghostEnumData);
 }
 
-NS_IMPL_ISUPPORTS1(nsWindowMemoryReporter::GhostURLsReporter,
-                   nsIMemoryReporter)
-
-nsWindowMemoryReporter::
-GhostURLsReporter::GhostURLsReporter(
-  nsWindowMemoryReporter* aWindowReporter)
-  : mWindowReporter(aWindowReporter)
+/* static */ int64_t
+nsWindowMemoryReporter::GhostWindowsReporter::DistinguishedAmount()
 {
-}
-
-NS_IMETHODIMP
-nsWindowMemoryReporter::
-GhostURLsReporter::GetName(nsACString& aName)
-{
-  aName.AssignLiteral("ghost-windows-multi");
-  return NS_OK;
+  nsTHashtable<nsUint64HashKey> ghostWindows;
+  sWindowReporter->CheckForGhostWindows(&ghostWindows);
+  return ghostWindows.Count();
 }
 
-struct ReportGhostWindowsEnumeratorData
-{
-  nsIMemoryReporterCallback* callback;
-  nsISupports* closure;
-  nsresult rv;
-};
-
-static PLDHashOperator
-ReportGhostWindowsEnumerator(nsUint64HashKey* aIDHashKey, void* aClosure)
-{
-  ReportGhostWindowsEnumeratorData *data =
-    static_cast<ReportGhostWindowsEnumeratorData*>(aClosure);
-
-  nsGlobalWindow::WindowByIdTable* windowsById =
-    nsGlobalWindow::GetWindowsTable();
-  if (!windowsById) {
-    NS_WARNING("Couldn't get window-by-id hashtable?");
-    return PL_DHASH_NEXT;
-  }
-
-  nsGlobalWindow* window = windowsById->Get(aIDHashKey->GetKey());
-  if (!window) {
-    NS_WARNING("Could not look up window?");
-    return PL_DHASH_NEXT;
-  }
-
-  nsAutoCString path;
-  path.AppendLiteral("ghost-windows/");
-  AppendWindowURI(window, path);
-
-  nsresult rv = data->callback->Callback(
-    /* process = */ EmptyCString(),
-    path,
-    nsIMemoryReporter::KIND_OTHER,
-    nsIMemoryReporter::UNITS_COUNT,
-    /* amount = */ 1,
-    /* description = */ NS_LITERAL_CSTRING("A ghost window."),
-    data->closure);
-
-  if (NS_FAILED(rv) && NS_SUCCEEDED(data->rv)) {
-    data->rv = rv;
-  }
-
-  return PL_DHASH_NEXT;
-}
-
-NS_IMETHODIMP
-nsWindowMemoryReporter::
-GhostURLsReporter::CollectReports(
-  nsIMemoryReporterCallback* aCb,
-  nsISupports* aClosure)
-{
-  // Get the IDs of all the ghost windows in existance.
-  nsTHashtable<nsUint64HashKey> ghostWindows;
-  mWindowReporter->CheckForGhostWindows(&ghostWindows);
-
-  ReportGhostWindowsEnumeratorData reportGhostWindowsEnumData =
-    { aCb, aClosure, NS_OK };
-
-  // Call aCb->Callback() for each ghost window.
-  ghostWindows.EnumerateEntries(ReportGhostWindowsEnumerator,
-                                &reportGhostWindowsEnumData);
-
-  return reportGhostWindowsEnumData.rv;
-}
-
-int64_t
-nsWindowMemoryReporter::NumGhostsReporter::Amount()
-{
-  nsTHashtable<nsUint64HashKey> ghostWindows;
-  mWindowReporter->CheckForGhostWindows(&ghostWindows);
-  return ghostWindows.Count();
-}
--- a/dom/base/nsWindowMemoryReporter.h
+++ b/dom/base/nsWindowMemoryReporter.h
@@ -116,56 +116,38 @@ public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIMEMORYREPORTER
   NS_DECL_NSIOBSERVER
 
   static void Init();
 
 private:
   /**
-   * GhostURLsReporter generates the list of all ghost windows' URLs.  If
-   * you're only interested in this list, running this report is faster than
-   * running nsWindowMemoryReporter.
-   */
-  class GhostURLsReporter MOZ_FINAL : public nsIMemoryReporter
-  {
-  public:
-    GhostURLsReporter(nsWindowMemoryReporter* aWindowReporter);
-
-    NS_DECL_ISUPPORTS
-    NS_DECL_NSIMEMORYREPORTER
-
-  private:
-    nsRefPtr<nsWindowMemoryReporter> mWindowReporter;
-  };
-
-  /**
    * nsGhostWindowReporter generates the "ghost-windows" report, which counts
    * the number of ghost windows present.
    */
-  class NumGhostsReporter MOZ_FINAL : public mozilla::MemoryUniReporter
+  class GhostWindowsReporter MOZ_FINAL : public mozilla::MemoryUniReporter
   {
   public:
-    NumGhostsReporter(nsWindowMemoryReporter* aWindowReporter)
+    GhostWindowsReporter()
       : MemoryUniReporter("ghost-windows", KIND_OTHER, UNITS_COUNT,
 "The number of ghost windows present (the number of nodes underneath "
 "explicit/window-objects/top(none)/ghost, modulo race conditions).  A ghost "
 "window is not shown in any tab, does not share a domain with any non-detached "
 "windows, and has met these criteria for at least "
 "memory.ghost_window_timeout_seconds, or has survived a round of "
 "about:memory's minimize memory usage button.\n\n"
 "Ghost windows can happen legitimately, but they are often indicative of "
 "leaks in the browser or add-ons.")
-      , mWindowReporter(aWindowReporter)
     {}
 
+    static int64_t DistinguishedAmount();
+
   private:
-    int64_t Amount() MOZ_OVERRIDE;
-
-    nsRefPtr<nsWindowMemoryReporter> mWindowReporter;
+    int64_t Amount() MOZ_OVERRIDE { return DistinguishedAmount(); }
   };
 
   // Protect ctor, use Init() instead.
   nsWindowMemoryReporter();
 
   /**
    * Get the number of seconds for which a window must satisfy ghost criteria
    * (1) and (2) before we deem that it satisfies criterion (3).
--- a/dom/base/nsWindowRoot.cpp
+++ b/dom/base/nsWindowRoot.cpp
@@ -1,23 +1,23 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "mozilla/BasicEvents.h"
 #include "nsCOMPtr.h"
 #include "nsWindowRoot.h"
 #include "nsPIDOMWindow.h"
 #include "nsEventListenerManager.h"
 #include "nsPresContext.h"
 #include "nsLayoutCID.h"
 #include "nsContentCID.h"
 #include "nsString.h"
 #include "nsEventDispatcher.h"
-#include "nsGUIEvent.h"
 #include "nsGlobalWindow.h"
 #include "nsFocusManager.h"
 #include "nsIContent.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMHTMLTextAreaElement.h"
 #include "nsIControllers.h"
 #include "nsIController.h"
 
--- a/dom/bindings/BindingDeclarations.h
+++ b/dom/bindings/BindingDeclarations.h
@@ -203,17 +203,17 @@ public:
       }
     } else {
       aString = AsAString();
     }
   }
 
 private:
   // We need to be able to act like a string as needed
-  Maybe<nsString> mString;
+  Maybe<nsAutoString> mString;
 
   // For callees that know we exist, we can be a stringbuffer/length/null-flag
   // triple.
   nsStringBuffer* mStringBuffer;
   uint32_t mLength;
   bool mIsNull;
 };
 
--- a/dom/indexedDB/IDBRequest.cpp
+++ b/dom/indexedDB/IDBRequest.cpp
@@ -3,16 +3,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "IDBRequest.h"
 
 #include "nsIScriptContext.h"
 
+#include "mozilla/ContentEvents.h"
 #include "mozilla/dom/IDBOpenDBRequestBinding.h"
 #include "mozilla/dom/UnionTypes.h"
 #include "nsComponentManagerUtils.h"
 #include "nsDOMClassInfoID.h"
 #include "nsDOMJSUtils.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsEventDispatcher.h"
--- a/dom/indexedDB/IDBRequest.h
+++ b/dom/indexedDB/IDBRequest.h
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_indexeddb_idbrequest_h__
 #define mozilla_dom_indexeddb_idbrequest_h__
 
 #include "mozilla/dom/indexedDB/IndexedDatabase.h"
 
 #include "mozilla/Attributes.h"
+#include "mozilla/EventForwards.h"
 #include "mozilla/dom/DOMError.h"
 #include "mozilla/dom/IDBRequestBinding.h"
 #include "mozilla/ErrorResult.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsWrapperCache.h"
 
 #include "mozilla/dom/indexedDB/IDBWrapperCache.h"
 
--- a/dom/indexedDB/IndexedDatabaseManager.cpp
+++ b/dom/indexedDB/IndexedDatabaseManager.cpp
@@ -10,16 +10,17 @@
 #include "nsIDiskSpaceWatcher.h"
 #include "nsIFile.h"
 #include "nsIFileStorage.h"
 #include "nsIObserverService.h"
 #include "nsIScriptError.h"
 
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/CondVar.h"
+#include "mozilla/ContentEvents.h"
 #include "mozilla/dom/quota/OriginOrPatternString.h"
 #include "mozilla/dom/quota/QuotaManager.h"
 #include "mozilla/dom/quota/Utilities.h"
 #include "mozilla/dom/TabContext.h"
 #include "mozilla/Services.h"
 #include "mozilla/storage.h"
 #include "nsContentUtils.h"
 #include "nsEventDispatcher.h"
--- a/dom/interfaces/base/nsICompositionStringSynthesizer.idl
+++ b/dom/interfaces/base/nsICompositionStringSynthesizer.idl
@@ -13,17 +13,17 @@
 [scriptable, uuid(9a7d7851-8c0a-4061-9edc-60d6693f86c9)]
 interface nsICompositionStringSynthesizer : nsISupports
 {
   /**
    * Set composition string or committed string.
    */
   void setString(in AString aString);
 
-  // NOTE: These values must be same to NS_TEXTRANGE_* in nsGUIEvent.h
+  // NOTE: These values must be same to NS_TEXTRANGE_* in TextEvents.h
   const unsigned long ATTR_RAWINPUT              = 0x02;
   const unsigned long ATTR_SELECTEDRAWTEXT       = 0x03;
   const unsigned long ATTR_CONVERTEDTEXT         = 0x04;
   const unsigned long ATTR_SELECTEDCONVERTEDTEXT = 0x05;
 
   /**
    * Append a clause.
    *
--- a/dom/interfaces/base/nsIDOMWindowUtils.idl
+++ b/dom/interfaces/base/nsIDOMWindowUtils.idl
@@ -810,17 +810,17 @@ interface nsIDOMWindowUtils : nsISupport
    *               for the other parameters and the result.
    */
   nsIQueryContentEventResult sendQueryContentEvent(in unsigned long aType,
                                                    in unsigned long aOffset,
                                                    in unsigned long aLength,
                                                    in long aX,
                                                    in long aY);
 
-  // NOTE: following values are same as NS_QUERY_* in nsGUIEvent.h
+  // NOTE: following values are same as NS_QUERY_* in BasicEvents.h
 
   /**
    * QUERY_SELECTED_TEXT queries the first selection range's information.
    *
    * @param aOffset   Not used.
    * @param aLength   Not used.
    * @param aX        Not used.
    * @param aY        Not used.
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -18,17 +18,20 @@
 #include "mozilla/dom/PContentDialogChild.h"
 #include "mozilla/ipc/DocumentRendererChild.h"
 #include "mozilla/ipc/FileDescriptorUtils.h"
 #include "mozilla/layers/AsyncPanZoomController.h"
 #include "mozilla/layers/CompositorChild.h"
 #include "mozilla/layers/ImageBridgeChild.h"
 #include "mozilla/layers/ShadowLayers.h"
 #include "mozilla/layout/RenderFrameChild.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/StaticPtr.h"
+#include "mozilla/TextEvents.h"
+#include "mozilla/TouchEvents.h"
 #include "mozilla/unused.h"
 #include "mozIApplication.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsEmbedCID.h"
 #include "nsEventListenerManager.h"
 #include <algorithm>
 #ifdef MOZ_CRASHREPORTER
--- a/dom/ipc/TabChild.h
+++ b/dom/ipc/TabChild.h
@@ -30,16 +30,17 @@
 #include "nsDOMEventTargetHelper.h"
 #include "nsIDialogCreator.h"
 #include "nsIPresShell.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsWeakReference.h"
 #include "nsITabChild.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/dom/TabContext.h"
+#include "mozilla/EventForwards.h"
 
 struct gfxMatrix;
 class nsICachedFileDescriptorListener;
 class nsIDOMWindowUtils;
 
 namespace mozilla {
 namespace layout {
 class RenderFrameChild;
--- a/dom/ipc/TabParent.cpp
+++ b/dom/ipc/TabParent.cpp
@@ -13,17 +13,20 @@
 #include "mozIApplication.h"
 #include "mozilla/BrowserElementParent.h"
 #include "mozilla/docshell/OfflineCacheUpdateParent.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/Hal.h"
 #include "mozilla/ipc/DocumentRendererParent.h"
 #include "mozilla/layers/CompositorParent.h"
 #include "mozilla/layout/RenderFrameParent.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/TextEvents.h"
+#include "mozilla/TouchEvents.h"
 #include "mozilla/unused.h"
 #include "nsCOMPtr.h"
 #include "nsContentPermissionHelper.h"
 #include "nsContentUtils.h"
 #include "nsDebug.h"
 #include "nsEventStateManager.h"
 #include "nsFocusManager.h"
 #include "nsFrameLoader.h"
--- a/dom/ipc/TabParent.h
+++ b/dom/ipc/TabParent.h
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_tabs_TabParent_h
 #define mozilla_tabs_TabParent_h
 
 #include "mozilla/dom/PBrowserParent.h"
 #include "mozilla/dom/PContentDialogParent.h"
 #include "mozilla/dom/TabContext.h"
+#include "mozilla/TouchEvents.h"
 #include "nsCOMPtr.h"
 #include "nsIAuthPromptProvider.h"
 #include "nsIBrowserDOMWindow.h"
 #include "nsIDialogParamBlock.h"
 #include "nsISecureBrowserUI.h"
 #include "nsITabParent.h"
 #include "Units.h"
 #include "js/TypeDecls.h"
--- a/dom/media/PeerConnection.js
+++ b/dom/media/PeerConnection.js
@@ -8,27 +8,21 @@ const {classes: Cc, interfaces: Ci, util
 
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 const PC_CONTRACT = "@mozilla.org/dom/peerconnection;1";
 const PC_ICE_CONTRACT = "@mozilla.org/dom/rtcicecandidate;1";
 const PC_SESSION_CONTRACT = "@mozilla.org/dom/rtcsessiondescription;1";
 const PC_MANAGER_CONTRACT = "@mozilla.org/dom/peerconnectionmanager;1";
-const PC_ICEEVENT_CONTRACT = "@mozilla.org/dom/rtcpeerconnectioniceevent;1";
-const MSEVENT_CONTRACT = "@mozilla.org/dom/mediastreamevent;1";
-const DCEVENT_CONTRACT = "@mozilla.org/dom/datachannelevent;1";
 
 const PC_CID = Components.ID("{9878b414-afaa-4176-a887-1e02b3b047c2}");
 const PC_ICE_CID = Components.ID("{02b9970c-433d-4cc2-923d-f7028ac66073}");
 const PC_SESSION_CID = Components.ID("{1775081b-b62d-4954-8ffe-a067bbf508a7}");
 const PC_MANAGER_CID = Components.ID("{7293e901-2be3-4c02-b4bd-cbef6fc24f78}");
-const PC_ICEEVENT_CID = Components.ID("{b9cd25a7-9859-4f9e-8f84-ef5181ff36c0}");
-const MSEVENT_CID = Components.ID("{a722a8a9-2290-4e99-a5ed-07b504292d08}");
-const DCEVENT_CID = Components.ID("{d5ed7fbf-01a8-4b18-af6c-861cf2aac920}");
 
 // Global list of PeerConnection objects, so they can be cleaned up when
 // a page is torn down. (Maps inner window ID to an array of PC objects).
 function GlobalPCList() {
   this._list = [];
   this._networkdown = false; // XXX Need to query current state somehow
   Services.obs.addObserver(this, "inner-window-destroyed", true);
   Services.obs.addObserver(this, "profile-change-net-teardown", true);
@@ -151,82 +145,16 @@ RTCSessionDescription.prototype = {
   init: function(win) { this._win = win; },
 
   __init: function(dict) {
     this.type = dict.type;
     this.sdp  = dict.sdp;
   }
 };
 
-function MediaStreamEvent() {
-  this.type = this._stream = null;
-}
-MediaStreamEvent.prototype = {
-  classDescription: "MediaStreamEvent",
-  classID: MSEVENT_CID,
-  contractID: MSEVENT_CONTRACT,
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
-                                         Ci.nsIDOMGlobalPropertyInitializer]),
-
-  init: function(win) { this._win = win; },
-
-  __init: function(type, dict) {
-    this.type = type;
-    this.__DOM_IMPL__.initEvent(type, dict.bubbles || false,
-                                dict.cancelable || false);
-    this._stream = dict.stream;
-  },
-
-  get stream() { return this._stream; }
-};
-
-function RTCDataChannelEvent() {
-  this.type = this._channel = null;
-}
-RTCDataChannelEvent.prototype = {
-  classDescription: "RTCDataChannelEvent",
-  classID: DCEVENT_CID,
-  contractID: DCEVENT_CONTRACT,
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
-                                         Ci.nsIDOMGlobalPropertyInitializer]),
-
-  init: function(win) { this._win = win; },
-
-  __init: function(type, dict) {
-    this.type = type;
-    this.__DOM_IMPL__.initEvent(type, dict.bubbles || false,
-                                dict.cancelable || false);
-    this._channel = dict.channel;
-  },
-
-  get channel() { return this._channel; }
-};
-
-function RTCPeerConnectionIceEvent() {
-  this.type = this._candidate = null;
-}
-RTCPeerConnectionIceEvent.prototype = {
-  classDescription: "RTCPeerConnectionIceEvent",
-  classID: PC_ICEEVENT_CID,
-  contractID: PC_ICEEVENT_CONTRACT,
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
-                                         Ci.nsIDOMGlobalPropertyInitializer]),
-
-  init: function(win) { this._win = win; },
-
-  __init: function(type, dict) {
-    this.type = type;
-    this.__DOM_IMPL__.initEvent(type, dict.bubbles || false,
-                                dict.cancelable || false);
-    this._candidate = dict.candidate;
-  },
-
-  get candidate() { return this._candidate; }
-};
-
 function RTCPeerConnection() {
   this._queue = [];
 
   this._pc = null;
   this._observer = null;
   this._closed = false;
 
   this._onCreateOfferSuccess = null;
@@ -1096,11 +1024,10 @@ PeerConnectionObserver.prototype = {
   },
 
   notifyClosedConnection: function() {
     this.dispatchEvent(new this._dompc._win.Event("closedconnection"));
   }
 };
 
 this.NSGetFactory = XPCOMUtils.generateNSGetFactory(
-  [GlobalPCList, RTCIceCandidate, RTCSessionDescription, RTCPeerConnection,
-   RTCPeerConnectionIceEvent, MediaStreamEvent, RTCDataChannelEvent]
+  [GlobalPCList, RTCIceCandidate, RTCSessionDescription, RTCPeerConnection]
 );
--- a/dom/media/PeerConnection.manifest
+++ b/dom/media/PeerConnection.manifest
@@ -1,15 +1,9 @@
 component {9878b414-afaa-4176-a887-1e02b3b047c2} PeerConnection.js
 component {02b9970c-433d-4cc2-923d-f7028ac66073} PeerConnection.js
 component {1775081b-b62d-4954-8ffe-a067bbf508a7} PeerConnection.js
 component {7293e901-2be3-4c02-b4bd-cbef6fc24f78} PeerConnection.js
-component {b9cd25a7-9859-4f9e-8f84-ef5181ff36c0} PeerConnection.js
-component {a722a8a9-2290-4e99-a5ed-07b504292d08} PeerConnection.js
-component {d5ed7fbf-01a8-4b18-af6c-861cf2aac920} PeerConnection.js
 
 contract @mozilla.org/dom/peerconnection;1 {9878b414-afaa-4176-a887-1e02b3b047c2}
 contract @mozilla.org/dom/rtcicecandidate;1 {02b9970c-433d-4cc2-923d-f7028ac66073}
 contract @mozilla.org/dom/rtcsessiondescription;1 {1775081b-b62d-4954-8ffe-a067bbf508a7}
 contract @mozilla.org/dom/peerconnectionmanager;1 {7293e901-2be3-4c02-b4bd-cbef6fc24f78}
-contract @mozilla.org/dom/rtcpeerconnectioniceevent;1 {b9cd25a7-9859-4f9e-8f84-ef5181ff36c0}
-contract @mozilla.org/dom/mediastreamevent;1 {a722a8a9-2290-4e99-a5ed-07b504292d08}
-contract @mozilla.org/dom/datachannelevent;1 {d5ed7fbf-01a8-4b18-af6c-861cf2aac920}
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -54,16 +54,19 @@ using mozilla::DefaultXDisplay;
 #include "nsIFocusManager.h"
 #include "nsFocusManager.h"
 #include "nsIDOMDragEvent.h"
 #include "nsIScrollableFrame.h"
 #include "nsIDocShell.h"
 #include "ImageContainer.h"
 #include "nsIDOMHTMLCollection.h"
 #include "GLContext.h"
+#include "mozilla/MiscEvents.h"
+#include "mozilla/MouseEvents.h"
+#include "mozilla/TextEvents.h"
 
 #include "nsContentCID.h"
 #include "nsWidgetsCID.h"
 static NS_DEFINE_CID(kWidgetCID, NS_CHILD_CID);
 static NS_DEFINE_CID(kAppShellCID, NS_APPSHELL_CID);
 
 #ifdef XP_WIN
 #include <wtypes.h>
--- a/dom/plugins/base/nsPluginNativeWindowOS2.cpp
+++ b/dom/plugins/base/nsPluginNativeWindowOS2.cpp
@@ -4,17 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /*****************************************************************************/
 
 #define INCL_WIN
 #include "os2.h"
 
 #include "nsDebug.h"
-#include "nsGUIEvent.h"
 #include "nsPluginNativeWindow.h"
 #include "nsThreadUtils.h"
 #include "nsAutoPtr.h"
 #include "nsTWeakRef.h"
 
 #define NS_PLUGIN_WINDOW_PROPERTY_ASSOCIATION "MozillaPluginWindowPropertyAssociation"
 #define NS_PLUGIN_CUSTOM_MSG_ID "MozFlashUserRelay"
 #define WM_USER_FLASH WM_USER+1
--- a/dom/plugins/base/nsPluginNativeWindowWin.cpp
+++ b/dom/plugins/base/nsPluginNativeWindowWin.cpp
@@ -1,28 +1,28 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "mozilla/BasicEvents.h"
 #include "mozilla/DebugOnly.h"
 
 #include "windows.h"
 #include "windowsx.h"
 
 // XXXbz windowsx.h defines GetFirstChild, GetNextSibling,
 // GetPrevSibling are macros, apparently... Eeevil.  We have functions
 // called that on some classes, so undef them.
 #undef GetFirstChild
 #undef GetNextSibling
 #undef GetPrevSibling
 
 #include "nsDebug.h"
 
-#include "nsGUIEvent.h"
 #include "nsWindowsDllInterceptor.h"
 #include "nsPluginNativeWindow.h"
 #include "nsThreadUtils.h"
 #include "nsAutoPtr.h"
 #include "nsTWeakRef.h"
 #include "nsCrashOnException.h"
 
 using namespace mozilla;
--- a/dom/plugins/ipc/PluginInstanceParent.h
+++ b/dom/plugins/ipc/PluginInstanceParent.h
@@ -21,17 +21,16 @@
 #include "nsAutoPtr.h"
 #include "nsDataHashtable.h"
 #include "nsHashKeys.h"
 #include "nsRect.h"
 
 #ifdef MOZ_X11
 class gfxXlibSurface;
 #endif
-#include "nsGUIEvent.h"
 #include "mozilla/unused.h"
 
 class gfxASurface;
 
 namespace mozilla {
 namespace layers {
 class ImageContainer;
 class CompositionNotifySink;
--- a/dom/src/events/nsJSEventListener.cpp
+++ b/dom/src/events/nsJSEventListener.cpp
@@ -5,24 +5,24 @@
 #include "nsJSEventListener.h"
 #include "nsJSUtils.h"
 #include "nsString.h"
 #include "nsIServiceManager.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIScriptContext.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIXPConnect.h"
-#include "nsGUIEvent.h"
 #include "nsIMutableArray.h"
 #include "nsVariant.h"
 #include "nsIDOMBeforeUnloadEvent.h"
 #include "nsGkAtoms.h"
 #include "xpcpublic.h"
 #include "nsJSEnvironment.h"
 #include "nsDOMJSUtils.h"
+#include "mozilla/ContentEvents.h"
 #include "mozilla/Likely.h"
 #include "mozilla/dom/UnionTypes.h"
 #include "nsDOMEvent.h"
 
 #ifdef DEBUG
 
 #include "nspr.h" // PR_fprintf
 
--- a/dom/system/gonk/AudioChannelManager.cpp
+++ b/dom/system/gonk/AudioChannelManager.cpp
@@ -1,13 +1,14 @@
 /* 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 "nsIDOMClassInfo.h"
+#include "nsIDOMEvent.h"
 #include "nsIDOMEventListener.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDocShell.h"
 #include "nsIPermissionManager.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "AudioChannelManager.h"
 #include "mozilla/dom/AudioChannelManagerBinding.h"
 
--- a/dom/webidl/MediaStreamEvent.webidl
+++ b/dom/webidl/MediaStreamEvent.webidl
@@ -7,13 +7,12 @@
  * http://dev.w3.org/2011/webrtc/editor/webrtc.html#mediastreamevent
  */
 
 dictionary MediaStreamEventInit : EventInit {
     MediaStream? stream = null;
 };
 
 [Pref="media.peerconnection.enabled",
- JSImplementation="@mozilla.org/dom/mediastreamevent;1",
  Constructor(DOMString type, optional MediaStreamEventInit eventInitDict)]
 interface MediaStreamEvent : Event {
   readonly attribute MediaStream? stream;
 };
--- a/dom/webidl/RTCDataChannelEvent.webidl
+++ b/dom/webidl/RTCDataChannelEvent.webidl
@@ -9,13 +9,12 @@
 
 interface RTCDataChannel;
 
 dictionary RTCDataChannelEventInit : EventInit {
     RTCDataChannel? channel = null;
 };
 
 [Pref="media.peerconnection.enabled",
- JSImplementation="@mozilla.org/dom/datachannelevent;1",
  Constructor(DOMString type, optional RTCDataChannelEventInit eventInitDict)]
 interface RTCDataChannelEvent : Event {
   readonly attribute RTCDataChannel? channel;
 };
--- a/dom/webidl/RTCPeerConnectionIceEvent.webidl
+++ b/dom/webidl/RTCPeerConnectionIceEvent.webidl
@@ -7,14 +7,13 @@
  * http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCPeerConnectionIceEvent
  */
 
 dictionary RTCPeerConnectionIceEventInit : EventInit {
   mozRTCIceCandidate? candidate = null;
 };
 
 [Pref="media.peerconnection.enabled",
- JSImplementation="@mozilla.org/dom/rtcpeerconnectioniceevent;1",
  Constructor(DOMString type,
              optional RTCPeerConnectionIceEventInit eventInitDict)]
 interface RTCPeerConnectionIceEvent : Event {
   readonly attribute mozRTCIceCandidate? candidate;
 };
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -198,17 +198,16 @@ WEBIDL_FILES = [
     'Location.webidl',
     'MediaElementAudioSourceNode.webidl',
     'MediaError.webidl',
     'MediaRecorder.webidl',
     'MediaSource.webidl',
     'MediaStream.webidl',
     'MediaStreamAudioDestinationNode.webidl',
     'MediaStreamAudioSourceNode.webidl',
-    'MediaStreamEvent.webidl',
     'MediaStreamTrack.webidl',
     'MessageChannel.webidl',
     'MessageEvent.webidl',
     'MessagePort.webidl',
     'MessagePortList.webidl',
     'MimeType.webidl',
     'MimeTypeArray.webidl',
     'MobileMessageManager.webidl',
@@ -248,20 +247,18 @@ WEBIDL_FILES = [
     'PositionError.webidl',
     'ProcessingInstruction.webidl',
     'Promise.webidl',
     'PushManager.webidl',
     'Range.webidl',
     'Rect.webidl',
     'RGBColor.webidl',
     'RTCConfiguration.webidl',
-    'RTCDataChannelEvent.webidl',
     'RTCIceCandidate.webidl',
     'RTCPeerConnection.webidl',
-    'RTCPeerConnectionIceEvent.webidl',
     'RTCSessionDescription.webidl',
     'Screen.webidl',
     'ScriptProcessorNode.webidl',
     'ScrollAreaEvent.webidl',
     'SettingsManager.webidl',
     'SimpleGestureEvent.webidl',
     'SourceBuffer.webidl',
     'SourceBufferList.webidl',
@@ -536,16 +533,19 @@ if CONFIG['MOZ_B2G']:
     WEBIDL_FILES += [
         'InputMethod.webidl',
     ]
 
 GENERATED_EVENTS_WEBIDL_FILES = [
     'BlobEvent.webidl',
     'DeviceLightEvent.webidl',
     'DeviceProximityEvent.webidl',
+    'MediaStreamEvent.webidl',
+    'RTCDataChannelEvent.webidl',
+    'RTCPeerConnectionIceEvent.webidl',
     'UserProximityEvent.webidl',
 ]
 
 if CONFIG['MOZ_GAMEPAD']:
     GENERATED_EVENTS_WEBIDL_FILES += [
         'GamepadAxisMoveEvent.webidl',
         'GamepadButtonEvent.webidl',
         'GamepadEvent.webidl',
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -28,26 +28,26 @@
 #include "nsPrintfCString.h"
 #include "nsHostObjectProtocolHandler.h"
 
 #include <algorithm>
 #include "jsfriendapi.h"
 #include "js/OldDebugAPI.h"
 #include "js/MemoryMetrics.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/ContentEvents.h"
 #include "mozilla/Likely.h"
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/dom/ImageData.h"
 #include "mozilla/dom/ImageDataBinding.h"
 #include "nsAlgorithm.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsError.h"
 #include "nsDOMJSUtils.h"
-#include "nsGUIEvent.h"
 #include "nsJSEnvironment.h"
 #include "nsJSUtils.h"
 #include "nsNetUtil.h"
 #include "nsProxyRelease.h"
 #include "nsSandboxFlags.h"
 #include "nsThreadUtils.h"
 #include "xpcpublic.h"
 
--- a/editor/libeditor/base/IMETextTxn.cpp
+++ b/editor/libeditor/base/IMETextTxn.cpp
@@ -1,20 +1,20 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "IMETextTxn.h"
 #include "mozilla/mozalloc.h"           // for operator new
+#include "mozilla/TextEvents.h"      // for nsTextRangeStyle
 #include "nsAString.h"                  // for nsAString_internal::Length, etc
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsDebug.h"                    // for NS_ASSERTION, etc
 #include "nsError.h"                    // for NS_SUCCEEDED, NS_FAILED, etc
-#include "nsGUIEvent.h"                 // for nsTextRangeStyle
 #include "nsIDOMCharacterData.h"        // for nsIDOMCharacterData
 #include "nsIDOMRange.h"                // for nsRange::SetEnd, etc
 #include "nsIContent.h"                 // for nsIContent
 #include "nsIEditor.h"                  // for nsIEditor
 #include "nsIPresShell.h"               // for SelectionType
 #include "nsIPrivateTextRange.h"        // for nsIPrivateTextRange, etc
 #include "nsISelection.h"               // for nsISelection
 #include "nsISelectionController.h"     // for nsISelectionController, etc
--- a/editor/libeditor/base/nsEditor.cpp
+++ b/editor/libeditor/base/nsEditor.cpp
@@ -22,16 +22,17 @@
 #include "PlaceholderTxn.h"             // for PlaceholderTxn
 #include "SplitElementTxn.h"            // for SplitElementTxn
 #include "mozFlushType.h"               // for mozFlushType::Flush_Frames
 #include "mozISpellCheckingEngine.h"
 #include "mozInlineSpellChecker.h"      // for mozInlineSpellChecker
 #include "mozilla/Preferences.h"        // for Preferences
 #include "mozilla/Selection.h"          // for Selection, etc
 #include "mozilla/Services.h"           // for GetObserverService
+#include "mozilla/TextEvents.h"
 #include "mozilla/dom/Element.h"        // for Element, nsINode::AsElement
 #include "mozilla/mozalloc.h"           // for operator new, etc
 #include "nsAString.h"                  // for nsAString_internal::Length, etc
 #include "nsCCUncollectableMarker.h"    // for nsCCUncollectableMarker
 #include "nsCaret.h"                    // for nsCaret
 #include "nsCaseTreatment.h"
 #include "nsCharTraits.h"               // for NS_IS_HIGH_SURROGATE, etc
 #include "nsComponentManagerUtils.h"    // for do_CreateInstance
@@ -41,17 +42,16 @@
 #include "nsDebug.h"                    // for NS_ENSURE_TRUE, etc
 #include "nsEditProperty.h"             // for nsEditProperty, etc
 #include "nsEditor.h"
 #include "nsEditorEventListener.h"      // for nsEditorEventListener
 #include "nsEditorUtils.h"              // for nsAutoRules, etc
 #include "nsError.h"                    // for NS_OK, etc
 #include "nsFocusManager.h"             // for nsFocusManager
 #include "nsFrameSelection.h"           // for nsFrameSelection
-#include "nsGUIEvent.h"                 // for nsKeyEvent, nsEvent, etc
 #include "nsGkAtoms.h"                  // for nsGkAtoms, nsGkAtoms::dir
 #include "nsIAbsorbingTransaction.h"    // for nsIAbsorbingTransaction
 #include "nsIAtom.h"                    // for nsIAtom
 #include "nsIContent.h"                 // for nsIContent
 #include "nsIDOMAttr.h"                 // for nsIDOMAttr
 #include "nsIDOMCharacterData.h"        // for nsIDOMCharacterData
 #include "nsIDOMDocument.h"             // for nsIDOMDocument
 #include "nsIDOMElement.h"              // for nsIDOMElement
--- a/editor/libeditor/base/nsEditorEventListener.cpp
+++ b/editor/libeditor/base/nsEditorEventListener.cpp
@@ -8,17 +8,16 @@
 #include "mozilla/dom/Element.h"        // for Element
 #include "nsAString.h"
 #include "nsCaret.h"                    // for nsCaret
 #include "nsDebug.h"                    // for NS_ENSURE_TRUE, etc
 #include "nsEditor.h"                   // for nsEditor, etc
 #include "nsEditorEventListener.h"
 #include "nsEventListenerManager.h"     // for nsEventListenerManager
 #include "nsFocusManager.h"             // for nsFocusManager
-#include "nsGUIEvent.h"                 // for NS_EVENT_FLAG_BUBBLE, etc
 #include "nsGkAtoms.h"                  // for nsGkAtoms, nsGkAtoms::input
 #include "nsIClipboard.h"               // for nsIClipboard, etc
 #include "nsIContent.h"                 // for nsIContent
 #include "nsID.h"
 #include "nsIDOMDOMStringList.h"        // for nsIDOMDOMStringList
 #include "nsIDOMDataTransfer.h"         // for nsIDOMDataTransfer
 #include "nsIDOMDocument.h"             // for nsIDOMDocument
 #include "nsIDOMDragEvent.h"            // for nsIDOMDragEvent
--- a/editor/libeditor/html/nsHTMLDataTransfer.cpp
+++ b/editor/libeditor/html/nsHTMLDataTransfer.cpp
@@ -21,17 +21,16 @@
 #include "nsContentUtils.h"
 #include "nsDebug.h"
 #include "nsDependentSubstring.h"
 #include "nsEditProperty.h"
 #include "nsEditRules.h"
 #include "nsEditor.h"
 #include "nsEditorUtils.h"
 #include "nsError.h"
-#include "nsGUIEvent.h"
 #include "nsGkAtoms.h"
 #include "nsHTMLEditUtils.h"
 #include "nsHTMLEditor.h"
 #include "nsIClipboard.h"
 #include "nsIContent.h"
 #include "nsIContentFilter.h"
 #include "nsIDOMComment.h"
 #include "nsIDOMDOMStringList.h"
--- a/editor/libeditor/html/nsHTMLEditor.cpp
+++ b/editor/libeditor/html/nsHTMLEditor.cpp
@@ -1,14 +1,15 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/DebugOnly.h"
+#include "mozilla/TextEvents.h"
 
 #include "nsCRT.h"
 
 #include "nsUnicharUtils.h"
 
 #include "nsHTMLEditor.h"
 #include "nsHTMLEditRules.h"
 #include "nsTextEditUtils.h"
@@ -22,16 +23,17 @@
 #include "nsIDOMText.h"
 #include "nsIDOMMozNamedAttrMap.h"
 #include "nsIDOMNodeList.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMAttr.h"
 #include "nsIDocumentInlines.h"
 #include "nsIDOMEventTarget.h" 
 #include "nsIDOMKeyEvent.h"
+#include "nsIDOMMouseEvent.h"
 #include "nsIDOMHTMLAnchorElement.h"
 #include "nsISelectionController.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsILinkHandler.h"
 #include "nsIInlineSpellChecker.h"
 
 #include "mozilla/css/Loader.h"
 #include "nsCSSStyleSheet.h"
--- a/editor/libeditor/text/nsPlaintextDataTransfer.cpp
+++ b/editor/libeditor/text/nsPlaintextDataTransfer.cpp
@@ -1,24 +1,24 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "mozilla/MouseEvents.h"
 #include "mozilla/Util.h"
 #include "nsAString.h"
 #include "nsCOMPtr.h"
 #include "nsCRT.h"
 #include "nsComponentManagerUtils.h"
 #include "nsContentUtils.h"
 #include "nsDebug.h"
 #include "nsEditor.h"
 #include "nsEditorUtils.h"
 #include "nsError.h"
-#include "nsGUIEvent.h"
 #include "nsIClipboard.h"
 #include "nsIContent.h"
 #include "nsIDOMDataTransfer.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMDragEvent.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMNode.h"
 #include "nsIDOMRange.h"
--- a/editor/libeditor/text/nsPlaintextEditor.cpp
+++ b/editor/libeditor/text/nsPlaintextEditor.cpp
@@ -2,32 +2,32 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 
 #include "mozilla/Assertions.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Selection.h"
+#include "mozilla/TextEvents.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/mozalloc.h"
 #include "nsAString.h"
 #include "nsAutoPtr.h"
 #include "nsCRT.h"
 #include "nsCaret.h"
 #include "nsCharTraits.h"
 #include "nsComponentManagerUtils.h"
 #include "nsContentCID.h"
 #include "nsCopySupport.h"
 #include "nsDebug.h"
 #include "nsDependentSubstring.h"
 #include "nsEditRules.h"
 #include "nsEditorUtils.h"  // nsAutoEditBatch, nsAutoRules
 #include "nsError.h"
-#include "nsGUIEvent.h"
 #include "nsGkAtoms.h"
 #include "nsIClipboard.h"
 #include "nsIContent.h"
 #include "nsIContentIterator.h"
 #include "nsIDOMCharacterData.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMEventTarget.h" 
--- a/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp
+++ b/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp
@@ -13,17 +13,16 @@
 #include "nsHTMLReflowState.h"
 #include "nsIServiceManager.h"
 #include "nsComponentManagerUtils.h"
 #include "nsXPIDLString.h"
 #include "nsIAtom.h"
 #include "nsReadableUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsISimpleEnumerator.h"
-#include "nsGUIEvent.h"
 #include "mozilla/LookAndFeel.h"
 
 // Interfaces needed to be included
 #include "nsPresContext.h"
 #include "nsIContextMenuListener.h"
 #include "nsIContextMenuListener2.h"
 #include "nsITooltipListener.h"
 #include "nsIDOMNode.h"
--- a/embedding/browser/webBrowser/nsWebBrowser.cpp
+++ b/embedding/browser/webBrowser/nsWebBrowser.cpp
@@ -21,17 +21,16 @@
 #include "nsIWebBrowserChrome.h"
 #include "nsPIDOMWindow.h"
 #include "nsIWebProgress.h"
 #include "nsIWebProgressListener.h"
 #include "nsIWebBrowserFocus.h"
 #include "nsIWebBrowserStream.h"
 #include "nsIPresShell.h"
 #include "nsIURIContentListener.h"
-#include "nsGUIEvent.h"
 #include "nsISHistoryListener.h"
 #include "nsIURI.h"
 #include "nsIWebBrowserPersist.h"
 #include "nsCWebBrowserPersist.h"
 #include "nsIServiceManager.h"
 #include "nsAutoPtr.h"
 #include "nsFocusManager.h"
 #include "Layers.h"
--- a/embedding/components/windowwatcher/src/nsAutoWindowStateHelper.cpp
+++ b/embedding/components/windowwatcher/src/nsAutoWindowStateHelper.cpp
@@ -1,23 +1,21 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsAutoWindowStateHelper.h"
 
 #include "nsDOMEvent.h"
-#include "nsGUIEvent.h"
 #include "nsIDocument.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsString.h"
-#include "nsGUIEvent.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 /****************************************************************
  ****************** nsAutoWindowStateHelper *********************
  ****************************************************************/
 
--- a/extensions/spellcheck/src/mozInlineSpellChecker.cpp
+++ b/extensions/spellcheck/src/mozInlineSpellChecker.cpp
@@ -54,17 +54,16 @@
 #include "nsISelectionController.h"
 #include "nsIServiceManager.h"
 #include "nsITextServicesFilter.h"
 #include "nsString.h"
 #include "nsThreadUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsIContent.h"
 #include "nsEventListenerManager.h"
-#include "nsGUIEvent.h"
 #include "nsRange.h"
 #include "nsContentUtils.h"
 #include "nsEditor.h"
 #include "mozilla/Services.h"
 #include "nsIObserverService.h"
 #include "nsITextControlElement.h"
 
 using namespace mozilla::dom;
--- a/extensions/widgetutils/src/nsWidgetUtils.cpp
+++ b/extensions/widgetutils/src/nsWidgetUtils.cpp
@@ -29,22 +29,22 @@
 #include "nsIObserverService.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMCompositionListener.h"
 #include "nsIDOMTextListener.h"
 #include "nsIDOMMouseEvent.h"
 #include "nsIDOMWheelEvent.h"
 #include "nsView.h"
-#include "nsGUIEvent.h"
 #include "nsViewManager.h"
 #include "nsIContentPolicy.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIContent.h"
 #include "nsITimer.h"
+#include "mozilla/MouseEvents.h"
 
 using namespace mozilla;
 
 const int MIN_INT =((int) (1 << (sizeof(int) * 8 - 1)));
 
 static int g_lastX=MIN_INT;
 static int g_lastY=MIN_INT;
 static int32_t g_panning = 0;
--- a/gfx/layers/ThebesLayerBuffer.cpp
+++ b/gfx/layers/ThebesLayerBuffer.cpp
@@ -594,17 +594,17 @@ ThebesLayerBuffer::BeginPaint(ThebesLaye
       // pixels are sampled
       neededRegion = destBufferRect;
     }
 
     // If we have an existing buffer, but the content type has changed or we
     // have transitioned into/out of component alpha, then we need to recreate it.
     if (HaveBuffer() &&
         (contentType != BufferContentType() ||
-         mode == Layer::SURFACE_COMPONENT_ALPHA) != (HaveBufferOnWhite())) {
+        (mode == Layer::SURFACE_COMPONENT_ALPHA) != HaveBufferOnWhite())) {
 
       // We're effectively clearing the valid region, so we need to draw
       // the entire needed region now.
       result.mRegionToInvalidate = aLayer->GetValidRegion();
       validRegion.SetEmpty();
       Clear();
       // Restart decision process with the cleared buffer. We can only go
       // around the loop one more iteration, since mBuffer is null now.
--- a/gfx/layers/composite/APZCTreeManager.cpp
+++ b/gfx/layers/composite/APZCTreeManager.cpp
@@ -8,18 +8,19 @@
 #include "Compositor.h"                 // for Compositor
 #include "CompositorParent.h"           // for CompositorParent, etc
 #include "InputData.h"                  // for InputData, etc
 #include "Layers.h"                     // for ContainerLayer, Layer, etc
 #include "gfx3DMatrix.h"                // for gfx3DMatrix
 #include "mozilla/dom/Touch.h"          // for Touch
 #include "mozilla/gfx/Point.h"          // for Point
 #include "mozilla/layers/AsyncPanZoomController.h"
+#include "mozilla/MouseEvents.h"
 #include "mozilla/mozalloc.h"           // for operator new
-#include "nsGUIEvent.h"                 // for nsMouseEvent, nsTouchEvent, etc
+#include "mozilla/TouchEvents.h"
 #include "nsPoint.h"                    // for nsIntPoint
 #include "nsTArray.h"                   // for nsTArray, nsTArray_Impl, etc
 #include "nsThreadUtils.h"              // for NS_IsMainThread
 
 #define APZC_LOG(...)
 // #define APZC_LOG(args...) printf_stderr(args)
 
 namespace mozilla {
--- a/gfx/layers/composite/ContentHost.cpp
+++ b/gfx/layers/composite/ContentHost.cpp
@@ -224,38 +224,36 @@ ContentHostBase::SetCompositor(Composito
 
 #ifdef MOZ_DUMP_PAINTING
 
 void
 ContentHostBase::Dump(FILE* aFile,
                       const char* aPrefix,
                       bool aDumpHtml)
 {
+  if (!aDumpHtml) {
+    return;
+  }
   if (!aFile) {
     aFile = stderr;
   }
-  if (aDumpHtml) {
-    fprintf(aFile, "<ul>");
-  }
+  fprintf(aFile, "<ul>");
   if (mDeprecatedTextureHost) {
     fprintf(aFile, "%s", aPrefix);
-    fprintf(aFile, aDumpHtml ? "<li> <a href=" : "Front buffer: ");
+    fprintf(aFile, "<li> <a href=");
     DumpDeprecatedTextureHost(aFile, mDeprecatedTextureHost);
-    fprintf(aFile, aDumpHtml ? "> Front buffer </a></li> " : " ");
+    fprintf(aFile, "> Front buffer </a></li> ");
   }
   if (mDeprecatedTextureHostOnWhite) {
     fprintf(aFile, "%s", aPrefix);
-    fprintf(aFile, aDumpHtml ? "<li> <a href=" : "DeprecatedTextureHost on white: ");
+    fprintf(aFile, "<li> <a href=");
     DumpDeprecatedTextureHost(aFile, mDeprecatedTextureHostOnWhite);
-    fprintf(aFile, aDumpHtml ? "> Front buffer on white </a> </li> " : " ");
+    fprintf(aFile, "> Front buffer on white </a> </li> ");
   }
-  if (aDumpHtml) {
-    fprintf(aFile, "</ul>");
-  }
-
+  fprintf(aFile, "</ul>");
 }
 
 #endif
 
 ContentHostSingleBuffered::~ContentHostSingleBuffered()
 {
   DestroyTextures();
   DestroyFrontHost();
@@ -749,38 +747,36 @@ ContentHostDoubleBuffered::PrintInfo(nsA
 
 #ifdef MOZ_DUMP_PAINTING
 void
 ContentHostDoubleBuffered::Dump(FILE* aFile,
                                 const char* aPrefix,
                                 bool aDumpHtml)
 {
   ContentHostBase::Dump(aFile, aPrefix, aDumpHtml);
+  if (!aDumpHtml) {
+    return;
+  }
   if (!aFile) {
     aFile = stderr;
   }
-  if (aDumpHtml) {
-    fprintf(aFile, "<ul>");
-  }
+  fprintf(aFile, "<ul>");
   if (mBackHost) {
     fprintf(aFile, "%s", aPrefix);
-    fprintf(aFile, aDumpHtml ? "<li> <a href=" : "Back buffer: ");
+    fprintf(aFile, "<li> <a href=");
     DumpDeprecatedTextureHost(aFile, mBackHost);
-    fprintf(aFile, aDumpHtml ? " >Back buffer</a></li>" : " ");
+    fprintf(aFile, " >Back buffer</a></li>");
   }
   if (mBackHostOnWhite) {
     fprintf(aFile, "%s", aPrefix);
-    fprintf(aFile, aDumpHtml ? "<li> <a href=" : "Back buffer on white: ");
+    fprintf(aFile, "<li> <a href=");
     DumpDeprecatedTextureHost(aFile, mBackHostOnWhite);
-    fprintf(aFile, aDumpHtml ? " >Back buffer on white</a> </li>" : " ");
+    fprintf(aFile, " >Back buffer on white</a> </li>");
   }
-  if (aDumpHtml) {
-    fprintf(aFile, "</ul>");
-  }
-
+  fprintf(aFile, "</ul>");
 }
 #endif
 
 LayerRenderState
 ContentHostBase::GetRenderState()
 {
   LayerRenderState result = mDeprecatedTextureHost->GetRenderState();
 
--- a/gfx/layers/composite/ThebesLayerComposite.cpp
+++ b/gfx/layers/composite/ThebesLayerComposite.cpp
@@ -109,17 +109,19 @@ ThebesLayerComposite::RenderLayer(const 
 
   gfx::Matrix4x4 transform;
   ToMatrix4x4(GetEffectiveTransform(), transform);
   gfx::Rect clipRect(aClipRect.x, aClipRect.y, aClipRect.width, aClipRect.height);
 
 #ifdef MOZ_DUMP_PAINTING
   if (gfxUtils::sDumpPainting) {
     nsRefPtr<gfxImageSurface> surf = mBuffer->GetAsSurface();
-    WriteSnapshotToDumpFile(this, surf);
+    if (surf) {
+      WriteSnapshotToDumpFile(this, surf);
+    }
   }
 #endif
 
   EffectChain effectChain;
   LayerManagerComposite::AutoAddMaskEffect autoMaskEffect(mMaskLayer, effectChain);
 
   nsIntRegion visibleRegion = GetEffectiveVisibleRegion();
 
@@ -153,17 +155,17 @@ ThebesLayerComposite::RenderLayer(const 
   }
 
   mCompositeManager->GetCompositor()->MakeCurrent();
 }
 
 CompositableHost*
 ThebesLayerComposite::GetCompositableHost()
 {
-  if ( mBuffer && mBuffer->IsAttached()) {
+  if (mBuffer && mBuffer->IsAttached()) {
     return mBuffer.get();
   }
 
   return nullptr;
 }
 
 void
 ThebesLayerComposite::CleanupResources()
--- a/gfx/layers/ipc/AsyncPanZoomController.cpp
+++ b/gfx/layers/ipc/AsyncPanZoomController.cpp
@@ -16,16 +16,17 @@
 #include "InputData.h"                  // for MultiTouchInput, etc
 #include "Units.h"                      // for CSSRect, CSSPoint, etc
 #include "base/message_loop.h"          // for MessageLoop
 #include "base/task.h"                  // for NewRunnableMethod, etc
 #include "base/tracked.h"               // for FROM_HERE
 #include "gfxTypes.h"                   // for gfxFloat
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/ClearOnShutdown.h"    // for ClearOnShutdown
+#include "mozilla/EventForwards.h"      // for nsEventStatus_*
 #include "mozilla/Preferences.h"        // for Preferences
 #include "mozilla/ReentrantMonitor.h"   // for ReentrantMonitorAutoEnter, etc
 #include "mozilla/StaticPtr.h"          // for StaticAutoPtr
 #include "mozilla/TimeStamp.h"          // for TimeDuration, TimeStamp
 #include "mozilla/dom/Touch.h"          // for Touch
 #include "mozilla/gfx/BasePoint.h"      // for BasePoint
 #include "mozilla/gfx/BaseRect.h"       // for BaseRect
 #include "mozilla/gfx/Point.h"          // for Point, RoundedToInt, etc
@@ -36,17 +37,16 @@
 #include "mozilla/layers/Axis.h"        // for AxisX, AxisY, Axis, etc
 #include "mozilla/layers/GeckoContentController.h"
 #include "mozilla/layers/TaskThrottler.h"  // for TaskThrottler
 #include "mozilla/mozalloc.h"           // for operator new, etc
 #include "nsAlgorithm.h"                // for clamped
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsDebug.h"                    // for NS_WARNING
-#include "nsGUIEvent.h"                 // for nsInputEvent, nsTouchEvent, etc
 #include "nsISupportsImpl.h"
 #include "nsMathUtils.h"                // for NS_hypot
 #include "nsPoint.h"                    // for nsIntPoint
 #include "nsStyleConsts.h"
 #include "nsStyleStruct.h"              // for nsTimingFunction
 #include "nsTArray.h"                   // for nsTArray, nsTArray_Impl, etc
 #include "nsThreadUtils.h"              // for NS_IsMainThread
 #include "nsTraceRefcnt.h"              // for MOZ_COUNT_CTOR, etc
--- a/gfx/layers/opengl/TextureHostOGL.cpp
+++ b/gfx/layers/opengl/TextureHostOGL.cpp
@@ -1083,24 +1083,23 @@ void GrallocDeprecatedTextureHostOGL::Se
     DeleteTextures();
   }
   mCompositor = glCompositor;
 }
 
 gfx::SurfaceFormat
 GrallocDeprecatedTextureHostOGL::GetFormat() const
 {
-  if (mTextureTarget == LOCAL_GL_TEXTURE_EXTERNAL) {
-    return gfx::FORMAT_R8G8B8A8;
+  switch (mTextureTarget) {
+  case LOCAL_GL_TEXTURE_EXTERNAL: return gfx::FORMAT_R8G8B8A8;
+  case LOCAL_GL_TEXTURE_2D: return mFormat;
+  default: return gfx::FORMAT_UNKNOWN;
   }
-  MOZ_ASSERT(mTextureTarget == LOCAL_GL_TEXTURE_2D);
-  return mFormat;
 }
 
-
 void
 GrallocDeprecatedTextureHostOGL::DeleteTextures()
 {
   if (mEGLImage) {
     gl()->MakeCurrent();
     gl()->DestroyEGLImage(mEGLImage);
     mEGLImage = 0;
   }
new file mode 100644
--- /dev/null
+++ b/gfx/tests/gtest/TestTextures.cpp
@@ -0,0 +1,144 @@
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+#include "gtest/gtest.h"
+#include "gmock/gmock.h"
+
+#include "mozilla/layers/TextureClient.h"
+#include "mozilla/layers/TextureHost.h"
+#include "gfx2DGlue.h"
+#include "gfxImageSurface.h"
+#include "gfxTypes.h"
+
+using namespace gfx;
+using namespace mozilla;
+using namespace mozilla::layers;
+
+/*
+ * This test performs the following actions:
+ * - creates a surface
+ * - initialize a texture client with it
+ * - serilaizes the texture client
+ * - deserializes the data into a texture host
+ * - reads the surface from the texture host.
+ *
+ * The surface in the end should be equal to the inital one.
+ * This test is run for different combinations of texture types and
+ * image formats.
+ */
+
+
+// fills the surface with values betwee 0 and 100.
+void SetupSurface(gfxImageSurface* surface) {
+  int bpp = gfxASurface::BytePerPixelFromFormat(surface->Format());
+  int stride = surface->Stride();
+  uint8_t val = 0;
+  uint8_t* data = surface->Data();
+  for (int y = 0; y < surface->Height(); ++y) {
+    for (int x = 0; x < surface->Height(); ++x) {
+      for (int b = 0; b < bpp; ++b) {
+        data[y*stride + x*bpp + b] = val;
+        if (val == 100) {
+          val = 0;
+        } else {
+          ++val;
+        }
+      }
+    }
+  }
+}
+
+// return true if two surfaces contain the same data
+void AssertSurfacesEqual(gfxImageSurface* surface1,
+                         gfxImageSurface* surface2)
+{
+  ASSERT_EQ(surface1->GetSize(), surface2->GetSize());
+  ASSERT_EQ(surface1->Format(), surface2->Format());
+
+  uint8_t* data1 = surface1->Data();
+  uint8_t* data2 = surface2->Data();
+  int stride1 = surface1->Stride();
+  int stride2 = surface2->Stride();
+  int bpp = gfxASurface::BytePerPixelFromFormat(surface1->Format());
+
+  for (int y = 0; y < surface1->Height(); ++y) {
+    for (int x = 0; x < surface1->Width(); ++x) {
+      for (int b = 0; b < bpp; ++b) {
+        ASSERT_EQ(data1[y*stride1 + x*bpp + b],
+                  data2[y*stride2 + x*bpp + b]);
+      }
+    }
+  }
+}
+
+// Run the test for a texture client and a surface
+void TestTextureClientSurface(TextureClient* texture, gfxImageSurface* surface) {
+
+  // client allocation
+  ASSERT_TRUE(texture->AsTextureClientSurface() != nullptr);
+  TextureClientSurface* client = texture->AsTextureClientSurface();
+  client->AllocateForSurface(ToIntSize(surface->GetSize()));
+  ASSERT_TRUE(texture->IsAllocated());
+
+  // client painting
+  client->UpdateSurface(surface);
+
+  nsRefPtr<gfxASurface> aSurface = client->GetAsSurface();
+  nsRefPtr<gfxImageSurface> clientSurface = aSurface->GetAsImageSurface();
+
+  ASSERT_TRUE(texture->Lock(OPEN_READ_ONLY));
+  AssertSurfacesEqual(surface, clientSurface);
+  texture->Unlock();
+
+  // client serialization
+  texture->SetID(1);
+  SurfaceDescriptor descriptor;
+  ASSERT_TRUE(texture->ToSurfaceDescriptor(descriptor));
+
+  ASSERT_NE(descriptor.type(), SurfaceDescriptor::Tnull_t);
+
+  // host deserialization
+  RefPtr<TextureHost> host = CreateBackendIndependentTextureHost(texture->GetID(),
+                                                                 descriptor, nullptr,
+                                                                 texture->GetFlags());
+
+  ASSERT_TRUE(host.get() != nullptr);
+  ASSERT_EQ(host->GetFlags(), texture->GetFlags());
+  ASSERT_EQ(host->GetID(), texture->GetID());
+
+  // host read
+  ASSERT_TRUE(host->Lock());
+  nsRefPtr<gfxImageSurface> hostSurface = host->GetAsSurface();
+  host->Unlock();
+
+  AssertSurfacesEqual(surface, hostSurface.get());
+
+  // host deallocation
+  host->DeallocateSharedData();
+}
+
+TEST(Layers, TextureSerialization) {
+  // the test is run on all the following image formats
+  gfxImageFormat formats[3] = {
+    gfxImageFormatARGB32,
+    gfxImageFormatRGB24,
+    gfxImageFormatA8,
+  };
+
+  for (int f = 0; f < 3; ++f) {
+    RefPtr<gfxImageSurface> surface = new gfxImageSurface(gfxIntSize(400,300), formats[f]);
+    SetupSurface(surface.get());
+    AssertSurfacesEqual(surface, surface);
+
+    RefPtr<TextureClient> client
+      = new MemoryTextureClient(nullptr,
+                                mozilla::gfx::ImageFormatToSurfaceFormat(surface->Format()),
+                                TEXTURE_FLAGS_DEFAULT);
+
+    TestTextureClientSurface(client, surface);
+
+    // XXX - Test more texture client types.
+  }
+}
--- a/gfx/tests/gtest/moz.build
+++ b/gfx/tests/gtest/moz.build
@@ -15,16 +15,17 @@ GTEST_CPP_SOURCES += [
     # Test works but it doesn't assert anything
     #'gfxTextRunPerfTest.cpp',
     'gfxWordCacheTest.cpp',
     'TestAsyncPanZoomController.cpp',
     'TestLayers.cpp',
     'TestTiledLayerBuffer.cpp',
     'TestRegion.cpp',
     'TestColorNames.cpp',
+    'TestTextures.cpp',
 ]
 
 # Because of gkmedia on windows we wont find these
 # symbols in xul.dll.
 if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'windows':
     GTEST_CPP_SOURCES += [
         'TestBase.cpp',
         'TestMoz2D.cpp',
--- a/gfx/thebes/gfxWindowsSurface.cpp
+++ b/gfx/thebes/gfxWindowsSurface.cpp
@@ -55,22 +55,22 @@ gfxWindowsSurface::gfxWindowsSurface(con
     if (!CheckSurfaceSize(size))
         MakeInvalid(size);
 
     cairo_surface_t *surf = cairo_win32_surface_create_with_dib((cairo_format_t)imageFormat,
                                                                 size.width, size.height);
 
     Init(surf);
 
-    RecordMemoryUsed(size.width * size.height * 4 + sizeof(gfxWindowsSurface));
-
-    if (CairoStatus() == 0)
+    if (CairoStatus() == CAIRO_STATUS_SUCCESS) {
         mDC = cairo_win32_surface_get_dc(CairoSurface());
-    else
+        RecordMemoryUsed(size.width * size.height * 4 + sizeof(gfxWindowsSurface));
+    } else {
         mDC = nullptr;
+    }
 }
 
 gfxWindowsSurface::gfxWindowsSurface(HDC dc, const gfxIntSize& realSize, gfxImageFormat imageFormat) :
     mOwnsDC(false), mForPrinting(false), mWnd(nullptr)
 {
     gfxIntSize size(realSize);
     if (!CheckSurfaceSize(size))
         MakeInvalid(size);
--- a/image/src/imgLoader.cpp
+++ b/image/src/imgLoader.cpp
@@ -132,17 +132,17 @@ public:
            nsIMemoryReporter::KIND_NONHEAP, content.mUnusedUncompressedNonheap,
            "Memory used by not in-use content images (uncompressed data).");
 
 #undef REPORT
 
     return NS_OK;
   }
 
-  static int64_t GetImagesContentUsedUncompressed()
+  static int64_t ImagesContentUsedUncompressedDistinguishedAmount()
   {
     size_t n = 0;
     for (uint32_t i = 0; i < imgLoader::sMemReporter->mKnownLoaders.Length(); i++) {
       imgLoader::sMemReporter->mKnownLoaders[i]->mCache.EnumerateRead(EntryUsedUncompressedSize, &n);
     }
     return n;
   }
 
@@ -218,36 +218,16 @@ private:
     }
 
     return PL_DHASH_NEXT;
   }
 };
 
 NS_IMPL_ISUPPORTS1(imgMemoryReporter, nsIMemoryReporter)
 
-// This is used by telemetry.
-class ImagesContentUsedUncompressedReporter MOZ_FINAL
-  : public MemoryUniReporter
-{
-public:
-  ImagesContentUsedUncompressedReporter()
-    : MemoryUniReporter("images-content-used-uncompressed",
-                         KIND_OTHER, UNITS_BYTES,
-"This is the sum of the 'explicit/images/content/used/uncompressed-heap' "
-"and 'explicit/images/content/used/uncompressed-nonheap' numbers.  However, "
-"it is measured at a different time and so may give slightly different "
-"results.")
-  {}
-private:
-  int64_t Amount() MOZ_OVERRIDE
-  {
-    return imgMemoryReporter::GetImagesContentUsedUncompressed();
-  }
-};
-
 NS_IMPL_ISUPPORTS3(nsProgressNotificationProxy,
                      nsIProgressEventSink,
                      nsIChannelEventSink,
                      nsIInterfaceRequestor)
 
 NS_IMETHODIMP
 nsProgressNotificationProxy::OnProgress(nsIRequest* request,
                                         nsISupports* ctxt,
@@ -834,17 +814,17 @@ void imgLoader::GlobalInit()
   rv = Preferences::GetInt("image.cache.size", &cachesize);
   if (NS_SUCCEEDED(rv))
     sCacheMaxSize = cachesize;
   else
     sCacheMaxSize = 5 * 1024 * 1024;
 
   sMemReporter = new imgMemoryReporter();
   NS_RegisterMemoryReporter(sMemReporter);
-  NS_RegisterMemoryReporter(new ImagesContentUsedUncompressedReporter());
+  RegisterImagesContentUsedUncompressedDistinguishedAmount(imgMemoryReporter::ImagesContentUsedUncompressedDistinguishedAmount);
 }
 
 nsresult imgLoader::InitCache()
 {
   nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
   if (!os)
     return NS_ERROR_FAILURE;
 
--- a/image/src/imgRequest.h
+++ b/image/src/imgRequest.h
@@ -9,17 +9,17 @@
 
 #include "nsIChannelEventSink.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIStreamListener.h"
 #include "nsIPrincipal.h"
 
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
-#include "nsString.h"
+#include "nsStringGlue.h"
 #include "nsError.h"
 #include "nsIAsyncVerifyRedirectCallback.h"
 
 class imgCacheValidator;
 class imgStatusTracker;
 class imgLoader;
 class imgRequestProxy;
 class imgCacheEntry;
--- a/intl/locale/public/nsIDateTimeFormat.h
+++ b/intl/locale/public/nsIDateTimeFormat.h
@@ -5,17 +5,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsIDateTimeFormat_h__
 #define nsIDateTimeFormat_h__
 
 
 #include "nsISupports.h"
 #include "nscore.h"
-#include "nsString.h"
+#include "nsStringGlue.h"
 #include "nsILocale.h"
 #include "nsIScriptableDateFormat.h"
 #include "prtime.h"
 #include <time.h>
 
 
 // {2BBAA0B0-A591-11d2-9119-006008A6EDF6}
 #define NS_IDATETIMEFORMAT_IID \
--- a/intl/locale/public/nsIPlatformCharset.h
+++ b/intl/locale/public/nsIPlatformCharset.h
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsIPlatformCharset_h__
 #define nsIPlatformCharset_h__
 
-#include "nsString.h"
+#include "nsStringGlue.h"
 #include "nsISupports.h"
 
 // Interface ID for our nsIPlatformCharset interface
 
 /* 778859d5-fc01-4f4b-bfaa-3c0d1b6c81d6 */
 #define NS_IPLATFORMCHARSET_IID \
 {   0x778859d5, \
     0xfc01, \
--- a/intl/uconv/idl/nsICharsetConverterManager.idl
+++ b/intl/uconv/idl/nsICharsetConverterManager.idl
@@ -4,18 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 #include "nsIAtom.idl"
 
 %{ C++
 #include "nsIUnicodeDecoder.h"
 #include "nsIUnicodeEncoder.h"
-#include "nsString.h"
-
 
 // XXX change to NS_CHARSETCONVERTERMANAGER_CID
 #define NS_ICHARSETCONVERTERMANAGER_CID \
   {0x3c1c0163, 0x9bd0, 0x11d3, { 0x9d, 0x9, 0x0, 0x50, 0x4, 0x0, 0x7, 0xb2}}
 
 // XXX change to NS_CHARSETCONVERTERMANAGER_PID
 #define NS_CHARSETCONVERTERMANAGER_CONTRACTID "@mozilla.org/charset-converter-manager;1"
 %}
--- a/js/src/builtin/Eval.cpp
+++ b/js/src/builtin/Eval.cpp
@@ -81,17 +81,17 @@ EvalCacheHashPolicy::match(const EvalCac
 // an OldDebugAPI  user's perspective, we want each eval() to create and
 // destroy a script. This hides implementation details and means we don't have
 // to deal with calls to JS_GetScriptObject for scripts in the eval cache.
 class EvalScriptGuard
 {
     JSContext *cx_;
     Rooted<JSScript*> script_;
 
-    /* These fields are only valid if lookup_.str is non-NULL. */
+    /* These fields are only valid if lookup_.str is non-nullptr. */
     EvalCacheLookup lookup_;
     EvalCache::AddPtr p_;
 
     Rooted<JSLinearString*> lookupStr_;
 
   public:
     EvalScriptGuard(JSContext *cx)
         : cx_(cx), script_(cx), lookup_(cx), lookupStr_(cx) {}
@@ -234,17 +234,17 @@ EvalKernel(JSContext *cx, const CallArgs
 {
     JS_ASSERT((evalType == INDIRECT_EVAL) == !caller);
     JS_ASSERT((evalType == INDIRECT_EVAL) == !pc);
     JS_ASSERT_IF(evalType == INDIRECT_EVAL, scopeobj->is<GlobalObject>());
     AssertInnerizedScopeChain(cx, *scopeobj);
 
     Rooted<GlobalObject*> scopeObjGlobal(cx, &scopeobj->global());
     if (!GlobalObject::isRuntimeCodeGenEnabled(cx, scopeObjGlobal)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CSP_BLOCKED_EVAL);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CSP_BLOCKED_EVAL);
         return false;
     }
 
     // ES5 15.1.2.1 step 1.
     if (args.length() < 1) {
         args.rval().setUndefined();
         return true;
     }
@@ -286,17 +286,17 @@ EvalKernel(JSContext *cx, const CallArgs
     if (!stableStr)
         return false;
 
     StableCharPtr chars = stableStr->chars();
     size_t length = stableStr->length();
 
     JSPrincipals *principals = PrincipalsForCompiledCode(args, cx);
 
-    RootedScript callerScript(cx, caller ? caller.script() : NULL);
+    RootedScript callerScript(cx, caller ? caller.script() : nullptr);
     EvalJSONResult ejr = TryEvalJSON(cx, callerScript, chars, length, args.rval());
     if (ejr != EvalJSON_NotJSON)
         return ejr == EvalJSON_Success;
 
     EvalScriptGuard esg(cx);
 
     if (evalType == DIRECT_EVAL && caller.isNonEvalFunctionFrame())
         esg.lookupInEvalCache(stableStr, callerScript, pc);
@@ -336,17 +336,17 @@ js::DirectEvalFromIon(JSContext *cx,
                       HandleObject scopeobj, HandleScript callerScript,
                       HandleValue thisValue, HandleString str,
                       jsbytecode *pc, MutableHandleValue vp)
 {
     AssertInnerizedScopeChain(cx, *scopeobj);
 
     Rooted<GlobalObject*> scopeObjGlobal(cx, &scopeobj->global());
     if (!GlobalObject::isRuntimeCodeGenEnabled(cx, scopeObjGlobal)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CSP_BLOCKED_EVAL);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CSP_BLOCKED_EVAL);
         return false;
     }
 
     // ES5 15.1.2.1 steps 2-8.
 
     unsigned staticLevel = callerScript->staticLevel + 1;
 
     Rooted<JSStableString*> stableStr(cx, str->ensureStable(cx));
@@ -400,17 +400,17 @@ js::DirectEvalFromIon(JSContext *cx,
                          NullFramePtr() /* evalInFrame */, vp.address());
 }
 
 bool
 js::IndirectEval(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     Rooted<GlobalObject*> global(cx, &args.callee().global());
-    return EvalKernel(cx, args, INDIRECT_EVAL, NullFramePtr(), global, NULL);
+    return EvalKernel(cx, args, INDIRECT_EVAL, NullFramePtr(), global, nullptr);
 }
 
 bool
 js::DirectEval(JSContext *cx, const CallArgs &args)
 {
     // Direct eval can assume it was called from an interpreted or baseline frame.
     ScriptFrameIter iter(cx);
     AbstractFramePtr caller = iter.abstractFramePtr();
--- a/js/src/builtin/Intl.cpp
+++ b/js/src/builtin/Intl.cpp
@@ -423,17 +423,17 @@ typedef int32_t
 
 typedef const char *
 (* GetAvailable)(int32_t localeIndex);
 
 static bool
 intl_availableLocales(JSContext *cx, CountAvailable countAvailable,
                       GetAvailable getAvailable, MutableHandleValue result)
 {
-    RootedObject locales(cx, NewObjectWithGivenProto(cx, &JSObject::class_, NULL, NULL));
+    RootedObject locales(cx, NewObjectWithGivenProto(cx, &JSObject::class_, nullptr, nullptr));
     if (!locales)
         return false;
 
 #if ENABLE_INTL_API
     uint32_t count = countAvailable();
     RootedValue t(cx, BooleanValue(true));
     for (uint32_t i = 0; i < count; i++) {
         const char *locale = getAvailable(i);
@@ -525,17 +525,17 @@ class ScopedICUObject
             deleter_(ptr_);
     }
 
     // In cases where an object should be deleted on abnormal exits,
     // but returned to the caller if everything goes well, call forget()
     // to transfer the object just before returning.
     T *forget() {
         T *tmp = ptr_;
-        ptr_ = NULL;
+        ptr_ = nullptr;
         return tmp;
     }
 };
 
 // As a small optimization (not important for correctness), this is the inline
 // capacity of a StringBuffer.
 static const size_t INITIAL_STRING_BUFFER_SIZE = 32;
 
@@ -618,17 +618,17 @@ Collator(JSContext *cx, CallArgs args, b
         // 10.1.3.1 paragraph 2
         RootedObject proto(cx, cx->global()->getOrCreateCollatorPrototype(cx));
         if (!proto)
             return false;
         obj = NewObjectWithGivenProto(cx, &CollatorClass, proto, cx->global());
         if (!obj)
             return false;
 
-        obj->setReservedSlot(UCOLLATOR_SLOT, PrivateValue(NULL));
+        obj->setReservedSlot(UCOLLATOR_SLOT, PrivateValue(nullptr));
     }
 
     // 10.1.2.1 steps 1 and 2; 10.1.3.1 steps 1 and 2
     RootedValue locales(cx, args.length() > 0 ? args[0] : UndefinedValue());
     RootedValue options(cx, args.length() > 1 ? args[1] : UndefinedValue());
 
     // 10.1.2.1 step 6; 10.1.3.1 step 3
     if (!IntlInitialize(cx, obj, cx->names().InitializeCollator, locales, options))
@@ -664,72 +664,72 @@ collator_finalize(FreeOp *fop, JSObject 
         ucol_close(coll);
 }
 
 static JSObject *
 InitCollatorClass(JSContext *cx, HandleObject Intl, Handle<GlobalObject*> global)
 {
     RootedFunction ctor(cx, global->createConstructor(cx, &Collator, cx->names().Collator, 0));
     if (!ctor)
-        return NULL;
+        return nullptr;
 
     RootedObject proto(cx, global->as<GlobalObject>().getOrCreateCollatorPrototype(cx));
     if (!proto)
-        return NULL;
+        return nullptr;
     if (!LinkConstructorAndPrototype(cx, ctor, proto))
-        return NULL;
+        return nullptr;
 
     // 10.2.2
     if (!JS_DefineFunctions(cx, ctor, collator_static_methods))
-        return NULL;
+        return nullptr;
 
     // 10.3.2 and 10.3.3
     if (!JS_DefineFunctions(cx, proto, collator_methods))
-        return NULL;
+        return nullptr;
 
     /*
      * Install the getter for Collator.prototype.compare, which returns a bound
      * comparison function for the specified Collator object (suitable for
      * passing to methods like Array.prototype.sort).
      */
     RootedValue getter(cx);
     if (!cx->global()->getIntrinsicValue(cx, cx->names().CollatorCompareGet, &getter))
-        return NULL;
+        return nullptr;
     RootedValue undefinedValue(cx, UndefinedValue());
     if (!JSObject::defineProperty(cx, proto, cx->names().compare, undefinedValue,
                                   JS_DATA_TO_FUNC_PTR(JSPropertyOp, &getter.toObject()),
-                                  NULL, JSPROP_GETTER))
+                                  nullptr, JSPROP_GETTER))
     {
-        return NULL;
+        return nullptr;
     }
 
     // 10.2.1 and 10.3
     RootedValue locales(cx, UndefinedValue());
     RootedValue options(cx, UndefinedValue());
     if (!IntlInitialize(cx, proto, cx->names().InitializeCollator, locales, options))
-        return NULL;
+        return nullptr;
 
     // 8.1
     RootedValue ctorValue(cx, ObjectValue(*ctor));
     if (!JSObject::defineProperty(cx, Intl, cx->names().Collator, ctorValue,
                                   JS_PropertyStub, JS_StrictPropertyStub, 0))
     {
-        return NULL;
+        return nullptr;
     }
 
     return ctor;
 }
 
 bool
 GlobalObject::initCollatorProto(JSContext *cx, Handle<GlobalObject*> global)
 {
     RootedObject proto(cx, global->createBlankPrototype(cx, &CollatorClass));
     if (!proto)
         return false;
-    proto->setReservedSlot(UCOLLATOR_SLOT, PrivateValue(NULL));
+    proto->setReservedSlot(UCOLLATOR_SLOT, PrivateValue(nullptr));
     global->setReservedSlot(COLLATOR_PROTO, ObjectValue(*proto));
     return true;
 }
 
 bool
 js::intl_Collator_availableLocales(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
@@ -750,36 +750,36 @@ js::intl_availableCollations(JSContext *
     JS_ASSERT(args[0].isString());
 
     JSAutoByteString locale(cx, args[0].toString());
     if (!locale)
         return false;
     UErrorCode status = U_ZERO_ERROR;
     UEnumeration *values = ucol_getKeywordValuesForLocale("co", locale.ptr(), false, &status);
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
         return false;
     }
     ScopedICUObject<UEnumeration> toClose(values, uenum_close);
 
     uint32_t count = uenum_count(values, &status);
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
         return false;
     }
 
     RootedObject collations(cx, NewDenseEmptyArray(cx));
     if (!collations)
         return false;
 
     uint32_t index = 0;
     for (uint32_t i = 0; i < count; i++) {
-        const char *collation = uenum_next(values, NULL, &status);
+        const char *collation = uenum_next(values, nullptr, &status);
         if (U_FAILURE(status)) {
-            JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+            JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
             return false;
         }
 
         // Per ECMA-402, 10.2.3, we don't include standard and search:
         // "The values 'standard' and 'search' must not be used as elements in
         // any [[sortLocaleData]][locale].co and [[searchLocaleData]][locale].co
         // array."
         if (equal(collation, "standard") || equal(collation, "search"))
@@ -814,38 +814,38 @@ js::intl_availableCollations(JSContext *
  */
 static UCollator *
 NewUCollator(JSContext *cx, HandleObject collator)
 {
     RootedValue value(cx);
 
     RootedObject internals(cx);
     if (!GetInternals(cx, collator, &internals))
-        return NULL;
+        return nullptr;
 
     if (!JSObject::getProperty(cx, internals, internals, cx->names().locale, &value))
-        return NULL;
+        return nullptr;
     JSAutoByteString locale(cx, value.toString());
     if (!locale)
-        return NULL;
+        return nullptr;
 
     // UCollator options with default values.
     UColAttributeValue uStrength = UCOL_DEFAULT;
     UColAttributeValue uCaseLevel = UCOL_OFF;
     UColAttributeValue uAlternate = UCOL_DEFAULT;
     UColAttributeValue uNumeric = UCOL_OFF;
     // Normalization is always on to meet the canonical equivalence requirement.
     UColAttributeValue uNormalization = UCOL_ON;
     UColAttributeValue uCaseFirst = UCOL_DEFAULT;
 
     if (!JSObject::getProperty(cx, internals, internals, cx->names().usage, &value))
-        return NULL;
+        return nullptr;
     JSAutoByteString usage(cx, value.toString());
     if (!usage)
-        return NULL;
+        return nullptr;
     if (equal(usage, "search")) {
         // ICU expects search as a Unicode locale extension on locale.
         // Unicode locale extensions must occur before private use extensions.
         const char *oldLocale = locale.ptr();
         const char *p;
         size_t index;
         size_t localeLen = strlen(oldLocale);
         if ((p = strstr(oldLocale, "-x-")))
@@ -858,91 +858,91 @@ NewUCollator(JSContext *cx, HandleObject
             index = p - oldLocale + 2;
             insert = "-co-search";
         } else {
             insert = "-u-co-search";
         }
         size_t insertLen = strlen(insert);
         char *newLocale = cx->pod_malloc<char>(localeLen + insertLen + 1);
         if (!newLocale)
-            return NULL;
+            return nullptr;
         memcpy(newLocale, oldLocale, index);
         memcpy(newLocale + index, insert, insertLen);
         memcpy(newLocale + index + insertLen, oldLocale + index, localeLen - index + 1); // '\0'
         locale.clear();
         locale.initBytes(newLocale);
     }
 
     // We don't need to look at the collation property - it can only be set
     // via the Unicode locale extension and is therefore already set on
     // locale.
 
     if (!JSObject::getProperty(cx, internals, internals, cx->names().sensitivity, &value))
-        return NULL;
+        return nullptr;
     JSAutoByteString sensitivity(cx, value.toString());
     if (!sensitivity)
-        return NULL;
+        return nullptr;
     if (equal(sensitivity, "base")) {
         uStrength = UCOL_PRIMARY;
     } else if (equal(sensitivity, "accent")) {
         uStrength = UCOL_SECONDARY;
     } else if (equal(sensitivity, "case")) {
         uStrength = UCOL_PRIMARY;
         uCaseLevel = UCOL_ON;
     } else {
         JS_ASSERT(equal(sensitivity, "variant"));
         uStrength = UCOL_TERTIARY;
     }
 
     if (!JSObject::getProperty(cx, internals, internals, cx->names().ignorePunctuation, &value))
-        return NULL;
+        return nullptr;
     // According to the ICU team, UCOL_SHIFTED causes punctuation to be
     // ignored. Looking at Unicode Technical Report 35, Unicode Locale Data
     // Markup Language, "shifted" causes whitespace and punctuation to be
     // ignored - that's a bit more than asked for, but there's no way to get
     // less.
     if (value.toBoolean())
         uAlternate = UCOL_SHIFTED;
 
     if (!JSObject::getProperty(cx, internals, internals, cx->names().numeric, &value))
-        return NULL;
+        return nullptr;
     if (!value.isUndefined() && value.toBoolean())
         uNumeric = UCOL_ON;
 
     if (!JSObject::getProperty(cx, internals, internals, cx->names().caseFirst, &value))
-        return NULL;
+        return nullptr;
     if (!value.isUndefined()) {
         JSAutoByteString caseFirst(cx, value.toString());
         if (!caseFirst)
-            return NULL;
+            return nullptr;
         if (equal(caseFirst, "upper"))
             uCaseFirst = UCOL_UPPER_FIRST;
         else if (equal(caseFirst, "lower"))
             uCaseFirst = UCOL_LOWER_FIRST;
         else
             JS_ASSERT(equal(caseFirst, "false"));
     }
 
     UErrorCode status = U_ZERO_ERROR;
     UCollator *coll = ucol_open(icuLocale(locale.ptr()), &status);
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
-        return NULL;
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
+        return nullptr;
     }
 
     ucol_setAttribute(coll, UCOL_STRENGTH, uStrength, &status);
     ucol_setAttribute(coll, UCOL_CASE_LEVEL, uCaseLevel, &status);
     ucol_setAttribute(coll, UCOL_ALTERNATE_HANDLING, uAlternate, &status);
     ucol_setAttribute(coll, UCOL_NUMERIC_COLLATION, uNumeric, &status);
     ucol_setAttribute(coll, UCOL_NORMALIZATION_MODE, uNormalization, &status);
     ucol_setAttribute(coll, UCOL_CASE_FIRST, uCaseFirst, &status);
     if (U_FAILURE(status)) {
         ucol_close(coll);
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
-        return NULL;
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
+        return nullptr;
     }
 
     return coll;
 }
 
 static bool
 intl_CompareStrings(JSContext *cx, UCollator *coll, HandleString str1, HandleString str2, MutableHandleValue result)
 {
@@ -1101,17 +1101,17 @@ NumberFormat(JSContext *cx, CallArgs arg
         // 11.1.3.1 paragraph 2
         RootedObject proto(cx, cx->global()->getOrCreateNumberFormatPrototype(cx));
         if (!proto)
             return false;
         obj = NewObjectWithGivenProto(cx, &NumberFormatClass, proto, cx->global());
         if (!obj)
             return false;
 
-        obj->setReservedSlot(UNUMBER_FORMAT_SLOT, PrivateValue(NULL));
+        obj->setReservedSlot(UNUMBER_FORMAT_SLOT, PrivateValue(nullptr));
     }
 
     // 11.1.2.1 steps 1 and 2; 11.1.3.1 steps 1 and 2
     RootedValue locales(cx, args.length() > 0 ? args[0] : UndefinedValue());
     RootedValue options(cx, args.length() > 1 ? args[1] : UndefinedValue());
 
     // 11.1.2.1 step 6; 11.1.3.1 step 3
     if (!IntlInitialize(cx, obj, cx->names().InitializeNumberFormat, locales, options))
@@ -1149,72 +1149,72 @@ numberFormat_finalize(FreeOp *fop, JSObj
         unum_close(nf);
 }
 
 static JSObject *
 InitNumberFormatClass(JSContext *cx, HandleObject Intl, Handle<GlobalObject*> global)
 {
     RootedFunction ctor(cx, global->createConstructor(cx, &NumberFormat, cx->names().NumberFormat, 0));
     if (!ctor)
-        return NULL;
+        return nullptr;
 
     RootedObject proto(cx, global->as<GlobalObject>().getOrCreateNumberFormatPrototype(cx));
     if (!proto)
-        return NULL;
+        return nullptr;
     if (!LinkConstructorAndPrototype(cx, ctor, proto))
-        return NULL;
+        return nullptr;
 
     // 11.2.2
     if (!JS_DefineFunctions(cx, ctor, numberFormat_static_methods))
-        return NULL;
+        return nullptr;
 
     // 11.3.2 and 11.3.3
     if (!JS_DefineFunctions(cx, proto, numberFormat_methods))
-        return NULL;
+        return nullptr;
 
     /*
      * Install the getter for NumberFormat.prototype.format, which returns a
      * bound formatting function for the specified NumberFormat object (suitable
      * for passing to methods like Array.prototype.map).
      */
     RootedValue getter(cx);
     if (!cx->global()->getIntrinsicValue(cx, cx->names().NumberFormatFormatGet, &getter))
-        return NULL;
+        return nullptr;
     RootedValue undefinedValue(cx, UndefinedValue());
     if (!JSObject::defineProperty(cx, proto, cx->names().format, undefinedValue,
                                   JS_DATA_TO_FUNC_PTR(JSPropertyOp, &getter.toObject()),
-                                  NULL, JSPROP_GETTER))
+                                  nullptr, JSPROP_GETTER))
     {
-        return NULL;
+        return nullptr;
     }
 
     // 11.2.1 and 11.3
     RootedValue locales(cx, UndefinedValue());
     RootedValue options(cx, UndefinedValue());
     if (!IntlInitialize(cx, proto, cx->names().InitializeNumberFormat, locales, options))
-        return NULL;
+        return nullptr;
 
     // 8.1
     RootedValue ctorValue(cx, ObjectValue(*ctor));
     if (!JSObject::defineProperty(cx, Intl, cx->names().NumberFormat, ctorValue,
                                   JS_PropertyStub, JS_StrictPropertyStub, 0))
     {
-        return NULL;
+        return nullptr;
     }
 
     return ctor;
 }
 
 bool
 GlobalObject::initNumberFormatProto(JSContext *cx, Handle<GlobalObject*> global)
 {
     RootedObject proto(cx, global->createBlankPrototype(cx, &NumberFormatClass));
     if (!proto)
         return false;
-    proto->setReservedSlot(UNUMBER_FORMAT_SLOT, PrivateValue(NULL));
+    proto->setReservedSlot(UNUMBER_FORMAT_SLOT, PrivateValue(nullptr));
     global->setReservedSlot(NUMBER_FORMAT_PROTO, ObjectValue(*proto));
     return true;
 }
 
 bool
 js::intl_NumberFormat_availableLocales(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
@@ -1239,17 +1239,17 @@ js::intl_numberingSystem(JSContext *cx, 
         return false;
 
     // There's no C API for numbering system, so use the C++ API and hope it
     // won't break. http://bugs.icu-project.org/trac/ticket/10039
     Locale ulocale(locale.ptr());
     UErrorCode status = U_ZERO_ERROR;
     NumberingSystem *numbers = NumberingSystem::createInstance(ulocale, status);
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
         return false;
     }
     const char *name = numbers->getName();
     RootedString jsname(cx, JS_NewStringCopyZ(cx, name));
     delete numbers;
     if (!jsname)
         return false;
     args.rval().setString(jsname);
@@ -1262,62 +1262,62 @@ js::intl_numberingSystem(JSContext *cx, 
  */
 static UNumberFormat *
 NewUNumberFormat(JSContext *cx, HandleObject numberFormat)
 {
     RootedValue value(cx);
 
     RootedObject internals(cx);
     if (!GetInternals(cx, numberFormat, &internals))
-       return NULL;
+       return nullptr;
 
     if (!JSObject::getProperty(cx, internals, internals, cx->names().locale, &value))
-        return NULL;
+        return nullptr;
     JSAutoByteString locale(cx, value.toString());
     if (!locale)
-        return NULL;
+        return nullptr;
 
     // UNumberFormat options with default values
     UNumberFormatStyle uStyle = UNUM_DECIMAL;
-    const UChar *uCurrency = NULL;
+    const UChar *uCurrency = nullptr;
     uint32_t uMinimumIntegerDigits = 1;
     uint32_t uMinimumFractionDigits = 0;
     uint32_t uMaximumFractionDigits = 3;
     int32_t uMinimumSignificantDigits = -1;
     int32_t uMaximumSignificantDigits = -1;
     bool uUseGrouping = true;
 
     // Sprinkle appropriate rooting flavor over things the GC might care about.
     SkipRoot skip(cx, &uCurrency);
     RootedString currency(cx);
 
     // We don't need to look at numberingSystem - it can only be set via
     // the Unicode locale extension and is therefore already set on locale.
 
     if (!JSObject::getProperty(cx, internals, internals, cx->names().style, &value))
-        return NULL;
+        return nullptr;
     JSAutoByteString style(cx, value.toString());
     if (!style)
-        return NULL;
+        return nullptr;
 
     if (equal(style, "currency")) {
         if (!JSObject::getProperty(cx, internals, internals, cx->names().currency, &value))
-            return NULL;
+            return nullptr;
         currency = value.toString();
         MOZ_ASSERT(currency->length() == 3, "IsWellFormedCurrencyCode permits only length-3 strings");
         // uCurrency remains owned by currency.
         uCurrency = JS_GetStringCharsZ(cx, currency);
         if (!uCurrency)
-            return NULL;
+            return nullptr;
 
         if (!JSObject::getProperty(cx, internals, internals, cx->names().currencyDisplay, &value))
-            return NULL;
+            return nullptr;
         JSAutoByteString currencyDisplay(cx, value.toString());
         if (!currencyDisplay)
-            return NULL;
+            return nullptr;
         if (equal(currencyDisplay, "code")) {
             uStyle = UNUM_CURRENCY_ISO;
         } else if (equal(currencyDisplay, "symbol")) {
             uStyle = UNUM_CURRENCY;
         } else {
             JS_ASSERT(equal(currencyDisplay, "name"));
             uStyle = UNUM_CURRENCY_PLURAL;
         }
@@ -1326,68 +1326,68 @@ NewUNumberFormat(JSContext *cx, HandleOb
     } else {
         JS_ASSERT(equal(style, "decimal"));
         uStyle = UNUM_DECIMAL;
     }
 
     RootedId id(cx, NameToId(cx->names().minimumSignificantDigits));
     bool hasP;
     if (!JSObject::hasProperty(cx, internals, id, &hasP))
-        return NULL;
+        return nullptr;
     if (hasP) {
         if (!JSObject::getProperty(cx, internals, internals, cx->names().minimumSignificantDigits,
                                    &value))
         {
-            return NULL;
+            return nullptr;
         }
         uMinimumSignificantDigits = int32_t(value.toNumber());
         if (!JSObject::getProperty(cx, internals, internals, cx->names().maximumSignificantDigits,
                                    &value))
         {
-            return NULL;
+            return nullptr;
         }
         uMaximumSignificantDigits = int32_t(value.toNumber());
     } else {
         if (!JSObject::getProperty(cx, internals, internals, cx->names().minimumIntegerDigits,
                                    &value))
         {
-            return NULL;
+            return nullptr;
         }
         uMinimumIntegerDigits = int32_t(value.toNumber());
         if (!JSObject::getProperty(cx, internals, internals, cx->names().minimumFractionDigits,
                                    &value))
         {
-            return NULL;
+            return nullptr;
         }
         uMinimumFractionDigits = int32_t(value.toNumber());
         if (!JSObject::getProperty(cx, internals, internals, cx->names().maximumFractionDigits,
                                    &value))
         {
-            return NULL;
+            return nullptr;
         }
         uMaximumFractionDigits = int32_t(value.toNumber());
     }
 
     if (!JSObject::getProperty(cx, internals, internals, cx->names().useGrouping, &value))
-        return NULL;
+        return nullptr;
     uUseGrouping = value.toBoolean();
 
     UErrorCode status = U_ZERO_ERROR;
-    UNumberFormat *nf = unum_open(uStyle, NULL, 0, icuLocale(locale.ptr()), NULL, &status);
+    UNumberFormat *nf = unum_open(uStyle, nullptr, 0, icuLocale(locale.ptr()), nullptr, &status);
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
-        return NULL;
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
+        return nullptr;
     }
     ScopedICUObject<UNumberFormat> toClose(nf, unum_close);
 
     if (uCurrency) {
         unum_setTextAttribute(nf, UNUM_CURRENCY_CODE, uCurrency, 3, &status);
         if (U_FAILURE(status)) {
-            JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
-            return NULL;
+            JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
+            return nullptr;
         }
     }
     if (uMinimumSignificantDigits != -1) {
         unum_setAttribute(nf, UNUM_SIGNIFICANT_DIGITS_USED, true);
         unum_setAttribute(nf, UNUM_MIN_SIGNIFICANT_DIGITS, uMinimumSignificantDigits);
         unum_setAttribute(nf, UNUM_MAX_SIGNIFICANT_DIGITS, uMaximumSignificantDigits);
     } else {
         unum_setAttribute(nf, UNUM_MIN_INTEGER_DIGITS, uMinimumIntegerDigits);
@@ -1406,25 +1406,26 @@ intl_FormatNumber(JSContext *cx, UNumber
     // FormatNumber doesn't consider -0.0 to be negative.
     if (IsNegativeZero(x))
         x = 0.0;
 
     StringBuffer chars(cx);
     if (!chars.resize(INITIAL_STRING_BUFFER_SIZE))
         return false;
     UErrorCode status = U_ZERO_ERROR;
-    int size = unum_formatDouble(nf, x, chars.begin(), INITIAL_STRING_BUFFER_SIZE, NULL, &status);
+    int size = unum_formatDouble(nf, x, chars.begin(), INITIAL_STRING_BUFFER_SIZE, nullptr,
+                                 &status);
     if (status == U_BUFFER_OVERFLOW_ERROR) {
         if (!chars.resize(size))
             return false;
         status = U_ZERO_ERROR;
-        unum_formatDouble(nf, x, chars.begin(), size, NULL, &status);
+        unum_formatDouble(nf, x, chars.begin(), size, nullptr, &status);
     }
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
         return false;
     }
 
     // Trim any unused characters.
     if (!chars.resize(size))
         return false;
 
     RootedString str(cx, chars.finishString());
@@ -1557,17 +1558,17 @@ DateTimeFormat(JSContext *cx, CallArgs a
         // 12.1.3.1 paragraph 2
         RootedObject proto(cx, cx->global()->getOrCreateDateTimeFormatPrototype(cx));
         if (!proto)
             return false;
         obj = NewObjectWithGivenProto(cx, &DateTimeFormatClass, proto, cx->global());
         if (!obj)
             return false;
 
-        obj->setReservedSlot(UDATE_FORMAT_SLOT, PrivateValue(NULL));
+        obj->setReservedSlot(UDATE_FORMAT_SLOT, PrivateValue(nullptr));
     }
 
     // 12.1.2.1 steps 1 and 2; 12.1.3.1 steps 1 and 2
     RootedValue locales(cx, args.length() > 0 ? args[0] : UndefinedValue());
     RootedValue options(cx, args.length() > 1 ? args[1] : UndefinedValue());
 
     // 12.1.2.1 step 6; 12.1.3.1 step 3
     if (!IntlInitialize(cx, obj, cx->names().InitializeDateTimeFormat, locales, options))
@@ -1604,72 +1605,72 @@ dateTimeFormat_finalize(FreeOp *fop, JSO
         udat_close(df);
 }
 
 static JSObject *
 InitDateTimeFormatClass(JSContext *cx, HandleObject Intl, Handle<GlobalObject*> global)
 {
     RootedFunction ctor(cx, global->createConstructor(cx, &DateTimeFormat, cx->names().DateTimeFormat, 0));
     if (!ctor)
-        return NULL;
+        return nullptr;
 
     RootedObject proto(cx, global->as<GlobalObject>().getOrCreateDateTimeFormatPrototype(cx));
     if (!proto)
-        return NULL;
+        return nullptr;
     if (!LinkConstructorAndPrototype(cx, ctor, proto))
-        return NULL;
+        return nullptr;
 
     // 12.2.2
     if (!JS_DefineFunctions(cx, ctor, dateTimeFormat_static_methods))
-        return NULL;
+        return nullptr;
 
     // 12.3.2 and 12.3.3
     if (!JS_DefineFunctions(cx, proto, dateTimeFormat_methods))
-        return NULL;
+        return nullptr;
 
     /*
      * Install the getter for DateTimeFormat.prototype.format, which returns a
      * bound formatting function for the specified DateTimeFormat object
      * (suitable for passing to methods like Array.prototype.map).
      */
     RootedValue getter(cx);
     if (!cx->global()->getIntrinsicValue(cx, cx->names().DateTimeFormatFormatGet, &getter))
-        return NULL;
+        return nullptr;
     RootedValue undefinedValue(cx, UndefinedValue());
     if (!JSObject::defineProperty(cx, proto, cx->names().format, undefinedValue,
                                   JS_DATA_TO_FUNC_PTR(JSPropertyOp, &getter.toObject()),
-                                  NULL, JSPROP_GETTER))
+                                  nullptr, JSPROP_GETTER))
     {
-        return NULL;
+        return nullptr;
     }
 
     // 12.2.1 and 12.3
     RootedValue locales(cx, UndefinedValue());
     RootedValue options(cx, UndefinedValue());
     if (!IntlInitialize(cx, proto, cx->names().InitializeDateTimeFormat, locales, options))
-        return NULL;
+        return nullptr;
 
     // 8.1
     RootedValue ctorValue(cx, ObjectValue(*ctor));
     if (!JSObject::defineProperty(cx, Intl, cx->names().DateTimeFormat, ctorValue,
                                   JS_PropertyStub, JS_StrictPropertyStub, 0))
     {
-        return NULL;
+        return nullptr;
     }
 
     return ctor;
 }
 
 bool
 GlobalObject::initDateTimeFormatProto(JSContext *cx, Handle<GlobalObject*> global)
 {
     RootedObject proto(cx, global->createBlankPrototype(cx, &DateTimeFormatClass));
     if (!proto)
         return false;
-    proto->setReservedSlot(UDATE_FORMAT_SLOT, PrivateValue(NULL));
+    proto->setReservedSlot(UDATE_FORMAT_SLOT, PrivateValue(nullptr));
     global->setReservedSlot(DATE_TIME_FORMAT_PROTO, ObjectValue(*proto));
     return true;
 }
 
 bool
 js::intl_DateTimeFormat_availableLocales(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
@@ -1709,48 +1710,48 @@ js::intl_availableCalendars(JSContext *c
 
     RootedObject calendars(cx, NewDenseEmptyArray(cx));
     if (!calendars)
         return false;
     uint32_t index = 0;
 
     // We need the default calendar for the locale as the first result.
     UErrorCode status = U_ZERO_ERROR;
-    UCalendar *cal = ucal_open(NULL, 0, locale.ptr(), UCAL_DEFAULT, &status);
+    UCalendar *cal = ucal_open(nullptr, 0, locale.ptr(), UCAL_DEFAULT, &status);
     const char *calendar = ucal_getType(cal, &status);
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
         return false;
     }
     ucal_close(cal);
     RootedString jscalendar(cx, JS_NewStringCopyZ(cx, bcp47CalendarName(calendar)));
     if (!jscalendar)
         return false;
     RootedValue element(cx, StringValue(jscalendar));
     if (!JSObject::defineElement(cx, calendars, index++, element))
         return false;
 
     // Now get the calendars that "would make a difference", i.e., not the default.
     UEnumeration *values = ucal_getKeywordValuesForLocale("ca", locale.ptr(), false, &status);
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
         return false;
     }
     ScopedICUObject<UEnumeration> toClose(values, uenum_close);
 
     uint32_t count = uenum_count(values, &status);
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
         return false;
     }
 
     for (; count > 0; count--) {
-        calendar = uenum_next(values, NULL, &status);
+        calendar = uenum_next(values, nullptr, &status);
         if (U_FAILURE(status)) {
-            JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+            JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
             return false;
         }
 
         jscalendar = JS_NewStringCopyZ(cx, bcp47CalendarName(calendar));
         if (!jscalendar)
             return false;
         element = StringValue(jscalendar);
         if (!JSObject::defineElement(cx, calendars, index++, element))
@@ -1777,34 +1778,34 @@ js::intl_patternForSkeleton(JSContext *c
     if (!skeleton)
         return false;
     SkipRoot skip(cx, &skeleton);
     uint32_t skeletonLen = u_strlen(skeleton);
 
     UErrorCode status = U_ZERO_ERROR;
     UDateTimePatternGenerator *gen = udatpg_open(icuLocale(locale.ptr()), &status);
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
         return false;
     }
     ScopedICUObject<UDateTimePatternGenerator> toClose(gen, udatpg_close);
 
-    int32_t size = udatpg_getBestPattern(gen, skeleton, skeletonLen, NULL, 0, &status);
+    int32_t size = udatpg_getBestPattern(gen, skeleton, skeletonLen, nullptr, 0, &status);
     if (U_FAILURE(status) && status != U_BUFFER_OVERFLOW_ERROR) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
         return false;
     }
     ScopedJSFreePtr<UChar> pattern(cx->pod_malloc<UChar>(size + 1));
     if (!pattern)
         return false;
     pattern[size] = '\0';
     status = U_ZERO_ERROR;
     udatpg_getBestPattern(gen, skeleton, skeletonLen, pattern, size, &status);
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
         return false;
     }
 
     RootedString str(cx, JS_NewUCStringCopyZ(cx, pattern));
     if (!str)
         return false;
     args.rval().setString(str);
     return true;
@@ -1816,102 +1817,102 @@ js::intl_patternForSkeleton(JSContext *c
  */
 static UDateFormat *
 NewUDateFormat(JSContext *cx, HandleObject dateTimeFormat)
 {
     RootedValue value(cx);
 
     RootedObject internals(cx);
     if (!GetInternals(cx, dateTimeFormat, &internals))
-       return NULL;
+       return nullptr;
 
     if (!JSObject::getProperty(cx, internals, internals, cx->names().locale, &value)) {
-        return NULL;
+        return nullptr;
     }
     JSAutoByteString locale(cx, value.toString());
     if (!locale)
-        return NULL;
+        return nullptr;
 
     // UDateFormat options with default values.
-    const UChar *uTimeZone = NULL;
+    const UChar *uTimeZone = nullptr;
     uint32_t uTimeZoneLength = 0;
-    const UChar *uPattern = NULL;
+    const UChar *uPattern = nullptr;
     uint32_t uPatternLength = 0;
 
     SkipRoot skipTimeZone(cx, &uTimeZone);
     SkipRoot skipPattern(cx, &uPattern);
 
     // We don't need to look at calendar and numberingSystem - they can only be
     // set via the Unicode locale extension and are therefore already set on
     // locale.
 
     RootedId id(cx, NameToId(cx->names().timeZone));
     bool hasP;
     if (!JSObject::hasProperty(cx, internals, id, &hasP))
-        return NULL;
+        return nullptr;
     if (hasP) {
         if (!JSObject::getProperty(cx, internals, internals, cx->names().timeZone, &value))
-            return NULL;
+            return nullptr;
         if (!value.isUndefined()) {
             uTimeZone = JS_GetStringCharsZ(cx, value.toString());
             if (!uTimeZone)
-                return NULL;
+                return nullptr;
             uTimeZoneLength = u_strlen(uTimeZone);
         }
     }
     if (!JSObject::getProperty(cx, internals, internals, cx->names().pattern, &value))
-        return NULL;
+        return nullptr;
     uPattern = JS_GetStringCharsZ(cx, value.toString());
     if (!uPattern)
-        return NULL;
+        return nullptr;
     uPatternLength = u_strlen(uPattern);
 
     UErrorCode status = U_ZERO_ERROR;
 
     // If building with ICU headers before 50.1, use UDAT_IGNORE instead of
     // UDAT_PATTERN.
     UDateFormat *df =
         udat_open(UDAT_PATTERN, UDAT_PATTERN, icuLocale(locale.ptr()), uTimeZone, uTimeZoneLength,
                   uPattern, uPatternLength, &status);
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
-        return NULL;
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
+        return nullptr;
     }
 
     // ECMAScript requires the Gregorian calendar to be used from the beginning
     // of ECMAScript time.
     UCalendar *cal = const_cast<UCalendar*>(udat_getCalendar(df));
     ucal_setGregorianChange(cal, StartOfTime, &status);
 
     // An error here means the calendar is not Gregorian, so we don't care.
 
     return df;
 }
 
 static bool
 intl_FormatDateTime(JSContext *cx, UDateFormat *df, double x, MutableHandleValue result)
 {
     if (!IsFinite(x)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DATE_NOT_FINITE);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DATE_NOT_FINITE);
         return false;
     }
 
     StringBuffer chars(cx);
     if (!chars.resize(INITIAL_STRING_BUFFER_SIZE))
         return false;
     UErrorCode status = U_ZERO_ERROR;
-    int size = udat_format(df, x, chars.begin(), INITIAL_STRING_BUFFER_SIZE, NULL, &status);
+    int size = udat_format(df, x, chars.begin(), INITIAL_STRING_BUFFER_SIZE, nullptr, &status);
     if (status == U_BUFFER_OVERFLOW_ERROR) {
         if (!chars.resize(size))
             return false;
         status = U_ZERO_ERROR;
-        udat_format(df, x, chars.begin(), size, NULL, &status);
+        udat_format(df, x, chars.begin(), size, nullptr, &status);
     }
     if (U_FAILURE(status)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INTERNAL_INTL_ERROR);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
         return false;
     }
 
     // Trim any unused characters.
     if (!chars.resize(size))
         return false;
 
     RootedString str(cx, chars.finishString());
@@ -2007,38 +2008,38 @@ js_InitIntlClass(JSContext *cx, HandleOb
     Rooted<GlobalObject*> global(cx, &obj->as<GlobalObject>());
 
     // The constructors above need to be able to determine whether they've been
     // called with this being "the standard built-in Intl object". The global
     // object reserves slots to track standard built-in objects, but doesn't
     // normally keep references to non-constructors. This makes sure there is one.
     RootedObject Intl(cx, global->getOrCreateIntlObject(cx));
     if (!Intl)
-        return NULL;
+        return nullptr;
 
     RootedValue IntlValue(cx, ObjectValue(*Intl));
     if (!JSObject::defineProperty(cx, global, cx->names().Intl, IntlValue,
                                   JS_PropertyStub, JS_StrictPropertyStub, 0))
     {
-        return NULL;
+        return nullptr;
     }
 
     if (!JS_DefineFunctions(cx, Intl, intl_static_methods))
-        return NULL;
+        return nullptr;
 
     // Skip initialization of the Intl constructors during initialization of the
     // self-hosting global as we may get here before self-hosted code is compiled,
     // and no core code refers to the Intl classes.
     if (!cx->runtime()->isSelfHostingGlobal(cx->global())) {
         if (!InitCollatorClass(cx, Intl, global))
-            return NULL;
+            return nullptr;
         if (!InitNumberFormatClass(cx, Intl, global))
-            return NULL;
+            return nullptr;
         if (!InitDateTimeFormatClass(cx, Intl, global))
-            return NULL;
+            return nullptr;
     }
 
     MarkStandardClassInitializedNoProto(global, &IntlClass);
 
     return Intl;
 }
 
 bool
--- a/js/src/builtin/MapObject.cpp
+++ b/js/src/builtin/MapObject.cpp
@@ -94,27 +94,27 @@ class OrderedHashTable
     uint32_t dataCapacity;      // size of data, in elements
     uint32_t liveCount;         // dataLength less empty (removed) entries
     uint32_t hashShift;         // multiplicative hash shift
     Range *ranges;              // list of all live Ranges on this table
     AllocPolicy alloc;
 
   public:
     OrderedHashTable(AllocPolicy &ap)
-        : hashTable(NULL), data(NULL), dataLength(0), ranges(NULL), alloc(ap) {}
+        : hashTable(nullptr), data(nullptr), dataLength(0), ranges(nullptr), alloc(ap) {}
 
     bool init() {
         MOZ_ASSERT(!hashTable, "init must be called at most once");
 
         uint32_t buckets = initialBuckets();
         Data **tableAlloc = static_cast<Data **>(alloc.malloc_(buckets * sizeof(Data *)));
         if (!tableAlloc)
             return false;
         for (uint32_t i = 0; i < buckets; i++)
-            tableAlloc[i] = NULL;
+            tableAlloc[i] = nullptr;
 
         uint32_t capacity = uint32_t(buckets * fillFactor());
         Data *dataAlloc = static_cast<Data *>(alloc.malloc_(capacity * sizeof(Data)));
         if (!dataAlloc) {
             alloc.free_(tableAlloc);
             return false;
         }
 
@@ -139,26 +139,26 @@ class OrderedHashTable
         freeData(data, dataLength);
     }
 
     /* Return the number of elements in the table. */
     uint32_t count() const { return liveCount; }
 
     /* True if any element matches l. */
     bool has(const Lookup &l) const {
-        return lookup(l) != NULL;
+        return lookup(l) != nullptr;
     }
 
-    /* Return a pointer to the element, if any, that matches l, else NULL. */
+    /* Return a pointer to the element, if any, that matches l, or nullptr. */
     T *get(const Lookup &l) {
         Data *e = lookup(l, prepareHash(l));
-        return e ? &e->element : NULL;
+        return e ? &e->element : nullptr;
     }
 
-    /* Return a pointer to the element, if any, that matches l, else NULL. */
+    /* Return a pointer to the element, if any, that matches l, or nullptr. */
     const T *get(const Lookup &l) const {
         return const_cast<OrderedHashTable *>(this)->get(l);
     }
 
     /*
      * If the table already contains an entry that matches |element|,
      * replace that entry with |element|. Otherwise add a new entry.
      *
@@ -200,17 +200,17 @@ class OrderedHashTable
      */
     bool remove(const Lookup &l, bool *foundp) {
         // Note: This could be optimized so that removing the last entry,
         // data[dataLength - 1], decrements dataLength. LIFO use cases would
         // benefit.
 
         // If a matching entry exists, empty it.
         Data *e = lookup(l, prepareHash(l));
-        if (e == NULL) {
+        if (e == nullptr) {
             *foundp = false;
             return true;
         }
 
         *foundp = true;
         liveCount--;
         Ops::makeEmpty(&e->element);
 
@@ -238,17 +238,17 @@ class OrderedHashTable
      * after a successful clear().
      */
     bool clear() {
         if (dataLength != 0) {
             Data **oldHashTable = hashTable;
             Data *oldData = data;
             uint32_t oldDataLength = dataLength;
 
-            hashTable = NULL;
+            hashTable = nullptr;
             if (!init()) {
                 // init() only mutates members on success; see comment above.
                 hashTable = oldHashTable;
                 return false;
             }
 
             alloc.free_(oldHashTable);
             freeData(oldData, oldDataLength);
@@ -312,17 +312,17 @@ class OrderedHashTable
         uint32_t count;
 
         /*
          * Links in the doubly-linked list of active Ranges on ht.
          *
          * prevp points to the previous Range's .next field;
          *   or to ht.ranges if this is the first Range in the list.
          * next points to the next Range;
-         *   or NULL if this is the last Range in the list.
+         *   or nullptr if this is the last Range in the list.
          *
          * Invariant: *prevp == this.
          */
         Range **prevp;
         Range *next;
 
         /*
          * Create a Range over all the entries in ht.
@@ -446,17 +446,17 @@ class OrderedHashTable
         void rekeyFront(const Key &k) {
             MOZ_ASSERT(valid());
             Data &entry = ht.data[i];
             HashNumber oldHash = prepareHash(Ops::getKey(entry.element)) >> ht.hashShift;
             HashNumber newHash = prepareHash(k) >> ht.hashShift;
             Ops::setKey(entry.element, k);
             if (newHash != oldHash) {
                 // Remove this entry from its old hash chain. (If this crashes
-                // reading NULL, it would mean we did not find this entry on
+                // reading nullptr, it would mean we did not find this entry on
                 // the hash chain where we expected it. That probably means the
                 // key's hash code changed since it was inserted, breaking the
                 // hash code invariant.)
                 Data **ep = &ht.hashTable[oldHash];
                 while (*ep != &entry)
                     ep = &(*ep)->chain;
                 *ep = entry.chain;
 
@@ -511,17 +511,17 @@ class OrderedHashTable
             return;
 
         HashNumber oldHash = prepareHash(current) >> hashShift;
         HashNumber newHash = prepareHash(newKey) >> hashShift;
 
         entry->element = element;
 
         // Remove this entry from its old hash chain. (If this crashes
-        // reading NULL, it would mean we did not find this entry on
+        // reading nullptr, it would mean we did not find this entry on
         // the hash chain where we expected it. That probably means the
         // key's hash code changed since it was inserted, breaking the
         // hash code invariant.)
         Data **ep = &hashTable[oldHash];
         while (*ep != entry)
             ep = &(*ep)->chain;
         *ep = entry->chain;
 
@@ -580,17 +580,17 @@ class OrderedHashTable
         alloc.free_(data);
     }
 
     Data *lookup(const Lookup &l, HashNumber h) {
         for (Data *e = hashTable[h >> hashShift]; e; e = e->chain) {
             if (Ops::match(Ops::getKey(e->element), l))
                 return e;
         }
-        return NULL;
+        return nullptr;
     }
 
     const Data *lookup(const Lookup &l) const {
         return const_cast<OrderedHashTable *>(this)->lookup(l, prepareHash(l));
     }
 
     /* This is called after rehashing the table. */
     void compacted() {
@@ -598,17 +598,17 @@ class OrderedHashTable
         // to the left within |data|. Notify all live Ranges of the change.
         for (Range *r = ranges; r; r = r->next)
             r->onCompact();
     }
 
     /* Compact the entries in |data| and rehash them. */
     void rehashInPlace() {
         for (uint32_t i = 0, N = hashBuckets(); i < N; i++)
-            hashTable[i] = NULL;
+            hashTable[i] = nullptr;
         Data *wp = data, *end = data + dataLength;
         for (Data *rp = data; rp != end; rp++) {
             if (!Ops::isEmpty(Ops::getKey(rp->element))) {
                 HashNumber h = prepareHash(Ops::getKey(rp->element)) >> hashShift;
                 if (rp != wp)
                     wp->element = OldMove(rp->element);
                 wp->chain = hashTable[h];
                 hashTable[h] = wp;
@@ -638,17 +638,17 @@ class OrderedHashTable
             return true;
         }
 
         size_t newHashBuckets = 1 << (HashNumberSizeBits - newHashShift);
         Data **newHashTable = static_cast<Data **>(alloc.malloc_(newHashBuckets * sizeof(Data *)));
         if (!newHashTable)
             return false;
         for (uint32_t i = 0; i < newHashBuckets; i++)
-            newHashTable[i] = NULL;
+            newHashTable[i] = nullptr;
 
         uint32_t newCapacity = uint32_t(newHashBuckets * fillFactor());
         Data *newData = static_cast<Data *>(alloc.malloc_(newCapacity * sizeof(Data)));
         if (!newData) {
             alloc.free_(newHashTable);
             return false;
         }
 
@@ -828,17 +828,17 @@ HashableValue::hash() const
 bool
 HashableValue::operator==(const HashableValue &other) const
 {
     // Two HashableValues are equal if they have equal bits.
     bool b = (value.asRawBits() == other.value.asRawBits());
 
 #ifdef DEBUG
     bool same;
-    JS_ASSERT(SameValue(NULL, value, other.value, &same));
+    JS_ASSERT(SameValue(nullptr, value, other.value, &same));
     JS_ASSERT(same == b);
 #endif
     return b;
 }
 
 HashableValue
 HashableValue::mark(JSTracer *trc) const
 {
@@ -912,40 +912,40 @@ GlobalObject::initMapIteratorProto(JSCon
 {
     JSObject *base = global->getOrCreateIteratorPrototype(cx);
     if (!base)
         return false;
     Rooted<JSObject*> proto(cx,
         NewObjectWithGivenProto(cx, &MapIteratorObject::class_, base, global));
     if (!proto)
         return false;
-    proto->setSlot(MapIteratorObject::RangeSlot, PrivateValue(NULL));
+    proto->setSlot(MapIteratorObject::RangeSlot, PrivateValue(nullptr));
     if (!JS_DefineFunctions(cx, proto, MapIteratorObject::methods))
         return false;
     global->setReservedSlot(MAP_ITERATOR_PROTO, ObjectValue(*proto));
     return true;
 }
 
 MapIteratorObject *
 MapIteratorObject::create(JSContext *cx, HandleObject mapobj, ValueMap *data,
                           MapObject::IteratorKind kind)
 {
     Rooted<GlobalObject *> global(cx, &mapobj->global());
     Rooted<JSObject*> proto(cx, global->getOrCreateMapIteratorPrototype(cx));
     if (!proto)
-        return NULL;
+        return nullptr;
 
     ValueMap::Range *range = cx->new_<ValueMap::Range>(data->all());
     if (!range)
-        return NULL;
+        return nullptr;
 
     JSObject *iterobj = NewObjectWithGivenProto(cx, &class_, proto, global);
     if (!iterobj) {
         js_delete(range);
-        return NULL;
+        return nullptr;
     }
     iterobj->setSlot(TargetSlot, ObjectValue(*mapobj));
     iterobj->setSlot(KindSlot, Int32Value(int32_t(kind)));
     iterobj->setSlot(RangeSlot, PrivateValue(range));
     return static_cast<MapIteratorObject *>(iterobj);
 }
 
 void
@@ -964,17 +964,17 @@ bool
 MapIteratorObject::next_impl(JSContext *cx, CallArgs args)
 {
     MapIteratorObject &thisobj = args.thisv().toObject().as<MapIteratorObject>();
     ValueMap::Range *range = thisobj.range();
     if (!range)
         return js_ThrowStopIteration(cx);
     if (range->empty()) {
         js_delete(range);
-        thisobj.setReservedSlot(RangeSlot, PrivateValue(NULL));
+        thisobj.setReservedSlot(RangeSlot, PrivateValue(nullptr));
         return js_ThrowStopIteration(cx);
     }
 
     switch (thisobj.kind()) {
       case MapObject::Keys:
         args.rval().set(range->front().key.get());
         break;
 
@@ -1014,76 +1014,76 @@ const Class MapObject::class_ = {
     JS_PropertyStub,         // addProperty
     JS_DeletePropertyStub,   // delProperty
     JS_PropertyStub,         // getProperty
     JS_StrictPropertyStub,   // setProperty
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub,
     finalize,
-    NULL,                    // checkAccess
-    NULL,                    // call
-    NULL,                    // hasInstance
-    NULL,                    // construct
+    nullptr,                 // checkAccess
+    nullptr,                 // call
+    nullptr,                 // hasInstance
+    nullptr,                 // construct
     mark
 };
 
 const JSPropertySpec MapObject::properties[] = {
     JS_PSG("size", size, 0),
     JS_PS_END
 };
 
 const JSFunctionSpec MapObject::methods[] = {
     JS_FN("get", get, 1, 0),
     JS_FN("has", has, 1, 0),
     JS_FN("set", set, 2, 0),
     JS_FN("delete", delete_, 1, 0),
     JS_FN("keys", keys, 0, 0),
     JS_FN("values", values, 0, 0),
     JS_FN("clear", clear, 0, 0),
-    {"forEach", {NULL, NULL}, 2, 0, "MapForEach"},
+    {"forEach", {nullptr, nullptr}, 2, 0, "MapForEach"},
     JS_FS_END
 };
 
 static JSObject *
 InitClass(JSContext *cx, Handle<GlobalObject*> global, const Class *clasp, JSProtoKey key, Native construct,
           const JSPropertySpec *properties, const JSFunctionSpec *methods)
 {
     Rooted<JSObject*> proto(cx, global->createBlankPrototype(cx, clasp));
     if (!proto)
-        return NULL;
-    proto->setPrivate(NULL);
+        return nullptr;
+    proto->setPrivate(nullptr);
 
     Rooted<JSFunction*> ctor(cx, global->createConstructor(cx, construct, ClassName(key, cx), 1));
     if (!ctor ||
         !LinkConstructorAndPrototype(cx, ctor, proto) ||
         !DefinePropertiesAndBrand(cx, proto, properties, methods) ||
         !DefineConstructorAndPrototype(cx, global, key, ctor, proto))
     {
-        return NULL;
+        return nullptr;
     }
     return proto;
 }
 
 JSObject *
 MapObject::initClass(JSContext *cx, JSObject *obj)
 {
     Rooted<GlobalObject*> global(cx, &obj->as<GlobalObject>());
     RootedObject proto(cx,
         InitClass(cx, global, &class_, JSProto_Map, construct, properties, methods));
     if (proto) {
         // Define the "entries" method.
         JSFunction *fun = JS_DefineFunction(cx, proto, "entries", entries, 0, 0);
         if (!fun)
-            return NULL;
+            return nullptr;
 
         // Define its alias.
         RootedValue funval(cx, ObjectValue(*fun));
-        if (!JS_DefineProperty(cx, proto, "iterator", funval, NULL, NULL, 0))
-            return NULL;
+        if (!JS_DefineProperty(cx, proto, "iterator", funval, nullptr, nullptr, 0))
+            return nullptr;
     }
     return proto;
 }
 
 template <class Range>
 static void
 MarkKey(Range &r, const HashableValue &key, JSTracer *trc)
 {
@@ -1478,40 +1478,40 @@ bool
 GlobalObject::initSetIteratorProto(JSContext *cx, Handle<GlobalObject*> global)
 {
     JSObject *base = global->getOrCreateIteratorPrototype(cx);
     if (!base)
         return false;
     RootedObject proto(cx, NewObjectWithGivenProto(cx, &SetIteratorObject::class_, base, global));
     if (!proto)
         return false;
-    proto->setSlot(SetIteratorObject::RangeSlot, PrivateValue(NULL));
+    proto->setSlot(SetIteratorObject::RangeSlot, PrivateValue(nullptr));
     if (!JS_DefineFunctions(cx, proto, SetIteratorObject::methods))
         return false;
     global->setReservedSlot(SET_ITERATOR_PROTO, ObjectValue(*proto));
     return true;
 }
 
 SetIteratorObject *
 SetIteratorObject::create(JSContext *cx, HandleObject setobj, ValueSet *data,
                           SetObject::IteratorKind kind)
 {
     Rooted<GlobalObject *> global(cx, &setobj->global());
     Rooted<JSObject*> proto(cx, global->getOrCreateSetIteratorPrototype(cx));
     if (!proto)
-        return NULL;
+        return nullptr;
 
     ValueSet::Range *range = cx->new_<ValueSet::Range>(data->all());
     if (!range)
-        return NULL;
+        return nullptr;
 
     JSObject *iterobj = NewObjectWithGivenProto(cx, &class_, proto, global);
     if (!iterobj) {
         js_delete(range);
-        return NULL;
+        return nullptr;
     }
     iterobj->setSlot(TargetSlot, ObjectValue(*setobj));
     iterobj->setSlot(KindSlot, Int32Value(int32_t(kind)));
     iterobj->setSlot(RangeSlot, PrivateValue(range));
     return static_cast<SetIteratorObject *>(iterobj);
 }
 
 void
@@ -1530,17 +1530,17 @@ bool
 SetIteratorObject::next_impl(JSContext *cx, CallArgs args)
 {
     SetIteratorObject &thisobj = args.thisv().toObject().as<SetIteratorObject>();
     ValueSet::Range *range = thisobj.range();
     if (!range)
         return js_ThrowStopIteration(cx);
     if (range->empty()) {
         js_delete(range);
-        thisobj.setReservedSlot(RangeSlot, PrivateValue(NULL));
+        thisobj.setReservedSlot(RangeSlot, PrivateValue(nullptr));
         return js_ThrowStopIteration(cx);
     }
 
     switch (thisobj.kind()) {
       case SetObject::Values:
         args.rval().set(range->front().get());
         break;
 
@@ -1577,56 +1577,56 @@ const Class SetObject::class_ = {
     JS_PropertyStub,         // addProperty
     JS_DeletePropertyStub,   // delProperty
     JS_PropertyStub,         // getProperty
     JS_StrictPropertyStub,   // setProperty
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub,
     finalize,
-    NULL,                    // checkAccess
-    NULL,                    // call
-    NULL,                    // hasInstance
-    NULL,                    // construct
+    nullptr,                 // checkAccess
+    nullptr,                 // call
+    nullptr,                 // hasInstance
+    nullptr,                 // construct
     mark
 };
 
 const JSPropertySpec SetObject::properties[] = {
     JS_PSG("size", size, 0),
     JS_PS_END
 };
 
 const JSFunctionSpec SetObject::methods[] = {
     JS_FN("has", has, 1, 0),
     JS_FN("add", add, 1, 0),
     JS_FN("delete", delete_, 1, 0),
     JS_FN("entries", entries, 0, 0),
     JS_FN("clear", clear, 0, 0),
-    {"forEach", {NULL, NULL}, 2, 0, "SetForEach"},
+    {"forEach", {nullptr, nullptr}, 2, 0, "SetForEach"},
     JS_FS_END
 };
 
 JSObject *
 SetObject::initClass(JSContext *cx, JSObject *obj)
 {
     Rooted<GlobalObject*> global(cx, &obj->as<GlobalObject>());
     RootedObject proto(cx,
         InitClass(cx, global, &class_, JSProto_Set, construct, properties, methods));
     if (proto) {
         // Define the "values" method.
         JSFunction *fun = JS_DefineFunction(cx, proto, "values", values, 0, 0);
         if (!fun)
-            return NULL;
+            return nullptr;
 
         // Define its aliases.
         RootedValue funval(cx, ObjectValue(*fun));
-        if (!JS_DefineProperty(cx, proto, "keys", funval, NULL, NULL, 0))
-            return NULL;
-        if (!JS_DefineProperty(cx, proto, "iterator", funval, NULL, NULL, 0))
-            return NULL;
+        if (!JS_DefineProperty(cx, proto, "keys", funval, nullptr, nullptr, 0))
+            return nullptr;
+        if (!JS_DefineProperty(cx, proto, "iterator", funval, nullptr, nullptr, 0))
+            return nullptr;
     }
     return proto;
 }
 
 void
 SetObject::mark(JSTracer *trc, JSObject *obj)
 {
     SetObject *setobj = static_cast<SetObject *>(obj);
--- a/js/src/builtin/Module.cpp
+++ b/js/src/builtin/Module.cpp
@@ -38,14 +38,14 @@ Module::setScript(JSScript *script)
     setReservedSlot(SCRIPT_SLOT, PrivateValue(script));
 }
 
 Module *
 Module::create(ExclusiveContext *cx, HandleAtom atom)
 {
     RootedObject object(cx, NewBuiltinClassInstance(cx, &class_));
     if (!object)
-        return NULL;
+        return nullptr;
     RootedModule module(cx, &object->as<Module>());
     module->setAtom(atom);
-    module->setScript(NULL);
+    module->setScript(nullptr);
     return module;
 }
--- a/js/src/builtin/Object.cpp
+++ b/js/src/builtin/Object.cpp
@@ -24,17 +24,17 @@ using js::frontend::IsIdentifier;
 using mozilla::ArrayLength;
 
 
 bool
 js::obj_construct(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
-    RootedObject obj(cx, NULL);
+    RootedObject obj(cx, nullptr);
     if (args.length() > 0) {
         /* If argv[0] is null or undefined, obj comes back null. */
         if (!js_ValueToObjectOrNull(cx, args[0], &obj))
             return false;
     }
     if (!obj) {
         /* Make an object whether this was called with 'new' or not. */
         JS_ASSERT(!args.length() || args[0].isNullOrUndefined());
@@ -110,43 +110,43 @@ obj_toSource(JSContext *cx, unsigned arg
 JSString *
 js::ObjectToSource(JSContext *cx, HandleObject obj)
 {
     /* If outermost, we need parentheses to be an expression, not a block. */
     bool outermost = (cx->cycleDetectorSet.count() == 0);
 
     AutoCycleDetector detector(cx, obj);
     if (!detector.init())
-        return NULL;
+        return nullptr;
     if (detector.foundCycle())
         return js_NewStringCopyZ<CanGC>(cx, "{}");
 
     StringBuffer buf(cx);
     if (outermost && !buf.append('('))
-        return NULL;
+        return nullptr;
     if (!buf.append('{'))
-        return NULL;
+        return nullptr;
 
     RootedValue v0(cx), v1(cx);
     MutableHandleValue val[2] = {&v0, &v1};
 
     RootedString str0(cx), str1(cx);
     MutableHandleString gsop[2] = {&str0, &str1};
 
     AutoIdVector idv(cx);
     if (!GetPropertyNames(cx, obj, JSITER_OWNONLY, &idv))
-        return NULL;
+        return nullptr;
 
     bool comma = false;
     for (size_t i = 0; i < idv.length(); ++i) {
         RootedId id(cx, idv[i]);
         RootedObject obj2(cx);
         RootedShape shape(cx);
         if (!JSObject::lookupGeneric(cx, obj, id, &obj2, &shape))
-            return NULL;
+            return nullptr;
 
         /*  Decide early whether we prefer get/set or old getter/setter syntax. */
         int valcnt = 0;
         if (shape) {
             bool doGet = true;
             if (obj2->isNative() && !IsImplicitDenseElement(shape)) {
                 unsigned attrs = shape->attributes();
                 if (attrs & JSPROP_GETTER) {
@@ -159,59 +159,59 @@ js::ObjectToSource(JSContext *cx, Handle
                     doGet = false;
                     val[valcnt].set(shape->setterValue());
                     gsop[valcnt].set(cx->names().set);
                     valcnt++;
                 }
             }
             if (doGet) {
                 valcnt = 1;
-                gsop[0].set(NULL);
+                gsop[0].set(nullptr);
                 if (!JSObject::getGeneric(cx, obj, obj, id, val[0]))
-                    return NULL;
+                    return nullptr;
             }
         }
 
         /* Convert id to a linear string. */
         RootedValue idv(cx, IdToValue(id));
         JSString *s = ToString<CanGC>(cx, idv);
         if (!s)
-            return NULL;
+            return nullptr;
         Rooted<JSLinearString*> idstr(cx, s->ensureLinear(cx));
         if (!idstr)
-            return NULL;
+            return nullptr;
 
         /*
          * If id is a string that's not an identifier, or if it's a negative
          * integer, then it must be quoted.
          */
         if (JSID_IS_ATOM(id)
             ? !IsIdentifier(idstr)
             : (!JSID_IS_INT(id) || JSID_TO_INT(id) < 0))
         {
             s = js_QuoteString(cx, idstr, jschar('\''));
             if (!s || !(idstr = s->ensureLinear(cx)))
-                return NULL;
+                return nullptr;
         }
 
         for (int j = 0; j < valcnt; j++) {
             /*
              * Censor an accessor descriptor getter or setter part if it's
              * undefined.
              */
             if (gsop[j] && val[j].isUndefined())
                 continue;
 
             /* Convert val[j] to its canonical source form. */
             RootedString valstr(cx, ValueToSource(cx, val[j]));
             if (!valstr)
-                return NULL;
+                return nullptr;
             const jschar *vchars = valstr->getChars(cx);
             if (!vchars)
-                return NULL;
+                return nullptr;
             size_t vlength = valstr->length();
 
             /*
              * Remove '(function ' from the beginning of valstr and ')' from the
              * end so that we can put "get" in front of the function definition.
              */
             if (gsop[j] && IsFunctionObject(val[j])) {
                 const jschar *start = vchars;
@@ -234,58 +234,58 @@ js::ObjectToSource(JSContext *cx, Handle
                 if (vchars)
                     vchars = js_strchr_limit(vchars, '(', end);
 
                 if (vchars) {
                     if (*vchars == ' ')
                         vchars++;
                     vlength = end - vchars - parenChomp;
                 } else {
-                    gsop[j].set(NULL);
+                    gsop[j].set(nullptr);
                     vchars = start;
                 }
             }
 
             if (comma && !buf.append(", "))
-                return NULL;
+                return nullptr;
             comma = true;
 
             if (gsop[j])
                 if (!buf.append(gsop[j]) || !buf.append(' '))
-                    return NULL;
+                    return nullptr;
 
             if (!buf.append(idstr))
-                return NULL;
+                return nullptr;
             if (!buf.append(gsop[j] ? ' ' : ':'))
-                return NULL;
+                return nullptr;
 
             if (!buf.append(vchars, vlength))
-                return NULL;
+                return nullptr;
         }
     }
 
     if (!buf.append('}'))
-        return NULL;
+        return nullptr;
     if (outermost && !buf.append(')'))
-        return NULL;
+        return nullptr;
 
     return buf.finishString();
 }
 #endif /* JS_HAS_TOSOURCE */
 
 JSString *
 JS_BasicObjectToString(JSContext *cx, HandleObject obj)
 {
     const char *className = JSObject::className(cx, obj);
 
     StringBuffer sb(cx);
     if (!sb.append("[object ") || !sb.appendInflated(className, strlen(className)) ||
         !sb.append("]"))
     {
-        return NULL;
+        return nullptr;
     }
     return sb.finishString();
 }
 
 /* ES5 15.2.4.2.  Note steps 1 and 2 are errata. */
 static bool
 obj_toString(JSContext *cx, unsigned argc, Value *vp)
 {
@@ -326,17 +326,17 @@ obj_toLocaleString(JSContext *cx, unsign
 
     /* Step 1. */
     RootedObject obj(cx, ToObject(cx, args.thisv()));
     if (!obj)
         return false;
 
     /* Steps 2-4. */
     RootedId id(cx, NameToId(cx->names().toString));
-    return obj->callMethod(cx, id, 0, NULL, args.rval());
+    return obj->callMethod(cx, id, 0, nullptr, args.rval());
 }
 
 static bool
 obj_valueOf(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     RootedObject obj(cx, ToObject(cx, args.thisv()));
     if (!obj)
@@ -353,17 +353,17 @@ template<DefineType Type>
 static bool
 DefineAccessor(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     if (!BoxNonStrictThis(cx, args))
         return false;
 
     if (args.length() < 2 || !js_IsCallable(args[1])) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_BAD_GETTER_OR_SETTER,
                              Type == Getter ? js_getter_str : js_setter_str);
         return false;
     }
 
     RootedId id(cx);
     if (!ValueToId<CanGC>(cx, args[0], &id))
         return false;
@@ -497,17 +497,17 @@ obj_getPrototypeOf(JSContext *cx, unsign
         return false;
     }
 
     if (args[0].isPrimitive()) {
         RootedValue val(cx, args[0]);
         char *bytes = DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, val, NullPtr());
         if (!bytes)
             return false;
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_UNEXPECTED_TYPE, bytes, "not an object");
         js_free(bytes);
         return false;
     }
 
     /* Step 2. */
 
     /*
@@ -592,17 +592,17 @@ obj_unwatch(JSContext *cx, unsigned argc
     args.rval().setUndefined();
     RootedId id(cx);
     if (argc != 0) {
         if (!ValueToId<CanGC>(cx, args[0], &id))
             return false;
     } else {
         id = JSID_VOID;
     }
-    return JS_ClearWatchPoint(cx, obj, id, NULL, NULL);
+    return JS_ClearWatchPoint(cx, obj, id, nullptr, nullptr);
 }
 
 #endif /* JS_HAS_OBJ_WATCHPOINT */
 
 /* ECMA 15.2.4.5. */
 static bool
 obj_hasOwnProperty(JSContext *cx, unsigned argc, Value *vp)
 {
@@ -677,28 +677,28 @@ obj_isPrototypeOf(JSContext *cx, unsigne
     return true;
 }
 
 /* ES5 15.2.3.5: Object.create(O [, Properties]) */
 static bool
 obj_create(JSContext *cx, unsigned argc, Value *vp)
 {
     if (argc == 0) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED,
                              "Object.create", "0", "s");
         return false;
     }
 
     CallArgs args = CallArgsFromVp(argc, vp);
     RootedValue v(cx, args[0]);
     if (!v.isObjectOrNull()) {
         char *bytes = DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, v, NullPtr());
         if (!bytes)
             return false;
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_UNEXPECTED_TYPE,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
                              bytes, "not an object or null");
         js_free(bytes);
         return false;
     }
 
     RootedObject proto(cx, v.toObjectOrNull());
 
     /*
@@ -707,17 +707,17 @@ obj_create(JSContext *cx, unsigned argc,
      */
     RootedObject obj(cx, NewObjectWithGivenProto(cx, &JSObject::class_, proto, &args.callee().global()));
     if (!obj)
         return false;
 
     /* 15.2.3.5 step 4. */
     if (args.hasDefined(1)) {
         if (args[1].isPrimitive()) {
-            JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NOT_NONNULL_OBJECT);
+            JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NOT_NONNULL_OBJECT);
             return false;
         }
 
         RootedObject props(cx, &args[1].toObject());
         if (!DefineProperties(cx, obj, props))
             return false;
     }
 
@@ -859,17 +859,17 @@ obj_defineProperties(JSContext *cx, unsi
     /* Steps 1 and 7. */
     RootedObject obj(cx);
     if (!GetFirstArgumentAsObject(cx, args, "Object.defineProperties", &obj))
         return false;
     args.rval().setObject(*obj);
 
     /* Step 2. */
     if (args.length() < 2) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED,
                              "Object.defineProperties", "0", "s");
         return false;
     }
     RootedValue val(cx, args[1]);
     RootedObject props(cx, ToObject(cx, val));
     if (!props)
         return false;
 
--- a/js/src/builtin/ParallelArray.cpp
+++ b/js/src/builtin/ParallelArray.cpp
@@ -98,32 +98,32 @@ ParallelArrayObject::construct(JSContext
 
 
 /* static */ JSFunction *
 ParallelArrayObject::getConstructor(JSContext *cx, unsigned argc)
 {
     RootedPropertyName ctorName(cx, ctorNames[js::Min(argc, NumCtors - 1)]);
     RootedValue ctorValue(cx);
     if (!cx->global()->getIntrinsicValue(cx, ctorName, &ctorValue))
-        return NULL;
+        return nullptr;
     JS_ASSERT(ctorValue.isObject() && ctorValue.toObject().is<JSFunction>());
     return &ctorValue.toObject().as<JSFunction>();
 }
 
 /*static*/ JSObject *
 ParallelArrayObject::newInstance(JSContext *cx, NewObjectKind newKind /* = GenericObject */)
 {
     gc::AllocKind kind = gc::GetGCObjectKind(NumFixedSlots);
     RootedObject result(cx, NewBuiltinClassInstance(cx, &class_, kind, newKind));
     if (!result)
-        return NULL;
+        return nullptr;
 
     // Add in the basic PA properties now with default values:
     if (!initProps(cx, result))
-        return NULL;
+        return nullptr;
 
     return result;
 }
 
 /*static*/ bool
 ParallelArrayObject::constructHelper(JSContext *cx, MutableHandleFunction ctor, CallArgs &args0)
 {
     RootedObject result(cx, newInstance(cx, TenuredObject));
@@ -190,60 +190,60 @@ ParallelArrayObject::initClass(JSContext
             "ParallelArrayConstructEmpty",
             "ParallelArrayConstructFromArray",
             "ParallelArrayConstructFromFunction",
             "ParallelArrayConstructFromFunctionMode"
         };
         for (uint32_t i = 0; i < NumCtors; i++) {
             JSAtom *atom = Atomize(cx, ctorStrs[i], strlen(ctorStrs[i]), InternAtom);
             if (!atom)
-                return NULL;
+                return nullptr;
             ctorNames[i].init(atom->asPropertyName());
         }
     }
 
     Rooted<GlobalObject *> global(cx, &obj->as<GlobalObject>());
 
     RootedObject proto(cx, global->createBlankPrototype(cx, &protoClass));
     if (!proto)
-        return NULL;
+        return nullptr;
 
     JSProtoKey key = JSProto_ParallelArray;
     RootedFunction ctor(cx, global->createConstructor(cx, construct,
                                                       cx->names().ParallelArray, 0));
     if (!ctor ||
         !LinkConstructorAndPrototype(cx, ctor, proto) ||
-        !DefinePropertiesAndBrand(cx, proto, NULL, methods) ||
+        !DefinePropertiesAndBrand(cx, proto, nullptr, methods) ||
         !DefineConstructorAndPrototype(cx, global, key, ctor, proto))
     {
-        return NULL;
+        return nullptr;
     }
 
     // Define the length getter.
     {
         const char lengthStr[] = "ParallelArrayLength";
         JSAtom *atom = Atomize(cx, lengthStr, strlen(lengthStr));
         if (!atom)
-            return NULL;
+            return nullptr;
         Rooted<PropertyName *> lengthProp(cx, atom->asPropertyName());
         RootedValue lengthValue(cx);
         if (!cx->global()->getIntrinsicValue(cx, lengthProp, &lengthValue))
-            return NULL;
+            return nullptr;
         RootedObject lengthGetter(cx, &lengthValue.toObject());
         if (!lengthGetter)
-            return NULL;
+            return nullptr;
 
         RootedId lengthId(cx, AtomToId(cx->names().length));
         unsigned flags = JSPROP_PERMANENT | JSPROP_SHARED | JSPROP_GETTER;
         RootedValue value(cx, UndefinedValue());
         if (!DefineNativeProperty(cx, proto, lengthId, value,
-                                  JS_DATA_TO_FUNC_PTR(PropertyOp, lengthGetter.get()), NULL,
+                                  JS_DATA_TO_FUNC_PTR(PropertyOp, lengthGetter.get()), nullptr,
                                   flags, 0, 0))
         {
-            return NULL;
+            return nullptr;
         }
     }
 
     return proto;
 }
 
 bool
 ParallelArrayObject::is(const Value &v)
--- a/js/src/builtin/Profilers.cpp
+++ b/js/src/builtin/Profilers.cpp
@@ -48,20 +48,20 @@ UnsafeError(const char *format, ...)
 JS_PUBLIC_API(const char *)
 JS_UnsafeGetLastProfilingError()
 {
     return gLastError;
 }
 
 #ifdef __APPLE__
 static bool
-StartOSXProfiling(const char *profileName = NULL)
+StartOSXProfiling(const char *profileName = nullptr)
 {
     bool ok = true;
-    const char* profiler = NULL;
+    const char* profiler = nullptr;
 #ifdef MOZ_SHARK
     ok = Shark::Start();
     profiler = "Shark";
 #endif
 #ifdef MOZ_INSTRUMENTS
     ok = Instruments::Start();
     profiler = "Instruments";
 #endif
@@ -194,17 +194,17 @@ JS_DumpProfile(const char *outfile, cons
 }
 
 #ifdef MOZ_PROFILING
 
 struct RequiredStringArg {
     JSContext *mCx;
     char *mBytes;
     RequiredStringArg(JSContext *cx, const CallArgs &args, size_t argi, const char *caller)
-        : mCx(cx), mBytes(NULL)
+        : mCx(cx), mBytes(nullptr)
     {
         if (args.length() <= argi) {
             JS_ReportError(cx, "%s: not enough arguments", caller);
         } else if (!args[argi].isString()) {
             JS_ReportError(cx, "%s: invalid arguments (string expected)", caller);
         } else {
             mBytes = JS_EncodeString(cx, args[argi].toString());
         }
@@ -217,65 +217,65 @@ struct RequiredStringArg {
     }
 };
 
 static bool
 StartProfiling(JSContext *cx, unsigned argc, jsval *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     if (args.length() == 0) {
-        args.rval().setBoolean(JS_StartProfiling(NULL));
+        args.rval().setBoolean(JS_StartProfiling(nullptr));
         return true;
     }
 
     RequiredStringArg profileName(cx, args, 0, "startProfiling");
     if (!profileName)
         return false;
     args.rval().setBoolean(JS_StartProfiling(profileName.mBytes));
     return true;
 }
 
 static bool
 StopProfiling(JSContext *cx, unsigned argc, jsval *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     if (args.length() == 0) {
-        args.rval().setBoolean(JS_StopProfiling(NULL));
+        args.rval().setBoolean(JS_StopProfiling(nullptr));
         return true;
     }
 
     RequiredStringArg profileName(cx, args, 0, "stopProfiling");
     if (!profileName)
         return false;
     args.rval().setBoolean(JS_StopProfiling(profileName.mBytes));
     return true;
 }
 
 static bool
 PauseProfilers(JSContext *cx, unsigned argc, jsval *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     if (args.length() == 0) {
-        args.rval().setBoolean(JS_PauseProfilers(NULL));
+        args.rval().setBoolean(JS_PauseProfilers(nullptr));
         return true;
     }
 
     RequiredStringArg profileName(cx, args, 0, "pauseProfiling");
     if (!profileName)
         return false;
     args.rval().setBoolean(JS_PauseProfilers(profileName.mBytes));
     return true;
 }
 
 static bool
 ResumeProfilers(JSContext *cx, unsigned argc, jsval *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     if (args.length() == 0) {
-        args.rval().setBoolean(JS_ResumeProfilers(NULL));
+        args.rval().setBoolean(JS_ResumeProfilers(nullptr));
         return true;
     }
 
     RequiredStringArg profileName(cx, args, 0, "resumeProfiling");
     if (!profileName)
         return false;
     args.rval().setBoolean(JS_ResumeProfilers(profileName.mBytes));
     return true;
@@ -283,24 +283,24 @@ ResumeProfilers(JSContext *cx, unsigned 
 
 /* Usage: DumpProfile([filename[, profileName]]) */
 static bool
 DumpProfile(JSContext *cx, unsigned argc, jsval *vp)
 {
     bool ret;
     CallArgs args = CallArgsFromVp(argc, vp);
     if (args.length() == 0) {
-        ret = JS_DumpProfile(NULL, NULL);
+        ret = JS_DumpProfile(nullptr, nullptr);
     } else {
         RequiredStringArg filename(cx, args, 0, "dumpProfile");
         if (!filename)
             return false;
 
         if (args.length() == 1) {
-            ret = JS_DumpProfile(filename.mBytes, NULL);
+            ret = JS_DumpProfile(filename.mBytes, nullptr);
         } else {
             RequiredStringArg profileName(cx, args, 1, "dumpProfile");
             if (!profileName)
                 return false;
 
             ret = JS_DumpProfile(filename.mBytes, profileName.mBytes);
         }
     }
@@ -338,17 +338,17 @@ StopCallgrind(JSContext *cx, unsigned ar
     return true;
 }
 
 static bool
 DumpCallgrind(JSContext *cx, unsigned argc, jsval *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     if (args.length() == 0) {
-        args.rval().setBoolean(js_DumpCallgrind(NULL));
+        args.rval().setBoolean(js_DumpCallgrind(nullptr));
         return true;
     }
 
     RequiredStringArg outFile(cx, args, 0, "dumpCallgrind");
     if (!outFile)
         return false;
 
     args.rval().setBoolean(js_DumpCallgrind(outFile.mBytes));
@@ -500,20 +500,20 @@ bool js_StartPerf()
         }
 
         // Split |flags| on spaces.  (Don't bother to free it -- we're going to
         // exec anyway.)
         char *toksave;
         char *tok = strtok_r(strdup(flags), " ", &toksave);
         while (tok) {
             args.append(tok);
-            tok = strtok_r(NULL, " ", &toksave);
+            tok = strtok_r(nullptr, " ", &toksave);
         }
 
-        args.append((char*) NULL);
+        args.append((char*) nullptr);
 
         execvp("perf", const_cast<char**>(args.begin()));
 
         /* Reached only if execlp fails. */
         fprintf(stderr, "Unable to start perf.\n");
         exit(1);
     }
     else if (childPid > 0) {
@@ -535,19 +535,19 @@ bool js_StopPerf()
         UnsafeError("js_StopPerf: perf is not running.\n");
         return true;
     }
 
     if (kill(perfPid, SIGINT)) {
         UnsafeError("js_StopPerf: kill failed\n");
 
         // Try to reap the process anyway.
-        waitpid(perfPid, NULL, WNOHANG);
+        waitpid(perfPid, nullptr, WNOHANG);
     }
     else {
-        waitpid(perfPid, NULL, 0);
+        waitpid(perfPid, nullptr, 0);
     }
 
     perfPid = 0;
     return true;
 }
 
 #endif /* __linux__ */
--- a/js/src/builtin/Profilers.h
+++ b/js/src/builtin/Profilers.h
@@ -15,17 +15,17 @@
 
 /**
  * Start any profilers that are available and have been configured on for this
  * platform. This is NOT thread safe.
  *
  * The profileName is used by some profilers to describe the current profiling
  * run. It may be used for part of the filename of the output, but the
  * specifics depend on the profiler. Many profilers will ignore it. Passing in
- * NULL is legal; some profilers may use it to output to stdout or similar.
+ * nullptr is legal; some profilers may use it to output to stdout or similar.
  *
  * Returns true if no profilers fail to start.
  */
 extern JS_PUBLIC_API(bool)
 JS_StartProfiling(const char *profileName);
 
 /**
  * Stop any profilers that were previously started with JS_StartProfiling.
--- a/js/src/builtin/RegExp.cpp
+++ b/js/src/builtin/RegExp.cpp
@@ -169,25 +169,25 @@ EscapeNakedForwardSlashes(JSContext *cx,
     StringBuffer sb(cx);
 
     for (const jschar *it = oldChars; it < oldChars + oldLen; ++it) {
         if (*it == '/' && (it == oldChars || it[-1] != '\\')) {
             /* There's a forward slash that needs escaping. */
             if (sb.empty()) {
                 /* This is the first one we've seen, copy everything up to this point. */
                 if (!sb.reserve(oldLen + 1))
-                    return NULL;
+                    return nullptr;
                 sb.infallibleAppend(oldChars, size_t(it - oldChars));
             }
             if (!sb.append('\\'))
-                return NULL;
+                return nullptr;
         }
 
         if (!sb.empty() && !sb.append(*it))
-            return NULL;
+            return nullptr;
     }
 
     return sb.empty() ? (JSAtom *)unescaped : sb.finishAtom();
 }
 
 /*
  * Compile a new |RegExpShared| for the |RegExpObject|.
  *
@@ -222,17 +222,17 @@ CompileRegExpObject(JSContext *cx, RegEx
         /*
          * Beware, sourceObj may be a (transparent) proxy to a RegExp, so only
          * use generic (proxyable) operations on sourceObj that do not assume
          * sourceObj.is<RegExpObject>().
          */
         RootedObject sourceObj(cx, &sourceValue.toObject());
 
         if (args.hasDefined(1)) {
-            JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NEWREGEXP_FLAGGED);
+            JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NEWREGEXP_FLAGGED);
             return false;
         }
 
         /*
          * Only extract the 'flags' out of sourceObj; do not reuse the
          * RegExpShared since it may be from a different compartment.
          */
         RegExpFlag flags;
@@ -280,17 +280,17 @@ CompileRegExpObject(JSContext *cx, RegEx
         if (!ParseRegExpFlags(cx, flagStr, &flags))
             return false;
     }
 
     RootedAtom escapedSourceStr(cx, EscapeNakedForwardSlashes(cx, source));
     if (!escapedSourceStr)
         return false;
 
-    if (!js::RegExpShared::checkSyntax(cx, NULL, escapedSourceStr))
+    if (!js::RegExpShared::checkSyntax(cx, nullptr, escapedSourceStr))
         return false;
 
     RegExpStatics *res = cx->global()->getRegExpStatics();
     RegExpObject *reobj = builder.build(escapedSourceStr, RegExpFlag(flags | res->getFlags()));
     if (!reobj)
         return false;
 
     args.rval().setObject(*reobj);
@@ -480,41 +480,41 @@ JSObject *
 js_InitRegExpClass(JSContext *cx, HandleObject obj)
 {
     JS_ASSERT(obj->isNative());
 
     Rooted<GlobalObject*> global(cx, &obj->as<GlobalObject>());
 
     RootedObject proto(cx, global->createBlankPrototype(cx, &RegExpObject::class_));
     if (!proto)
-        return NULL;
-    proto->setPrivate(NULL);
+        return nullptr;
+    proto->setPrivate(nullptr);
 
     HandlePropertyName empty = cx->names().empty;
     RegExpObjectBuilder builder(cx, &proto->as<RegExpObject>());
     if (!builder.build(empty, RegExpFlag(0)))
-        return NULL;
+        return nullptr;
 
-    if (!DefinePropertiesAndBrand(cx, proto, NULL, regexp_methods))
-        return NULL;
+    if (!DefinePropertiesAndBrand(cx, proto, nullptr, regexp_methods))
+        return nullptr;
 
     RootedFunction ctor(cx);
     ctor = global->createConstructor(cx, regexp_construct, cx->names().RegExp, 2);
     if (!ctor)
-        return NULL;
+        return nullptr;
 
     if (!LinkConstructorAndPrototype(cx, ctor, proto))
-        return NULL;
+        return nullptr;
 
     /* Add static properties to the RegExp constructor. */
     if (!JS_DefineProperties(cx, ctor, regexp_static_props))
-        return NULL;
+        return nullptr;
 
     if (!DefineConstructorAndPrototype(cx, global, JSProto_RegExp, ctor, proto))
-        return NULL;
+        return nullptr;
 
     return proto;
 }
 
 RegExpRunStatus
 js::ExecuteRegExp(JSContext *cx, HandleObject regexp, HandleString string,
                   MatchConduit &matches, RegExpStaticsUpdate staticsUpdate)
 {
@@ -522,17 +522,17 @@ js::ExecuteRegExp(JSContext *cx, HandleO
     Rooted<RegExpObject*> reobj(cx, &regexp->as<RegExpObject>());
 
     RegExpGuard re(cx);
     if (!reobj->getShared(cx, &re))
         return RegExpRunStatus_Error;
 
     RegExpStatics *res = (staticsUpdate == UpdateRegExpStatics)
                          ? cx->global()->getRegExpStatics()
-                         : NULL;
+                         : nullptr;
 
     /* Step 3. */
     Rooted<JSLinearString*> input(cx, string->ensureLinear(cx));
     if (!input)
         return RegExpRunStatus_Error;
 
     /* Step 4. */
     RootedValue lastIndex(cx, reobj->getLastIndex());
--- a/js/src/builtin/RegExp.h
+++ b/js/src/builtin/RegExp.h
@@ -25,18 +25,18 @@ enum RegExpStaticsUpdate { UpdateRegExpS
 
 RegExpRunStatus
 ExecuteRegExp(JSContext *cx, HandleObject regexp, HandleString string,
               MatchConduit &matches, RegExpStaticsUpdate staticsUpdate);
 
 /*
  * Legacy behavior of ExecuteRegExp(), which is baked into the JSAPI.
  *
- * |res| may be NULL if the RegExpStatics are not to be updated.
- * |input| may be NULL if there is no JSString corresponding to
+ * |res| may be nullptr if the RegExpStatics are not to be updated.
+ * |input| may be nullptr if there is no JSString corresponding to
  * |chars| and |length|.
  */
 bool
 ExecuteRegExpLegacy(JSContext *cx, RegExpStatics *res, RegExpObject &reobj,
                     Handle<JSLinearString*> input, const jschar *chars, size_t length,
                     size_t *lastIndex, bool test, MutableHandleValue rval);
 
 /* Translation from MatchPairs to a JS array in regexp_exec()'s output format. */
--- a/js/src/builtin/TestingFunctions.cpp
+++ b/js/src/builtin/TestingFunctions.cpp
@@ -28,17 +28,17 @@
 using namespace js;
 using namespace JS;
 
 using mozilla::ArrayLength;
 
 static bool
 GetBuildConfiguration(JSContext *cx, unsigned argc, jsval *vp)
 {
-    RootedObject info(cx, JS_NewObject(cx, NULL, NULL, NULL));
+    RootedObject info(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
     if (!info)
         return false;
     RootedValue value(cx);
 
 #ifdef JSGC_ROOT_ANALYSIS
     value = BooleanValue(true);
 #else
     value = BooleanValue(false);
@@ -593,26 +593,26 @@ NondeterministicGetWeakMapKeys(JSContext
     CallArgs args = CallArgsFromVp(argc, vp);
 
     if (argc != 1) {
         RootedObject callee(cx, &args.callee());
         ReportUsageError(cx, callee, "Wrong number of arguments");
         return false;
     }
     if (!args[0].isObject()) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NOT_EXPECTED_TYPE,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NOT_EXPECTED_TYPE,
                              "nondeterministicGetWeakMapKeys", "WeakMap",
                              InformalValueTypeName(args[0]));
         return false;
     }
     RootedObject arr(cx);
     if (!JS_NondeterministicGetWeakMapKeys(cx, &args[0].toObject(), arr.address()))
         return false;
     if (!arr) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NOT_EXPECTED_TYPE,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NOT_EXPECTED_TYPE,
                              "nondeterministicGetWeakMapKeys", "WeakMap",
                              args[0].toObject().getClass()->name);
         return false;
     }
     args.rval().setObject(*arr);
     return true;
 }
 
@@ -723,35 +723,35 @@ CountHeap(JSContext *cx, unsigned argc, 
     }
 
     JS_TracerInit(&countTracer.base, JS_GetRuntime(cx), CountHeapNotify);
     if (!countTracer.visited.init()) {
         JS_ReportOutOfMemory(cx);
         return false;
     }
     countTracer.ok = true;
-    countTracer.traceList = NULL;
-    countTracer.recycleList = NULL;
+    countTracer.traceList = nullptr;
+    countTracer.recycleList = nullptr;
 
     if (startValue.isUndefined()) {
         JS_TraceRuntime(&countTracer.base);
     } else {
         JS_CallValueTracer(&countTracer.base, startValue.address(), "root");
     }
 
     counter = 0;
-    while ((node = countTracer.traceList) != NULL) {
+    while ((node = countTracer.traceList) != nullptr) {
         if (traceKind == -1 || node->kind == traceKind)
             counter++;
         countTracer.traceList = node->next;
         node->next = countTracer.recycleList;
         countTracer.recycleList = node;
         JS_TraceChildren(&countTracer.base, node->thing, node->kind);
     }
-    while ((node = countTracer.recycleList) != NULL) {
+    while ((node = countTracer.recycleList) != nullptr) {
         countTracer.recycleList = node->next;
         js_free(node);
     }
     if (!countTracer.ok) {
         JS_ReportOutOfMemory(cx);
         return false;
     }
 
@@ -804,17 +804,17 @@ static const JSClass FinalizeCounterClas
 
 static bool
 MakeFinalizeObserver(JSContext *cx, unsigned argc, jsval *vp)
 {
     RootedObject scope(cx, JS::CurrentGlobalOrNull(cx));
     if (!scope)
         return false;
 
-    JSObject *obj = JS_NewObjectWithGivenProto(cx, &FinalizeCounterClass, NULL, scope);
+    JSObject *obj = JS_NewObjectWithGivenProto(cx, &FinalizeCounterClass, nullptr, scope);
     if (!obj)
         return false;
 
     *vp = OBJECT_TO_JSVAL(obj);
     return true;
 }
 
 static bool
@@ -822,17 +822,17 @@ FinalizeCount(JSContext *cx, unsigned ar
 {
     *vp = INT_TO_JSVAL(finalizeCount);
     return true;
 }
 
 static bool
 DumpHeapComplete(JSContext *cx, unsigned argc, jsval *vp)
 {
-    const char *fileName = NULL;
+    const char *fileName = nullptr;
     JSAutoByteString fileNameBytes;
     if (argc > 0) {
         Value v = JS_ARGV(cx, vp)[0];
         if (v.isString()) {
             JSString *str = v.toString();
             if (!fileNameBytes.encodeLatin1(cx, str))
                 return false;
             fileName = fileNameBytes.ptr();
@@ -911,17 +911,17 @@ DisplayName(JSContext *cx, unsigned argc
     if (argc == 0 || !args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
         RootedObject arg(cx, &args.callee());
         ReportUsageError(cx, arg, "Must have one function argument");
         return false;
     }
 
     JSFunction *fun = &args[0].toObject().as<JSFunction>();
     JSString *str = fun->displayAtom();
-    vp->setString(str == NULL ? cx->runtime()->emptyString : str);
+    vp->setString(str == nullptr ? cx->runtime()->emptyString : str);
     return true;
 }
 
 bool
 js::testingFunc_inParallelSection(JSContext *cx, unsigned argc, jsval *vp)
 {
     // If we were actually *in* a parallel section, then this function
     // would be inlined to TRUE in ion-generated code.
@@ -935,17 +935,17 @@ static const char *ObjectMetadataPropert
 static bool
 ShellObjectMetadataCallback(JSContext *cx, JSObject **pmetadata)
 {
     RootedValue fun(cx);
     if (!JS_GetProperty(cx, cx->global(), ObjectMetadataPropertyName, &fun))
         return false;
 
     RootedValue rval(cx);
-    if (!Invoke(cx, UndefinedValue(), fun, 0, NULL, &rval))
+    if (!Invoke(cx, UndefinedValue(), fun, 0, nullptr, &rval))
         return false;
 
     if (rval.isObject())
         *pmetadata = &rval.toObject();
 
     return true;
 }
 
@@ -954,21 +954,21 @@ SetObjectMetadataCallback(JSContext *cx,
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     args.rval().setUndefined();
 
     if (argc == 0 || !args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
         if (!JS_DeleteProperty(cx, cx->global(), ObjectMetadataPropertyName))
             return false;
-        js::SetObjectMetadataCallback(cx, NULL);
+        js::SetObjectMetadataCallback(cx, nullptr);
         return true;
     }
 
-    if (!JS_DefineProperty(cx, cx->global(), ObjectMetadataPropertyName, args[0], NULL, NULL, 0))
+    if (!JS_DefineProperty(cx, cx->global(), ObjectMetadataPropertyName, args[0], nullptr, nullptr, 0))
         return false;
 
     js::SetObjectMetadataCallback(cx, ShellObjectMetadataCallback);
     return true;
 }
 
 static bool
 SetObjectMetadata(JSContext *cx, unsigned argc, jsval *vp)
--- a/js/src/builtin/TypeRepresentation.cpp
+++ b/js/src/builtin/TypeRepresentation.cpp
@@ -32,20 +32,20 @@ const Class TypeRepresentation::class_ =
     JS_PropertyStub,         /* addProperty */
     JS_DeletePropertyStub,   /* delProperty */
     JS_PropertyStub,         /* getProperty */
     JS_StrictPropertyStub,   /* setProperty */
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub,
     obj_finalize,
-    NULL,           /* checkAccess */
-    NULL,           /* call        */
-    NULL,           /* hasInstance */
-    NULL,           /* construct   */
+    nullptr,        /* checkAccess */
+    nullptr,        /* call        */
+    nullptr,        /* hasInstance */
+    nullptr,        /* construct   */
     obj_trace,
 };
 
 ///////////////////////////////////////////////////////////////////////////
 // Hashing
 
 bool
 TypeRepresentationHasher::match(TypeRepresentation *key1,
@@ -221,37 +221,37 @@ StructTypeRepresentation::init(JSContext
     // consistency across build environments.
     uint32_t totalSize = 0;
 
     for (size_t i = 0; i < ids.length(); i++) {
         TypeRepresentation *fieldTypeRepr = fromOwnerObject(typeReprOwners[i]);
 
         uint32_t alignedSize = alignTo(totalSize, fieldTypeRepr->alignment());
         if (alignedSize < totalSize) {
-            JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+            JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                                  JSMSG_TYPEDOBJECT_TOO_BIG);
             return false;
         }
 
         new(fields() + i) StructField(i, ids[i], fieldTypeRepr, alignedSize);
         alignment_ = js::Max(alignment_, fieldTypeRepr->alignment());
 
         uint32_t incrementedSize = alignedSize + fieldTypeRepr->size();
         if (incrementedSize < alignedSize) {
-            JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+            JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                                  JSMSG_TYPEDOBJECT_TOO_BIG);
             return false;
         }
 
         totalSize = incrementedSize;
     }
 
     uint32_t alignedSize = alignTo(totalSize, alignment_);
     if (alignedSize < totalSize) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_TYPEDOBJECT_TOO_BIG);
         return false;
     }
 
     size_ = alignedSize;
     return true;
 }
 
@@ -264,31 +264,31 @@ TypeRepresentation::addToTableOrFree(JSC
 {
     JS_ASSERT(!ownerObject_);
 
     JSCompartment *comp = cx->compartment();
 
     if (!comp->typeReprs.add(p, this)) {
         js_ReportOutOfMemory(cx);
         js_free(this); // do not finalize, not present in the table
-        return NULL;
+        return nullptr;
     }
 
     // Now that the object is in the table, try to make the owner
     // object. If this succeeds, then the owner will remove from the
     // table once it is finalized. Otherwise, if this fails, we must
     // remove ourselves from the table ourselves and report an error.
     RootedObject ownerObject(cx,
         NewBuiltinClassInstance(cx,
                                 &class_,
                                 gc::GetGCObjectKind(&class_)));
     if (!ownerObject) {
         comp->typeReprs.remove(this);
         js_free(this);
-        return NULL;
+        return nullptr;
     }
     ownerObject->setPrivate(this);
     ownerObject_.init(ownerObject);
     return &*ownerObject;
 }
 
 /*static*/
 JSObject *
@@ -302,17 +302,17 @@ ScalarTypeRepresentation::Create(JSConte
     if (p)
         return (*p)->ownerObject();
 
     // Note: cannot use cx->new_ because constructor is private.
     ScalarTypeRepresentation *ptr =
         (ScalarTypeRepresentation *) cx->malloc_(
             sizeof(ScalarTypeRepresentation));
     if (!ptr)
-        return NULL;
+        return nullptr;
     new(ptr) ScalarTypeRepresentation(type);
 
     return ptr->addToTableOrFree(cx, p);
 }
 
 /*static*/
 JSObject *
 ArrayTypeRepresentation::Create(JSContext *cx,
@@ -321,32 +321,32 @@ ArrayTypeRepresentation::Create(JSContex
 {
     JSCompartment *comp = cx->compartment();
 
     // Overly conservative, since we are using `size_t` to represent
     // size, but `SafeMul` operators on `int32_t` types. Still, it
     // should be good enough for now.
     int32_t temp;
     if (!SafeMul(element->size(), length, &temp)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_TYPEDOBJECT_TOO_BIG);
-        return NULL;
+        return nullptr;
     }
 
     ArrayTypeRepresentation sample(element, length);
     TypeRepresentationHash::AddPtr p = comp->typeReprs.lookupForAdd(&sample);
     if (p)
         return (*p)->ownerObject();
 
     // Note: cannot use cx->new_ because constructor is private.
     ArrayTypeRepresentation *ptr =
         (ArrayTypeRepresentation *) cx->malloc_(
             sizeof(ArrayTypeRepresentation));
     if (!ptr)
-        return NULL;
+        return nullptr;
     new(ptr) ArrayTypeRepresentation(element, length);
 
     return ptr->addToTableOrFree(cx, p);
 }
 
 /*static*/
 JSObject *
 StructTypeRepresentation::Create(JSContext *cx,
@@ -357,17 +357,17 @@ StructTypeRepresentation::Create(JSConte
     JSCompartment *comp = cx->compartment();
 
     // Note: cannot use cx->new_ because constructor is private.
     size_t size = sizeof(StructTypeRepresentation) + count * sizeof(StructField);
     StructTypeRepresentation *ptr =
         (StructTypeRepresentation *) cx->malloc_(size);
     new(ptr) StructTypeRepresentation();
     if (!ptr->init(cx, ids, typeReprOwners))
-        return NULL;
+        return nullptr;
 
     TypeRepresentationHash::AddPtr p = comp->typeReprs.lookupForAdd(ptr);
     if (p) {
         js_free(ptr); // do not finalize, not present in the table
         return (*p)->ownerObject();
     }
 
     return ptr->addToTableOrFree(cx, p);
@@ -541,17 +541,17 @@ StructTypeRepresentation::appendStringSt
 
 const StructField *
 StructTypeRepresentation::fieldNamed(jsid id) const
 {
     for (size_t i = 0; i < fieldCount(); i++) {
         if (field(i).id.get() == id)
             return &field(i);
     }
-    return NULL;
+    return nullptr;
 }
 
 /*static*/ bool
 TypeRepresentation::isTypeRepresentationOwnerObject(JSObject *obj)
 {
     return obj->getClass() == &class_;
 }
 
--- a/js/src/builtin/TypedObject.cpp
+++ b/js/src/builtin/TypedObject.cpp
@@ -63,17 +63,17 @@ static bool
 DataThrowError(JSContext *cx, unsigned argc, Value *vp)
 {
     return ReportIsNotFunction(cx, *vp);
 }
 
 static void
 ReportCannotConvertTo(JSContext *cx, HandleValue fromValue, const char *toType)
 {
-    JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CONVERT_TO,
+    JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CONVERT_TO,
                          InformalValueTypeName(fromValue), toType);
 }
 
 static void
 ReportCannotConvertTo(JSContext *cx, HandleObject fromObject, const char *toType)
 {
     RootedValue fromValue(cx, ObjectValue(*fromObject));
     ReportCannotConvertTo(cx, fromValue, toType);
@@ -113,17 +113,17 @@ Clamp(int32_t value, int32_t min, int32_
         return max;
     return value;
 }
 
 static inline JSObject *
 ToObjectIfObject(HandleValue value)
 {
     if (!value.isObject())
-        return NULL;
+        return nullptr;
 
     return &value.toObject();
 }
 
 static inline bool
 IsNumericType(HandleObject type)
 {
     return type &&
@@ -265,32 +265,32 @@ const Class js::TypeClass = {
 
 static bool
 TypeEquivalent(JSContext *cx, unsigned int argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     RootedObject thisObj(cx, ToObjectIfObject(args.thisv()));
     if (!thisObj || !IsBinaryType(thisObj)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_INCOMPATIBLE_PROTO,
                              "Type", "equivalent",
                              InformalValueTypeName(args.thisv()));
         return false;
     }
 
     if (args.length() < 1) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED,
                              "Type.equivalent", "1", "s");
         return false;
     }
 
     RootedObject otherObj(cx, ToObjectIfObject(args[0]));
     if (!otherObj || !IsBinaryType(otherObj)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_TYPEDOBJECT_NOT_TYPE_OBJECT);
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_TYPEDOBJECT_NOT_TYPE_OBJECT);
         return false;
     }
 
     TypeRepresentation *thisRepr = typeRepresentation(thisObj);
     TypeRepresentation *otherRepr = typeRepresentation(otherObj);
     args.rval().setBoolean(thisRepr == otherRepr);
     return true;
 }
@@ -302,22 +302,22 @@ TypeEquivalent(JSContext *cx, unsigned i
     JSCLASS_HAS_CACHED_PROTO(JSProto_##name_),                                \
     JS_PropertyStub,       /* addProperty */                                  \
     JS_DeletePropertyStub, /* delProperty */                                  \
     JS_PropertyStub,       /* getProperty */                                  \
     JS_StrictPropertyStub, /* setProperty */                                  \
     JS_EnumerateStub,                                                         \
     JS_ResolveStub,                                                           \
     JS_ConvertStub,                                                           \
-    NULL,                                                                     \
-    NULL,                                                                     \
+    nullptr,                                                                  \
+    nullptr,                                                                  \
     NumericType<constant_, type_>::call,                                      \
-    NULL,                                                                     \
-    NULL,                                                                     \
-    NULL                                                                      \
+    nullptr,                                                                  \
+    nullptr,                                                                  \
+    nullptr                                                                   \
 },
 
 const Class js::NumericTypeClasses[ScalarTypeRepresentation::TYPE_MAX] = {
     JS_FOR_EACH_SCALAR_TYPE_REPR(BINARYDATA_NUMERIC_CLASSES)
 };
 
 template <typename Domain, typename Input>
 bool
@@ -468,17 +468,17 @@ ReifyScalar(JSContext *cx, ScalarTypeRep
 }
 
 template <ScalarTypeRepresentation::Type type, typename T>
 bool
 NumericType<type, T>::call(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     if (args.length() < 1) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED,
                              args.callee().getClass()->name, "0", "s");
         return false;
     }
 
     RootedValue arg(cx, args[0]);
     T answer;
     if (!convert(cx, arg, &answer))
         return false; // convert() raises TypeError.
@@ -522,56 +522,56 @@ SetupAndGetPrototypeObjectForComplexType
                                                  HandleObject complexTypeGlobal)
 {
     RootedObject global(cx, cx->compartment()->maybeGlobal());
     RootedValue complexTypePrototypeVal(cx);
     RootedValue complexTypePrototypePrototypeVal(cx);
 
     if (!JSObject::getProperty(cx, complexTypeGlobal, complexTypeGlobal,
                                cx->names().classPrototype, &complexTypePrototypeVal))
-        return NULL;
+        return nullptr;
 
     JS_ASSERT(complexTypePrototypeVal.isObject()); // immutable binding
     RootedObject complexTypePrototypeObj(cx,
         &complexTypePrototypeVal.toObject());
 
     if (!JSObject::getProperty(cx, complexTypePrototypeObj,
                                complexTypePrototypeObj,
                                cx->names().classPrototype,
                                &complexTypePrototypePrototypeVal))
-        return NULL;
+        return nullptr;
 
     RootedObject prototypeObj(cx,
-        NewObjectWithGivenProto(cx, &JSObject::class_, NULL, global));
+        NewObjectWithGivenProto(cx, &JSObject::class_, nullptr, global));
 
     JS_ASSERT(complexTypePrototypePrototypeVal.isObject()); // immutable binding
     RootedObject proto(cx, &complexTypePrototypePrototypeVal.toObject());
     if (!JS_SetPrototype(cx, prototypeObj, proto))
-        return NULL;
+        return nullptr;
 
     return prototypeObj;
 }
 
 const Class ArrayType::class_ = {
     "ArrayType",
     JSCLASS_HAS_RESERVED_SLOTS(ARRAY_TYPE_RESERVED_SLOTS) |
     JSCLASS_HAS_CACHED_PROTO(JSProto_ArrayType),
     JS_PropertyStub,
     JS_DeletePropertyStub,
     JS_PropertyStub,
     JS_StrictPropertyStub,
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub,
-    NULL,
-    NULL,
-    NULL,
-    NULL,
+    nullptr,
+    nullptr,
+    nullptr,
+    nullptr,
     BinaryBlock::construct,
-    NULL
+    nullptr
 };
 
 static JSObject *
 ArrayElementType(HandleObject array)
 {
     JS_ASSERT(IsArrayType(array));
     return &array->getFixedSlot(SLOT_ARRAY_ELEM_TYPE).toObject();
 }
@@ -638,24 +638,24 @@ ConvertAndCopyArrayTo(JSContext *cx, Arr
 
 static bool
 DataInstanceUpdate(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     if (args.length() < 1) {
         JS_ReportErrorNumber(cx, js_GetErrorMessage,
-                             NULL, JSMSG_MORE_ARGS_NEEDED,
+                             nullptr, JSMSG_MORE_ARGS_NEEDED,
                              "update()", "0", "s");
         return false;
     }
 
     RootedObject thisObj(cx, ToObjectIfObject(args.thisv()));
     if (!thisObj || !IsBlock(thisObj)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_INCOMPATIBLE_PROTO,
                              "Data", "update",
                              InformalValueTypeName(args.thisv()));
         return false;
     }
 
     RootedValue val(cx, args[0]);
     if (!ConvertAndCopyTo(cx, val, thisObj))
@@ -689,24 +689,24 @@ FillBinaryArrayWithValue(JSContext *cx, 
 
 static bool
 ArrayRepeat(JSContext *cx, unsigned int argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     if (args.length() < 1) {
         JS_ReportErrorNumber(cx, js_GetErrorMessage,
-                             NULL, JSMSG_MORE_ARGS_NEEDED,
+                             nullptr, JSMSG_MORE_ARGS_NEEDED,
                              "repeat()", "0", "s");
         return false;
     }
 
     RootedObject thisObj(cx, ToObjectIfObject(args.thisv()));
     if (!thisObj || !IsArrayType(thisObj)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_INCOMPATIBLE_PROTO,
                              "ArrayType", "repeat",
                              InformalValueTypeName(args.thisv()));
         return false;
     }
 
     RootedObject binaryArray(cx, BinaryBlock::createZeroed(cx, thisObj));
     if (!binaryArray)
@@ -723,17 +723,17 @@ ArrayRepeat(JSContext *cx, unsigned int 
 bool
 ArrayType::toSource(JSContext *cx, unsigned int argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     RootedObject thisObj(cx, ToObjectIfObject(args.thisv()));
     if (!thisObj || !IsArrayType(thisObj)) {
         JS_ReportErrorNumber(cx, js_GetErrorMessage,
-                             NULL, JSMSG_INCOMPATIBLE_PROTO,
+                             nullptr, JSMSG_INCOMPATIBLE_PROTO,
                              "ArrayType", "toSource",
                              InformalValueTypeName(args.thisv()));
         return false;
     }
 
     StringBuffer contents(cx);
     if (!typeRepresentation(thisObj)->appendString(cx, contents))
         return false;
@@ -768,23 +768,23 @@ ArrayType::toSource(JSContext *cx, unsig
  */
 static bool
 ArraySubarray(JSContext *cx, unsigned int argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     if (args.length() < 1) {
         JS_ReportErrorNumber(cx, js_GetErrorMessage,
-                             NULL, JSMSG_MORE_ARGS_NEEDED,
+                             nullptr, JSMSG_MORE_ARGS_NEEDED,
                              "subarray()", "0", "s");
         return false;
     }
 
     if (!args[0].isInt32()) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_TYPEDOBJECT_SUBARRAY_INTEGER_ARG, "1");
         return false;
     }
 
     RootedObject thisObj(cx, &args.thisv().toObject());
     if (!IsBinaryArray(cx, thisObj)) {
         ReportCannotConvertTo(cx, thisObj, "binary array");
         return false;
@@ -794,17 +794,17 @@ ArraySubarray(JSContext *cx, unsigned in
     ArrayTypeRepresentation *typeRepr = typeRepresentation(type)->asArray();
     size_t length = typeRepr->length();
 
     int32_t begin = args[0].toInt32();
     int32_t end = length;
 
     if (args.length() >= 2) {
         if (!args[1].isInt32()) {
-            JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+            JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                     JSMSG_TYPEDOBJECT_SUBARRAY_INTEGER_ARG, "2");
             return false;
         }
 
         end = args[1].toInt32();
     }
 
     if (begin < 0)
@@ -842,25 +842,25 @@ ArraySubarray(JSContext *cx, unsigned in
 
 static bool
 ArrayFillSubarray(JSContext *cx, unsigned int argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     if (args.length() < 1) {
         JS_ReportErrorNumber(cx, js_GetErrorMessage,
-                             NULL, JSMSG_MORE_ARGS_NEEDED,
+                             nullptr, JSMSG_MORE_ARGS_NEEDED,
                              "fill()", "0", "s");
         return false;
     }
 
     RootedObject thisObj(cx, ToObjectIfObject(args.thisv()));
     if (!thisObj || !IsBinaryArray(cx, thisObj)) {
         JS_ReportErrorNumber(cx, js_GetErrorMessage,
-                             NULL, JSMSG_INCOMPATIBLE_PROTO,
+                             nullptr, JSMSG_INCOMPATIBLE_PROTO,
                              "ArrayType", "fill",
                              InformalValueTypeName(args.thisv()));
         return false;
     }
 
     Value funArrayTypeVal = GetFunctionNativeReserved(&args.callee(), 0);
     JS_ASSERT(funArrayTypeVal.isObject());
 
@@ -886,33 +886,33 @@ InitializeCommonTypeDescriptorProperties
 {
     TypeRepresentation *typeRepr =
         TypeRepresentation::fromOwnerObject(typeReprOwnerObj);
 
     // byteLength
     RootedValue typeByteLength(cx, NumberValue(typeRepr->size()));
     if (!JSObject::defineProperty(cx, obj, cx->names().byteLength,
                                   typeByteLength,
-                                  NULL, NULL,
+                                  nullptr, nullptr,
                                   JSPROP_READONLY | JSPROP_PERMANENT))
         return false;
 
     // byteAlignment
     RootedValue typeByteAlignment(cx, NumberValue(typeRepr->alignment()));
     if (!JSObject::defineProperty(cx, obj, cx->names().byteAlignment,
                                   typeByteAlignment,
-                                  NULL, NULL,
+                                  nullptr, nullptr,
                                   JSPROP_READONLY | JSPROP_PERMANENT))
         return false;
 
     // variable -- always false since we do not yet support variable-size types
     RootedValue variable(cx, JSVAL_FALSE);
     if (!JSObject::defineProperty(cx, obj, cx->names().variable,
                                   variable,
-                                  NULL, NULL,
+                                  nullptr, nullptr,
                                   JSPROP_READONLY | JSPROP_PERMANENT))
         return false;
 
     return true;
 }
 
 JSObject *
 ArrayType::create(JSContext *cx, HandleObject arrayTypeGlobal,
@@ -921,100 +921,100 @@ ArrayType::create(JSContext *cx, HandleO
     JS_ASSERT(elementType);
     JS_ASSERT(IsBinaryType(elementType));
 
     TypeRepresentation *elementTypeRepr = typeRepresentation(elementType);
     RootedObject typeReprObj(
         cx,
         ArrayTypeRepresentation::Create(cx, elementTypeRepr, length));
     if (!typeReprObj)
-        return NULL;
+        return nullptr;
 
     RootedObject obj(cx, NewBuiltinClassInstance(cx, &ArrayType::class_));
     if (!obj)
-        return NULL;
+        return nullptr;
     obj->initFixedSlot(SLOT_TYPE_REPR, ObjectValue(*typeReprObj));
 
     RootedValue elementTypeVal(cx, ObjectValue(*elementType));
     if (!JSObject::defineProperty(cx, obj, cx->names().elementType,
-                                  elementTypeVal, NULL, NULL,
+                                  elementTypeVal, nullptr, nullptr,
                                   JSPROP_READONLY | JSPROP_PERMANENT))
-        return NULL;
+        return nullptr;
 
     obj->initFixedSlot(SLOT_ARRAY_ELEM_TYPE, elementTypeVal);
 
     RootedValue lengthVal(cx, Int32Value(length));
     if (!JSObject::defineProperty(cx, obj, cx->names().length,
-                                  lengthVal, NULL, NULL,
+                                  lengthVal, nullptr, nullptr,
                                   JSPROP_READONLY | JSPROP_PERMANENT))
-        return NULL;
+        return nullptr;
 
     if (!InitializeCommonTypeDescriptorProperties(cx, obj, typeReprObj))
-        return NULL;
+        return nullptr;
 
     RootedObject prototypeObj(cx,
         SetupAndGetPrototypeObjectForComplexTypeInstance(cx, arrayTypeGlobal));
 
     if (!prototypeObj)
-        return NULL;
+        return nullptr;
 
     if (!LinkConstructorAndPrototype(cx, obj, prototypeObj))
-        return NULL;
+        return nullptr;
 
     JSFunction *fillFun = DefineFunctionWithReserved(cx, prototypeObj, "fill", ArrayFillSubarray, 1, 0);
     if (!fillFun)
-        return NULL;
+        return nullptr;
 
     // This is important
     // so that A.prototype.fill.call(b, val)
     // where b.type != A raises an error
     SetFunctionNativeReserved(fillFun, 0, ObjectValue(*obj));
 
     return obj;
 }
 
 bool
 ArrayType::construct(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     if (!args.isConstructing()) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_NOT_FUNCTION, "ArrayType");
         return false;
     }
 
     if (args.length() != 2 ||
         !args[0].isObject() ||
         !args[1].isNumber() ||
         args[1].toNumber() < 0)
     {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_TYPEDOBJECT_ARRAYTYPE_BAD_ARGS);
         return false;
     }
 
     RootedObject arrayTypeGlobal(cx, &args.callee());
     RootedObject elementType(cx, &args[0].toObject());
 
     if (!IsBinaryType(elementType)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_TYPEDOBJECT_ARRAYTYPE_BAD_ARGS);
         return false;
     }
 
     if (!args[1].isInt32()) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_TYPEDOBJECT_ARRAYTYPE_BAD_ARGS);
         return false;
     }
 
     int32_t length = args[1].toInt32();
     if (length < 0) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_TYPEDOBJECT_ARRAYTYPE_BAD_ARGS);
         return false;
     }
 
     RootedObject obj(cx, create(cx, arrayTypeGlobal, elementType, length));
     if (!obj)
         return false;
     args.rval().setObject(*obj);
@@ -1031,22 +1031,22 @@ const Class StructType::class_ = {
     JSCLASS_HAS_CACHED_PROTO(JSProto_StructType),
     JS_PropertyStub,
     JS_DeletePropertyStub,
     JS_PropertyStub,
     JS_StrictPropertyStub,
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub,
-    NULL, /* finalize */
-    NULL, /* checkAccess */
-    NULL, /* call */
-    NULL, /* hasInstance */
+    nullptr, /* finalize */
+    nullptr, /* checkAccess */
+    nullptr, /* call */
+    nullptr, /* hasInstance */
     BinaryBlock::construct,
-    NULL  /* trace */
+    nullptr  /* trace */
 };
 
 static bool
 ConvertAndCopyStructTo(JSContext *cx,
                        StructTypeRepresentation *typeRepr,
                        HandleValue from,
                        uint8_t *mem)
 {
@@ -1160,128 +1160,130 @@ StructType::layout(JSContext *cx, Handle
     RootedObject fieldNamesVec(
         cx,
         NewDenseCopiedArray(cx, fieldNameValues.length(),
                             fieldNameValues.begin()));
     if (!fieldNamesVec)
         return false;
     RootedValue fieldNamesVecValue(cx, ObjectValue(*fieldNamesVec));
     if (!JSObject::defineProperty(cx, structType, cx->names().fieldNames,
-                                  fieldNamesVecValue, NULL, NULL,
+                                  fieldNamesVecValue, nullptr, nullptr,
                                   JSPROP_READONLY | JSPROP_PERMANENT))
         return false;
 
     // Construct the fieldNames, fieldOffsets and fieldTypes objects:
     // fieldNames : [ string ]
     // fieldOffsets : { string: integer, ... }
     // fieldTypes : { string: Type, ... }
     RootedObject fieldOffsets(
         cx,
-        NewObjectWithClassProto(cx, &JSObject::class_, NULL, NULL));
+        NewObjectWithClassProto(cx, &JSObject::class_, nullptr, nullptr));
     RootedObject fieldTypes(
         cx,
-        NewObjectWithClassProto(cx, &JSObject::class_, NULL, NULL));
+        NewObjectWithClassProto(cx, &JSObject::class_, nullptr, nullptr));
     for (size_t i = 0; i < typeRepr->fieldCount(); i++) {
         const StructField &field = typeRepr->field(i);
         RootedId fieldId(cx, field.id);
 
         // fieldOffsets[id] = offset
         RootedValue offset(cx, NumberValue(field.offset));
         if (!JSObject::defineGeneric(cx, fieldOffsets, fieldId,
-                                     offset, NULL, NULL,
+                                     offset, nullptr, nullptr,
                                      JSPROP_READONLY | JSPROP_PERMANENT))
             return false;
 
         // fieldTypes[id] = typeObj
         if (!JSObject::defineGeneric(cx, fieldTypes, fieldId,
-                                     fieldTypeObjs.handleAt(i), NULL, NULL,
+                                     fieldTypeObjs.handleAt(i),
+                                     nullptr, nullptr,
                                      JSPROP_READONLY | JSPROP_PERMANENT))
             return false;
     }
 
     RootedValue fieldOffsetsValue(cx, ObjectValue(*fieldOffsets));
     if (!JSObject::defineProperty(cx, structType, cx->names().fieldOffsets,
-                                  fieldOffsetsValue, NULL, NULL,
+                                  fieldOffsetsValue, nullptr, nullptr,
                                   JSPROP_READONLY | JSPROP_PERMANENT))
         return false;
 
     RootedValue fieldTypesValue(cx, ObjectValue(*fieldTypes));
     if (!JSObject::defineProperty(cx, structType, cx->names().fieldTypes,
-                                  fieldTypesValue, NULL, NULL,
+                                  fieldTypesValue, nullptr, nullptr,
                                   JSPROP_READONLY | JSPROP_PERMANENT))
         return false;
 
     return true;
 }
 
 JSObject *
 StructType::create(JSContext *cx, HandleObject structTypeGlobal,
                    HandleObject fields)
 {
     RootedObject obj(cx, NewBuiltinClassInstance(cx, &StructType::class_));
     if (!obj)
-        return NULL;
+        return nullptr;
 
     if (!StructType::layout(cx, obj, fields))
-        return NULL;
+        return nullptr;
 
     RootedObject fieldsProto(cx);
     if (!JSObject::getProto(cx, fields, &fieldsProto))
-        return NULL;
+        return nullptr;
 
     RootedObject typeReprObj(cx, typeRepresentationOwnerObj(obj));
     if (!InitializeCommonTypeDescriptorProperties(cx, obj, typeReprObj))
-        return NULL;
+        return nullptr;
 
     RootedObject prototypeObj(cx,
         SetupAndGetPrototypeObjectForComplexTypeInstance(cx, structTypeGlobal));
 
     if (!prototypeObj)
-        return NULL;
+        return nullptr;
 
     if (!LinkConstructorAndPrototype(cx, obj, prototypeObj))
-        return NULL;
+        return nullptr;
 
     return obj;
 }
 
 bool
 StructType::construct(JSContext *cx, unsigned int argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     if (!args.isConstructing()) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                              JSMSG_NOT_FUNCTION, "StructType");
         return false;
     }
 
     if (args.length() >= 1 && args[0].isObject()) {
         RootedObject structTypeGlobal(cx, &args.callee());
         RootedObject fields(cx, &args[0].toObject());
         RootedObject obj(cx, create(cx, structTypeGlobal, fields));
         if (!obj)
             return false;
         args.rval().setObject(*obj);
         return true;
     }
 
-    JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+    JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                          JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_ARGS);
     return false;
 }
 
 bool
 StructType::toSource(JSContext *cx, unsigned int argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     RootedObject thisObj(cx, ToObjectIfObject(args.thisv()));
     if (!thisObj || !IsStructType(thisObj)) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INCOMPATIBLE_PROTO,
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
+                             JSMSG_INCOMPATIBLE_PROTO,
                              "StructType", "toSource",
                              InformalValueTypeName(args.thisv()));
         return false;
     }
 
     StringBuffer contents(cx);
     if (!typeRepresentation(thisObj)->appendString(cx, contents))
         return false;
@@ -1414,61 +1416,61 @@ GlobalObject::initArrayTypeObject(JSCont
 static JSObject *
 SetupComplexHeirarchy(JSContext *cx, Handle<GlobalObject*> global, JSProtoKey protoKey,
                       HandleObject complexObject, MutableHandleObject proto,
                       MutableHandleObject protoProto)
 {
     // get the 'Type' constructor
     RootedObject TypeObject(cx, global->getOrCreateTypeObject(cx));
     if (!TypeObject)
-        return NULL;
+        return nullptr;
 
     // Set complexObject.__proto__ = Type
     if (!JS_SetPrototype(cx, complexObject, TypeObject))
-        return NULL;
+        return nullptr;
 
     RootedObject DataObject(cx, global->getOrCreateDataObject(cx));
     if (!DataObject)
-        return NULL;
+        return nullptr;
 
     RootedValue DataProtoVal(cx);
     if (!JSObject::getProperty(cx, DataObject, DataObject,
                                cx->names().classPrototype, &DataProtoVal))
-        return NULL;
+        return nullptr;
 
     RootedObject DataProto(cx, &DataProtoVal.toObject());
     if (!DataProto)
-        return NULL;
+        return nullptr;
 
     RootedObject prototypeObj(cx,
-        NewObjectWithGivenProto(cx, &JSObject::class_, NULL, global));
+        NewObjectWithGivenProto(cx, &JSObject::class_, nullptr, global));
     if (!prototypeObj)
-        return NULL;
+        return nullptr;
     if (!LinkConstructorAndPrototype(cx, complexObject, prototypeObj))
-        return NULL;
+        return nullptr;
     if (!DefineConstructorAndPrototype(cx, global, protoKey,
                                        complexObject, prototypeObj))
-        return NULL;
+        return nullptr;
 
     // Set complexObject.prototype.__proto__ = Data
     if (!JS_SetPrototype(cx, prototypeObj, DataObject))
-        return NULL;
+        return nullptr;
 
     proto.set(prototypeObj);
 
     // Set complexObject.prototype.prototype.__proto__ = Data.prototype
-    RootedObject prototypePrototypeObj(cx, JS_NewObject(cx, NULL, NULL,
+    RootedObject prototypePrototypeObj(cx, JS_NewObject(cx, nullptr, nullptr,
                                        global));
 
     if (!LinkConstructorAndPrototype(cx, prototypeObj,
                                      prototypePrototypeObj))
-        return NULL;
+        return nullptr;
 
     if (!JS_SetPrototype(cx, prototypePrototypeObj, DataProto))
-        return NULL;
+        return nullptr;
 
     protoProto.set(prototypePrototypeObj);
 
     return complexObject;
 }
 
 static bool
 InitType(JSContext *cx, HandleObject globalObj)
@@ -1519,17 +1521,17 @@ InitArrayType(JSContext *cx, HandleObjec
         return false;
 
     RootedValue forEachFunVal(cx);
     RootedAtom forEachAtom(cx, Atomize(cx, "forEach", 7));
     RootedId forEachId(cx, AtomToId(forEachAtom));
     if (!JSObject::getProperty(cx, arrayProto, arrayProto, forEachAtom->asPropertyName(), &forEachFunVal))
         return false;
 
-    if (!JSObject::defineGeneric(cx, protoProto, forEachId, forEachFunVal, NULL, NULL, 0))
+    if (!JSObject::defineGeneric(cx, protoProto, forEachId, forEachFunVal, nullptr, nullptr, 0))
         return false;
 
     if (!JS_DefineFunction(cx, protoProto, "subarray",
                            ArraySubarray, 1, 0))
         return false;
 
     return true;
 }
@@ -1595,29 +1597,29 @@ DefineNumericClass(JSContext *cx,
 
 JSObject *
 js_InitTypedObjectClasses(JSContext *cx, HandleObject obj)
 {
     JS_ASSERT(obj->is<GlobalObject>());
     Rooted<GlobalObject *> global(cx, &obj->as<GlobalObject>());
 
     if (!InitType(cx, obj))
-        return NULL;
+        return nullptr;
 
 #define BINARYDATA_NUMERIC_DEFINE(constant_, type_, name_)                    \
     if (!DefineNumericClass<constant_>(cx, global, #name_))                   \
-        return NULL;
+        return nullptr;
     JS_FOR_EACH_SCALAR_TYPE_REPR(BINARYDATA_NUMERIC_DEFINE)
 #undef BINARYDATA_NUMERIC_DEFINE
 
     if (!InitArrayType(cx, obj))
-        return NULL;
+        return nullptr;
 
     if (!InitStructType(cx, obj))
-        return NULL;
+        return nullptr;
 
     return global;
 }
 
 ///////////////////////////////////////////////////////////////////////////
 // Binary blocks
 
 const Class BinaryBlock::class_ = {
@@ -1630,20 +1632,20 @@ const Class BinaryBlock::class_ = {
     JS_PropertyStub,
     JS_DeletePropertyStub,
     JS_PropertyStub,
     JS_StrictPropertyStub,
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub,
     BinaryBlock::obj_finalize,
-    NULL,           /* checkAccess */
-    NULL,           /* call        */
-    NULL,           /* construct   */
-    NULL,           /* hasInstance */
+    nullptr,        /* checkAccess */
+    nullptr,        /* call        */
+    nullptr,        /* construct   */
+    nullptr,        /* hasInstance */
     BinaryBlock::obj_trace,
     JS_NULL_CLASS_EXT,
     {
         BinaryBlock::obj_lookupGeneric,
         BinaryBlock::obj_lookupProperty,
         BinaryBlock::obj_lookupElement,
         BinaryBlock::obj_lookupSpecial,
         BinaryBlock::obj_defineGeneric,
@@ -1660,17 +1662,17 @@ const Class BinaryBlock::class_ = {
         BinaryBlock::obj_setElement,
         BinaryBlock::obj_setSpecial,
         BinaryBlock::obj_getGenericAttributes,
         BinaryBlock::obj_setGenericAttributes,
         BinaryBlock::obj_deleteProperty,
         BinaryBlock::obj_deleteElement,
         BinaryBlock::obj_deleteSpecial,
         BinaryBlock::obj_enumerate,
-        NULL, /* thisObject */
+        nullptr, /* thisObject */
     }
 };
 
 static bool
 ReportBlockTypeError(JSContext *cx,
                      const unsigned errorNumber,
                      HandleObject obj)
 {
@@ -1686,17 +1688,17 @@ ReportBlockTypeError(JSContext *cx,
     RootedString result(cx, contents.finishString());
     if (!result)
         return false;
 
     char *typeReprStr = JS_EncodeString(cx, result.get());
     if (!typeReprStr)
         return false;
 
-    JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+    JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                          errorNumber, typeReprStr);
 
     JS_free(cx, (void *) typeReprStr);
     return false;
 }
 
 /*static*/ void
 BinaryBlock::obj_trace(JSTracer *trace, JSObject *object)
@@ -1720,67 +1722,67 @@ BinaryBlock::obj_finalize(js::FreeOp *op
 /*static*/ JSObject *
 BinaryBlock::createNull(JSContext *cx, HandleObject type, HandleValue owner)
 {
     JS_ASSERT(IsBinaryType(type));
 
     RootedValue protoVal(cx);
     if (!JSObject::getProperty(cx, type, type,
                                cx->names().classPrototype, &protoVal))
-        return NULL;
+        return nullptr;
 
     RootedObject obj(cx,
-        NewObjectWithClassProto(cx, &class_, &protoVal.toObject(), NULL));
+        NewObjectWithClassProto(cx, &class_, &protoVal.toObject(), nullptr));
     obj->initFixedSlot(SLOT_DATATYPE, ObjectValue(*type));
     obj->initFixedSlot(SLOT_BLOCKREFOWNER, owner);
 
     // Tag the type object for this instance with the type
     // representation, if that has not been done already.
     if (cx->typeInferenceEnabled()) {
         RootedTypeObject typeObj(cx, obj->getType(cx));
         if (typeObj) {
             TypeRepresentation *typeRepr = typeRepresentation(type);
             if (!typeObj->addTypedObjectAddendum(cx, typeRepr))
-                return NULL;
+                return nullptr;
         }
     }
 
     return obj;
 }
 
 /*static*/ JSObject *
 BinaryBlock::createZeroed(JSContext *cx, HandleObject type)
 {
     RootedValue owner(cx, NullValue());
     RootedObject obj(cx, createNull(cx, type, owner));
     if (!obj)
-        return NULL;
+        return nullptr;
 
     TypeRepresentation *typeRepr = typeRepresentation(type);
     size_t memsize = typeRepr->size();
     void *memory = JS_malloc(cx, memsize);
     if (!memory)
-        return NULL;
+        return nullptr;
     memset(memory, 0, memsize);
     obj->setPrivate(memory);
     return obj;
 }
 
 /*static*/ JSObject *
 BinaryBlock::createDerived(JSContext *cx, HandleObject type,
                            HandleObject owner, size_t offset)
 {
     JS_ASSERT(IsBlock(owner));
     JS_ASSERT(offset <= BlockSize(cx, owner));
     JS_ASSERT(offset + TypeSize(type) <= BlockSize(cx, owner));
 
     RootedValue ownerValue(cx, ObjectValue(*owner));
     RootedObject obj(cx, createNull(cx, type, ownerValue));
     if (!obj)
-        return NULL;
+        return nullptr;
 
     obj->setPrivate(BlockMem(owner) + offset);
     return obj;
 }
 
 /*static*/ bool
 BinaryBlock::construct(JSContext *cx, unsigned int argc, Value *vp)
 {
@@ -1841,18 +1843,18 @@ BinaryBlock::obj_lookupGeneric(JSContext
             return true;
         }
         break;
       }
     }
 
     RootedObject proto(cx, obj->getProto());
     if (!proto) {
-        objp.set(NULL);
-        propp.set(NULL);
+        objp.set(nullptr);
+        propp.set(nullptr);
         return true;
     }
 
     return JSObject::lookupGeneric(cx, proto, id, objp, propp);
 }
 
 bool
 BinaryBlock::obj_lookupProperty(JSContext *cx,
@@ -1883,17 +1885,17 @@ ReportPropertyError(JSContext *cx,
     RootedString str(cx, IdToString(cx, id));
     if (!str)
         return false;
 
     char *propName = JS_EncodeString(cx, str);
     if (!propName)
         return false;
 
-    JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+    JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                          errorNumber, propName);
 
     JS_free(cx, propName);
     return false;
 }
 
 bool
 BinaryBlock::obj_lookupSpecial(JSContext *cx, HandleObject obj,
@@ -2083,17 +2085,17 @@ BinaryBlock::obj_setGeneric(JSContext *c
 
     switch (typeRepr->kind()) {
       case ScalarTypeRepresentation::Scalar:
         break;
 
       case ScalarTypeRepresentation::Array:
         if (JSID_IS_ATOM(id, cx->names().length)) {
             JS_ReportErrorNumber(cx, js_GetErrorMessage,
-                                 NULL, JSMSG_CANT_REDEFINE_ARRAY_LENGTH);
+                                 nullptr, JSMSG_CANT_REDEFINE_ARRAY_LENGTH);
             return false;
         }
         break;
 
       case ScalarTypeRepresentation::Struct: {
         const StructField *field = typeRepr->asStruct()->fieldNamed(id);
         if (!field)
             break;
@@ -2127,17 +2129,17 @@ BinaryBlock::obj_setElement(JSContext *c
       case ScalarTypeRepresentation::Struct:
         break;
 
       case ScalarTypeRepresentation::Array: {
         ArrayTypeRepresentation *arrayTypeRepr = typeRepr->asArray();
 
         if (index >= arrayTypeRepr->length()) {
             JS_ReportErrorNumber(cx, js_GetErrorMessage,
-                                 NULL, JSMSG_TYPEDOBJECT_BINARYARRAY_BAD_INDEX);
+                                 nullptr, JSMSG_TYPEDOBJECT_BINARYARRAY_BAD_INDEX);
             return false;
         }
 
         size_t offset = arrayTypeRepr->element()->size() * index;
         uint8_t *mem = BlockMem(obj) + offset;
         return ConvertAndCopyTo(cx, arrayTypeRepr->element(), vp, mem);
       }
     }
@@ -2173,17 +2175,17 @@ BinaryBlock::obj_getGenericAttributes(JS
         }
         if (JSID_IS_ATOM(id, cx->names().length)) {
             *attrsp = JSPROP_READONLY | JSPROP_PERMANENT;
             return true;
         }
         break;
 
       case TypeRepresentation::Struct:
-        if (typeRepr->asStruct()->fieldNamed(id) != NULL) {
+        if (typeRepr->asStruct()->fieldNamed(id) != nullptr) {
             *attrsp = JSPROP_ENUMERATE | JSPROP_PERMANENT;
             return true;
         }
         break;
     }
 
     RootedObject proto(cx, obj->getProto());
     if (!proto) {
@@ -2204,17 +2206,17 @@ IsOwnId(JSContext *cx, HandleObject obj,
     switch (typeRepr->kind()) {
       case TypeRepresentation::Scalar:
         return false;
 
       case TypeRepresentation::Array:
         return js_IdIsIndex(id, &index) || JSID_IS_ATOM(id, cx->names().length);
 
       case TypeRepresentation::Struct:
-        return typeRepr->asStruct()->fieldNamed(id) != NULL;
+        return typeRepr->asStruct()->fieldNamed(id) != nullptr;
     }
 
     return false;
 }
 
 bool
 BinaryBlock::obj_setGenericAttributes(JSContext *cx, HandleObject obj,
                                        HandleId id, unsigned *attrsp)
--- a/js/src/builtin/TypedObject.h
+++ b/js/src/builtin/TypedObject.h
@@ -34,17 +34,17 @@ enum StructTypeCommonSlots {
     STRUCT_TYPE_RESERVED_SLOTS
 };
 
 // Slots for data blocks:
 enum BlockCommonSlots {
     // The type descriptor with which this block is associated.
     SLOT_DATATYPE = 0,
 
-    // If this value is NULL, then the block instance owns the
+    // If this value is nullptr, then the block instance owns the
     // uint8_t* in its priate data. Otherwise, this field contains the
     // owner, and thus keeps the owner alive.
     SLOT_BLOCKREFOWNER,
 
     BLOCK_RESERVED_SLOTS
 };
 
 extern const Class DataClass;
@@ -110,17 +110,17 @@ class StructType : public JSObject
     static bool construct(JSContext *cx, unsigned int argc, jsval *vp);
 };
 
 /* Binary data objects and handles */
 class BinaryBlock
 {
   private:
     // Creates a binary data object of the given type and class, but with
-    // a NULL memory pointer. Caller must use setPrivate() to set the
+    // a nullptr memory pointer. Caller must use setPrivate() to set the
     // memory pointer properly.
     static JSObject *createNull(JSContext *cx, HandleObject type,
                                 HandleValue owner);
 
     static void obj_finalize(js::FreeOp *op, JSObject *obj);
 
     static void obj_trace(JSTracer *trace, JSObject *object);
 
--- a/js/src/ctypes/CTypes.cpp
+++ b/js/src/ctypes/CTypes.cpp
@@ -79,17 +79,17 @@ GetDeflatedUTF8StringLength(JSContext *m
         }
     }
     return nbytes;
 
   bad_surrogate:
     if (maybecx) {
         JS_snprintf(buffer, 10, "0x%x", c);
         JS_ReportErrorFlagsAndNumber(maybecx, JSREPORT_ERROR, js_GetErrorMessage,
-                                     NULL, JSMSG_BAD_SURROGATE_CHAR, buffer);
+                                     nullptr, JSMSG_BAD_SURROGATE_CHAR, buffer);
     }
     return (size_t) -1;
 }
 
 bool
 DeflateStringToUTF8Buffer(JSContext *maybecx, const jschar *src, size_t srclen,
                               char *dst, size_t *dstlenp)
 {
@@ -141,17 +141,17 @@ badSurrogate:
     /* Delegate error reporting to the measurement function. */
     if (maybecx)
         GetDeflatedUTF8StringLength(maybecx, src - 1, srclen + 1);
     return false;
 
 bufferTooSmall:
     *dstlenp = (origDstlen - dstlen);
     if (maybecx) {
-        JS_ReportErrorNumber(maybecx, js_GetErrorMessage, NULL,
+        JS_ReportErrorNumber(maybecx, js_GetErrorMessage, nullptr,
                              JSMSG_BUFFER_TOO_SMALL);
     }
     return false;
 }
 
 /*******************************************************************************
 ** JSAPI function prototypes
 *******************************************************************************/
@@ -178,17 +178,17 @@ namespace CType {
   static bool HasInstance(JSContext* cx, HandleObject obj, MutableHandleValue v, bool* bp);
 
 
   /*
    * Get the global "ctypes" object.
    *
    * |obj| must be a CType object.
    *
-   * This function never returns NULL.
+   * This function never returns nullptr.
    */
   static JSObject* GetGlobalCTypes(JSContext* cx, JSObject* obj);
 
 }
 
 namespace ABI {
   bool IsABI(JSObject* obj);
   static bool ToSource(JSContext* cx, unsigned argc, jsval* vp);
@@ -302,17 +302,17 @@ namespace CDataFinalizer {
   static bool Construct(JSContext* cx, unsigned argc, jsval *vp);
 
   /*
    * Private data held by |CDataFinalizer|.
    *
    * See also |enum CDataFinalizerSlot| for the slots of
    * |CDataFinalizer|.
    *
-   * Note: the private data may be NULL, if |dispose|, |forget| or the
+   * Note: the private data may be nullptr, if |dispose|, |forget| or the
    * finalizer has already been called.
    */
   struct Private {
     /*
      * The C data to pass to the code.
      * Finalization/|dispose|/|forget| release this memory.
      */
     void *cargs;
@@ -358,33 +358,33 @@ namespace CDataFinalizer {
    */
   static bool IsCDataFinalizer(JSObject *obj);
 
   /*
    * Clean up the finalization information of a CDataFinalizer.
    *
    * Used by |Finalize|, |Dispose| and |Forget|.
    *
-   * @param p The private information of the CDataFinalizer. If NULL,
+   * @param p The private information of the CDataFinalizer. If nullptr,
    * this function does nothing.
-   * @param obj Either NULL, if the object should not be cleaned up (i.e.
-   * during finalization) or a CDataFinalizer JSObject. Always use NULL
+   * @param obj Either nullptr, if the object should not be cleaned up (i.e.
+   * during finalization) or a CDataFinalizer JSObject. Always use nullptr
    * if you are calling from a finalizer.
    */
   static void Cleanup(Private *p, JSObject *obj);
 
   /*
    * Perform the actual call to the finalizer code.
    */
   static void CallFinalizer(CDataFinalizer::Private *p,
                             int* errnoStatus,
                             int32_t* lastErrorStatus);
 
   /*
-   * Return the CType of a CDataFinalizer object, or NULL if the object
+   * Return the CType of a CDataFinalizer object, or nullptr if the object
    * has been cleaned-up already.
    */
   static JSObject *GetCType(JSContext *cx, JSObject *obj);
 
   /*
    * Perform finalization of a |CDataFinalizer|
    */
   static void Finalize(JSFreeOp *fop, JSObject *obj);
@@ -462,52 +462,52 @@ static const JSClass sCABIClass = {
 
 // Class representing ctypes.{C,Pointer,Array,Struct,Function}Type.prototype.
 // This exists to give said prototypes a class of "CType", and to provide
 // reserved slots for stashing various other prototype objects.
 static const JSClass sCTypeProtoClass = {
   "CType",
   JSCLASS_HAS_RESERVED_SLOTS(CTYPEPROTO_SLOTS),
   JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
-  JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, NULL,
-  NULL, ConstructAbstract, NULL, ConstructAbstract
+  JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, nullptr,
+  nullptr, ConstructAbstract, nullptr, ConstructAbstract
 };
 
 // Class representing ctypes.CData.prototype and the 'prototype' properties
 // of CTypes. This exists to give said prototypes a class of "CData".
 static const JSClass sCDataProtoClass = {
   "CData",
   0,
   JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
   JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub
 };
 
 static const JSClass sCTypeClass = {
   "CType",
   JSCLASS_IMPLEMENTS_BARRIERS | JSCLASS_HAS_RESERVED_SLOTS(CTYPE_SLOTS),
   JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
   JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, CType::Finalize,
-  NULL, CType::ConstructData, CType::HasInstance, CType::ConstructData,
+  nullptr, CType::ConstructData, CType::HasInstance, CType::ConstructData,
   CType::Trace
 };
 
 static const JSClass sCDataClass = {
   "CData",
   JSCLASS_HAS_RESERVED_SLOTS(CDATA_SLOTS),
   JS_PropertyStub, JS_DeletePropertyStub, ArrayType::Getter, ArrayType::Setter,
   JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, CData::Finalize,
-  NULL, FunctionType::Call, NULL, FunctionType::Call
+  nullptr, FunctionType::Call, nullptr, FunctionType::Call
 };
 
 static const JSClass sCClosureClass = {
   "CClosure",
   JSCLASS_IMPLEMENTS_BARRIERS | JSCLASS_HAS_RESERVED_SLOTS(CCLOSURE_SLOTS),
   JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
   JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, CClosure::Finalize,
-  NULL, NULL, NULL, NULL, CClosure::Trace
+  nullptr, nullptr, nullptr, nullptr, CClosure::Trace
 };
 
 /*
  * Class representing the prototype of CDataFinalizer.
  */
 static const JSClass sCDataFinalizerProtoClass = {
   "CDataFinalizer",
   0,
@@ -794,17 +794,17 @@ static const JSErrorFormatString ErrorFo
 #undef MSG_DEF
 };
 
 static const JSErrorFormatString*
 GetErrorMessage(void* userRef, const char* locale, const unsigned errorNumber)
 {
   if (0 < errorNumber && errorNumber < CTYPESERR_LIMIT)
     return &ErrorFormatString[errorNumber];
-  return NULL;
+  return nullptr;
 }
 
 static bool
 TypeError(JSContext* cx, const char* expected, jsval actual)
 {
   JSString* str = JS_ValueToSource(cx, actual);
   JSAutoByteString bytes;
 
@@ -812,113 +812,113 @@ TypeError(JSContext* cx, const char* exp
   if (str) {
     src = bytes.encodeLatin1(cx, str);
     if (!src)
       return false;
   } else {
     JS_ClearPendingException(cx);
     src = "<<error converting value to string>>";
   }
-  JS_ReportErrorNumber(cx, GetErrorMessage, NULL,
+  JS_ReportErrorNumber(cx, GetErrorMessage, nullptr,
                        CTYPESMSG_TYPE_ERROR, expected, src);
   return false;
 }
 
 static JSObject*
 InitCTypeClass(JSContext* cx, HandleObject parent)
 {
   JSFunction *fun = JS_DefineFunction(cx, parent, "CType", ConstructAbstract, 0,
                                       CTYPESCTOR_FLAGS);
   if (!fun)
-    return NULL;
+    return nullptr;
 
   RootedObject ctor(cx, JS_GetFunctionObject(fun));
   RootedObject fnproto(cx);
   if (!JS_GetPrototype(cx, ctor, &fnproto))
-    return NULL;
+    return nullptr;
   JS_ASSERT(ctor);
   JS_ASSERT(fnproto);
 
   // Set up ctypes.CType.prototype.
   RootedObject prototype(cx, JS_NewObject(cx, &sCTypeProtoClass, fnproto, parent));
   if (!prototype)
-    return NULL;
+    return nullptr;
 
   if (!JS_DefineProperty(cx, ctor, "prototype", OBJECT_TO_JSVAL(prototype),
-         NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
-    return NULL;
+         nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
+    return nullptr;
 
   if (!JS_DefineProperty(cx, prototype, "constructor", OBJECT_TO_JSVAL(ctor),
-         NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
-    return NULL;
+         nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
+    return nullptr;
 
   // Define properties and functions common to all CTypes.
   if (!JS_DefineProperties(cx, prototype, sCTypeProps) ||
       !JS_DefineFunctions(cx, prototype, sCTypeFunctions))
-    return NULL;
+    return nullptr;
 
   if (!JS_FreezeObject(cx, ctor) || !JS_FreezeObject(cx, prototype))
-    return NULL;
+    return nullptr;
 
   return prototype;
 }
 
 static JSObject*
 InitABIClass(JSContext* cx, JSObject* parent)
 {
-  RootedObject obj(cx, JS_NewObject(cx, NULL, NULL, NULL));
+  RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
 
   if (!obj)
-    return NULL;
+    return nullptr;
 
   if (!JS_DefineFunctions(cx, obj, sCABIFunctions))
-    return NULL;
+    return nullptr;
 
   return obj;
 }
 
 
 static JSObject*
 InitCDataClass(JSContext* cx, HandleObject parent, HandleObject CTypeProto)
 {
   JSFunction* fun = JS_DefineFunction(cx, parent, "CData", ConstructAbstract, 0,
                       CTYPESCTOR_FLAGS);
   if (!fun)
-    return NULL;
+    return nullptr;
 
   RootedObject ctor(cx, JS_GetFunctionObject(fun));
   JS_ASSERT(ctor);
 
   // Set up ctypes.CData.__proto__ === ctypes.CType.prototype.
   // (Note that 'ctypes.CData instanceof Function' is still true, thanks to the
   // prototype chain.)
   if (!JS_SetPrototype(cx, ctor, CTypeProto))
-    return NULL;
+    return nullptr;
 
   // Set up ctypes.CData.prototype.
-  RootedObject prototype(cx, JS_NewObject(cx, &sCDataProtoClass, NULL, parent));
+  RootedObject prototype(cx, JS_NewObject(cx, &sCDataProtoClass, nullptr, parent));
   if (!prototype)
-    return NULL;
+    return nullptr;
 
   if (!JS_DefineProperty(cx, ctor, "prototype", OBJECT_TO_JSVAL(prototype),
-         NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
-    return NULL;
+         nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
+    return nullptr;
 
   if (!JS_DefineProperty(cx, prototype, "constructor", OBJECT_TO_JSVAL(ctor),
-         NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
-    return NULL;
+         nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
+    return nullptr;
 
   // Define properties and functions common to all CDatas.
   if (!JS_DefineProperties(cx, prototype, sCDataProps) ||
       !JS_DefineFunctions(cx, prototype, sCDataFunctions))
-    return NULL;
+    return nullptr;
 
   if (//!JS_FreezeObject(cx, prototype) || // XXX fixme - see bug 541212!
       !JS_FreezeObject(cx, ctor))
-    return NULL;
+    return nullptr;
 
   return prototype;
 }
 
 static bool
 DefineABIConstant(JSContext* cx,
                   HandleObject parent,
                   const char* name,
@@ -959,27 +959,27 @@ InitTypeConstructor(JSContext* cx,
 
   // Set up the .prototype and .prototype.constructor properties.
   typeProto.set(JS_NewObject(cx, &sCTypeProtoClass, CTypeProto, parent));
   if (!typeProto)
     return false;
 
   // Define property before proceeding, for GC safety.
   if (!JS_DefineProperty(cx, obj, "prototype", OBJECT_TO_JSVAL(typeProto),
-         NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
+         nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
     return false;
 
   if (fns && !JS_DefineFunctions(cx, typeProto, fns))
     return false;
 
   if (!JS_DefineProperties(cx, typeProto, props))
     return false;
 
   if (!JS_DefineProperty(cx, typeProto, "constructor", OBJECT_TO_JSVAL(obj),
-         NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
+         nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
     return false;
 
   // Stash ctypes.{Pointer,Array,Struct}Type.prototype on a reserved slot of
   // the type constructor, for faster lookup.
   js::SetFunctionNativeReserved(obj, SLOT_FN_CTORPROTO, OBJECT_TO_JSVAL(typeProto));
 
   // Create an object to serve as the common ancestor for all CData objects
   // created from the given type constructor. This has ctypes.CData.prototype
@@ -1013,41 +1013,41 @@ static JSObject*
 InitInt64Class(JSContext* cx,
                HandleObject parent,
                const JSClass* clasp,
                JSNative construct,
                const JSFunctionSpec* fs,
                const JSFunctionSpec* static_fs)
 {
   // Init type class and constructor
-  RootedObject prototype(cx, JS_InitClass(cx, parent, NULL, clasp, construct,
-                                          0, NULL, fs, NULL, static_fs));
+  RootedObject prototype(cx, JS_InitClass(cx, parent, nullptr, clasp, construct,
+                                          0, nullptr, fs, nullptr, static_fs));
   if (!prototype)
-    return NULL;
+    return nullptr;
 
   RootedObject ctor(cx, JS_GetConstructor(cx, prototype));
   if (!ctor)
-    return NULL;
+    return nullptr;
   if (!JS_FreezeObject(cx, ctor))
-    return NULL;
+    return nullptr;
 
   // Redefine the 'join' function as an extended native and stash
   // ctypes.{Int64,UInt64}.prototype in a reserved slot of the new function.
   JS_ASSERT(clasp == &sInt64ProtoClass || clasp == &sUInt64ProtoClass);
   JSNative native = (clasp == &sInt64ProtoClass) ? Int64::Join : UInt64::Join;
   JSFunction* fun = js::DefineFunctionWithReserved(cx, ctor, "join", native,
                       2, CTYPESFN_FLAGS);
   if (!fun)
-    return NULL;
+    return nullptr;
 
   js::SetFunctionNativeReserved(fun, SLOT_FN_INT64PROTO,
     OBJECT_TO_JSVAL(prototype));
 
   if (!JS_FreezeObject(cx, prototype))
-    return NULL;
+    return nullptr;
 
   return prototype;
 }
 
 static void
 AttachProtos(JSObject* proto, const AutoObjectVector& protos)
 {
   // For a given 'proto' of [[Class]] "CTypeProto", attach each of the 'protos'
@@ -1119,35 +1119,35 @@ InitTypeClasses(JSContext* cx, HandleObj
   //     binary data of the given type.
   //   * 'prototype' property:
   //     * [[Class]] "CDataProto"
   //     * __proto__ === 'p', the prototype object from above
   //     * 'constructor' property === 't'
   AutoObjectVector protos(cx);
   protos.resize(CTYPEPROTO_SLOTS);
   if (!InitTypeConstructor(cx, parent, CTypeProto, CDataProto,
-         sPointerFunction, NULL, sPointerProps,
+         sPointerFunction, nullptr, sPointerProps,
          sPointerInstanceFunctions, sPointerInstanceProps,
          protos.handleAt(SLOT_POINTERPROTO), protos.handleAt(SLOT_POINTERDATAPROTO)))
     return false;
 
   if (!InitTypeConstructor(cx, parent, CTypeProto, CDataProto,
-         sArrayFunction, NULL, sArrayProps,
+         sArrayFunction, nullptr, sArrayProps,
          sArrayInstanceFunctions, sArrayInstanceProps,
          protos.handleAt(SLOT_ARRAYPROTO), protos.handleAt(SLOT_ARRAYDATAPROTO)))
     return false;
 
   if (!InitTypeConstructor(cx, parent, CTypeProto, CDataProto,
          sStructFunction, sStructFunctions, sStructProps,
-         sStructInstanceFunctions, NULL,
+         sStructInstanceFunctions, nullptr,
          protos.handleAt(SLOT_STRUCTPROTO), protos.handleAt(SLOT_STRUCTDATAPROTO)))
     return false;
 
   if (!InitTypeConstructor(cx, parent, CTypeProto, protos.handleAt(SLOT_POINTERDATAPROTO),
-         sFunctionFunction, NULL, sFunctionProps, sFunctionInstanceFunctions, NULL,
+         sFunctionFunction, nullptr, sFunctionProps, sFunctionInstanceFunctions, nullptr,
          protos.handleAt(SLOT_FUNCTIONPROTO), protos.handleAt(SLOT_FUNCTIONDATAPROTO)))
     return false;
 
   protos[SLOT_CDATAPROTO] = CDataProto;
 
   // Create and attach the ctypes.{Int64,UInt64} constructors.
   // Each of these has, respectively:
   //   * [[Class]] "Function"
@@ -1205,32 +1205,32 @@ InitTypeClasses(JSContext* cx, HandleObj
       INT_TO_JSVAL(ffiType.alignment), &ffiType));                             \
   if (!typeObj_##name)                                                         \
     return false;
 #include "ctypes/typedefs.h"
 
   // Alias 'ctypes.unsigned' as 'ctypes.unsigned_int', since they represent
   // the same type in C.
   if (!JS_DefineProperty(cx, parent, "unsigned",
-         OBJECT_TO_JSVAL(typeObj_unsigned_int), NULL, NULL,
+         OBJECT_TO_JSVAL(typeObj_unsigned_int), nullptr, nullptr,
          JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
     return false;
 
   // Create objects representing the special types void_t and voidptr_t.
   RootedObject typeObj(cx,
     CType::DefineBuiltin(cx, parent, "void_t", CTypeProto, CDataProto, "void",
                          TYPE_void_t, JSVAL_VOID, JSVAL_VOID, &ffi_type_void));
   if (!typeObj)
     return false;
 
   typeObj = PointerType::CreateInternal(cx, typeObj);
   if (!typeObj)
     return false;
   if (!JS_DefineProperty(cx, parent, "voidptr_t", OBJECT_TO_JSVAL(typeObj),
-         NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
+         nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
     return false;
 
   return true;
 }
 
 bool
 IsCTypesGlobal(JSObject* obj)
 {
@@ -1240,17 +1240,17 @@ IsCTypesGlobal(JSObject* obj)
 // Get the JSCTypesCallbacks struct from the 'ctypes' object 'obj'.
 JSCTypesCallbacks*
 GetCallbacks(JSObject* obj)
 {
   JS_ASSERT(IsCTypesGlobal(obj));
 
   jsval result = JS_GetReservedSlot(obj, SLOT_CALLBACKS);
   if (JSVAL_IS_VOID(result))
-    return NULL;
+    return nullptr;
 
   return static_cast<JSCTypesCallbacks*>(JSVAL_TO_PRIVATE(result));
 }
 
 // Utility function to access a property of an object as an object
 // returns false and sets the error if the property does not exist
 // or is not an object
 static bool GetObjectProperty(JSContext *cx, HandleObject obj,
@@ -1277,17 +1277,17 @@ using namespace js;
 using namespace js::ctypes;
 
 JS_PUBLIC_API(bool)
 JS_InitCTypesClass(JSContext* cx, JSObject *globalArg)
 {
   RootedObject global(cx, globalArg);
 
   // attach ctypes property to global object
-  RootedObject ctypes(cx, JS_NewObject(cx, &sCTypesGlobalClass, NULL, NULL));
+  RootedObject ctypes(cx, JS_NewObject(cx, &sCTypesGlobalClass, nullptr, nullptr));
   if (!ctypes)
     return false;
 
   if (!JS_DefineProperty(cx, global, "ctypes", OBJECT_TO_JSVAL(ctypes),
          JS_PropertyStub, JS_StrictPropertyStub, JSPROP_READONLY | JSPROP_PERMANENT)){
     return false;
   }
 
@@ -1299,30 +1299,30 @@ JS_InitCTypesClass(JSContext* cx, JSObje
       !JS_DefineProperties(cx, ctypes, sModuleProps))
     return false;
 
   // Set up ctypes.CDataFinalizer.prototype.
   RootedObject ctor(cx);
   if (!GetObjectProperty(cx, ctypes, "CDataFinalizer", &ctor))
     return false;
 
-  RootedObject prototype(cx, JS_NewObject(cx, &sCDataFinalizerProtoClass, NULL, ctypes));
+  RootedObject prototype(cx, JS_NewObject(cx, &sCDataFinalizerProtoClass, nullptr, ctypes));
   if (!prototype)
     return false;
 
   if (!JS_DefineProperties(cx, prototype, sCDataFinalizerProps) ||
       !JS_DefineFunctions(cx, prototype, sCDataFinalizerFunctions))
     return false;
 
   if (!JS_DefineProperty(cx, ctor, "prototype", OBJECT_TO_JSVAL(prototype),
-                         NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
+                         nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
     return false;
 
   if (!JS_DefineProperty(cx, prototype, "constructor", OBJECT_TO_JSVAL(ctor),
-                         NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
+                         nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
     return false;
 
 
   // Seal the ctypes object, to prevent modification.
   return JS_FreezeObject(cx, ctypes);
 }
 
 JS_PUBLIC_API(void)
@@ -1704,17 +1704,17 @@ jsvalToFloat(JSContext *cx, jsval val, F
 }
 
 template<class IntegerType>
 static bool
 StringToInteger(JSContext* cx, JSString* string, IntegerType* result)
 {
   JS_STATIC_ASSERT(numeric_limits<IntegerType>::is_exact);
 
-  const jschar* cp = string->getChars(NULL);
+  const jschar* cp = string->getChars(nullptr);
   if (!cp)
     return false;
 
   const jschar* end = cp + string->length();
   if (cp == end)
     return false;
 
   IntegerType sign = 1;
@@ -2195,19 +2195,19 @@ ImplicitConvert(JSContext* cx,
                 bool isArgument,
                 bool* freePointer)
 {
   RootedObject targetType(cx, targetType_);
   JS_ASSERT(CType::IsSizeDefined(targetType));
 
   // First, check if val is either a CData object or a CDataFinalizer
   // of type targetType.
-  JSObject* sourceData = NULL;
-  JSObject* sourceType = NULL;
-  RootedObject valObj(cx, NULL);
+  JSObject* sourceData = nullptr;
+  JSObject* sourceType = nullptr;
+  RootedObject valObj(cx, nullptr);
   if (!JSVAL_IS_PRIMITIVE(val)) {
     valObj = JSVAL_TO_OBJECT(val);
     if (CData::IsCData(valObj)) {
       sourceData = valObj;
       sourceType = CData::GetCType(sourceData);
 
       // If the types are equal, copy the buffer contained within the CData.
       // (Note that the buffers may overlap partially or completely.)
@@ -2286,17 +2286,17 @@ ImplicitConvert(JSContext* cx,
     }                                                                          \
     *static_cast<type*>(buffer) = result;                                      \
     break;                                                                     \
   }
 #include "ctypes/typedefs.h"
   case TYPE_pointer: {
     if (JSVAL_IS_NULL(val)) {
       // Convert to a null pointer.
-      *static_cast<void**>(buffer) = NULL;
+      *static_cast<void**>(buffer) = nullptr;
       break;
     }
 
     JS::Rooted<JSObject*> baseType(cx, PointerType::GetBaseType(targetType));
     if (sourceData) {
       // First, determine if the targetType is ctypes.void_t.ptr.
       TypeCode sourceCode = CType::GetTypeCode(sourceType);
       void* sourceBuffer = CData::GetData(sourceData);
@@ -2461,17 +2461,17 @@ ImplicitConvert(JSContext* cx,
       }
 
       for (uint32_t i = 0; i < sourceLength; ++i) {
         RootedValue item(cx);
         if (!JS_GetElement(cx, valObj, i, &item))
           return false;
 
         char* data = intermediate.get() + elementSize * i;
-        if (!ImplicitConvert(cx, item, baseType, data, false, NULL))
+        if (!ImplicitConvert(cx, item, baseType, data, false, nullptr))
           return false;
       }
 
       memcpy(buffer, intermediate.get(), arraySize);
 
     } else if (!JSVAL_IS_PRIMITIVE(val) &&
                JS_IsArrayBufferObject(valObj)) {
       // Check that array is consistent with type, then
@@ -2544,17 +2544,17 @@ ImplicitConvert(JSContext* cx,
           return false;
 
         RootedValue prop(cx);
         if (!JS_GetPropertyById(cx, valObj, id, &prop))
           return false;
 
         // Convert the field via ImplicitConvert().
         char* fieldData = intermediate.get() + field->mOffset;
-        if (!ImplicitConvert(cx, prop, field->mType, fieldData, false, NULL))
+        if (!ImplicitConvert(cx, prop, field->mType, fieldData, false, nullptr))
           return false;
 
         ++i;
       }
 
       const FieldInfoHash* fields = StructType::GetFieldInfo(targetType);
       if (i != fields->count()) {
         JS_ReportError(cx, "missing fields");
@@ -2577,17 +2577,17 @@ ImplicitConvert(JSContext* cx,
 
 // Convert jsval 'val' to a C binary representation of CType 'targetType',
 // storing the result in 'buffer'. This function is more forceful than
 // ImplicitConvert.
 static bool
 ExplicitConvert(JSContext* cx, HandleValue val, HandleObject targetType, void* buffer)
 {
   // If ImplicitConvert succeeds, use that result.
-  if (ImplicitConvert(cx, val, targetType, buffer, false, NULL))
+  if (ImplicitConvert(cx, val, targetType, buffer, false, nullptr))
     return true;
 
   // If ImplicitConvert failed, and there is no pending exception, then assume
   // hard failure (out of memory, or some other similarly serious condition).
   // We store any pending exception in case we need to re-throw it.
   RootedValue ex(cx);
   if (!JS_GetPendingException(cx, &ex))
     return false;
@@ -3122,17 +3122,17 @@ CType::ConstructBasic(JSContext* cx,
                       const CallArgs& args)
 {
   if (args.length() > 1) {
     JS_ReportError(cx, "CType constructor takes zero or one argument");
     return false;
   }
 
   // construct a CData object
-  RootedObject result(cx, CData::Create(cx, obj, NullPtr(), NULL, true));
+  RootedObject result(cx, CData::Create(cx, obj, NullPtr(), nullptr, true));
   if (!result)
     return false;
 
   if (args.length() == 1) {
     if (!ExplicitConvert(cx, args[0], obj, CData::GetData(result)))
       return false;
   }
 
@@ -3169,45 +3169,45 @@ CType::Create(JSContext* cx,
   //       functions common to all CData objects of types derived from
   //       'typeProto'. (For instance, this could be ctypes.CData.prototype
   //       for simple types, or something representing structs for StructTypes.)
   //     * 'constructor' property === 't'
   //     * Additional properties specified by 'ps', as appropriate for the
   //       specific type instance 't'.
   RootedObject typeObj(cx, JS_NewObject(cx, &sCTypeClass, typeProto, parent));
   if (!typeObj)
-    return NULL;
+    return nullptr;
 
   // Set up the reserved slots.
   JS_SetReservedSlot(typeObj, SLOT_TYPECODE, INT_TO_JSVAL(type));
   if (ffiType)
     JS_SetReservedSlot(typeObj, SLOT_FFITYPE, PRIVATE_TO_JSVAL(ffiType));
   if (name)
     JS_SetReservedSlot(typeObj, SLOT_NAME, STRING_TO_JSVAL(name));
   JS_SetReservedSlot(typeObj, SLOT_SIZE, size);
   JS_SetReservedSlot(typeObj, SLOT_ALIGN, align);
 
   if (dataProto) {
     // Set up the 'prototype' and 'prototype.constructor' properties.
     RootedObject prototype(cx, JS_NewObject(cx, &sCDataProtoClass, dataProto, parent));
     if (!prototype)
-      return NULL;
+      return nullptr;
 
     if (!JS_DefineProperty(cx, prototype, "constructor", OBJECT_TO_JSVAL(typeObj),
-           NULL, NULL, JSPROP_READONLY | JSPROP_PERMANENT))
-      return NULL;
+           nullptr, nullptr, JSPROP_READONLY | JSPROP_PERMANENT))
+      return nullptr;
 
     // Set the 'prototype' object.
     //if (!JS_FreezeObject(cx, prototype)) // XXX fixme - see bug 541212!
-    //  return NULL;
+    //  return nullptr;
     JS_SetReservedSlot(typeObj, SLOT_PROTO, OBJECT_TO_JSVAL(prototype));
   }
 
   if (!JS_FreezeObject(cx, typeObj))
-    return NULL;
+    return nullptr;
 
   // Assert a sanity check on size and alignment: size % alignment should always
   // be zero.
   JS_ASSERT_IF(IsSizeDefined(typeObj),
                GetSize(typeObj) % GetAlignment(typeObj) == 0);
 
   return typeObj;
 }
@@ -3227,27 +3227,27 @@ CType::DefineBuiltin(JSContext* cx,
   RootedObject parent(cx, parent_);
   RootedObject typeProto(cx, typeProto_);
   RootedObject dataProto(cx, dataProto_);
   RootedValue size(cx, size_);
   RootedValue align(cx, align_);
 
   RootedString nameStr(cx, JS_NewStringCopyZ(cx, name));
   if (!nameStr)
-    return NULL;
+    return nullptr;
 
   // Create a new CType object with the common properties and slots.
   RootedObject typeObj(cx, Create(cx, typeProto, dataProto, type, nameStr, size, align, ffiType));
   if (!typeObj)
-    return NULL;
+    return nullptr;
 
   // Define the CType as a 'propName' property on 'parent'.
   if (!JS_DefineProperty(cx, parent, propName, OBJECT_TO_JSVAL(typeObj),
-         NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
-    return NULL;
+         nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
+    return nullptr;
 
   return typeObj;
 }
 
 void
 CType::Finalize(JSFreeOp *fop, JSObject* obj)
 {
   // Make sure our TypeCode slot is legit. If it's not, bail.
@@ -3514,34 +3514,34 @@ CType::GetFFIType(JSContext* cx, JSObjec
     result = StructType::BuildFFIType(cx, obj);
     break;
 
   default:
     MOZ_ASSUME_UNREACHABLE("simple types must have an ffi_type");
   }
 
   if (!result)
-    return NULL;
+    return nullptr;
   JS_SetReservedSlot(obj, SLOT_FFITYPE, PRIVATE_TO_JSVAL(result.get()));
   return result.forget();
 }
 
 JSString*
 CType::GetName(JSContext* cx, HandleObject obj)
 {
   JS_ASSERT(CType::IsCType(obj));
 
   jsval string = JS_GetReservedSlot(obj, SLOT_NAME);
   if (!JSVAL_IS_VOID(string))
     return JSVAL_TO_STRING(string);
 
   // Build the type name lazily.
   JSString* name = BuildTypeName(cx, obj);
   if (!name)
-    return NULL;
+    return nullptr;
   JS_SetReservedSlot(obj, SLOT_NAME, STRING_TO_JSVAL(name));
   return name;
 }
 
 JSObject*
 CType::GetProtoFromCtor(JSObject* obj, CTypeProtoSlot slot)
 {
   // Get ctypes.{Pointer,Array,Struct}Type.prototype from a reserved slot
@@ -3560,17 +3560,17 @@ JSObject*
 CType::GetProtoFromType(JSContext* cx, JSObject* objArg, CTypeProtoSlot slot)
 {
   JS_ASSERT(IsCType(objArg));
   RootedObject obj(cx, objArg);
 
   // Get the prototype of the type object.
   RootedObject proto(cx);
   if (!JS_GetPrototype(cx, obj, &proto))
-    return NULL;
+    return nullptr;
   JS_ASSERT(proto);
   JS_ASSERT(CType::IsCTypeProto(proto));
 
   // Get the requested ctypes.{Pointer,Array,Struct,Function}Type.prototype.
   jsval result = JS_GetReservedSlot(proto, slot);
   JS_ASSERT(!JSVAL_IS_PRIMITIVE(result));
   return JSVAL_TO_OBJECT(result);
 }
@@ -3760,17 +3760,17 @@ CType::HasInstance(JSContext* cx, Handle
 static JSObject*
 CType::GetGlobalCTypes(JSContext* cx, JSObject* objArg)
 {
   JS_ASSERT(CType::IsCType(objArg));
 
   RootedObject obj(cx, objArg);
   RootedObject objTypeProto(cx);
   if (!JS_GetPrototype(cx, obj, &objTypeProto))
-    return NULL;
+    return nullptr;
   JS_ASSERT(objTypeProto);
   JS_ASSERT(CType::IsCTypeProto(objTypeProto));
 
   jsval valCTypes = JS_GetReservedSlot(objTypeProto, SLOT_CTYPES);
   JS_ASSERT(!JSVAL_IS_PRIMITIVE(valCTypes));
 
   JS_ASSERT(!JSVAL_IS_PRIMITIVE(valCTypes));
   return &valCTypes.toObject();
@@ -3864,28 +3864,28 @@ PointerType::CreateInternal(JSContext* c
     return &slot.toObject();
 
   // Get ctypes.PointerType.prototype and the common prototype for CData objects
   // of this type, or ctypes.FunctionType.prototype for function pointers.
   CTypeProtoSlot slotId = CType::GetTypeCode(baseType) == TYPE_function ?
     SLOT_FUNCTIONDATAPROTO : SLOT_POINTERDATAPROTO;
   RootedObject dataProto(cx, CType::GetProtoFromType(cx, baseType, slotId));
   if (!dataProto)
-    return NULL;
+    return nullptr;
   RootedObject typeProto(cx, CType::GetProtoFromType(cx, baseType, SLOT_POINTERPROTO));
   if (!typeProto)
-    return NULL;
+    return nullptr;
 
   // Create a new CType object with the common properties and slots.
   JSObject* typeObj = CType::Create(cx, typeProto, dataProto, TYPE_pointer,
-                        NULL, INT_TO_JSVAL(sizeof(void*)),
+                        nullptr, INT_TO_JSVAL(sizeof(void*)),
                         INT_TO_JSVAL(ffi_type_pointer.alignment),
                         &ffi_type_pointer);
   if (!typeObj)
-    return NULL;
+    return nullptr;
 
   // Set the target type. (This will be 'null' for an opaque pointer type.)
   JS_SetReservedSlot(typeObj, SLOT_TARGET_T, OBJECT_TO_JSVAL(baseType));
 
   // Finally, cache our newly-created PointerType on our pointed-to CType.
   JS_SetReservedSlot(baseType, SLOT_PTR, OBJECT_TO_JSVAL(typeObj));
 
   return typeObj;
@@ -3901,17 +3901,17 @@ PointerType::ConstructData(JSContext* cx
     return false;
   }
 
   if (args.length() > 3) {
     JS_ReportError(cx, "constructor takes 0, 1, 2, or 3 arguments");
     return false;
   }
 
-  RootedObject result(cx, CData::Create(cx, obj, NullPtr(), NULL, true));
+  RootedObject result(cx, CData::Create(cx, obj, NullPtr(), nullptr, true));
   if (!result)
     return false;
 
   // Set return value early, must not observe *vp after
   args.rval().setObject(*result);
 
   // There are 3 things that we might be creating here:
   // 1 - A null pointer (no arguments)
@@ -3946,20 +3946,20 @@ PointerType::ConstructData(JSContext* cx
 
   //
   // Case 3 - Closure
   //
 
   // The second argument is an optional 'this' parameter with which to invoke
   // the given js function. Callers may leave this blank, or pass null if they
   // wish to pass the third argument.
-  RootedObject thisObj(cx, NULL);
+  RootedObject thisObj(cx, nullptr);
   if (args.length() >= 2) {
     if (args[1].isNull()) {
-      thisObj = NULL;
+      thisObj = nullptr;
     } else if (!JSVAL_IS_PRIMITIVE(args[1])) {
       thisObj = &args[1].toObject();
     } else if (!JS_ValueToObject(cx, args[1], &thisObj)) {
       return false;
     }
   }
 
   // The third argument is an optional error sentinel that js-ctypes will return
@@ -4014,17 +4014,17 @@ PointerType::IsNull(JSContext* cx, unsig
   // Get pointer type and base type.
   JSObject* typeObj = CData::GetCType(obj);
   if (CType::GetTypeCode(typeObj) != TYPE_pointer) {
     JS_ReportError(cx, "not a PointerType");
     return false;
   }
 
   void* data = *static_cast<void**>(CData::GetData(obj));
-  args.rval().setBoolean(data == NULL);
+  args.rval().setBoolean(data == nullptr);
   return true;
 }
 
 bool
 PointerType::OffsetBy(JSContext* cx, const CallArgs& args, int offset)
 {
   JSObject* obj = JS_THIS_OBJECT(cx, args.base());
   if (!obj)
@@ -4093,17 +4093,17 @@ PointerType::ContentsGetter(JSContext* c
 
   RootedObject baseType(cx, GetBaseType(typeObj));
   if (!CType::IsSizeDefined(baseType)) {
     JS_ReportError(cx, "cannot get contents of undefined size");
     return false;
   }
 
   void* data = *static_cast<void**>(CData::GetData(obj));
-  if (data == NULL) {
+  if (data == nullptr) {
     JS_ReportError(cx, "cannot read contents of null pointer");
     return false;
   }
 
   RootedValue result(cx);
   if (!ConvertToJS(cx, baseType, NullPtr(), data, false, false, result.address()))
     return false;
 
@@ -4132,22 +4132,22 @@ PointerType::ContentsSetter(JSContext* c
 
   JSObject* baseType = GetBaseType(typeObj);
   if (!CType::IsSizeDefined(baseType)) {
     JS_ReportError(cx, "cannot set contents of undefined size");
     return false;
   }
 
   void* data = *static_cast<void**>(CData::GetData(obj));
-  if (data == NULL) {
+  if (data == nullptr) {
     JS_ReportError(cx, "cannot write contents to null pointer");
     return false;
   }
 
-  return ImplicitConvert(cx, vp, baseType, data, false, NULL);
+  return ImplicitConvert(cx, vp, baseType, data, false, nullptr);
 }
 
 /*******************************************************************************
 ** ArrayType implementation
 *******************************************************************************/
 
 bool
 ArrayType::Create(JSContext* cx, unsigned argc, jsval* vp)
@@ -4186,51 +4186,51 @@ ArrayType::CreateInternal(JSContext* cx,
                           HandleObject baseType,
                           size_t length,
                           bool lengthDefined)
 {
   // Get ctypes.ArrayType.prototype and the common prototype for CData objects
   // of this type, from ctypes.CType.prototype.
   RootedObject typeProto(cx, CType::GetProtoFromType(cx, baseType, SLOT_ARRAYPROTO));
   if (!typeProto)
-    return NULL;
+    return nullptr;
   RootedObject dataProto(cx, CType::GetProtoFromType(cx, baseType, SLOT_ARRAYDATAPROTO));
   if (!dataProto)
-    return NULL;
+    return nullptr;
 
   // Determine the size of the array from the base type, if possible.
   // The size of the base type must be defined.
   // If our length is undefined, both our size and length will be undefined.
   size_t baseSize;
   if (!CType::GetSafeSize(baseType, &baseSize)) {
     JS_ReportError(cx, "base size must be defined");
-    return NULL;
+    return nullptr;
   }
 
   RootedValue sizeVal(cx, JSVAL_VOID);
   RootedValue lengthVal(cx, JSVAL_VOID);
   if (lengthDefined) {
     // Check for overflow, and convert to an int or double as required.
     size_t size = length * baseSize;
     if (length > 0 && size / length != baseSize) {
       JS_ReportError(cx, "size overflow");
-      return NULL;
+      return nullptr;
     }
     if (!SizeTojsval(cx, size, sizeVal.address()) ||
         !SizeTojsval(cx, length, lengthVal.address()))
-      return NULL;
+      return nullptr;
   }
 
   size_t align = CType::GetAlignment(baseType);
 
   // Create a new CType object with the common properties and slots.
-  JSObject* typeObj = CType::Create(cx, typeProto, dataProto, TYPE_array, NULL,
-                        sizeVal, INT_TO_JSVAL(align), NULL);
+  JSObject* typeObj = CType::Create(cx, typeProto, dataProto, TYPE_array, nullptr,
+                        sizeVal, INT_TO_JSVAL(align), nullptr);
   if (!typeObj)
-    return NULL;
+    return nullptr;
 
   // Set the element type.
   JS_SetReservedSlot(typeObj, SLOT_ELEMENT_T, OBJECT_TO_JSVAL(baseType));
 
   // Set the length.
   JS_SetReservedSlot(typeObj, SLOT_LENGTH, lengthVal);
 
   return typeObj;
@@ -4318,17 +4318,17 @@ ArrayType::ConstructData(JSContext* cx,
     }
 
     // Construct a new ArrayType of defined length, for the new CData object.
     obj = CreateInternal(cx, baseType, length, true);
     if (!obj)
       return false;
   }
 
-  JSObject* result = CData::Create(cx, obj, NullPtr(), NULL, true);
+  JSObject* result = CData::Create(cx, obj, NullPtr(), nullptr, true);
   if (!result)
     return false;
 
   args.rval().setObject(*result);
 
   if (convertObject) {
     if (!ExplicitConvert(cx, args[0], obj, CData::GetData(result)))
       return false;
@@ -4394,45 +4394,45 @@ ArrayType::BuildFFIType(JSContext* cx, J
 {
   JS_ASSERT(CType::IsCType(obj));
   JS_ASSERT(CType::GetTypeCode(obj) == TYPE_array);
   JS_ASSERT(CType::IsSizeDefined(obj));
 
   JSObject* baseType = ArrayType::GetBaseType(obj);
   ffi_type* ffiBaseType = CType::GetFFIType(cx, baseType);
   if (!ffiBaseType)
-    return NULL;
+    return nullptr;
 
   size_t length = ArrayType::GetLength(obj);
 
   // Create an ffi_type to represent the array. This is necessary for the case
   // where the array is part of a struct. Since libffi has no intrinsic
   // support for array types, we approximate it by creating a struct type
   // with elements of type 'baseType' and with appropriate size and alignment
   // values. It would be nice to not do all the work of setting up 'elements',
   // but some libffi platforms currently require that it be meaningful. I'm
   // looking at you, x86_64.
   AutoPtr<ffi_type> ffiType(cx->new_<ffi_type>());
   if (!ffiType) {
     JS_ReportOutOfMemory(cx);
-    return NULL;
+    return nullptr;
   }
 
   ffiType->type = FFI_TYPE_STRUCT;
   ffiType->size = CType::GetSize(obj);
   ffiType->alignment = CType::GetAlignment(obj);
   ffiType->elements = cx->pod_malloc<ffi_type*>(length + 1);
   if (!ffiType->elements) {
     JS_ReportAllocationOverflow(cx);
-    return NULL;
+    return nullptr;
   }
 
   for (size_t i = 0; i < length; ++i)
     ffiType->elements[i] = ffiBaseType;
-  ffiType->elements[length] = NULL;
+  ffiType->elements[length] = nullptr;
 
   return ffiType.forget();
 }
 
 bool
 ArrayType::ElementTypeGetter(JSContext* cx, HandleObject obj, HandleId idval, MutableHandleValue vp)
 {
   if (!CType::IsCType(obj) || CType::GetTypeCode(obj) != TYPE_array) {
@@ -4529,17 +4529,17 @@ ArrayType::Setter(JSContext* cx, HandleO
   if (!ok || index >= length) {
     JS_ReportError(cx, "invalid index");
     return false;
   }
 
   JSObject* baseType = GetBaseType(typeObj);
   size_t elementSize = CType::GetSize(baseType);
   char* data = static_cast<char*>(CData::GetData(obj)) + elementSize * index;
-  return ImplicitConvert(cx, vp, baseType, data, false, NULL);
+  return ImplicitConvert(cx, vp, baseType, data, false, nullptr);
 }
 
 bool
 ArrayType::AddressOfElement(JSContext* cx, unsigned argc, jsval* vp)
 {
   CallArgs args = CallArgsFromVp(argc, vp);
   RootedObject obj(cx, JS_THIS_OBJECT(cx, vp));
   if (!obj)
@@ -4561,17 +4561,17 @@ ArrayType::AddressOfElement(JSContext* c
   }
 
   RootedObject baseType(cx, GetBaseType(typeObj));
   RootedObject pointerType(cx, PointerType::CreateInternal(cx, baseType));
   if (!pointerType)
     return false;
 
   // Create a PointerType CData object containing null.
-  RootedObject result(cx, CData::Create(cx, pointerType, NullPtr(), NULL, true));
+  RootedObject result(cx, CData::Create(cx, pointerType, NullPtr(), nullptr, true));
   if (!result)
     return false;
 
   args.rval().setObject(*result);
 
   // Convert the index to a size_t and bounds-check it.
   size_t index;
   size_t length = GetLength(typeObj);
@@ -4594,87 +4594,87 @@ ArrayType::AddressOfElement(JSContext* c
 
 // For a struct field descriptor 'val' of the form { name : type }, extract
 // 'name' and 'type'.
 static JSFlatString*
 ExtractStructField(JSContext* cx, jsval val, JSObject** typeObj)
 {
   if (JSVAL_IS_PRIMITIVE(val)) {
     JS_ReportError(cx, "struct field descriptors require a valid name and type");
-    return NULL;
+    return nullptr;
   }
 
   RootedObject obj(cx, JSVAL_TO_OBJECT(val));
   RootedObject iter(cx, JS_NewPropertyIterator(cx, obj));
   if (!iter)
-    return NULL;
+    return nullptr;
 
   RootedId nameid(cx);
   if (!JS_NextProperty(cx, iter, nameid.address()))
-    return NULL;
+    return nullptr;
   if (JSID_IS_VOID(nameid)) {
     JS_ReportError(cx, "struct field descriptors require a valid name and type");
-    return NULL;
+    return nullptr;
   }
 
   if (!JSID_IS_STRING(nameid)) {
     JS_ReportError(cx, "struct field descriptors require a valid name and type");
-    return NULL;
+    return nullptr;
   }
 
   // make sure we have one, and only one, property
   jsid id;
   if (!JS_NextProperty(cx, iter, &id))
-    return NULL;
+    return nullptr;
   if (!JSID_IS_VOID(id)) {
     JS_ReportError(cx, "struct field descriptors must contain one property");
-    return NULL;
+    return nullptr;
   }
 
   RootedValue propVal(cx);
   if (!JS_GetPropertyById(cx, obj, nameid, &propVal))
-    return NULL;
+    return nullptr;
 
   if (propVal.isPrimitive() || !CType::IsCType(&propVal.toObject())) {
     JS_ReportError(cx, "struct field descriptors require a valid name and type");
-    return NULL;
+    return nullptr;
   }
 
   // Undefined size or zero size struct members are illegal.
   // (Zero-size arrays are legal as struct members in C++, but libffi will
   // choke on a zero-size struct, so we disallow them.)
   *typeObj = &propVal.toObject();
   size_t size;
   if (!CType::GetSafeSize(*typeObj, &size) || size == 0) {
     JS_ReportError(cx, "struct field types must have defined and nonzero size");
-    return NULL;
+    return nullptr;
   }
 
   return JSID_TO_FLAT_STRING(nameid);
 }
 
 // For a struct field with 'name' and 'type', add an element of the form
 // { name : type }.
 static bool
 AddFieldToArray(JSContext* cx,
                 jsval* element,
                 JSFlatString* name_,
                 JSObject* typeObj_)
 {
   RootedObject typeObj(cx, typeObj_);
   Rooted<JSFlatString*> name(cx, name_);
-  RootedObject fieldObj(cx, JS_NewObject(cx, NULL, NULL, NULL));
+  RootedObject fieldObj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
   if (!fieldObj)
     return false;
 
   *element = OBJECT_TO_JSVAL(fieldObj);
 
   if (!JS_DefineUCProperty(cx, fieldObj,
          name->chars(), name->length(),
-         OBJECT_TO_JSVAL(typeObj), NULL, NULL,
+         OBJECT_TO_JSVAL(typeObj), nullptr, nullptr,
          JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
     return false;
 
   return JS_FreezeObject(cx, fieldObj);
 }
 
 bool
 StructType::Create(JSContext* cx, unsigned argc, jsval* vp)
@@ -4695,22 +4695,22 @@ StructType::Create(JSContext* cx, unsign
 
   // Get ctypes.StructType.prototype from the ctypes.StructType constructor.
   RootedObject typeProto(cx, CType::GetProtoFromCtor(&args.callee(), SLOT_STRUCTPROTO));
 
   // Create a simple StructType with no defined fields. The result will be
   // non-instantiable as CData, will have no 'prototype' property, and will
   // have undefined size and alignment and no ffi_type.
   RootedObject result(cx, CType::Create(cx, typeProto, NullPtr(), TYPE_struct,
-                                        JSVAL_TO_STRING(name), JSVAL_VOID, JSVAL_VOID, NULL));
+                                        JSVAL_TO_STRING(name), JSVAL_VOID, JSVAL_VOID, nullptr));
   if (!result)
     return false;
 
   if (args.length() == 2) {
-    RootedObject arr(cx, JSVAL_IS_PRIMITIVE(args[1]) ? NULL : &args[1].toObject());
+    RootedObject arr(cx, JSVAL_IS_PRIMITIVE(args[1]) ? nullptr : &args[1].toObject());
     if (!arr || !JS_IsArrayObject(cx, arr)) {
       JS_ReportError(cx, "second argument must be an array");
       return false;
     }
 
     // Define the struct fields.
     if (!DefineInternal(cx, result, arr))
       return false;
@@ -4743,22 +4743,22 @@ StructType::DefineInternal(JSContext* cx
   // ctypes.CType.prototype.
   RootedObject dataProto(cx, CType::GetProtoFromType(cx, typeObj, SLOT_STRUCTDATAPROTO));
   if (!dataProto)
     return false;
 
   // Set up the 'prototype' and 'prototype.constructor' properties.
   // The prototype will reflect the struct fields as properties on CData objects
   // created from this type.
-  RootedObject prototype(cx, JS_NewObject(cx, &sCDataProtoClass, dataProto, NULL));
+  RootedObject prototype(cx, JS_NewObject(cx, &sCDataProtoClass, dataProto, nullptr));
   if (!prototype)
     return false;
 
   if (!JS_DefineProperty(cx, prototype, "constructor", OBJECT_TO_JSVAL(typeObj),
-         NULL, NULL, JSPROP_READONLY | JSPROP_PERMANENT))
+         nullptr, nullptr, JSPROP_READONLY | JSPROP_PERMANENT))
     return false;
 
   // Create a FieldInfoHash to stash on the type object, and an array to root
   // its constituents. (We cannot simply stash the hash in a reserved slot now
   // to get GC safety for free, since if anything in this function fails we
   // do not want to mutate 'typeObj'.)
   AutoPtr<FieldInfoHash> fields(cx->new_<FieldInfoHash>());
   Array<jsval, 16> fieldRootsArray;
@@ -4775,17 +4775,17 @@ StructType::DefineInternal(JSContext* cx
     structSize = 0;
     structAlign = 0;
 
     for (uint32_t i = 0; i < len; ++i) {
       RootedValue item(cx);
       if (!JS_GetElement(cx, fieldsObj, i, &item))
         return false;
 
-      RootedObject fieldType(cx, NULL);
+      RootedObject fieldType(cx, nullptr);
       JSFlatString* flat = ExtractStructField(cx, item, fieldType.address());
       if (!flat)
         return false;
       Rooted<JSStableString*> name(cx, flat->ensureStable(cx));
       if (!name)
         return false;
       fieldRootsArray[i] = OBJECT_TO_JSVAL(fieldType);
 
@@ -4870,60 +4870,60 @@ StructType::BuildFFIType(JSContext* cx, 
   size_t len = fields->count();
 
   size_t structSize = CType::GetSize(obj);
   size_t structAlign = CType::GetAlignment(obj);
 
   AutoPtr<ffi_type> ffiType(cx->new_<ffi_type>());
   if (!ffiType) {
     JS_ReportOutOfMemory(cx);
-    return NULL;
+    return nullptr;
   }
   ffiType->type = FFI_TYPE_STRUCT;
 
   AutoPtr<ffi_type*> elements;
   if (len != 0) {
     elements = cx->pod_malloc<ffi_type*>(len + 1);
     if (!elements) {
       JS_ReportOutOfMemory(cx);
-      return NULL;
+      return nullptr;
     }
-    elements[len] = NULL;
+    elements[len] = nullptr;
 
     for (FieldInfoHash::Range r = fields->all(); !r.empty(); r.popFront()) {
       const FieldInfoHash::Entry& entry = r.front();
       ffi_type* fieldType = CType::GetFFIType(cx, entry.value.mType);
       if (!fieldType)
-        return NULL;
+        return nullptr;
       elements[entry.value.mIndex] = fieldType;
     }
 
   } else {
     // Represent an empty struct as having a size of 1 byte, just like C++.
     JS_ASSERT(structSize == 1);
     JS_ASSERT(structAlign == 1);
     elements = cx->pod_malloc<ffi_type*>(2);
     if (!elements) {
       JS_ReportOutOfMemory(cx);
-      return NULL;
+      return nullptr;
     }
     elements[0] = &ffi_type_uint8;
-    elements[1] = NULL;
+    elements[1] = nullptr;
   }
 
   ffiType->elements = elements.get();
 
 #ifdef DEBUG
   // Perform a sanity check: the result of our struct size and alignment
   // calculations should match libffi's. We force it to do this calculation
   // by calling ffi_prep_cif.
   ffi_cif cif;
   ffiType->size = 0;
   ffiType->alignment = 0;
-  ffi_status status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, ffiType.get(), NULL);
+  ffi_status status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, ffiType.get(), nullptr);
   JS_ASSERT(status == FFI_OK);
   JS_ASSERT(structSize == ffiType->size);
   JS_ASSERT(structAlign == ffiType->alignment);
 #else
   // Fill in the ffi_type's size and align fields. This makes libffi treat the
   // type as initialized; it will not recompute the values. (We assume
   // everything agrees; if it doesn't, we really want to know about it, which
   // is the purpose of the above debug-only check.)
@@ -4982,17 +4982,17 @@ StructType::ConstructData(JSContext* cx,
     return false;
   }
 
   if (!CType::IsSizeDefined(obj)) {
     JS_ReportError(cx, "cannot construct an opaque StructType");
     return false;
   }
 
-  JSObject* result = CData::Create(cx, obj, NullPtr(), NULL, true);
+  JSObject* result = CData::Create(cx, obj, NullPtr(), nullptr, true);
   if (!result)
     return false;
 
   args.rval().setObject(*result);
 
   if (args.length() == 0)
     return true;
 
@@ -5030,17 +5030,17 @@ StructType::ConstructData(JSContext* cx,
   // We have a type constructor of the form 'ctypes.StructType(a, b, c, ...)'.
   // ImplicitConvert each field.
   if (args.length() == fields->count()) {
     for (FieldInfoHash::Range r = fields->all(); !r.empty(); r.popFront()) {
       const FieldInfo& field = r.front().value;
       STATIC_ASSUME(field.mIndex < fields->count());  /* Quantified invariant */
       if (!ImplicitConvert(cx, args[field.mIndex], field.mType,
              buffer + field.mOffset,
-             false, NULL))
+             false, nullptr))
         return false;
     }
 
     return true;
   }
 
   JS_ReportError(cx, "constructor takes 0, 1, or %u arguments",
     fields->count());
@@ -5066,53 +5066,53 @@ StructType::LookupField(JSContext* cx, J
   JS_ASSERT(CType::GetTypeCode(obj) == TYPE_struct);
 
   FieldInfoHash::Ptr ptr = GetFieldInfo(obj)->lookup(name);
   if (ptr)
     return &ptr->value;
 
   JSAutoByteString bytes(cx, name);
   if (!bytes)
-    return NULL;
+    return nullptr;
 
   JS_ReportError(cx, "%s does not name a field", bytes.ptr());
-  return NULL;
+  return nullptr;
 }
 
 JSObject*
 StructType::BuildFieldsArray(JSContext* cx, JSObject* obj)
 {
   JS_ASSERT(CType::IsCType(obj));
   JS_ASSERT(CType::GetTypeCode(obj) == TYPE_struct);
   JS_ASSERT(CType::IsSizeDefined(obj));
 
   const FieldInfoHash* fields = GetFieldInfo(obj);
   size_t len = fields->count();
 
   // Prepare a new array for the 'fields' property of the StructType.
   Array<jsval, 16> fieldsVec;
   if (!fieldsVec.appendN(JSVAL_VOID, len))
-    return NULL;
+    return nullptr;
   js::AutoArrayRooter root(cx, fieldsVec.length(), fieldsVec.begin());
 
   for (FieldInfoHash::Range r = fields->all(); !r.empty(); r.popFront()) {
     const FieldInfoHash::Entry& entry = r.front();
     // Add the field descriptor to the array.
     if (!AddFieldToArray(cx, &fieldsVec[entry.value.mIndex],
                          entry.key, entry.value.mType))
-      return NULL;
+      return nullptr;
   }
 
   RootedObject fieldsProp(cx, JS_NewArrayObject(cx, len, fieldsVec.begin()));
   if (!fieldsProp)
-    return NULL;
+    return nullptr;
 
   // Seal the fields array.
   if (!JS_FreezeObject(cx, fieldsProp))
-    return NULL;
+    return nullptr;
 
   return fieldsProp;
 }
 
 bool
 StructType::FieldsArrayGetter(JSContext* cx, HandleObject obj, HandleId idval, MutableHandleValue vp)
 {
   if (!CType::IsCType(obj) || CType::GetTypeCode(obj) != TYPE_struct) {
@@ -5179,17 +5179,17 @@ StructType::FieldSetter(JSContext* cx, H
     return false;
   }
 
   const FieldInfo* field = LookupField(cx, typeObj, JSID_TO_FLAT_STRING(idval));
   if (!field)
     return false;
 
   char* data = static_cast<char*>(CData::GetData(obj)) + field->mOffset;
-  return ImplicitConvert(cx, vp, field->mType, data, false, NULL);
+  return ImplicitConvert(cx, vp, field->mType, data, false, nullptr);
 }
 
 bool
 StructType::AddressOfField(JSContext* cx, unsigned argc, jsval* vp)
 {
   CallArgs args = CallArgsFromVp(argc, vp);
   RootedObject obj(cx, JS_THIS_OBJECT(cx, vp));
   if (!obj)
@@ -5219,17 +5219,17 @@ StructType::AddressOfField(JSContext* cx
     return false;
 
   RootedObject baseType(cx, field->mType);
   RootedObject pointerType(cx, PointerType::CreateInternal(cx, baseType));
   if (!pointerType)
     return false;
 
   // Create a PointerType CData object containing null.
-  JSObject* result = CData::Create(cx, pointerType, NullPtr(), NULL, true);
+  JSObject* result = CData::Create(cx, pointerType, NullPtr(), nullptr, true);
   if (!result)
     return false;
 
   args.rval().setObject(*result);
 
   // Manually set the pointer inside the object, so we skip the conversion step.
   void** data = static_cast<void**>(CData::GetData(result));
   *data = static_cast<char*>(CData::GetData(obj)) + field->mOffset;
@@ -5238,31 +5238,31 @@ StructType::AddressOfField(JSContext* cx
 
 /*******************************************************************************
 ** FunctionType implementation
 *******************************************************************************/
 
 // Helper class for handling allocation of function arguments.
 struct AutoValue
 {
-  AutoValue() : mData(NULL) { }
+  AutoValue() : mData(nullptr) { }
 
   ~AutoValue()
   {
     js_free(mData);
   }
 
   bool SizeToType(JSContext* cx, JSObject* type)
   {
     // Allocate a minimum of sizeof(ffi_arg) to handle small integers.
     size_t size = Align(CType::GetSize(type), sizeof(ffi_arg));
     mData = js_malloc(size);
     if (mData)
       memset(mData, 0, size);
-    return mData != NULL;
+    return mData != nullptr;
   }
 
   void* mData;
 };
 
 static bool
 GetABI(JSContext* cx, jsval abiType, ffi_abi* result)
 {
@@ -5296,68 +5296,68 @@ GetABI(JSContext* cx, jsval abiType, ffi
 }
 
 static JSObject*
 PrepareType(JSContext* cx, jsval type)
 {
   if (JSVAL_IS_PRIMITIVE(type) ||
       !CType::IsCType(JSVAL_TO_OBJECT(type))) {
     JS_ReportError(cx, "not a ctypes type");
-    return NULL;
+    return nullptr;
   }
 
   JSObject* result = JSVAL_TO_OBJECT(type);
   TypeCode typeCode = CType::GetTypeCode(result);
 
   if (typeCode == TYPE_array) {
     // convert array argument types to pointers, just like C.
     // ImplicitConvert will do the same, when passing an array as data.
     RootedObject baseType(cx, ArrayType::GetBaseType(result));
     result = PointerType::CreateInternal(cx, baseType);
     if (!result)
-      return NULL;
+      return nullptr;
 
   } else if (typeCode == TYPE_void_t || typeCode == TYPE_function) {
     // disallow void or function argument types
     JS_ReportError(cx, "Cannot have void or function argument type");
-    return NULL;
+    return nullptr;
   }
 
   if (!CType::IsSizeDefined(result)) {
     JS_ReportError(cx, "Argument type must have defined size");
-    return NULL;
+    return nullptr;
   }
 
   // libffi cannot pass types of zero size by value.
   JS_ASSERT(CType::GetSize(result) != 0);
 
   return result;
 }
 
 static JSObject*
 PrepareReturnType(JSContext* cx, jsval type)
 {
   if (JSVAL_IS_PRIMITIVE(type) ||
       !CType::IsCType(JSVAL_TO_OBJECT(type))) {
     JS_ReportError(cx, "not a ctypes type");
-    return NULL;
+    return nullptr;
   }
 
   JSObject* result = JSVAL_TO_OBJECT(type);
   TypeCode typeCode = CType::GetTypeCode(result);
 
   // Arrays and functions can never be return types.
   if (typeCode == TYPE_array || typeCode == TYPE_function) {
     JS_ReportError(cx, "Return type cannot be an array or function");
-    return NULL;
+    return nullptr;
   }
 
   if (typeCode != TYPE_void_t && !CType::IsSizeDefined(result)) {
     JS_ReportError(cx, "Return type must have defined size");
-    return NULL;
+    return nullptr;
   }
 
   // libffi cannot pass types of zero size by value.
   JS_ASSERT(typeCode == TYPE_void_t || CType::GetSize(result) != 0);
 
   return result;
 }
 
@@ -5466,98 +5466,98 @@ NewFunctionInfo(JSContext* cx,
                 jsval abiType,
                 jsval returnType,
                 jsval* argTypes,
                 unsigned argLength)
 {
   AutoPtr<FunctionInfo> fninfo(cx->new_<FunctionInfo>());
   if (!fninfo) {
     JS_ReportOutOfMemory(cx);
-    return NULL;
+    return nullptr;
   }
 
   ffi_abi abi;
   if (!GetABI(cx, abiType, &abi)) {
     JS_ReportError(cx, "Invalid ABI specification");
-    return NULL;
+    return nullptr;
   }
   fninfo->mABI = JSVAL_TO_OBJECT(abiType);
 
   // prepare the result type
   fninfo->mReturnType = PrepareReturnType(cx, returnType);
   if (!fninfo->mReturnType)
-    return NULL;
+    return nullptr;
 
   // prepare the argument types
   if (!fninfo->mArgTypes.reserve(argLength) ||
       !fninfo->mFFITypes.reserve(argLength)) {
     JS_ReportOutOfMemory(cx);
-    return NULL;
+    return nullptr;
   }
 
   fninfo->mIsVariadic = false;
 
   for (uint32_t i = 0; i < argLength; ++i) {
     bool isEllipsis;
     if (!IsEllipsis(cx, argTypes[i], &isEllipsis))
-      return NULL;
+      return nullptr;
     if (isEllipsis) {
       fninfo->mIsVariadic = true;
       if (i < 1) {
         JS_ReportError(cx, "\"...\" may not be the first and only parameter "
                        "type of a variadic function declaration");
-        return NULL;
+        return nullptr;
       }
       if (i < argLength - 1) {
         JS_ReportError(cx, "\"...\" must be the last parameter type of a "
                        "variadic function declaration");
-        return NULL;
+        return nullptr;
       }
       if (GetABICode(fninfo->mABI) != ABI_DEFAULT) {
         JS_ReportError(cx, "Variadic functions must use the __cdecl calling "
                        "convention");
-        return NULL;
+        return nullptr;
       }
       break;
     }
 
     JSObject* argType = PrepareType(cx, argTypes[i]);
     if (!argType)
-      return NULL;
+      return nullptr;
 
     ffi_type* ffiType = CType::GetFFIType(cx, argType);
     if (!ffiType)
-      return NULL;
+      return nullptr;
 
     fninfo->mArgTypes.infallibleAppend(argType);
     fninfo->mFFITypes.infallibleAppend(ffiType);
   }
 
   if (fninfo->mIsVariadic)
     // wait to PrepareCIF until function is called
     return fninfo.forget();
 
   if (!PrepareCIF(cx, fninfo.get()))
-    return NULL;
+    return nullptr;
 
   return fninfo.forget();
 }
 
 bool
 FunctionType::Create(JSContext* cx, unsigned argc, jsval* vp)
 {
   // Construct and return a new FunctionType object.
   CallArgs args = CallArgsFromVp(argc, vp);
   if (args.length() < 2 || args.length() > 3) {
     JS_ReportError(cx, "FunctionType takes two or three arguments");
     return false;
   }
 
   AutoValueVector argTypes(cx);
-  RootedObject arrayObj(cx, NULL);
+  RootedObject arrayObj(cx, nullptr);
 
   if (args.length() == 3) {
     // Prepare an array of jsvals for the arguments.
     if (!JSVAL_IS_PRIMITIVE(args[2]))
       arrayObj = &args[2].toObject();
     if (!arrayObj || !JS_IsArrayObject(cx, arrayObj)) {
       JS_ReportError(cx, "third argument must be an array");
       return false;
@@ -5593,34 +5593,34 @@ FunctionType::CreateInternal(JSContext* 
                              jsval abi,
                              jsval rtype,
                              jsval* argtypes,
                              unsigned arglen)
 {
   // Determine and check the types, and prepare the function CIF.
   AutoPtr<FunctionInfo> fninfo(NewFunctionInfo(cx, abi, rtype, argtypes, arglen));
   if (!fninfo)
-    return NULL;
+    return nullptr;
 
   // Get ctypes.FunctionType.prototype and the common prototype for CData objects
   // of this type, from ctypes.CType.prototype.
   RootedObject typeProto(cx, CType::GetProtoFromType(cx, fninfo->mReturnType,
                                                      SLOT_FUNCTIONPROTO));
   if (!typeProto)
-    return NULL;
+    return nullptr;
   RootedObject dataProto(cx, CType::GetProtoFromType(cx, fninfo->mReturnType,
                                                      SLOT_FUNCTIONDATAPROTO));
   if (!dataProto)
-    return NULL;
+    return nullptr;
 
   // Create a new CType object with the common properties and slots.
   JSObject* typeObj = CType::Create(cx, typeProto, dataProto, TYPE_function,
-                        NULL, JSVAL_VOID, JSVAL_VOID, NULL);
+                        nullptr, JSVAL_VOID, JSVAL_VOID, nullptr);
   if (!typeObj)
-    return NULL;
+    return nullptr;
 
   // Stash the FunctionInfo in a reserved slot.
   JS_SetReservedSlot(typeObj, SLOT_FNINFO, PRIVATE_TO_JSVAL(fninfo.forget()));
 
   return typeObj;
 }
 
 // Construct a function pointer to a JS function (see CClosure::Create()).
@@ -5959,92 +5959,92 @@ CClosure::Create(JSContext* cx,
                  HandleObject fnObj,
                  HandleObject thisObj,
                  jsval errVal_,
                  PRFuncPtr* fnptr)
 {
   RootedValue errVal(cx, errVal_);
   JS_ASSERT(fnObj);
 
-  RootedObject result(cx, JS_NewObject(cx, &sCClosureClass, NULL, NULL));
+  RootedObject result(cx, JS_NewObject(cx, &sCClosureClass, nullptr, nullptr));
   if (!result)
-    return NULL;
+    return nullptr;
 
   // Get the FunctionInfo from the FunctionType.
   FunctionInfo* fninfo = FunctionType::GetFunctionInfo(typeObj);
   JS_ASSERT(!fninfo->mIsVariadic);
   JS_ASSERT(GetABICode(fninfo->mABI) != ABI_WINAPI);
 
   AutoPtr<ClosureInfo> cinfo(cx->new_<ClosureInfo>(JS_GetRuntime(cx)));
   if (!cinfo) {
     JS_ReportOutOfMemory(cx);
-    return NULL;
+    return nullptr;
   }
 
   // Get the prototype of the FunctionType object, of class CTypeProto,
   // which stores our JSContext for use with the closure.
   RootedObject proto(cx);
   if (!JS_GetPrototype(cx, typeObj, &proto))
-    return NULL;
+    return nullptr;
   JS_ASSERT(proto);
   JS_ASSERT(CType::IsCTypeProto(proto));
 
   // Get a JSContext for use with the closure.
   cinfo->cx = js::DefaultJSContext(JS_GetRuntime(cx));
 
   // Prepare the error sentinel value. It's important to do this now, because
   // we might be unable to convert the value to the proper type. If so, we want
   // the caller to know about it _now_, rather than some uncertain time in the
   // future when the error sentinel is actually needed.
   if (!JSVAL_IS_VOID(errVal)) {
 
     // Make sure the callback returns something.
     if (CType::GetTypeCode(fninfo->mReturnType) == TYPE_void_t) {
       JS_ReportError(cx, "A void callback can't pass an error sentinel");
-      return NULL;
+      return nullptr;
     }
 
     // With the exception of void, the FunctionType constructor ensures that
     // the return type has a defined size.
     JS_ASSERT(CType::IsSizeDefined(fninfo->mReturnType));
 
     // Allocate a buffer for the return value.
     size_t rvSize = CType::GetSize(fninfo->mReturnType);
     cinfo->errResult = cx->malloc_(rvSize);
     if (!cinfo->errResult)
-      return NULL;
+      return nullptr;
 
     // Do the value conversion. This might fail, in which case we throw.
     if (!ImplicitConvert(cx, errVal, fninfo->mReturnType, cinfo->errResult,
-                         false, NULL))
-      return NULL;
+                         false, nullptr))
+      return nullptr;
   } else {
-    cinfo->errResult = NULL;
+    cinfo->errResult = nullptr;
   }
 
   // Copy the important bits of context into cinfo.
   cinfo->closureObj = result;
   cinfo->typeObj = typeObj;
   cinfo->thisObj = thisObj;
   cinfo->jsfnObj = fnObj;
 
   // Create an ffi_closure object and initialize it.
   void* code;
   cinfo->closure =
     static_cast<ffi_closure*>(ffi_closure_alloc(sizeof(ffi_closure), &code));
   if (!cinfo->closure || !code) {
     JS_ReportError(cx, "couldn't create closure - libffi error");
-    return NULL;
+    return nullptr;
   }
 
   ffi_status status = ffi_prep_closure_loc(cinfo->closure, &fninfo->mCIF,
     CClosure::ClosureStub, cinfo.get(), code);
   if (status != FFI_OK) {
     JS_ReportError(cx, "couldn't create closure - libffi error");
-    return NULL;
+    return nullptr;
   }
 
   // Stash the ClosureInfo struct on our new object.
   JS_SetReservedSlot(result, SLOT_CLOSUREINFO, PRIVATE_TO_JSVAL(cinfo.forget()));
 
   // Casting between void* and a function pointer is forbidden in C and C++.
   // Do it via an integral type.
   *fnptr = reinterpret_cast<PRFuncPtr>(reinterpret_cast<uintptr_t>(code));
@@ -6146,30 +6146,30 @@ CClosure::ClosureStub(ffi_cif* cif, void
   for (uint32_t i = 0; i < cif->nargs; ++i) {
     // Convert each argument, and have any CData objects created depend on
     // the existing buffers.
     RootedObject argType(cx, fninfo->mArgTypes[i]);
     if (!ConvertToJS(cx, argType, NullPtr(), args[i], false, false, &argv[i]))
       return;
   }
 
-  // Call the JS function. 'thisObj' may be NULL, in which case the JS engine
-  // will find an appropriate object to use.
+  // Call the JS function. 'thisObj' may be nullptr, in which case the JS
+  // engine will find an appropriate object to use.
   RootedValue rval(cx);
   bool success = JS_CallFunctionValue(cx, thisObj, OBJECT_TO_JSVAL(jsfnObj),
                                         cif->nargs, argv.begin(), rval.address());
 
   // Convert the result. Note that we pass 'isArgument = false', such that
   // ImplicitConvert will *not* autoconvert a JS string into a pointer-to-char
   // type, which would require an allocation that we can't track. The JS
   // function must perform this conversion itself and return a PointerType
   // CData; thusly, the burden of freeing the data is left to the user.
   if (success && cif->rtype != &ffi_type_void)
     success = ImplicitConvert(cx, rval, fninfo->mReturnType, result, false,
-                              NULL);
+                              nullptr);
 
   if (!success) {
     // Something failed. The callee may have thrown, or it may not have
     // returned a value that ImplicitConvert() was happy with. Depending on how
     // prudent the consumer has been, we may or may not have a recovery plan.
 
     // In any case, a JS exception cannot be passed to C code, so report the
     // exception if any and clear it from the cx.
@@ -6231,17 +6231,18 @@ CClosure::ClosureStub(ffi_cif* cif, void
 //
 // * If an object 'refObj' is supplied, the new CData object stores the
 //   referent object in a reserved slot for GC safety, such that 'refObj' will
 //   be held alive by the resulting CData object. 'refObj' may or may not be
 //   a CData object; merely an object we want to keep alive.
 //   * If 'refObj' is a CData object, 'ownResult' must be false.
 //   * Otherwise, 'refObj' is a Library or CClosure object, and 'ownResult'
 //     may be true or false.
-// * Otherwise 'refObj' is NULL. In this case, 'ownResult' may be true or false.
+// * Otherwise 'refObj' is nullptr. In this case, 'ownResult' may be true or
+//   false.
 //
 // * If 'ownResult' is true, the CData object will allocate an appropriately
 //   sized buffer, and free it upon finalization. If 'source' data is
 //   supplied, the data will be copied from 'source' into the buffer;
 //   otherwise, the entirety of the new buffer will be initialized to zero.
 // * If 'ownResult' is false, the new CData's buffer refers to a slice of
 //   another buffer kept alive by 'refObj'. 'source' data must be provided,
 //   and the new CData's buffer will refer to 'source'.
@@ -6263,48 +6264,48 @@ CData::Create(JSContext* cx,
   JS_ASSERT(!JSVAL_IS_PRIMITIVE(slot));
 
   RootedObject proto(cx, JSVAL_TO_OBJECT(slot));
   RootedObject parent(cx, JS_GetParent(typeObj));
   JS_ASSERT(parent);
 
   RootedObject dataObj(cx, JS_NewObject(cx, &sCDataClass, proto, parent));
   if (!dataObj)
-    return NULL;
+    return nullptr;
 
   // set the CData's associated type
   JS_SetReservedSlot(dataObj, SLOT_CTYPE, OBJECT_TO_JSVAL(typeObj));
 
   // Stash the referent object, if any, for GC safety.
   if (refObj)
     JS_SetReservedSlot(dataObj, SLOT_REFERENT, OBJECT_TO_JSVAL(refObj));
 
   // Set our ownership flag.
   JS_SetReservedSlot(dataObj, SLOT_OWNS, BOOLEAN_TO_JSVAL(ownResult));
 
   // attach the buffer. since it might not be 2-byte aligned, we need to
   // allocate an aligned space for it and store it there. :(
   char** buffer = cx->new_<char*>();
   if (!buffer) {
     JS_ReportOutOfMemory(cx);
-    return NULL;
+    return nullptr;
   }
 
   char* data;
   if (!ownResult) {
     data = static_cast<char*>(source);
   } else {
     // Initialize our own buffer.
     size_t size = CType::GetSize(typeObj);
     data = (char*)cx->malloc_(size);
     if (!data) {
       // Report a catchable allocation error.
       JS_ReportAllocationOverflow(cx);
       js_free(buffer);
-      return NULL;
+      return nullptr;
     }
 
     if (!source)
       memset(data, 0, size);
     else
       memcpy(data, source, size);
   }
 
@@ -6389,17 +6390,17 @@ CData::ValueGetter(JSContext* cx, Handle
 bool
 CData::ValueSetter(JSContext* cx, HandleObject obj, HandleId idval, bool strict, MutableHandleValue vp)
 {
   if (!IsCData(obj)) {
     JS_ReportError(cx, "not a CData");
     return false;
   }
 
-  return ImplicitConvert(cx, vp, GetCType(obj), GetData(obj), false, NULL);
+  return ImplicitConvert(cx, vp, GetCType(obj), GetData(obj), false, nullptr);
 }
 
 bool
 CData::Address(JSContext* cx, unsigned argc, jsval* vp)
 {
   CallArgs args = CallArgsFromVp(argc, vp);
   if (args.length() != 0) {
     JS_ReportError(cx, "address takes zero arguments");
@@ -6415,17 +6416,17 @@ CData::Address(JSContext* cx, unsigned a
   }
 
   RootedObject typeObj(cx, CData::GetCType(obj));
   RootedObject pointerType(cx, PointerType::CreateInternal(cx, typeObj));
   if (!pointerType)
     return false;
 
   // Create a PointerType CData object containing null.
-  JSObject* result = CData::Create(cx, pointerType, NullPtr(), NULL, true);
+  JSObject* result = CData::Create(cx, pointerType, NullPtr(), nullptr, true);
   if (!result)
     return false;
 
   args.rval().setObject(*result);
 
   // Manually set the pointer inside the object, so we skip the conversion step.
   void** data = static_cast<void**>(GetData(result));
   *data = GetData(obj);
@@ -6530,17 +6531,17 @@ ReadStringCommon(JSContext* cx, InflateU
   JSObject* typeObj = CData::GetCType(obj);
   TypeCode typeCode = CType::GetTypeCode(typeObj);
   void* data;
   size_t maxLength = -1;
   switch (typeCode) {
   case TYPE_pointer:
     baseType = PointerType::GetBaseType(typeObj);
     data = *static_cast<void**>(CData::GetData(obj));
-    if (data == NULL) {
+    if (data == nullptr) {
       JS_ReportError(cx, "cannot read contents of null pointer");
       return false;
     }
     break;
   case TYPE_array:
     baseType = ArrayType::GetBaseType(typeObj);
     data = CData::GetData(obj);
     maxLength = ArrayType::GetLength(typeObj);
@@ -6613,17 +6614,17 @@ CData::GetSourceString(JSContext *cx, Ha
   // 't.ptr' for pointers;
   // 't.array([n])' for arrays;
   // 'n' for structs, where n = t.name, the struct's name. (We assume this is
   // bound to a variable in the current scope.)
   AutoString source;
   BuildTypeSource(cx, typeObj, true, source);
   AppendString(source, "(");
   if (!BuildDataSource(cx, typeObj, data, false, source))
-    return NULL;
+    return nullptr;
 
   AppendString(source, ")");
 
   return NewUCString(cx, source);
 }
 
 bool
 CData::ToSource(JSContext* cx, unsigned argc, jsval* vp)
@@ -6787,40 +6788,40 @@ CDataFinalizer::IsCDataFinalizer(JSObjec
 JSObject *
 CDataFinalizer::GetCType(JSContext *cx, JSObject *obj)
 {
   MOZ_ASSERT(IsCDataFinalizer(obj));
 
   jsval valData = JS_GetReservedSlot(obj,
                                      SLOT_DATAFINALIZER_VALTYPE);
   if (JSVAL_IS_VOID(valData)) {
-    return NULL;
+    return nullptr;
   }
 
   return JSVAL_TO_OBJECT(valData);
 }
 
 JSObject*
 CDataFinalizer::GetCData(JSContext *cx, JSObject *obj)
 {
   if (!obj) {
     JS_ReportError(cx, "No C data");
-    return NULL;
+    return nullptr;
   }
   if (CData::IsCData(obj)) {
     return obj;
   }
   if (!CDataFinalizer::IsCDataFinalizer(obj)) {
     JS_ReportError(cx, "Not C data");
-    return NULL;
+    return nullptr;
   }
   RootedValue val(cx);
   if (!CDataFinalizer::GetValue(cx, obj, val.address()) || JSVAL_IS_PRIMITIVE(val)) {
     JS_ReportError(cx, "Empty CDataFinalizer");
-    return NULL;
+    return nullptr;
   }
   return JSVAL_TO_OBJECT(val);
 }
 
 bool
 CDataFinalizer::GetValue(JSContext *cx, JSObject *obj, jsval *aResult)
 {
   MOZ_ASSERT(IsCDataFinalizer(obj));
@@ -6858,17 +6859,17 @@ CDataFinalizer::Construct(JSContext* cx,
   RootedObject objProto(cx);
   if (!GetObjectProperty(cx, objSelf, "prototype", &objProto)) {
     JS_ReportError(cx, "CDataFinalizer.prototype does not exist");
     return false;
   }
 
   // Get arguments
   if (args.length() == 0) { // Special case: the empty (already finalized) object
-    JSObject *objResult = JS_NewObject(cx, &sCDataFinalizerClass, objProto, NULL);
+    JSObject *objResult = JS_NewObject(cx, &sCDataFinalizerClass, objProto, nullptr);
     args.rval().setObject(*objResult);
     return true;
   }
 
   if (args.length() != 2) {
     JS_ReportError(cx, "CDataFinalizer takes 2 arguments");
     return false;
   }
@@ -6954,17 +6955,17 @@ CDataFinalizer::Construct(JSContext* cx,
   ScopedJSFreePtr<void> rvalue;
   if (CType::GetTypeCode(returnType) != TYPE_void_t) {
     rvalue = malloc(Align(CType::GetSize(returnType),
                           sizeof(ffi_arg)));
   } //Otherwise, simply do not allocate
 
   // 5. Create |objResult|
 
-  JSObject *objResult = JS_NewObject(cx, &sCDataFinalizerClass, objProto, NULL);
+  JSObject *objResult = JS_NewObject(cx, &sCDataFinalizerClass, objProto, nullptr);
   if (!objResult) {
     return false;
   }
 
   // If our argument is a CData, it holds a type.
   // This is the type that we should capture, not that
   // of the function, which may be less precise.
   JSObject *objBestArgType = objArgType;
@@ -7028,20 +7029,20 @@ CDataFinalizer::Construct(JSContext* cx,
  * Actually call the finalizer. Does not perform any cleanup on the object.
  *
  * Preconditions: |this| must be a |CDataFinalizer|, |p| must be non-null.
  * The function fails if |this| has gone through |Forget|/|Dispose|
  * or |Finalize|.
  *
  * This function does not alter the value of |errno|/|GetLastError|.
  *
- * If argument |errnoStatus| is non-NULL, it receives the value of |errno|
+ * If argument |errnoStatus| is non-nullptr, it receives the value of |errno|
  * immediately after the call. Under Windows, if argument |lastErrorStatus|
- * is non-NULL, it receives the value of |GetLastError| immediately after the
- * call. On other platforms, |lastErrorStatus| is ignored.
+ * is non-nullptr, it receives the value of |GetLastError| immediately after
+ * the call. On other platforms, |lastErrorStatus| is ignored.
  */
 void
 CDataFinalizer::CallFinalizer(CDataFinalizer::Private *p,
                               int* errnoStatus,
                               int32_t* lastErrorStatus)
 {
   int savedErrno = errno;
   errno = 0;
@@ -7163,17 +7164,17 @@ CDataFinalizer::Methods::Dispose(JSConte
   RootedObject resultType(cx, FunctionType::GetFunctionInfo(objCodeType)->mReturnType);
   RootedValue result(cx, JSVAL_VOID);
 
   int errnoStatus;
 #if defined(XP_WIN)
   int32_t lastErrorStatus;
   CDataFinalizer::CallFinalizer(p, &errnoStatus, &lastErrorStatus);
 #else
-  CDataFinalizer::CallFinalizer(p, &errnoStatus, NULL);
+  CDataFinalizer::CallFinalizer(p, &errnoStatus, nullptr);
 #endif // defined(XP_WIN)
 
   JS_SetReservedSlot(objCTypes, SLOT_ERRNO, INT_TO_JSVAL(errnoStatus));
 #if defined(XP_WIN)
   JS_SetReservedSlot(objCTypes, SLOT_LASTERROR, INT_TO_JSVAL(lastErrorStatus));
 #endif // defined(XP_WIN)
 
   if (ConvertToJS(cx, resultType, NullPtr(), p->rvalue, false, true, result.address())) {
@@ -7200,30 +7201,30 @@ CDataFinalizer::Finalize(JSFreeOp* fop, 
 {
   CDataFinalizer::Private *p = (CDataFinalizer::Private *)
     JS_GetPrivate(obj);
 
   if (!p) {
     return;
   }
 
-  CDataFinalizer::CallFinalizer(p, NULL, NULL);
-  CDataFinalizer::Cleanup(p, NULL);
+  CDataFinalizer::CallFinalizer(p, nullptr, nullptr);
+  CDataFinalizer::Cleanup(p, nullptr);
 }
 
 /*
  * Perform cleanup of a CDataFinalizer
  *
  * Release strong references, cleanup |Private|.
  *
- * Argument |p| contains the private information of the CDataFinalizer. If NULL,
- * this function does nothing.
- * Argument |obj| should contain |NULL| during finalization (or in any context
- * in which the object itself should not be cleaned up), or a CDataFinalizer
- * object otherwise.
+ * Argument |p| contains the private information of the CDataFinalizer. If
+ * nullptr, this function does nothing.
+ * Argument |obj| should contain |nullptr| during finalization (or in any
+ * context in which the object itself should not be cleaned up), or a
+ * CDataFinalizer object otherwise.
  */
 void
 CDataFinalizer::Cleanup(CDataFinalizer::Private *p, JSObject *obj)
 {
   if (!p) {
     return;  // We have already cleaned up
   }
 
@@ -7232,17 +7233,17 @@ CDataFinalizer::Cleanup(CDataFinalizer::
   free(p);
 
   if (!obj) {
     return;  // No slots to clean up
   }
 
   JS_ASSERT(CDataFinalizer::IsCDataFinalizer(obj));
 
-  JS_SetPrivate(obj, NULL);
+  JS_SetPrivate(obj, nullptr);
   for (int i = 0; i < CDATAFINALIZER_SLOTS; ++i) {
     JS_SetReservedSlot(obj, i, JSVAL_NULL);
   }
 }
 
 
 /*******************************************************************************
 ** Int64 and UInt64 implementation
@@ -7253,29 +7254,29 @@ Int64Base::Construct(JSContext* cx,
                      HandleObject proto,
                      uint64_t data,
                      bool isUnsigned)
 {
   const JSClass* clasp = isUnsigned ? &sUInt64Class : &sInt64Class;
   RootedObject parent(cx, JS_GetParent(proto));
   RootedObject result(cx, JS_NewObject(cx, clasp, proto, parent));
   if (!result)
-    return NULL;
+    return nullptr;
 
   // attach the Int64's data
   uint64_t* buffer = cx->new_<uint64_t>(data);
   if (!buffer) {
     JS_ReportOutOfMemory(cx);
-    return NULL;
+    return nullptr;
   }
 
   JS_SetReservedSlot(result, SLOT_INT64, PRIVATE_TO_JSVAL(buffer));
 
   if (!JS_FreezeObject(cx, result))
-    return NULL;
+    return nullptr;
 
   return result;
 }
 
 void
 Int64Base::Finalize(JSFreeOp *fop, JSObject* obj)
 {
   jsval slot = JS_GetReservedSlot(obj, SLOT_INT64);
--- a/js/src/ctypes/CTypes.h
+++ b/js/src/ctypes/CTypes.h
@@ -22,30 +22,30 @@ namespace ctypes {
 // Class that takes ownership of a pointer T*, and calls cx->delete_() or
 // cx->array_delete() upon destruction.
 template<class T>
 class AutoPtr {
 private:
   typedef AutoPtr<T> self_type;
 
 public:
-  AutoPtr() : mPtr(NULL) { }
+  AutoPtr() : mPtr(nullptr) { }
   explicit AutoPtr(T* ptr) : mPtr(ptr) { }
   ~AutoPtr() { js_delete(mPtr); }
 
   T*   operator->()         { return mPtr; }
-  bool operator!()          { return mPtr == NULL; }
+  bool operator!()          { return mPtr == nullptr; }
   T&   operator[](size_t i) { return *(mPtr + i); }
   // Note: we cannot safely provide an 'operator T*()', since this would allow
   // the compiler to perform implicit conversion from one AutoPtr to another
   // via the constructor AutoPtr(T*).
 
   T*   get()         { return mPtr; }
-  void set(T* other) { JS_ASSERT(mPtr == NULL); mPtr = other; }
-  T*   forget()      { T* result = mPtr; mPtr = NULL; return result; }
+  void set(T* other) { JS_ASSERT(mPtr == nullptr); mPtr = other; }
+  T*   forget()      { T* result = mPtr; mPtr = nullptr; return result; }
 
   self_type& operator=(T* rhs) { mPtr = rhs; return *this; }
 
 private:
   // Do not allow copy construction or assignment from another AutoPtr.
   AutoPtr(AutoPtr<T>&);
   self_type& operator=(AutoPtr<T>& rhs);
 
@@ -86,33 +86,33 @@ AppendString(Vector<T, N, AP> &v, Vector
   v.append(w.begin(), w.length());
 }
 
 template <size_t N, class AP>
 void
 AppendString(Vector<jschar, N, AP> &v, JSString* str)
 {
   JS_ASSERT(str);
-  const jschar *chars = str->getChars(NULL);
+  const jschar *chars = str->getChars(nullptr);
   if (!chars)
     return;
   v.append(chars, str->length());
 }
 
 template <size_t N, class AP>
 void
 AppendString(Vector<char, N, AP> &v, JSString* str)
 {
   JS_ASSERT(str);
   size_t vlen = v.length();
   size_t alen = str->length();
   if (!v.resize(vlen + alen))
     return;
 
-  const jschar *chars = str->getChars(NULL);
+  const jschar *chars = str->getChars(nullptr);
   if (!chars)
     return;
 
   for (size_t i = 0; i < alen; ++i)
     v[i + vlen] = char(chars[i]);
 }
 
 template <class T, size_t N, class AP, size_t ArrayLength>
@@ -138,17 +138,17 @@ void
 PrependString(Vector<jschar, N, AP> &v, JSString* str)
 {
   JS_ASSERT(str);
   size_t vlen = v.length();
   size_t alen = str->length();
   if (!v.resize(vlen + alen))
     return;
 
-  const jschar *chars = str->getChars(NULL);
+  const jschar *chars = str->getChars(nullptr);
   if (!chars)
     return;
 
   // Move vector data forward. This is safe since we've already resized.
   memmove(v.begin() + alen, v.begin(), vlen * sizeof(jschar));
 
   // Copy data to insert.
   memcpy(v.begin(), chars, alen * sizeof(jschar));
@@ -282,21 +282,21 @@ struct ClosureInfo
   JS::Heap<JSObject*> closureObj;  // CClosure object
   JS::Heap<JSObject*> typeObj;     // FunctionType describing the C function
   JS::Heap<JSObject*> thisObj;     // 'this' object to use for the JS function call
   JS::Heap<JSObject*> jsfnObj;     // JS function
   void* errResult;                 // Result that will be returned if the closure throws
   ffi_closure* closure;            // The C closure itself
 
   // Anything conditionally freed in the destructor should be initialized to
-  // NULL here.
+  // nullptr here.
   ClosureInfo(JSRuntime* runtime)
     : rt(runtime)
-    , errResult(NULL)
-    , closure(NULL)
+    , errResult(nullptr)
+    , closure(nullptr)
   {}
 
   ~ClosureInfo() {
     if (closure)
       ffi_closure_free(closure);
     js_free(errResult);
   }
 };
--- a/js/src/ctypes/Library.cpp
+++ b/js/src/ctypes/Library.cpp
@@ -53,17 +53,17 @@ bool
 Library::Name(JSContext* cx, unsigned argc, jsval *vp)
 {
   if (argc != 1) {
     JS_ReportError(cx, "libraryName takes one argument");
     return false;
   }
 
   jsval arg = JS_ARGV(cx, vp)[0];
-  JSString* str = NULL;
+  JSString* str = nullptr;
   if (JSVAL_IS_STRING(arg)) {
     str = JSVAL_TO_STRING(arg);
   }
   else {
     JS_ReportError(cx, "name argument must be a string");
       return false;
   }
 
@@ -80,66 +80,67 @@ Library::Name(JSContext* cx, unsigned ar
   JS_SET_RVAL(cx, vp, STR