Merge m-c to fx-team.
authorRyan VanderMeulen <ryanvm@gmail.com>
Mon, 20 May 2013 16:22:54 -0400
changeset 132457 4ac6c72b06c838aaabe8c8cb6c0a69047d23fc54
parent 132456 bbc2b4a574557c7180b18841d9df11cf9337d20f (current diff)
parent 132424 4236b11635084000d9921be88d4c45d53979bf5a (diff)
child 132458 24c7abacfd423ea281d1126e5f7c33215452fea5
child 132485 4bbefbb00abcc61787b81c3fc8a27b308902007d
child 132494 e353f92a63bd8ecac1ab86a4c82473730ea2ba07
child 155353 2c3ed93031c9ccba6903ef0569d0989156b40e99
push id28286
push userryanvm@gmail.com
push dateTue, 21 May 2013 02:28:38 +0000
treeherdermozilla-inbound@24c7abacfd42 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone24.0a1
first release with
nightly linux32
4ac6c72b06c8 / 24.0a1 / 20130521031106 / files
nightly linux64
4ac6c72b06c8 / 24.0a1 / 20130521031106 / files
nightly mac
4ac6c72b06c8 / 24.0a1 / 20130521031106 / files
nightly win32
4ac6c72b06c8 / 24.0a1 / 20130521031106 / files
nightly win64
4ac6c72b06c8 / 24.0a1 / 20130521031106 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge m-c to fx-team.
accessible/public/nsIAccessibleCursorable.idl
layout/reftests/font-features/font-variant-features.css
--- a/CLOBBER
+++ b/CLOBBER
@@ -12,12 +12,12 @@
 #          O               O
 #          |               |
 #          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 848530 - Added a dependency file for moz.build traversal.
+Landing bug 865806
 
 Alternative to clobber is to run ./config.status from the objdir and to
 touch the CLOBBER file in the objdir.
--- a/Makefile.in
+++ b/Makefile.in
@@ -72,21 +72,17 @@ export::
 	$(RM) -r $(DIST)/sdk
 	$(MAKE) -C config export
 	$(MAKE) tier_nspr
 
 backend.RecursiveMakeBackend.built:
 	@echo "Updating build backend because of moz.build changes."
 	@$(PYTHON) ./config.status
 
-ifdef .PYMAKE
-includedeps backend.RecursiveMakeBackend.built.pp
-else
 include backend.RecursiveMakeBackend.built.pp
-endif
 
 export MOZBUILD_BACKEND_CHECKED=1
 
 ifdef ENABLE_TESTS
 # Additional makefile targets to call automated test suites
 include $(topsrcdir)/testing/testsuite-targets.mk
 endif
 
--- a/accessible/public/ia2/Makefile.in
+++ b/accessible/public/ia2/Makefile.in
@@ -21,28 +21,32 @@ GARBAGE       += $(MIDL_GENERATED_FILES)
 FORCE_SHARED_LIB = 1
 
 SRCS_IN_OBJDIR   = 1
 
 # Please keep this list in sync with the moz.build file until the rest of this
 # Makefile is ported over.
 MIDL_INTERFACES = \
   Accessible2.idl \
+  Accessible2_2.idl \
   AccessibleAction.idl \
   AccessibleApplication.idl \
   AccessibleComponent.idl \
+  AccessibleDocument.idl \
   AccessibleEditableText.idl \
   AccessibleHyperlink.idl \
   AccessibleHypertext.idl \
+  AccessibleHypertext2.idl \
   AccessibleImage.idl \
   AccessibleRelation.idl \
   AccessibleTable.idl \
   AccessibleTable2.idl \
   AccessibleTableCell.idl \
   AccessibleText.idl \
+  AccessibleText2.idl \
   AccessibleValue.idl \
   $(NULL)
 
 # Please keep this list in sync with the moz.build file until the rest of this
 # Makefile is ported over.
 MIDL_ENUMS = \
   AccessibleEventId.idl \
   AccessibleRole.idl \
--- a/accessible/public/ia2/moz.build
+++ b/accessible/public/ia2/moz.build
@@ -5,28 +5,32 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 MODULE = 'accessibility'
 
 # Please keep this list in sync with the Makefile.in until the rest of that file
 # is ported over.
 midl_interfaces = [
     'Accessible2',
+    'Accessible2_2',
     'AccessibleAction',
     'AccessibleApplication',
     'AccessibleComponent',
+    'AccessibleDocument',
     'AccessibleEditableText',
     'AccessibleHyperlink',
     'AccessibleHypertext',
+    'AccessibleHypertext2',
     'AccessibleImage',
     'AccessibleRelation',
     'AccessibleTable',
     'AccessibleTable2',
     'AccessibleTableCell',
     'AccessibleText',
+    'AccessibleText2',
     'AccessibleValue',
 ]
 
 # Please keep this list in sync with the Makefile.in until the rest of that file
 # is ported over.
 midl_enums = [
     'AccessibleEventId',
     'AccessibleRole',
--- a/accessible/public/moz.build
+++ b/accessible/public/moz.build
@@ -6,17 +6,16 @@
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
     DIRS += ['msaa', 'ia2']
 
 XPIDL_SOURCES += [
     'nsIAccessible.idl',
     'nsIAccessibleApplication.idl',
     'nsIAccessibleCaretMoveEvent.idl',
-    'nsIAccessibleCursorable.idl',
     'nsIAccessibleDocument.idl',
     'nsIAccessibleEditableText.idl',
     'nsIAccessibleEvent.idl',
     'nsIAccessibleHideEvent.idl',
     'nsIAccessibleHyperLink.idl',
     'nsIAccessibleHyperText.idl',
     'nsIAccessibleImage.idl',
     'nsIAccessiblePivot.idl',
deleted file mode 100644
--- a/accessible/public/nsIAccessibleCursorable.idl
+++ /dev/null
@@ -1,26 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; 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 "nsISupports.idl"
-
-interface nsIAccessiblePivot;
-
-/**
- * An interface implemented by an accessible object that has an associated
- * virtual cursor. Typically, a top-level application or content document.
- * A virtual cursor is an implementation of nsIAccessiblePivot that provides an
- * exclusive spot in the cursorable's subtree, this could be used to create a
- * pseudo-focus or caret browsing experience that is centered around the
- * accessibility API.
- */
-[scriptable, uuid(5452dea5-d235-496f-8757-3ca016ff49ff)]
-interface nsIAccessibleCursorable : nsISupports
-{
-  /**
-   * The virtual cursor pivot this object manages.
-   */
-  readonly attribute nsIAccessiblePivot virtualCursor;
-};
--- a/accessible/public/nsIAccessibleDocument.idl
+++ b/accessible/public/nsIAccessibleDocument.idl
@@ -1,32 +1,33 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 
 interface nsIAccessible;
+interface nsIAccessiblePivot;
 interface nsIDOMDocument;
 interface nsIDOMNode;
 interface nsIDOMWindow;
 
 /**
  * An interface for in-process accessibility clients
  * that wish to retrieve information about a document.
  * When accessibility is turned on in Gecko,
  * there is an nsIAccessibleDocument for each document
  * whether it is XUL, HTML or whatever.
  * You can QueryInterface to nsIAccessibleDocument from the nsIAccessible for
  * the root node of a document. You can also get one from 
  * nsIAccessible::GetAccessibleDocument() or 
  * nsIAccessibleEvent::GetAccessibleDocument()
  */
-[scriptable, uuid(451242bd-8a0c-4198-ae88-c053609a4e5d)]
+[scriptable, uuid(fe5b3886-2b6a-491a-80cd-a3e6342c451d)]
 interface nsIAccessibleDocument : nsISupports
 {
   /**
    * The URL of the document
    */
   readonly attribute AString URL;
 
   /**
@@ -71,12 +72,17 @@ interface nsIAccessibleDocument : nsISup
   readonly attribute nsIAccessibleDocument parentDocument;
 
   /**
    * Return the count of child document accessibles.
    */
   readonly attribute unsigned long childDocumentCount;
 
   /**
+   * The virtual cursor pivot this document manages.
+   */
+  readonly attribute nsIAccessiblePivot virtualCursor;
+
+  /**
    * Return the child document accessible at the given index.
    */
   nsIAccessibleDocument getChildDocumentAt(in unsigned long index);
 };
--- a/accessible/src/generic/DocAccessible.cpp
+++ b/accessible/src/generic/DocAccessible.cpp
@@ -125,18 +125,16 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(DocAccessible)
   NS_INTERFACE_MAP_ENTRY(nsIAccessibleDocument)
   NS_INTERFACE_MAP_ENTRY(nsIDocumentObserver)
   NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
   NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
   NS_INTERFACE_MAP_ENTRY(nsIObserver)
   NS_INTERFACE_MAP_ENTRY(nsIAccessiblePivotObserver)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIAccessibleDocument)
-  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIAccessibleCursorable,
-                                     (mDocFlags & eCursorable))
     foundInterface = 0;
 
   nsresult status;
   if (!foundInterface) {
     // HTML document accessible must inherit from HyperTextAccessible to get
     // support text interfaces. XUL document accessible doesn't need this.
     // However at some point we may push <body> to implement the interfaces and
     // return DocAccessible to inherit from AccessibleWrap.
@@ -472,29 +470,25 @@ DocAccessible::GetChildDocumentAt(uint32
 
   if (IsDefunct())
     return NS_OK;
 
   NS_IF_ADDREF(*aDocument = GetChildDocumentAt(aIndex));
   return *aDocument ? NS_OK : NS_ERROR_INVALID_ARG;
 }
 
-// nsIAccessibleVirtualCursor method
 NS_IMETHODIMP
 DocAccessible::GetVirtualCursor(nsIAccessiblePivot** aVirtualCursor)
 {
   NS_ENSURE_ARG_POINTER(aVirtualCursor);
   *aVirtualCursor = nullptr;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
-  if (!(mDocFlags & eCursorable))
-    return NS_OK;
-
   if (!mVirtualCursor) {
     mVirtualCursor = new nsAccessiblePivot(this);
     mVirtualCursor->AddObserver(this);
   }
 
   NS_ADDREF(*aVirtualCursor = mVirtualCursor);
   return NS_OK;
 }
@@ -1460,20 +1454,16 @@ DocAccessible::NotifyOfLoading(bool aIsR
 }
 
 void
 DocAccessible::DoInitialUpdate()
 {
   if (nsCoreUtils::IsTabDocument(mDocumentNode))
     mDocFlags |= eTabDocument;
 
-  // We provide a virtual cursor if this is a root doc or if it's a tab doc.
-  if (!mDocumentNode->GetParentDocument() || (mDocFlags & eTabDocument))
-    mDocFlags |= eCursorable;
-
   mLoadState |= eTreeConstructed;
 
   // The content element may be changed before the initial update and then we
   // miss the notification (since content tree change notifications are ignored
   // prior to initial update). Make sure the content element is valid.
   nsIContent* contentElm = nsCoreUtils::GetRoleContent(mDocumentNode);
   if (mContent != contentElm) {
     mContent = contentElm;
--- a/accessible/src/generic/DocAccessible.h
+++ b/accessible/src/generic/DocAccessible.h
@@ -1,17 +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/. */
 
 #ifndef mozilla_a11y_DocAccessible_h__
 #define mozilla_a11y_DocAccessible_h__
 
-#include "nsIAccessibleCursorable.h"
 #include "nsIAccessibleDocument.h"
 #include "nsIAccessiblePivot.h"
 
 #include "AccEvent.h"
 #include "HyperTextAccessibleWrap.h"
 
 #include "nsClassHashtable.h"
 #include "nsDataHashtable.h"
@@ -40,28 +39,25 @@ template<class Class, class Arg>
 class TNotification;
 
 class DocAccessible : public HyperTextAccessibleWrap,
                       public nsIAccessibleDocument,
                       public nsIDocumentObserver,
                       public nsIObserver,
                       public nsIScrollPositionListener,
                       public nsSupportsWeakReference,
-                      public nsIAccessibleCursorable,
                       public nsIAccessiblePivotObserver
 {
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(DocAccessible, Accessible)
 
   NS_DECL_NSIACCESSIBLEDOCUMENT
 
   NS_DECL_NSIOBSERVER
 
-  NS_DECL_NSIACCESSIBLECURSORABLE
-
   NS_DECL_NSIACCESSIBLEPIVOTOBSERVER
 
 public:
 
   DocAccessible(nsIDocument* aDocument, nsIContent* aRootContent,
                 nsIPresShell* aPresShell);
   virtual ~DocAccessible();
 
@@ -487,21 +483,18 @@ protected:
 
   /**
    * State and property flags, kept by mDocFlags.
    */
   enum {
     // Whether scroll listeners were added.
     eScrollInitialized = 1 << 0,
 
-    // Whether we support nsIAccessibleCursorable.
-    eCursorable = 1 << 1,
-
     // Whether the document is a tab document.
-    eTabDocument = 1 << 2
+    eTabDocument = 1 << 1
   };
 
   /**
    * Cache of accessibles within this document accessible.
    */
   AccessibleHashtable mAccessibleCache;
   nsDataHashtable<nsPtrHashKey<const nsINode>, Accessible*>
     mNodeToAccessibleMap;
@@ -534,17 +527,17 @@ protected:
    * Keep the ARIA attribute old value that is initialized by
    * AttributeWillChange and used by AttributeChanged notifications.
    */
   nsIAtom* mARIAAttrOldValue;
 
   nsTArray<nsRefPtr<DocAccessible> > mChildDocuments;
 
   /**
-   * The virtual cursor of the document when it supports nsIAccessibleCursorable.
+   * The virtual cursor of the document.
    */
   nsRefPtr<nsAccessiblePivot> mVirtualCursor;
 
   /**
    * A storage class for pairing content with one of its relation attributes.
    */
   class AttrRelProvider
   {
--- a/accessible/tests/mochitest/pivot/test_virtualcursor.html
+++ b/accessible/tests/mochitest/pivot/test_virtualcursor.html
@@ -21,37 +21,27 @@
   <script type="application/javascript" src="../layout.js"></script>
 
   <script type="application/javascript">
     var gBrowserWnd = null;
     var gQueue = null;
 
     function doTest()
     {
-      var rootAcc = getRootAccessible(browserWindow().document);
-      try {
-        rootAcc.QueryInterface(nsIAccessibleCursorable);
-      } catch (e) {
-        ok(false, "Root accessible does not support nsIAccessibleCursorable");
-      }
-      var doc = currentTabDocument();
-      var docAcc = getAccessible(doc, [nsIAccessibleDocument,
-                                       nsIAccessibleCursorable]);
+      var rootAcc = getAccessible(browserDocument(), [nsIAccessibleDocument]);
+      ok(rootAcc.virtualCursor,
+         "root document does not have virtualCursor");
 
-      // Test that embedded documents don't have their own virtual cursor.
+      var doc = currentTabDocument();
+      var docAcc = getAccessible(doc, [nsIAccessibleDocument]);
+
+      // Test that embedded documents have their own virtual cursor.
       is(docAcc.childDocumentCount, 1, "Expecting one child document");
-      var childDoc = docAcc.getChildDocumentAt(0);
-      var supportsVC = true;
-      try {
-        childDoc.QueryInterface(nsIAccessibleCursorable);
-      } catch (e) {
-        supportsVC = false;
-      }
-
-      ok(!supportsVC, "no nsIAccessibleCursorable support in child document");
+      ok(docAcc.getChildDocumentAt(0).virtualCursor,
+         "child document does not have virtualCursor");
 
       gQueue = new eventQueue();
 
       gQueue.onFinish = function onFinish()
       {
         closeBrowserWindow();
       }
 
--- a/caps/include/nsScriptSecurityManager.h
+++ b/caps/include/nsScriptSecurityManager.h
@@ -378,20 +378,21 @@ private:
                       JSMutableHandleValue vp);
     
     // Decides, based on CSP, whether or not eval() and stuff can be executed.
     static JSBool
     ContentSecurityPolicyPermitsJSAction(JSContext *cx);
 
     // Returns null if a principal cannot be found; generally callers
     // should error out at that point.
-    static nsIPrincipal* doGetObjectPrincipal(JSObject *obj);
+    static nsIPrincipal* doGetObjectPrincipal(JS::Handle<JSObject*> obj);
 #ifdef DEBUG
     static nsIPrincipal*
-    old_doGetObjectPrincipal(JSObject *obj, bool aAllowShortCircuit = true);
+    old_doGetObjectPrincipal(JS::Handle<JSObject*> obj,
+                             bool aAllowShortCircuit = true);
 #endif
 
     // Returns null if a principal cannot be found.  Note that rv can be NS_OK
     // when this happens -- this means that there was no JS running.
     nsIPrincipal*
     doGetSubjectPrincipal(nsresult* rv);
     
     nsresult
--- a/caps/src/nsScriptSecurityManager.cpp
+++ b/caps/src/nsScriptSecurityManager.cpp
@@ -1628,17 +1628,17 @@ nsScriptSecurityManager::CheckFunctionAc
     if (!aTargetObj) {
         // We're done here
         return NS_OK;
     }
 
     /*
     ** Get origin of subject and object and compare.
     */
-    JSObject* obj = (JSObject*)aTargetObj;
+    JS::Rooted<JSObject*> obj(aCx, (JSObject*)aTargetObj);
     nsIPrincipal* object = doGetObjectPrincipal(obj);
 
     if (!object)
         return NS_ERROR_FAILURE;
 
     bool subsumes;
     rv = subject->Subsumes(object, &subsumes);
     if (NS_SUCCEEDED(rv) && !subsumes) {
@@ -2018,26 +2018,27 @@ nsScriptSecurityManager::GetSubjectPrinc
     JSPrincipals *principals = JS_GetCompartmentPrincipals(compartment);
     return nsJSPrincipals::get(principals);
 }
 
 NS_IMETHODIMP
 nsScriptSecurityManager::GetObjectPrincipal(JSContext *aCx, JSObject *aObj,
                                             nsIPrincipal **result)
 {
-    *result = doGetObjectPrincipal(aObj);
+    JS::Rooted<JSObject*> obj(aCx, aObj);
+    *result = doGetObjectPrincipal(obj);
     if (!*result)
         return NS_ERROR_FAILURE;
     NS_ADDREF(*result);
     return NS_OK;
 }
 
 // static
 nsIPrincipal*
-nsScriptSecurityManager::doGetObjectPrincipal(JSObject *aObj)
+nsScriptSecurityManager::doGetObjectPrincipal(JS::Handle<JSObject*> aObj)
 {
     JSCompartment *compartment = js::GetObjectCompartment(aObj);
     JSPrincipals *principals = JS_GetCompartmentPrincipals(compartment);
     nsIPrincipal *principal = nsJSPrincipals::get(principals);
 
     // We leave the old code in for a little while to make sure that pulling
     // object principals directly off the compartment always gives an equivalent
     // result (from a security perspective).
@@ -2047,24 +2048,25 @@ nsScriptSecurityManager::doGetObjectPrin
 #endif
 
     return principal;
 }
 
 #ifdef DEBUG
 // static
 nsIPrincipal*
-nsScriptSecurityManager::old_doGetObjectPrincipal(JSObject *aObj,
+nsScriptSecurityManager::old_doGetObjectPrincipal(JS::Handle<JSObject*> aObj,
                                                   bool aAllowShortCircuit)
 {
     NS_ASSERTION(aObj, "Bad call to doGetObjectPrincipal()!");
     nsIPrincipal* result = nullptr;
 
-    JS::RootedObject obj(sXPConnect->GetCurrentJSContext(), aObj);
-    JSObject* origObj = obj;
+    JSContext* cx = sXPConnect->GetCurrentJSContext();
+    JS::RootedObject obj(cx, aObj);
+    JS::RootedObject origObj(cx, obj);
     js::Class *jsClass = js::GetObjectClass(obj);
 
     // A common case seen in this code is that we enter this function
     // with obj being a Function object, whose parent is a Call
     // object. Neither of those have object principals, so we can skip
     // those objects here before we enter the below loop. That way we
     // avoid wasting time checking properties of their classes etc in
     // the loop.
@@ -2287,18 +2289,18 @@ nsScriptSecurityManager::CheckXPCPermiss
         {
             nsresult rv;
             if (!jsObject)
             {
                 nsCOMPtr<nsIXPConnectWrappedJS> xpcwrappedjs =
                     do_QueryInterface(aObj);
                 if (xpcwrappedjs)
                 {
-                    rv = xpcwrappedjs->GetJSObject(jsObject.address());
-                    NS_ENSURE_SUCCESS(rv, rv);
+                    jsObject = xpcwrappedjs->GetJSObject();
+                    NS_ENSURE_STATE(jsObject);
                 }
             }
 
             if (!aSubjectPrincipal)
             {
                 // No subject principal passed in. Compute it.
                 aSubjectPrincipal = GetSubjectPrincipal(cx, &rv);
                 NS_ENSURE_SUCCESS(rv, rv);
--- a/config/stl-headers
+++ b/config/stl-headers
@@ -13,16 +13,17 @@
 #
 
 new
 
 # FIXME: these headers haven't been reviewed yet, but we use them
 # unsafely in Gecko, so we might as well prevent them from
 # throwing exceptions
 algorithm
+atomic
 deque
 iostream
 iterator
 limits
 list
 map
 memory
 set
@@ -33,8 +34,9 @@ vector
 cassert
 climits
 cstdarg
 cstdio
 cstdlib
 cstring
 cwchar
 tuple
+xutility
--- a/content/base/public/nsIDOMDataChannel.idl
+++ b/content/base/public/nsIDOMDataChannel.idl
@@ -1,15 +1,26 @@
+/* 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 "domstubs.idl"
 
 #include "nsIDOMEventTarget.idl"
 
+%{C++
+#ifdef GetBinaryType
+// Windows apparently has a #define for GetBinaryType...
+#undef GetBinaryType
+#endif
+%}
+
 interface nsIVariant;
 
-[scriptable, builtinclass, uuid(1aed816d-1156-414e-8fe2-f01daa6021f0)]
+[scriptable, builtinclass, uuid(4410f28d-c9eb-481d-a47e-e7ef49f382c8)]
 interface nsIDOMDataChannel : nsIDOMEventTarget
 {
   readonly attribute DOMString label;
   readonly attribute DOMString protocol;
   readonly attribute boolean reliable;
   readonly attribute boolean ordered;
 
   readonly attribute DOMString readyState;
@@ -20,19 +31,9 @@ interface nsIDOMDataChannel : nsIDOMEven
   [implicit_jscontext] attribute jsval onopen;
   [implicit_jscontext] attribute jsval onerror;
   [implicit_jscontext] attribute jsval onclose;
   [implicit_jscontext] attribute jsval onmessage;
 
   attribute DOMString binaryType;
 
   void close();
-
-  /**
-   * Transmits data to other end of the connection.
-   * @param data The data to be transmitted.  Arraybuffers and Blobs are sent as
-   * binary data.  Strings are sent as UTF-8 text data.  Other types are
-   * converted to a String and sent as a String.
-   * @return if the connection is still established and the data was queued or
-   *         sent successfully.
-   */
-  void send(in nsIVariant data);
 };
--- a/content/base/src/moz.build
+++ b/content/base/src/moz.build
@@ -30,17 +30,20 @@ EXPORTS += [
     'nsScriptLoader.h',
     'nsStubDocumentObserver.h',
     'nsStubMutationObserver.h',
     'nsStyledElement.h',
     'nsTextFragment.h',
 ]
 
 if CONFIG['MOZ_WEBRTC']:
-    EXPORTS += ['nsDOMDataChannel.h']
+    EXPORTS += [
+        'nsDOMDataChannel.h',
+        'nsDOMDataChannelDeclarations.h',
+    ]
 
 EXPORTS.mozilla.dom += [
     'Attr.h',
     'Comment.h',
     'DOMImplementation.h',
     'DocumentFragment.h',
     'DocumentType.h',
     'EventSource.h',
--- a/content/base/src/nsDOMDataChannel.cpp
+++ b/content/base/src/nsDOMDataChannel.cpp
@@ -1,138 +1,78 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 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 "nsDOMDataChannel.h"
+
 #ifdef MOZ_LOGGING
 #define FORCE_PR_LOG
 #endif
 
 #include "base/basictypes.h"
 #include "prlog.h"
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* GetDataChannelLog();
 #endif
 #undef LOG
 #define LOG(args) PR_LOG(GetDataChannelLog(), PR_LOG_DEBUG, args)
 
 
-#include "nsDOMDataChannel.h"
+#include "nsDOMDataChannelDeclarations.h"
 #include "nsIDOMFile.h"
-#include "nsIJSNativeInitializer.h"
 #include "nsIDOMDataChannel.h"
 #include "nsIDOMMessageEvent.h"
-#include "nsDOMClassInfo.h"
 #include "nsDOMEventTargetHelper.h"
 
-#include "js/Value.h"
-
 #include "nsError.h"
 #include "nsAutoPtr.h"
 #include "nsContentUtils.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsIScriptObjectPrincipal.h"
-#include "nsJSUtils.h"
 #include "nsNetUtil.h"
 #include "nsDOMFile.h"
 
 #include "DataChannel.h"
 
-#ifdef GetBinaryType
-// Windows apparently has a #define for GetBinaryType...
-#undef GetBinaryType
-#endif
-
 using namespace mozilla;
-
-class nsDOMDataChannel : public nsDOMEventTargetHelper,
-                         public nsIDOMDataChannel,
-                         public mozilla::DataChannelListener
-{
-public:
-  nsDOMDataChannel(already_AddRefed<mozilla::DataChannel> aDataChannel)
-    : mDataChannel(aDataChannel)
-    , mBinaryType(DC_BINARY_TYPE_BLOB)
-  {}
-
-  ~nsDOMDataChannel()
-  {
-    // Don't call us anymore!  Likely isn't an issue (or maybe just less of
-    // one) once we block GC until all the (appropriate) onXxxx handlers
-    // are dropped. (See WebRTC spec)
-    LOG(("Close()ing %p", mDataChannel.get()));
-    mDataChannel->SetListener(nullptr, nullptr);
-    mDataChannel->Close();
-  }
-
-  nsresult Init(nsPIDOMWindow* aDOMWindow);
-
-  NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_NSIDOMDATACHANNEL
-
-  NS_REALLY_FORWARD_NSIDOMEVENTTARGET(nsDOMEventTargetHelper)
-
-  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMDataChannel,
-                                           nsDOMEventTargetHelper)
+using namespace mozilla::dom;
 
-  nsresult
-  DoOnMessageAvailable(const nsACString& aMessage, bool aBinary);
-
-  virtual nsresult
-  OnMessageAvailable(nsISupports* aContext, const nsACString& aMessage);
-
-  virtual nsresult
-  OnBinaryMessageAvailable(nsISupports* aContext, const nsACString& aMessage);
-
-  virtual nsresult OnSimpleEvent(nsISupports* aContext, const nsAString& aName);
-
-  virtual nsresult
-  OnChannelConnected(nsISupports* aContext);
-
-  virtual nsresult
-  OnChannelClosed(nsISupports* aContext);
+nsDOMDataChannel::~nsDOMDataChannel()
+{
+  // Don't call us anymore!  Likely isn't an issue (or maybe just less of
+  // one) once we block GC until all the (appropriate) onXxxx handlers
+  // are dropped. (See WebRTC spec)
+  LOG(("Close()ing %p", mDataChannel.get()));
+  mDataChannel->SetListener(nullptr, nullptr);
+  mDataChannel->Close();
+}
 
-  virtual void
-  AppReady();
-
-private:
-  // Get msg info out of JS variable being sent (string, arraybuffer, blob)
-  nsresult GetSendParams(nsIVariant *aData, nsCString &aStringOut,
-                         nsCOMPtr<nsIInputStream> &aStreamOut,
-                         bool &aIsBinary, uint32_t &aOutgoingLength);
-
-  // Owning reference
-  nsRefPtr<mozilla::DataChannel> mDataChannel;
-  nsString  mOrigin;
-  enum
-  {
-    DC_BINARY_TYPE_ARRAYBUFFER,
-    DC_BINARY_TYPE_BLOB,
-  } mBinaryType;
-};
-
-DOMCI_DATA(DataChannel, nsDOMDataChannel)
+/* virtual */ JSObject*
+nsDOMDataChannel::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
+{
+  return DataChannelBinding::Wrap(aCx, aScope, this);
+}
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsDOMDataChannel,
                                                   nsDOMEventTargetHelper)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsDOMDataChannel,
                                                 nsDOMEventTargetHelper)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_ADDREF_INHERITED(nsDOMDataChannel, nsDOMEventTargetHelper)
 NS_IMPL_RELEASE_INHERITED(nsDOMDataChannel, nsDOMEventTargetHelper)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMDataChannel)
   NS_INTERFACE_MAP_ENTRY(nsIDOMDataChannel)
-  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(DataChannel)
 NS_INTERFACE_MAP_END_INHERITING(nsDOMEventTargetHelper)
 
 nsresult
 nsDOMDataChannel::Init(nsPIDOMWindow* aDOMWindow)
 {
   nsresult rv;
   nsAutoString urlParam;
 
@@ -180,38 +120,63 @@ nsDOMDataChannel::GetLabel(nsAString& aL
 
 NS_IMETHODIMP
 nsDOMDataChannel::GetProtocol(nsAString& aProtocol)
 {
   mDataChannel->GetProtocol(aProtocol);
   return NS_OK;
 }
 
+uint16_t
+nsDOMDataChannel::Stream() const
+{
+  return mDataChannel->GetStream();
+}
+
 NS_IMETHODIMP
 nsDOMDataChannel::GetStream(uint16_t *aStream)
 {
-  mDataChannel->GetStream(aStream);
+  *aStream = Stream();
   return NS_OK;
 }
 
 // XXX should be GetType()?  Open question for the spec
+bool
+nsDOMDataChannel::Reliable() const
+{
+  return mDataChannel->GetType() == mozilla::DataChannelConnection::RELIABLE;
+}
+
 NS_IMETHODIMP
 nsDOMDataChannel::GetReliable(bool* aReliable)
 {
-  *aReliable = (mDataChannel->GetType() == mozilla::DataChannelConnection::RELIABLE);
+  *aReliable = Reliable();
   return NS_OK;
 }
 
+bool
+nsDOMDataChannel::Ordered() const
+{
+  return mDataChannel->GetOrdered();
+}
+
 NS_IMETHODIMP
 nsDOMDataChannel::GetOrdered(bool* aOrdered)
 {
-  *aOrdered = mDataChannel->GetOrdered();
+  *aOrdered = Ordered();
   return NS_OK;
 }
 
+RTCDataChannelState
+nsDOMDataChannel::ReadyState() const
+{
+  return static_cast<RTCDataChannelState>(mDataChannel->GetReadyState());
+}
+
+
 NS_IMETHODIMP
 nsDOMDataChannel::GetReadyState(nsAString& aReadyState)
 {
   uint16_t readyState = mDataChannel->GetReadyState();
   // From the WebRTC spec
   const char * stateName[] = {
     "connecting",
     "open",
@@ -220,20 +185,26 @@ nsDOMDataChannel::GetReadyState(nsAStrin
   };
   MOZ_ASSERT(/*readyState >= mozilla::DataChannel::CONNECTING && */ // Always true due to datatypes
              readyState <= mozilla::DataChannel::CLOSED);
   aReadyState.AssignASCII(stateName[readyState]);
 
   return NS_OK;
 }
 
+uint32_t
+nsDOMDataChannel::BufferedAmount() const
+{
+  return mDataChannel->GetBufferedAmount();
+}
+
 NS_IMETHODIMP
 nsDOMDataChannel::GetBufferedAmount(uint32_t* aBufferedAmount)
 {
-  *aBufferedAmount = mDataChannel->GetBufferedAmount();
+  *aBufferedAmount = BufferedAmount();
   return NS_OK;
 }
 
 NS_IMETHODIMP nsDOMDataChannel::GetBinaryType(nsAString & aBinaryType)
 {
   switch (mBinaryType) {
   case DC_BINARY_TYPE_ARRAYBUFFER:
     aBinaryType.AssignLiteral("arraybuffer");
@@ -262,130 +233,115 @@ nsDOMDataChannel::SetBinaryType(const ns
 
 NS_IMETHODIMP
 nsDOMDataChannel::Close()
 {
   mDataChannel->Close();
   return NS_OK;
 }
 
-// Almost a clone of nsWebSocketChannel::Send()
-NS_IMETHODIMP
-nsDOMDataChannel::Send(nsIVariant* aData)
+// All of the following is copy/pasted from WebSocket.cpp.
+void
+nsDOMDataChannel::Send(const nsAString& aData, ErrorResult& aRv)
+{
+  NS_ConvertUTF16toUTF8 msgString(aData);
+  Send(nullptr, msgString, msgString.Length(), false, aRv);
+}
+
+void
+nsDOMDataChannel::Send(nsIDOMBlob* aData, ErrorResult& aRv)
+{
+  NS_ABORT_IF_FALSE(NS_IsMainThread(), "Not running on main thread");
+
+  nsCOMPtr<nsIInputStream> msgStream;
+  nsresult rv = aData->GetInternalStream(getter_AddRefs(msgStream));
+  if (NS_FAILED(rv)) {
+    aRv.Throw(rv);
+    return;
+  }
+
+  uint64_t msgLength;
+  rv = aData->GetSize(&msgLength);
+  if (NS_FAILED(rv)) {
+    aRv.Throw(rv);
+    return;
+  }
+
+  if (msgLength > UINT32_MAX) {
+    aRv.Throw(NS_ERROR_FILE_TOO_BIG);
+    return;
+  }
+
+  Send(msgStream, EmptyCString(), msgLength, true, aRv);
+}
+
+void
+nsDOMDataChannel::Send(ArrayBuffer& aData, ErrorResult& aRv)
+{
+  NS_ABORT_IF_FALSE(NS_IsMainThread(), "Not running on main thread");
+
+  MOZ_ASSERT(sizeof(*aData.Data()) == 1);
+  uint32_t len = aData.Length();
+  char* data = reinterpret_cast<char*>(aData.Data());
+
+  nsDependentCSubstring msgString(data, len);
+  Send(nullptr, msgString, len, true, aRv);
+}
+
+void
+nsDOMDataChannel::Send(ArrayBufferView& aData, ErrorResult& aRv)
+{
+  NS_ABORT_IF_FALSE(NS_IsMainThread(), "Not running on main thread");
+
+  MOZ_ASSERT(sizeof(*aData.Data()) == 1);
+  uint32_t len = aData.Length();
+  char* data = reinterpret_cast<char*>(aData.Data());
+
+  nsDependentCSubstring msgString(data, len);
+  Send(nullptr, msgString, len, true, aRv);
+}
+
+void
+nsDOMDataChannel::Send(nsIInputStream* aMsgStream,
+                       const nsACString& aMsgString,
+                       uint32_t aMsgLength,
+                       bool aIsBinary,
+                       ErrorResult& aRv)
 {
   MOZ_ASSERT(NS_IsMainThread());
   uint16_t state = mDataChannel->GetReadyState();
 
   // In reality, the DataChannel protocol allows this, but we want it to
   // look like WebSockets
   if (state == mozilla::DataChannel::CONNECTING) {
-    return NS_ERROR_DOM_INVALID_STATE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
+    return;
   }
 
-  nsCString msgString;
-  nsCOMPtr<nsIInputStream> msgStream;
-  bool isBinary;
-  uint32_t msgLen;
-  nsresult rv = GetSendParams(aData, msgString, msgStream, isBinary, msgLen);
-  NS_ENSURE_SUCCESS(rv, rv);
-
   if (state == mozilla::DataChannel::CLOSING ||
       state == mozilla::DataChannel::CLOSED) {
-    return NS_OK;
+    return;
   }
 
   MOZ_ASSERT(state == mozilla::DataChannel::OPEN,
-             "Unknown state in nsWebSocket::Send");
+             "Unknown state in nsDOMDataChannel::Send");
 
   int32_t sent;
-  if (msgStream) {
-    sent = mDataChannel->SendBinaryStream(msgStream, msgLen);
+  if (aMsgStream) {
+    sent = mDataChannel->SendBinaryStream(aMsgStream, aMsgLength);
   } else {
-    if (isBinary) {
-      sent = mDataChannel->SendBinaryMsg(msgString);
+    if (aIsBinary) {
+      sent = mDataChannel->SendBinaryMsg(aMsgString);
     } else {
-      sent = mDataChannel->SendMsg(msgString);
+      sent = mDataChannel->SendMsg(aMsgString);
     }
   }
-  return sent >= 0 ? NS_OK : NS_ERROR_FAILURE;
-}
-
-// XXX Exact clone of nsWebSocketChannel::GetSendParams() - find a way to share!
-nsresult
-nsDOMDataChannel::GetSendParams(nsIVariant* aData, nsCString& aStringOut,
-                                nsCOMPtr<nsIInputStream>& aStreamOut,
-                                bool& aIsBinary, uint32_t& aOutgoingLength)
-{
-  // Get type of data (arraybuffer, blob, or string)
-  uint16_t dataType;
-  nsresult rv = aData->GetDataType(&dataType);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  if (dataType == nsIDataType::VTYPE_INTERFACE ||
-      dataType == nsIDataType::VTYPE_INTERFACE_IS) {
-    nsCOMPtr<nsISupports> supports;
-    nsID* iid;
-    rv = aData->GetAsInterface(&iid, getter_AddRefs(supports));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsMemory::Free(iid);
-
-    AutoSafeJSContext cx;
-    // ArrayBuffer?
-    JS::Rooted<JS::Value> realVal(cx);
-    JS::Rooted<JSObject*> obj(cx);
-    nsresult rv = aData->GetAsJSVal(realVal.address());
-    if (NS_SUCCEEDED(rv) && !JSVAL_IS_PRIMITIVE(realVal) &&
-        (obj = JSVAL_TO_OBJECT(realVal)) &&
-        (JS_IsArrayBufferObject(obj))) {
-      int32_t len = JS_GetArrayBufferByteLength(obj);
-      char* data = reinterpret_cast<char*>(JS_GetArrayBufferData(obj));
-
-      aStringOut.Assign(data, len);
-      aIsBinary = true;
-      aOutgoingLength = len;
-      return NS_OK;
-    }
-
-    // Blob?
-    nsCOMPtr<nsIDOMBlob> blob = do_QueryInterface(supports);
-    if (blob) {
-      rv = blob->GetInternalStream(getter_AddRefs(aStreamOut));
-      NS_ENSURE_SUCCESS(rv, rv);
-
-      // GetSize() should not perform blocking I/O (unlike Available())
-      uint64_t blobLen;
-      rv = blob->GetSize(&blobLen);
-      NS_ENSURE_SUCCESS(rv, rv);
-      if (blobLen > UINT32_MAX) {
-        return NS_ERROR_FILE_TOO_BIG;
-      }
-      aOutgoingLength = static_cast<uint32_t>(blobLen);
-
-      aIsBinary = true;
-      return NS_OK;
-    }
+  if (sent < 0) {
+    aRv.Throw(NS_ERROR_FAILURE);
   }
-
-  // Text message: if not already a string, turn it into one.
-  // TODO: bug 704444: Correctly coerce any JS type to string
-  //
-  PRUnichar* data = nullptr;
-  uint32_t len = 0;
-  rv = aData->GetAsWStringWithSize(&len, &data);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsString text;
-  text.Adopt(data, len);
-
-  CopyUTF16toUTF8(text, aStringOut);
-
-  aIsBinary = false;
-  aOutgoingLength = aStringOut.Length();
-  return NS_OK;
 }
 
 nsresult
 nsDOMDataChannel::DoOnMessageAvailable(const nsACString& aData,
                                        bool aBinary)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
--- a/content/base/src/nsDOMDataChannel.h
+++ b/content/base/src/nsDOMDataChannel.h
@@ -1,30 +1,110 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 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/. */
 
-#ifndef nsDOMDataChannel_h__
-#define nsDOMDataChannel_h__
+#ifndef nsDOMDataChannel_h
+#define nsDOMDataChannel_h
 
-// This defines only what's necessary to create nsDOMDataChannels, since this
-// gets used with MOZ_INTERNAL_API not set for media/webrtc/signaling/testing
-
-#include "nsCOMPtr.h"
+#include "mozilla/dom/DataChannelBinding.h"
+#include "mozilla/dom/TypedArray.h"
+#include "mozilla/net/DataChannel.h"
+#include "nsDOMEventTargetHelper.h"
 #include "nsIDOMDataChannel.h"
 
-namespace mozilla {
-   class DataChannel;
-}
+class nsDOMDataChannel : public nsDOMEventTargetHelper,
+                         public nsIDOMDataChannel,
+                         public mozilla::DataChannelListener
+{
+public:
+  nsDOMDataChannel(already_AddRefed<mozilla::DataChannel> aDataChannel)
+    : mDataChannel(aDataChannel)
+    , mBinaryType(DC_BINARY_TYPE_BLOB)
+  {
+    SetIsDOMBinding();
+  }
+
+  ~nsDOMDataChannel();
 
-class nsPIDOMWindow;
+  nsresult Init(nsPIDOMWindow* aDOMWindow);
+
+  NS_DECL_ISUPPORTS_INHERITED
+  NS_DECL_NSIDOMDATACHANNEL
+
+  NS_REALLY_FORWARD_NSIDOMEVENTTARGET(nsDOMEventTargetHelper)
+
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMDataChannel,
+                                           nsDOMEventTargetHelper)
+
+  virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
+    MOZ_OVERRIDE;
+  nsPIDOMWindow* GetParentObject() const
+  {
+    return GetOwner();
+  }
 
-nsresult
-NS_NewDOMDataChannel(already_AddRefed<mozilla::DataChannel> dataChannel,
-                     nsPIDOMWindow* aWindow,
-                     nsIDOMDataChannel** domDataChannel);
+  // WebIDL
+  // Uses XPIDL GetLabel.
+  bool Reliable() const;
+  mozilla::dom::RTCDataChannelState ReadyState() const;
+  uint32_t BufferedAmount() const;
+  IMPL_EVENT_HANDLER(open)
+  IMPL_EVENT_HANDLER(error)
+  IMPL_EVENT_HANDLER(close)
+  // Uses XPIDL Close.
+  IMPL_EVENT_HANDLER(message)
+  mozilla::dom::RTCDataChannelType BinaryType() const
+  {
+    return static_cast<mozilla::dom::RTCDataChannelType>(
+      static_cast<int>(mBinaryType));
+  }
+  void SetBinaryType(mozilla::dom::RTCDataChannelType aType)
+  {
+    mBinaryType = static_cast<DataChannelBinaryType>(
+      static_cast<int>(aType));
+  }
+  void Send(const nsAString& aData, mozilla::ErrorResult& aRv);
+  void Send(nsIDOMBlob* aData, mozilla::ErrorResult& aRv);
+  void Send(mozilla::dom::ArrayBuffer& aData, mozilla::ErrorResult& aRv);
+  void Send(mozilla::dom::ArrayBufferView& aData, mozilla::ErrorResult& aRv);
+
+  // Uses XPIDL GetProtocol.
+  bool Ordered() const;
+  uint16_t Stream() const;
+
+  nsresult
+  DoOnMessageAvailable(const nsACString& aMessage, bool aBinary);
 
-// Tell DataChannel it's ok to deliver open and message events
-void NS_DataChannelAppReady(nsIDOMDataChannel* domDataChannel);
+  virtual nsresult
+  OnMessageAvailable(nsISupports* aContext, const nsACString& aMessage);
+
+  virtual nsresult
+  OnBinaryMessageAvailable(nsISupports* aContext, const nsACString& aMessage);
+
+  virtual nsresult OnSimpleEvent(nsISupports* aContext, const nsAString& aName);
+
+  virtual nsresult
+  OnChannelConnected(nsISupports* aContext);
+
+  virtual nsresult
+  OnChannelClosed(nsISupports* aContext);
 
-#endif
+  virtual void
+  AppReady();
+
+private:
+  void Send(nsIInputStream* aMsgStream, const nsACString& aMsgString,
+            uint32_t aMsgLength, bool aIsBinary, mozilla::ErrorResult& aRv);
+
+  // Owning reference
+  nsRefPtr<mozilla::DataChannel> mDataChannel;
+  nsString  mOrigin;
+  enum DataChannelBinaryType {
+    DC_BINARY_TYPE_ARRAYBUFFER,
+    DC_BINARY_TYPE_BLOB,
+  };
+  DataChannelBinaryType mBinaryType;
+};
+
+#endif // nsDOMDataChannel_h
copy from content/base/src/nsDOMDataChannel.h
copy to content/base/src/nsDOMDataChannelDeclarations.h
--- a/content/base/src/nsDOMDataChannel.h
+++ b/content/base/src/nsDOMDataChannelDeclarations.h
@@ -1,16 +1,16 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 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/. */
 
-#ifndef nsDOMDataChannel_h__
-#define nsDOMDataChannel_h__
+#ifndef nsDOMDataChannelDeclarations_h
+#define nsDOMDataChannelDeclarations_h
 
 // This defines only what's necessary to create nsDOMDataChannels, since this
 // gets used with MOZ_INTERNAL_API not set for media/webrtc/signaling/testing
 
 #include "nsCOMPtr.h"
 #include "nsIDOMDataChannel.h"
 
 namespace mozilla {
@@ -22,9 +22,9 @@ class nsPIDOMWindow;
 nsresult
 NS_NewDOMDataChannel(already_AddRefed<mozilla::DataChannel> dataChannel,
                      nsPIDOMWindow* aWindow,
                      nsIDOMDataChannel** domDataChannel);
 
 // Tell DataChannel it's ok to deliver open and message events
 void NS_DataChannelAppReady(nsIDOMDataChannel* domDataChannel);
 
-#endif
+#endif // nsDOMDataChannelDeclarations_h
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -2199,17 +2199,17 @@ public:
 
       StructuredCloneData data;
       data.mData = mData.data();
       data.mDataLength = mData.nbytes();
       data.mClosure = mClosure;
 
       nsRefPtr<nsFrameMessageManager> mm = tabChild->GetInnerManager();
       mm->ReceiveMessage(static_cast<EventTarget*>(tabChild), mMessage,
-                         false, &data, nullptr, nullptr, nullptr);
+                         false, &data, JS::NullPtr(), nullptr, nullptr);
     }
     return NS_OK;
   }
   nsRefPtr<nsFrameLoader> mFrameLoader;
   nsString mMessage;
   JSAutoStructuredCloneBuffer mData;
   StructuredCloneClosure mClosure;
 };
--- a/content/base/src/nsFrameMessageManager.cpp
+++ b/content/base/src/nsFrameMessageManager.cpp
@@ -621,17 +621,17 @@ public:
 
 // nsIMessageListener
 
 nsresult
 nsFrameMessageManager::ReceiveMessage(nsISupports* aTarget,
                                       const nsAString& aMessage,
                                       bool aSync,
                                       const StructuredCloneData* aCloneData,
-                                      JSObject* aObjectsArray,
+                                      JS::Handle<JSObject*> aObjectsArray,
                                       InfallibleTArray<nsString>* aJSONRetVal,
                                       JSContext* aContext)
 {
   JSContext *cxToUse = mContext ? mContext
                                 : (aContext ? aContext
                                             : nsContentUtils::GetSafeJSContext());
   JS::Rooted<JSObject*> objectsArray(cxToUse, aObjectsArray);
   AutoPushJSContext ctx(cxToUse);
@@ -641,18 +641,17 @@ nsFrameMessageManager::ReceiveMessage(ns
 
     for (uint32_t i = 0; i < mListeners.Length(); ++i) {
       if (mListeners[i].mMessage == name) {
         nsCOMPtr<nsIXPConnectWrappedJS> wrappedJS =
           do_QueryInterface(mListeners[i].mListener);
         if (!wrappedJS) {
           continue;
         }
-        JS::Rooted<JSObject*> object(ctx);
-        wrappedJS->GetJSObject(object.address());
+        JS::Rooted<JSObject*> object(ctx, wrappedJS->GetJSObject());
         if (!object) {
           continue;
         }
         nsCxPusher pusher;
         pusher.Push(ctx);
 
         JSAutoRequest ar(ctx);
         JSAutoCompartment ac(ctx, object);
@@ -1004,18 +1003,17 @@ nsFrameScriptExecutor::LoadFrameScriptIn
 
   if (holder) {
     nsCxPusher pusher;
     pusher.Push(mCx);
     {
       // Need to scope JSAutoRequest to happen after Push but before Pop,
       // at least for now. See bug 584673.
       JSAutoRequest ar(mCx);
-      JS::Rooted<JSObject*> global(mCx);
-      mGlobal->GetJSObject(global.address());
+      JS::Rooted<JSObject*> global(mCx, mGlobal->GetJSObject());
       if (global) {
         (void) JS_ExecuteScript(mCx, global, holder->mScript, nullptr);
       }
     }
   }
 }
 
 void
@@ -1063,18 +1061,17 @@ nsFrameScriptExecutor::TryCacheLoadAndCo
 
   if (!dataString.IsEmpty()) {
     nsCxPusher pusher;
     pusher.Push(mCx);
     {
       // Need to scope JSAutoRequest to happen after Push but before Pop,
       // at least for now. See bug 584673.
       JSAutoRequest ar(mCx);
-      JS::Rooted<JSObject*> global(mCx);
-      mGlobal->GetJSObject(global.address());
+      JS::Rooted<JSObject*> global(mCx, mGlobal->GetJSObject());
       if (global) {
         JSAutoCompartment ac(mCx, global);
         JS::CompileOptions options(mCx);
         options.setNoScriptRval(true)
                .setFileAndLine(url.get(), 1)
                .setPrincipals(nsJSPrincipals::get(mPrincipal));
         JS::RootedObject empty(mCx, nullptr);
         JS::Rooted<JSScript*> script(mCx,
@@ -1133,19 +1130,18 @@ nsFrameScriptExecutor::InitTabChildGloba
   JS_SetContextPrivate(cx, aScope);
 
   nsresult rv =
     xpc->InitClassesWithNewWrappedGlobal(cx, aScope, mPrincipal,
                                          flags, JS::SystemZone, getter_AddRefs(mGlobal));
   NS_ENSURE_SUCCESS(rv, false);
 
 
-  JS::Rooted<JSObject*> global(cx);
-  rv = mGlobal->GetJSObject(global.address());
-  NS_ENSURE_SUCCESS(rv, false);
+  JS::Rooted<JSObject*> global(cx, mGlobal->GetJSObject());
+  NS_ENSURE_TRUE(global, false);
 
   JS_SetGlobalObject(cx, global);
 
   // Set the location information for the new global, so that tools like
   // about:memory may use that information.
   xpc::SetLocationForGlobal(global, aID);
 
   DidCreateCx();
@@ -1201,17 +1197,17 @@ public:
     if (nsFrameMessageManager::sChildProcessManager) {
       StructuredCloneData data;
       data.mData = mData.data();
       data.mDataLength = mData.nbytes();
       data.mClosure = mClosure;
 
       nsRefPtr<nsFrameMessageManager> ppm = nsFrameMessageManager::sChildProcessManager;
       ppm->ReceiveMessage(static_cast<nsIContentFrameMessageManager*>(ppm.get()), mMessage,
-                          false, &data, nullptr, nullptr, nullptr);
+                          false, &data, JS::NullPtr(), nullptr, nullptr);
     }
     return NS_OK;
   }
   nsString mMessage;
   JSAutoStructuredCloneBuffer mData;
   StructuredCloneClosure mClosure;
 };
 
@@ -1331,17 +1327,17 @@ public:
       StructuredCloneData data;
       data.mData = mData.data();
       data.mDataLength = mData.nbytes();
       data.mClosure = mClosure;
 
       nsRefPtr<nsFrameMessageManager> ppm =
         nsFrameMessageManager::sSameProcessParentManager;
       ppm->ReceiveMessage(static_cast<nsIContentFrameMessageManager*>(ppm.get()),
-                          mMessage, false, &data, nullptr, nullptr, nullptr);
+                          mMessage, false, &data, JS::NullPtr(), nullptr, nullptr);
      }
      return NS_OK;
   }
   nsString mMessage;
   JSAutoStructuredCloneBuffer mData;
   StructuredCloneClosure mClosure;
 };
 
@@ -1371,17 +1367,17 @@ public:
       for (uint32_t i = 0; i < len; ++i) {
         nsCOMPtr<nsIRunnable> async = asyncMessages[i];
         async->Run();
       }
     }
     if (nsFrameMessageManager::sSameProcessParentManager) {
       nsRefPtr<nsFrameMessageManager> ppm = nsFrameMessageManager::sSameProcessParentManager;
       ppm->ReceiveMessage(static_cast<nsIContentFrameMessageManager*>(ppm.get()), aMessage,
-                          true, &aData, nullptr, aJSONRetVal);
+                          true, &aData, JS::NullPtr(), aJSONRetVal);
     }
     return true;
   }
 
   virtual bool DoSendAsyncMessage(const nsAString& aMessage,
                                   const mozilla::dom::StructuredCloneData& aData)
   {
     if (!nsFrameMessageManager::sPendingSameProcessAsyncMessages) {
--- a/content/base/src/nsFrameMessageManager.h
+++ b/content/base/src/nsFrameMessageManager.h
@@ -177,17 +177,17 @@ public:
   NS_DECL_NSIFRAMESCRIPTLOADER
   NS_DECL_NSIPROCESSCHECKER
 
   static nsFrameMessageManager*
   NewProcessMessageManager(mozilla::dom::ContentParent* aProcess);
 
   nsresult ReceiveMessage(nsISupports* aTarget, const nsAString& aMessage,
                           bool aSync, const StructuredCloneData* aCloneData,
-                          JSObject* aObjectsArray,
+                          JS::Handle<JSObject*> aObjectsArray,
                           InfallibleTArray<nsString>* aJSONRetVal,
                           JSContext* aContext = nullptr);
 
   void AddChildManager(nsFrameMessageManager* aManager,
                        bool aLoadScripts = true);
   void RemoveChildManager(nsFrameMessageManager* aManager)
   {
     mChildManagers.RemoveObject(aManager);
--- a/content/base/src/nsInProcessTabChildGlobal.cpp
+++ b/content/base/src/nsInProcessTabChildGlobal.cpp
@@ -33,17 +33,18 @@ nsInProcessTabChildGlobal::DoSendSyncMes
   asyncMessages.SwapElements(mASyncMessages);
   uint32_t len = asyncMessages.Length();
   for (uint32_t i = 0; i < len; ++i) {
     nsCOMPtr<nsIRunnable> async = asyncMessages[i];
     async->Run();
   }
   if (mChromeMessageManager) {
     nsRefPtr<nsFrameMessageManager> mm = mChromeMessageManager;
-    mm->ReceiveMessage(mOwner, aMessage, true, &aData, nullptr, aJSONRetVal);
+    mm->ReceiveMessage(mOwner, aMessage, true, &aData, JS::NullPtr(),
+                       aJSONRetVal);
   }
   return true;
 }
 
 class nsAsyncMessageToParent : public nsRunnable
 {
 public:
   nsAsyncMessageToParent(nsInProcessTabChildGlobal* aTabChild,
@@ -68,17 +69,17 @@ public:
     if (mTabChild->mChromeMessageManager) {
       StructuredCloneData data;
       data.mData = mData.data();
       data.mDataLength = mData.nbytes();
       data.mClosure = mClosure;
 
       nsRefPtr<nsFrameMessageManager> mm = mTabChild->mChromeMessageManager;
       mm->ReceiveMessage(mTabChild->mOwner, mMessage, false, &data,
-                         nullptr, nullptr, nullptr);
+                         JS::NullPtr(), nullptr, nullptr);
     }
     return NS_OK;
   }
   nsRefPtr<nsInProcessTabChildGlobal> mTabChild;
   nsString mMessage;
   JSAutoStructuredCloneBuffer mData;
   StructuredCloneClosure mClosure;
   // True if this runnable has already been called. This can happen if DoSendSyncMessage
--- a/content/base/src/nsInProcessTabChildGlobal.h
+++ b/content/base/src/nsInProcessTabChildGlobal.h
@@ -116,20 +116,17 @@ public:
 
   void DelayedDisconnect();
 
   virtual JSObject* GetGlobalJSObject() {
     if (!mGlobal) {
       return nullptr;
     }
 
-    JSObject* global;
-    mGlobal->GetJSObject(&global);
-
-    return global;
+    return mGlobal->GetJSObject();
   }
 protected:
   nsresult Init();
   nsresult InitTabChildGlobal();
   nsCOMPtr<nsIContentFrameMessageManager> mMessageManager;
   nsCOMPtr<nsIDocShell> mDocShell;
   bool mInitialized;
   bool mLoadingScript;
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -4287,24 +4287,21 @@ WebGLContext::CompileShader(WebGLShader 
         compiler = ShConstructCompiler((ShShaderType) shader->ShaderType(),
                                        SH_WEBGL_SPEC,
                                        targetShaderSourceLanguage,
                                        &resources);
 
         int compileOptions = SH_ATTRIBUTES_UNIFORMS |
                              SH_ENFORCE_PACKING_RESTRICTIONS;
 
-        // we want to do this everywhere, but:
-//TODO: Enable on windows:
-#ifndef XP_WIN // to do this on Windows, we need ANGLE r1719, 1733, 1734.
-#ifndef XP_MACOSX // to do this on Mac, we need to do it only on Mac OSX > 10.6 as this
+        // We want to do this everywhere, but:
+#ifndef XP_MACOSX // To do this on Mac, we need to do it only on Mac OSX > 10.6 as this
                   // causes the shader compiler in 10.6 to crash
         compileOptions |= SH_CLAMP_INDIRECT_ARRAY_BOUNDS;
 #endif
-#endif
 
         if (useShaderSourceTranslation) {
             compileOptions |= SH_OBJECT_CODE
                             | SH_MAP_LONG_VARIABLE_NAMES;
 #ifdef XP_MACOSX
             if (gl->WorkAroundDriverBugs()) {
                 // Work around bug 665578 and bug 769810
                 if (gl->Vendor() == gl::GLContext::VendorATI) {
--- a/content/events/src/Touch.h
+++ b/content/events/src/Touch.h
@@ -1,22 +1,23 @@
 /* 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/. */
 
 #ifndef mozilla_dom_Touch_h
 #define mozilla_dom_Touch_h
 
-#include "nsDOMUIEvent.h"
 #include "nsIDOMTouchEvent.h"
 #include "nsString.h"
 #include "nsTArray.h"
 #include "mozilla/Attributes.h"
 #include "nsJSEnvironment.h"
+#include "nsWrapperCache.h"
+#include "mozilla/dom/EventTarget.h"
 
 namespace mozilla {
 namespace dom {
 
 class Touch MOZ_FINAL : public nsIDOMTouch
                       , public nsWrapperCache
 {
 public:
--- a/content/events/src/nsDOMEventTargetHelper.h
+++ b/content/events/src/nsDOMEventTargetHelper.h
@@ -160,17 +160,17 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsDOMEvent
 
 // WebIDL event handlers
 #define IMPL_EVENT_HANDLER(_event)                                        \
   inline mozilla::dom::EventHandlerNonNull* GetOn##_event()               \
   {                                                                       \
     return GetEventHandler(nsGkAtoms::on##_event);                        \
   }                                                                       \
   inline void SetOn##_event(mozilla::dom::EventHandlerNonNull* aCallback, \
-                            ErrorResult& aRv)                             \
+                            mozilla::ErrorResult& aRv)                    \
   {                                                                       \
     SetEventHandler(nsGkAtoms::on##_event, aCallback, aRv);               \
   }
 
 /* Use this macro to declare functions that forward the behavior of this
  * interface to another object.
  * This macro doesn't forward PreHandleEvent because sometimes subclasses
  * want to override it.
--- a/content/events/src/nsDOMKeyboardEvent.cpp
+++ b/content/events/src/nsDOMKeyboardEvent.cpp
@@ -1,15 +1,14 @@
 /* -*- 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 "nsDOMClassInfoID.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");
@@ -30,21 +29,18 @@ nsDOMKeyboardEvent::~nsDOMKeyboardEvent(
     delete static_cast<nsKeyEvent*>(mEvent);
     mEvent = nullptr;
   }
 }
 
 NS_IMPL_ADDREF_INHERITED(nsDOMKeyboardEvent, nsDOMUIEvent)
 NS_IMPL_RELEASE_INHERITED(nsDOMKeyboardEvent, nsDOMUIEvent)
 
-DOMCI_DATA(KeyboardEvent, nsDOMKeyboardEvent)
-
 NS_INTERFACE_MAP_BEGIN(nsDOMKeyboardEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMKeyEvent)
-  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(KeyboardEvent)
 NS_INTERFACE_MAP_END_INHERITING(nsDOMUIEvent)
 
 NS_IMETHODIMP
 nsDOMKeyboardEvent::GetAltKey(bool* aIsDown)
 {
   NS_ENSURE_ARG_POINTER(aIsDown);
   *aIsDown = AltKey();
   return NS_OK;
--- a/content/events/src/nsEventListenerService.cpp
+++ b/content/events/src/nsEventListenerService.cpp
@@ -79,18 +79,18 @@ NS_IMPL_ISUPPORTS1(nsEventListenerServic
 bool
 nsEventListenerInfo::GetJSVal(JSContext* aCx,
                               mozilla::Maybe<JSAutoCompartment>& aAc,
                               JS::Value* aJSVal)
 {
   *aJSVal = JSVAL_NULL;
   nsCOMPtr<nsIXPConnectWrappedJS> wrappedJS = do_QueryInterface(mListener);
   if (wrappedJS) {
-    JS::Rooted<JSObject*> object(aCx, nullptr);
-    if (NS_FAILED(wrappedJS->GetJSObject(object.address()))) {
+    JS::Rooted<JSObject*> object(aCx, wrappedJS->GetJSObject());
+    if (!object) {
       return false;
     }
     aAc.construct(aCx, object);
     *aJSVal = OBJECT_TO_JSVAL(object);
     return true;
   }
 
   nsCOMPtr<nsIJSEventListener> jsl = do_QueryInterface(mListener);
--- a/content/media/wmf/DXVA2Manager.cpp
+++ b/content/media/wmf/DXVA2Manager.cpp
@@ -21,18 +21,20 @@ class D3D9DXVA2Manager : public DXVA2Man
 public:
   D3D9DXVA2Manager();
   virtual ~D3D9DXVA2Manager();
 
   HRESULT Init();
 
   IUnknown* GetDXVADeviceManager() MOZ_OVERRIDE;
 
+  // Copies a region (aRegion) of the video frame stored in aVideoSample
+  // into an image which is returned by aOutImage.
   HRESULT CopyToImage(IMFSample* aVideoSample,
-                      const nsIntSize& aSize,
+                      const nsIntRect& aRegion,
                       ImageContainer* aContainer,
                       Image** aOutImage) MOZ_OVERRIDE;
 
 private:
   nsRefPtr<IDirect3D9Ex> mD3D9;
   nsRefPtr<IDirect3DDevice9Ex> mDevice;
   nsRefPtr<IDirect3DDeviceManager9> mDeviceManager;
   UINT32 mResetToken;
@@ -132,17 +134,17 @@ D3D9DXVA2Manager::Init()
   mDevice = device;
   mDeviceManager = deviceManager;
 
   return S_OK;
 }
 
 HRESULT
 D3D9DXVA2Manager::CopyToImage(IMFSample* aSample,
-                              const nsIntSize& aSize,
+                              const nsIntRect& aRegion,
                               ImageContainer* aImageContainer,
                               Image** aOutImage)
 {
   nsRefPtr<IMFMediaBuffer> buffer;
   HRESULT hr = aSample->GetBufferByIndex(0, getter_AddRefs(buffer));
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
 
   nsRefPtr<IDirect3DSurface9> surface;
@@ -154,17 +156,17 @@ D3D9DXVA2Manager::CopyToImage(IMFSample*
 
   ImageFormat format = D3D9_RGB32_TEXTURE;
   nsRefPtr<Image> image = aImageContainer->CreateImage(&format, 1);
   NS_ENSURE_TRUE(image, E_FAIL);
   NS_ASSERTION(image->GetFormat() == D3D9_RGB32_TEXTURE,
                "Wrong format?");
 
   D3D9SurfaceImage* videoImage = static_cast<D3D9SurfaceImage*>(image.get());
-  hr = videoImage->SetData(D3D9SurfaceImage::Data(surface, aSize));
+  hr = videoImage->SetData(D3D9SurfaceImage::Data(surface, aRegion));
 
   image.forget(aOutImage);
 
   return S_OK;
 }
 
 /* static */
 DXVA2Manager*
--- a/content/media/wmf/DXVA2Manager.h
+++ b/content/media/wmf/DXVA2Manager.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/. */
 #if !defined(DXVA2Manager_h_)
 #define DXVA2Manager_h_
 
 #include "WMF.h"
 #include "nsAutoPtr.h"
 #include "mozilla/Mutex.h"
+#include "nsRect.h"
 
 class nsIntSize;
 
 namespace mozilla {
 
 namespace layers {
 class Image;
 class ImageContainer;
@@ -30,17 +31,17 @@ public:
   // Returns a pointer to the D3D device manager responsible for managing the
   // device we're using for hardware accelerated video decoding. If we're using
   // D3D9, this is an IDirect3DDeviceManager9. It is safe to call this on any
   // thread.
   virtual IUnknown* GetDXVADeviceManager() = 0;
 
   // Creates an Image for the video frame stored in aVideoSample.
   virtual HRESULT CopyToImage(IMFSample* aVideoSample,
-                              const nsIntSize& aSize,
+                              const nsIntRect& aRegion,
                               layers::ImageContainer* aContainer,
                               layers::Image** aOutImage) = 0;
 
   virtual ~DXVA2Manager();
 
 protected:
   Mutex mLock;
   DXVA2Manager();
--- a/content/media/wmf/WMFReader.cpp
+++ b/content/media/wmf/WMFReader.cpp
@@ -786,17 +786,17 @@ WMFReader::CreateD3DVideoFrame(IMFSample
   NS_ENSURE_TRUE(mDXVA2Manager, E_ABORT);
   NS_ENSURE_TRUE(mUseHwAccel, E_ABORT);
 
   *aOutVideoData = nullptr;
   HRESULT hr;
 
   nsRefPtr<Image> image;
   hr = mDXVA2Manager->CopyToImage(aSample,
-                                  nsIntSize(mPictureRegion.width, mPictureRegion.height),
+                                  mPictureRegion,
                                   mDecoder->GetImageContainer(),
                                   getter_AddRefs(image));
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
   NS_ENSURE_TRUE(image, E_FAIL);
 
   VideoData *v = VideoData::CreateFromImage(mInfo,
                                             mDecoder->GetImageContainer(),
                                             aOffsetBytes,
--- a/content/svg/content/src/SVGAnimatedRect.cpp
+++ b/content/svg/content/src/SVGAnimatedRect.cpp
@@ -30,29 +30,25 @@ SVGAnimatedRect::SVGAnimatedRect(nsSVGVi
 }
 
 SVGAnimatedRect::~SVGAnimatedRect()
 {
   nsSVGViewBox::sSVGAnimatedRectTearoffTable.RemoveTearoff(mVal);
 }
 
 already_AddRefed<SVGIRect>
-SVGAnimatedRect::GetBaseVal(ErrorResult& aRv)
+SVGAnimatedRect::GetBaseVal()
 {
-  nsRefPtr<SVGIRect> rect;
-  aRv = mVal->ToDOMBaseVal(getter_AddRefs(rect), mSVGElement);
-  return rect.forget();
+  return mVal->ToDOMBaseVal(mSVGElement);
 }
 
 already_AddRefed<SVGIRect>
-SVGAnimatedRect::GetAnimVal(ErrorResult& aRv)
+SVGAnimatedRect::GetAnimVal()
 {
-  nsRefPtr<SVGIRect> rect;
-  aRv = mVal->ToDOMAnimVal(getter_AddRefs(rect), mSVGElement);
-  return rect.forget();
+  return mVal->ToDOMAnimVal(mSVGElement);
 }
 
 JSObject*
 SVGAnimatedRect::WrapObject(JSContext* aCx,
                             JS::Handle<JSObject*> aScope)
 {
   return SVGAnimatedRectBinding::Wrap(aCx, aScope, this);
 }
--- a/content/svg/content/src/SVGAnimatedRect.h
+++ b/content/svg/content/src/SVGAnimatedRect.h
@@ -32,19 +32,19 @@ public:
   nsSVGElement* GetParentObject() const
   {
     return mSVGElement;
   }
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
 
-  already_AddRefed<SVGIRect> GetBaseVal(ErrorResult& aRv);
+  already_AddRefed<SVGIRect> GetBaseVal();
 
-  already_AddRefed<SVGIRect> GetAnimVal(ErrorResult& aRv);
+  already_AddRefed<SVGIRect> GetAnimVal();
 
 private:
   nsSVGViewBox* mVal; // kept alive because it belongs to content
   nsRefPtr<nsSVGElement> mSVGElement;
 };
 
 } // namespace dom
 } // namespace mozilla
--- a/content/svg/content/src/SVGMarkerElement.cpp
+++ b/content/svg/content/src/SVGMarkerElement.cpp
@@ -104,19 +104,17 @@ SVGMarkerElement::SVGMarkerElement(alrea
 
 NS_IMPL_ELEMENT_CLONE_WITH_INIT(SVGMarkerElement)
 
 //----------------------------------------------------------------------
 
 already_AddRefed<SVGAnimatedRect>
 SVGMarkerElement::ViewBox()
 {
-  nsRefPtr<SVGAnimatedRect> rect;
-  mViewBox.ToDOMAnimatedRect(getter_AddRefs(rect), this);
-  return rect.forget();
+  return mViewBox.ToSVGAnimatedRect(this);
 }
 
 already_AddRefed<DOMSVGAnimatedPreserveAspectRatio>
 SVGMarkerElement::PreserveAspectRatio()
 {
   nsRefPtr<DOMSVGAnimatedPreserveAspectRatio> ratio;
   mPreserveAspectRatio.ToDOMAnimatedPreserveAspectRatio(getter_AddRefs(ratio), this);
   return ratio.forget();
--- a/content/svg/content/src/SVGPatternElement.cpp
+++ b/content/svg/content/src/SVGPatternElement.cpp
@@ -62,19 +62,17 @@ SVGPatternElement::SVGPatternElement(alr
 
 NS_IMPL_ELEMENT_CLONE_WITH_INIT(SVGPatternElement)
 
 //----------------------------------------------------------------------
 
 already_AddRefed<SVGAnimatedRect>
 SVGPatternElement::ViewBox()
 {
-  nsRefPtr<SVGAnimatedRect> rect;
-  mViewBox.ToDOMAnimatedRect(getter_AddRefs(rect), this);
-  return rect.forget();
+  return mViewBox.ToSVGAnimatedRect(this);
 }
 
 already_AddRefed<DOMSVGAnimatedPreserveAspectRatio>
 SVGPatternElement::PreserveAspectRatio()
 {
   nsRefPtr<DOMSVGAnimatedPreserveAspectRatio> ratio;
   mPreserveAspectRatio.ToDOMAnimatedPreserveAspectRatio(getter_AddRefs(ratio), this);
   return ratio.forget();
--- a/content/svg/content/src/SVGSVGElement.cpp
+++ b/content/svg/content/src/SVGSVGElement.cpp
@@ -440,19 +440,17 @@ SVGSVGElement::GetElementById(const nsAS
   return nullptr;
 }
 
 //----------------------------------------------------------------------
 
 already_AddRefed<SVGAnimatedRect>
 SVGSVGElement::ViewBox()
 {
-  nsRefPtr<SVGAnimatedRect> rect;
-  mViewBox.ToDOMAnimatedRect(getter_AddRefs(rect), this);
-  return rect.forget();
+  return mViewBox.ToSVGAnimatedRect(this);
 }
 
 already_AddRefed<DOMSVGAnimatedPreserveAspectRatio>
 SVGSVGElement::PreserveAspectRatio()
 {
   nsRefPtr<DOMSVGAnimatedPreserveAspectRatio> ratio;
   mPreserveAspectRatio.ToDOMAnimatedPreserveAspectRatio(getter_AddRefs(ratio), this);
   return ratio.forget();
--- a/content/svg/content/src/SVGSymbolElement.cpp
+++ b/content/svg/content/src/SVGSymbolElement.cpp
@@ -38,19 +38,17 @@ SVGSymbolElement::SVGSymbolElement(alrea
 
 NS_IMPL_ELEMENT_CLONE_WITH_INIT(SVGSymbolElement)
 
 //----------------------------------------------------------------------
 
 already_AddRefed<SVGAnimatedRect>
 SVGSymbolElement::ViewBox()
 {
-  nsRefPtr<SVGAnimatedRect> rect;
-  mViewBox.ToDOMAnimatedRect(getter_AddRefs(rect), this);
-  return rect.forget();
+  return mViewBox.ToSVGAnimatedRect(this);
 }
 
 already_AddRefed<DOMSVGAnimatedPreserveAspectRatio>
 SVGSymbolElement::PreserveAspectRatio()
 {
   nsRefPtr<DOMSVGAnimatedPreserveAspectRatio> ratio;
   mPreserveAspectRatio.ToDOMAnimatedPreserveAspectRatio(getter_AddRefs(ratio), this);
   return ratio.forget();
--- a/content/svg/content/src/SVGViewElement.cpp
+++ b/content/svg/content/src/SVGViewElement.cpp
@@ -62,19 +62,17 @@ SVGViewElement::SetZoomAndPan(uint16_t a
   rv.Throw(NS_ERROR_RANGE_ERR);
 }
 
 //----------------------------------------------------------------------
 
 already_AddRefed<SVGAnimatedRect>
 SVGViewElement::ViewBox()
 {
-  nsRefPtr<SVGAnimatedRect> box;
-  mViewBox.ToDOMAnimatedRect(getter_AddRefs(box), this);
-  return box.forget();
+  return mViewBox.ToSVGAnimatedRect(this);
 }
 
 already_AddRefed<DOMSVGAnimatedPreserveAspectRatio>
 SVGViewElement::PreserveAspectRatio()
 {
   nsRefPtr<DOMSVGAnimatedPreserveAspectRatio> ratio;
   mPreserveAspectRatio.ToDOMAnimatedPreserveAspectRatio(getter_AddRefs(ratio), this);
   return ratio.forget();
--- a/content/svg/content/src/nsSVGViewBox.cpp
+++ b/content/svg/content/src/nsSVGViewBox.cpp
@@ -52,17 +52,17 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
 static nsSVGAttrTearoffTable<nsSVGViewBox, nsSVGViewBox::DOMBaseVal>
   sBaseSVGViewBoxTearoffTable;
 static nsSVGAttrTearoffTable<nsSVGViewBox, nsSVGViewBox::DOMAnimVal>
   sAnimSVGViewBoxTearoffTable;
-nsSVGAttrTearoffTable<nsSVGViewBox, mozilla::dom::SVGAnimatedRect>
+nsSVGAttrTearoffTable<nsSVGViewBox, dom::SVGAnimatedRect>
   nsSVGViewBox::sSVGAnimatedRectTearoffTable;
 
 
 /* Implementation of nsSVGViewBox methods */
 
 void
 nsSVGViewBox::Init()
 {
@@ -193,73 +193,68 @@ nsSVGViewBox::GetBaseValueString(nsAStri
   PRUnichar buf[200];
   nsTextFormatter::snprintf(buf, sizeof(buf)/sizeof(PRUnichar),
                             NS_LITERAL_STRING("%g %g %g %g").get(),
                             (double)mBaseVal.x, (double)mBaseVal.y,
                             (double)mBaseVal.width, (double)mBaseVal.height);
   aValue.Assign(buf);
 }
 
-nsresult
-nsSVGViewBox::ToDOMAnimatedRect(dom::SVGAnimatedRect **aResult,
-                                nsSVGElement* aSVGElement)
+
+already_AddRefed<dom::SVGAnimatedRect>
+nsSVGViewBox::ToSVGAnimatedRect(nsSVGElement* aSVGElement)
 {
   nsRefPtr<dom::SVGAnimatedRect> domAnimatedRect =
     sSVGAnimatedRectTearoffTable.GetTearoff(this);
   if (!domAnimatedRect) {
     domAnimatedRect = new dom::SVGAnimatedRect(this, aSVGElement);
     sSVGAnimatedRectTearoffTable.AddTearoff(this, domAnimatedRect);
   }
 
-  domAnimatedRect.forget(aResult);
-  return NS_OK;
+  return domAnimatedRect.forget();
 }
 
-nsresult
-nsSVGViewBox::ToDOMBaseVal(dom::SVGIRect **aResult,
-                           nsSVGElement *aSVGElement)
+already_AddRefed<dom::SVGIRect>
+nsSVGViewBox::ToDOMBaseVal(nsSVGElement *aSVGElement)
 {
   if (!mHasBaseVal || mBaseVal.none) {
-    *aResult = nullptr;
-    return NS_OK;
+    return nullptr;
   }
+
   nsRefPtr<DOMBaseVal> domBaseVal =
     sBaseSVGViewBoxTearoffTable.GetTearoff(this);
   if (!domBaseVal) {
     domBaseVal = new DOMBaseVal(this, aSVGElement);
     sBaseSVGViewBoxTearoffTable.AddTearoff(this, domBaseVal);
   }
 
-  domBaseVal.forget(aResult);
-  return NS_OK;
+ return domBaseVal.forget();
 }
 
 nsSVGViewBox::DOMBaseVal::~DOMBaseVal()
 {
   sBaseSVGViewBoxTearoffTable.RemoveTearoff(mVal);
 }
 
-nsresult
-nsSVGViewBox::ToDOMAnimVal(dom::SVGIRect **aResult,
-                           nsSVGElement *aSVGElement)
+already_AddRefed<dom::SVGIRect>
+nsSVGViewBox::ToDOMAnimVal(nsSVGElement *aSVGElement)
 {
   if ((mAnimVal && mAnimVal->none) ||
       (!mAnimVal && (!mHasBaseVal || mBaseVal.none))) {
-    *aResult = nullptr;
-    return NS_OK;
+    return nullptr;
   }
+
   nsRefPtr<DOMAnimVal> domAnimVal =
     sAnimSVGViewBoxTearoffTable.GetTearoff(this);
   if (!domAnimVal) {
     domAnimVal = new DOMAnimVal(this, aSVGElement);
     sAnimSVGViewBoxTearoffTable.AddTearoff(this, domAnimVal);
   }
 
-  domAnimVal.forget(aResult);
-  return NS_OK;
+  return domAnimVal.forget();
 }
 
 nsSVGViewBox::DOMAnimVal::~DOMAnimVal()
 {
   sAnimSVGViewBoxTearoffTable.RemoveTearoff(mVal);
 }
 
 void
--- a/content/svg/content/src/nsSVGViewBox.h
+++ b/content/svg/content/src/nsSVGViewBox.h
@@ -75,22 +75,25 @@ public:
   void SetAnimValue(const nsSVGViewBoxRect& aRect,
                     nsSVGElement *aSVGElement);
 
   nsresult SetBaseValueString(const nsAString& aValue,
                               nsSVGElement *aSVGElement,
                               bool aDoSetAttr);
   void GetBaseValueString(nsAString& aValue) const;
 
-  nsresult ToDOMAnimatedRect(mozilla::dom::SVGAnimatedRect **aResult,
-                             nsSVGElement *aSVGElement);
-  nsresult ToDOMBaseVal(mozilla::dom::SVGIRect **aResult,
-                        nsSVGElement* aSVGElement);
-  nsresult ToDOMAnimVal(mozilla::dom::SVGIRect **aResult,
-                        nsSVGElement* aSVGElement);
+  already_AddRefed<mozilla::dom::SVGAnimatedRect>
+  ToSVGAnimatedRect(nsSVGElement *aSVGElement);
+
+  already_AddRefed<mozilla::dom::SVGIRect>
+  ToDOMBaseVal(nsSVGElement* aSVGElement);
+
+  already_AddRefed<mozilla::dom::SVGIRect>
+  ToDOMAnimVal(nsSVGElement* aSVGElement);
+
   // Returns a new nsISMILAttr object that the caller must delete
   nsISMILAttr* ToSMILAttr(nsSVGElement* aSVGElement);
 
 private:
 
   nsSVGViewBoxRect mBaseVal;
   nsAutoPtr<nsSVGViewBoxRect> mAnimVal;
   bool mHasBaseVal;
--- a/content/xbl/src/nsXBLProtoImpl.cpp
+++ b/content/xbl/src/nsXBLProtoImpl.cpp
@@ -78,18 +78,18 @@ nsXBLProtoImpl::InstallImplementation(ns
 
   // Stash a strong reference to the JSClass in the binding.
   aBinding->SetJSClass(static_cast<nsXBLJSClass*>(JS_GetClass(targetClassObject)));
 
   // If the prototype already existed, we don't need to install anything. return early.
   if (!targetObjectIsNew)
     return NS_OK;
 
-  JS::Rooted<JSObject*> targetScriptObject(context->GetNativeContext());
-  holder->GetJSObject(targetScriptObject.address());
+  JS::Rooted<JSObject*> targetScriptObject(context->GetNativeContext(),
+                                           holder->GetJSObject());
 
   AutoPushJSContext cx(context->GetNativeContext());
   JSAutoRequest ar(cx);
   JSAutoCompartment ac(cx, targetClassObject);
   AutoVersionChecker avc(cx);
 
   // Walk our member list and install each one in turn.
   for (nsXBLProtoImplMember* curr = mMembers;
--- a/content/xbl/src/nsXBLProtoImplMethod.cpp
+++ b/content/xbl/src/nsXBLProtoImplMethod.cpp
@@ -259,17 +259,18 @@ nsXBLProtoImplMethod::Write(nsIScriptCon
 {
   if (mJSMethodObject) {
     nsresult rv = aStream->Write8(XBLBinding_Serialize_Method);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = aStream->WriteWStringZ(mName);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    return XBL_SerializeFunction(aContext, aStream, mJSMethodObject);
+    return XBL_SerializeFunction(aContext, aStream,
+                                 JS::Handle<JSObject*>::fromMarkedLocation(&mJSMethodObject));
   }
 
   return NS_OK;
 }
 
 nsresult
 nsXBLProtoImplAnonymousMethod::Execute(nsIContent* aBoundElement)
 {
@@ -364,14 +365,15 @@ nsresult
 nsXBLProtoImplAnonymousMethod::Write(nsIScriptContext* aContext,
                                      nsIObjectOutputStream* aStream,
                                      XBLBindingSerializeDetails aType)
 {
   if (mJSMethodObject) {
     nsresult rv = aStream->Write8(aType);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    rv = XBL_SerializeFunction(aContext, aStream, mJSMethodObject);
+    rv = XBL_SerializeFunction(aContext, aStream,
+                               JS::Handle<JSObject*>::fromMarkedLocation(&mJSMethodObject));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return NS_OK;
 }
--- a/content/xbl/src/nsXBLProtoImplProperty.cpp
+++ b/content/xbl/src/nsXBLProtoImplProperty.cpp
@@ -368,19 +368,21 @@ nsXBLProtoImplProperty::Write(nsIScriptC
   }
 
   nsresult rv = aStream->Write8(type);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = aStream->WriteWStringZ(mName);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (mJSAttributes & JSPROP_GETTER) {
-    rv = XBL_SerializeFunction(aContext, aStream, mJSGetterObject);
+    rv = XBL_SerializeFunction(aContext, aStream,
+      JS::Handle<JSObject*>::fromMarkedLocation(&mJSGetterObject));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   if (mJSAttributes & JSPROP_SETTER) {
-    rv = XBL_SerializeFunction(aContext, aStream, mJSSetterObject);
+    rv = XBL_SerializeFunction(aContext, aStream,
+      JS::Handle<JSObject*>::fromMarkedLocation(&mJSSetterObject));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return NS_OK;
 }
--- a/content/xbl/src/nsXBLSerialize.cpp
+++ b/content/xbl/src/nsXBLSerialize.cpp
@@ -8,21 +8,20 @@
 #include "nsContentUtils.h"
 #include "jsdbgapi.h"
 
 using namespace mozilla;
 
 nsresult
 XBL_SerializeFunction(nsIScriptContext* aContext,
                       nsIObjectOutputStream* aStream,
-                      JSObject* aFunctionObject)
+                      JS::Handle<JSObject*> aFunction)
 {
   AutoPushJSContext cx(aContext->GetNativeContext());
-  JS::RootedObject function(cx, aFunctionObject);
-  return nsContentUtils::XPConnect()->WriteFunction(aStream, cx, function);
+  return nsContentUtils::XPConnect()->WriteFunction(aStream, cx, aFunction);
 }
 
 nsresult
 XBL_DeserializeFunction(nsIScriptContext* aContext,
                         nsIObjectInputStream* aStream,
                         JS::MutableHandle<JSObject*> aFunctionObjectp)
 {
   AutoPushJSContext cx(aContext->GetNativeContext());
--- a/content/xbl/src/nsXBLSerialize.h
+++ b/content/xbl/src/nsXBLSerialize.h
@@ -74,16 +74,16 @@ typedef uint8_t XBLBindingSerializeDetai
 // are no more attributes.
 #define XBLBinding_Serialize_NoMoreAttributes 0xFF
 
 PR_STATIC_ASSERT(XBLBinding_Serialize_CustomNamespace >= kNameSpaceID_LastBuiltin);
 
 nsresult
 XBL_SerializeFunction(nsIScriptContext* aContext,
                       nsIObjectOutputStream* aStream,
-                      JSObject* aFunctionObject);
+                      JS::Handle<JSObject*> aFunctionObject);
 
 nsresult
 XBL_DeserializeFunction(nsIScriptContext* aContext,
                         nsIObjectInputStream* aStream,
                         JS::MutableHandle<JSObject*> aFunctionObject);
 
 #endif // nsXBLSerialize_h__
--- a/content/xslt/src/xslt/txMozillaXSLTProcessor.cpp
+++ b/content/xslt/src/xslt/txMozillaXSLTProcessor.cpp
@@ -1433,19 +1433,18 @@ txVariable::Convert(nsIVariant *aValue, 
 
             // Convert random JS Objects to a string.
             nsCOMPtr<nsIXPConnectJSObjectHolder> holder =
                 do_QueryInterface(supports);
             if (holder) {
                 JSContext* cx = nsContentUtils::GetCurrentJSContext();
                 NS_ENSURE_TRUE(cx, NS_ERROR_NOT_AVAILABLE);
 
-                JS::RootedObject jsobj(cx);
-                rv = holder->GetJSObject(jsobj.address());
-                NS_ENSURE_SUCCESS(rv, rv);
+                JS::RootedObject jsobj(cx, holder->GetJSObject());
+                NS_ENSURE_STATE(jsobj);
 
                 JS::RootedString str(cx, JS_ValueToString(cx, OBJECT_TO_JSVAL(jsobj)));
                 NS_ENSURE_TRUE(str, NS_ERROR_FAILURE);
 
                 nsDependentJSString value;
                 NS_ENSURE_TRUE(value.init(cx, str), NS_ERROR_FAILURE);
 
                 *aResult = new StringResult(value, nullptr);
--- a/content/xul/content/src/nsXULElement.cpp
+++ b/content/xul/content/src/nsXULElement.cpp
@@ -2521,17 +2521,17 @@ nsXULPrototypeScript::DeserializeOutOfLi
             if (NS_SUCCEEDED(rv))
                 rv = Deserialize(objectInput, aGlobal, nullptr, nullptr);
 
             if (NS_SUCCEEDED(rv)) {
                 if (useXULCache && mSrcURI) {
                     bool isChrome = false;
                     mSrcURI->SchemeIs("chrome", &isChrome);
                     if (isChrome)
-                        cache->PutScript(mSrcURI, mScriptObject);
+                        cache->PutScript(mSrcURI, GetScriptObject());
                 }
                 cache->FinishInputStream(mSrcURI);
             } else {
                 // If mSrcURI is not in the cache,
                 // rv will be NS_ERROR_NOT_AVAILABLE and we'll try to
                 // update the cache file to hold a serialization of
                 // this script, once it has finished loading.
                 if (rv != NS_ERROR_NOT_AVAILABLE)
@@ -2623,19 +2623,19 @@ void
 nsXULPrototypeScript::Set(JSScript* aObject)
 {
     MOZ_ASSERT(!mScriptObject, "Leaking script object.");
     if (!aObject) {
         mScriptObject = nullptr;
         return;
     }
 
+    mScriptObject = aObject;
     nsContentUtils::HoldJSObjects(
         this, NS_CYCLE_COLLECTION_PARTICIPANT(nsXULPrototypeNode));
-    mScriptObject = aObject;
 }
 
 //----------------------------------------------------------------------
 //
 // nsXULPrototypeText
 //
 
 nsresult
--- a/content/xul/content/src/nsXULElement.h
+++ b/content/xul/content/src/nsXULElement.h
@@ -231,19 +231,23 @@ public:
                      nsIURI* aURI, uint32_t aLineNo,
                      nsIDocument* aDocument,
                      nsIScriptGlobalObjectOwner* aGlobalOwner);
 
     void UnlinkJSObjects();
 
     void Set(JSScript* aObject);
 
-    JSScript *GetScriptObject()
+    // It's safe to return a handle because we trace mScriptObject, no one ever
+    // uses the handle (or the script object) past the point at which the
+    // nsXULPrototypeScript dies, and we can't get memmoved so the
+    // &mScriptObject pointer can't go stale.
+    JS::Handle<JSScript*> GetScriptObject()
     {
-        return mScriptObject;
+        return JS::Handle<JSScript*>::fromMarkedLocation(&mScriptObject);
     }
 
     void TraceScriptObject(JSTracer* aTrc)
     {
         if (mScriptObject) {
             JS_CallScriptTracer(aTrc, &mScriptObject, "active window XUL prototype script");
         }
     }
--- a/content/xul/document/src/XULDocument.cpp
+++ b/content/xul/document/src/XULDocument.cpp
@@ -3639,28 +3639,28 @@ XULDocument::OnStreamComplete(nsIStreamL
         NS_RELEASE(doc);
     }
 
     return rv;
 }
 
 
 nsresult
-XULDocument::ExecuteScript(nsIScriptContext * aContext, JSScript* aScriptObject)
+XULDocument::ExecuteScript(nsIScriptContext * aContext,
+                           JS::Handle<JSScript*> aScriptObject)
 {
     NS_PRECONDITION(aScriptObject != nullptr && aContext != nullptr, "null ptr");
     if (! aScriptObject || ! aContext)
         return NS_ERROR_NULL_POINTER;
 
     NS_ENSURE_TRUE(mScriptGlobalObject, NS_ERROR_NOT_INITIALIZED);
 
     // Execute the precompiled script with the given version
-    JS::Rooted<JSScript*> script(aContext->GetNativeContext(), aScriptObject);
     JSObject* global = mScriptGlobalObject->GetGlobalJSObject();
-    return aContext->ExecuteScript(script, global);
+    return aContext->ExecuteScript(aScriptObject, global);
 }
 
 nsresult
 XULDocument::ExecuteScript(nsXULPrototypeScript *aScript)
 {
     NS_PRECONDITION(aScript != nullptr, "null ptr");
     NS_ENSURE_TRUE(aScript, NS_ERROR_NULL_POINTER);
     NS_ENSURE_TRUE(mScriptGlobalObject, NS_ERROR_NOT_INITIALIZED);
--- a/content/xul/document/src/XULDocument.h
+++ b/content/xul/document/src/XULDocument.h
@@ -398,17 +398,18 @@ protected:
      * completed, aBlock will be set to true.
      */
     nsresult LoadScript(nsXULPrototypeScript *aScriptProto, bool* aBlock);
 
     /**
      * Execute the precompiled script object scoped by this XUL document's
      * containing window object, and using its associated script context.
      */
-    nsresult ExecuteScript(nsIScriptContext *aContext, JSScript* aScriptObject);
+    nsresult ExecuteScript(nsIScriptContext *aContext,
+                           JS::Handle<JSScript*> aScriptObject);
 
     /**
      * Helper method for the above that uses aScript to find the appropriate
      * script context and object.
      */
     nsresult ExecuteScript(nsXULPrototypeScript *aScript);
 
     /**
--- a/content/xul/document/src/nsXULPrototypeCache.cpp
+++ b/content/xul/document/src/nsXULPrototypeCache.cpp
@@ -200,17 +200,18 @@ nsXULPrototypeCache::GetScript(nsIURI* a
     CacheScriptEntry entry;
     if (!mScriptTable.Get(aURI, &entry)) {
         return nullptr;
     }
     return entry.mScriptObject;
 }
 
 nsresult
-nsXULPrototypeCache::PutScript(nsIURI* aURI, JSScript* aScriptObject)
+nsXULPrototypeCache::PutScript(nsIURI* aURI,
+                               JS::Handle<JSScript*> aScriptObject)
 {
     CacheScriptEntry existingEntry;
     if (mScriptTable.Get(aURI, &existingEntry)) {
 #ifdef DEBUG
         nsAutoCString scriptName;
         aURI->GetSpec(scriptName);
         nsAutoCString message("Loaded script ");
         message += scriptName;
--- a/content/xul/document/src/nsXULPrototypeCache.h
+++ b/content/xul/document/src/nsXULPrototypeCache.h
@@ -64,17 +64,17 @@ public:
 
     // The following methods are used to put and retrive various items into and
     // from the cache.
 
     nsXULPrototypeDocument* GetPrototype(nsIURI* aURI);
     nsresult PutPrototype(nsXULPrototypeDocument* aDocument);
 
     JSScript* GetScript(nsIURI* aURI);
-    nsresult PutScript(nsIURI* aURI, JSScript* aScriptObject);
+    nsresult PutScript(nsIURI* aURI, JS::Handle<JSScript*> aScriptObject);
 
     nsXBLDocumentInfo* GetXBLDocumentInfo(nsIURI* aURL) {
         return mXBLDocTable.GetWeak(aURL);
     }
     nsresult PutXBLDocumentInfo(nsXBLDocumentInfo* aDocumentInfo);
 
     /**
      * Get a style sheet by URI. If the style sheet is not in the cache,
--- a/dom/alarm/AlarmDB.jsm
+++ b/dom/alarm/AlarmDB.jsm
@@ -134,25 +134,23 @@ AlarmDB.prototype = {
    */
   getAll: function getAll(aManifestURL, aSuccessCb, aErrorCb) {
     debug("getAll()");
 
     this.newTxn(
       "readonly",
       ALARMSTORE_NAME,
       function txnCb(aTxn, aStore) {
-        if (!aTxn.result)
+        if (!aTxn.result) {
           aTxn.result = [];
+        }
 
-        aStore.mozGetAll().onsuccess = function setTxnResult(aEvent) {
-          aEvent.target.result.forEach(function addAlarm(aAlarm) {
-            if (!aManifestURL || aManifestURL == aAlarm.manifestURL)
-              aTxn.result.push(aAlarm);
-          });
-
+        let index = aStore.index("manifestURL");
+        index.mozGetAll(aManifestURL).onsuccess = function setTxnResult(aEvent) {
+          aTxn.result = aEvent.target.result;
           debug("Request successful. Record count: " + aTxn.result.length);
         };
       },
       aSuccessCb,
       aErrorCb
     );
   }
 };
--- a/dom/apps/src/Webapps.js
+++ b/dom/apps/src/Webapps.js
@@ -363,17 +363,18 @@ WebappsApplication.prototype = {
     this._ondownloadapplied = null;
 
     this._downloadError = null;
 
     this.initHelper(aWindow, ["Webapps:OfflineCache",
                               "Webapps:CheckForUpdate:Return:OK",
                               "Webapps:CheckForUpdate:Return:KO",
                               "Webapps:Launch:Return:KO",
-                              "Webapps:PackageEvent"]);
+                              "Webapps:PackageEvent",
+                              "Webapps:ClearBrowserData:Return"]);
 
     cpmm.sendAsyncMessage("Webapps:RegisterForMessages",
                           ["Webapps:OfflineCache",
                            "Webapps:PackageEvent",
                            "Webapps:CheckForUpdate:Return:OK"]);
   },
 
   get manifest() {
@@ -459,21 +460,36 @@ WebappsApplication.prototype = {
                                               startPoint: aStartPoint || "",
                                               oid: this._id,
                                               timestamp: Date.now(),
                                               requestID: this.getRequestId(request) });
     return request;
   },
 
   clearBrowserData: function() {
+    let request = this.createRequest();
     let browserChild =
       BrowserElementPromptService.getBrowserElementChildForWindow(this._window);
     if (browserChild) {
-      browserChild.messageManager.sendAsyncMessage("Webapps:ClearBrowserData");
+      browserChild.messageManager.sendAsyncMessage(
+        "Webapps:ClearBrowserData",
+        { manifestURL: this.manifestURL,
+          oid: this._id,
+          requestID: this.getRequestId(request) }
+      );
+    } else {
+      let runnable = {
+        run: function run() {
+          Services.DOMRequest.fireError(request, "NO_CLEARABLE_BROWSER");
+        }
+      }
+      Services.tm.currentThread.dispatch(runnable,
+                                         Ci.nsIThread.DISPATCH_NORMAL);
     }
+    return request;
   },
 
   uninit: function() {
     this._onprogress = null;
     cpmm.sendAsyncMessage("Webapps:UnregisterForMessages",
                           ["Webapps:OfflineCache",
                            "Webapps:PackageEvent",
                            "Webapps:CheckForUpdate:Return:OK"]);
@@ -585,16 +601,19 @@ WebappsApplication.prototype = {
             break;
           case "applied":
             manifestCache.evict(this.manifestURL, this.innerWindowID);
             this._manifest = msg.manifest;
             this._fireEvent("downloadapplied", this._ondownloadapplied);
             break;
         }
         break;
+      case "Webapps:ClearBrowserData:Return":
+        Services.DOMRequest.fireSuccess(req, null);
+        break;
     }
   },
 
   classID: Components.ID("{723ed303-7757-4fb0-b261-4f78b1f6bd22}"),
 
   QueryInterface: XPCOMUtils.generateQI([Ci.mozIDOMApplication]),
 
   classInfo: XPCOMUtils.generateCI({classID: Components.ID("{723ed303-7757-4fb0-b261-4f78b1f6bd22}"),
--- a/dom/apps/src/Webapps.jsm
+++ b/dom/apps/src/Webapps.jsm
@@ -1849,18 +1849,26 @@ this.DOMApplicationRegistry = {
               manifest.package_path)) {
           sendError("INVALID_MANIFEST");
         } else if (!AppsUtils.checkInstallAllowed(manifest, app.installOrigin)) {
           sendError("INSTALL_FROM_DENIED");
         } else {
           app.etag = xhr.getResponseHeader("Etag");
           app.manifestHash = this.computeManifestHash(manifest);
           debug("at install package got app etag=" + app.etag);
-          Services.obs.notifyObservers(aMm, "webapps-ask-install",
-                                       JSON.stringify(aData));
+          // We allow bypassing the install confirmation process to facilitate
+          // automation.
+          let prefName = "dom.mozApps.auto_confirm_install";
+          if (Services.prefs.prefHasUserValue(prefName) &&
+              Services.prefs.getBoolPref(prefName)) {
+            this.confirmInstall(aData);
+          } else {
+            Services.obs.notifyObservers(aMm, "webapps-ask-install",
+                                         JSON.stringify(aData));
+          }
         }
       }
       else {
         sendError("MANIFEST_URL_ERROR");
       }
     }).bind(this), false);
 
     xhr.addEventListener("error", (function() {
@@ -2006,29 +2014,28 @@ this.DOMApplicationRegistry = {
 
     this.queuedDownload[app.manifestURL] = {
       manifest: manifest,
       app: appObject,
       profileDir: aProfileDir,
       offlineCacheObserver: aOfflineCacheObserver
     }
 
-    let postFirstInstallTask = (function () {
-      // Only executed on install not involving sync.
-      this.broadcastMessage("Webapps:AddApp", { id: id, app: appObject });
-      this.broadcastMessage("Webapps:Install:Return:OK", aData);
-      Services.obs.notifyObservers(this, "webapps-sync-install", appNote);
-    }).bind(this);
+    // We notify about the successful installation via mgmt.oninstall and the
+    // corresponging DOMRequest.onsuccess event as soon as the app is properly
+    // saved in the registry.
+    if (!aFromSync) {
+      this._saveApps((function() {
+        this.broadcastMessage("Webapps:AddApp", { id: id, app: appObject });
+        this.broadcastMessage("Webapps:Install:Return:OK", aData);
+        Services.obs.notifyObservers(this, "webapps-sync-install", appNote);
+      }).bind(this));
+    }
 
     if (!aData.isPackage) {
-      if (!aFromSync) {
-        this._saveApps((function() {
-          postFirstInstallTask();
-        }).bind(this));
-      }
       this.updateAppHandlers(null, app.manifest, app);
       if (aInstallSuccessCallback) {
         aInstallSuccessCallback(manifest);
       }
     }
 
     if (manifest.package_path) {
       // origin for install apps is meaningless here, since it's app:// and this
@@ -2062,19 +2069,16 @@ this.DOMApplicationRegistry = {
                                                     manifestURL: appObject.manifestURL },
                                                   true);
           debug("About to fire Webapps:PackageEvent 'installed'");
           this.broadcastMessage("Webapps:PackageEvent",
                                 { type: "installed",
                                   manifestURL: appObject.manifestURL,
                                   app: app,
                                   manifest: aManifest });
-          if (!aFromSync) {
-            postFirstInstallTask();
-          }
           if (aInstallSuccessCallback) {
             aInstallSuccessCallback(aManifest);
           }
         }).bind(this));
       }).bind(this));
     }
   },
 
@@ -3010,17 +3014,17 @@ this.DOMApplicationRegistry = {
 
     return desktopINI.exists();
 #else
     return true;
 #endif
 
   },
 
-  _notifyCategoryAndObservers: function(subject, topic, data) {
+  _notifyCategoryAndObservers: function(subject, topic, data,  msg) {
     const serviceMarker = "service,";
 
     // First create observers from the category manager.
     let cm =
       Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
     let enumerator = cm.enumerateCategory(topic);
 
     let observers = [];
@@ -3059,44 +3063,46 @@ this.DOMApplicationRegistry = {
       } catch (e) { }
     }
 
     observers.forEach(function (observer) {
       try {
         observer.observe(subject, topic, data);
       } catch(e) { }
     });
+    // Send back an answer to the child.
+    ppmm.broadcastAsyncMessage("Webapps:ClearBrowserData:Return", msg);
   },
 
   registerBrowserElementParentForApp: function(bep, appId) {
     let mm = bep._mm;
 
     // Make a listener function that holds on to this appId.
     let listener = this.receiveAppMessage.bind(this, appId);
 
     this.frameMessages.forEach(function(msgName) {
       mm.addMessageListener(msgName, listener);
     });
   },
 
   receiveAppMessage: function(appId, message) {
     switch (message.name) {
       case "Webapps:ClearBrowserData":
-        this._clearPrivateData(appId, true);
+        this._clearPrivateData(appId, true, message.data);
         break;
     }
   },
 
-  _clearPrivateData: function(appId, browserOnly) {
+  _clearPrivateData: function(appId, browserOnly, msg) {
     let subject = {
       appId: appId,
       browserOnly: browserOnly,
       QueryInterface: XPCOMUtils.generateQI([Ci.mozIApplicationClearPrivateDataParams])
     };
-    this._notifyCategoryAndObservers(subject, "webapps-clear-data", null);
+    this._notifyCategoryAndObservers(subject, "webapps-clear-data", null, msg);
   }
 };
 
 /**
  * Appcache download observer
  */
 let AppcacheObserver = function(aApp) {
   debug("Creating AppcacheObserver for " + aApp.origin +
--- a/dom/apps/tests/Makefile.in
+++ b/dom/apps/tests/Makefile.in
@@ -7,21 +7,30 @@ topsrcdir        = @top_srcdir@
 srcdir           = @srcdir@
 VPATH            = @srcdir@
 
 relativesrcdir   = @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MOCHITEST_FILES = \
-  test_app_update.html \
   file_app.sjs \
   file_app.template.html \
-  file_hosted_app.template.webapp \
   file_cached_app.template.webapp \
   file_cached_app.template.appcache \
+  file_hosted_app.template.webapp \
+  test_app_update.html \
   $(NULL)
 
+ifdef MOZ_B2G
+MOCHITEST_FILES += \
+  file_packaged_app.sjs \
+  file_packaged_app.template.webapp \
+  file_packaged_app.template.html \
+  test_packaged_app_install.html \
+  $(NULL)
+endif
+
 MOCHITEST_CHROME_FILES = \
   test_apps_service.xul \
   $(NULL)
 
 include $(topsrcdir)/config/rules.mk
--- a/dom/apps/tests/file_app.template.html
+++ b/dom/apps/tests/file_app.template.html
@@ -35,17 +35,20 @@ function finish() {
 function cbError() {
   ok(false, "Error callback invoked");
   finish();
 }
 
 function go() {
   ok(true, "Launched app");
   var request = window.navigator.mozApps.getSelf();
-  request.onsuccess = function() { var app = request.result; checkApp(app); }
+  request.onsuccess = function() {
+    var app = request.result;
+    checkApp(app);
+  }
   request.onerror = cbError;
 }
 
 function checkApp(app) {
   // If the app is installed, |app| will be non-null. If it is, verify its state.
   installed(!!app);
   if (app) {
     var appName = "Really Rapid Release (APPTYPETOKEN)";
new file mode 100644
--- /dev/null
+++ b/dom/apps/tests/file_packaged_app.sjs
@@ -0,0 +1,166 @@
+var Cc = Components.classes;
+var Ci = Components.interfaces;
+var Cu = Components.utils;
+
+// From prio.h
+const PR_RDWR        = 0x04;
+const PR_CREATE_FILE = 0x08;
+const PR_TRUNCATE    = 0x20;
+
+Cu.import("resource://gre/modules/FileUtils.jsm");
+Cu.import("resource://gre/modules/NetUtil.jsm");
+
+var gBasePath = "tests/dom/apps/tests/";
+var gMiniManifestTemplate = "file_packaged_app.template.webapp";
+var gAppTemplate = "file_packaged_app.template.html";
+var gAppName = "appname";
+var gDevName = "devname";
+var gDevUrl = "http://dev.url";
+
+function handleRequest(request, response) {
+  var query = getQuery(request);
+
+  response.setHeader("Access-Control-Allow-Origin", "*", false);
+
+  var packageSize = ("packageSize" in query) ? query.packageSize : 0;
+  var appName = ("appName" in query) ? query.appName : gAppName;
+  var devName = ("devName" in query) ? query.devName : gDevName;
+  var devUrl = ("devUrl" in query) ? query.devUrl : gDevUrl;
+
+  // If this is a version update, update state, prepare the manifest,
+  // the application package and return.
+  if ("setVersion" in query) {
+    var version = query.setVersion;
+    setState("version", version);
+
+    var packageName = "test_packaged_app_" + version + ".zip";
+    setState("packageName", packageName);
+    var packagePath = "/" + gBasePath + "file_packaged_app.sjs?getPackage=" +
+                      packageName;
+    setState("packagePath", packagePath);
+
+    // Create the application package.
+    var zipWriter = Cc["@mozilla.org/zipwriter;1"]
+                    .createInstance(Ci.nsIZipWriter);
+    var zipFile = FileUtils.getFile("TmpD", [packageName]);
+    zipWriter.open(zipFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
+
+    // We want to run some tests without the manifest included in the zip.
+    if (version != "0") {
+      var manifestTemplate = gBasePath + gMiniManifestTemplate;
+      var manifest = makeResource(manifestTemplate, version, packagePath,
+                                  packageSize, appName, devName, devUrl);
+      addZipEntry(zipWriter, manifest, "manifest.webapp");
+    }
+
+    var appTemplate = gBasePath + gAppTemplate;
+    var app = makeResource(appTemplate, version, packagePath, packageSize,
+                           appName, devName, devUrl);
+    addZipEntry(zipWriter, app, "index.html");
+
+    zipWriter.close();
+
+    response.setHeader("Content-Type", "text/html", false);
+    response.write("OK");
+    return;
+  }
+
+  // Get the version from server state
+  var version = Number(getState("version"));
+  var packageName = String(getState("packageName"));
+  var packagePath = String(getState("packagePath"));
+
+  var etag = getEtag(request, version);
+
+  if (etagMatches(request, etag)) {
+    dump("Etags Match. Sending 304\n");
+    response.setStatusLine(request.httpVersion, "304", "Not modified");
+    return;
+  }
+
+  response.setHeader("Etag", etag, false);
+
+  // Serve the application package corresponding to the requested app version.
+  if ("getPackage" in query) {
+    var resource = readFile(packageName, true);
+    response.setHeader("Content-Type",
+                       "Content-Type: application/java-archive", false);
+    response.write(resource);
+    return;
+  }
+
+  // Serve the mini-manifest corresponding to the requested app version.
+  if ("getManifest" in query) {
+    var template = gBasePath + gMiniManifestTemplate;
+    if (!("noManifestContentType" in query)) {
+      response.setHeader("Content-Type",
+                         "application/x-web-app-manifest+json", false);
+    }
+    packagePath = "wrongPackagePath" in query ? "" : packagePath;
+    var manifest = makeResource(template, version, packagePath, packageSize,
+                                appName, devName, devUrl);
+    response.write(manifest);
+    return;
+  }
+
+  response.setHeader("Content-type", "text-html", false);
+  response.write("KO");
+}
+
+function getQuery(request) {
+  var query = {};
+  request.queryString.split('&').forEach(function (val) {
+    var [name, value] = val.split('=');
+    query[name] = unescape(value);
+  });
+  return query;
+}
+
+function getEtag(request, version) {
+  return request.queryString.replace(/&/g, '-').replace(/=/g, '-') +
+         '-' + version;
+}
+
+function etagMatches(request, etag) {
+  return request.hasHeader("If-None-Match") &&
+         request.getHeader("If-None-Match") == etag;
+}
+
+// File and resources helpers
+
+function addZipEntry(zipWriter, entry, entryName) {
+  var stream = Cc["@mozilla.org/io/string-input-stream;1"]
+               .createInstance(Ci.nsIStringInputStream);
+  stream.setData(entry, entry.length);
+  zipWriter.addEntryStream(entryName, Date.now(),
+                           Ci.nsIZipWriter.COMPRESSION_BEST, stream, false);
+}
+
+function readFile(path, fromTmp) {
+  var dir = fromTmp ? "TmpD" : "CurWorkD";
+  var file = Cc["@mozilla.org/file/directory_service;1"]
+             .getService(Ci.nsIProperties)
+             .get(dir, Ci.nsILocalFile);
+  var fstream = Cc["@mozilla.org/network/file-input-stream;1"]
+                .createInstance(Ci.nsIFileInputStream);
+  var split = path.split("/");
+  for(var i = 0; i < split.length; ++i) {
+    file.append(split[i]);
+  }
+  fstream.init(file, -1, 0, 0);
+  var data = NetUtil.readInputStreamToString(fstream, fstream.available());
+  fstream.close();
+  return data;
+}
+
+function makeResource(templatePath, version, packagePath, packageSize,
+                      appName, developerName, developerUrl) {
+  var res = readFile(templatePath, false)
+            .replace(/VERSIONTOKEN/g, version)
+            .replace(/PACKAGEPATHTOKEN/g, packagePath)
+            .replace(/PACKAGESIZETOKEN/g, packageSize)
+            .replace(/NAMETOKEN/g, appName)
+            .replace(/DEVELOPERTOKEN/g, developerName)
+            .replace(/DEVELOPERURLTOKEN/g, developerUrl);
+  return res;
+}
new file mode 100644
--- /dev/null
+++ b/dom/apps/tests/file_packaged_app.template.html
@@ -0,0 +1,7 @@
+<html>
+<head>
+</head>
+<body>
+App Body. Version: VERSIONTOKEN
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/apps/tests/file_packaged_app.template.webapp
@@ -0,0 +1,13 @@
+{
+  "name" : "NAMETOKEN",
+  "version" : "VERSIONTOKEN",
+  "size" : PACKAGESIZETOKEN,
+  "package_path": "PACKAGEPATHTOKEN",
+  "description": "Updated even faster than Firefox, just to annoy slashdotters",
+  "launch_path": "tests/dom/apps/tests/file_packaged_app.sjs",
+  "developer": {
+    "name": "DEVELOPERTOKEN",
+    "url": "DEVELOPERURLTOKEN"
+  },
+  "default_locale": "en-US"
+}
new file mode 100644
--- /dev/null
+++ b/dom/apps/tests/test_packaged_app_install.html
@@ -0,0 +1,401 @@
+<!DOCTYPE html>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id={821589}
+-->
+<head>
+  <title>Test for Bug {821589} Packaged apps installation and update</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id={821589}">Mozilla Bug {821589}</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+
+"use strict";
+
+var gInstallOrigin = "http://mochi.test:8888";
+var gSJSPath = "tests/dom/apps/tests/file_packaged_app.sjs";
+var gSJS = "http://test/" + gSJSPath;
+var gAppName = "appname";
+var gApp = null;
+
+var launchableValue = undefined;
+
+var index = -1;
+
+function debug(aMsg) {
+  //dump("== Tests debug == " + aMsg + "\n");
+}
+
+function next() {
+  index += 1;
+  if (index >= steps.length) {
+    ok(false, "Shouldn't get here!");
+    return;
+  }
+  try {
+    steps[index]();
+  } catch(ex) {
+    ok(false, "Caught exception", ex);
+  }
+}
+
+function go() {
+  next();
+}
+
+function finish() {
+  SpecialPowers.setAllAppsLaunchable(launchableValue);
+  SpecialPowers.removePermission("webapps-manage", document);
+  SimpleTest.finish();
+}
+
+function cbError(aError) {
+  ok(false, "Error callback invoked " + aError);
+  finish();
+}
+
+function setAppVersion(aVersion, aCb) {
+  var xhr = new XMLHttpRequest();
+  xhr.addEventListener("load", function() {
+    is(xhr.responseText, "OK", "setVersion OK");
+    aCb();
+  });
+  xhr.addEventListener("error", cbError);
+  xhr.addEventListener("abort", cbError);
+  xhr.open("GET", gSJS + "?setVersion=" + aVersion, true);
+  xhr.send();
+}
+
+function checkAppInstallError(aMiniManifestURL, aExpectedError) {
+  var req = navigator.mozApps.installPackage(aMiniManifestURL);
+  req.onsuccess = function() {
+    ok(false, "We are supposed to throw " + aExpectedError);
+    finish();
+  };
+  req.onerror = function(evt) {
+    var error = evt.target.error.name;
+    if (error == aExpectedError) {
+      ok(true, "Got expected " + aExpectedError);
+      next();
+    } else {
+      ok(false, "Got unexpected " + aError);
+      finish();
+    }
+  };
+}
+
+function checkUninstallApp(aApp) {
+  var req = navigator.mozApps.mgmt.uninstall(aApp);
+  req.onsuccess = function() {
+    ok(true, "App uninstalled");
+    aApp.ondownloadsuccess = null;
+    aApp.ondownloaderror = null;
+    aApp.onprogress = null;
+    next();
+  };
+  req.onerror = function(evt) {
+    ok(false, "Got unexpected " + evt.target.error.name);
+    finish();
+  };
+}
+
+function checkAppDownloadError(aMiniManifestURL,
+                               aExpectedError,
+                               aVersion,
+                               aUninstall,
+                               aDownloadAvailable,
+                               aName) {
+  var req = navigator.mozApps.installPackage(aMiniManifestURL);
+  req.onsuccess = function() {
+    ok(true, "App installed");
+  };
+  req.onerror = function(evt) {
+    ok(false, "Got unexpected " + evt.target.error.name);
+    finish();
+  };
+
+  navigator.mozApps.mgmt.oninstall = function(evt) {
+    var aApp = evt.application;
+    aApp.ondownloaderror = function(evt) {
+      var error = aApp.downloadError.name;
+      if (error == aExpectedError) {
+        ok(true, "Got expected " + aExpectedError);
+        var expected = {
+          name: aName,
+          manifestURL: aMiniManifestURL,
+          installOrigin: gInstallOrigin,
+          progress: 0,
+          installState: "pending",
+          downloadAvailable: aDownloadAvailable,
+          downloading: false,
+          downloadSize: 0,
+          size: 0,
+          readyToApplyDownload: false,
+        };
+        checkAppState(aApp, aVersion, expected, false, aUninstall, next);
+      } else {
+        ok(false, "Got unexpected " + error);
+        finish();
+      }
+    };
+    aApp.ondownloadsuccess = function(evt) {
+      ok(false, "We are supposed to throw " + aExpectedError);
+      finish();
+    };
+  };
+}
+
+function checkInstalledApp(aMiniManifestURL,
+                           aVersion,
+                           aExpectedApp,
+                           aLaunchable,
+                           aCb) {
+  var req = navigator.mozApps.checkInstalled(aMiniManifestURL);
+  req.onsuccess = function(evt) {
+    ok(true, "The app is installed");
+    checkAppState(evt.application, aVersion, aExpectedApp, aLaunchable,
+                  false, aCb);
+  };
+  req.onerror = function() {
+    ok(false, "The app is not installed");
+    finish();
+  };
+}
+
+function checkAppState(aApp,
+                       aVersion,
+                       aExpectedApp,
+                       aLaunchable,
+                       aUninstall,
+                       aCb) {
+  debug(JSON.stringify(aApp, null, 2));
+  if (aApp.manifest) {
+    debug(JSON.stringify(aApp.manifest, null, 2));
+  }
+
+  if (aExpectedApp.name) {
+    if (aApp.manifest) {
+      is(aApp.manifest.name, aExpectedApp.name, "Check name");
+    }
+    is(aApp.updateManifest.name, aExpectedApp.name, "Check name mini-manifest");
+  }
+  if (aApp.manifest) {
+    is(aApp.manifest.version, aVersion, "Check version");
+  }
+  if (typeof aExpectedApp.size !== "undefined" && aApp.manifest) {
+    is(aApp.manifest.size, aExpectedApp.size, "Check size");
+  }
+  if (aApp.manifest) {
+    is(aApp.manifest.launch_path, gSJSPath, "Check launch path");
+  }
+  if (aExpectedApp.manifestURL) {
+    is(aApp.manifestURL, aExpectedApp.manifestURL, "Check manifestURL");
+  }
+  if (aExpectedApp.installOrigin) {
+    is(aApp.installOrigin, aExpectedApp.installOrigin, "Check installOrigin");
+  }
+  ok(aApp.removable, "Removable app");
+  if (typeof aExpectedApp.progress !== "undefined") {
+    todo(aApp.progress == aExpectedApp.progress, "Check progress");
+  }
+  if (aExpectedApp.installState) {
+    is(aApp.installState, aExpectedApp.installState, "Check installState");
+  }
+  if (typeof aExpectedApp.downloadAvailable !== "undefined") {
+    is(aApp.downloadAvailable, aExpectedApp.downloadAvailable,
+       "Check download available");
+  }
+  if (typeof aExpectedApp.downloading !== "undefined") {
+    is(aApp.downloading, aExpectedApp.downloading, "Check downloading");
+  }
+  if (typeof aExpectedApp.downloadSize !== "undefined") {
+    is(aApp.downloadSize, aExpectedApp.downloadSize, "Check downloadSize");
+  }
+  if (typeof aExpectedApp.readyToApplyDownload !== "undefined") {
+    is(aApp.readyToApplyDownload, aExpectedApp.readyToApplyDownload,
+       "Check readyToApplyDownload");
+  }
+  if (aLaunchable) {
+    if (aUninstall) {
+      checkUninstallApp(aApp);
+    } else if (aCb && typeof aCb === 'function') {
+      aCb();
+    }
+    return;
+  }
+
+  // Check if app is not launchable.
+  var req = aApp.launch();
+  req.onsuccess = function () {
+    ok(false, "We shouldn't be here");
+    finish();
+  };
+  req.onerror = function() {
+    ok(true, "App is not launchable");
+    if (aUninstall) {
+      checkUninstallApp(aApp);
+    } else if (aCb && typeof aCb === 'function') {
+      aCb();
+    }
+    return;
+  };
+}
+
+SimpleTest.waitForExplicitFinish();
+
+var steps = [
+  function() {
+    // Set up
+    launchableValue = SpecialPowers.setAllAppsLaunchable(true);
+    SpecialPowers.addPermission("webapps-manage", true, document);
+    ok(true, "Set up");
+    next();
+  },
+  function() {
+    ok(true, "autoConfirmAppInstall");
+    SpecialPowers.autoConfirmAppInstall(next);
+  },
+  function() {
+    setAppVersion(0, next);
+  },
+  function() {
+    // Test network error.
+    ok(true, "== TEST == Network error");
+    checkAppInstallError("http://notvalidurl", "NETWORK_ERROR");
+  },
+  function() {
+    // Test wrong mini-manifest content type.
+    ok(true, "== TEST == Not valid mini-manifest content type");
+    var miniManifestURL = gSJS +
+                          "?getManifest=true" +
+                          "&noManifestContentType=true";
+    checkAppInstallError(miniManifestURL, "INVALID_MANIFEST");
+  },
+  function() {
+    // Test mini-manifest 'size' value is not number. Bug 839435.
+    ok(true, "== TEST == Size value is not a number");
+    var miniManifestURL = gSJS +
+                          "?getManifest=true" +
+                          "&packageSize=\"NotANumber\"";
+    checkAppInstallError(miniManifestURL, "INVALID_MANIFEST");
+  },
+  function() {
+    // Test mini-manifest  negative 'size' value. Bug 839435.
+    ok(true, "== TEST == Negative size value");
+    var miniManifestURL = gSJS +
+                          "?getManifest=true" +
+                          "&packageSize=-1";
+    checkAppInstallError(miniManifestURL, "INVALID_MANIFEST");
+  },
+  function() {
+    // Test wrong package path
+    ok(true, "== TEST == Installing app with wrong package path");
+    var miniManifestURL = gSJS +
+                          "?getManifest=true" +
+                          "&wrongPackagePath=true";
+    checkAppInstallError(miniManifestURL, "INVALID_MANIFEST");
+  },
+  function() {
+    // Test no manifest in zip file.
+    ok(true, "== TEST == No manifest in the zip file");
+    var miniManifestURL = gSJS + "?getManifest=true";
+    checkAppDownloadError(miniManifestURL, "MISSING_MANIFEST", 0, true, true,
+                          gAppName);
+  },
+  function() {
+    setAppVersion(1, next);
+  },
+  function() {
+    // Test mini-manifest app name is different from the webapp manifest name.
+    // Bug 844243.
+    ok(true, "== TEST == Mini-manifest app name is different from webapp " +
+             "manifest name");
+    var miniManifestURL = gSJS +
+                          "?getManifest=true" +
+                          "&appName=arandomname";
+    checkAppDownloadError(miniManifestURL, "MANIFEST_MISMATCH", 1, true, true,
+                          "arandomname");
+  },
+  function() {
+    // Test mini-manifest dev name is different from the webapp manifest dev
+    // name.
+    ok (true, "== TEST == Mini-manifest dev name is different from manifest " +
+              "dev name");
+    var miniManifestURL = gSJS +
+                          "?getManifest=true" +
+                          "&devName=arandomdevname";
+    checkAppDownloadError(miniManifestURL, "MANIFEST_MISMATCH", 1, true, true,
+                          gAppName);
+  },
+  function() {
+    // Test mini-manifest dev url is different from the webapp manifest dev
+    // url.
+    ok (true, "== TEST == Mini-manifest dev url is different from manifest " +
+              "dev url");
+    var miniManifestURL = gSJS +
+                          "?getManifest=true" +
+                          "&devUrl=arandomdevurl";
+    checkAppDownloadError(miniManifestURL, "MANIFEST_MISMATCH", 1, true, true,
+                          gAppName);
+  },
+  function() {
+    setAppVersion(2, next);
+  },
+  function() {
+    ok(true, "== TEST == Install packaged app");
+    var miniManifestURL = gSJS +
+                          "?getManifest=true";
+    navigator.mozApps.mgmt.oninstall = function(evt) {
+      ok(true, "Got oninstall event");
+      gApp = evt.application;
+      gApp.ondownloaderror = function() {
+        ok(false, "Download error " + gApp.downloadError.name);
+        finish();
+      };
+      gApp.ondownloadsuccess = function() {
+        ok(true, "App downloaded");
+        var expected = {
+          name: gAppName,
+          manifestURL: miniManifestURL,
+          installOrigin: gInstallOrigin,
+          progress: 0,
+          installState: "installed",
+          downloadAvailable: false,
+          downloading: false,
+          downloadSize: 0,
+          size: 0,
+          readyToApplyDownload: false,
+        };
+        checkAppState(gApp, 2, expected, true, false, next);
+      };
+    };
+
+    var request = navigator.mozApps.installPackage(miniManifestURL);
+    request.onerror = function(evt) {
+      cbError(evt.target.error.name);
+    };
+    request.onsuccess = function() {
+      ok(true, "Application installed");
+    };
+  },
+  function() {
+    ok(true, "all done!\n");
+    SimpleTest.finish();
+  }
+];
+
+addLoadEvent(go);
+
+</script>
+</pre>
+</body>
+</html>
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -328,20 +328,16 @@ using mozilla::dom::workers::ResolveWork
 
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/Likely.h"
 
 #ifdef MOZ_TIME_MANAGER
 #include "TimeManager.h"
 #endif
 
-#ifdef MOZ_WEBRTC
-#include "nsIDOMDataChannel.h"
-#endif
-
 using namespace mozilla;
 using namespace mozilla::dom;
 
 static NS_DEFINE_CID(kDOMSOF_CID, NS_DOM_SCRIPT_OBJECT_FACTORY_CID);
 
 static const char kDOMStringBundleURL[] =
   "chrome://global/locale/dom/dom.properties";
 
@@ -560,18 +556,16 @@ static nsDOMClassInfoData sClassInfoData
   NS_DEFINE_CLASSINFO_DATA(MouseScrollEvent, nsEventSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(WheelEvent, nsEventSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(DragEvent, nsEventSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(ClipboardEvent, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
-  NS_DEFINE_CLASSINFO_DATA(KeyboardEvent, nsEventSH,
-                           DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(CompositionEvent, nsEventSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
 
 #define MOZ_GENERATED_EVENT_LIST
 #define MOZ_GENERATED_EVENT(_event_interface)             \
   NS_DEFINE_CLASSINFO_DATA(_event_interface, nsEventSH,   \
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
 #include "GeneratedEvents.h"
@@ -901,21 +895,16 @@ static nsDOMClassInfoData sClassInfoData
                            EVENTTARGET_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(CSSFontFeatureValuesRule, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
 
 #ifdef MOZ_TIME_MANAGER
   NS_DEFINE_CLASSINFO_DATA(MozTimeManager, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
 #endif
-
-#ifdef MOZ_WEBRTC
-  NS_DEFINE_CLASSINFO_DATA(DataChannel, nsEventTargetSH,
-                           EVENTTARGET_SCRIPTABLE_FLAGS)
-#endif
 };
 
 #define NS_DEFINE_CONTRACT_CTOR(_class, _contract_id)                           \
   static nsresult                                                               \
   _class##Ctor(nsISupports** aInstancePtrResult)                                \
   {                                                                             \
     nsresult rv = NS_OK;                                                        \
     nsCOMPtr<nsISupports> native = do_CreateInstance(_contract_id, &rv);        \
@@ -1708,21 +1697,16 @@ nsDOMClassInfo::Init()
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMMutationEvent)
     DOM_CLASSINFO_EVENT_MAP_ENTRIES
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(UIEvent, nsIDOMUIEvent)
     DOM_CLASSINFO_UI_EVENT_MAP_ENTRIES
   DOM_CLASSINFO_MAP_END
 
-  DOM_CLASSINFO_MAP_BEGIN_NO_CLASS_IF(KeyboardEvent, nsIDOMKeyEvent)
-    DOM_CLASSINFO_MAP_ENTRY(nsIDOMKeyEvent)
-    DOM_CLASSINFO_UI_EVENT_MAP_ENTRIES
-  DOM_CLASSINFO_MAP_END
-
   DOM_CLASSINFO_MAP_BEGIN(CompositionEvent, nsIDOMCompositionEvent)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMCompositionEvent)
     DOM_CLASSINFO_UI_EVENT_MAP_ENTRIES
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(MouseEvent, nsIDOMMouseEvent)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMMouseEvent)
     DOM_CLASSINFO_UI_EVENT_MAP_ENTRIES
@@ -2280,23 +2264,16 @@ nsDOMClassInfo::Init()
   DOM_CLASSINFO_MAP_END
 
 #ifdef MOZ_TIME_MANAGER
   DOM_CLASSINFO_MAP_BEGIN(MozTimeManager, nsIDOMMozTimeManager)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMMozTimeManager)
   DOM_CLASSINFO_MAP_END
 #endif
 
-#ifdef MOZ_WEBRTC
-  DOM_CLASSINFO_MAP_BEGIN(DataChannel, nsIDOMDataChannel)
-    DOM_CLASSINFO_MAP_ENTRY(nsIDOMDataChannel)
-    DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
-  DOM_CLASSINFO_MAP_END
-#endif
-
   MOZ_STATIC_ASSERT(MOZ_ARRAY_LENGTH(sClassInfoData) == eDOMClassInfoIDCount,
                     "The number of items in sClassInfoData doesn't match the "
                     "number of nsIDOMClassInfo ID's, this is bad! Fix it!");
 
 #ifdef DEBUG
   for (size_t i = 0; i < eDOMClassInfoIDCount; i++) {
     if (!sClassInfoData[i].u.mConstructorFptr ||
         sClassInfoData[i].mDebugID != i) {
@@ -2667,18 +2644,18 @@ nsDOMClassInfo::CheckAccess(nsIXPConnect
 {
   JS::Rooted<jsid> id(cx, aId);
   uint32_t mode_type = mode & JSACC_TYPEMASK;
 
   if ((mode_type == JSACC_WATCH || mode_type == JSACC_PROTO) && sSecMan) {
     nsresult rv;
     JS::Rooted<JSObject*> real_obj(cx);
     if (wrapper) {
-      rv = wrapper->GetJSObject(real_obj.address());
-      NS_ENSURE_SUCCESS(rv, rv);
+      real_obj = wrapper->GetJSObject();
+      NS_ENSURE_STATE(real_obj);
     }
     else {
       real_obj = obj;
     }
 
     rv =
       sSecMan->CheckPropertyAccess(cx, real_obj, mData->mName, id,
                                    nsIXPCSecurityManager::ACCESS_GET_PROPERTY);
@@ -3378,18 +3355,17 @@ BaseStubConstructor(nsIWeakReference* aW
     if (initializer) {
       rv = initializer->Initialize(currentInner, cx, obj, args);
       if (NS_FAILED(rv)) {
         return rv;
       }
     } else {
       nsCOMPtr<nsIXPConnectWrappedJS> wrappedJS = do_QueryInterface(native);
 
-      JS::Rooted<JSObject*> thisObject(cx);
-      wrappedJS->GetJSObject(thisObject.address());
+      JS::Rooted<JSObject*> thisObject(cx, wrappedJS->GetJSObject());
       if (!thisObject) {
         return NS_ERROR_UNEXPECTED;
       }
 
       nsCxPusher pusher;
       pusher.Push(cx);
 
       JSAutoRequest ar(cx);
@@ -4124,18 +4100,17 @@ GetXPCProto(nsIXPConnect *aXPConnect, JS
   }
   NS_ENSURE_TRUE(ci, NS_ERROR_UNEXPECTED);
 
   nsresult rv =
     aXPConnect->GetWrappedNativePrototype(cx, aWin->GetGlobalJSObject(), ci,
                                           aProto);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  JS::Rooted<JSObject*> proto_obj(cx);
-  (*aProto)->GetJSObject(proto_obj.address());
+  JS::Rooted<JSObject*> proto_obj(cx, (*aProto)->GetJSObject());
   if (!JS_WrapObject(cx, proto_obj.address())) {
     return NS_ERROR_FAILURE;
   }
 
   NS_IF_RELEASE(*aProto);
   return aXPConnect->HoldObject(cx, proto_obj, aProto);
 }
 
@@ -4167,18 +4142,17 @@ ResolvePrototype(nsIXPConnect *aXPConnec
                   false, v.address(), getter_AddRefs(holder));
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (install) {
     rv = constructor->Install(cx, obj, v);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  JS::Rooted<JSObject*> class_obj(cx);
-  holder->GetJSObject(class_obj.address());
+  JS::Rooted<JSObject*> class_obj(cx, holder->GetJSObject());
   NS_ASSERTION(class_obj, "The return value lied");
 
   const nsIID *primary_iid = &NS_GET_IID(nsISupports);
 
   if (!ci_data) {
     primary_iid = &name_struct->mIID;
   }
   else if (ci_data->mProtoChainInterface) {
@@ -4445,18 +4419,17 @@ nsWindowSH::GlobalResolve(nsGlobalWindow
     JS::Rooted<JS::Value> v(cx);
     rv = WrapNative(cx, obj, constructor, &NS_GET_IID(nsIDOMDOMConstructor),
                     false, v.address(), getter_AddRefs(holder));
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = constructor->Install(cx, obj, v);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    JS::Rooted<JSObject*> class_obj(cx);
-    holder->GetJSObject(class_obj.address());
+    JS::Rooted<JSObject*> class_obj(cx, holder->GetJSObject());
     NS_ASSERTION(class_obj, "The return value lied");
 
     // ... and define the constants from the DOM interface on that
     // constructor object.
 
     JSAutoCompartment ac(cx, class_obj);
     rv = DefineInterfaceConstants(cx, class_obj, &name_struct->mIID);
     NS_ENSURE_SUCCESS(rv, rv);
@@ -4474,19 +4447,18 @@ nsWindowSH::GlobalResolve(nsGlobalWindow
 
     // Create the XPConnect prototype for our classinfo, PostCreateProto will
     // set up the prototype chain.
     nsCOMPtr<nsIXPConnectJSObjectHolder> proto_holder;
     rv = GetXPCProto(sXPConnect, cx, aWin, name_struct,
                      getter_AddRefs(proto_holder));
 
     if (NS_SUCCEEDED(rv) && obj != aWin->GetGlobalJSObject()) {
-      JS::Rooted<JSObject*> dot_prototype(cx);
-      rv = proto_holder->GetJSObject(dot_prototype.address());
-      NS_ENSURE_SUCCESS(rv, rv);
+      JS::Rooted<JSObject*> dot_prototype(cx, proto_holder->GetJSObject());
+      NS_ENSURE_STATE(dot_prototype);
 
       const nsDOMClassInfoData *ci_data;
       if (name_struct->mType == nsGlobalNameStruct::eTypeClassConstructor) {
         ci_data = &sClassInfoData[name_struct->mDOMClassInfoID];
       } else {
         ci_data = name_struct->mData;
       }
 
@@ -4516,19 +4488,18 @@ nsWindowSH::GlobalResolve(nsGlobalWindow
     // We need to use the XPConnect prototype for the DOM class that this
     // constructor is an alias for (for example for Image we need the prototype
     // for HTMLImageElement).
     nsCOMPtr<nsIXPConnectJSObjectHolder> proto_holder;
     rv = GetXPCProto(sXPConnect, cx, aWin, alias_struct,
                      getter_AddRefs(proto_holder));
     NS_ENSURE_SUCCESS(rv, rv);
 
-    JSObject* dot_prototype;
-    rv = proto_holder->GetJSObject(&dot_prototype);
-    NS_ENSURE_SUCCESS(rv, rv);
+    JSObject* dot_prototype = proto_holder->GetJSObject();
+    NS_ENSURE_STATE(dot_prototype);
 
     const nsDOMClassInfoData *ci_data;
     if (alias_struct->mType == nsGlobalNameStruct::eTypeClassConstructor) {
       ci_data = &sClassInfoData[alias_struct->mDOMClassInfoID];
     } else if (alias_struct->mType == nsGlobalNameStruct::eTypeExternalClassInfo) {
       ci_data = alias_struct->mData;
     } else {
       return NS_ERROR_UNEXPECTED;
@@ -4550,19 +4521,17 @@ nsWindowSH::GlobalResolve(nsGlobalWindow
     nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
     rv = WrapNative(cx, obj, constructor, &NS_GET_IID(nsIDOMDOMConstructor),
                     false, val.address(), getter_AddRefs(holder));
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = constructor->Install(cx, obj, val);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    JSObject* class_obj;
-    holder->GetJSObject(&class_obj);
-    NS_ASSERTION(class_obj, "Why didn't we get a JSObject?");
+    NS_ASSERTION(holder->GetJSObject(), "Why didn't we get a JSObject?");
 
     *did_resolve = true;
 
     return NS_OK;
   }
 
   if (name_struct->mType == nsGlobalNameStruct::eTypeProperty) {
     if (name_struct->mChromeOnly && !nsContentUtils::IsCallerChrome())
@@ -4897,18 +4866,17 @@ nsWindowSH::NewResolve(nsIXPConnectWrapp
     // here) since we must define window.location to prevent the
     // getter from being overriden (for security reasons).
 
     nsCOMPtr<nsIDOMLocation> location;
     nsresult rv = win->GetLocation(getter_AddRefs(location));
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Make sure we wrap the location object in the window's scope.
-    JS::Rooted<JSObject*> scope(cx);
-    wrapper->GetJSObject(scope.address());
+    JS::Rooted<JSObject*> scope(cx, wrapper->GetJSObject());
 
     nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
     JS::Rooted<JS::Value> v(cx);
     rv = WrapNative(cx, scope, location, &NS_GET_IID(nsIDOMLocation), true,
                     v.address(), getter_AddRefs(holder));
     NS_ENSURE_SUCCESS(rv, rv);
 
     JSBool ok = JS_WrapValue(cx, v.address()) &&
@@ -5081,18 +5049,17 @@ nsWindowSH::NewResolve(nsIXPConnectWrapp
     return rv;
   }
 
   // Make a fast expando if we're assigning to (not declaring or
   // binding a name) a new undefined property that's not already
   // defined on our prototype chain. This way we can access this
   // expando w/o ever getting back into XPConnect.
   if (flags & JSRESOLVE_ASSIGNING) {
-    JS::Rooted<JSObject*> realObj(cx);
-    wrapper->GetJSObject(realObj.address());
+    JS::Rooted<JSObject*> realObj(cx, wrapper->GetJSObject());
 
     if (obj == realObj) {
       JS::Rooted<JSObject*> proto(cx);
       if (!js::GetObjectProto(cx, obj, &proto)) {
           *_retval = JS_FALSE;
           return NS_OK;
       }
       if (proto) {
@@ -5927,23 +5894,17 @@ nsNamedArraySH::NewResolve(nsIXPConnectW
                            JSObject **objp, bool *_retval)
 {
   JS::Rooted<JSObject*> obj(cx, aObj);
   JS::Rooted<jsid> id(cx, aId);
   if ((!(JSRESOLVE_ASSIGNING & flags)) && JSID_IS_STRING(id) &&
       !ObjectIsNativeWrapper(cx, obj)) {
 
     {
-      JS::Rooted<JSObject*> realObj(cx);
-
-      if (wrapper) {
-        wrapper->GetJSObject(realObj.address());
-      } else {
-        realObj = obj;
-      }
+      JS::Rooted<JSObject*> realObj(cx, wrapper ? wrapper->GetJSObject() : obj);
 
       JSAutoCompartment ac(cx, realObj);
       JS::Rooted<JSObject*> proto(cx);
       if (!::JS_GetPrototype(cx, realObj, proto.address())) {
         return NS_ERROR_FAILURE;
       }
 
       if (proto) {
@@ -6923,18 +6884,17 @@ nsStorage2SH::NewResolve(nsIXPConnectWra
                          JSObject *obj, jsid aId, uint32_t flags,
                          JSObject **objp, bool *_retval)
 {
   JS::Rooted<jsid> id(cx, aId);
   if (ObjectIsNativeWrapper(cx, obj)) {
     return NS_OK;
   }
 
-  JS::Rooted<JSObject*> realObj(cx);
-  wrapper->GetJSObject(realObj.address());
+  JS::Rooted<JSObject*> realObj(cx, wrapper->GetJSObject());
 
   JSAutoCompartment ac(cx, realObj);
 
   // First check to see if the property is defined on our prototype,
   // after converting id to a string if it's an integer.
 
   JS::Rooted<JSString*> jsstr(cx, IdToString(cx, id));
   if (!jsstr) {
--- a/dom/base/nsDOMClassInfoClasses.h
+++ b/dom/base/nsDOMClassInfoClasses.h
@@ -23,17 +23,16 @@ DOMCI_CLASS(Element)
 DOMCI_CLASS(Event)
 DOMCI_CLASS(MutationEvent)
 DOMCI_CLASS(UIEvent)
 DOMCI_CLASS(MouseEvent)
 DOMCI_CLASS(MouseScrollEvent)
 DOMCI_CLASS(WheelEvent)
 DOMCI_CLASS(DragEvent)
 DOMCI_CLASS(ClipboardEvent)
-DOMCI_CLASS(KeyboardEvent)
 DOMCI_CLASS(CompositionEvent)
 #define MOZ_GENERATED_EVENT_LIST
 #define MOZ_GENERATED_EVENT(_event_interface) DOMCI_CLASS(_event_interface)
 #include "GeneratedEvents.h"
 #undef MOZ_GENERATED_EVENT_LIST
 DOMCI_CLASS(DeviceMotionEvent)
 DOMCI_CLASS(DeviceAcceleration)
 DOMCI_CLASS(DeviceRotationRate)
@@ -235,10 +234,9 @@ DOMCI_CLASS(LockedFile)
 
 DOMCI_CLASS(CSSFontFeatureValuesRule)
 
 #ifdef MOZ_TIME_MANAGER
 DOMCI_CLASS(MozTimeManager)
 #endif
 
 #ifdef MOZ_WEBRTC
-DOMCI_CLASS(DataChannel)
 #endif
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -2125,17 +2125,17 @@ CreateNativeGlobalForInner(JSContext* aC
 
   nsRefPtr<nsIXPConnectJSObjectHolder> jsholder;
   nsresult rv = xpc->InitClassesWithNewWrappedGlobal(
     aCx, ToSupports(aNewInner),
     aPrincipal, flags, zoneSpec, getter_AddRefs(jsholder));
   NS_ENSURE_SUCCESS(rv, rv);
 
   MOZ_ASSERT(jsholder);
-  jsholder->GetJSObject(aNativeGlobal);
+  *aNativeGlobal = jsholder->GetJSObject();
   jsholder.forget(aHolder);
 
   // Set the location information for the new global, so that tools like
   // about:memory may use that information
   MOZ_ASSERT(*aNativeGlobal);
   xpc::SetLocationForGlobal(*aNativeGlobal, aURI);
 
   return NS_OK;
--- a/dom/bindings/Bindings.conf
+++ b/dom/bindings/Bindings.conf
@@ -226,16 +226,20 @@ DOMInterfaces = {
 'CSSValue': {
   'concrete': False
 },
 
 'CSSValueList': {
   'nativeType': 'nsDOMCSSValueList'
 },
 
+'DataChannel': {
+    'nativeType': 'nsDOMDataChannel',
+},
+
 'DataContainerEvent': {
     'nativeType': 'nsDOMDataContainerEvent',
 },
 
 'DelayNode': [
 {
     'resultNotAddRefed': [ 'delayTime' ],
 }],
@@ -559,16 +563,20 @@ DOMInterfaces = {
 {
     'workers': True,
 }],
 
 'KeyboardEvent': {
     'nativeType': 'nsDOMKeyboardEvent',
 },
 
+'KeyEvent': {
+    'concrete': False
+},
+
 'LocalMediaStream': {
     'headerFile': 'DOMMediaStream.h',
     'nativeType': 'mozilla::DOMLocalMediaStream'
 },
 
 'Location': {
     # NOTE: Before you turn on codegen for Location, make sure all the
     # Unforgeable stuff is dealt with.
--- a/dom/bindings/CallbackObject.h
+++ b/dom/bindings/CallbackObject.h
@@ -338,18 +338,18 @@ public:
 
     nsCOMPtr<nsIXPConnectWrappedJS> wrappedJS = do_QueryInterface(callback);
     if (!wrappedJS) {
       return nullptr;
     }
 
     AutoSafeJSContext cx;
 
-    JS::Rooted<JSObject*> obj(cx);
-    if (NS_FAILED(wrappedJS->GetJSObject(obj.address())) || !obj) {
+    JS::Rooted<JSObject*> obj(cx, wrappedJS->GetJSObject());
+    if (!obj) {
       return nullptr;
     }
 
     JSAutoCompartment ac(cx, obj);
 
     nsRefPtr<WebIDLCallbackT> newCallback = new WebIDLCallbackT(obj);
     return newCallback.forget();
   }
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -6052,17 +6052,17 @@ class ClassMethod(ClassItem):
         args = ', '.join([a.define() for a in self.args])
 
         body = CGIndenter(CGGeneric(self.getBody())).define()
 
         return string.Template("""${templateClause}${decorators}${returnType}
 ${className}::${name}(${args})${const}
 {
 ${body}
-}\n
+}
 """).substitute({ 'templateClause': templateClause,
                   'decorators': self.getDecorators(False),
                   'returnType': self.returnType,
                   'className': cgClass.getNameString(),
                   'name': self.name,
                   'args': args,
                   'const': ' const' if self.const else '',
                   'body': body })
@@ -6091,17 +6091,17 @@ class ClassConstructor(ClassItem):
     """
     def __init__(self, args, inline=False, bodyInHeader=False,
                  visibility="private", explicit=False, baseConstructors=None,
                  body=""):
         self.args = args
         self.inline = inline or bodyInHeader
         self.bodyInHeader = bodyInHeader
         self.explicit = explicit
-        self.baseConstructors = baseConstructors
+        self.baseConstructors = baseConstructors or []
         self.body = body
         ClassItem.__init__(self, None, visibility)
 
     def getDecorators(self, declaring):
         decorators = []
         if self.explicit:
             decorators.append('explicit')
         if self.inline and declaring:
@@ -6109,17 +6109,17 @@ class ClassConstructor(ClassItem):
         if decorators:
             return ' '.join(decorators) + ' '
         return ''
 
     def getInitializationList(self, cgClass):
         items = [str(c) for c in self.baseConstructors]
         for m in cgClass.members:
             if not m.static:
-                initialize = m.getBody()
+                initialize = m.body
                 if initialize:
                     items.append(m.name + "(" + initialize + ")")
             
         if len(items) > 0:
             return '\n  : ' + ',\n    '.join(items)
         return ''
 
     def getBody(self):
@@ -6150,17 +6150,17 @@ class ClassConstructor(ClassItem):
 
         body = '  ' + self.getBody()
         body = '\n' + stripTrailingWhitespace(body.replace('\n', '\n  '))
         if len(body) > 0:
             body += '\n'
 
         return string.Template("""${decorators}
 ${className}::${className}(${args})${initializationList}
-{${body}}\n
+{${body}}
 """).substitute({ 'decorators': self.getDecorators(False),
                   'className': cgClass.getNameString(),
                   'args': args,
                   'initializationList': self.getInitializationList(cgClass),
                   'body': body })
 
 class ClassDestructor(ClassItem):
     """
@@ -6220,17 +6220,17 @@ class ClassDestructor(ClassItem):
 
         body = '  ' + self.getBody()
         body = '\n' + stripTrailingWhitespace(body.replace('\n', '\n  '))
         if len(body) > 0:
             body += '\n'
 
         return string.Template("""${decorators}
 ${className}::~${className}()
-{${body}}\n
+{${body}}
 """).substitute({ 'decorators': self.getDecorators(False),
                   'className': cgClass.getNameString(),
                   'body': body })
 
 class ClassMember(ClassItem):
     def __init__(self, name, type, visibility="private", static=False,
                  body=None):
         self.type = type;
@@ -6284,17 +6284,18 @@ class ClassEnum(ClassItem):
     def define(self, cgClass):
         # Only goes in the header
         return ''
 
 class CGClass(CGThing):
     def __init__(self, name, bases=[], members=[], constructors=[],
                  destructor=None, methods=[],
                  typedefs = [], enums=[], templateArgs=[],
-                 templateSpecialization=[], isStruct=False, indent='',
+                 templateSpecialization=[], isStruct=False,
+                 disallowCopyConstruction=False, indent='',
                  decorators='',
                  extradeclarations='',
                  extradefinitions=''):
         CGThing.__init__(self)
         self.name = name
         self.bases = bases
         self.members = members
         self.constructors = constructors
@@ -6302,16 +6303,17 @@ class CGClass(CGThing):
         # code wants lists of members.
         self.destructors = [destructor] if destructor else []
         self.methods = methods
         self.typedefs = typedefs
         self.enums = enums
         self.templateArgs = templateArgs
         self.templateSpecialization = templateSpecialization
         self.isStruct = isStruct
+        self.disallowCopyConstruction = disallowCopyConstruction
         self.indent = indent
         self.defaultVisibility ='public' if isStruct else 'private'
         self.decorators = decorators
         self.extradeclarations = extradeclarations
         self.extradefinitions = extradefinitions
 
     def getNameString(self):
         className = self.name
@@ -6387,19 +6389,30 @@ class CGClass(CGThing):
                             result = result + separator
                         declaration = member.declare(cgClass)
                         declaration = CGIndenter(CGGeneric(declaration)).define()
                         result = result + declaration
                         itemCount = itemCount + 1
                     lastVisibility = visibility
             return (result, lastVisibility, itemCount)
 
+        if self.disallowCopyConstruction:
+            class DisallowedCopyConstructor(object):
+                def __init__(self):
+                    self.visibility = "private"
+                def declare(self, cgClass):
+                    name = cgClass.getNameString()
+                    return "%s(const %s&) MOZ_DELETE;\n" % (name, name)
+            disallowedCopyConstructors = [DisallowedCopyConstructor()]
+        else:
+            disallowedCopyConstructors = []
+
         order = [(self.enums, ''), (self.typedefs, ''), (self.members, ''),
-                 (self.constructors, '\n'), (self.destructors, '\n'),
-                 (self.methods, '\n')]
+                 (self.constructors + disallowedCopyConstructors, '\n'),
+                 (self.destructors, '\n'), (self.methods, '\n')]
 
         lastVisibility = self.defaultVisibility
         itemCount = 0
         for (memberList, separator) in order:
             (memberString, lastVisibility, itemCount) = \
                 declareMembers(self, memberList, lastVisibility, itemCount,
                                separator)
             if self.indent:
@@ -6411,21 +6424,24 @@ class CGClass(CGThing):
         return result
 
     def define(self):
         def defineMembers(cgClass, memberList, itemCount, separator=''):
             result = ''
             for member in memberList:
                 if itemCount != 0:
                     result = result + separator
-                result = result + member.define(cgClass)
-                itemCount = itemCount + 1
+                definition = member.define(cgClass)
+                if definition:
+                    # Member variables would only produce empty lines here.
+                    result += definition
+                    itemCount += 1
             return (result, itemCount)
 
-        order = [(self.members, '\n'), (self.constructors, '\n'),
+        order = [(self.members, ''), (self.constructors, '\n'),
                  (self.destructors, '\n'), (self.methods, '\n')]
 
         result = self.extradefinitions
         itemCount = 0
         for (memberList, separator) in order:
             (memberString, itemCount) = defineMembers(self, memberList,
                                                       itemCount, separator)
             result = result + memberString
@@ -7487,188 +7503,214 @@ class CGNamespacedEnum(CGThing):
     def define(self):
         assert False # Only for headers.
 
 class CGDictionary(CGThing):
     def __init__(self, dictionary, descriptorProvider):
         self.dictionary = dictionary
         self.descriptorProvider = descriptorProvider
         self.workers = descriptorProvider.workers
+        # NOTE: jsids are per-runtime, so don't use them in workers
         self.needToInitIds = not self.workers and len(dictionary.members) > 0
         self.memberInfo = [
             (member,
              getJSToNativeConversionInfo(member.type,
                                          descriptorProvider,
                                          isMember="Dictionary",
                                          isOptional=(not member.defaultValue),
                                          defaultValue=member.defaultValue))
             for member in dictionary.members ]
+        self.structs = self.getStructs()
 
     def declare(self):
-        d = self.dictionary
-        if d.parent:
-            inheritance = "%s" % self.makeClassName(d.parent)
-        elif not self.workers:
-            inheritance = "MainThreadDictionaryBase"
-        else:
-            inheritance = "DictionaryBase"
-        memberDecls = ["  %s %s;" %
-                       (self.getMemberType(m),
-                        self.makeMemberName(m[0].identifier.name))
-                       for m in self.memberInfo]
-
-        return (string.Template(
-                "struct ${selfName} : public ${inheritance} {\n"
-                "  ${selfName}() {}\n"
-                "  bool Init(JSContext* cx, JS::Handle<JS::Value> val);\n" +
-                ("  bool Init(const nsAString& aJSON);\n" if not self.workers else "") +
-                "  bool ToObject(JSContext* cx, JS::Handle<JSObject*> parentObject, JS::Value *vp) const;\n"
-                "  void TraceDictionary(JSTracer* trc);\n"
-                "\n" +
-                "\n".join(memberDecls) + "\n"
-                "private:\n"
-                "  // Disallow copy-construction\n"
-                "  ${selfName}(const ${selfName}&) MOZ_DELETE;\n" +
-                # NOTE: jsids are per-runtime, so don't use them in workers
-                ("  static bool InitIds(JSContext* cx);\n"
-                 "  static bool initedIds;\n" if self.needToInitIds else "") +
-                "\n".join("  static jsid " +
-                          self.makeIdName(m.identifier.name) + ";" for
-                          m in d.members) + "\n"
-                "};\n"
-                "struct ${selfName}Initializer : public ${selfName} {\n"
-                "  ${selfName}Initializer() {\n"
-                "    // Safe to pass a null context if we pass a null value\n"
-                "    Init(nullptr, JS::NullHandleValue);\n"
-                "  }\n"
-                "};").substitute( { "selfName": self.makeClassName(d),
-                                    "inheritance": inheritance }))
+        return self.structs.declare()
 
     def define(self):
-        d = self.dictionary
-        if d.parent:
-            initParent = ("// Per spec, we init the parent's members first\n"
-                          "if (!%s::Init(cx, val)) {\n"
-                          "  return false;\n"
-                          "}\n" % self.makeClassName(d.parent))
-            toObjectParent = ("// Per spec, we define the parent's members first\n"
-                              "if (!%s::ToObject(cx, parentObject, vp)) {\n"
-                              "  return false;\n"
-                              "}\n" % self.makeClassName(d.parent))
-            ensureObject = "JS::Rooted<JSObject*> obj(cx, &vp->toObject());\n"
-            traceParent = ("%s::TraceDictionary(trc);\n" %
-                           self.makeClassName(d.parent))
-        else:
-            initParent = ""
-            toObjectParent = ""
-            ensureObject = ("JS::Rooted<JSObject*> obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));\n"
-                            "if (!obj) {\n"
-                            "  return false;\n"
-                            "}\n"
-                            "*vp = JS::ObjectValue(*obj);\n")
-            traceParent = ""
-
-        memberInits = [CGIndenter(self.getMemberConversion(m)).define()
+        return self.structs.define()
+
+    def base(self):
+        if self.dictionary.parent:
+            return self.makeClassName(self.dictionary.parent)
+        if not self.workers:
+            return "MainThreadDictionaryBase"
+        return "DictionaryBase"
+
+    def initMethod(self):
+        body = (
+            "// Passing a null JSContext is OK only if we're initing from null,\n"
+            "// Since in that case we will not have to do any property gets\n"
+            "MOZ_ASSERT_IF(!cx, val.isNull());\n")
+
+        if self.needToInitIds:
+            body += (
+                "if (cx && !initedIds && !InitIds(cx)) {\n"
+                "  return false;\n"
+                "}\n")
+
+        if self.dictionary.parent:
+            body += (
+                "// Per spec, we init the parent's members first\n"
+                "if (!%s::Init(cx, val)) {\n"
+                "  return false;\n"
+                "}\n") % self.makeClassName(self.dictionary.parent)
+
+        memberInits = [self.getMemberConversion(m).define()
                        for m in self.memberInfo]
+        if memberInits:
+            body += (
+                "JSBool found;\n"
+                "JS::Rooted<JS::Value> temp(cx);\n"
+                "bool isNull = val.isNullOrUndefined();\n")
+
+        body += (
+            "if (!IsConvertibleToDictionary(cx, val)) {\n"
+            "  return ThrowErrorMessage(cx, MSG_NOT_DICTIONARY);\n"
+            "}\n"
+            "\n")
+
+        if memberInits:
+            body += "\n\n".join(memberInits) + "\n"
+
+        body += "return true;"
+
+        return ClassMethod("Init", "bool", [
+            Argument('JSContext*', 'cx'),
+            Argument('JS::Handle<JS::Value>', 'val'),
+        ], body=body)
+
+    def initFromJSONMethod(self):
+        assert not self.workers
+        return ClassMethod("Init", "bool", [
+                Argument('const nsAString&', 'aJSON'),
+            ], body=(
+                "AutoSafeJSContext cx;\n"
+                "JSAutoRequest ar(cx);\n"
+                "JS::Rooted<JS::Value> json(cx);\n"
+                "bool ok = ParseJSON(cx, aJSON, &json);\n"
+                "NS_ENSURE_TRUE(ok, false);\n"
+                "return Init(cx, json);"
+            ))
+
+    def toObjectMethod(self):
+        body = ""
+        if self.needToInitIds:
+            body += (
+                "if (!initedIds && !InitIds(cx)) {\n"
+                "  return false;\n"
+                "}\n")
+
+        if self.dictionary.parent:
+            body += (
+                "// Per spec, we define the parent's members first\n"
+                "if (!%s::ToObject(cx, parentObject, vp)) {\n"
+                "  return false;\n"
+                "}\n"
+                "JS::Rooted<JSObject*> obj(cx, &vp->toObject());\n"
+                "\n") % self.makeClassName(self.dictionary.parent)
+        else:
+            body += (
+                "JS::Rooted<JSObject*> obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));\n"
+                "if (!obj) {\n"
+                "  return false;\n"
+                "}\n"
+                "*vp = JS::ObjectValue(*obj);\n"
+                "\n")
+
+        body += "\n\n".join(self.getMemberDefinition(m).define()
+                            for m in self.memberInfo)
+        body += "\n\nreturn true;"
+
+        return ClassMethod("ToObject", "bool", [
+            Argument('JSContext*', 'cx'),
+            Argument('JS::Handle<JSObject*>', 'parentObject'),
+            Argument('JS::Value*', 'vp'),
+        ], const=True, body=body)
+
+    def initIdsMethod(self):
+        assert self.needToInitIds
         idinit = [CGGeneric('!InternJSString(cx, %s, "%s")' %
                             (m.identifier.name + "_id", m.identifier.name))
-                  for m in d.members]
+                  for m in self.dictionary.members]
         idinit = CGList(idinit, " ||\n")
         idinit = CGWrapper(idinit, pre="if (",
                            post=(") {\n"
                                  "  return false;\n"
                                  "}"),
                            reindent=True)
-        memberDefines = [CGIndenter(self.getMemberDefinition(m)).define()
-                         for m in self.memberInfo]
-        memberTraces = [CGIndenter(self.getMemberTrace(m)).define()
+        body = (
+           "MOZ_ASSERT(!initedIds);\n"
+           "%s\n"
+           "initedIds = true;\n"
+           "return true;") % idinit.define()
+
+        return ClassMethod("InitIds", "bool", [
+            Argument("JSContext*", "cx"),
+        ], static=True, body=body, visibility="private")
+
+    def traceDictionaryMethod(self):
+        body = ""
+        if self.dictionary.parent:
+            cls = self.makeClassName(self.dictionary.parent)
+            body += "%s::TraceDictionary(trc);\n" % cls
+
+        memberTraces = [self.getMemberTrace(m)
                         for m in self.dictionary.members
                         if typeNeedsCx(m.type, self.descriptorProvider)]
 
-        return string.Template(
-            # NOTE: jsids are per-runtime, so don't use them in workers
-            ("bool ${selfName}::initedIds = false;\n" +
-             "\n".join("jsid ${selfName}::%s = JSID_VOID;" %
-                       self.makeIdName(m.identifier.name)
-                       for m in d.members) + "\n"
-             "\n"
-             "bool\n"
-             "${selfName}::InitIds(JSContext* cx)\n"
-             "{\n"
-             "  MOZ_ASSERT(!initedIds);\n"
-             "${idInit}\n"
-             "  initedIds = true;\n"
-             "  return true;\n"
-             "}\n"
-             "\n" if self.needToInitIds else "") +
-            "bool\n"
-            "${selfName}::Init(JSContext* cx, JS::Handle<JS::Value> val)\n"
-            "{\n"
-            "  // Passing a null JSContext is OK only if we're initing from null,\n"
-            "  // Since in that case we will not have to do any property gets\n"
-            "  MOZ_ASSERT_IF(!cx, val.isNull());\n" +
-            # NOTE: jsids are per-runtime, so don't use them in workers
-            ("  if (cx && !initedIds && !InitIds(cx)) {\n"
-             "    return false;\n"
-             "  }\n" if self.needToInitIds else "") +
-            "${initParent}" +
-            ("  JSBool found;\n"
-             "  JS::Rooted<JS::Value> temp(cx);\n"
-             "  bool isNull = val.isNullOrUndefined();\n" if len(memberInits) > 0 else "") +
-            "  if (!IsConvertibleToDictionary(cx, val)) {\n"
-            "    return ThrowErrorMessage(cx, MSG_NOT_DICTIONARY);\n"
-            "  }\n"
-            "\n"
-            "${initMembers}\n"
-            "  return true;\n"
-            "}\n"
-            "\n" +
-            ("bool\n"
-             "${selfName}::Init(const nsAString& aJSON)\n"
-             "{\n"
-             "  AutoSafeJSContext cx;\n"
-             "  JSAutoRequest ar(cx);\n"
-             "  JS::Rooted<JS::Value> json(cx);\n"
-             "  bool ok = ParseJSON(cx, aJSON, &json);\n"
-             "  NS_ENSURE_TRUE(ok, false);\n"
-             "  return Init(cx, json);\n"
-             "}\n" if not self.workers else "") +
-            "\n"
-            "bool\n"
-            "${selfName}::ToObject(JSContext* cx, JS::Handle<JSObject*> parentObject, JS::Value *vp) const\n"
-            "{\n" +
-            # NOTE: jsids are per-runtime, so don't use them in workers
-            ("  if (!initedIds && !InitIds(cx)) {\n"
-             "    return false;\n"
-             "  }\n" if self.needToInitIds else "") +
-            "${toObjectParent}"
-            "${ensureObject}"
-            "\n"
-            "${defineMembers}\n"
-            "\n"
-            "  return true;\n"
-            "}\n"
-            "\n"
-            "void\n"
-            "${selfName}::TraceDictionary(JSTracer* trc)\n"
-            "{\n"
-            "${traceParent}"
-            "${traceMembers}\n"
-            "}").substitute({
-                "selfName": self.makeClassName(d),
-                "initParent": CGIndenter(CGGeneric(initParent)).define(),
-                "initMembers": "\n\n".join(memberInits),
-                "idInit": CGIndenter(idinit).define(),
-                "isMainThread": toStringBool(not self.workers),
-                "toObjectParent": CGIndenter(CGGeneric(toObjectParent)).define(),
-                "ensureObject": CGIndenter(CGGeneric(ensureObject)).define(),
-                "traceMembers": "\n\n".join(memberTraces),
-                "traceParent": CGIndenter(CGGeneric(traceParent)).define(),
-                "defineMembers": "\n\n".join(memberDefines)
-                })
+        body += "\n\n".join(memberTraces)
+
+        return ClassMethod("TraceDictionary", "void", [
+            Argument("JSTracer*", "trc"),
+        ], body=body)
+
+    def getStructs(self):
+        d = self.dictionary
+        selfName = self.makeClassName(d)
+        members = [ClassMember(self.makeMemberName(m[0].identifier.name),
+                               self.getMemberType(m),
+                               visibility="public") for m in self.memberInfo]
+        ctor = ClassConstructor([], bodyInHeader=True, visibility="public")
+        methods = []
+
+        if self.needToInitIds:
+            methods.append(self.initIdsMethod())
+            members.append(ClassMember("initedIds", "bool", static=True, body="false"))
+            members.extend(
+                ClassMember(self.makeIdName(m.identifier.name), "jsid", static=True, body="JSID_VOID")
+                for m in d.members)
+
+        methods.append(self.initMethod())
+
+        if not self.workers:
+            methods.append(self.initFromJSONMethod())
+
+        methods.append(self.toObjectMethod())
+        methods.append(self.traceDictionaryMethod())
+
+        struct = CGClass(selfName,
+            bases=[ClassBase(self.base())],
+            members=members,
+            constructors=[ctor],
+            methods=methods,
+            isStruct=True,
+            disallowCopyConstruction=True)
+
+
+        initializerCtor = ClassConstructor([],
+            bodyInHeader=True,
+            visibility="public",
+            body=(
+                "// Safe to pass a null context if we pass a null value\n"
+                "Init(nullptr, JS::NullHandleValue);"))
+        initializerStruct = CGClass(selfName + "Initializer",
+            bases=[ClassBase(selfName)],
+            constructors=[initializerCtor],
+            isStruct=True)
+
+        return CGList([struct, initializerStruct])
 
     def deps(self):
         return self.dictionary.getDeps()
 
     @staticmethod
     def makeDictionaryName(dictionary, workers):
         suffix = "Workers" if workers else ""
         return dictionary.identifier.name + suffix
@@ -7838,17 +7880,17 @@ class CGDictionary(CGThing):
             if type.nullable():
                 trace = CGIfWrapper(trace, "!%s.IsNull()" % memberNullable)
         else:
             assert 0 # unknown type
 
         if not member.defaultValue:
             trace = CGIfWrapper(trace, "%s.WasPassed()" % memberLoc)
 
-        return trace
+        return trace.define()
 
     @staticmethod
     def makeIdName(name):
         return name + "_id"
 
     @staticmethod
     def getDictionaryDependenciesFromType(type):
         if type.isDictionary():
@@ -8950,17 +8992,18 @@ def genConstructorBody(descriptor, initC
     }
     // Extract the JS implementation from the XPCOM object.
     nsCOMPtr<nsIXPConnectWrappedJS> implWrapped = do_QueryInterface(implISupports);
     MOZ_ASSERT(implWrapped, "Failed to get wrapped JS from XPCOM component.");
     if (!implWrapped) {
       aRv.Throw(NS_ERROR_FAILURE);
       return nullptr;
     }
-    if (NS_FAILED(implWrapped->GetJSObject(jsImplObj.address()))) {
+    jsImplObj = implWrapped->GetJSObject();
+    if (!jsImplObj) {
       aRv.Throw(NS_ERROR_FAILURE);
       return nullptr;
     }
   }
   // Build the C++ implementation.
   nsRefPtr<${implClass}> impl = new ${implClass}(jsImplObj, window);${initCall}
   return impl.forget();""").substitute({"implClass" : descriptor.name,
                  "contractId" : descriptor.interface.getJSImplementation(),
--- a/dom/bluetooth/BluetoothOppManager.cpp
+++ b/dom/bluetooth/BluetoothOppManager.cpp
@@ -24,17 +24,17 @@
 #include "nsIObserverService.h"
 #include "nsIDOMFile.h"
 #include "nsIFile.h"
 #include "nsIInputStream.h"
 #include "nsIMIMEService.h"
 #include "nsIOutputStream.h"
 #include "nsNetUtil.h"
 
-#define TARGET_SUBDIR "downloads/bluetooth/"
+#define TARGET_SUBDIR "Download/Bluetooth/"
 
 USING_BLUETOOTH_NAMESPACE
 using namespace mozilla;
 using namespace mozilla::ipc;
 
 class BluetoothOppManagerObserver : public nsIObserver
 {
 public:
--- a/dom/bluetooth/BluetoothService.cpp
+++ b/dom/bluetooth/BluetoothService.cpp
@@ -746,17 +746,17 @@ BluetoothService::Observe(nsISupports* a
 
   MOZ_ASSERT(false, "BluetoothService got unexpected topic!");
   return NS_ERROR_UNEXPECTED;
 }
 
 void
 BluetoothService::Notify(const BluetoothSignal& aData)
 {
-  nsString type;
+  nsString type = NS_LITERAL_STRING("bluetooth-pairing-request");
 
   JSContext* cx = nsContentUtils::GetSafeJSContext();
   NS_ASSERTION(!::JS_IsExceptionPending(cx),
                "Shouldn't get here when an exception is pending!");
 
   JSAutoRequest jsar(cx);
   JSObject* obj = JS_NewObject(cx, NULL, NULL, NULL);
   if (!obj) {
@@ -767,46 +767,42 @@ BluetoothService::Notify(const Bluetooth
   if (!SetJsObject(cx, aData.value(), obj)) {
     NS_WARNING("Failed to set properties of system message!");
     return;
   }
 
   BT_LOG("[S] %s: %s", __FUNCTION__, NS_ConvertUTF16toUTF8(aData.name()).get());
 
   if (aData.name().EqualsLiteral("RequestConfirmation")) {
-    NS_ASSERTION(aData.value().get_ArrayOfBluetoothNamedValue().Length() == 3,
+    NS_ASSERTION(aData.value().get_ArrayOfBluetoothNamedValue().Length() == 4,
       "RequestConfirmation: Wrong length of parameters");
-    type.AssignLiteral("bluetooth-requestconfirmation");
   } else if (aData.name().EqualsLiteral("RequestPinCode")) {
-    NS_ASSERTION(aData.value().get_ArrayOfBluetoothNamedValue().Length() == 2,
+    NS_ASSERTION(aData.value().get_ArrayOfBluetoothNamedValue().Length() == 3,
       "RequestPinCode: Wrong length of parameters");
-    type.AssignLiteral("bluetooth-requestpincode");
   } else if (aData.name().EqualsLiteral("RequestPasskey")) {
-    NS_ASSERTION(aData.value().get_ArrayOfBluetoothNamedValue().Length() == 2,
+    NS_ASSERTION(aData.value().get_ArrayOfBluetoothNamedValue().Length() == 3,
       "RequestPinCode: Wrong length of parameters");
-    type.AssignLiteral("bluetooth-requestpasskey");
   } else if (aData.name().EqualsLiteral("Authorize")) {
     NS_ASSERTION(aData.value().get_ArrayOfBluetoothNamedValue().Length() == 2,
       "Authorize: Wrong length of parameters");
     type.AssignLiteral("bluetooth-authorize");
   } else if (aData.name().EqualsLiteral("Cancel")) {
     NS_ASSERTION(aData.value().get_ArrayOfBluetoothNamedValue().Length() == 0,
       "Cancel: Wrong length of parameters");
     type.AssignLiteral("bluetooth-cancel");
   } else if (aData.name().EqualsLiteral("PairedStatusChanged")) {
     NS_ASSERTION(aData.value().get_ArrayOfBluetoothNamedValue().Length() == 1,
       "PairedStatusChagned: Wrong length of parameters");
     type.AssignLiteral("bluetooth-pairedstatuschanged");
   } else {
-#ifdef DEBUG
     nsCString warningMsg;
     warningMsg.AssignLiteral("Not handling service signal: ");
     warningMsg.Append(NS_ConvertUTF16toUTF8(aData.name()));
     NS_WARNING(warningMsg.get());
-#endif
+    return;
   }
 
   nsCOMPtr<nsISystemMessagesInternal> systemMessenger =
     do_GetService("@mozilla.org/system-message-internal;1");
   NS_ENSURE_TRUE_VOID(systemMessenger);
 
   systemMessenger->BroadcastMessage(type, OBJECT_TO_JSVAL(obj));
 }
--- a/dom/bluetooth/linux/BluetoothDBusService.cpp
+++ b/dom/bluetooth/linux/BluetoothDBusService.cpp
@@ -515,16 +515,19 @@ AgentEventFilter(DBusConnection *conn, D
                                DBUS_TYPE_INVALID)) {
       BT_WARNING("%s: Invalid arguments: RequestConfirmation()", __FUNCTION__);
       errorStr.AssignLiteral("Invalid arguments: RequestConfirmation()");
     } else {
       parameters.AppendElement(BluetoothNamedValue(
                                  NS_LITERAL_STRING("path"),
                                  NS_ConvertUTF8toUTF16(objectPath)));
       parameters.AppendElement(BluetoothNamedValue(
+                                 NS_LITERAL_STRING("method"),
+                                 NS_LITERAL_STRING("confirmation")));
+      parameters.AppendElement(BluetoothNamedValue(
                                  NS_LITERAL_STRING("passkey"),
                                  passkey));
 
       KeepDBusPairingMessage(GetAddressFromObjectPath(
                                NS_ConvertUTF8toUTF16(objectPath)), msg);
 
       BluetoothSignal signal(signalName, signalPath, parameters);
 
@@ -548,16 +551,19 @@ AgentEventFilter(DBusConnection *conn, D
                                DBUS_TYPE_INVALID)) {
       BT_WARNING("%s: Invalid arguments for RequestPinCode() method",
                  __FUNCTION__);
       errorStr.AssignLiteral("Invalid arguments for RequestPinCode() method");
     } else {
       parameters.AppendElement(BluetoothNamedValue(
                                  NS_LITERAL_STRING("path"),
                                  NS_ConvertUTF8toUTF16(objectPath)));
+      parameters.AppendElement(BluetoothNamedValue(
+                                 NS_LITERAL_STRING("method"),
+                                 NS_LITERAL_STRING("pincode")));
 
       KeepDBusPairingMessage(GetAddressFromObjectPath(
                                NS_ConvertUTF8toUTF16(objectPath)), msg);
 
       BluetoothSignal signal(signalName, signalPath, parameters);
 
       // Fire a Device properties fetcher at the main thread
       nsRefPtr<DevicePropertiesSignalHandler> b =
@@ -579,16 +585,19 @@ AgentEventFilter(DBusConnection *conn, D
                                DBUS_TYPE_INVALID)) {
       BT_WARNING("%s: Invalid arguments for RequestPasskey() method",
                  __FUNCTION__);
       errorStr.AssignLiteral("Invalid arguments for RequestPasskey() method");
     } else {
       parameters.AppendElement(BluetoothNamedValue(
                                  NS_LITERAL_STRING("path"),
                                  NS_ConvertUTF8toUTF16(objectPath)));
+      parameters.AppendElement(BluetoothNamedValue(
+                                 NS_LITERAL_STRING("method"),
+                                 NS_LITERAL_STRING("passkey")));
 
       KeepDBusPairingMessage(GetAddressFromObjectPath(
                                NS_ConvertUTF8toUTF16(objectPath)), msg);
 
       BluetoothSignal signal(signalName, signalPath, parameters);
 
       // Fire a Device properties fetcher at the main thread
       nsRefPtr<DevicePropertiesSignalHandler> b =
@@ -1843,67 +1852,53 @@ public:
   {
     MOZ_ASSERT(NS_IsMainThread());
   }
 
   NS_IMETHOD Run()
   {
     MOZ_ASSERT(!NS_IsMainThread());
 
-    BluetoothValue v = mSignal.value();
-    if (v.type() != BluetoothValue::TArrayOfBluetoothNamedValue ||
-        v.get_ArrayOfBluetoothNamedValue().Length() == 0) {
-      NS_WARNING("Invalid value type for GetDeviceProperties() method");
-      return NS_ERROR_FAILURE;
-    }
-
     const InfallibleTArray<BluetoothNamedValue>& arr =
-      v.get_ArrayOfBluetoothNamedValue();
-    NS_ASSERTION(arr[0].name().EqualsLiteral("path"),
-                 "failed to get object path");
-    NS_ASSERTION(arr[0].value().type() == BluetoothValue::TnsString,
-                 "failed to get_nsString");
+      mSignal.value().get_ArrayOfBluetoothNamedValue();
     nsString devicePath = arr[0].value().get_nsString();
 
     BluetoothValue prop;
-    if (!GetPropertiesInternal(devicePath, DBUS_DEVICE_IFACE, prop)) {
-      NS_WARNING("Getting properties failed!");
-      return NS_ERROR_FAILURE;
-    }
-    InfallibleTArray<BluetoothNamedValue>& properties =
-      prop.get_ArrayOfBluetoothNamedValue();
+    bool rv = GetPropertiesInternal(devicePath, DBUS_DEVICE_IFACE, prop);
+    NS_ENSURE_TRUE(rv, NS_ERROR_FAILURE);
 
     // Return original dbus message parameters and also device name
     // for agent events "RequestConfirmation", "RequestPinCode",
     // and "RequestPasskey"
     InfallibleTArray<BluetoothNamedValue>& parameters =
-      v.get_ArrayOfBluetoothNamedValue();
+      mSignal.value().get_ArrayOfBluetoothNamedValue();
 
     // Replace object path with device address
     nsString address = GetAddressFromObjectPath(devicePath);
     parameters[0].name().AssignLiteral("address");
     parameters[0].value() = address;
 
+    InfallibleTArray<BluetoothNamedValue>& properties =
+      prop.get_ArrayOfBluetoothNamedValue();
     uint8_t i;
     for (i = 0; i < properties.Length(); i++) {
       // Append device name
       if (properties[i].name().EqualsLiteral("Name")) {
         properties[i].name().AssignLiteral("name");
         parameters.AppendElement(properties[i]);
-        mSignal.value() = parameters;
         break;
       }
     }
-    NS_ASSERTION(i != properties.Length(), "failed to get device name");
+    MOZ_ASSERT(i != properties.Length(), "failed to get device name");
 
     nsRefPtr<DistributeBluetoothSignalTask> t =
       new DistributeBluetoothSignalTask(mSignal);
     if (NS_FAILED(NS_DispatchToMainThread(t))) {
-       NS_WARNING("Failed to dispatch to main thread!");
-       return NS_ERROR_FAILURE;
+      NS_WARNING("Failed to dispatch to main thread!");
+      return NS_ERROR_FAILURE;
     }
 
     return NS_OK;
   }
 
 private:
   BluetoothSignal mSignal;
 };
@@ -1983,23 +1978,40 @@ private:
   nsTArray<nsString> mDeviceAddresses;
   nsRefPtr<BluetoothReplyRunnable> mRunnable;
   FilterFunc mFilterFunc;
 };
 
 nsresult
 BluetoothDBusService::GetDevicePropertiesInternal(const BluetoothSignal& aSignal)
 {
-  NS_ASSERTION(NS_IsMainThread(), "Must be called from main thread!");
+  MOZ_ASSERT(NS_IsMainThread());
 
   if (!mConnection || !gThreadConnection) {
     NS_ERROR("Bluetooth service not started yet!");
     return NS_ERROR_FAILURE;
   }
 
+  BluetoothValue v = aSignal.value();
+  if (v.type() != BluetoothValue::TArrayOfBluetoothNamedValue ||
+      v.get_ArrayOfBluetoothNamedValue().Length() == 0) {
+    NS_WARNING("Invalid value type for GetDevicePropertiesInternal() method");
+    return NS_ERROR_FAILURE;
+  }
+
+  const InfallibleTArray<BluetoothNamedValue>& arr =
+    v.get_ArrayOfBluetoothNamedValue();
+
+  // Device object path should be put in the first element
+  if (!arr[0].name().EqualsLiteral("path") ||
+      arr[0].value().type() != BluetoothValue::TnsString) {
+    NS_WARNING("Invalid object path for GetDevicePropertiesInternal() method");
+    return NS_ERROR_FAILURE;
+  }
+
   nsRefPtr<nsRunnable> func(new BluetoothDevicePropertiesRunnable(aSignal));
   if (NS_FAILED(mBluetoothCommandThread->Dispatch(func, NS_DISPATCH_NORMAL))) {
     NS_WARNING("Cannot dispatch task!");
     return NS_ERROR_FAILURE;
   }
 
   return NS_OK;
 }
--- a/dom/indexedDB/IDBFactory.cpp
+++ b/dom/indexedDB/IDBFactory.cpp
@@ -213,19 +213,18 @@ IDBFactory::Create(ContentParent* aConte
 
   nsIXPConnect* xpc = nsContentUtils::XPConnect();
   NS_ASSERTION(xpc, "This should never be null!");
 
   nsCOMPtr<nsIXPConnectJSObjectHolder> globalHolder;
   nsresult rv = xpc->CreateSandbox(cx, principal, getter_AddRefs(globalHolder));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  JS::Rooted<JSObject*> global(cx);
-  rv = globalHolder->GetJSObject(global.address());
-  NS_ENSURE_SUCCESS(rv, rv);
+  JS::Rooted<JSObject*> global(cx, globalHolder->GetJSObject());
+  NS_ENSURE_STATE(global);
 
   // The CreateSandbox call returns a proxy to the actual sandbox object. We
   // don't need a proxy here.
   global = js::UncheckedUnwrap(global);
 
   JSAutoCompartment ac(cx, global);
 
   nsRefPtr<IDBFactory> factory;
--- a/dom/indexedDB/IDBKeyRange.cpp
+++ b/dom/indexedDB/IDBKeyRange.cpp
@@ -47,18 +47,18 @@ ReturnKeyRange(JSContext* aCx,
   nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
   if (NS_FAILED(xpc->WrapNative(aCx, global, aKeyRange,
                                 NS_GET_IID(nsIIDBKeyRange),
                                 getter_AddRefs(holder)))) {
     JS_ReportError(aCx, "Couldn't wrap IDBKeyRange object.");
     return false;
   }
 
-  JS::Rooted<JSObject*> result(aCx);
-  if (NS_FAILED(holder->GetJSObject(result.address()))) {
+  JS::Rooted<JSObject*> result(aCx, holder->GetJSObject());
+  if (!result) {
     JS_ReportError(aCx, "Couldn't get JSObject from wrapper.");
     return false;
   }
 
   JS_SET_RVAL(aCx, aVp, OBJECT_TO_JSVAL(result));
   return true;
 }
 
--- a/dom/interfaces/apps/nsIDOMApplicationRegistry.idl
+++ b/dom/interfaces/apps/nsIDOMApplicationRegistry.idl
@@ -2,17 +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/. */
 
 #include "domstubs.idl"
 #include "nsIDOMEventTarget.idl"
 
 interface nsIDOMDOMRequest;
 
-[scriptable, uuid(d33ee8a0-00e4-4669-b55d-f77fbee1153d)]
+[scriptable, uuid(8bdeef38-e9cd-46f8-b8de-ed9e6b4d01ea)]
 interface mozIDOMApplication  : nsISupports
 {
   readonly attribute jsval manifest;
   readonly attribute jsval updateManifest;
   readonly attribute DOMString manifestURL;
   readonly attribute jsval receipts; /* an array of strings */
   readonly attribute DOMString origin;
   readonly attribute DOMString installOrigin;
@@ -80,18 +80,21 @@ interface mozIDOMApplication  : nsISuppo
   /**
    * Cancels an ongoing update download.
    */
   void cancelDownload();
 
   /* startPoint will be used when several launch_path exists for an app */
   nsIDOMDOMRequest launch([optional] in DOMString startPoint);
 
-  /* Clear data that has been collected through mozbrowser elements. */
-  void clearBrowserData();
+  /**
+   * Clear data that has been collected through mozbrowser elements.
+   * onsuccess will be called once data is actually cleared.
+   */
+  nsIDOMDOMRequest clearBrowserData();
 };
 
 [scriptable, uuid(cf742022-5ba3-11e2-868f-03310341b006)]
 interface mozIDOMApplicationMgmt : nsISupports
 {
   /**
    * the request will return the all the applications installed. Only accessible
    * to privileged callers.
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -1021,17 +1021,17 @@ ContentChild::RecvNotifyVisited(const UR
 bool
 ContentChild::RecvAsyncMessage(const nsString& aMsg,
                                      const ClonedMessageData& aData)
 {
   nsRefPtr<nsFrameMessageManager> cpm = nsFrameMessageManager::sChildProcessManager;
   if (cpm) {
     StructuredCloneData cloneData = ipc::UnpackClonedMessageDataForChild(aData);
     cpm->ReceiveMessage(static_cast<nsIContentFrameMessageManager*>(cpm.get()),
-                        aMsg, false, &cloneData, nullptr, nullptr);
+                        aMsg, false, &cloneData, JS::NullPtr(), nullptr);
   }
   return true;
 }
 
 bool
 ContentChild::RecvGeolocationUpdate(const GeoPosition& somewhere)
 {
   nsCOMPtr<nsIGeolocationUpdate> gs = do_GetService("@mozilla.org/geolocation/service;1");
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -861,17 +861,17 @@ ContentParent::ActorDestroy(ActorDestroy
         mForceKillTask->Cancel();
         mForceKillTask = nullptr;
     }
 
     nsRefPtr<nsFrameMessageManager> ppm = mMessageManager;
     if (ppm) {
       ppm->ReceiveMessage(static_cast<nsIContentFrameMessageManager*>(ppm.get()),
                           CHILD_PROCESS_SHUTDOWN_MESSAGE, false,
-                          nullptr, nullptr, nullptr);
+                          nullptr, JS::NullPtr(), nullptr);
     }
     nsCOMPtr<nsIThreadObserver>
         kungFuDeathGrip(static_cast<nsIThreadObserver*>(this));
     nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
     if (obs) {
         obs->RemoveObserver(static_cast<nsIObserver*>(this), "xpcom-shutdown");
         obs->RemoveObserver(static_cast<nsIObserver*>(this), "memory-pressure");
         obs->RemoveObserver(static_cast<nsIObserver*>(this), "child-memory-reporter-request");
@@ -2326,30 +2326,30 @@ bool
 ContentParent::RecvSyncMessage(const nsString& aMsg,
                                const ClonedMessageData& aData,
                                InfallibleTArray<nsString>* aRetvals)
 {
   nsRefPtr<nsFrameMessageManager> ppm = mMessageManager;
   if (ppm) {
     StructuredCloneData cloneData = ipc::UnpackClonedMessageDataForParent(aData);
     ppm->ReceiveMessage(static_cast<nsIContentFrameMessageManager*>(ppm.get()),
-                        aMsg, true, &cloneData, nullptr, aRetvals);
+                        aMsg, true, &cloneData, JS::NullPtr(), aRetvals);
   }
   return true;
 }
 
 bool
 ContentParent::RecvAsyncMessage(const nsString& aMsg,
                                       const ClonedMessageData& aData)
 {
   nsRefPtr<nsFrameMessageManager> ppm = mMessageManager;
   if (ppm) {
     StructuredCloneData cloneData = ipc::UnpackClonedMessageDataForParent(aData);
     ppm->ReceiveMessage(static_cast<nsIContentFrameMessageManager*>(ppm.get()),
-                        aMsg, false, &cloneData, nullptr, nullptr);
+                        aMsg, false, &cloneData, JS::NullPtr(), nullptr);
   }
   return true;
 }
 
 bool
 ContentParent::RecvFilePathUpdateNotify(const nsString& aType,
                                         const nsString& aStorageName,
                                         const nsString& aFilePath,
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -1431,17 +1431,17 @@ TabChild::DispatchMessageManagerMessage(
     }
 
     nsFrameScriptCx cx(static_cast<nsIWebBrowserChrome*>(this), this);
     // Let the BrowserElementScrolling helper (if it exists) for this
     // content manipulate the frame state.
     nsRefPtr<nsFrameMessageManager> mm =
       static_cast<nsFrameMessageManager*>(mTabChildGlobal->mMessageManager.get());
     mm->ReceiveMessage(static_cast<EventTarget*>(mTabChildGlobal),
-                       aMessageName, false, &cloneData, nullptr, nullptr);
+                       aMessageName, false, &cloneData, JS::NullPtr(), nullptr);
 }
 
 static void
 ScrollWindowTo(nsIDOMWindow* aWindow, const mozilla::gfx::Point& aPoint)
 {
     nsGlobalWindow* window = static_cast<nsGlobalWindow*>(aWindow);
     nsIScrollableFrame* sf = window->GetScrollFrame();
 
@@ -1969,17 +1969,17 @@ TabChild::RecvAsyncMessage(const nsStrin
                            const ClonedMessageData& aData)
 {
   if (mTabChildGlobal) {
     nsFrameScriptCx cx(static_cast<nsIWebBrowserChrome*>(this), this);
     StructuredCloneData cloneData = UnpackClonedMessageDataForChild(aData);
     nsRefPtr<nsFrameMessageManager> mm =
       static_cast<nsFrameMessageManager*>(mTabChildGlobal->mMessageManager.get());
     mm->ReceiveMessage(static_cast<EventTarget*>(mTabChildGlobal),
-                       aMessage, false, &cloneData, nullptr, nullptr);
+                       aMessage, false, &cloneData, JS::NullPtr(), nullptr);
   }
   return true;
 }
 
 class UnloadScriptEvent : public nsRunnable
 {
 public:
   UnloadScriptEvent(TabChild* aTabChild, TabChildGlobal* aTabChildGlobal)
--- a/dom/ipc/TabParent.cpp
+++ b/dom/ipc/TabParent.cpp
@@ -1097,17 +1097,17 @@ TabParent::ReceiveMessage(const nsString
   if (frameLoader && frameLoader->GetFrameMessageManager()) {
     nsRefPtr<nsFrameMessageManager> manager =
       frameLoader->GetFrameMessageManager();
     JSContext* ctx = manager->GetJSContext();
     JSAutoRequest ar(ctx);
     uint32_t len = 0; //TODO: obtain a real value in bug 572685
     // Because we want JS messages to have always the same properties,
     // create array even if len == 0.
-    JSObject* objectsArray = JS_NewArrayObject(ctx, len, NULL);
+    JS::Rooted<JSObject*> objectsArray(ctx, JS_NewArrayObject(ctx, len, NULL));
     if (!objectsArray) {
       return false;
     }
 
     manager->ReceiveMessage(mFrameElement,
                             aMessage,
                             aSync,
                             aCloneData,
--- a/dom/messages/SystemMessagePermissionsChecker.jsm
+++ b/dom/messages/SystemMessagePermissionsChecker.jsm
@@ -50,16 +50,19 @@ this.SystemMessagePermissionsTable = {
     "bluetooth": []
   },
   "bluetooth-pairedstatuschanged": {
     "bluetooth": []
   },
   "bluetooth-hfp-status-changed": {
     "bluetooth": []
   },
+  "bluetooth-pairing-request": {
+    "bluetooth": []
+  },
   "bluetooth-opp-transfer-complete": {
     "bluetooth": []
   },
   "bluetooth-opp-update-progress": {
     "bluetooth": []
   },
   "bluetooth-opp-receiving-file-confirmation": {
     "bluetooth": []
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -1240,18 +1240,17 @@ NPObject* NP_CALLBACK
   NS_ENSURE_TRUE(xpc, nullptr);
 
   nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
   xpc->WrapNative(cx, ::JS_GetGlobalObject(cx), element,
                   NS_GET_IID(nsIDOMElement),
                   getter_AddRefs(holder));
   NS_ENSURE_TRUE(holder, nullptr);
 
-  JS::Rooted<JSObject*> obj(cx);
-  holder->GetJSObject(obj.address());
+  JS::Rooted<JSObject*> obj(cx, holder->GetJSObject());
   NS_ENSURE_TRUE(obj, nullptr);
 
   return nsJSObjWrapper::GetNewOrUsed(npp, cx, obj);
 }
 
 NPIdentifier NP_CALLBACK
 _getstringidentifier(const NPUTF8* name)
 {
--- a/dom/src/jsurl/nsJSProtocolHandler.cpp
+++ b/dom/src/jsurl/nsJSProtocolHandler.cpp
@@ -285,19 +285,18 @@ nsresult nsJSThunk::EvaluateScript(nsICh
         nsCOMPtr<nsIXPConnectJSObjectHolder> sandbox;
         rv = xpc->CreateSandbox(cx, principal, getter_AddRefs(sandbox));
         NS_ENSURE_SUCCESS(rv, rv);
 
         // The nsXPConnect sandbox API gives us a wrapper to the sandbox for
         // our current compartment. Because our current context doesn't necessarily
         // subsume that of the sandbox, we want to unwrap and enter the sandbox's
         // compartment. It's a shame that the APIs here are so clunkly. :-(
-        JS::Rooted<JSObject*> sandboxObj(cx);
-        rv = sandbox->GetJSObject(sandboxObj.address());
-        NS_ENSURE_SUCCESS(rv, rv);
+        JS::Rooted<JSObject*> sandboxObj(cx, sandbox->GetJSObject());
+        NS_ENSURE_STATE(sandboxObj);
         sandboxObj = js::UncheckedUnwrap(sandboxObj);
         JSAutoCompartment ac(cx, sandboxObj);
 
         // Push our JSContext on the context stack so the JS_ValueToString call (and
         // JS_ReportPendingException, if relevant) will use the principal of cx.
         nsCxPusher pusher;
         pusher.Push(cx);
         rv = xpc->EvalInSandboxObject(NS_ConvertUTF8toUTF16(script),
--- a/dom/system/gonk/AudioManager.cpp
+++ b/dom/system/gonk/AudioManager.cpp
@@ -74,17 +74,21 @@ public:
       InternalSetAudioRoutes(SWITCH_STATE_HEADSET);
     else if (sHeadsetState & AUDIO_DEVICE_OUT_WIRED_HEADPHONE)
       InternalSetAudioRoutes(SWITCH_STATE_HEADPHONE);
     else
       InternalSetAudioRoutes(SWITCH_STATE_OFF);
 
     int32_t phoneState = nsIAudioManager::PHONE_STATE_INVALID;
     am->GetPhoneState(&phoneState);
+#if ANDROID_VERSION < 17
     AudioSystem::setPhoneState(phoneState);
+#else
+    AudioSystem::setPhoneState(static_cast<audio_mode_t>(phoneState));
+#endif
 
     AudioSystem::get_audio_flinger();
     return NS_OK;
   }
 };
 
 static void
 BinderDeadCallback(status_t aErr)
@@ -252,18 +256,26 @@ AudioManager::AudioManager() : mPhoneSta
   }
 
   for (int loop = 0; loop < AUDIO_STREAM_CNT; loop++) {
     AudioSystem::initStreamVolume(static_cast<audio_stream_type_t>(loop), 0,
                                   sMaxStreamVolumeTbl[loop]);
     mCurrentStreamVolumeTbl[loop] = sMaxStreamVolumeTbl[loop];
   }
   // Force publicnotification to output at maximal volume
-  AudioSystem::setStreamVolumeIndex(static_cast<audio_stream_type_t>(AUDIO_STREAM_ENFORCED_AUDIBLE),
-                                    sMaxStreamVolumeTbl[AUDIO_STREAM_ENFORCED_AUDIBLE]);
+#if ANDROID_VERSION < 17
+  AudioSystem::setStreamVolumeIndex(
+    static_cast<audio_stream_type_t>(AUDIO_STREAM_ENFORCED_AUDIBLE),
+    sMaxStreamVolumeTbl[AUDIO_STREAM_ENFORCED_AUDIBLE]);
+#else
+  AudioSystem::setStreamVolumeIndex(
+    static_cast<audio_stream_type_t>(AUDIO_STREAM_ENFORCED_AUDIBLE),
+    sMaxStreamVolumeTbl[AUDIO_STREAM_ENFORCED_AUDIBLE],
+    AUDIO_DEVICE_OUT_SPEAKER);
+#endif
 
   AudioSystem::setErrorCallback(BinderDeadCallback);
 }
 
 AudioManager::~AudioManager() {
   UnregisterSwitchObserver(SWITCH_HEADPHONES, mObserver);
 
   nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
@@ -345,17 +357,21 @@ AudioManager::GetPhoneState(int32_t* aSt
 
 NS_IMETHODIMP
 AudioManager::SetPhoneState(int32_t aState)
 {
   if (mPhoneState == aState) {
     return NS_OK;
   }
 
+#if ANDROID_VERSION < 17
   if (AudioSystem::setPhoneState(aState)) {
+#else
+  if (AudioSystem::setPhoneState(static_cast<audio_mode_t>(aState))) {
+#endif
     return NS_ERROR_FAILURE;
   }
 
   mPhoneState = aState;
 
   if (mPhoneAudioAgent) {
     mPhoneAudioAgent->StopPlaying();
     mPhoneAudioAgent = nullptr;
@@ -446,34 +462,68 @@ AudioManager::SetFmRadioAudioEnabled(boo
       >(AudioSystem::setDeviceConnectionState)) {
     AudioSystem::setDeviceConnectionState(AUDIO_DEVICE_OUT_FM,
       aFmRadioAudioEnabled ? AUDIO_POLICY_DEVICE_STATE_AVAILABLE :
       AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, "");
     InternalSetAudioRoutes(GetCurrentSwitchState(SWITCH_HEADPHONES));
     // sync volume with music after powering on fm radio
     if (aFmRadioAudioEnabled) {
       int32_t volIndex = 0;
-      AudioSystem::getStreamVolumeIndex(static_cast<audio_stream_type_t>(AUDIO_STREAM_MUSIC), &volIndex);
-      AudioSystem::setStreamVolumeIndex(static_cast<audio_stream_type_t>(AUDIO_STREAM_FM), volIndex);
+#if ANDROID_VERSION < 17
+      AudioSystem::getStreamVolumeIndex(
+        static_cast<audio_stream_type_t>(AUDIO_STREAM_MUSIC),
+        &volIndex);
+      AudioSystem::setStreamVolumeIndex(
+        static_cast<audio_stream_type_t>(AUDIO_STREAM_FM),
+        volIndex);
+#else
+      AudioSystem::getStreamVolumeIndex(
+        static_cast<audio_stream_type_t>(AUDIO_STREAM_MUSIC),
+        &volIndex,
+        AUDIO_DEVICE_OUT_DEFAULT);
+      AudioSystem::setStreamVolumeIndex(
+        static_cast<audio_stream_type_t>(AUDIO_STREAM_FM),
+        volIndex,
+        AUDIO_DEVICE_OUT_SPEAKER);
+#endif
       mCurrentStreamVolumeTbl[AUDIO_STREAM_FM] = volIndex;
     }
     return NS_OK;
   } else {
     return NS_ERROR_NOT_IMPLEMENTED;
   }
 }
 
 NS_IMETHODIMP
 AudioManager::SetStreamVolumeIndex(int32_t aStream, int32_t aIndex) {
+#if ANDROID_VERSION < 17
   status_t status =
-    AudioSystem::setStreamVolumeIndex(static_cast<audio_stream_type_t>(aStream), aIndex);
+    AudioSystem::setStreamVolumeIndex(
+      static_cast<audio_stream_type_t>(aStream),
+      aIndex);
+#else
+  status_t status =
+    AudioSystem::setStreamVolumeIndex(
+      static_cast<audio_stream_type_t>(aStream),
+      aIndex,
+      AUDIO_DEVICE_OUT_SPEAKER);
+#endif
 
   // sync fm volume with music stream type
   if (aStream == AUDIO_STREAM_MUSIC && IsDeviceOn(AUDIO_DEVICE_OUT_FM)) {
-    AudioSystem::setStreamVolumeIndex(static_cast<audio_stream_type_t>(AUDIO_STREAM_FM), aIndex);
+#if ANDROID_VERSION < 17
+    AudioSystem::setStreamVolumeIndex(
+      static_cast<audio_stream_type_t>(AUDIO_STREAM_FM),
+      aIndex);
+#else
+    AudioSystem::setStreamVolumeIndex(
+      static_cast<audio_stream_type_t>(AUDIO_STREAM_FM),
+      aIndex,
+      AUDIO_DEVICE_OUT_SPEAKER);
+#endif
     mCurrentStreamVolumeTbl[AUDIO_STREAM_FM] = aIndex;
   }
   mCurrentStreamVolumeTbl[aStream] = aIndex;
 
   return status ? NS_ERROR_FAILURE : NS_OK;
 }
 
 NS_IMETHODIMP
--- a/dom/system/gonk/android_audio/AudioSystem.h
+++ b/dom/system/gonk/android_audio/AudioSystem.h
@@ -218,16 +218,29 @@ typedef enum {
                                AUDIO_CHANNEL_IN_PRESSURE |
                                AUDIO_CHANNEL_IN_X_AXIS |
                                AUDIO_CHANNEL_IN_Y_AXIS |
                                AUDIO_CHANNEL_IN_Z_AXIS |
                                AUDIO_CHANNEL_IN_VOICE_UPLINK |
                                AUDIO_CHANNEL_IN_VOICE_DNLINK),
 } audio_channels_t;
 
+#if ANDROID_VERSION >= 17
+typedef enum {
+    AUDIO_MODE_INVALID          = -2,
+    AUDIO_MODE_CURRENT          = -1,
+    AUDIO_MODE_NORMAL           = 0,
+    AUDIO_MODE_RINGTONE         = 1,
+    AUDIO_MODE_IN_CALL          = 2,
+    AUDIO_MODE_IN_COMMUNICATION = 3,
+
+    AUDIO_MODE_CNT,
+    AUDIO_MODE_MAX              = AUDIO_MODE_CNT - 1,
+} audio_mode_t;
+#endif
 #endif
 
 typedef enum {
     /* output devices */      
     AUDIO_DEVICE_OUT_EARPIECE                  = 0x1,
     AUDIO_DEVICE_OUT_SPEAKER                   = 0x2,
     AUDIO_DEVICE_OUT_WIRED_HEADSET             = 0x4,
     AUDIO_DEVICE_OUT_WIRED_HEADPHONE           = 0x8,
@@ -295,17 +308,23 @@ typedef enum {
                                AUDIO_DEVICE_IN_AUX_DIGITAL |
                                AUDIO_DEVICE_IN_VOICE_CALL |
                                AUDIO_DEVICE_IN_BACK_MIC |
                                AUDIO_DEVICE_IN_ANC_HEADSET |
                                AUDIO_DEVICE_IN_FM_RX |
                                AUDIO_DEVICE_IN_FM_RX_A2DP |
                                AUDIO_DEVICE_IN_DEFAULT),
     AUDIO_DEVICE_IN_ALL_SCO = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET,
+#if ANDROID_VERSION < 17
 } audio_devices_t;
+#else
+};
+
+typedef uint32_t audio_devices_t;
+#endif
 
 /* device connection states used for audio_policy->set_device_connection_state()
  *  */
 typedef enum {
     AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
     AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
     
     AUDIO_POLICY_DEVICE_STATE_CNT,
@@ -645,16 +664,19 @@ public:
     };
 
     //
     // IAudioPolicyService interface (see AudioPolicyInterface for method descriptions)
     //
     static status_t setDeviceConnectionState(audio_devices device, device_connection_state state, const char *device_address);
     static device_connection_state getDeviceConnectionState(audio_devices device, const char *device_address);
     static status_t setPhoneState(int state);
+#if ANDROID_VERSION >= 17
+    static status_t setPhoneState(audio_mode_t state);
+#endif
     static status_t setRingerMode(uint32_t mode, uint32_t mask);
 #ifdef VANILLA_ANDROID
     static status_t setForceUse(force_use usage, forced_config config);
     static forced_config getForceUse(force_use usage);
     static audio_io_handle_t getOutput(stream_type stream,
                                         uint32_t samplingRate = 0,
                                         uint32_t format = FORMAT_DEFAULT,
                                         uint32_t channels = CHANNEL_OUT_STEREO,
@@ -701,16 +723,24 @@ public:
     static status_t initStreamVolume(stream_type stream,
                                       int indexMin,
                                       int indexMax);
     static status_t initStreamVolume(audio_stream_type_t stream,
                                       int indexMin,
                                       int indexMax);
     static status_t setStreamVolumeIndex(stream_type stream, int index);
     static status_t setStreamVolumeIndex(audio_stream_type_t stream, int index);
+#if ANDROID_VERSION >= 17
+    static status_t setStreamVolumeIndex(audio_stream_type_t stream,
+                                         int index,
+                                         audio_devices_t device);
+    static status_t getStreamVolumeIndex(audio_stream_type_t stream,
+                                         int *index,
+                                         audio_devices_t device);
+#endif
     static status_t getStreamVolumeIndex(stream_type stream, int *index);
     static status_t getStreamVolumeIndex(audio_stream_type_t stream, int *index);
 
     static uint32_t getStrategyForStream(stream_type stream);
 
     static audio_io_handle_t getOutputForEffect(effect_descriptor_t *desc);
     static status_t registerEffect(effect_descriptor_t *desc,
                                     audio_io_handle_t output,
--- a/dom/system/gonk/android_audio/EffectApi.h
+++ b/dom/system/gonk/android_audio/EffectApi.h
@@ -595,22 +595,24 @@ enum audio_device_e {
     DEVICE_BLUETOOTH_SCO_CARKIT = 0x40,         // bluetooth SCO car kit
     DEVICE_BLUETOOTH_A2DP = 0x80,               // generic bluetooth A2DP
     DEVICE_BLUETOOTH_A2DP_HEADPHONES = 0x100,   // bluetooth A2DP headphones
     DEVICE_BLUETOOTH_A2DP_SPEAKER = 0x200,      // bluetooth A2DP speakers
     DEVICE_AUX_DIGITAL = 0x400,                 // digital output
     DEVICE_EXTERNAL_SPEAKER = 0x800             // external speaker (stereo and High quality)
 };
 
+#if ANDROID_VERSION < 17
 // Audio mode
 enum audio_mode_e {
     AUDIO_MODE_NORMAL,      // device idle
     AUDIO_MODE_RINGTONE,    // device ringing
     AUDIO_MODE_IN_CALL      // audio call connected (VoIP or telephony)
 };
+#endif
 
 // Values for "accessMode" field of buffer_config_t:
 //   overwrite, read only, accumulate (read/modify/write)
 enum effect_buffer_access_e {
     EFFECT_BUFFER_ACCESS_WRITE,
     EFFECT_BUFFER_ACCESS_READ,
     EFFECT_BUFFER_ACCESS_ACCUMULATE
 
--- a/dom/tests/mochitest/general/test_interfaces.html
+++ b/dom/tests/mochitest/general/test_interfaces.html
@@ -21,541 +21,541 @@ https://bugzilla.mozilla.org/show_bug.cg
 /** Test for Bug 766694 **/
 
 // This is a list of all interfaces that are exposed to every webpage.  Please only
 // add things to this list with great care.
 
 // IMPORTANT: Do not change this list without review from a DOM peer!
 var interfaceNamesInGlobalScope =
   [
-    "MozApplicationEvent",
-    "HTMLByteRanges",
-    "URL",
-    "BatteryManager",
-    "HTMLStyleElement",
-    "PropertyNodeList",
-    "SVGPatternElement",
-    "LinkStyle",
-    "IDBTransaction",
-    "CSSMediaRule",
-    "SVGFEMergeNodeElement",
-    "HTMLUnknownElement",
-    "SVGStylable",
-    "MozContactChangeEvent",
-    "ToString",
-    "MozBrowserFrame",
-    "UserDataHandler",
-    "HTMLDirectoryElement",
-    "SVGNumberList",
-    "SVGMaskElement",
-    "DeviceMotionEvent",
-    "GetSVGDocument",
-    "SVGAnimatedPreserveAspectRatio",
-    "SVGViewElement",
-    "HTMLTableSectionElement",
-    "HTMLCollection",
-    "HTMLProgressElement",
-    "CRMFObject",
-    "CSSStyleSheet",
-    "UIEvent",
-    "IDBOpenDBRequest",
-    "XMLHttpRequest",
-    "SVGTextPathElement",
-    "StorageItem",
-    "SVGPolygonElement",
-    "MutationRecord",
-    "TimeEvent",
-    "HTMLElement",
-    "HTMLOptionElement",
-    "Pkcs11",
-    "NotifyAudioAvailableEvent",
-    "ElementReplaceEvent",
+    "AnimationEvent",
     "Array",
-    "SVGZoomAndPan",
-    "XULPopupElement",
-    "MediaError",
-    "DeviceStorageCursor",
-    "DeviceStorageChangeEvent",
-    "PageTransitionEvent",
-    "DataContainerEvent",
-    "MozCSSKeyframesRule",
-    "SVGAnimatedInteger",
-    "TouchEvent",
-    "OpenWindowEventDetail",
-    "IDBIndex",
-    "EventListener",
-    "TransitionEvent",
-    "XULContainerItemElement",
-    "HTMLTableCaptionElement",
-    "SVGRect",
-    "IDBCursor",
-    "History",
-    "HTMLTableRowElement",
-    "NodeFilter",
-    "ClientRectList",
-    "CanvasRenderingContext2D",
-    "SVGPathSegLinetoVerticalRel",
-    "MozAlarmsManager",
-    "MozPowerManager",
-    "SVGElement",
-    "GeoPositionError",
-    "XPathEvaluator",
-    "NodeIterator",
-    "MozNavigatorNetwork",
-    "CryptoDialogs",
-    "SVGLocatable",
-    "XULElement",
-    "CSSRuleList",
-    "SVGMarkerElement",
-    "Rect",
-    "SVGPathElement",
-    "SVGUseElement",
-    "SVGAnimatedPoints",
-    "DeviceAcceleration",
-    "DOMError",
-    "SVGAnimateMotionElement",
-    "HTMLMeterElement",
-    "SmartCardEvent",
-    "CSSValueList",
-    "ValidityState",
-    "HTMLAppletElement",
-    "Touch",
-    "Controllers",
-    "AnimationEvent",
-    "NavigatorDesktopNotification",
-    "LoadStatus",
-    "MediaQueryList",
-    "Contact",
-    "MediaQueryListListener",
-    "DesktopNotificationCenter",
-    "PluginArray",
-    "XULSelectControlElement",
-    "TimeRanges",
-    "ImageData",
-    "SVGPathSegArcAbs",
-    "MimeTypeArray",
-    "DocumentFragment",
-    "ParserJS",
-    "CanvasPattern",
-    "GeoPosition",
-    "XPathExpression",
+    "AsyncScrollEventDetail",
+    "Attr",
     "BarProp",
-    "NSEditableElement",
-    "SVGRectElement",
-    "DOMRequest",
-    "WindowPerformance",
-    "DOMSettableTokenList",
-    "SVGTransformList",
-    "SVGTransformable",
-    "XULControlElement",
-    "HTMLFrameSetElement",
-    "CSSCharsetRule",
-    "TouchList",
-    "DOMStringList",
-    "HTMLCommandElement",
-    "FileList",
-    "XULRelatedElement",
+    "BatteryManager",
+    "BeforeUnloadEvent",
     "Blob",
-    "Node",
-    "HTMLEmbedElement",
-    "ProgressEvent",
-    "SVGAnimateElement",
-    "MutationEvent",
-    "TreeSelection",
-    "DeviceLightEvent",
-    "SVGCircleElement",
-    "SVGFEComponentTransferElement",
-    "SVGPathSeg",
-    "SVGSVGElement",
-    "GlobalPropertyInitializer",
-    "HTMLMenuItemElement",
-    "HTMLDataListElement",
-    "XPathResult",
-    "XMLDocument",
-    "DocumentType",
-    "MozNamedAttrMap",
-    "DeviceProximityEvent",
-    "XULLabeledControlElement",
-    "MozWakeLock",
-    "MozConnection",
-    "WebGLRenderingContext",
-    "JSON",
+    "BlobEvent",
+    "BoxObject",
+    "CameraCapabilities",
+    "CameraControl",
+    "CameraManager",
+    "CanvasGradient",
+    "CanvasPattern",
+    "CanvasRenderingContext2D",
+    "CDATASection",
+    "CharacterData",
+    "ChromeWindow",
+    "ClientInformation",
     "ClientRect",
-    "GetUserMediaSuccessCallback",
+    "ClientRectList",
+    "ClipboardEvent",
+    "CloseEvent",
     "CommandEvent",
-    "HTMLDocument",
-    "DeviceOrientationEvent",
-    "HTMLPreElement",
-    "StorageEvent",
-    "CSS2Properties",
-    "StorageIndexedDB",
-    "XULDocument",
-    "XULMultiSelectControlElement",
-    "SVGTitleElement",
-    "PerformanceTiming",
-    "LSProgressEvent",
-    "NSEvent",
-    "HTMLBRElement",
-    "MouseScrollEvent",
-    "WheelEvent",
-    "HashChangeEvent",
-    "TreeWalker",
-    "HTMLTitleElement",
-    "LockedFile",
-    "GetUserMediaErrorCallback",
-    "SVGFEMorphologyElement",
-    "SVGFETurbulenceElement",
-    "XULTextBoxElement",
-    "SVGDocument",
-    "CSSStyleDeclaration",
-    "SVGAltGlyphElement",
-    "Screen",
-    "FileReader",
-    "SVGSwitchElement",
-    "SVGPolylineElement",
-    "SVGPathSegLinetoAbs",
-    "NavigatorDeviceStorage",
-    "HTMLOptionsCollection",
-    "IDBKeyRange",
-    "Parser",
-    "HTMLDivElement",
-    "HTMLLinkElement",
-    "ClientInformation",
-    "SVGMpathElement",
-    "HTMLTextAreaElement",
-    "SVGAnimatedEnumeration",
-    "Attr",
-    "StyleSheet",
-    "HTMLBodyElement",
-    "SVGPathSegCurvetoQuadraticSmoothRel",
-    "HTMLHeadingElement",
-    "Document",
-    "FileHandle",
-    "HTMLAnchorElement",
-    "SVGZoomEvent",
-    "UserProximityEvent",
-    "SVGAnimateTransformElement",
-    "CSSMozDocumentRule",
-    "HTMLQuoteElement",
-    "PopStateEvent",
-    "IDBVersionChangeEvent",
-    "HTMLCanvasElement",
-    "MouseEvent",
-    "OfflineResourceList",
-    "Range",
-    "MozCSSKeyframeRule",
-    "SettingsLock",
-    "Screen",
-    "ImageDocument",
-    "TextMetrics",
-    "SVGScriptElement",
-    "CDATASection",
-    "CanvasGradient",
-    "SVGViewSpec",
-    "DOMException",
-    "MozSmsMessage",
-    "MozMmsMessage",
-    "SVGFESpecularLightingElement",
-    "StorageObsolete",
+    "Comment",
+    "CompositionEvent",
+    "Contact",
     "ContactManager",
-    "NSXPathExpression",
-    "SVGLineElement",
-    "SVGPathSegArcRel",
-    "XSLTProcessor",
-    "SVGPathSegLinetoVerticalAbs",
-    "SVGPathSegLinetoRel",
-    "HTMLImageElement",
-    "MozSmsEvent",
-    "MozMmsEvent",
-    "CustomEvent",
-    "XMLHttpRequestUpload",
-    "SVGFEFuncBElement",
-    "Text",
-    "SVGPathSegCurvetoCubicRel",
-    "DataTransfer",
-    "SVGTSpanElement",
-    "SVGRadialGradientElement",
-    "SVGFEDisplacementMapElement",
-    "SVGPathSegCurvetoCubicSmoothAbs",
-    "CSSValue",
-    "DesktopNotification",
-    "KeyEvent",
-    "HTMLAreaElement",
-    "XULLabelElement",
-    "FormData",
-    "IDBDatabase",
-    "CSSPrimitiveValue",
-    "SVGStopElement",
-    "XULCommandEvent",
-    "HTMLMediaElement",
-    "SVGPathSegLinetoHorizontalAbs",
-    "SVGAnimatedRect",
-    "SVGTextContentElement",
-    "TreeColumn",
-    "XPathNamespace",
-    "FontFace",
-    "SVGPathSegCurvetoCubicSmoothRel",
-    "HTMLMapElement",
-    "SVGImageElement",
-    "HTMLMetaElement",
-    "NotifyPaintEvent",
-    "XULTreeElement",
-    "DragEvent",
-    "ClipboardEvent",
-    "IDBObjectStore",
-    "NodeSelector",
-    "NavigatorUserMedia",
-    "TreeContentView",
-    "MimeType",
-    "SVGForeignObjectElement",
-    "MozMobileNetworkInfo",
-    "SVGAnimatedString",
-    "HTMLPropertiesCollection",
-    "WindowInternal",
-    "Serializer",
-    "SVGFEFuncGElement",
-    "XULCheckboxElement",
-    "SVGFEPointLightElement",
-    "ModalContentWindow",
+    "Controllers",
+    "Counter",
+    "CRMFObject",
     "Crypto",
-    "StorageManager",
-    "SVGAngle",
-    "Navigator",
-    "SVGPathSegCurvetoQuadraticSmoothAbs",
-    "HTMLButtonElement",
-    "SVGPointList",
-    "SVGFEColorMatrixElement",
-    "USSDReceivedEvent",
-    "SettingsManager",
-    "DeviceRotationRate",
-    "HTMLAudioElement",
-    "SVGFEDistantLightElement",
-    "HTMLOListElement",
-    "ProcessingInstruction",
-    "CSSUnknownRule",
-    "SVGComponentTransferFunctionElement",
-    "SVGEvent",
-    "SVGPathSegLinetoHorizontalRel",
-    "SVGAnimatedNumber",
-    "HTMLHtmlElement",
-    "MozSmsManager",
-    "MozMobileMessageManager",
-    "MozSmsFilter",
-    "SVGFETileElement",
-    "MozMobileConnectionInfo",
-    "CSSRule",
-    "HTMLSelectElement",
-    "MessageEvent",
-    "SVGFEImageElement",
-    "URL",
-    "DeviceStorage",
-    "SVGFEOffsetElement",
-    "DOMImplementation",
-    "SVGFECompositeElement",
-    "MediaList",
-    "HTMLFrameElement",
-    "NodeList",
-    "SVGPathSegCurvetoQuadraticRel",
-    "IDBFactory",
-    "SVGFilterPrimitiveStandardAttributes",
-    "CSSImportRule",
-    "SVGPathSegClosePath",
-    "HTMLTableCellElement",
-    "WindowUtils",
-    "SVGAnimatedNumberList",
-    "WindowCollection",
-    "SVGPathSegMovetoRel",
-    "ChromeWindow",
-    "Comment",
-    "HTMLSourceElement",
-    "SVGStringList",
-    "Storage",
-    "HTMLModElement",
-    "PaintRequest",
-    "XPathNSResolver",
-    "XULDescriptionElement",
-    "SVGLinearGradientElement",
-    "JSWindow",
-    "SVGGElement",
-    "BoxObject",
-    "SVGFEBlendElement",
-    "Event",
-    "File",
-    "HTMLOptGroupElement",
-    "SVGAnimatedLengthList",
-    "SVGAnimatedTransformList",
-    "MozTouchEvent",
-    "MozWakeLockListener",
-    "Selection",
-    "XULTreeBuilder",
-    "ScrollAreaEvent",
-    "SVGStyleElement",
-    "XULContainerElement",
-    "DOMTokenList",
-    "HTMLHRElement",
-    "HTMLFontElement",
-    "SVGFEFloodElement",
-    "HTMLDListElement",
-    "SVGSymbolElement",
-    "SVGLengthList",
-    "TreeColumns",
-    "PaintRequestList",
-    "SVGTextElement",
-    "SimpleGestureEvent",
-    "SVGMatrix",
-    "HTMLUListElement",
-    "SVGFEConvolveMatrixElement",
-    "SVGAnimationElement",
-    "SVGMetadataElement",
-    "EventListenerInfo",
-    "CSSStyleRule",
-    "IDBRequest",
-    "Performance",
-    "XULMenuListElement",
-    "SVGTransform",
-    "SVGTextPositioningElement",
-    "SVGFEMergeElement",
-    "FileRequest",
-    "SVGDefsElement",
-    "Element",
-    "HTMLBaseElement",
-    "GeoPositionErrorCallback",
-    "HTMLVideoElement",
-    "MozSettingsEvent",
-    "SVGAnimatedPathData",
-    "SVGUnitTypes",
-    "SVGTests",
-    "RGBColor",
-    "HTMLLabelElement",
-    "EventSource",
-    "MozNavigatorSms",
-    "MozNavigatorMobileMessage",
-    "SVGSetElement",
-    "GlobalObjectConstructor",
-    "SVGAnimatedBoolean",
-    "HTMLTableElement",
-    "Window",
-    "SVGNumber",
-    "XULImageElement",
-    "Plugin",
-    "SVGAnimatedLength",
-    "FontFaceList",
-    "EventTarget",
-    "SVGFEFuncRElement",
-    "SVGPathSegMovetoAbs",
-    "SVGPoint",
-    "GeoPositionCoords",
-    "HTMLIFrameElement",
-    "PerformanceNavigation",
-    "MediaStream",
-    "DOMStringMap",
-    "HTMLFieldSetElement",
-    "SVGFEDiffuseLightingElement",
-    "StyleSheetList",
-    "ElementCSSInlineStyle",
-    "HTMLInputElement",
-    "CharacterData",
-    "HTMLObjectElement",
-    "SVGURIReference",
-    "GeoGeolocation",
-    "HTMLParamElement",
-    "HTMLTableColElement",
-    "MozBlobBuilder",
-    "SVGFESpotLightElement",
-    "PopupBlockedEvent",
-    "XULButtonElement",
-    "CSSPageRule",
-    "Location",
-    "DocumentXBL",
-    "HTMLHeadElement",
-    "XULTemplateBuilder",
-    "GeoPositionCallback",
-    "XULCommandDispatcher",
-    "DocumentTouch",
-    "XULSelectControlItemElement",
-    "SVGPathSegCurvetoQuadraticAbs",
-    "MutationObserver",
-    "RequestService",
-    "Counter",
-    "SVGAnimatedAngle",
-    "SVGPathSegList",
-    "SVGFEFuncAElement",
-    "WebSocket",
-    "ElementTimeControl",
-    "HTMLLegendElement",
-    "SVGFEGaussianBlurElement",
-    "SVGEllipseElement",
-    "SVGDescElement",
-    "BeforeUnloadEvent",
-    "NSRGBAColor",
-    "MozBrowserFrame",
-    "SVGPreserveAspectRatio",
-    "HTMLMenuElement",
-    "CloseEvent",
-    "IDBCursorWithValue",
+    "CryptoDialogs",
+    "CSS2Properties",
+    "CSSCharsetRule",
+    "CSSConditionRule",
     "CSSFontFaceRule",
     "CSSFontFeatureValuesRule",
-    "XMLHttpRequestEventTarget",
-    "CompositionEvent",
-    "HTMLOutputElement",
-    "HTMLFormElement",
-    "SVGLength",
-    "SVGFilterElement",
-    "HTMLScriptElement",
-    "SVGPathSegCurvetoCubicAbs",
-    "HTMLLIElement",
-    "SVGClipPathElement",
-    "NavigatorGeolocation",
-    "HTMLParagraphElement",
+    "CSSGroupingRule",
+    "CSSImportRule",
+    "CSSMediaRule",
+    "CSSMozDocumentRule",
+    "CSSPageRule",
+    "CSSPrimitiveValue",
+    "CSSRule",
+    "CSSRuleList",
+    "CSSStyleDeclaration",
+    "CSSStyleRule",
+    "CSSStyleSheet",
+    "CSSSupportsRule",
+    "CSSUnknownRule",
+    "CSSValue",
+    "CSSValueList",
+    "CustomEvent",
+    "DataChannel",
+    "DataContainerEvent",
+    "DataErrorEvent",
+    "DataTransfer",
+    "DesktopNotification",
+    "DesktopNotificationCenter",
+    "DeviceAcceleration",
+    "DeviceLightEvent",
+    "DeviceMotionEvent",
+    "DeviceOrientationEvent",
+    "DeviceProximityEvent",
+    "DeviceRotationRate",
+    "DeviceStorage",
+    "DeviceStorageChangeEvent",
+    "DeviceStorageCursor",
+    "Document",
+    "DocumentFragment",
+    "DocumentTouch",
+    "DocumentType",
+    "DocumentXBL",
+    "DOMCursor",
+    "DOMError",
+    "DOMException",
+    "DOMImplementation",
+    "DOMRequest",
+    "DOMSettableTokenList",
+    "DOMStringList",
+    "DOMStringMap",
+    "DOMTokenList",
+    "DOMTransactionEvent",
+    "DragEvent",
+    "Element",
+    "ElementCSSInlineStyle",
+    "ElementReplaceEvent",
+    "ElementTimeControl",
+    "Event",
+    "EventListener",
+    "EventListenerInfo",
+    "EventSource",
+    "EventTarget",
     "EventTarget",
     "File",
-    "SVGGradientElement",
-    "SVGFitToViewBox",
-    "SVGAElement",
-    "NavigatorCamera",
-    "CameraControl",
-    "CameraCapabilities",
-    "CameraManager",
-    "CSSSupportsRule",
+    "File",
+    "FileHandle",
+    "FileList",
+    "FileReader",
+    "FileRequest",
+    "FontFace",
+    "FontFaceList",
+    "FormData",
+    "Gamepad",
+    "GamepadAxisMoveEvent",
+    "GamepadButtonEvent",
+    "GamepadEvent",
+    "GeoGeolocation",
+    "GeoPosition",
+    "GeoPositionCallback",
+    "GeoPositionCoords",
+    "GeoPositionError",
+    "GeoPositionErrorCallback",
+    "GetSVGDocument",
+    "GetUserMediaErrorCallback",
+    "GetUserMediaSuccessCallback",
+    "GlobalObjectConstructor",
+    "GlobalPropertyInitializer",
+    "HashChangeEvent",
+    "History",
+    "HTMLAnchorElement",
+    "HTMLAppletElement",
+    "HTMLAreaElement",
+    "HTMLAudioElement",
+    "HTMLBaseElement",
+    "HTMLBodyElement",
+    "HTMLBRElement",
+    "HTMLButtonElement",
+    "HTMLByteRanges",
+    "HTMLCanvasElement",
+    "HTMLCollection",
+    "HTMLCommandElement",
+    "HTMLDataListElement",
+    "HTMLDirectoryElement",
+    "HTMLDivElement",
+    "HTMLDListElement",
+    "HTMLDocument",
+    "HTMLElement",
+    "HTMLEmbedElement",
+    "HTMLFieldSetElement",
+    "HTMLFontElement",
+    "HTMLFormElement",
+    "HTMLFrameElement",
+    "HTMLFrameSetElement",
+    "HTMLHeadElement",
+    "HTMLHeadingElement",
+    "HTMLHRElement",
+    "HTMLHtmlElement",
+    "HTMLIFrameElement",
+    "HTMLImageElement",
+    "HTMLInputElement",
+    "HTMLLabelElement",
+    "HTMLLegendElement",
+    "HTMLLIElement",
+    "HTMLLinkElement",
+    "HTMLMapElement",
+    "HTMLMediaElement",
+    "HTMLMenuElement",
+    "HTMLMenuItemElement",
+    "HTMLMetaElement",
+    "HTMLMeterElement",
+    "HTMLModElement",
+    "HTMLObjectElement",
+    "HTMLOListElement",
+    "HTMLOptGroupElement",
+    "HTMLOptionElement",
+    "HTMLOptionsCollection",
+    "HTMLOutputElement",
+    "HTMLParagraphElement",
+    "HTMLParamElement",
+    "HTMLPreElement",
+    "HTMLProgressElement",
+    "HTMLPropertiesCollection",
+    "HTMLQuoteElement",
+    "HTMLScriptElement",
+    "HTMLSelectElement",
+    "HTMLSourceElement",
+    "HTMLStyleElement",
+    "HTMLTableCaptionElement",
+    "HTMLTableCellElement",
+    "HTMLTableColElement",
+    "HTMLTableElement",
+    "HTMLTableRowElement",
+    "HTMLTableSectionElement",
+    "HTMLTextAreaElement",
+    "HTMLTitleElement",
+    "HTMLUListElement",
+    "HTMLUnknownElement",
+    "HTMLVideoElement",
+    "IDBCursor",
+    "IDBCursorWithValue",
+    "IDBDatabase",
+    "IDBFactory",
+    "IDBIndex",
+    "IDBKeyRange",
+    "IDBObjectStore",
+    "IDBOpenDBRequest",
+    "IDBRequest",
+    "IDBTransaction",
+    "IDBVersionChangeEvent",
+    "ImageData",
+    "ImageDocument",
+    "JSON",
+    "JSWindow",
+    "KeyEvent",
+    "LinkStyle",
+    "LoadStatus",
+    "LocalMediaStream",
+    "Location",
+    "LockedFile",
+    "LSProgressEvent",
+    "MediaError",
+    "MediaList",
+    "MediaQueryList",
+    "MediaQueryListListener",
+    "MediaStream",
+    "MessageEvent",
+    "MimeType",
+    "MimeTypeArray",
+    "ModalContentWindow",
+    "MouseEvent",
+    "MouseScrollEvent",
+    "MozAlarmsManager",
+    "MozApplicationEvent",
+    "MozBlobBuilder",
+    "MozBrowserFrame",
+    "MozBrowserFrame",
+    "MozCanvasPrintState",
+    "MozConnection",
+    "MozContactChangeEvent",
+    "MozCSSKeyframeRule",
+    "MozCSSKeyframesRule",
+    "MozMmsEvent",
+    "MozMmsMessage",
     "MozMobileCellInfo",
-    "UndoManager",
-    "DOMTransactionEvent",
-    "MozCanvasPrintState",
-    "TCPSocket",
-    "MozTimeManager",
+    "MozMobileConnectionInfo",
+    "MozMobileMessageManager",
+    "MozMobileMessageThread",
+    "MozMobileNetworkInfo",
+    "MozNamedAttrMap",
+    "MozNavigatorMobileMessage",
+    "MozNavigatorNetwork",
+    "MozNavigatorSms",
     "MozNavigatorTime",
-    "PermissionSettings",
-    "DataErrorEvent",
-    "DataChannel",
-    "MozNetworkStatsManager",
     "MozNetworkStats",
     "MozNetworkStatsData",
-    "RTCSessionDescription",
+    "MozNetworkStatsManager",
+    "MozPowerManager",
+    "MozSettingsEvent",
+    "MozSmsEvent",
+    "MozSmsFilter",
+    "MozSmsManager",
+    "MozSmsMessage",
+    "MozSmsSegmentInfo",
+    "MozTimeManager",
+    "MozTouchEvent",
+    "MozWakeLock",
+    "MozWakeLockListener",
+    "MutationEvent",
+    "MutationObserver",
+    "MutationRecord",
+    "Navigator",
+    "NavigatorCamera",
+    "NavigatorDesktopNotification",
+    "NavigatorDeviceStorage",
+    "NavigatorGeolocation",
+    "NavigatorUserMedia",
+    "Node",
+    "NodeFilter",
+    "NodeIterator",
+    "NodeList",
+    "NodeSelector",
+    "NotifyAudioAvailableEvent",
+    "NotifyPaintEvent",
+    "NSEditableElement",
+    "NSEvent",
+    "NSRGBAColor",
+    "NSXPathExpression",
+    "OfflineResourceList",
+    "OpenWindowEventDetail",
+    "PageTransitionEvent",
+    "PaintRequest",
+    "PaintRequestList",
+    "Parser",
+    "ParserJS",
+    "PaymentRequestInfo",
+    "Performance",
+    "PerformanceNavigation",
+    "PerformanceTiming",
+    "PermissionSettings",
+    "Pkcs11",
+    "Plugin",
+    "PluginArray",
+    "PopStateEvent",
+    "PopupBlockedEvent",
+    "ProcessingInstruction",
+    "ProgressEvent",
+    "PropertyNodeList",
+    "PushManager",
+    "Range",
+    "Rect",
+    "RequestService",
+    "RGBColor",
     "RTCIceCandidate",
     "RTCPeerConnection",
-    "LocalMediaStream",
-    "CSSConditionRule",
-    "CSSGroupingRule",
-    "AsyncScrollEventDetail",
-    "MozSmsSegmentInfo",
-    "DOMCursor",
-    "BlobEvent",
-    "Gamepad",
-    "GamepadEvent",
-    "GamepadButtonEvent",
-    "GamepadAxisMoveEvent",
+    "RTCSessionDescription",
+    "Screen",
+    "Screen",
+    "ScrollAreaEvent",
+    "Selection",
+    "Serializer",
+    "SettingsLock",
+    "SettingsManager",
+    "SimpleGestureEvent",
+    "SmartCardEvent",
+    "SpeechRecognitionError",
     "SpeechRecognitionEvent",
-    "SpeechRecognitionError",
     "SpeechSynthesisEvent",
-    "PushManager",
+    "Storage",
+    "StorageEvent",
+    "StorageIndexedDB",
+    "StorageItem",
+    "StorageManager",
+    "StorageObsolete",
     "StyleRuleChangeEvent",
-    "StyleSheetChangeEvent",
+    "StyleSheet",
     "StyleSheetApplicableStateChangeEvent",
-    "MozMobileMessageThread",
-    "PaymentRequestInfo",
+    "StyleSheetChangeEvent",
+    "StyleSheetList",
+    "SVGAElement",
+    "SVGAltGlyphElement",
+    "SVGAngle",
+    "SVGAnimatedAngle",
+    "SVGAnimatedBoolean",
+    "SVGAnimatedEnumeration",
+    "SVGAnimatedInteger",
+    "SVGAnimatedLength",
+    "SVGAnimatedLengthList",
+    "SVGAnimatedNumber",
+    "SVGAnimatedNumberList",
+    "SVGAnimatedPathData",
+    "SVGAnimatedPoints",
+    "SVGAnimatedPreserveAspectRatio",
+    "SVGAnimatedRect",
+    "SVGAnimatedString",
+    "SVGAnimatedTransformList",
+    "SVGAnimateElement",
+    "SVGAnimateMotionElement",
+    "SVGAnimateTransformElement",
+    "SVGAnimationElement",
+    "SVGCircleElement",
+    "SVGClipPathElement",
+    "SVGComponentTransferFunctionElement",
+    "SVGDefsElement",
+    "SVGDescElement",
+    "SVGDocument",
+    "SVGElement",
+    "SVGEllipseElement",
+    "SVGEvent",
+    "SVGFEBlendElement",
+    "SVGFEColorMatrixElement",
+    "SVGFEComponentTransferElement",
+    "SVGFECompositeElement",
+    "SVGFEConvolveMatrixElement",
+    "SVGFEDiffuseLightingElement",
+    "SVGFEDisplacementMapElement",
+    "SVGFEDistantLightElement",
+    "SVGFEFloodElement",
+    "SVGFEFuncAElement",
+    "SVGFEFuncBElement",
+    "SVGFEFuncGElement",
+    "SVGFEFuncRElement",
+    "SVGFEGaussianBlurElement",
+    "SVGFEImageElement",
+    "SVGFEMergeElement",
+    "SVGFEMergeNodeElement",
+    "SVGFEMorphologyElement",
+    "SVGFEOffsetElement",
+    "SVGFEPointLightElement",
+    "SVGFESpecularLightingElement",
+    "SVGFESpotLightElement",
+    "SVGFETileElement",
+    "SVGFETurbulenceElement",
+    "SVGFilterElement",
+    "SVGFilterPrimitiveStandardAttributes",
+    "SVGFitToViewBox",
+    "SVGForeignObjectElement",
+    "SVGGElement",
+    "SVGGradientElement",
+    "SVGImageElement",
+    "SVGLength",
+    "SVGLengthList",
+    "SVGLinearGradientElement",
+    "SVGLineElement",
+    "SVGLocatable",
+    "SVGMarkerElement",
+    "SVGMaskElement",
+    "SVGMatrix",
+    "SVGMetadataElement",
+    "SVGMpathElement",
+    "SVGNumber",
+    "SVGNumberList",
+    "SVGPathElement",
+    "SVGPathSeg",
+    "SVGPathSegArcAbs",
+    "SVGPathSegArcRel",
+    "SVGPathSegClosePath",
+    "SVGPathSegCurvetoCubicAbs",
+    "SVGPathSegCurvetoCubicRel",
+    "SVGPathSegCurvetoCubicSmoothAbs",
+    "SVGPathSegCurvetoCubicSmoothRel",
+    "SVGPathSegCurvetoQuadraticAbs",
+    "SVGPathSegCurvetoQuadraticRel",
+    "SVGPathSegCurvetoQuadraticSmoothAbs",
+    "SVGPathSegCurvetoQuadraticSmoothRel",
+    "SVGPathSegLinetoAbs",
+    "SVGPathSegLinetoHorizontalAbs",
+    "SVGPathSegLinetoHorizontalRel",
+    "SVGPathSegLinetoRel",
+    "SVGPathSegLinetoVerticalAbs",
+    "SVGPathSegLinetoVerticalRel",
+    "SVGPathSegList",
+    "SVGPathSegMovetoAbs",
+    "SVGPathSegMovetoRel",
+    "SVGPatternElement",
+    "SVGPoint",
+    "SVGPointList",
+    "SVGPolygonElement",
+    "SVGPolylineElement",
+    "SVGPreserveAspectRatio",
+    "SVGRadialGradientElement",
+    "SVGRect",
+    "SVGRectElement",
+    "SVGScriptElement",
+    "SVGSetElement",
+    "SVGStopElement",
+    "SVGStringList",
+    "SVGStylable",
+    "SVGStyleElement",
+    "SVGSVGElement",
+    "SVGSwitchElement",
+    "SVGSymbolElement",
+    "SVGTests",
+    "SVGTextContentElement",
+    "SVGTextElement",
+    "SVGTextPathElement",
+    "SVGTextPositioningElement",
+    "SVGTitleElement",
+    "SVGTransform",
+    "SVGTransformable",
+    "SVGTransformList",
+    "SVGTSpanElement",
+    "SVGUnitTypes",
+    "SVGURIReference",
+    "SVGUseElement",
+    "SVGViewElement",
+    "SVGViewSpec",
+    "SVGZoomAndPan",
+    "SVGZoomEvent",
+    "TCPSocket",
+    "Text",
+    "TextMetrics",
+    "TimeEvent",
+    "TimeRanges",
+    "ToString",
+    "Touch",
+    "TouchEvent",
+    "TouchList",
+    "TransitionEvent",
+    "TreeColumn",
+    "TreeColumns",
+    "TreeContentView",
+    "TreeSelection",
+    "TreeWalker",
+    "UIEvent",
+    "UndoManager",
+    "URL",
+    "URL",
+    "UserDataHandler",
+    "UserProximityEvent",
+    "USSDReceivedEvent",
+    "ValidityState",
+    "WebGLRenderingContext",
+    "WebSocket",
+    "WheelEvent",
+    "Window",
+    "WindowCollection",
+    "WindowInternal",
+    "WindowPerformance",
+    "WindowUtils",
+    "XMLDocument",
+    "XMLHttpRequest",
+    "XMLHttpRequestEventTarget",
+    "XMLHttpRequestUpload",
+    "XPathEvaluator",
+    "XPathExpression",
+    "XPathNamespace",
+    "XPathNSResolver",
+    "XPathResult",
+    "XSLTProcessor",
+    "XULButtonElement",
+    "XULCheckboxElement",
+    "XULCommandDispatcher",
+    "XULCommandEvent",
+    "XULContainerElement",
+    "XULContainerItemElement",
+    "XULControlElement",
+    "XULDescriptionElement",
+    "XULDocument",
+    "XULElement",
+    "XULImageElement",
+    "XULLabeledControlElement",
+    "XULLabelElement",
+    "XULMenuListElement",
+    "XULMultiSelectControlElement",
+    "XULPopupElement",
+    "XULRelatedElement",
+    "XULSelectControlElement",
+    "XULSelectControlItemElement",
+    "XULTemplateBuilder",
+    "XULTextBoxElement",
+    "XULTreeBuilder",
+    "XULTreeElement",
   ]
 // IMPORTANT: Do not change this list without review from a DOM peer!
 
 // If your interface is named nsIDOMSomeInterface and you don't mean to expose
 // it to every webpage, simply change its name to nsISomeInterface to fix this problem.
 
 for (var i in SpecialPowers.Components.interfaces) {
   var s = i.toString();
copy from content/base/public/nsIDOMDataChannel.idl
copy to dom/webidl/DataChannel.webidl
--- a/content/base/public/nsIDOMDataChannel.idl
+++ b/dom/webidl/DataChannel.webidl
@@ -1,38 +1,50 @@
-#include "domstubs.idl"
-
-#include "nsIDOMEventTarget.idl"
+/* 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/. */
 
-interface nsIVariant;
+enum RTCDataChannelState {
+  "connecting",
+  "open",
+  "closing",
+  "closed"
+};
 
-[scriptable, builtinclass, uuid(1aed816d-1156-414e-8fe2-f01daa6021f0)]
-interface nsIDOMDataChannel : nsIDOMEventTarget
+enum RTCDataChannelType {
+  "arraybuffer",
+  "blob"
+};
+
+// XXX This interface is called RTCDataChannel in the spec.
+interface DataChannel : EventTarget
 {
   readonly attribute DOMString label;
-  readonly attribute DOMString protocol;
   readonly attribute boolean reliable;
-  readonly attribute boolean ordered;
-
-  readonly attribute DOMString readyState;
+  readonly attribute RTCDataChannelState readyState;
   readonly attribute unsigned long bufferedAmount;
-
-  readonly attribute unsigned short stream;
-
-  [implicit_jscontext] attribute jsval onopen;
-  [implicit_jscontext] attribute jsval onerror;
-  [implicit_jscontext] attribute jsval onclose;
-  [implicit_jscontext] attribute jsval onmessage;
+  [SetterThrows]
+  attribute EventHandler onopen;
+  [SetterThrows]
+  attribute EventHandler onerror;
+  [SetterThrows]
+  attribute EventHandler onclose;
+  void close();
+  [SetterThrows]
+  attribute EventHandler onmessage;
+  attribute RTCDataChannelType binaryType;
+  [Throws]
+  void send(DOMString data);
+  [Throws]
+  void send(Blob data);
+  [Throws]
+  void send(ArrayBuffer data);
+  [Throws]
+  void send(ArrayBufferView data);
+};
 
-  attribute DOMString binaryType;
-
-  void close();
-
-  /**
-   * Transmits data to other end of the connection.
-   * @param data The data to be transmitted.  Arraybuffers and Blobs are sent as
-   * binary data.  Strings are sent as UTF-8 text data.  Other types are
-   * converted to a String and sent as a String.
-   * @return if the connection is still established and the data was queued or
-   *         sent successfully.
-   */
-  void send(in nsIVariant data);
+// Mozilla extensions.
+partial interface DataChannel
+{
+  readonly attribute DOMString protocol;
+  readonly attribute boolean ordered;
+  readonly attribute unsigned short stream;
 };
copy from dom/webidl/KeyboardEvent.webidl
copy to dom/webidl/KeyEvent.webidl
--- a/dom/webidl/KeyboardEvent.webidl
+++ b/dom/webidl/KeyEvent.webidl
@@ -1,17 +1,18 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
 interface WindowProxy;
 
-interface KeyboardEvent : UIEvent
+// http://www.w3.org/TR/1999/WD-DOM-Level-2-19990923/events.html#Events-KeyEvent
+interface KeyEvent
 {
   const unsigned long DOM_VK_CANCEL         = 0x03;
   const unsigned long DOM_VK_HELP           = 0x06;
   const unsigned long DOM_VK_BACK_SPACE     = 0x08;
   const unsigned long DOM_VK_TAB            = 0x09;
   const unsigned long DOM_VK_CLEAR          = 0x0C;
   const unsigned long DOM_VK_RETURN         = 0x0D;
   const unsigned long DOM_VK_ENTER          = 0x0E;
@@ -218,41 +219,20 @@ interface KeyboardEvent : UIEvent
   const unsigned long DOM_VK_PLAY           = 0xFA;
   const unsigned long DOM_VK_ZOOM           = 0xFB;
   const unsigned long DOM_VK_PA1            = 0xFD;
 
   // OEM specific virtual keyCode of Windows should pass through DOM keyCode
   // for compatibility with the other web browsers on Windows.
   const unsigned long DOM_VK_WIN_OEM_CLEAR  = 0xFE;
 
-  readonly attribute unsigned long    charCode;
-  readonly attribute unsigned long    keyCode;
-
-  readonly attribute boolean          altKey;
-  readonly attribute boolean          ctrlKey;
-  readonly attribute boolean          shiftKey;
-  readonly attribute boolean          metaKey;
-
   [Throws]
   void initKeyEvent(DOMString type,
                     boolean canBubble,
                     boolean cancelable,
                     WindowProxy? view,
                     boolean ctrlKey,
                     boolean altKey,
                     boolean shiftKey,
                     boolean metaKey,
                     unsigned long keyCode,
                     unsigned long charCode);
-
-  boolean getModifierState(DOMString key);
-
-  const unsigned long DOM_KEY_LOCATION_STANDARD = 0x00;
-  const unsigned long DOM_KEY_LOCATION_LEFT     = 0x01;
-  const unsigned long DOM_KEY_LOCATION_RIGHT    = 0x02;
-  const unsigned long DOM_KEY_LOCATION_NUMPAD   = 0x03;
-  const unsigned long DOM_KEY_LOCATION_MOBILE   = 0x04;
-  const unsigned long DOM_KEY_LOCATION_JOYSTICK = 0x05;
-
-  readonly attribute unsigned long location;
-
-  readonly attribute DOMString key;
 };
--- a/dom/webidl/KeyboardEvent.webidl
+++ b/dom/webidl/KeyboardEvent.webidl
@@ -3,256 +3,32 @@
  * 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/.
  */
 
 interface WindowProxy;
 
 interface KeyboardEvent : UIEvent
 {
-  const unsigned long DOM_VK_CANCEL         = 0x03;
-  const unsigned long DOM_VK_HELP           = 0x06;
-  const unsigned long DOM_VK_BACK_SPACE     = 0x08;
-  const unsigned long DOM_VK_TAB            = 0x09;
-  const unsigned long DOM_VK_CLEAR          = 0x0C;
-  const unsigned long DOM_VK_RETURN         = 0x0D;
-  const unsigned long DOM_VK_ENTER          = 0x0E;
-  const unsigned long DOM_VK_SHIFT          = 0x10;
-  const unsigned long DOM_VK_CONTROL        = 0x11;
-  const unsigned long DOM_VK_ALT            = 0x12;
-  const unsigned long DOM_VK_PAUSE          = 0x13;
-  const unsigned long DOM_VK_CAPS_LOCK      = 0x14;
-  const unsigned long DOM_VK_KANA           = 0x15;
-  const unsigned long DOM_VK_HANGUL         = 0x15;
-  const unsigned long DOM_VK_EISU           = 0x16; // Japanese Mac keyboard only
-  const unsigned long DOM_VK_JUNJA          = 0x17;
-  const unsigned long DOM_VK_FINAL          = 0x18;
-  const unsigned long DOM_VK_HANJA          = 0x19;
-  const unsigned long DOM_VK_KANJI          = 0x19;
-  const unsigned long DOM_VK_ESCAPE         = 0x1B;
-  const unsigned long DOM_VK_CONVERT        = 0x1C;
-  const unsigned long DOM_VK_NONCONVERT     = 0x1D;
-  const unsigned long DOM_VK_ACCEPT         = 0x1E;
-  const unsigned long DOM_VK_MODECHANGE     = 0x1F;
-  const unsigned long DOM_VK_SPACE          = 0x20;
-  const unsigned long DOM_VK_PAGE_UP        = 0x21;
-  const unsigned long DOM_VK_PAGE_DOWN      = 0x22;
-  const unsigned long DOM_VK_END            = 0x23;
-  const unsigned long DOM_VK_HOME           = 0x24;
-  const unsigned long DOM_VK_LEFT           = 0x25;
-  const unsigned long DOM_VK_UP             = 0x26;
-  const unsigned long DOM_VK_RIGHT          = 0x27;
-  const unsigned long DOM_VK_DOWN           = 0x28;
-  const unsigned long DOM_VK_SELECT         = 0x29;
-  const unsigned long DOM_VK_PRINT          = 0x2A;
-  const unsigned long DOM_VK_EXECUTE        = 0x2B;
-  const unsigned long DOM_VK_PRINTSCREEN    = 0x2C;
-  const unsigned long DOM_VK_INSERT         = 0x2D;
-  const unsigned long DOM_VK_DELETE         = 0x2E;
-
-  // DOM_VK_0 - DOM_VK_9 match their ascii values
-  const unsigned long DOM_VK_0              = 0x30;
-  const unsigned long DOM_VK_1              = 0x31;
-  const unsigned long DOM_VK_2              = 0x32;
-  const unsigned long DOM_VK_3              = 0x33;
-  const unsigned long DOM_VK_4              = 0x34;
-  const unsigned long DOM_VK_5              = 0x35;
-  const unsigned long DOM_VK_6              = 0x36;
-  const unsigned long DOM_VK_7              = 0x37;
-  const unsigned long DOM_VK_8              = 0x38;
-  const unsigned long DOM_VK_9              = 0x39;
-
-  const unsigned long DOM_VK_COLON          = 0x3A;
-  const unsigned long DOM_VK_SEMICOLON      = 0x3B;
-  const unsigned long DOM_VK_LESS_THAN      = 0x3C;
-  const unsigned long DOM_VK_EQUALS         = 0x3D;
-  const unsigned long DOM_VK_GREATER_THAN   = 0x3E;
-  const unsigned long DOM_VK_QUESTION_MARK  = 0x3F;
-  const unsigned long DOM_VK_AT             = 0x40;
-
-  // DOM_VK_A - DOM_VK_Z match their ascii values
-  const unsigned long DOM_VK_A              = 0x41;
-  const unsigned long DOM_VK_B              = 0x42;
-  const unsigned long DOM_VK_C              = 0x43;
-  const unsigned long DOM_VK_D              = 0x44;
-  const unsigned long DOM_VK_E              = 0x45;
-  const unsigned long DOM_VK_F              = 0x46;
-  const unsigned long DOM_VK_G              = 0x47;
-  const unsigned long DOM_VK_H              = 0x48;
-  const unsigned long DOM_VK_I              = 0x49;
-  const unsigned long DOM_VK_J              = 0x4A;
-  const unsigned long DOM_VK_K              = 0x4B;
-  const unsigned long DOM_VK_L              = 0x4C;
-  const unsigned long DOM_VK_M              = 0x4D;
-  const unsigned long DOM_VK_N              = 0x4E;
-  const unsigned long DOM_VK_O              = 0x4F;
-  const unsigned long DOM_VK_P              = 0x50;
-  const unsigned long DOM_VK_Q              = 0x51;
-  const unsigned long DOM_VK_R              = 0x52;
-  const unsigned long DOM_VK_S              = 0x53;
-  const unsigned long DOM_VK_T              = 0x54;
-  const unsigned long DOM_VK_U              = 0x55;
-  const unsigned long DOM_VK_V              = 0x56;
-  const unsigned long DOM_VK_W              = 0x57;
-  const unsigned long DOM_VK_X              = 0x58;
-  const unsigned long DOM_VK_Y              = 0x59;
-  const unsigned long DOM_VK_Z              = 0x5A;
-
-  const unsigned long DOM_VK_WIN            = 0x5B;
-  const unsigned long DOM_VK_CONTEXT_MENU   = 0x5D;
-  const unsigned long DOM_VK_SLEEP          = 0x5F;
-
-  // Numpad keys
-  const unsigned long DOM_VK_NUMPAD0        = 0x60;
-  const unsigned long DOM_VK_NUMPAD1        = 0x61;
-  const unsigned long DOM_VK_NUMPAD2        = 0x62;
-  const unsigned long DOM_VK_NUMPAD3        = 0x63;
-  const unsigned long DOM_VK_NUMPAD4        = 0x64;
-  const unsigned long DOM_VK_NUMPAD5        = 0x65;
-  const unsigned long DOM_VK_NUMPAD6        = 0x66;
-  const unsigned long DOM_VK_NUMPAD7        = 0x67;
-  const unsigned long DOM_VK_NUMPAD8        = 0x68;
-  const unsigned long DOM_VK_NUMPAD9        = 0x69;
-  const unsigned long DOM_VK_MULTIPLY       = 0x6A;
-  const unsigned long DOM_VK_ADD            = 0x6B;
-  const unsigned long DOM_VK_SEPARATOR      = 0x6C;
-  const unsigned long DOM_VK_SUBTRACT       = 0x6D;
-  const unsigned long DOM_VK_DECIMAL        = 0x6E;
-  const unsigned long DOM_VK_DIVIDE         = 0x6F;
-
-  const unsigned long DOM_VK_F1             = 0x70;
-  const unsigned long DOM_VK_F2             = 0x71;
-  const unsigned long DOM_VK_F3             = 0x72;
-  const unsigned long DOM_VK_F4             = 0x73;
-  const unsigned long DOM_VK_F5             = 0x74;
-  const unsigned long DOM_VK_F6             = 0x75;
-  const unsigned long DOM_VK_F7             = 0x76;
-  const unsigned long DOM_VK_F8             = 0x77;
-  const unsigned long DOM_VK_F9             = 0x78;
-  const unsigned long DOM_VK_F10            = 0x79;
-  const unsigned long DOM_VK_F11            = 0x7A;
-  const unsigned long DOM_VK_F12            = 0x7B;
-  const unsigned long DOM_VK_F13            = 0x7C;
-  const unsigned long DOM_VK_F14            = 0x7D;
-  const unsigned long DOM_VK_F15            = 0x7E;
-  const unsigned long DOM_VK_F16            = 0x7F;
-  const unsigned long DOM_VK_F17            = 0x80;
-  const unsigned long DOM_VK_F18            = 0x81;
-  const unsigned long DOM_VK_F19            = 0x82;
-  const unsigned long DOM_VK_F20            = 0x83;
-  const unsigned long DOM_VK_F21            = 0x84;
-  const unsigned long DOM_VK_F22            = 0x85;
-  const unsigned long DOM_VK_F23            = 0x86;
-  const unsigned long DOM_VK_F24            = 0x87;
-
-  const unsigned long DOM_VK_NUM_LOCK       = 0x90;
-  const unsigned long DOM_VK_SCROLL_LOCK    = 0x91;
-
-  // OEM specific virtual keyCode of Windows should pass through DOM keyCode
-  // for compatibility with the other web browsers on Windows.
-  const unsigned long DOM_VK_WIN_OEM_FJ_JISHO   = 0x92;
-  const unsigned long DOM_VK_WIN_OEM_FJ_MASSHOU = 0x93;
-  const unsigned long DOM_VK_WIN_OEM_FJ_TOUROKU = 0x94;
-  const unsigned long DOM_VK_WIN_OEM_FJ_LOYA    = 0x95;
-  const unsigned long DOM_VK_WIN_OEM_FJ_ROYA    = 0x96;
-
-  const unsigned long DOM_VK_CIRCUMFLEX     = 0xA0;
-  const unsigned long DOM_VK_EXCLAMATION    = 0xA1;
-  const unsigned long DOM_VK_DOUBLE_QUOTE   = 0xA2;
-  const unsigned long DOM_VK_HASH           = 0xA3;
-  const unsigned long DOM_VK_DOLLAR         = 0xA4;
-  const unsigned long DOM_VK_PERCENT        = 0xA5;
-  const unsigned long DOM_VK_AMPERSAND      = 0xA6;
-  const unsigned long DOM_VK_UNDERSCORE     = 0xA7;
-  const unsigned long DOM_VK_OPEN_PAREN     = 0xA8;
-  const unsigned long DOM_VK_CLOSE_PAREN    = 0xA9;
-  const unsigned long DOM_VK_ASTERISK       = 0xAA;
-  const unsigned long DOM_VK_PLUS           = 0xAB;
-  const unsigned long DOM_VK_PIPE           = 0xAC;
-  const unsigned long DOM_VK_HYPHEN_MINUS   = 0xAD;
-
-  const unsigned long DOM_VK_OPEN_CURLY_BRACKET  = 0xAE;
-  const unsigned long DOM_VK_CLOSE_CURLY_BRACKET = 0xAF;
-
-  const unsigned long DOM_VK_TILDE          = 0xB0;
-
-  const unsigned long DOM_VK_VOLUME_MUTE    = 0xB5;
-  const unsigned long DOM_VK_VOLUME_DOWN    = 0xB6;
-  const unsigned long DOM_VK_VOLUME_UP      = 0xB7;
-
-  const unsigned long DOM_VK_COMMA          = 0xBC;
-  const unsigned long DOM_VK_PERIOD         = 0xBE;
-  const unsigned long DOM_VK_SLASH          = 0xBF;
-  const unsigned long DOM_VK_BACK_QUOTE     = 0xC0;
-  const unsigned long DOM_VK_OPEN_BRACKET   = 0xDB; // square bracket
-  const unsigned long DOM_VK_BACK_SLASH     = 0xDC;
-  const unsigned long DOM_VK_CLOSE_BRACKET  = 0xDD; // square bracket
-  const unsigned long DOM_VK_QUOTE          = 0xDE; // Apostrophe
-
-  const unsigned long DOM_VK_META           = 0xE0;
-  const unsigned long DOM_VK_ALTGR          = 0xE1;
-
-  // OEM specific virtual keyCode of Windows should pass through DOM keyCode
-  // for compatibility with the other web browsers on Windows.
-  const unsigned long DOM_VK_WIN_ICO_HELP    = 0xE3;
-  const unsigned long DOM_VK_WIN_ICO_00      = 0xE4;
-  const unsigned long DOM_VK_WIN_ICO_CLEAR   = 0xE6;
-  const unsigned long DOM_VK_WIN_OEM_RESET   = 0xE9;
-  const unsigned long DOM_VK_WIN_OEM_JUMP    = 0xEA;
-  const unsigned long DOM_VK_WIN_OEM_PA1     = 0xEB;
-  const unsigned long DOM_VK_WIN_OEM_PA2     = 0xEC;
-  const unsigned long DOM_VK_WIN_OEM_PA3     = 0xED;
-  const unsigned long DOM_VK_WIN_OEM_WSCTRL  = 0xEE;
-  const unsigned long DOM_VK_WIN_OEM_CUSEL   = 0xEF;
-  const unsigned long DOM_VK_WIN_OEM_ATTN    = 0xF0;
-  const unsigned long DOM_VK_WIN_OEM_FINISH  = 0xF1;
-  const unsigned long DOM_VK_WIN_OEM_COPY    = 0xF2;
-  const unsigned long DOM_VK_WIN_OEM_AUTO    = 0xF3;
-  const unsigned long DOM_VK_WIN_OEM_ENLW    = 0xF4;
-  const unsigned long DOM_VK_WIN_OEM_BACKTAB = 0xF5;
-
-  // Following keys are not used on most keyboards.  However, for compatibility
-  // with other browsers on Windows, we should define them.
-  const unsigned long DOM_VK_ATTN           = 0xF6;
-  const unsigned long DOM_VK_CRSEL          = 0xF7;
-  const unsigned long DOM_VK_EXSEL          = 0xF8;
-  const unsigned long DOM_VK_EREOF          = 0xF9;
-  const unsigned long DOM_VK_PLAY           = 0xFA;
-  const unsigned long DOM_VK_ZOOM           = 0xFB;
-  const unsigned long DOM_VK_PA1            = 0xFD;
-
-  // OEM specific virtual keyCode of Windows should pass through DOM keyCode
-  // for compatibility with the other web browsers on Windows.
-  const unsigned long DOM_VK_WIN_OEM_CLEAR  = 0xFE;
-
   readonly attribute unsigned long    charCode;
   readonly attribute unsigned long    keyCode;
 
   readonly attribute boolean          altKey;
   readonly attribute boolean          ctrlKey;
   readonly attribute boolean          shiftKey;
   readonly attribute boolean          metaKey;
 
-  [Throws]
-  void initKeyEvent(DOMString type,
-                    boolean canBubble,
-                    boolean cancelable,
-                    WindowProxy? view,
-                    boolean ctrlKey,
-                    boolean altKey,
-                    boolean shiftKey,
-                    boolean metaKey,
-                    unsigned long keyCode,
-                    unsigned long charCode);
-
   boolean getModifierState(DOMString key);
 
   const unsigned long DOM_KEY_LOCATION_STANDARD = 0x00;
   const unsigned long DOM_KEY_LOCATION_LEFT     = 0x01;
   const unsigned long DOM_KEY_LOCATION_RIGHT    = 0x02;
   const unsigned long DOM_KEY_LOCATION_NUMPAD   = 0x03;
   const unsigned long DOM_KEY_LOCATION_MOBILE   = 0x04;
   const unsigned long DOM_KEY_LOCATION_JOYSTICK = 0x05;
 
   readonly attribute unsigned long location;
 
   readonly attribute DOMString key;
 };
+
+// Mozilla extensions
+KeyboardEvent implements KeyEvent;
--- a/dom/webidl/SVGAnimatedRect.webidl
+++ b/dom/webidl/SVGAnimatedRect.webidl
@@ -6,13 +6,11 @@
  * The origin of this IDL file is
  * http://www.w3.org/TR/SVG2/
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
 interface SVGAnimatedRect {
-  [GetterThrows]
   readonly attribute SVGRect? baseVal;
-  [GetterThrows]
   readonly attribute SVGRect? animVal;
 };
--- a/dom/webidl/WebIDL.mk
+++ b/dom/webidl/WebIDL.mk
@@ -156,16 +156,17 @@ webidl_files = \
   HTMLVideoElement.webidl \
   IDBDatabase.webidl \
   IDBFactory.webidl \
   IDBVersionChangeEvent.webidl \
   ImageData.webidl \
   ImageDocument.webidl \
   InspectorUtils.webidl \
   KeyboardEvent.webidl \
+  KeyEvent.webidl \
   LinkStyle.webidl \
   LocalMediaStream.webidl \
   Location.webidl \
   MediaError.webidl \
   MediaStream.webidl \
   MediaStreamEvent.webidl \
   MediaStreamTrack.webidl \
   MessageEvent.webidl \
@@ -353,16 +354,17 @@ endif
 ifdef MOZ_WEBGL
 webidl_files += \
   WebGLRenderingContext.webidl \
   $(NULL)
 endif
 
 ifdef MOZ_WEBRTC
 webidl_files += \
+  DataChannel.webidl \
   MediaStreamList.webidl \
   $(NULL)
 endif
 
 ifdef MOZ_WEBSPEECH
 webidl_files += \
   SpeechGrammar.webidl \
   SpeechGrammarList.webidl \
--- a/extensions/pref/autoconfig/src/nsJSConfigTriggers.cpp
+++ b/extensions/pref/autoconfig/src/nsJSConfigTriggers.cpp
@@ -52,18 +52,18 @@ nsresult CentralizedAdminPrefManagerInit
     // Create a sandbox.
     AutoSafeJSContext cx;
     JSAutoRequest ar(cx);
     nsCOMPtr<nsIXPConnectJSObjectHolder> sandbox;
     rv = xpc->CreateSandbox(cx, principal, getter_AddRefs(sandbox));
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Unwrap, store and root the sandbox.
-    rv = sandbox->GetJSObject(&autoconfigSb);
-    NS_ENSURE_SUCCESS(rv, rv);
+    autoconfigSb = sandbox->GetJSObject();
+    NS_ENSURE_STATE(autoconfigSb);
     autoconfigSb = js::UncheckedUnwrap(autoconfigSb);
     JSAutoCompartment ac(cx, autoconfigSb);
     if (!JS_AddNamedObjectRoot(cx, &autoconfigSb, "AutoConfig Sandbox"))
         return NS_ERROR_FAILURE;
 
     return NS_OK;
 }
 
--- a/gfx/gl/GLContext.cpp
+++ b/gfx/gl/GLContext.cpp
@@ -347,16 +347,17 @@ GLContext::InitWithPrefix(const char *pr
         // defined in GLContext.h for renderer IDs
         glRendererString = (const char *)fGetString(LOCAL_GL_RENDERER);
         if (!glRendererString)
             mInitialized = false;
 
         const char *rendererMatchStrings[RendererOther] = {
                 "Adreno 200",
                 "Adreno 205",
+                "Adreno (TM) 205",
                 "Adreno (TM) 320",
                 "PowerVR SGX 530",
                 "PowerVR SGX 540"
         };
 
         mRenderer = RendererOther;
         for (int i = 0; i < RendererOther; ++i) {
             if (DoesStringMatch(glRendererString, rendererMatchStrings[i])) {
--- a/gfx/gl/GLContext.h
+++ b/gfx/gl/GLContext.h
@@ -292,17 +292,18 @@ public:
         VendorImagination,
         VendorNouveau,
         VendorOther
     };
 
     enum {
         RendererAdreno200,
         RendererAdreno205,
-        RendererAdreno320,
+        RendererAdrenoTM205,
+        RendererAdrenoTM320,
         RendererSGX530,
         RendererSGX540,
         RendererOther
     };
 
     int Vendor() const {
         return mVendor;
     }
--- a/gfx/layers/D3D9SurfaceImage.cpp
+++ b/gfx/layers/D3D9SurfaceImage.cpp
@@ -32,51 +32,53 @@ D3D9SurfaceImage::SetData(const Data& aD
                                          D3DDEVTYPE_HAL,
                                          desc.Format,
                                          D3DFMT_X8R8G8B8);
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
 
   // DXVA surfaces aren't created sharable, so we need to copy the surface
   // to a sharable texture to that it's accessible to the layer manager's
   // device.
+  const nsIntRect& region = aData.mRegion;
   RefPtr<IDirect3DTexture9> texture;
   HANDLE shareHandle = NULL;
-  hr = device->CreateTexture(desc.Width,
-                             desc.Height,
+  hr = device->CreateTexture(region.width,
+                             region.height,
                              1,
                              D3DUSAGE_RENDERTARGET,
                              D3DFMT_X8R8G8B8,
                              D3DPOOL_DEFAULT,
                              byRef(texture),
                              &shareHandle);
   NS_ENSURE_TRUE(SUCCEEDED(hr) && shareHandle, hr);
 
   // Copy the image onto the texture, preforming YUV -> RGB conversion if necessary.
   RefPtr<IDirect3DSurface9> textureSurface;
   hr = texture->GetSurfaceLevel(0, byRef(textureSurface));
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
 
   // Stash the surface description for later use.
   textureSurface->GetDesc(&mDesc);
 
-  hr = device->StretchRect(surface, NULL, textureSurface, NULL, D3DTEXF_NONE);
+  RECT src = { region.x, region.y, region.x+region.width, region.y+region.height };
+  hr = device->StretchRect(surface, &src, textureSurface, NULL, D3DTEXF_NONE);
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
 
   // Flush the draw command now, so that by the time we come to draw this
   // image, we're less likely to need to wait for the draw operation to
   // complete.
   RefPtr<IDirect3DQuery9> query;
   hr = device->CreateQuery(D3DQUERYTYPE_EVENT, byRef(query));
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
   hr = query->Issue(D3DISSUE_END);
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
 
   mTexture = texture;
   mShareHandle = shareHandle;
-  mSize = gfxIntSize(aData.mSize.width, aData.mSize.height);
+  mSize = gfxIntSize(region.width, region.height);
   mQuery = query;
 
   return S_OK;
 }
 
 void
 D3D9SurfaceImage::EnsureSynchronized()
 {
--- a/gfx/layers/D3D9SurfaceImage.h
+++ b/gfx/layers/D3D9SurfaceImage.h
@@ -17,20 +17,20 @@ namespace layers {
 // Image class that wraps a IDirect3DSurface9. This class copies the image
 // passed into SetData(), so that it can be accessed from other D3D devices.
 // This class also manages the synchronization of the copy, to ensure the
 // resource is ready to use.
 class D3D9SurfaceImage : public Image {
 public:
 
   struct Data {
-    Data(IDirect3DSurface9* aSurface, const nsIntSize& aSize)
-      : mSurface(aSurface), mSize(aSize) {}
+    Data(IDirect3DSurface9* aSurface, const nsIntRect& aRegion)
+      : mSurface(aSurface), mRegion(aRegion) {}
     RefPtr<IDirect3DSurface9> mSurface;
-    nsIntSize mSize;
+    nsIntRect mRegion;
   };
 
   D3D9SurfaceImage() : Image(NULL, D3D9_RGB32_TEXTURE), mSize(0, 0) {}
   virtual ~D3D9SurfaceImage() {}
 
   // Copies the surface into a sharable texture's surface, and initializes
   // the image.
   HRESULT SetData(const Data& aData);
--- a/gfx/layers/composite/AsyncCompositionManager.cpp
+++ b/gfx/layers/composite/AsyncCompositionManager.cpp
@@ -308,17 +308,16 @@ SampleAnimations(Layer* aLayer, TimeStam
     case eCSSProperty_transform:
     {
       gfx3DMatrix matrix = interpolatedValue.get_ArrayOfTransformFunction()[0].get_TransformMatrix().value();
       if (ContainerLayer* c = aLayer->AsContainerLayer()) {
         matrix.ScalePost(c->GetInheritedXScale(),
                          c->GetInheritedYScale(),
                          1);
       }
-      NS_ASSERTION(!aLayer->GetIsFixedPosition(), "Can't animate transforms on fixed-position layers");
       layerComposite->SetShadowTransform(matrix);
       layerComposite->SetShadowTransformSetByAnimation(true);
       break;
     }
     default:
       NS_WARNING("Unhandled animated property");
     }
   }
--- a/gfx/layers/opengl/TextureHostOGL.cpp
+++ b/gfx/layers/opengl/TextureHostOGL.cpp
@@ -834,16 +834,29 @@ GrallocTextureHostOGL::Unlock()
    * The job of this function is to ensure that we release any read lock placed on
    * our android::GraphicBuffer by any drawing code that sourced it via this TextureHost.
    *
    * Indeed, as soon as we draw with a texture that's tied to a android::GraphicBuffer,
    * the GL may place read locks on it. We must ensure that we release them early enough,
    * i.e. before the next time that we will try to acquire a write lock on the same buffer,
    * because read and write locks on gralloc buffers are mutually exclusive.
    */
+  if (mGL->Renderer() == GLContext::RendererAdrenoTM205) {
+    /* XXX This is working around a driver bug exhibited on at least the
+     * Geeksphone Peak, where retargeting to a different EGL image is very
+     * slow. See Bug 869696.
+     */
+    if (mGLTexture) {
+      mGL->MakeCurrent();
+      mGL->fDeleteTextures(1, &mGLTexture);
+      mGLTexture = 0;
+    }
+    return;
+  }
+
   mGL->MakeCurrent();
   mGL->fActiveTexture(LOCAL_GL_TEXTURE0);
   mGL->fBindTexture(mTextureTarget, mGLTexture);
   mGL->fEGLImageTargetTexture2D(mTextureTarget, mGL->GetNullEGLImage());
 }
 
 gfx::SurfaceFormat
 GrallocTextureHostOGL::GetFormat() const
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..ec80d54126b89901f13253e9ce29bb9757da3a0f
GIT binary patch
literal 1272
zc$|e)J5t3k3^X&;oP&}xFfPS)sB^T;pmGmH_gMYxJmv|U__wmwYemlc$M^H_^2z$j
z`o?;@jqx<n!1DDH^}Zbbj^l{V9)sAN=V>hd8ku+Y7{q4IDXdd<wLYH{F%Dc70ym1>
zby`lEK)A8zLpS7{c23|peNb+`%)OIf>CmL3GIQO+e4+|-NjMDLOK4qE*kg&3g+l--
z_AOl$Ak)Uvdck95;zm<Mj$i1n8&m{{YvCS^i~#wm8Y>!-XW?2F)EPq(T#L9SV1>y7
zO=>gQuwp3gY~g{&JU2;+j$?}@SHQH+7-=cA&1AJ&so-NInGyZDzT<E8bow8jw~J2~
z&mDhDz8(Medo|y;&4(_3x_tX5KY!=5KFt6AzI6AiyN~_-y&UCo-@E@q_dglq2P5bs
A82|tP
--- a/image/test/crashtests/crashtests.list
+++ b/image/test/crashtests/crashtests.list
@@ -1,12 +1,13 @@
 asserts(0-2) load ownerdiscard.html # bug 804291, bug 807211
 
 load 83804-1.gif
 load 89341-1.gif
+load 463696.bmp
 load 570451.png
 
 load colormap-range.gif
 
 # the following tests were inspired by bug 525326
 # they have image sizes of 65535x65535 which is larger than we allow
 load invalid-size.gif
 # this image has a valid size for the first frame, but the second frame is 65535x65535
--- a/ipc/testshell/XPCShellEnvironment.cpp
+++ b/ipc/testshell/XPCShellEnvironment.cpp
@@ -1021,19 +1021,18 @@ XPCShellEnvironment::Init()
                                               principal, 0,
                                               JS::SystemZone,
                                               getter_AddRefs(holder));
     if (NS_FAILED(rv)) {
         NS_ERROR("InitClassesWithNewWrappedGlobal failed!");
         return false;
     }
 
-    JS::Rooted<JSObject*> globalObj(cx);
-    rv = holder->GetJSObject(globalObj.address());
-    if (NS_FAILED(rv)) {
+    JS::Rooted<JSObject*> globalObj(cx, holder->GetJSObject());
+    if (!globalObj) {
         NS_ERROR("Failed to get global JSObject!");
         return false;
     }
 
     backstagePass->SetGlobalObject(globalObj);
 
     {
         JSAutoRequest ar(cx);
--- a/js/src/ion/CodeGenerator.cpp
+++ b/js/src/ion/CodeGenerator.cpp
@@ -6237,18 +6237,19 @@ CodeGenerator::visitGetDOMProperty(LGetD
     const Register ObjectReg = ToRegister(ins->getObjectReg());
     const Register PrivateReg = ToRegister(ins->getPrivReg());
     const Register ValueReg = ToRegister(ins->getValueReg());
 
     DebugOnly<uint32_t> initialStack = masm.framePushed();
 
     masm.checkStackAlignment();
 
-    /* Make Space for the outparam */
-    masm.adjustStack(-int32_t(sizeof(Value)));
+    // Make space for the outparam.  Pre-initialize it to UndefinedValue so we
+    // can trace it at GC time.
+    masm.Push(UndefinedValue());
     masm.movePtr(StackPointer, ValueReg);
 
     masm.Push(ObjectReg);
 
     // GetReservedSlot(obj, DOM_OBJECT_SLOT).toPrivate()
     masm.loadPrivate(Address(ObjectReg, JSObject::getFixedSlotOffset(0)), PrivateReg);
 
     // Rooting will happen at GC time.
@@ -6302,17 +6303,17 @@ CodeGenerator::visitSetDOMProperty(LSetD
     const Register ObjectReg = ToRegister(ins->getObjectReg());
     const Register PrivateReg = ToRegister(ins->getPrivReg());
     const Register ValueReg = ToRegister(ins->getValueReg());
 
     DebugOnly<uint32_t> initialStack = masm.framePushed();
 
     masm.checkStackAlignment();
 
-    // Push thei argument. Rooting will happen at GC time.
+    // Push the argument. Rooting will happen at GC time.
     ValueOperand argVal = ToValue(ins, LSetDOMProperty::Value);
     masm.Push(argVal);
     masm.movePtr(StackPointer, ValueReg);
 
     masm.Push(ObjectReg);
 
     // GetReservedSlot(obj, DOM_OBJECT_SLOT).toPrivate()
     masm.loadPrivate(Address(ObjectReg, JSObject::getFixedSlotOffset(0)), PrivateReg);
--- a/js/src/ion/IonFrames.cpp
+++ b/js/src/ion/IonFrames.cpp
@@ -827,24 +827,24 @@ MarkIonExitFrame(JSTracer *trc, const Io
         gc::MarkIdRoot(trc, oolgetter->id(), "ion-ool-property-op-id");
         gc::MarkObjectRoot(trc, oolgetter->obj(), "ion-ool-property-op-obj");
         return;
     }
 
     if (frame.isDOMExit()) {
         IonDOMExitFrameLayout *dom = frame.exitFrame()->DOMExit();
         gc::MarkObjectRoot(trc, dom->thisObjAddress(), "ion-dom-args");
-        if (dom->isSetterFrame()) {
-            gc::MarkValueRoot(trc, dom->vp(), "ion-dom-args");
-        } else if (dom->isMethodFrame()) {
+        if (dom->isMethodFrame()) {
             IonDOMMethodExitFrameLayout *method =
                 reinterpret_cast<IonDOMMethodExitFrameLayout *>(dom);
             size_t len = method->argc() + 2;
             Value *vp = method->vp();
             gc::MarkValueRootRange(trc, len, vp, "ion-dom-args");
+        } else {
+            gc::MarkValueRoot(trc, dom->vp(), "ion-dom-args");
         }
         return;
     }
 
     MarkIonCodeRoot(trc, footer->addressOfIonCode(), "ion-exit-code");
 
     const VMFunction *f = footer->function();
     if (f == NULL || f->explicitArgs == 0)
--- a/js/src/ion/arm/IonFrames-arm.h
+++ b/js/src/ion/arm/IonFrames-arm.h
@@ -392,19 +392,16 @@ class IonDOMExitFrameLayout
         return offsetof(IonDOMExitFrameLayout, loCalleeResult_);
     }
     inline Value *vp() {
         return reinterpret_cast<Value*>(&loCalleeResult_);
     }
     inline JSObject **thisObjAddress() {
         return &thisObj;
     }
-    inline bool isSetterFrame() {
-        return footer_.ionCode() == ION_FRAME_DOMSETTER;
-    }
     inline bool isMethodFrame() {
         return footer_.ionCode() == ION_FRAME_DOMMETHOD;
     }
 };
 
 class IonDOMMethodExitFrameLayout
 {
     IonExitFooterFrame footer_;
--- a/js/src/ion/shared/IonFrames-x86-shared.h
+++ b/js/src/ion/shared/IonFrames-x86-shared.h
@@ -357,19 +357,16 @@ class IonDOMExitFrameLayout
         return offsetof(IonDOMExitFrameLayout, loCalleeResult_);
     }
     inline Value *vp() {
         return reinterpret_cast<Value*>(&loCalleeResult_);
     }
     inline JSObject **thisObjAddress() {
         return &thisObj;
     }
-    inline bool isSetterFrame() {
-        return footer_.ionCode() == ION_FRAME_DOMSETTER;
-    }
     inline bool isMethodFrame() {
         return footer_.ionCode() == ION_FRAME_DOMMETHOD;
     }
 };
 
 class IonDOMMethodExitFrameLayout
 {
   protected: // only to silence a clang warning about unused private fields
--- a/js/src/jsfriendapi.h
+++ b/js/src/jsfriendapi.h
@@ -172,17 +172,18 @@ struct JSFunctionSpecWithHelp {
 #define JS_FN_HELP(name,call,nargs,flags,usage,help)                          \
     {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, usage, help}
 #define JS_FS_HELP_END                                                        \
     {NULL, NULL, 0, 0, NULL, NULL}
 
 extern JS_FRIEND_API(bool)
 JS_DefineFunctionsWithHelp(JSContext *cx, JSObject *obj, const JSFunctionSpecWithHelp *fs);
 
-typedef bool (* JS_SourceHook)(JSContext *cx, JSScript *script, jschar **src, uint32_t *length);
+typedef bool (* JS_SourceHook)(JSContext *cx, JS::Handle<JSScript*> script,
+                               jschar **src, uint32_t *length);
 
 extern JS_FRIEND_API(void)
 JS_SetSourceHook(JSRuntime *rt, JS_SourceHook hook);
 
 namespace js {
 
 extern mozilla::ThreadLocal<PerThreadData *> TlsPerThreadData;
 
--- a/js/xpconnect/idl/nsIXPConnect.idl
+++ b/js/xpconnect/idl/nsIXPConnect.idl
@@ -58,20 +58,20 @@ interface nsIXPCSecurityManager;
 interface nsIPrincipal;
 
 %{C++
 class nsCycleCollectionTraversalCallback;
 class nsScriptObjectTracer;
 %}
 
 /***************************************************************************/
-[uuid(8916a320-d118-11d3-8f3a-0010a4e73d9a)]
+[uuid(909e8641-7c54-4dff-9b94-ba631f057b33)]
 interface nsIXPConnectJSObjectHolder : nsISupports
 {
-    readonly attribute JSObjectPtr      JSObject;
+    [notxpcom, nostdcall] JSObjectPtr GetJSObject();
 };
 
 [uuid(92e98688-0154-4b65-971b-0d4afe8fd7cb)]
 interface nsIXPConnectWrappedNative : nsIXPConnectJSObjectHolder
 {
     /* attribute 'JSObject' inherited from nsIXPConnectJSObjectHolder */
     readonly attribute nsISupports      Native;
     readonly attribute JSObjectPtr      JSObjectPrototype;
--- a/js/xpconnect/loader/mozJSComponentLoader.cpp
+++ b/js/xpconnect/loader/mozJSComponentLoader.cpp
@@ -541,50 +541,48 @@ mozJSComponentLoader::LoadModule(FileLoc
     nsCOMPtr<nsIComponentManager> cm;
     rv = NS_GetComponentManager(getter_AddRefs(cm));
     if (NS_FAILED(rv))
         return NULL;
 
     JSCLContextHelper cx(mContext);
     JSAutoCompartment ac(cx, entry->obj);
 
-    JSObject* cm_jsobj;
     nsCOMPtr<nsIXPConnectJSObjectHolder> cm_holder;
     rv = xpc->WrapNative(cx, entry->obj, cm,
                          NS_GET_IID(nsIComponentManager),
                          getter_AddRefs(cm_holder));
 
     if (NS_FAILED(rv)) {
 #ifdef DEBUG_shaver
         fprintf(stderr, "WrapNative(%p,%p,nsIComponentManager) failed: %x\n",
                 (void *)(JSContext*)cx, (void *)mCompMgr, rv);
 #endif
         return NULL;
     }
 
-    rv = cm_holder->GetJSObject(&cm_jsobj);
-    if (NS_FAILED(rv)) {
+    JSObject* cm_jsobj = cm_holder->GetJSObject();
+    if (!cm_jsobj) {
 #ifdef DEBUG_shaver
         fprintf(stderr, "GetJSObject of ComponentManager failed\n");
 #endif
         return NULL;
     }
 
-    JSObject* file_jsobj;
     nsCOMPtr<nsIXPConnectJSObjectHolder> file_holder;
     rv = xpc->WrapNative(cx, entry->obj, file,
                          NS_GET_IID(nsIFile),
                          getter_AddRefs(file_holder));
 
     if (NS_FAILED(rv)) {
         return NULL;
     }
 
-    rv = file_holder->GetJSObject(&file_jsobj);
-    if (NS_FAILED(rv)) {
+    JSObject* file_jsobj = file_holder->GetJSObject();
+    if (!file_jsobj) {
         return NULL;
     }
 
     JSCLAutoErrorReporterSetter aers(cx, mozJSLoaderErrorReporter);
 
     RootedValue NSGetFactory_val(cx);
     if (!JS_GetProperty(cx, entry->obj, "NSGetFactory", NSGetFactory_val.address()) ||
         JSVAL_IS_VOID(NSGetFactory_val)) {
@@ -657,17 +655,17 @@ mozJSComponentLoader::FindTargetObject(J
         nsAXPCNativeCallContext *cc = nullptr;
         rv = xpc->GetCurrentNativeCallContext(&cc);
         NS_ENSURE_SUCCESS(rv, rv);
 
         nsCOMPtr<nsIXPConnectWrappedNative> wn;
         rv = cc->GetCalleeWrapper(getter_AddRefs(wn));
         NS_ENSURE_SUCCESS(rv, rv);
 
-        wn->GetJSObject(targetObject.address());
+        targetObject = wn->GetJSObject();
         if (!targetObject) {
             NS_ERROR("null calling object");
             return NS_ERROR_FAILURE;
         }
 
         targetObject = JS_GetGlobalForObject(aCx, targetObject);
     }
 
@@ -740,36 +738,34 @@ mozJSComponentLoader::PrepareObjectForLo
         rv = xpc->InitClassesWithNewWrappedGlobal(aCx,
                                                   static_cast<nsIGlobalObject *>(backstagePass),
                                                   mSystemPrincipal,
                                                   0,
                                                   JS::SystemZone,
                                                   getter_AddRefs(holder));
         NS_ENSURE_SUCCESS(rv, nullptr);
 
-        RootedObject global(aCx);
-        rv = holder->GetJSObject(global.address());
-        NS_ENSURE_SUCCESS(rv, nullptr);
+        RootedObject global(aCx, holder->GetJSObject());
+        NS_ENSURE_TRUE(global, nullptr);
 
         backstagePass->SetGlobalObject(global);
 
         JSAutoCompartment ac(aCx, global);
         if (!JS_DefineFunctions(aCx, global, gGlobalFun) ||
             !JS_DefineProfilingFunctions(aCx, global)) {
             return nullptr;
         }
 
         if (aReuseLoaderGlobal) {
             mLoaderGlobal = holder;
         }
     }
 
-    RootedObject obj(aCx);
-    rv = holder->GetJSObject(obj.address());
-    NS_ENSURE_SUCCESS(rv, nullptr);
+    RootedObject obj(aCx, holder->GetJSObject());
+    NS_ENSURE_TRUE(obj, nullptr);
 
     JSAutoCompartment ac(aCx, obj);
 
     if (aReuseLoaderGlobal) {
         // If we're reusing the loader global, we don't actually use the
         // global, but rather we use a different object as the 'this' object.
         obj = JS_NewObject(aCx, &kFakeBackstagePassJSClass, nullptr, nullptr);
         NS_ENSURE_TRUE(obj, nullptr);
@@ -790,19 +786,18 @@ mozJSComponentLoader::PrepareObjectForLo
         *aRealFile = true;
 
         nsCOMPtr<nsIXPConnectJSObjectHolder> locationHolder;
         rv = xpc->WrapNative(aCx, obj, aComponentFile,
                              NS_GET_IID(nsIFile),
                              getter_AddRefs(locationHolder));
         NS_ENSURE_SUCCESS(rv, nullptr);
 
-        RootedObject locationObj(aCx);
-        rv = locationHolder->GetJSObject(locationObj.address());
-        NS_ENSURE_SUCCESS(rv, nullptr);
+        RootedObject locationObj(aCx, locationHolder->GetJSObject());
+        NS_ENSURE_TRUE(locationObj, nullptr);
 
         if (!JS_DefineProperty(aCx, obj, "__LOCATION__",
                                JS::ObjectValue(*locationObj),
                                nullptr, nullptr, 0)) {
             return nullptr;
         }
     }
 
@@ -1135,18 +1130,18 @@ mozJSComponentLoader::ClearModules(const
 void
 mozJSComponentLoader::UnloadModules()
 {
     mInitialized = false;
 
     if (mLoaderGlobal) {
         MOZ_ASSERT(mReuseLoaderGlobal, "How did this happen?");
 
-        RootedObject global(mContext);
-        if (NS_SUCCEEDED(mLoaderGlobal->GetJSObject(global.address()))) {
+        RootedObject global(mContext, mLoaderGlobal->GetJSObject());
+        if (global) {
             JSAutoRequest ar(mContext);
             JS_SetAllNonReservedSlotsToUndefined(mContext, global);
         } else {
             NS_WARNING("Going to leak!");
         }
 
         mLoaderGlobal = nullptr;
     }
--- a/js/xpconnect/public/nsTArrayHelpers.h
+++ b/js/xpconnect/public/nsTArrayHelpers.h
@@ -8,35 +8,37 @@
 template <class T>
 inline nsresult
 nsTArrayToJSArray(JSContext* aCx, const nsTArray<T>& aSourceArray,
                   JSObject** aResultArray)
 {
   MOZ_ASSERT(aCx);
   JSAutoRequest ar(aCx);
 
-  JSObject* arrayObj = JS_NewArrayObject(aCx, aSourceArray.Length(), nullptr);
+  JS::Rooted<JSObject*> arrayObj(aCx,
+    JS_NewArrayObject(aCx, aSourceArray.Length(), nullptr));
   if (!arrayObj) {
     NS_WARNING("JS_NewArrayObject failed!");
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   JS::Rooted<JSObject*> global(aCx, JS_GetGlobalForScopeChain(aCx));
   MOZ_ASSERT(global);
 
   for (uint32_t index = 0; index < aSourceArray.Length(); index++) {
     nsCOMPtr<nsISupports> obj;
     nsresult rv = aSourceArray[index]->QueryInterface(NS_GET_IID(nsISupports), getter_AddRefs(obj));
     NS_ENSURE_SUCCESS(rv, rv);
 
-    jsval wrappedVal;
-    rv = nsContentUtils::WrapNative(aCx, global, obj, &wrappedVal, nullptr, true);
+    JS::Rooted<JS::Value> wrappedVal(aCx);
+    rv = nsContentUtils::WrapNative(aCx, global, obj, wrappedVal.address(),
+                                    nullptr, true);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (!JS_SetElement(aCx, arrayObj, index, &wrappedVal)) {
+    if (!JS_SetElement(aCx, arrayObj, index, wrappedVal.address())) {
       NS_WARNING("JS_SetElement failed!");
       return NS_ERROR_FAILURE;
     }
   }
 
   if (!JS_FreezeObject(aCx, arrayObj)) {
     NS_WARNING("JS_FreezeObject failed!");
     return NS_ERROR_FAILURE;
@@ -50,34 +52,35 @@ template <>
 inline nsresult
 nsTArrayToJSArray<nsString>(JSContext* aCx,
                             const nsTArray<nsString>& aSourceArray,
                             JSObject** aResultArray)
 {
   MOZ_ASSERT(aCx);
   JSAutoRequest ar(aCx);
 
-  JSObject* arrayObj = JS_NewArrayObject(aCx, aSourceArray.Length(), nullptr);
+  JS::Rooted<JSObject*> arrayObj(aCx,
+    JS_NewArrayObject(aCx, aSourceArray.Length(), nullptr));
   if (!arrayObj) {
     NS_WARNING("JS_NewArrayObject failed!");
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   for (uint32_t index = 0; index < aSourceArray.Length(); index++) {
     JSString* s = JS_NewUCStringCopyN(aCx, aSourceArray[index].BeginReading(),
                                       aSourceArray[index].Length());
 
     if(!s) {
       NS_WARNING("Memory allocation error!");
       return NS_ERROR_OUT_OF_MEMORY;
     }
 
-    jsval wrappedVal = STRING_TO_JSVAL(s);
+    JS::Rooted<JS::Value> wrappedVal(aCx, STRING_TO_JSVAL(s));
 
-    if (!JS_SetElement(aCx, arrayObj, index, &wrappedVal)) {
+    if (!JS_SetElement(aCx, arrayObj, index, wrappedVal.address())) {
       NS_WARNING("JS_SetElement failed!");
       return NS_ERROR_FAILURE;
     }
   }
 
   if (!JS_FreezeObject(aCx, arrayObj)) {
     NS_WARNING("JS_FreezeObject failed!");
     return NS_ERROR_FAILURE;
--- a/js/xpconnect/shell/xpcshell.cpp
+++ b/js/xpconnect/shell/xpcshell.cpp
@@ -199,30 +199,29 @@ GetLocationProperty(JSContext *cx, JSHan
             absolutePath.Append(filenameString);
 
             rv = NS_NewLocalFile(absolutePath,
                                  false, getter_AddRefs(location));
         }
 
         if (location) {
             nsCOMPtr<nsIXPConnectJSObjectHolder> locationHolder;
-            JS::Rooted<JSObject*> locationObj(cx, nullptr);
 
             bool symlink;
             // don't normalize symlinks, because that's kind of confusing
             if (NS_SUCCEEDED(location->IsSymlink(&symlink)) &&
                 !symlink)
                 location->Normalize();
             rv = xpc->WrapNative(cx, obj, location,
                                  NS_GET_IID(nsIFile),
                                  getter_AddRefs(locationHolder));
 
             if (NS_SUCCEEDED(rv) &&
-                NS_SUCCEEDED(locationHolder->GetJSObject(locationObj.address()))) {
-                vp.set(OBJECT_TO_JSVAL(locationObj));
+                locationHolder->GetJSObject()) {
+                vp.set(OBJECT_TO_JSVAL(locationHolder->GetJSObject()));
             }
         }
     }
 
     return true;
 #endif
 }
 
@@ -1687,17 +1686,16 @@ static JSSecurityCallbacks shellSecurity
 int
 main(int argc, char **argv, char **envp)
 {
 #ifdef XP_MACOSX
     InitAutoreleasePool();
 #endif
     JSRuntime *rt;
     JSContext *cx;
-    JSObject *glob, *envobj;
     int result;
     nsresult rv;
 
 #ifdef HAVE_SETBUF
     // unbuffer stdout so that output is in the correct order; note that stderr
     // is unbuffered by default
     setbuf(stdout, 0);
 #endif
@@ -1815,16 +1813,19 @@ main(int argc, char **argv, char **envp)
         gOldJSContextCallback = JS_SetContextCallback(rt, ContextCallback);
 
         cx = JS_NewContext(rt, 8192);
         if (!cx) {
             printf("JS_NewContext failed!\n");
             return 1;
         }
 
+        JS::Rooted<JSObject*> glob(cx);
+        JS::Rooted<JSObject*> envobj(cx);
+
         argc--;
         argv++;
         ProcessArgsForCompartment(cx, argv, argc);
 
         nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID());
         if (!xpc) {
             printf("failed to get nsXPConnect service!\n");
             return 1;
@@ -1888,19 +1889,18 @@ main(int argc, char **argv, char **envp)
                                                   static_cast<nsIGlobalObject *>(backstagePass),
                                                   systemprincipal,
                                                   0,
                                                   JS::SystemZone,
                                                   getter_AddRefs(holder));
         if (NS_FAILED(rv))
             return 1;
 
-        rv = holder->GetJSObject(&glob);
-        if (NS_FAILED(rv)) {
-            NS_ASSERTION(glob == nullptr, "bad GetJSObject?");
+        glob = holder->GetJSObject();
+        if (!glob) {
             return 1;
         }
 
         backstagePass->SetGlobalObject(glob);
 
         JS_BeginRequest(cx);
         {
             JSAutoCompartment ac(cx, glob);
@@ -1926,18 +1926,17 @@ main(int argc, char **argv, char **envp)
 
             nsAutoString workingDirectory;
             if (GetCurrentWorkingDirectory(workingDirectory))
                 gWorkingDirectory = &workingDirectory;
 
             JS_DefineProperty(cx, glob, "__LOCATION__", JSVAL_VOID,
                               GetLocationProperty, NULL, 0);
 
-            JS::Rooted<JSObject*> rootedGlob(cx, glob);
-            result = ProcessArgs(cx, rootedGlob, argv, argc, &dirprovider);
+            result = ProcessArgs(cx, glob, argv, argc, &dirprovider);
 
             JS_DropPrincipals(rt, gJSPrincipals);
             JS_SetAllNonReservedSlotsToUndefined(cx, glob);
             JS_GC(rt);
             xpc::danger::PopJSContext();
             JS_GC(rt);
         } //this scopes the JSAutoCrossCompartmentCall
         JS_EndRequest(cx);
--- a/js/xpconnect/src/XPCComponents.cpp
+++ b/js/xpconnect/src/XPCComponents.cpp
@@ -328,17 +328,19 @@ nsXPCComponents_Interfaces::NewResolve(n
             wrapper->GetXPConnect(getter_AddRefs(xpc));
             if (xpc) {
                 nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
                 if (NS_SUCCEEDED(xpc->WrapNative(cx, obj,
                                                  static_cast<nsIJSIID*>(nsid),
                                                  NS_GET_IID(nsIJSIID),
                                                  getter_AddRefs(holder)))) {
                     RootedObject idobj(cx);
-                    if (holder && NS_SUCCEEDED(holder->GetJSObject(idobj.address()))) {
+                    if (holder &&
+                        // Assign, not compare
+                        (idobj = holder->GetJSObject())) {
                         *objp = obj;
                         *_retval = JS_DefinePropertyById(cx, obj, id,
                                                          OBJECT_TO_JSVAL(idobj),
                                                          nullptr, nullptr,
                                                          JSPROP_ENUMERATE |
                                                          JSPROP_READONLY |
                                                          JSPROP_PERMANENT);
                     }
@@ -618,17 +620,19 @@ nsXPCComponents_InterfacesByID::NewResol
         wrapper->GetXPConnect(getter_AddRefs(xpc));
         if (xpc) {
             nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
             if (NS_SUCCEEDED(xpc->WrapNative(cx, obj,
                                              static_cast<nsIJSIID*>(nsid),
                                              NS_GET_IID(nsIJSIID),
                                              getter_AddRefs(holder)))) {
                 RootedObject idobj(cx);
-                if (holder && NS_SUCCEEDED(holder->GetJSObject(idobj.address()))) {
+                if (holder &&
+                    // Assign, not compare
+                    (idobj = holder->GetJSObject())) {
                     *objp = obj;
                     *_retval =
                         JS_DefinePropertyById(cx, obj, id,
                                               OBJECT_TO_JSVAL(idobj),
                                               nullptr, nullptr,
                                               JSPROP_ENUMERATE |
                                               JSPROP_READONLY |
                                               JSPROP_PERMANENT);
@@ -898,17 +902,19 @@ nsXPCComponents_Classes::NewResolve(nsIX
             wrapper->GetXPConnect(getter_AddRefs(xpc));
             if (xpc) {
                 nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
                 if (NS_SUCCEEDED(xpc->WrapNative(cx, obj,
                                                  static_cast<nsIJSCID*>(nsid),
                                                  NS_GET_IID(nsIJSCID),
                                                  getter_AddRefs(holder)))) {
                     RootedObject idobj(cx);
-                    if (holder && NS_SUCCEEDED(holder->GetJSObject(idobj.address()))) {
+                    if (holder &&
+                        // Assign, not compare
+                        (idobj = holder->GetJSObject())) {
                         *objp = obj;
                         *_retval = JS_DefinePropertyById(cx, obj, id,
                                                          OBJECT_TO_JSVAL(idobj),
                                                          nullptr, nullptr,
                                                          JSPROP_ENUMERATE |
                                                          JSPROP_READONLY |
                                                          JSPROP_PERMANENT);
                     }
@@ -1160,17 +1166,19 @@ nsXPCComponents_ClassesByID::NewResolve(
             wrapper->GetXPConnect(getter_AddRefs(xpc));
             if (xpc) {
                 nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
                 if (NS_SUCCEEDED(xpc->WrapNative(cx, obj,
                                                  static_cast<nsIJSCID*>(nsid),
                                                  NS_GET_IID(nsIJSCID),
                                                  getter_AddRefs(holder)))) {
                     RootedObject idobj(cx);
-                    if (holder && NS_SUCCEEDED(holder->GetJSObject(idobj.address()))) {
+                    if (holder &&
+                        // Assign, not compare
+                        (idobj = holder->GetJSObject())) {
                         *objp = obj;
                         *_retval = JS_DefinePropertyById(cx, obj, id,
                                                          ObjectValue(*idobj),
                                                          nullptr, nullptr,
                                                          JSPROP_ENUMERATE |
                                                          JSPROP_READONLY |
                                                          JSPROP_PERMANENT);
                     }
@@ -1974,17 +1982,18 @@ nsXPCComponents_Exception::CallOrConstru
     if (!e)
         return ThrowAndFail(NS_ERROR_XPC_UNEXPECTED, cx, _retval);
 
     nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
     RootedObject newObj(cx);
 
     if (NS_FAILED(xpc->WrapNative(cx, obj, e, NS_GET_IID(nsIXPCException),
                                   getter_AddRefs(holder))) || !holder ||
-        NS_FAILED(holder->GetJSObject(newObj.address())) || !newObj) {
+        // Assign, not compare
+        !(newObj = holder->GetJSObject())) {
         return ThrowAndFail(NS_ERROR_XPC_CANT_CREATE_WN, cx, _retval);
     }
 
     args.rval().setObject(*newObj);
     return NS_OK;
 }
 
 /* bool hasInstance (in nsIXPConnectWrappedNative wrapper, in JSContextPtr cx, in JSObjectPtr obj, in jsval val, out bool bp); */
@@ -2231,20 +2240,22 @@ nsXPCConstructor::CallOrConstruct(nsIXPC
 
     nsCOMPtr<nsIXPConnectJSObjectHolder> cidHolder;
     nsCOMPtr<nsIXPConnectJSObjectHolder> iidHolder;
     RootedObject cidObj(cx);
     RootedObject iidObj(cx);
 
     if (NS_FAILED(xpc->WrapNative(cx, obj, mClassID, NS_GET_IID(nsIJSCID),
                                   getter_AddRefs(cidHolder))) || !cidHolder ||
-        NS_FAILED(cidHolder->GetJSObject(cidObj.address())) || !cidObj ||
+        // Assign, not compare
+        !(cidObj = cidHolder->GetJSObject()) ||
         NS_FAILED(xpc->WrapNative(cx, obj, mInterfaceID, NS_GET_IID(nsIJSIID),
                                   getter_AddRefs(iidHolder))) || !iidHolder ||
-        NS_FAILED(iidHolder->GetJSObject(iidObj.address())) || !iidObj) {
+        // Assign, not compare
+        !(iidObj = iidHolder->GetJSObject())) {
         return ThrowAndFail(NS_ERROR_XPC_CANT_CREATE_WN, cx, _retval);
     }
 
     Value argv[1] = {ObjectValue(*iidObj)};
     RootedValue rval(cx);
     if (!JS_CallFunctionName(cx, cidObj, "createInstance", 1, argv, rval.address()) ||
         rval.isPrimitive()) {
         // createInstance will have thrown an exception
@@ -2498,17 +2509,18 @@ nsXPCComponents_Constructor::CallOrConst
         // we do the lookup by asking the Components.interfaces object
         // for the property with this name - i.e. we let its caching of these
         // nsIJSIID objects work for us.
 
         if (NS_FAILED(comp->GetInterfaces(getter_AddRefs(ifaces))) ||
             NS_FAILED(xpc->WrapNative(cx, obj, ifaces,
                                       NS_GET_IID(nsIXPCComponents_Interfaces),
                                       getter_AddRefs(holder))) || !holder ||
-            NS_FAILED(holder->GetJSObject(ifacesObj.address())) || !ifacesObj) {
+            // Assign, not compare
+            !(ifacesObj = holder->GetJSObject())) {
             return ThrowAndFail(NS_ERROR_XPC_UNEXPECTED, cx, _retval);
         }
 
         RootedString str(cx, JS_ValueToString(cx, args[1]));
         RootedId id(cx);
         if (!str || !JS_ValueToId(cx, StringValue(str), id.address()))
             return ThrowAndFail(NS_ERROR_XPC_BAD_CONVERT_JS, cx, _retval);
 
@@ -2546,17 +2558,18 @@ nsXPCComponents_Constructor::CallOrConst
         nsCOMPtr<nsIXPCComponents_Classes> classes;
         nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
         RootedObject classesObj(cx);
 
         if (NS_FAILED(comp->GetClasses(getter_AddRefs(classes))) ||
             NS_FAILED(xpc->WrapNative(cx, obj, classes,
                                       NS_GET_IID(nsIXPCComponents_Classes),
                                       getter_AddRefs(holder))) || !holder ||
-            NS_FAILED(holder->GetJSObject(classesObj.address())) || !classesObj) {
+            // Assign, not compare
+            !(classesObj = holder->GetJSObject())) {
             return ThrowAndFail(NS_ERROR_XPC_UNEXPECTED, cx, _retval);
         }
 
         RootedString str(cx, JS_ValueToString(cx, args[0]));
         RootedId id(cx);
         if (!str || !JS_ValueToId(cx, StringValue(str), id.address()))
             return ThrowAndFail(NS_ERROR_XPC_BAD_CONVERT_JS, cx, _retval);
 
@@ -2578,17 +2591,18 @@ nsXPCComponents_Constructor::CallOrConst
     if (!ctor)
         return ThrowAndFail(NS_ERROR_XPC_UNEXPECTED, cx, _retval);
 
     nsCOMPtr<nsIXPConnectJSObjectHolder> holder2;
     RootedObject newObj(cx);
 
     if (NS_FAILED(xpc->WrapNative(cx, obj, ctor, NS_GET_IID(nsIXPCConstructor),
                                   getter_AddRefs(holder2))) || !holder2 ||
-        NS_FAILED(holder2->GetJSObject(newObj.address())) || !newObj) {
+        // Assign, not compare
+        !(newObj = holder2->GetJSObject())) {
         return ThrowAndFail(NS_ERROR_XPC_CANT_CREATE_WN, cx, _retval);
     }
 
     args.rval().setObject(*newObj);
     return NS_OK;
 }
 
 /* bool hasInstance (in nsIXPConnectWrappedNative wrapper, in JSContextPtr cx, in JSObjectPtr obj, in jsval val, out bool bp); */
--- a/js/xpconnect/src/XPCJSID.cpp
+++ b/js/xpconnect/src/XPCJSID.cpp
@@ -720,17 +720,17 @@ GetWrapperObject(MutableHandleObject obj
 
     nsAXPCNativeCallContext *ccxp = NULL;
     xpc->GetCurrentNativeCallContext(&ccxp);
     if (!ccxp)
         return;
 
     nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
     ccxp->GetCalleeWrapper(getter_AddRefs(wrapper));
-    wrapper->GetJSObject(obj.address());
+    obj.set(wrapper->GetJSObject());
 }
 
 /* nsISupports createInstance (); */
 NS_IMETHODIMP
 nsJSCID::CreateInstance(const JS::Value& iidval, JSContext* cx,
                         uint8_t optionalArgc, JS::Value* retval)
 {
     if (!mDetails.IsValid())
@@ -814,17 +814,19 @@ nsJSCID::GetService(const JS::Value& iid
     rv = svcMgr->GetService(mDetails.ID(), *iid, getter_AddRefs(srvc));
     NS_ASSERTION(NS_FAILED(rv) || srvc, "service manager returned success, but service is null!");
     if (NS_FAILED(rv) || !srvc)
         return NS_ERROR_XPC_GS_RETURNED_FAILURE;
 
     RootedObject instJSObj(cx);
     nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
     rv = nsXPConnect::GetXPConnect()->WrapNative(cx, obj, srvc, *iid, getter_AddRefs(holder));
-    if (NS_FAILED(rv) || !holder || NS_FAILED(holder->GetJSObject(instJSObj.address())))
+    if (NS_FAILED(rv) || !holder ||
+        // Assign, not compare
+        !(instJSObj = holder->GetJSObject()))
         return NS_ERROR_XPC_CANT_CREATE_WN;
 
     *retval = OBJECT_TO_JSVAL(instJSObj);
     return NS_OK;
 }
 
 /* bool construct (in nsIXPConnectWrappedNative wrapper, in JSContextPtr cx, in JSObjectPtr obj, in uint32_t argc, in JSValPtr argv, in JSValPtr vp); */
 NS_IMETHODIMP
@@ -896,17 +898,17 @@ xpc_NewIDObject(JSContext *cx, HandleObj
         nsXPConnect* xpc = nsXPConnect::GetXPConnect();
         if (xpc) {
             nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
             nsresult rv = xpc->WrapNative(cx, jsobj,
                                           static_cast<nsISupports*>(iid),
                                           NS_GET_IID(nsIJSID),
                                           getter_AddRefs(holder));
             if (NS_SUCCEEDED(rv) && holder) {
-                holder->GetJSObject(obj.address());
+                obj = holder->GetJSObject();
             }
         }
     }
     return obj;
 }
 
 // note: returned pointer is only valid while |obj| remains alive!
 const nsID*
--- a/js/xpconnect/src/XPCJSRuntime.cpp
+++ b/js/xpconnect/src/XPCJSRuntime.cpp
@@ -2596,17 +2596,18 @@ ReadSourceFromFilename(JSContext *cx, co
   return NS_OK;
 }
 
 /*
   The JS engine calls this function when it needs the source for a chrome JS
   function. See the comment in the XPCJSRuntime constructor.
 */
 static bool
-SourceHook(JSContext *cx, JSScript *script, jschar **src, uint32_t *length)
+SourceHook(JSContext *cx, JS::Handle<JSScript*> script, jschar **src,
+           uint32_t *length)
 {
   *src = NULL;
   *length = 0;
 
   if (!nsContentUtils::IsCallerChrome())
     return true;
 
   const char *filename = JS_GetScriptFilename(cx, script);
--- a/js/xpconnect/src/XPCJSWeakReference.cpp
+++ b/js/xpconnect/src/XPCJSWeakReference.cpp
@@ -73,18 +73,17 @@ xpcJSWeakReference::Get(JSContext* aCx, 
         // We have a generic XPCOM object that supports weak references here.
         // Wrap it and pass it out.
         JS::Rooted<JSObject*> global(aCx, JS_GetGlobalForScopeChain(aCx));
         return nsContentUtils::WrapNative(aCx, global,
                                           supports, &NS_GET_IID(nsISupports),
                                           aRetval);
     }
 
-    JS::RootedObject obj(aCx);
-    wrappedObj->GetJSObject(obj.address());
+    JS::RootedObject obj(aCx, wrappedObj->GetJSObject());
     if (!obj) {
         return NS_OK;
     }
 
     // Most users of XPCWrappedJS don't need to worry about
     // re-wrapping because things are implicitly rewrapped by
     // xpcconvert. However, because we're doing this directly
     // through the native call context, we need to call
--- a/js/xpconnect/src/XPCThrower.cpp
+++ b/js/xpconnect/src/XPCThrower.cpp
@@ -246,18 +246,18 @@ XPCThrower::ThrowExceptionObject(JSConte
             if (!glob)
                 return false;
 
             nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
             nsresult rv = xpc->WrapNative(cx, glob, e,
                                           NS_GET_IID(nsIException),
                                           getter_AddRefs(holder));
             if (NS_SUCCEEDED(rv) && holder) {
-                JS::RootedObject obj(cx);
-                if (NS_SUCCEEDED(holder->GetJSObject(obj.address()))) {
+                JS::RootedObject obj(cx, holder->GetJSObject());
+                if (obj) {
                     JS_SetPendingException(cx, OBJECT_TO_JSVAL(obj));
                     success = true;
                 }
             }
         }
     }
     return success;
 }
--- a/js/xpconnect/src/XPCWrappedJS.cpp
+++ b/js/xpconnect/src/XPCWrappedJS.cpp
@@ -231,25 +231,20 @@ NS_IMETHODIMP
 nsXPCWrappedJS::GetWeakReference(nsIWeakReference** aInstancePtr)
 {
     if (mRoot != this)
         return mRoot->GetWeakReference(aInstancePtr);
 
     return nsSupportsWeakReference::GetWeakReference(aInstancePtr);
 }
 
-NS_IMETHODIMP
-nsXPCWrappedJS::GetJSObject(JSObject** aJSObj)
+JSObject*
+nsXPCWrappedJS::GetJSObject()
 {
-    NS_PRECONDITION(aJSObj, "bad param");
-    NS_PRECONDITION(IsValid(), "bad wrapper");
-
-    if (!(*aJSObj = GetJSObject()))
-        return NS_ERROR_OUT_OF_MEMORY;
-    return NS_OK;
+    return xpc_UnmarkGrayObject(mJSObj);
 }
 
 static bool
 CheckMainThreadOnly(nsXPCWrappedJS *aWrapper)
 {
     if(aWrapper->IsMainThreadOnly())
         return NS_IsMainThread();
 
--- a/js/xpconnect/src/XPCWrappedNative.cpp
+++ b/js/xpconnect/src/XPCWrappedNative.cpp
@@ -558,19 +558,17 @@ XPCWrappedNative::GetNewOrUsed(XPCCallCo
             return NS_OK;
         }
     } else {
         ac.construct(ccx, parent);
 
         nsISupports *Object = helper.Object();
         if (nsXPCWrappedJSClass::IsWrappedJS(Object)) {
             nsCOMPtr<nsIXPConnectWrappedJS> wrappedjs(do_QueryInterface(Object));
-            RootedObject obj(ccx);
-            wrappedjs->GetJSObject(obj.address());
-            if (xpc::AccessCheck::isChrome(js::GetObjectCompartment(obj)) &&
+            if (xpc::AccessCheck::isChrome(js::GetObjectCompartment(wrappedjs->GetJSObject())) &&
                 !xpc::AccessCheck::isChrome(js::GetObjectCompartment(Scope->GetGlobalJSObject()))) {
                 needsCOW = true;
             }
         }
     }
 
     AutoMarkingWrappedNativeProtoPtr proto(ccx);
 
@@ -1913,19 +1911,18 @@ XPCWrappedNative::InitTearOff(XPCCallCon
         // into an infinite loop.
         // see: http://bugzilla.mozilla.org/show_bug.cgi?id=96725
 
         // The code in this block also does a check for the double wrapped
         // nsIPropertyBag case.
 
         nsCOMPtr<nsIXPConnectWrappedJS> wrappedJS(do_QueryInterface(obj));
         if (wrappedJS) {
-            RootedObject jso(ccx);
-            if (NS_SUCCEEDED(wrappedJS->GetJSObject(jso.address())) &&
-                jso == mFlatJSObject) {
+            RootedObject jso(ccx, wrappedJS->GetJSObject());
+            if (jso == mFlatJSObject) {
                 // The implementing JSObject is the same as ours! Just say OK
                 // without actually extending the set.
                 //
                 // XXX It is a little cheesy to have FindTearOff return an
                 // 'empty' tearoff. But this is the centralized place to do the
                 // QI activities on the underlying object. *And* most caller to
                 // FindTearOff only look for a non-null result and ignore the
                 // actual tearoff returned. The only callers that do use the
@@ -2938,21 +2935,21 @@ CallMethodHelper::Invoke()
     nsXPTCVariant* argv = mDispatchParams.Elements();
 
     return NS_InvokeByIndex(mCallee, mVTableIndex, argc, argv);
 }
 
 /***************************************************************************/
 // interface methods
 
-/* readonly attribute JSObjectPtr JSObject; */
-NS_IMETHODIMP XPCWrappedNative::GetJSObject(JSObject * *aJSObject)
+/* JSObjectPtr GetJSObject(); */
+JSObject*
+XPCWrappedNative::GetJSObject()
 {
-    *aJSObject = GetFlatJSObject();
-    return NS_OK;
+    return GetFlatJSObject();
 }
 
 /* readonly attribute nsISupports Native; */
 NS_IMETHODIMP XPCWrappedNative::GetNative(nsISupports * *aNative)
 {
     // No need to QI here, we already have the correct nsISupports
     // vtable.
     *aNative = mIdentity;
@@ -3544,23 +3541,21 @@ void DEBUG_ReportShadowedMembers(XPCNati
             }
         }
     }
 }
 #endif
 
 NS_IMPL_THREADSAFE_ISUPPORTS1(XPCJSObjectHolder, nsIXPConnectJSObjectHolder)
 
-NS_IMETHODIMP
-XPCJSObjectHolder::GetJSObject(JSObject** aJSObj)
+JSObject*
+XPCJSObjectHolder::GetJSObject()
 {
-    NS_PRECONDITION(aJSObj, "bad param");
     NS_PRECONDITION(mJSObj, "bad object state");
-    *aJSObj = mJSObj;
-    return NS_OK;
+    return mJSObj;
 }
 
 XPCJSObjectHolder::XPCJSObjectHolder(XPCCallContext& ccx, JSObject* obj)
     : mJSObj(obj)
 {
     ccx.GetRuntime()->AddObjectHolderRoot(this);
 }
 
--- a/js/xpconnect/src/XPCWrappedNativeJSOps.cpp
+++ b/js/xpconnect/src/XPCWrappedNativeJSOps.cpp
@@ -141,18 +141,18 @@ XPC_WN_Shared_ToSource(JSContext *cx, un
 
 static JSObject*
 GetDoubleWrappedJSObject(XPCCallContext& ccx, XPCWrappedNative* wrapper)
 {
     RootedObject obj(ccx);
     nsCOMPtr<nsIXPConnectWrappedJS>
         underware = do_QueryInterface(wrapper->GetIdentityObject());
     if (underware) {
-        RootedObject mainObj(ccx);
-        if (NS_SUCCEEDED(underware->GetJSObject(mainObj.address())) && mainObj) {
+        RootedObject mainObj(ccx, underware->GetJSObject());
+        if (mainObj) {
             RootedId id(ccx, ccx.GetRuntime()->
                             GetStringID(XPCJSRuntime::IDX_WRAPPED_JSOBJECT));
 
             JSAutoCompartment ac(ccx, mainObj);
 
             RootedValue val(ccx);
             if (JS_GetPropertyById(ccx, mainObj, id, val.address()) &&
                 !JSVAL_IS_PRIMITIVE(val)) {
--- a/js/xpconnect/src/dom_quickstubs.qsconf
+++ b/js/xpconnect/src/dom_quickstubs.qsconf
@@ -48,17 +48,16 @@ members = [
     'nsIDOMJSWindow.dump',
     # nsLocationSH has ~ALLOW_PROP_MODS_TO_PROTOTYPE, so don't try.
     #'nsIDOMLocation.hostname',
     #'nsIDOMLocation.href',
 
     # dom/interfaces/core
     'nsIDOMDOMStringList.*',
 
-    'nsIDOMKeyEvent.*',
     'nsIDOMDragEvent.*',
     'nsIDOMProgressEvent.lengthComputable',
     'nsIDOMProgressEvent.loaded',
     'nsIDOMProgressEvent.total',
     #XXX Can't quickstub initProgressEvent because it has long long parameters.
 
     'nsIDOMTouchList.*',
 
--- a/js/xpconnect/src/xpcprivate.h
+++ b/js/xpconnect/src/xpcprivate.h
@@ -3142,22 +3142,16 @@ public:
                  JSObject* aJSObj,
                  REFNSIID aIID,
                  nsISupports* aOuter,
                  nsXPCWrappedJS** wrapper);
 
     nsISomeInterface* GetXPTCStub() { return mXPTCStub; }
 
     /**
-     * This getter clears the gray bit before handing out the JSObject which
-     * means that the object is guaranteed to be kept alive past the next CC.
-     */
-    JSObject* GetJSObject() const {return xpc_UnmarkGrayObject(mJSObj);}
-
-    /**
      * This getter does not change the color of the JSObject meaning that the
      * object returned is not guaranteed to be kept alive past the next CC.
      *
      * This should only be called if you are certain that the return value won't
      * be passed into a JS API function and that it won't be stored without
      * being rooted (or otherwise signaling the stored value to the CC).
      */
     JSObject* GetJSObjectPreserveColor() const {return mJSObj;}
new file mode 100644
--- /dev/null
+++ b/layout/base/crashtests/367498-1.html
@@ -0,0 +1,8 @@
+<html><head>
+</head><body>
+This page should not have a very large height;
+<span style="display: -moz-grid-line;">
+<select></select>
+</span>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/base/crashtests/367498-2.html
@@ -0,0 +1,14 @@
+<html><head>
+</head><body>
+<marquee>
+<div style="border: 1px solid black; -moz-border-radius: 2em;">
+<marquee>
+<span style="display: -moz-grid-line;">
+<select></select>
+</span>
+</marquee>
+</div>
+</marquee>
+
+</body>
+</html>
--- a/layout/base/crashtests/crashtests.list
+++ b/layout/base/crashtests/crashtests.list
@@ -128,16 +128,18 @@ load 363729-3.html
 load 364427-1.html
 load 365909-1.xhtml
 load 365909-2.xhtml
 load 366128-1.xhtml
 load 366271-1.html
 load 366967-1.html
 load 367015-1.html
 load 367243-1.html
+load 367498-1.html
+load 367498-2.html
 load 369176-1.html
 load 369945-1.xhtml
 load 371681-1.xhtml
 load 372237-1.html
 load 372475-1.xhtml
 load 372550-1.html
 load 372576.xul
 load 373628-1.html
new file mode 100644
--- /dev/null
+++ b/layout/forms/crashtests/682684-binding.xml
@@ -0,0 +1,4 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+<style>html::before { content:"b"; }</style>
+<input contenteditable="true" spellcheck="true"/>
+</html>
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/layout/forms/crashtests/682684.xhtml
@@ -0,0 +1,3 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+<span style="mask: url(682684-binding.xml#a);"/>
+</html>
--- a/layout/forms/crashtests/crashtests.list
+++ b/layout/forms/crashtests/crashtests.list
@@ -43,9 +43,10 @@ load 513113-1.html
 load 538062-1.xhtml
 load 570624-1.html
 skip-if(B2G) load 498698-1.html # bug 833371
 asserts(1) load 578604-1.html # bug 584564
 asserts(4-7) load 590302-1.xhtml # bug 584564
 load 626014.xhtml
 load 639733.xhtml
 asserts(0-1) load 669767.html
+load 682684.xhtml
 load 865602.html
new file mode 100644
--- /dev/null
+++ b/layout/generic/crashtests/367360.html
@@ -0,0 +1,30 @@
+<html><head>
+<title>Testcase bug - Crash [@ nsHTMLButtonControlFrame::GetContentInsertionFrame] with -moz-column-count and display: list-item</title>
+</head>
+<body>
+<div style="display: table;">
+text
+<listing style="-moz-column-count: 2;">
+<dl>
+
+
+
+
+
+
+
+
+tesxt
+
+
+<menu>
+<span style="display: list-item;  -moz-column-count: 1;">
+<span style="display: list-item;  -moz-column-count: 1;">
+text
+</span></span>
+</menu>
+<div>text</div>
+</dl>
+</listing>
+</div>
+</body></html>
new file mode 100644
--- /dev/null
+++ b/layout/generic/crashtests/368752.html
@@ -0,0 +1,20 @@
+<html class="reftest-wait"><head>
+<title>Testcase bug - Crash [@ nsIFrame::Invalidate] with display: inherit, large margin and padding and generated content</title>
+<script>
+function addstyle(){
+var x=document.createElementNS('http://www.w3.org/1999/xhtml','style');
+x.innerHTML='body::before {content: "text"; }';
+document.documentElement.appendChild(x);
+document.documentElement.offsetHeight;
+document.documentElement.removeAttribute("class");
+}
+</script>
+
+</head>
+<body onload="setTimeout(addstyle,0);">
+<div style="display: table;">
+<div style="display: inherit;float: left;margin-bottom: -9999999px;padding-top: 9999999999px;">
+<span style="position: fixed;">t</span>
+</div>
+</div>
+</body></html>
new file mode 100644
--- /dev/null
+++ b/layout/generic/crashtests/493649.html
@@ -0,0 +1,5 @@
+<html xmlns="http://www.w3.org/1999/xhtml" style="position: fixed; -moz-column-count: 3; white-space: pre;"><body style="height: 0pt;">
+
+
+
+</body></html>
--- a/layout/generic/crashtests/crashtests.list
+++ b/layout/generic/crashtests/crashtests.list
@@ -64,19 +64,21 @@ load 363722-2.html
 load 363848-1.xhtml
 load 364220.html
 load 364407-1.html
 load 364686-1.xhtml
 load 366021-1.xhtml
 load 366667-1.html
 load 366952-1.html
 load 367246-1.html
+load 367360.html
 load 368330-1.html
 load 368461-1.xhtml
 load 368568.html
+load 368752.html
 load 368860-1.html
 load 368863-1.html
 load 369038-1.xhtml
 load 369150-1.html
 load 369150-2.html
 load 369227-1.xhtml
 load 369542-1.html
 load 369542-2.html
@@ -327,16 +329,17 @@ load 478170-1.html
 load 478185-1.html
 asserts-if(!Android,1) load 479938-1.html # Bug 575011
 load 480345-1.html
 skip-if(Android) load 481921.html
 load 489462-1.html
 load 489480-1.xhtml
 load 493111-1.html
 load 493118-1.html
+load 493649.html
 load 494283-1.xhtml
 load 494283-2.html
 load 494300-1.xul
 load 494332-1.html
 load 495875-1.html
 load 495875-2.html
 load 496742.html
 load 499138.html
--- a/layout/generic/nsFlexContainerFrame.cpp
+++ b/layout/generic/nsFlexContainerFrame.cpp
@@ -460,38 +460,31 @@ protected:
   bool mHadMeasuringReflow; // Did this item get a preliminary reflow,
                             // to measure its desired height?
   bool mIsStretched; // See IsStretched() documentation
   uint8_t mAlignSelf; // My "align-self" computed value (with "auto"
                       // swapped out for parent"s "align-items" value,
                       // in our constructor).
 };
 
-/**
- * Helper-function to find the nsIContent* that we should use for comparing the
- * DOM tree position of the given flex-item frame.
- *
- * In most cases, this will be aFrame->GetContent(), but if aFrame is an
- * anonymous container, then its GetContent() won't be what we want. In such
- * cases, we need to find aFrame's first non-anonymous-container descendant.
- */
-static nsIContent*
-GetContentForComparison(const nsIFrame* aFrame)
+// Helper-function to find the first non-anonymous-box descendent of aFrame.
+static nsIFrame*
+GetFirstNonAnonBoxDescendant(nsIFrame* aFrame)
 {
-  MOZ_ASSERT(aFrame, "null frame passed to GetContentForComparison()");
+  MOZ_ASSERT(aFrame, "null frame passed to GetFirstNonAnonBoxDescendant()");
   MOZ_ASSERT(aFrame->IsFlexItem(), "only intended for flex items");
 
   while (true) {
     nsIAtom* pseudoTag = aFrame->StyleContext()->GetPseudo();
 
     // If aFrame isn't an anonymous container, then it'll do.
     if (!pseudoTag ||                                 // No pseudotag.
         !nsCSSAnonBoxes::IsAnonBox(pseudoTag) ||      // Pseudotag isn't anon.
         pseudoTag == nsCSSAnonBoxes::mozNonElement) { // Text, not a container.
-      return aFrame->GetContent();
+      return aFrame;
     }
 
     // Otherwise, descend to its first child and repeat.
     aFrame = aFrame->GetFirstPrincipalChild();
     MOZ_ASSERT(aFrame, "why do we have an anonymous box without any children?");
   }
 }
 
@@ -523,16 +516,23 @@ IsOrderLEQWithDOMFallback(nsIFrame* aFra
 
   int32_t order1 = aFrame1->StylePosition()->mOrder;
   int32_t order2 = aFrame2->StylePosition()->mOrder;
 
   if (order1 != order2) {
     return order1 < order2;
   }
 
+  // The "order" values are equal, so we need to fall back on DOM comparison.
+  // For that, we need to dig through any anonymous box wrapper frames to find
+  // the actual frame that corresponds to our child content.
+  aFrame1 = GetFirstNonAnonBoxDescendant(aFrame1);
+  aFrame2 = GetFirstNonAnonBoxDescendant(aFrame2);
+
+  // Special case:
   // If either frame is for generated content from ::before or ::after, then
   // we can't use nsContentUtils::PositionIsBefore(), since that method won't
   // recognize generated content as being an actual sibling of other nodes.
   // We know where ::before and ::after nodes *effectively* insert in the DOM
   // tree, though (at the beginning & end), so we can just special-case them.
   nsIAtom* pseudo1 = aFrame1->StyleContext()->GetPseudo();
   nsIAtom* pseudo2 = aFrame2->StyleContext()->GetPseudo();
   if (pseudo1 == nsCSSPseudoElements::before ||
@@ -541,19 +541,19 @@ IsOrderLEQWithDOMFallback(nsIFrame* aFra
     return true;
   }
   if (pseudo1 == nsCSSPseudoElements::after ||
       pseudo2 == nsCSSPseudoElements::before) {
     // frame1 is ::after and/or frame2 is ::before => frame1 is not LEQ frame2.
     return false;
   }
 
-  // Same "order" value --> use DOM position.
-  nsIContent* content1 = GetContentForComparison(aFrame1);
-  nsIContent* content2 = GetContentForComparison(aFrame2);
+  // Usual case: Compare DOM position.
+  nsIContent* content1 = aFrame1->GetContent();
+  nsIContent* content2 = aFrame2->GetContent();
   MOZ_ASSERT(content1 != content2,
              "Two different flex items are using the same nsIContent node for "
              "comparison, so we may be sorting them in an arbitrary order");
 
   return nsContentUtils::PositionIsBefore(content1, content2);
 }
 
 /**
copy from layout/reftests/flexbox/flexbox-with-pseudo-elements-1-ref.html
copy to layout/reftests/flexbox/flexbox-with-pseudo-elements-3-ref.html
--- a/layout/reftests/flexbox/flexbox-with-pseudo-elements-1-ref.html
+++ b/layout/reftests/flexbox/flexbox-with-pseudo-elements-3-ref.html
@@ -17,22 +17,20 @@
       align-items: flex-end;
       justify-content: space-between;
       height: 50px;
       width: 300px;
       margin-bottom: 2px;
       background: lightgray;
     }
     .fakeBefore {
-      align-self: center;
       content: 'b';
       background: yellow;
     }
     .fakeAfter {
-      align-self: center;
       content: 'a';
       background: lightblue;
     }
   </style>
 </head>
 <body>
   <div class="flexContainer">
     <div class="fakeBefore">b</div>
copy from layout/reftests/flexbox/flexbox-with-pseudo-elements-1.html
copy to layout/reftests/flexbox/flexbox-with-pseudo-elements-3.html
--- a/layout/reftests/flexbox/flexbox-with-pseudo-elements-1.html
+++ b/layout/reftests/flexbox/flexbox-with-pseudo-elements-3.html
@@ -1,39 +1,47 @@
 <!DOCTYPE html>
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
-<!-- Testcase to ensure we handle ::before and ::after pseudo-elements on
-     a flex container and treat them as flex items (e.g. honoring "align-self",
-     and not merging them into anonymous flex items formed around text).
--->
+<!-- Testcase to ensure we handle ::before and ::after pseudo-elements on a
+     flex container, specifically when they've got display:table-row or
+     table-cell.
+
+     Note that we *don't* treat the table row or cell frames themselves as flex
+     items, because they get wrapped in an anonymous table box, and *that* is
+     the flex item.  So, "align-self" and "order" have no effect on the
+     row/cell. -->
 <html>
 <head>
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       align-items: flex-end;
       justify-content: space-between;
       height: 50px;
       width: 300px;
       margin-bottom: 2px;
       background: lightgray;
     }
     div.withBefore::before {
-      align-self: center;
+      display: table-row;
       content: 'b';
       background: yellow;
+      align-self: center; /* should have no effect */
+      order: 1;           /* should have no effect */
     }
     div.withAfter::after {
-      align-self: center;
+      display: table-cell;
       content: 'a';
       background: lightblue;
+      align-self: center; /* should have no effect */
+      order: -1;          /* should have no effect */
     }
   </style>
 </head>
 <body>
   <div class="flexContainer withBefore">
     x
     <div>y</div>
     z
--- a/layout/reftests/flexbox/reftest.list
+++ b/layout/reftests/flexbox/reftest.list
@@ -223,8 +223,9 @@ skip-if(B2G) == flexbox-resizeviewport-1
 fuzzy-if(gtk2Widget,1,66) == flexbox-widget-flex-items-1.html flexbox-widget-flex-items-1-ref.html
 fuzzy-if(gtk2Widget,1,74) == flexbox-widget-flex-items-2.html flexbox-widget-flex-items-2-ref.html
 fuzzy-if(gtk2Widget,1,58) == flexbox-widget-flex-items-3.html flexbox-widget-flex-items-3-ref.html
 fuzzy-if(gtk2Widget,1,31) == flexbox-widget-flex-items-4.html flexbox-widget-flex-items-4-ref.html
 
 # Tests for flex containers with pseudo-elements
 == flexbox-with-pseudo-elements-1.html flexbox-with-pseudo-elements-1-ref.html
 == flexbox-with-pseudo-elements-2.html flexbox-with-pseudo-elements-2-ref.html
+== flexbox-with-pseudo-elements-3.html flexbox-with-pseudo-elements-3-ref.html
--- a/layout/reftests/svg/text/pattern-content-ref.svg
+++ b/layout/reftests/svg/text/pattern-content-ref.svg
@@ -5,12 +5,12 @@
 <svg xmlns="http://www.w3.org/2000/svg">
   <defs>
     <pattern id="p2" width="8" height="8" patternUnits="userSpaceOnUse">
       <rect x="-1" y="-1" width="10" height="10" fill="yellow"/>
       <rect width="4" height="4"/>
       <rect x="4" y="4" width="4" height="4"/>
     </pattern>
   </defs>
-  <g transform="scale(2,1)translate(50,120)scale(4)">
-    <text style="font: bold 48px sans-serif; fill: url(#p2)">a</text>
+  <g transform="scale(2)translate(50,120)scale(4)">
+    <text style="font: bold 48px sans-serif; fill: url(#p2); stroke: black; stroke-width: 1px">a</text>
   </g>
 </svg>
--- a/layout/reftests/svg/text/pattern-content.svg
+++ b/layout/reftests/svg/text/pattern-content.svg
@@ -10,10 +10,13 @@
       <rect x="4" y="4" width="4" height="4"/>
     </pattern>
     <pattern id="p" width="200" height="200" patternUnits="userSpaceOnUse">
       <g transform="translate(50,120)scale(4)">
         <text style="font: bold 48px sans-serif; fill: url(#p2)">a</text>
       </g>
     </pattern>
   </defs>
-  <rect width="200" height="200" fill="url(#p)" transform="scale(2,1)"/>
+  <rect width="200" height="200" fill="url(#p)" transform="scale(2)"/>
+  <g transform="scale(2)translate(50,120)scale(4)">
+    <text style="font: bold 48px sans-serif; fill: none; stroke: black; stroke-width: 1px">a</text>
+  </g>
 </svg>
--- a/layout/reftests/svg/text/reftest.list
+++ b/layout/reftests/svg/text/reftest.list
@@ -148,24 +148,24 @@ HTTP(../..) == simple-transform-rotate.s
 
 # dynamic document changes
 == dynamic-font-size.svg dynamic-font-size-ref.svg
 == dynamic-dominant-baseline.svg dynamic-dominant-baseline-ref.svg
 == dynamic-multiple-x.svg dynamic-multiple-x-ref.svg
 
 # text and masks
 HTTP(../..) == mask-applied.svg mask-applied-ref.svg
-# HTTP(../..) == mask-content.svg mask-content-ref.svg  # disabled due to infinite invalidation loop bug
+# HTTP(../..) == mask-content.svg mask-content-ref.svg  # fails due to invalidation problem - bug 873806
 
 # text and clipPaths
 HTTP(../..) == clipPath-applied.svg clipPath-applied-ref.svg
-# HTTP(../..) == clipPath-content.svg clipPath-content-ref.svg  # disabled due to infinite invalidation loop bug
+# HTTP(../..) == clipPath-content.svg clipPath-content-ref.svg  # fails due to invalidation problem - bug 873806
 
 # text and patterns
-# == pattern-content.svg pattern-content-ref.svg  # disabled due to infinite invalidation loop bug
+fuzzy-if(cocoaWidget,1,6) == pattern-content.svg pattern-content-ref.svg
 
 # text and filters
 HTTP(../..) == filter-applied.svg filter-applied-ref.svg
 
 # selection
 needs-focus == selectSubString.svg selectSubString-ref.svg
 needs-focus == selectSubString-2.svg selectSubString-2-ref.svg
 needs-focus == selectSubString-3.svg selectSubString-3-ref.svg
--- a/layout/style/nsStyleUtil.h
+++ b/layout/style/nsStyleUtil.h
@@ -2,19 +2,19 @@
 /* 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 nsStyleUtil_h___
 #define nsStyleUtil_h___
 
 #include "nsCoord.h"
 #include "nsCSSProperty.h"
+#include "gfxFontFeatures.h"
 #include "nsIPrincipal.h"
 #include "nsSubstring.h"
-#include "gfxFontFeatures.h"
 
 class nsCSSValue;
 class nsStringComparator;
 class nsIContent;
 struct gfxFontFeature;
 class nsCSSValueList;
 template <class E> class nsTArray;
 
--- a/layout/svg/nsSVGTextFrame2.cpp
+++ b/layout/svg/nsSVGTextFrame2.cpp
@@ -4773,43 +4773,56 @@ nsSVGTextFrame2::NotifyGlyphMetricsChang
 
 void
 nsSVGTextFrame2::UpdateGlyphPositioning(bool aForceGlobalTransform)
 {
   nsIFrame* kid = GetFirstPrincipalChild();
   if (!kid)
     return;
 
-  bool needsReflow =
-    (mState & (NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN));
-
   NS_ASSERTION(!(kid->GetStateBits() & NS_FRAME_IN_REFLOW),
                "should not be in reflow when about to reflow again");
 
-  if (!needsReflow)
-    return;
-
-  if (mState & NS_FRAME_IS_DIRTY) {
-    // If we require a full reflow, ensure our kid is marked fully dirty.
-    kid->AddStateBits(NS_FRAME_IS_DIRTY);
-  }
-
-  if (needsReflow) {
+  if (mState & (NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN)) {
+    if (mState & NS_FRAME_IS_DIRTY) {
+      // If we require a full reflow, ensure our kid is marked fully dirty.
+      // (Note that our anonymous nsBlockFrame is not an nsISVGChildFrame, so
+      // even when we are called via our ReflowSVG this will not be done for us
+      // by nsSVGDisplayContainerFrame::ReflowSVG.)
+      kid->AddStateBits(NS_FRAME_IS_DIRTY);
+    }
     nsPresContext::InterruptPreventer noInterrupts(PresContext());
     DoReflow(aForceGlobalTransform);
   }
 
-  DoGlyphPositioning();
+  if (mPositioningDirty) {
+    DoGlyphPositioning();
+  }
 }
 
 void
 nsSVGTextFrame2::DoReflow(bool aForceGlobalTransform)
 {
+  // Since we are going to reflow the anonymous block frame, we will
+  // need to update mPositions.
   mPositioningDirty = true;
 
+  if (mState & NS_STATE_SVG_NONDISPLAY_CHILD) {
+    // Normally, this flag would be cleared in ReflowSVG(), but that doesn't
+    // get called for non-display frames. We don't want to reflow our
+    // descendants every time nsSVGTextFrame2::PaintSVG makes sure that we have
+    // valid positions by calling UpdateGlyphPositioning(), so we need to clear
+    // these dirty bits. Note that this also breaks an invalidation loop where
+    // our descendants invalidate as they reflow, which invalidates rendering
+    // observers, which reschedules the frame that is currently painting by
+    // referencing us to paint again. See bug 839958 comment 7. Hopefully we
+    // will break that loop more convincingly at some point.
+    mState &= ~(NS_FRAME_IS_DIRTY | NS_FRAME_HAS_DIRTY_CHILDREN);
+  }
+
   nsPresContext *presContext = PresContext();
   nsIFrame* kid = GetFirstPrincipalChild();
   if (!kid)
     return;
 
   nsIPresShell* presShell = presContext->PresShell();
   NS_ASSERTION(presShell, "null presShell");
   nsRefPtr<nsRenderingContext> renderingContext =
new file mode 100644
--- /dev/null
+++ b/layout/xul/base/src/crashtests/452185.html
@@ -0,0 +1,3 @@
+<html><head></head><body><div style="position: absolute;"> </div>
+<style>div, head {-moz-binding:url(452185.xml#a);</style>
+</body></html>
new file mode 100644
--- /dev/null
+++ b/layout/xul/base/src/crashtests/452185.xml
@@ -0,0 +1,5 @@
+<bindings xmlns="http://www.mozilla.org/xbl" xmlns:xlink="http://www.w3.org/1999/xlink">
+<binding id="a">
+<content><tbody xmlns="http://www.w3.org/1999/xhtml"><style>*::before { content:"b"; }</style></tbody></content>
+
+</binding></bindings>
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/layout/xul/base/src/crashtests/467080.xul
@@ -0,0 +1,24 @@
+<?xml-stylesheet href="chrome://browser/skin/" type="text/css"?>
+<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mathml="http://www.w3.org/1998/Math/MathML" style="-moz-binding:url(#a);" class="reftest-wait">
+
+<content xmlns="http://www.mozilla.org/xbl" ordinal="-1">
+<mathml:median style="display: block;"/>
+</content>
+
+<script xmlns="http://www.w3.org/1999/xhtml"><![CDATA[
+function finish() {
+  document.documentElement.removeAttribute("class");
+}
+function doe() {
+document.documentElement.removeAttribute('style');
+setTimeout(finish, 0);
+}
+setTimeout(doe, 100);
+]]></script>
+
+
+<bindings xmlns="http://www.mozilla.org/xbl">
+<binding id="a">
+<content><children/></content>
+</binding></bindings>
+</window>
--- a/layout/xul/base/src/crashtests/crashtests.list
+++ b/layout/xul/base/src/crashtests/crashtests.list
@@ -60,19 +60,21 @@ load 420424-1.xul
 load 430356-1.xhtml
 load 431738.xhtml
 load 432058-1.xul
 load 432068-1.xul
 load 432068-2.xul
 load 433296-1.xul
 load 433429.xul
 load 434458-1.xul
+load 452185.html
 load 460900-1.xul
 load 464149-1.xul
 asserts-if(winWidget,1) load 464407-1.xhtml # Bug 450974
+load 467080.xul
 load 467481-1.xul
 load 470063-1.html
 load 470272.html
 load 472189.xul
 load 475133.html
 load 488210-1.xhtml
 load 495728-1.xul
 load 508927-1.xul
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp
@@ -28,17 +28,17 @@
 #include "nsIConsoleService.h"
 #include "nsThreadUtils.h"
 #include "nsProxyRelease.h"
 
 #include "runnable_utils.h"
 #include "PeerConnectionCtx.h"
 #include "PeerConnectionImpl.h"
 #include "nsPIDOMWindow.h"
-#include "nsDOMDataChannel.h"
+#include "nsDOMDataChannelDeclarations.h"
 
 #ifdef MOZILLA_INTERNAL_API
 #include "nsContentUtils.h"
 #include "nsDOMJSUtils.h"
 #include "nsIDocument.h"
 #include "nsIScriptError.h"
 #include "nsPrintfCString.h"
 #include "nsURLHelper.h"
--- a/mobile/android/base/Tabs.java
+++ b/mobile/android/base/Tabs.java
@@ -14,16 +14,17 @@ import org.json.JSONObject;
 
 import android.accounts.Account;
 import android.accounts.AccountManager;
 import android.accounts.OnAccountsUpdateListener;
 import android.content.ContentResolver;
 import android.database.ContentObserver;
 import android.graphics.Color;
 import android.net.Uri;
+import android.os.Handler;
 import android.util.Log;
 
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.concurrent.CopyOnWriteArrayList;
@@ -52,26 +53,34 @@ public class Tabs implements GeckoEventL
     public static final int LOADURL_NEW_TAB = 1;
     public static final int LOADURL_USER_ENTERED = 2;
     public static final int LOADURL_PRIVATE = 4;
     public static final int LOADURL_PINNED = 8;
     public static final int LOADURL_DELAY_LOAD = 16;
     public static final int LOADURL_DESKTOP = 32;
     public static final int LOADURL_BACKGROUND = 64;
 
-    private static final int SCORE_INCREMENT_TAB_LOCATION_CHANGE = 5;
-    private static final int SCORE_INCREMENT_TAB_SELECTED = 10;
-    private static final int SCORE_THRESHOLD = 30;
+    private static final long PERSIST_TABS_AFTER_MILLISECONDS = 1000 * 5;
 
     private static AtomicInteger sTabId = new AtomicInteger(0);
     private volatile boolean mInitialTabsAdded;
 
     private GeckoApp mActivity;
     private ContentObserver mContentObserver;
 
+    private final Runnable mPersistTabsRunnable = new Runnable() {
+        @Override
+        public void run() {
+            boolean syncIsSetup = SyncAccounts.syncAccountsExist(getActivity());
+            if (syncIsSetup) {
+                TabsAccessor.persistLocalTabs(getContentResolver(), getTabsInOrder());
+            }
+        }
+    };
+
     private Tabs() {
         registerEventListener("Session:RestoreEnd");
         registerEventListener("SessionHistory:New");
         registerEventListener("SessionHistory:Back");
         registerEventListener("SessionHistory:Forward");
         registerEventListener("SessionHistory:Goto");
         registerEventListener("SessionHistory:Purge");
         registerEventListener("Tab:Added");
@@ -117,16 +126,18 @@ public class Tabs implements GeckoEventL
         }
     }
 
     // Ideally, this would remove the reference to the activity once it's
     // detached; however, we have lifecycle issues with GeckoApp and Tabs that
     // requires us to keep it around (see
     // https://bugzilla.mozilla.org/show_bug.cgi?id=844407).
     public synchronized void detachFromActivity(GeckoApp activity) {
+        ThreadUtils.getBackgroundHandler().removeCallbacks(mPersistTabsRunnable);
+
         if (mContentObserver != null) {
             BrowserDB.unregisterContentObserver(getContentResolver(), mContentObserver);
         }
 
         if (mAccountListener != null) {
             mAccountManager.removeOnAccountsUpdatedListener(mAccountListener);
             mAccountListener = null;
         }
@@ -540,54 +551,50 @@ public class Tabs implements GeckoEventL
                 }
             }
         });
     }
 
     private void onTabChanged(Tab tab, Tabs.TabEvents msg, Object data) {
         switch (msg) {
             case LOCATION_CHANGE:
-                mScore += SCORE_INCREMENT_TAB_LOCATION_CHANGE;
+                queuePersistAllTabs();
                 break;
             case RESTORED:
                 mInitialTabsAdded = true;
                 break;
 
             // When one tab is deselected, another one is always selected, so only
-            // increment the score once. When tabs are added/closed, they are also
-            // selected/unselected, so it would be redundant to also listen
+            // queue a single persist operation. When tabs are added/closed, they
+            // are also selected/unselected, so it would be redundant to also listen
             // for ADDED/CLOSED events.
             case SELECTED:
-                mScore += SCORE_INCREMENT_TAB_SELECTED;
+                queuePersistAllTabs();
             case UNSELECTED:
                 tab.onChange();
                 break;
             default:
                 break;
         }
-
-        if (mScore > SCORE_THRESHOLD) {
-            persistAllTabs();
-            mScore = 0;
-        }
     }
 
     // This method persists the current ordered list of tabs in our tabs content provider.
     public void persistAllTabs() {
-        final GeckoApp activity = getActivity();
-        final Iterable<Tab> tabs = getTabsInOrder();
-        ThreadUtils.postToBackgroundThread(new Runnable() {
-            @Override
-            public void run() {
-                boolean syncIsSetup = SyncAccounts.syncAccountsExist(activity);
-                if (syncIsSetup) {
-                    TabsAccessor.persistLocalTabs(getContentResolver(), tabs);
-                }
-            }
-        });
+        ThreadUtils.postToBackgroundThread(mPersistTabsRunnable);
+    }
+
+    /**
+     * Queues a request to persist tabs after PERSIST_TABS_AFTER_MILLISECONDS
+     * milliseconds have elapsed. If any existing requests are already queued then
+     * those requests are removed.
+     */
+    private void queuePersistAllTabs() {
+        Handler backgroundHandler = ThreadUtils.getBackgroundHandler();
+        backgroundHandler.removeCallbacks(mPersistTabsRunnable);
+        backgroundHandler.postDelayed(mPersistTabsRunnable, PERSIST_TABS_AFTER_MILLISECONDS);
     }
 
     private void registerEventListener(String event) {
         GeckoAppShell.getEventDispatcher().registerEventListener(event, this);
     }
 
     /**
      * Loads a tab with the given URL in the currently selected tab.
--- a/mobile/android/confvars.sh
+++ b/mobile/android/confvars.sh
@@ -50,15 +50,18 @@ MOZ_ONLY_TOUCH_EVENTS=1
 MOZ_APP_ID={aa3c5121-dab2-40e2-81ca-7ea25febc110}
 
 MOZ_ANDROID_OMTC=1
 MOZ_EXTENSION_MANAGER=1
 MOZ_APP_STATIC_INI=1
 
 MOZ_FENNEC=1
 
+# Enable on-demand decompression
+MOZ_ENABLE_SZIP=1
+
 MOZ_FOLD_LIBS=1
 
 # Enable navigator.mozPay
 MOZ_PAY=1
 
 # Enable UI for healthreporter
 MOZ_SERVICES_HEALTHREPORT=1
--- a/modules/libpref/src/init/all.js
+++ b/modules/libpref/src/init/all.js
@@ -3856,16 +3856,24 @@ pref("browser.zoom.reflowZoom.reflowTime
  * but has no effect if browser.zoom.reflowOnZoom is disabled.
  *
  * Note that this should be turned off only in cases where debugging of the
  * reflow-on-zoom feature is necessary, and enabling the feature during
  * a page load inhbits this debugging.
  */
 pref("browser.zoom.reflowZoom.reflowTextOnPageLoad", true);
 
+
+/**
+ * The minimum font size to maintain when double-tap zooming into an element, in
+ * twips. The browser will attempt to make the frame large enough to enlarge the
+ * font size to this value.
+ */
+pref("browser.zoom.reflowZoom.minFontSizeTwips", 120);
+
 // Image-related prefs
 // The maximum size, in bytes, of the decoded images we cache
 pref("image.cache.size", 5242880);
 // A weight, from 0-1000, to place on time when comparing to size.
 // Size is given a weight of 1000 - timeweight.
 pref("image.cache.timeweight", 500);
 
 // The default Accept header sent for images loaded over HTTP(S)
--- a/netwerk/ipc/NeckoParent.cpp
+++ b/netwerk/ipc/NeckoParent.cpp
@@ -83,17 +83,18 @@ NeckoParent::GetValidatedAppInfo(const S
 
   *aAppId = NECKO_UNKNOWN_APP_ID;
   *aInBrowserElement = false;
 
   if (aBrowser) {
     nsRefPtr<TabParent> tabParent = static_cast<TabParent*>(aBrowser);
 
     *aAppId = tabParent->OwnOrContainingAppId();
-    *aInBrowserElement = tabParent->IsBrowserElement();
+    *aInBrowserElement = aSerialized.IsNotNull() ? aSerialized.mIsInBrowserElement
+                                                 : tabParent->IsBrowserElement();
 
     if (*aAppId == NECKO_UNKNOWN_APP_ID) {
       return "TabParent reports appId=NECKO_UNKNOWN_APP_ID!";
     }
     // We may get appID=NO_APP if child frame is neither a browser nor an app
     if (*aAppId == NECKO_NO_APP_ID) {
       if (tabParent->HasOwnApp()) {
         return "TabParent reports NECKO_NO_APP_ID but also is an app";
--- a/netwerk/sctp/datachannel/DataChannel.h
+++ b/netwerk/sctp/datachannel/DataChannel.h
@@ -405,17 +405,17 @@ public:
         return CONNECTING;
       return mState;
     }
 
   void SetReadyState(uint16_t aState) { mState = aState; }
 
   void GetLabel(nsAString& aLabel) { CopyUTF8toUTF16(mLabel, aLabel); }
   void GetProtocol(nsAString& aProtocol) { CopyUTF8toUTF16(mProtocol, aProtocol); }
-  void GetStream(uint16_t *aStream) { *aStream = mStream; }
+  uint16_t GetStream() { return mStream; }
 
   void AppReady();
 
   void SendOrQueue(DataChannelOnMessageAvailable *aMessage);
 
 protected:
   Mutex mListenerLock; // protects mListener and mContext
   DataChannelListener *mListener;
--- a/other-licenses/ia2/Accessible2.idl
+++ b/other-licenses/ia2/Accessible2.idl
@@ -1,96 +1,153 @@
 /*************************************************************************
  *
  *  File Name (Accessible2.idl)
- *
- *  IAccessible2 IDL Specification
- *
- *  Copyright (c) Linux Foundation 2007, 2009
- *  Copyright (c) IBM Corp. 2006
- *  Copyright (c) Sun Microsystems, Inc. 2000, 2006
+ * 
+ *  IAccessible2 IDL Specification 
+ * 
+ *  Copyright (c) 2007, 2013 Linux Foundation 
+ *  Copyright (c) 2006 IBM Corporation 
+ *  Copyright (c) 2000, 2006 Sun Microsystems, Inc. 
+ *  All rights reserved. 
+ *   
+ *   
+ *  Redistribution and use in source and binary forms, with or without 
+ *  modification, are permitted provided that the following conditions 
+ *  are met: 
+ *   
+ *   1. Redistributions of source code must retain the above copyright 
+ *      notice, this list of conditions and the following disclaimer. 
+ *   
+ *   2. Redistributions in binary form must reproduce the above 
+ *      copyright notice, this list of conditions and the following 
+ *      disclaimer in the documentation and/or other materials 
+ *      provided with the distribution. 
  *
- *  This library is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Lesser General Public
- *  License version 2.1, as published by the Free Software Foundation; either
- *  version 2.1 of the License, or (at your option) any later version.
- *
- *  This library is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *  Lesser General Public License for more details.
- *
- *  You should have received a copy of the GNU Lesser General Public
- *  License along with this library; if not, write to the Free Software
- *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
- *
- ************************************************************************/
+ *   3. Neither the name of the Linux Foundation nor the names of its 
+ *      contributors may be used to endorse or promote products 
+ *      derived from this software without specific prior written 
+ *      permission. 
+ *   
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
+ *  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
+ *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+ *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
+ *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
+ *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
+ *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
+ *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+ *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
+ *  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
+ *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ *   
+ *  This BSD License conforms to the Open Source Initiative "Simplified 
+ *  BSD License" as published at: 
+ *  http://www.opensource.org/licenses/bsd-license.php 
+ *   
+ *  IAccessible2 is a trademark of the Linux Foundation. The IAccessible2 
+ *  mark may be used in accordance with the Linux Foundation Trademark 
+ *  Policy to indicate compliance with the IAccessible2 specification. 
+ * 
+ ************************************************************************/ 
 
 /** @mainpage
 
  @section _interfaces Interfaces
   IAccessible2\n
+  IAccessible2_2\n
   IAccessibleAction\n
   IAccessibleApplication\n
   IAccessibleComponent\n
+  IAccessibleDocument\n
+  IAccessibleEditableText\n
   IAccessibleHypertext\n
+  IAccessibleHypertext2\n
   IAccessibleHyperlink\n
   IAccessibleImage\n
   IAccessibleRelation\n
-  IAccessibleTable [deprecated]\n
+  IAccessibleTable [Deprecated]\n
   IAccessibleTable2\n
   IAccessibleTableCell\n
   IAccessibleText\n
-  IAccessibleEditableText\n
+  IAccessibleText2\n
   IAccessibleValue
 
  @section _structs Structs
   IA2Locale\n
   IA2TableModelChange\n
   IA2TextSegment
 
  @section _enums Enums
+  ::IA2Actions values are predefined actions for use when implementing support for HTML5 media.\n
   ::IA2CoordinateType values define the requested coordinate type (screen or parent window).\n
   ::IA2EventID values identify events.\n
   ::IA2Role values defines roles which are in addition to the existing MSAA roles.\n
   ::IA2ScrollType values define where to place an object or substring on the screen.\n
   ::IA2States values define states which are in addition to the existing MSAA states.\n
   ::IA2TableModelChangeType values describe the kinds of changes made to a table (insert, delete, update).\n
   ::IA2TextBoundaryType values define the requested text unit (character, word, sentence, line, paragraph).\n
   ::IA2TextSpecialOffsets values define special offsets for use in the text interfaces.
 
  @section _constants Constants
   @ref grpRelations
 
  @section _misc Miscellaneous
-  @ref _licensePage "LGPL License"\n
+  @ref _licensePage "BSD License"\n
   @ref _generalInfo "General Information"\n
 
- @page _licensePage LGPL License
-  IAccessible2 IDL Specification
+ @page _licensePage BSD License
+  %IAccessible2 IDL Specification
 
-  Copyright (c) Linux Foundation 2007, 2008\n
-  Copyright (c) IBM Corp. 2006\n
-  Copyright (c) Sun Microsystems, Inc. 2000, 2006
+  Copyright (c) 2007, 2013 Linux Foundation\n
+  Copyright (c) 2006 IBM Corporation\n
+  Copyright (c) 2000, 2006 Sun Microsystems, Inc.\n
+  All rights reserved.
 
-  This library is free software; you can redistribute it and/or
-  modify it under the terms of the GNU Lesser General Public
-  License version 2.1, as published by the Free Software Foundation; either
-  version 2.1 of the License, or (at your option) any later version.
-
-  This library is distributed in the hope that it will be useful,
-  but WITHOUT ANY WARRANTY; without even the implied warranty of
-  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-  Lesser General Public License for more details.
-
-  You should have received a copy of the GNU Lesser General Public
-  License along with this library; if not, write to the Free Software
-  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-
-  You may also refer to http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
+  Redistribution and use in source and binary forms, with or without 
+  modification, are permitted provided that the following conditions 
+  are met: 
+    
+   1. Redistributions of source code must retain the above copyright 
+      notice, this list of conditions and the following disclaimer. 
+ 
+   2. Redistributions in binary form must reproduce the above 
+      copyright notice, this list of conditions and the following 
+      disclaimer in the documentation and/or other materials 
+      provided with the distribution. 
+ 
+   3. Neither the name of the Linux Foundation nor the names of its 
+      contributors may be used to endorse or promote products 
+      derived from this software without specific prior written 
+      permission. 
+ 
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
+  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
+  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
+  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
+  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
+  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
+  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
+  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
+  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ 
+  This BSD License conforms to the Open Source Initiative "Simplified 
+  BSD License" as published at: 
+  http://www.opensource.org/licenses/bsd-license.php 
+ 
+  %IAccessible2 is a trademark of the Linux Foundation. The %IAccessible2 
+  mark may be used in accordance with the
+  <a href="http://www.linuxfoundation.org/collaborate/workgroups/accessibility/trademark-policy">
+  Linux Foundation Trademark Policy</a> to indicate compliance with the %IAccessible2 specification. 
 
  @page _generalInfo General Information 
   The following information is applicable to two or more interfaces.
 
  @ref _errors\n
  @ref _memory\n
  &nbsp;&nbsp;@ref _arrayConsideration\n
  @ref _indexes\n
@@ -100,19 +157,19 @@
  @ref _changingInterfaces\n
  @ref _applicationInfo\n
  @ref _childIDs\n
  @ref _variants\n
  @ref _iaaction-iahyperlink\n
  @ref _trademark
 
  @section _errors Error Handling
-  HRESULT values are defined by the Microsoft&reg; Win32&reg; API.  For more information, refer to 
-  <a href="http://msdn2.microsoft.com/en-us/library/bb401631.aspx">Interpreting HRESULT Values</a>
-  in MSDN&reg;.
+  HRESULT values are defined by the Microsoft&reg; Win32&reg; API.  For more information, refer to
+  <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa378137%28v=vs.85%29.aspx">
+  Interpreting HRESULT Values</a> in MSDN&reg;.
 
   Note that the S_FALSE return value is considered a non-error value and the 
   SUCCEEDED macro will return TRUE.  S_FALSE is used when there is no failure
   but there was nothing valid to return, e.g. in IAccessible2::attributes when
   there are no attributes.  When S_FALSE is returned [out] pointer types should 
   be NULL and [out] longs should generally be 0, but sometimes -1 is used such
   as IAccessible2::indexInParent, IAccessibleText::caretOffset, and
   IAccessibleHypertext::hyperlinkIndex.
@@ -139,31 +196,38 @@
   @li An article by Don Box in a
    <a href="http://www.microsoft.com/msj/1196/activex1196.aspx">Q & A section</a>
    of the November 1996 edition of the Microsoft Systems Journal.
   @li A posting to a CodeGuru forum, 
    <a href="http://www.codeguru.com/forum/showthread.php?t=364511">Windows SDK 
    String: What are the rules for BSTR allocation and deallocation?</a>
 
  @subsection _arrayConsideration Special Consideration when using Arrays
-  There are several methods which return arrays.  It is considered a best practice
-  for the client to allocate and free the arrays.  This can be done for 
-  IAccessible2::relations and IAccessibleRelation::targets.  However, due to the
-  coding of the IDL for the remaining methods which return arrays, the server must
-  allocate the array and the client must free the array when no longer needed.  
-  These methods are IAccessible2::extendedStates, IAccessible2::localizedExtendedStates, 
+  There are several methods which return arrays.  In the case of IAccessible2::relations
+  and IAccessibleRelation::targets the client must allocate and free the arrays.
+
+  For the remaining methods which return arrays, the server must allocate the array
+  and the client must free the array when no longer needed.  These methods are
+  IAccessible2::extendedStates, IAccessible2::localizedExtendedStates,
+  IAccessible2_2::relationTargetsOfType, IAccessibleAction::keyBinding, 
+  IAccessibleHypertext2::hyperlinks, IAccessibleTable::selectedChildren, 
+  IAccessibleTable::selectedColumns, IAccessibleTable::selectedRows,
+  IAccessibleTable2::selectedCells, IAccessibleTable2::selectedColumns,
+  IAccessibleTable2::selectedRows, IAccessibleTableCell::columnHeaderCells,
+  and IAccessibleTableCell::rowHeaderCells.
+  For those methods, the server must allocate both the top level array and any storage 
+  associated with it, e.g. for BSTRs.  The server must allocate the arrays with 
+  CoTaskMemAlloc and any BSTRs with SysAllocString.  The client must use CoTaskMemFree
+  to free the array and any BSTRs must be freed with SysFreeString.  
+  
+  Also, the IDL for IAccessible2::extendedStates, IAccessible2::localizedExtendedStates, 
   IAccessibleAction::keyBinding, IAccessibleTable::selectedChildren, 
-  IAccessibleTable::selectedColumns, and IAccessibleTable::selectedRows.  For those 
-  methods, the server must allocate both the top level array and any storage 
-  associated with it, e.g. for BSTRs.  The client must use CoTaskMemFree to free
-  the array and any BSTRs must be freed with SysFreeString.  
-  
-  Also, the IDL for those methods includes an extraneous [in] parameter for the 
-  caller to specify the max size of the array.  This parameter will be ignored by 
-  the COM server.
+  IAccessibleTable::selectedColumns, and IAccessibleTable::selectedRows includes an
+  extraneous [in] parameter for the caller to specify the max size of the array.
+  This parameter will be ignored by the COM server.
 
  @section _indexes Zero and One Based Indexes
   Unless otherwise specified all offsets and indexes are 0 based. 
 
  @section _enums Enums
   Note that enums start at 0.
 
  @section _specialOffsets Special Offsets for use in the IAccessibleText and IAccessibleEditableText Methods
@@ -198,28 +262,26 @@
     hr = pService->QueryService(IID_IAccessible, IID_IAccessible2, (void**)&pIA2); 
     if (SUCCEEDED(hr) && pIA2) { 
       // The control supports IAccessible2. 
       // pIA2 is the reference to the accessible object's IAccessible2 interface.
     } 
   } 
   @endcode
 
- @section _changingInterfaces Changing between Accessible Interfaces
-  Note that developers must always implement MSAA's IAccessible and, if needed, some 
-  of the interfaces in the set of IAccessible2 interfaces.  Although the IAccessible2 
-  IDL is currently coded such that IAccessible2 is a subclass of MSAA's IAccessible, 
-  none of MSAA's IAccessible methods are overridden or extended.  In order to allow 
-  future removal of the inheritance, Assistive Technologies (ATs) should not rely on 
-  that inheritance. 
+  @section _changingInterfaces Changing between Accessible Interfaces
+  Note that developers must always implement MSAA's IAccessible and, if needed, some
+  of the interfaces in the set of IAccessible2 interfaces.  Although the IAccessible2
+  IDL is coded such that IAccessible2 is a subclass of MSAA's IAccessible, none of
+  MSAA's IAccessible methods are redefined by IAccessible2.
 
   QueryService must be used to switch from a reference to an MSAA IAccessible interface 
   to another interface.  This has been 
-  <a href="http://www.accessinteropalliance.org/docs/Introducing_IAccessibleEx.doc">
-  documented by Microsoft</a> and the pertinent facts have been extracted below: 
+  <a href="http://www.atia.org/files/public/Introducing_IAccessibleEx.doc">
+  documented</a> and the pertinent facts have been extracted below: 
 
   @par 
    Why use QueryService instead of just using QueryInterface to get IAccessibleEx 
    directly? The reason is that since MSAA 2.0, clients don't talk to a server's 
    IAccessible interface directly; instead they talk to an intermediate MSAA-provided 
    wrapper that calls through to the original IAccessible. This wrapper provides services 
    such as implementing IDispatch, supplying information from MSAA 2.0's Dynamic Annotation 
    service, and scaling locations when running on Windows Vista with DPI scaling enabled. 
@@ -299,23 +361,25 @@ import "IA2CommonTypes.idl";
 IAccessible2::locale returns this struct.
 */
 typedef struct IA2Locale {
   BSTR language; ///< ISO 639-1 Alpha-2 two character language code
   BSTR country;  ///< ISO 3166-1 Alpha-2 two character country code
   BSTR variant;  ///< Application specific variant of the locale
 } IA2Locale;
 
-/** This interface must always be provided for objects that support some
+/** @brief This interface exposes the primary set of information about an
+ IAccessible2 enabled accessible object.
+
+ This interface must always be provided for objects that support some
  portion of the collection of the %IAccessible2 interfaces.
 
  Please refer to @ref _changingInterfaces "Changing between Accessible Interfaces"
  for special considerations related to use of the MSAA IAccessible interface and 
  the set of %IAccessible2 interfaces.
-
  */
 [object, uuid(E89F726E-C4F4-4c19-BB19-B647D7FA8478)]
 interface IAccessible2 : IAccessible
 {
 
   /** @brief Returns the number of accessible relations for this object.
    @param [out] nRelations
    @retval S_OK
@@ -325,17 +389,17 @@ interface IAccessible2 : IAccessible
      [out, retval] long *nRelations
     );
 
   /** @brief Returns one accessible relation for this object.
    @param [in] relationIndex
      0 based
    @param [out] relation
    @retval S_OK
-   @retval E_INVALIDARG if bad [in] passed, [out] value is NULL
+   @retval E_INVALIDARG if bad [in] passed
   */
   [propget] HRESULT relation
     (
      [in] long relationIndex,
      [out, retval] IAccessibleRelation **relation
     );
 
   /** @brief Returns multiple accessible relations for this object.
@@ -344,16 +408,17 @@ interface IAccessible2 : IAccessible
    @param [out] relations
     The array of accessible relation objects.  Note that this array is to be
 	allocated by the client and freed when no longer needed.  Refer to @ref 
 	_arrayConsideration "Special Consideration when using Arrays" for more details.
    @param [out] nRelations 
     actual number of relations in the returned array (not more than maxRelations)
    @retval S_OK
    @retval S_FALSE if there are no relations, nRelations is set to 0
+   @note As a performant alternative, client code should consider using IAccessible2_2::relationTargetsOfType.
   */
   [propget] HRESULT relations
     (
      [in] long maxRelations, 
      [out, size_is(maxRelations), length_is(*nRelations)]
        IAccessibleRelation **relations, 
      [out, retval] long *nRelations 
     );
@@ -413,26 +478,29 @@ interface IAccessible2 : IAccessible
    Also used for collections of non-text objects.
 
    @param [out] groupLevel
     1 based, 0 indicates that this value is not applicable
    @param [out] similarItemsInGroup
     1 based, 0 indicates that this value is not applicable
    @param [out] positionInGroup
     1 based, 0 indicates that this value is not applicable. This is an index
-	into the objects in the current group, not an index into all the objects
-	at the same group level.
+    into the objects in the current group, not an index into all the objects
+    at the same group level.
    @retval S_OK if at least one value is valid
-   @retval S_FALSE if no values are valid
+   @retval S_FALSE if no values are valid, [out] values are 0s
    @note This method is meant to describe the nature of an object's containment
-    structure.  This is normally not implemented on a combo box to describe the nature
+    structure.  It's exposed by trees, tree grids, nested lists, nested menus,
+    but not headings, which uses the level object attribute.  It is also exposed
+    by radio buttons (with groupLevel == 0).
+   @note This is normally not implemented on a combo box to describe the nature
     of its contents.  Normally an AT will get that information from its child list 
-	object.  However, in some cases when combo boxes are not able to be structured
-	such that the list is a child of the combo box, this method is implemented
-	on the combo box itself. ATs can use this interface if a child list is not found.
+    object.  However, in some cases when non-edit combo boxes are not able to be structured
+    such that the list is a child of the combo box, this method is implemented on
+    the combo box itself. ATs can use this interface if a child list is not found.
 	*/
   [propget] HRESULT groupPosition
     (
      [out] long *groupLevel,
      [out] long *similarItemsInGroup,
      [out, retval] long *positionInGroup 
     );
 
@@ -486,35 +554,36 @@ interface IAccessible2 : IAccessible
 
    An extended state is a state which is dynamically generated by the application.
    It is not predefined by the %IAccessible2 specification.
 
    @param [in] maxExtendedStates
     This parameter is ignored. Refer to @ref _arrayConsideration 
 	"Special Consideration when using Arrays" for more details.
    @param [out] extendedStates
-    This array is allocated by the server.  Free it with CoTaskMemFree.
+    This array is allocated by the server.  The client must free it with CoTaskMemFree.
    @param [out] nExtendedStates
     The number of extended states returned; the size of the returned array.
    @retval S_OK
    @retval S_FALSE if there are no states, [out] values are NULL and 0 respectively
   */
   [propget] HRESULT extendedStates
     (
      [in] long maxExtendedStates,
      [out, size_is(,maxExtendedStates), length_is(,*nExtendedStates)] BSTR **extendedStates,
      [out, retval] long *nExtendedStates
     );
 
   /** @brief Returns the localized extended states (array of strings).
+
    @param [in] maxLocalizedExtendedStates
     This parameter is ignored. Refer to @ref _arrayConsideration 
 	"Special Consideration when using Arrays" for more details.
    @param [out] localizedExtendedStates
-    This array is allocated by the server.  Free it with CoTaskMemFree. 
+    This array is allocated by the server.  The client must free it with CoTaskMemFree. 
    @param [out] nLocalizedExtendedStates
     The number of localized extended states returned; the size of the returned array.
    @retval S_OK
    @retval S_FALSE if there are no states, [out] values are NULL and 0 respectively
   */
   [propget] HRESULT localizedExtendedStates
     (
      [in] long maxLocalizedExtendedStates,
@@ -549,17 +618,21 @@ interface IAccessible2 : IAccessible
 
    Another use of this value by an AT is to identify when a grouping object has 
    changed, e.g. when moving from a radio button in one group to a radio button in a 
    different group.
 
    One means of implementing this would be to create a factory with a 32 bit number 
    generator and a reuse pool.  The number generator would emit numbers starting 
    at 1.  Each time an object's life cycle ended, its number would be saved into a 
-   resuse pool.  The number generator would be used whenever the reuse pool was empty.
+   reuse pool.  The number generator would be used whenever the reuse pool was empty.
+
+   Another way to create a unique ID is to generate it from a pointer value, e.g. an
+   object's address. That would be unique because no two active objects can use the
+   same allocated memory space.
 
    @param [out] uniqueID
    @retval S_OK
   */
   [propget] HRESULT uniqueID
     (
      [out, retval] long *uniqueID
     );
@@ -600,19 +673,20 @@ interface IAccessible2 : IAccessible
    @param [out] locale
    @retval S_OK
   */
   [propget] HRESULT locale
     (
      [out, retval] IA2Locale *locale
     );
 
-  /** @brief Returns the attributes specific to this %IAccessible2 object, such as a cell's formula.
+  /** @brief Returns the attributes specific to this object, such as a cell's formula.
    @param [out] attributes
    @retval S_OK
    @retval S_FALSE returned if there is nothing to return, [out] value is NULL
   */
   [propget] HRESULT attributes
     (
      [out, retval] BSTR *attributes
     );
 
 }
+
new file mode 100644
--- /dev/null
+++ b/other-licenses/ia2/Accessible2_2.idl
@@ -0,0 +1,123 @@
+/*************************************************************************
+ *
+ *  File Name (Accessible2_2.idl)
+ * 
+ *  IAccessible2 IDL Specification 
+ * 
+ *  Copyright (c) 2007, 2013 Linux Foundation 
+ *  Copyright (c) 2006 IBM Corporation 
+ *  Copyright (c) 2000, 2006 Sun Microsystems, Inc. 
+ *  All rights reserved. 
+ *   
+ *   
+ *  Redistribution and use in source and binary forms, with or without 
+ *  modification, are permitted provided that the following conditions 
+ *  are met: 
+ *   
+ *   1. Redistributions of source code must retain the above copyright 
+ *      notice, this list of conditions and the following disclaimer. 
+ *   
+ *   2. Redistributions in binary form must reproduce the above 
+ *      copyright notice, this list of conditions and the following 
+ *      disclaimer in the documentation and/or other materials 
+ *      provided with the distribution. 
+ *
+ *   3. Neither the name of the Linux Foundation nor the names of its 
+ *      contributors may be used to endorse or promote products 
+ *      derived from this software without specific prior written 
+ *      permission. 
+ *   
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
+ *  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
+ *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+ *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
+ *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
+ *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
+ *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
+ *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+ *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
+ *  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
+ *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ *   
+ *  This BSD License conforms to the Open Source Initiative "Simplified 
+ *  BSD License" as published at: 
+ *  http://www.opensource.org/licenses/bsd-license.php 
+ *   
+ *  IAccessible2 is a trademark of the Linux Foundation. The IAccessible2 
+ *  mark may be used in accordance with the Linux Foundation Trademark 
+ *  Policy to indicate compliance with the IAccessible2 specification. 
+ * 
+ ************************************************************************/ 
+
+import "objidl.idl";
+import "oaidl.idl";
+import "oleacc.idl";
+import "Accessible2.idl";
+
+/** @brief This interface exposes the primary set of information about an
+ IAccessible2 enabled accessible object.
+
+ This interface must always be provided for objects that support some
+ portion of the collection of the %IAccessible2 interfaces.
+
+ Please refer to @ref _changingInterfaces "Changing between Accessible Interfaces"
+ for special considerations related to use of the MSAA IAccessible interface and 
+ the set of %IAccessible2 interfaces.
+ */
+[object, uuid(6C9430E9-299D-4E6F-BD01-A82A1E88D3FF)]
+interface IAccessible2_2 : IAccessible2
+{
+  /** @brief Returns the attribute value of a specified attribute specific to this object.
+   @param [in] name
+   @param [out] attribute
+   @retval S_OK
+   @retval S_FALSE returned if there is nothing to return, [out] value is NULL.
+   @retval E_INVALIDARG if bad [in] passed.
+   @note The output value is a VARIANT.  Typically it will be a VT_BSTR, but there
+     are some cases where it will be a VT_I4 or VT_BOOL.  Refer to the <a href=
+     "http://www.linuxfoundation.org/collaborate/workgroups/accessibility/iaccessible2/objectattributesIAccessible2">
+     Object Attributes specification</a> for more information.
+  */
+  [propget] HRESULT attribute
+    (
+     [in] BSTR name,
+     [out, retval] VARIANT *attribute
+    );
+
+  /** @brief Returns the deepest hypertext accessible in the subtree of this object, and the caret offset within it.
+   @param [out] accessible
+   @param [out] caretOffset
+   @retval S_OK
+   @retval S_FALSE returned if there is no caret in any of the objects in the subtree, [out] accessible is NULL and [out] caretOffset is -1.
+  */
+  [propget] HRESULT accessibleWithCaret
+    (
+     [out] IUnknown **accessible,
+     [out, retval] long *caretOffset
+    );
+
+  /** @brief Returns relation targets for a specified target type.
+   @param [in] type
+    The requested @ref grpRelations "relation type".
+   @param [in] maxTargets
+    The number of targets requested.  0 indicates that all targets should be returned.
+   @param [out] targets
+    This array is allocated by the server.  The client must free it with CoTaskMemFree.
+   @param [out] nTargets
+    The number of targets returned; the size of the returned array.
+   @retval S_OK
+   @retval S_FALSE if there are no targets, [out] values are NULL and 0 respectively.
+   @retval E_INVALIDARG if bad [in] passed.
+  */
+  [propget] HRESULT relationTargetsOfType
+    (
+     [in] BSTR type,
+     [in] long maxTargets,
+     [out, size_is(,*nTargets)] IUnknown ***targets,
+     [out, retval] long *nTargets
+    );
+
+}
+
--- a/other-licenses/ia2/AccessibleAction.idl
+++ b/other-licenses/ia2/AccessibleAction.idl
@@ -1,37 +1,89 @@
 /*************************************************************************
  *
  *  File Name (AccessibleAction.idl)
  *
- *  IAccessible2 IDL Specification
- *
- *  Copyright (c) Linux Foundation 2007, 2008
- *  Copyright (c) IBM Corp. 2006
- *  Copyright (c) Sun Microsystems, Inc. 2000, 2006
- *
- *  This library is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Lesser General Public
- *  License version 2.1, as published by the Free Software Foundation; either
- *  version 2.1 of the License, or (at your option) any later version.
+ *  IAccessible2 IDL Specification 
+ * 
+ *  Copyright (c) 2007, 2013 Linux Foundation 
+ *  Copyright (c) 2006 IBM Corporation 
+ *  Copyright (c) 2000, 2006 Sun Microsystems, Inc. 
+ *  All rights reserved. 
+ *   
+ *   
+ *  Redistribution and use in source and binary forms, with or without 
+ *  modification, are permitted provided that the following conditions 
+ *  are met: 
+ *   
+ *   1. Redistributions of source code must retain the above copyright 
+ *      notice, this list of conditions and the following disclaimer. 
+ *   
+ *   2. Redistributions in binary form must reproduce the above 
+ *      copyright notice, this list of conditions and the following 
+ *      disclaimer in the documentation and/or other materials 
+ *      provided with the distribution. 
  *
- *  This library is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *  Lesser General Public License for more details.
- *
- *  You should have received a copy of the GNU Lesser General Public
- *  License along with this library; if not, write to the Free Software
- *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
- *
- ************************************************************************/
+ *   3. Neither the name of the Linux Foundation nor the names of its 
+ *      contributors may be used to endorse or promote products 
+ *      derived from this software without specific prior written 
+ *      permission. 
+ *   
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
+ *  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
+ *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+ *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
+ *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
+ *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
+ *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
+ *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+ *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
+ *  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
+ *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ *   
+ *  This BSD License conforms to the Open Source Initiative "Simplified 
+ *  BSD License" as published at: 
+ *  http://www.opensource.org/licenses/bsd-license.php 
+ *   
+ *  IAccessible2 is a trademark of the Linux Foundation. The IAccessible2 
+ *  mark may be used in accordance with the Linux Foundation Trademark 
+ *  Policy to indicate compliance with the IAccessible2 specification. 
+ * 
+ ************************************************************************/ 
 
 import "objidl.idl";
 import "oaidl.idl";
 import "oleacc.idl";
+
+/** This enum defines values which are predefined actions for use when implementing
+ support for media.
+
+ This enum is used when specifying an action for IAccessibleAction::doAction.
+*/
+
+enum IA2Actions {
+  IA2_ACTION_OPEN = -1,         /**< Used to inform the server that the client will
+                                signal via IA2_ACTION_COMPLETE when it has consumed
+                                the content provided by the object.  This action
+                                allows the object's server to wait for all clients
+                                to signal their readiness for additional content.
+                                Any form of content generation that requires
+                                synchronization with an AT would require use of this
+                                action.  One example is the generation of text describing
+                                visual content not obvious from a video's sound track.
+                                In this scenario the Text to Speech or Braille output
+                                may take more time than the related length of silence
+                                in the video's sound track. */
+  IA2_ACTION_COMPLETE = -2,  	/**< Used by the client to inform the server that it has
+                                consumed the most recent content provided by this object. */
+  IA2_ACTION_CLOSE = -3         /**< Used to inform the server that the client no longer
+                                requires synchronization. */
+};
         
 /** @brief This interface gives access to actions that can be executed
   for accessible objects.
 
  Every accessible object that can be manipulated via the native GUI beyond the 
   methods available either in the MSAA IAccessible interface or in the set of 
   IAccessible2 interfaces (other than this IAccessibleAction interface) should 
   support the IAccessibleAction interface in order to provide Assistive Technology
@@ -65,32 +117,34 @@ interface IAccessibleAction : IUnknown
      [out,retval] long* nActions
     );
 
   /** @brief Performs the specified Action on the object.
    @param [in] actionIndex
     0 based index specifying the action to perform.  If it lies outside
     the valid range no action is performed.
    @retval S_OK
-   @retval E_INVALIDARG if bad [in] passed 
+   @retval S_FALSE if action could not be performed
+   @retval E_INVALIDARG if bad [in] passed
+   @note If implementing support for media, refer to the predefined constants in the ::IA2Actions enum.
     */
   HRESULT doAction
     (
      [in] long actionIndex
     );
 
   /** @brief Returns a description of the specified action of the object.
    @param [in] actionIndex
     0 based index specifying which action's description to return.
     If it lies outside the valid range an empty string is returned.
    @param [out] description
     The returned value is a localized string of the specified action.
    @retval S_OK
    @retval S_FALSE if there is nothing to return, [out] value is NULL 
-   @retval E_INVALIDARG if bad [in] passed, [out] value is NULL 
+   @retval E_INVALIDARG if bad [in] passed
     */
   [propget] HRESULT description
     (
      [in] long actionIndex,
      [out, retval] BSTR *description
     );
 
   /** @brief Returns an array of BSTRs describing one or more key bindings, if
@@ -115,52 +169,52 @@ interface IAccessibleAction : IUnknown
 
    @param [in] actionIndex
     0 based index specifying which action's key bindings should be returned.
    @param [in] nMaxBindings
     This parameter is ignored. Refer to @ref _arrayConsideration
 	"Special Consideration when using Arrays" for more details.
    @param [out] keyBindings
     An array of BSTRs, allocated by the server, one for each key binding.
-	Free it with CoTaskMemFree.
+	The client must free it with CoTaskMemFree.
    @param [out] nBindings
     The number of key bindings returned; the size of the returned array.
    @retval S_OK
-   @retval S_FALSE if there are no relations, [out] values are NULL and 0 respectively 
-   @retval E_INVALIDARG if bad [in] passed, [out] values are NULL and 0 respectively 
+   @retval S_FALSE if there are no key bindings, [out] values are NULL and 0 respectively 
+   @retval E_INVALIDARG if bad [in] passed
 	*/
   [propget] HRESULT keyBinding
     (
      [in] long actionIndex,
      [in] long nMaxBindings,
      [out, size_is(,nMaxBindings), length_is(,*nBindings)] BSTR **keyBindings,
 	 [out, retval] long *nBindings
     );
 
   /** @brief Returns the non-localized name of specified action.
    @param [in] actionIndex
     0 based index specifying which action's non-localized name should be returned.
    @param [out] name
    @retval S_OK
    @retval S_FALSE if there is nothing to return, [out] value is NULL 
-   @retval E_INVALIDARG if bad [in] passed, [out] value is NULL 
+   @retval E_INVALIDARG if bad [in] passed
    */
   [propget] HRESULT name
     (
      [in] long actionIndex,
      [out, retval] BSTR *name
     );
 
   /** @brief Returns the localized name of specified action.
    @param [in] actionIndex
     0 based index specifying which action's localized name should be returned.
    @param [out] localizedName
    @retval S_OK
    @retval S_FALSE if there is nothing to return, [out] value is NULL 
-   @retval E_INVALIDARG if bad [in] passed, [out] value is NULL 
+   @retval E_INVALIDARG if bad [in] passed
    */
   [propget] HRESULT localizedName
     (
      [in] long actionIndex,
      [out, retval] BSTR *localizedName
     );
 
 }
--- a/other-licenses/ia2/AccessibleApplication.idl
+++ b/other-licenses/ia2/AccessibleApplication.idl
@@ -1,33 +1,61 @@
 /*************************************************************************
  *
  *  File Name (AccessibleApplication.idl)
- *
- *  IAccessible2 IDL Specification
- *
- *  Copyright (c) Linux Foundation 2007, 2008
- *  Copyright (c) IBM Corp. 2006
- *  Copyright (c) Sun Microsystems, Inc. 2000, 2006
+ * 
+ *  IAccessible2 IDL Specification 
+ * 
+ *  Copyright (c) 2007, 2010 Linux Foundation 
+ *  Copyright (c) 2006 IBM Corporation 
+ *  Copyright (c) 2000, 2006 Sun Microsystems, Inc. 
+ *  All rights reserved. 
+ *   
+ *   
+ *  Redistribution and use in source and binary forms, with or without 
+ *  modification, are permitted provided that the following conditions 
+ *  are met: 
+ *   
+ *   1. Redistributions of source code must retain the above copyright 
+ *      notice, this list of conditions and the following disclaimer. 
+ *   
+ *   2. Redistributions in binary form must reproduce the above 
+ *      copyright notice, this list of conditions and the following 
+ *      disclaimer in the documentation and/or other materials 
+ *      provided with the distribution. 
  *
- *  This library is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Lesser General Public
- *  License version 2.1, as published by the Free Software Foundation; either
- *  version 2.1 of the License, or (at your option) any later version.
- *
- *  This library is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *  Lesser General Public License for more details.
- *
- *  You should have received a copy of the GNU Lesser General Public
- *  License along with this library; if not, write to the Free Software
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02110-1301  USA
- *
- ************************************************************************/
+ *   3. Neither the name of the Linux Foundation nor the names of its 
+ *      contributors may be used to endorse or promote products 
+ *      derived from this software without specific prior written 
+ *      permission. 
+ *   
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
+ *  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
+ *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+ *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
+ *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
+ *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
+ *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
+ *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+ *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
+ *  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
+ *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ *   
+ *  This BSD License conforms to the Open Source Initiative "Simplified 
+ *  BSD License" as published at: 
+ *  http://www.opensource.org/licenses/bsd-license.php 
+ *   
+ *  IAccessible2 is a trademark of the Linux Foundation. The IAccessible2 
+ *  mark may be used in accordance with the Linux Foundation Trademark 
+ *  Policy to indicate compliance with the IAccessible2 specification. 
+ * 
+ ************************************************************************/ 
+
 
 import "objidl.idl";
 import "oaidl.idl";
 import "oleacc.idl";
 
 /** @brief This interface gives access to the application's name and version information.
         
  This interface provides the AT with the information it needs to differentiate 
@@ -50,16 +78,19 @@ interface IAccessibleApplication : IUnkn
   */
   [propget] HRESULT appName
     (
      [out, retval] BSTR *name
     );
 
   /** @brief Returns the application version.
    @param [out] version
+    The version string must not contain levels when it is know beforehand that
+    this information will never require a change in a client's behavior.
+    For example, use "3.6.0" rather than "3.6.0.v201005131500".
    @retval S_OK
    @retval S_FALSE if there is nothing to return, [out] value is NULL
   */
   [propget] HRESULT appVersion
     (
      [out, retval] BSTR *version
     );
 
@@ -70,16 +101,19 @@ interface IAccessibleApplication : IUnkn
   */
   [propget] HRESULT toolkitName
     (
      [out, retval] BSTR *name
     );
 
   /** @brief Returns the toolkit/bridge version.
    @param [out] version
+    The version string must not contain levels when it is know beforehand that
+    this information will never require a change in a client's behavior.
+    For example, use "3.6.0" rather than "3.6.0.v201005131500".
    @retval S_OK
    @retval S_FALSE if there is nothing to return, [out] value is NULL
   */
   [propget] HRESULT toolkitVersion
     (
      [out, retval] BSTR *version
     );  
 
--- a/other-licenses/ia2/AccessibleComponent.idl
+++ b/other-licenses/ia2/AccessibleComponent.idl
@@ -1,33 +1,60 @@
 /*************************************************************************
  *
  *  File Name (AccessibleComponent.idl)
- *
- *  IAccessible2 IDL Specification
- *
- *  Copyright (c) Linux Foundation 2007, 2008
- *  Copyright (c) IBM Corp. 2006
- *  Copyright (c) Sun Microsystems, Inc. 2000, 2006
+ * 
+ *  IAccessible2 IDL Specification 
+ * 
+ *  Copyright (c) 2007, 2010 Linux Foundation 
+ *  Copyright (c) 2006 IBM Corporation 
+ *  Copyright (c) 2000, 2006 Sun Microsystems, Inc. 
+ *  All rights reserved. 
+ *   
+ *   
+ *  Redistribution and use in source and binary forms, with or without 
+ *  modification, are permitted provided that the following conditions 
+ *  are met: 
+ *   
+ *   1. Redistributions of source code must retain the above copyright 
+ *      notice, this list of conditions and the following disclaimer. 
+ *   
+ *   2. Redistributions in binary form must reproduce the above 
+ *      copyright notice, this list of conditions and the following 
+ *      disclaimer in the documentation and/or other materials 
+ *      provided with the distribution. 
  *
- *  This library is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Lesser General Public
- *  License version 2.1, as published by the Free Software Foundation; either
- *  version 2.1 of the License, or (at your option) any later version.
- *
- *  This library is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *  Lesser General Public License for more details.
- *
- *  You should have received a copy of the GNU Lesser General Public
- *  License along with this library; if not, write to the Free Software
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02110-1301  USA
- *
- ************************************************************************/
+ *   3. Neither the name of the Linux Foundation nor the names of its 
+ *      contributors may be used to endorse or promote products 
+ *      derived from this software without specific prior written 
+ *      permission. 
+ *   
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
+ *  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
+ *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+ *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
+ *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
+ *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
+ *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
+ *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+ *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
+ *  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
+ *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ *   
+ *  This BSD License conforms to the Open Source Initiative "Simplified 
+ *  BSD License" as published at: 
+ *  http://www.opensource.org/licenses/bsd-license.php 
+ *   
+ *  IAccessible2 is a trademark of the Linux Foundation. The IAccessible2 
+ *  mark may be used in accordance with the Linux Foundation Trademark 
+ *  Policy to indicate compliance with the IAccessible2 specification. 
+ * 
+ ************************************************************************/ 
 
 import "objidl.idl";
 import "oaidl.idl";
 import "oleacc.idl";
 
 /** A value specifying a color in ARGB format, where each 8 bit color component
 specifies alpha, red, green, and blue respectively.  The alpha value is optional.
 */
new file mode 100644
--- /dev/null
+++ b/other-licenses/ia2/AccessibleDocument.idl
@@ -0,0 +1,78 @@
+/*************************************************************************
+ *
+ *  File Name (AccessibleDocument.idl)
+ * 
+ *  IAccessible2 IDL Specification 
+ * 
+ *  Copyright (c) 2013 Linux Foundation 
+ *  All rights reserved. 
+ *   
+ *   
+ *  Redistribution and use in source and binary forms, with or without 
+ *  modification, are permitted provided that the following conditions 
+ *  are met: 
+ *   
+ *   1. Redistributions of source code must retain the above copyright 
+ *      notice, this list of conditions and the following disclaimer. 
+ *   
+ *   2. Redistributions in binary form must reproduce the above 
+ *      copyright notice, this list of conditions and the following 
+ *      disclaimer in the documentation and/or other materials 
+ *      provided with the distribution. 
+ *
+ *   3. Neither the name of the Linux Foundation nor the names of its 
+ *      contributors may be used to endorse or promote products 
+ *      derived from this software without specific prior written 
+ *      permission. 
+ *   
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
+ *  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
+ *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+ *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
+ *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
+ *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
+ *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
+ *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+ *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
+ *  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
+ *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ *   
+ *  This BSD License conforms to the Open Source Initiative "Simplified 
+ *  BSD License" as published at: 
+ *  http://www.opensource.org/licenses/bsd-license.php 
+ *   
+ *  IAccessible2 is a trademark of the Linux Foundation. The IAccessible2 
+ *  mark may be used in accordance with the Linux Foundation Trademark 
+ *  Policy to indicate compliance with the IAccessible2 specification. 
+ * 
+ ************************************************************************/ 
+
+import "objidl.idl";
+import "oaidl.idl";
+import "oleacc.idl";
+
+/** @brief This interface represents documents.
+
+ This interface is used for a representation of documents.
+*/
+[object, uuid(C48C7FCF-4AB5-4056-AFA6-902D6E1D1149)]
+interface IAccessibleDocument : IUnknown
+{
+  /** @brief Returns the most recently used anchor target within a document.
+  
+   A document's most recently targeted in-page anchor is returned.  A typical use
+    of this method is to fetch the anchor target within an HTML document.  In this
+    case anchor targets are those which has been defined with the <a> tag.  
+
+   @param [out] accessible
+   @retval S_OK
+   @retval S_FALSE if there are no existing valid anchor targets, [out] value is NULL.
+  */
+  [propget] HRESULT anchorTarget
+    (
+     [out, retval] IUnknown **accessible
+    );
+
+}
--- a/other-licenses/ia2/AccessibleEditableText.idl
+++ b/other-licenses/ia2/AccessibleEditableText.idl
@@ -1,33 +1,60 @@
 /*************************************************************************
  *
  *  File Name (AccessibleEditableText.idl)
- *
- *  IAccessible2 IDL Specification
- *
- *  Copyright (c) Linux Foundation 2007, 2008
- *  Copyright (c) IBM Corp. 2006
- *  Copyright (c) Sun Microsystems, Inc. 2000, 2006
+ * 
+ *  IAccessible2 IDL Specification 
+ * 
+ *  Copyright (c) 2007, 2012 Linux Foundation 
+ *  Copyright (c) 2006 IBM Corporation 
+ *  Copyright (c) 2000, 2006 Sun Microsystems, Inc. 
+ *  All rights reserved. 
+ *   
+ *   
+ *  Redistribution and use in source and binary forms, with or without 
+ *  modification, are permitted provided that the following conditions 
+ *  are met: 
+ *   
+ *   1. Redistributions of source code must retain the above copyright 
+ *      notice, this list of conditions and the following disclaimer. 
+ *   
+ *   2. Redistributions in binary form must reproduce the above 
+ *      copyright notice, this list of conditions and the following 
+ *      disclaimer in the documentation and/or other materials 
+ *      provided with the distribution. 
  *
- *  This library is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Lesser General Public
- *  License version 2.1, as published by the Free Software Foundation; either
- *  version 2.1 of the License, or (at your option) any later version.
- *
- *  This library is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *  Lesser General Public License for more details.
- *
- *  You should have received a copy of the GNU Lesser General Public
- *  License along with this library; if not, write to the Free Software
- *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
- *
- ************************************************************************/
+ *   3. Neither the name of the Linux Foundation nor the names of its 
+ *      contributors may be used to endorse or promote products 
+ *      derived from this software without specific prior written 
+ *      permission. 
+ *   
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
+ *  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
+ *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+ *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
+ *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
+ *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
+ *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
+ *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+ *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
+ *  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
+ *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ *   
+ *  This BSD License conforms to the Open Source Initiative "Simplified 
+ *  BSD License" as published at: 
+ *  http://www.opensource.org/licenses/bsd-license.php 
+ *   
+ *  IAccessible2 is a trademark of the Linux Foundation. The IAccessible2 
+ *  mark may be used in accordance with the Linux Foundation Trademark 
+ *  Policy to indicate compliance with the IAccessible2 specification. 
+ * 
+ ************************************************************************/ 
 
 import "objidl.idl";
 import "oaidl.idl";
 import "oleacc.idl";
 import "IA2CommonTypes.idl";
 
 /** @brief This interface provides clipboard capability to text objects.
 
@@ -49,27 +76,32 @@ import "IA2CommonTypes.idl";
   for information about a special offset constant that can be used in %IAccessibleEditableText methods.
 */
 [object, uuid(A59AA09A-7011-4b65-939D-32B1FB5547E3)]
 interface IAccessibleEditableText : IUnknown
 {
 
   /** @brief Copies the text range into the clipboard.
     
-   The specified text between the two given indices is copied into the
-    system clipboard.  
+   The selection is set to the specified offsets and then selection is copied into
+   the system clipboard.
         
    @param [in] startOffset
     Start index of the text to moved into the clipboard.
     The valid range is 0..length.
    @param [in] endOffset
     End index of the text to moved into the clipboard.
     The valid range is 0..length.
    @retval S_OK
    @retval E_INVALIDARG if bad [in] passed
+   @note Refer to @ref _specialOffsets 
+    "Special Offsets for use in the IAccessibleText and IAccessibleEditableText Methods" 
+    for information about special offsets that can be used in %IAccessibleEditableText
+    methods.
+   @deprecated This function is available via the application's GUI.
   */
   HRESULT copyText
     (
      [in] long startOffset, 
      [in] long endOffset 
     );
 
   /** @brief Deletes a range of text.
@@ -80,75 +112,94 @@ interface IAccessibleEditableText : IUnk
    @param [in] startOffset
     Start index of the text to be deleted.
     The valid range is 0..length.
    @param [in] endOffset
     End index of the text to be deleted.
     The valid range is 0..length.
    @retval S_OK
    @retval E_INVALIDARG if bad [in] passed
+   @note Refer to @ref _specialOffsets 
+    "Special Offsets for use in the IAccessibleText and IAccessibleEditableText Methods" 
+    for information about special offsets that can be used in %IAccessibleEditableText
+    methods.
   */
   HRESULT deleteText
     (
      [in] long startOffset, 
      [in] long endOffset 
     );
   
   /** @brief Inserts text at the specified position.
     
    The specified string is inserted at the given index into the text
     represented by this object.
 
    @param [in] offset
     Index at which to insert the text.
     The valid range is 0..length.
+	Refer to @ref _specialOffsets 
+    "Special Offsets for use in the IAccessibleText and IAccessibleEditableText Methods" 
+    for information about special offsets that can be used in %IAccessibleEditableText
+    methods.
    @param [in] text
     Text that is inserted.
    @retval S_OK
    @retval E_INVALIDARG if bad [in] passed
   */
   HRESULT insertText
     (
      [in] long offset,
      [in] BSTR *text
     );
   
   /** @brief Deletes a range of text and copies it to the clipboard.
     
-   The text between the two given indices is deleted from the text
-    represented by this object and copied to the clipboard.
+   The selection is set to the specified offsets, the selection is then copied into
+    the system clipboard, and then the selection is deleted.
 
    @param [in] startOffset
     Start index of the text to be deleted.
     The valid range is 0..length.
    @param [in] endOffset 	
     End index of the text to be deleted.
     The valid range is 0..length.
    @retval S_OK
    @retval E_INVALIDARG if bad [in] passed
+   @note Refer to @ref _specialOffsets 
+    "Special Offsets for use in the IAccessibleText and IAccessibleEditableText Methods" 
+    for information about special offsets that can be used in %IAccessibleEditableText
+    methods.
+   @deprecated This function is available via the application's GUI.
   */
   HRESULT cutText
     (
      [in] long startOffset,
      [in] long endOffset
     );
 
-  /** @brief Pastes text from the clipboard.
+  /** @brief Pastes content from the clipboard.
     
-   The text in the system clipboard is pasted into the text represented
-    by this object at the given index.  This method is similar to the 
-	IAccessibleEditableText::insertText method. If the index is not valid 
-	the system clipboard text is not inserted.
-   
+   Any existing selection is removed, the clipboard content is then pasted into 
+    this object's text at the given offset.  This method is similar to the insertText
+    method.  If the index is not valid the system clipboard content is not inserted. The
+    behavior is the same as	when Ctrl+V is used, i.e. the pasted contents are not
+    necessarily plain text.
+  
    @param [in] offset
-    Index at which to insert the text from the system clipboard into
+    Index at which to insert the content from the system clipboard into
     the text represented by this object.
     The valid range is 0..length.
+	Refer to @ref _specialOffsets 
+    "Special Offsets for use in the IAccessibleText and IAccessibleEditableText Methods" 
+    for information about special offsets that can be used in %IAccessibleEditableText
+    methods.
    @retval S_OK
    @retval E_INVALIDARG if bad [in] passed
+   @deprecated This function is available via the application's GUI.
   */
   HRESULT pasteText
     (
      [in] long offset
     );
 
   /** @brief Replaces text.
     
@@ -157,22 +208,26 @@ interface IAccessibleEditableText : IUnk
     IAccessibleEditableText::deleteText with the two indices and then 
     calling IAccessibleEditableText::insertText with the replacement text
 	at the start index.
        
    @param [in] startOffset
     Start index of the text to be replaced.
     The valid range is 0..length.
    @param [in] endOffset
-    Start index of the text to be replaced.
+    End index of the text to be replaced.
     The valid range is 0..length.
    @param [in] text
     The Text that replaces the text between the given indices.
    @retval S_OK
    @retval E_INVALIDARG if bad [in] passed
+   @note Refer to @ref _specialOffsets 
+    "Special Offsets for use in the IAccessibleText and IAccessibleEditableText Methods" 
+    for information about special offsets that can be used in %IAccessibleEditableText
+    methods.
   */
   HRESULT replaceText
     (
      [in] long startOffset,
      [in] long endOffset,
      [in] BSTR *text
     );
 
@@ -180,23 +235,27 @@ interface IAccessibleEditableText : IUnk
     
    Sets the attributes for the text between the two given indices. The old
     attributes are replaced by the new list of attributes.
         
    @param [in] startOffset
     Start index of the text whose attributes are modified.
     The valid range is 0..length.
    @param [in] endOffset
-    Start index of the text whose attributes are modified.
+    End index of the text whose attributes are modified.
     The valid range is 0..length.
    @param [in] attributes
     Set of attributes that replaces the old list of attributes of
     the specified text portion.
    @retval S_OK
    @retval E_INVALIDARG if bad [in] passed
+   @note Refer to @ref _specialOffsets 
+    "Special Offsets for use in the IAccessibleText and IAccessibleEditableText Methods" 
+    for information about special offsets that can be used in %IAccessibleEditableText
+    methods.
   */
   HRESULT setAttributes
     (
      [in] long startOffset,
      [in] long endOffset,
      [in] BSTR *attributes
     );
 }
--- a/other-licenses/ia2/AccessibleEventId.idl
+++ b/other-licenses/ia2/AccessibleEventId.idl
@@ -1,47 +1,74 @@
 /*************************************************************************
  *
  *  File Name (AccessibleEventID.idl)
- *
- *  IAccessible2 IDL Specification
- *
- *  Copyright (c) Linux Foundation 2007, 2008
- *  Copyright (c) IBM Corp. 2006
- *  Copyright (c) Sun Microsystems, Inc. 2000, 2006
+ * 
+ *  IAccessible2 IDL Specification 
+ * 
+ *  Copyright (c) 2007, 2010 Linux Foundation 
+ *  Copyright (c) 2006 IBM Corporation 
+ *  Copyright (c) 2000, 2006 Sun Microsystems, Inc. 
+ *  All rights reserved. 
+ *   
+ *   
+ *  Redistribution and use in source and binary forms, with or without 
+ *  modification, are permitted provided that the following conditions 
+ *  are met: 
+ *   
+ *   1. Redistributions of source code must retain the above copyright 
+ *      notice, this list of conditions and the following disclaimer. 
+ *   
+ *   2. Redistributions in binary form must reproduce the above 
+ *      copyright notice, this list of conditions and the following 
+ *      disclaimer in the documentation and/or other materials 
+ *      provided with the distribution. 
  *
- *  This library is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Lesser General Public
- *  License version 2.1, as published by the Free Software Foundation; either
- *  version 2.1 of the License, or (at your option) any later version.
- *
- *  This library is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *  Lesser General Public License for more details.
- *
- *  You should have received a copy of the GNU Lesser General Public
- *  License along with this library; if not, write to the Free Software
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02110-1301  USA
- *
- ************************************************************************/
+ *   3. Neither the name of the Linux Foundation nor the names of its 
+ *      contributors may be used to endorse or promote products 
+ *      derived from this software without specific prior written 
+ *      permission. 
+ *   
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
+ *  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
+ *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+ *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
+ *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
+ *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
+ *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
+ *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+ *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
+ *  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
+ *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ *   
+ *  This BSD License conforms to the Open Source Initiative "Simplified 
+ *  BSD License" as published at: 
+ *  http://www.opensource.org/licenses/bsd-license.php 
+ *   
+ *  IAccessible2 is a trademark of the Linux Foundation. The IAccessible2 
+ *  mark may be used in accordance with the Linux Foundation Trademark 
+ *  Policy to indicate compliance with the IAccessible2 specification. 
+ * 
+ ************************************************************************/ 
 
 /** %IAccessible2 specific event constants 
 
  This enum defines the event IDs fired by %IAccessible2 objects.  The event IDs
  are in addition to those used by MSAA.
 */
 enum IA2EventID {
 
   /** The change of the number or attributes of actions of an accessible
     object is signaled by events of this type. 
   */
   IA2_EVENT_ACTION_CHANGED = 0x101,
 
-  /** The active descendant of a component has changed.
+  /** <b>Deprecated.</b> The active descendant of a component has changed.
 	
 	Note: This event constant is misspelled and thus is deprecated and will be
 	removed in a later version. Please use the correctly spelled version which
 	follows.
   */
   IA2_EVENT_ACTIVE_DECENDENT_CHANGED,
 
   /** The active descendant of a component has changed.  The active descendant 
--- a/other-licenses/ia2/AccessibleHyperlink.idl
+++ b/other-licenses/ia2/AccessibleHyperlink.idl
@@ -1,33 +1,60 @@
 /*************************************************************************
  *
  *  File Name (AccessibleHyperlink.idl)
- *