Merge m-c to b2g-inbound
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Thu, 26 Sep 2013 13:56:53 +0200
changeset 148878 dd888d7af6a83c5be7032469d330b261bd499072
parent 148877 4218995e8a9e39dde2db3889226a220c09157b5c (current diff)
parent 148785 f77c6ef21e9d2bc3860e084e7649ffc2d78fff2e (diff)
child 148879 347b380903ebb789f7600752d445dd6ce67a2ed1
push id34380
push userryanvm@gmail.com
push dateFri, 27 Sep 2013 01:41:00 +0000
treeherdermozilla-inbound@fdc6054e33e4 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone27.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge m-c to b2g-inbound
js/src/jsmemorymetrics.cpp
--- a/config/check_spidermonkey_style.py
+++ b/config/check_spidermonkey_style.py
@@ -312,20 +312,16 @@ def is_module_header(enclosing_inclname,
     if module == module_name(header_inclname):
         return True
 
     # A public header, e.g. module == "foo/Bar", header_inclname == "js/Bar.h".
     m = re.match(r'js\/(.*)\.h', header_inclname)
     if m is not None and module.endswith('/' + m.group(1)):
         return True
 
-    # A weird public header case.
-    if module == 'jsmemorymetrics' and header_inclname == 'js/MemoryMetrics.h':
-        return True
-
     return False
 
 
 class Include(object):
     '''Important information for a single #include statement.'''
 
     def __init__(self, inclname, linenum, is_system):
         self.inclname = inclname
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -211,16 +211,17 @@
 #include "nsDOMEventTargetHelper.h"
 #include "prrng.h"
 #include "nsSandboxFlags.h"
 #include "TimeChangeObserver.h"
 #include "mozilla/dom/AudioContext.h"
 #include "mozilla/dom/BrowserElementDictionariesBinding.h"
 #include "mozilla/dom/FunctionBinding.h"
 #include "mozilla/dom/WindowBinding.h"
+#include "mozilla/dom/TabChild.h"
 
 #ifdef MOZ_WEBSPEECH
 #include "mozilla/dom/SpeechSynthesis.h"
 #endif
 
 #ifdef MOZ_JSDEBUGGER
 #include "jsdIDebuggerService.h"
 #endif
@@ -5708,16 +5709,19 @@ nsGlobalWindow::Focus()
     nsCOMPtr<nsIDOMElement> frameElement = do_QueryInterface(frame);
     if (frameElement) {
       uint32_t flags = nsIFocusManager::FLAG_NOSCROLL;
       if (canFocus)
         flags |= nsIFocusManager::FLAG_RAISE;
       return fm->SetFocus(frameElement, flags);
     }
   }
+  else if (TabChild *child = TabChild::GetFrom(this)) {
+    child->SendRequestFocus(canFocus);
+  }
   else if (canFocus) {
     // if there is no parent, this must be a toplevel window, so raise the
     // window if canFocus is true
     return fm->SetActiveWindow(this);
   }
 
   return NS_OK;
 }
--- a/dom/bindings/BindingGen.py
+++ b/dom/bindings/BindingGen.py
@@ -31,17 +31,17 @@ def generate_binding_files(config, outpu
 
     mk = Makefile()
     # NOTE: it's VERY important that we output dependencies for the FooBinding
     # file here, not for the header or generated cpp file.  These dependencies
     # are used later to properly determine changedDeps and prevent rebuilding
     # too much.  See the comment explaining $(binding_dependency_trackers) in
     # Makefile.in.
     rule = mk.create_rule([outputprefix])
-    rule.add_dependencies(os.path.join(srcprefix, x) for x in root.deps())
+    rule.add_dependencies(os.path.join(srcprefix, x) for x in sorted(root.deps()))
     rule.add_dependencies(iter_modules_in_path(topsrcdir))
     with open(depsname, 'w') as f:
         mk.dump(f)
 
 def main():
     # Parse arguments.
     from optparse import OptionParser
     usagestring = "usage: %prog [header|cpp] configFile outputPrefix srcPrefix webIDLFile"
--- a/dom/bindings/BindingUtils.cpp
+++ b/dom/bindings/BindingUtils.cpp
@@ -867,26 +867,67 @@ GetNativePropertyHooks(JSContext *cx, JS
 
   MOZ_ASSERT(IsDOMIfaceAndProtoClass(js::GetObjectClass(obj)));
   const DOMIfaceAndProtoJSClass* ifaceAndProtoJSClass =
     DOMIfaceAndProtoJSClass::FromJSClass(js::GetObjectClass(obj));
   type = ifaceAndProtoJSClass->mType;
   return ifaceAndProtoJSClass->mNativeHooks;
 }
 
+// Try to resolve a property as an unforgeable property from the given
+// NativeProperties, if it's there.  nativeProperties is allowed to be null (in
+// which case we of course won't resolve anything).
+static bool
+XrayResolveUnforgeableProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
+                               JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
+                               JS::MutableHandle<JSPropertyDescriptor> desc,
+                               const NativeProperties* nativeProperties);
+
+static bool
+XrayResolveNativeProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
+                          const NativePropertyHooks* nativePropertyHooks,
+                          DOMObjectType type, JS::Handle<JSObject*> obj,
+                          JS::Handle<jsid> id,
+                          JS::MutableHandle<JSPropertyDescriptor> desc);
+
 bool
 XrayResolveOwnProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
                        JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
                        JS::MutableHandle<JSPropertyDescriptor> desc, unsigned flags)
 {
   DOMObjectType type;
   const NativePropertyHooks *nativePropertyHooks =
     GetNativePropertyHooks(cx, obj, type);
 
-  return type != eInstance || !nativePropertyHooks->mResolveOwnProperty ||
+  if (type != eInstance) {
+    // For prototype objects and interface objects, just return their
+    // normal set of properties.
+    return XrayResolveNativeProperty(cx, wrapper, nativePropertyHooks, type,
+                                     obj, id, desc);
+  }
+
+  // Check for unforgeable properties before doing mResolveOwnProperty weirdness
+  const NativePropertiesHolder& nativeProperties =
+    nativePropertyHooks->mNativeProperties;
+  if (!XrayResolveUnforgeableProperty(cx, wrapper, obj, id, desc,
+                                      nativeProperties.regular)) {
+    return false;
+  }
+  if (desc.object()) {
+    return true;
+  }
+  if (!XrayResolveUnforgeableProperty(cx, wrapper, obj, id, desc,
+                                      nativeProperties.chromeOnly)) {
+    return false;
+  }
+  if (desc.object()) {
+    return true;
+  }
+
+  return !nativePropertyHooks->mResolveOwnProperty ||
          nativePropertyHooks->mResolveOwnProperty(cx, wrapper, obj, id, desc, flags);
 }
 
 static bool
 XrayResolveAttribute(JSContext* cx, JS::Handle<JSObject*> wrapper,
                      JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
                      const Prefable<const JSPropertySpec>* attributes, jsid* attributeIds,
                      const JSPropertySpec* attributeSpecs, JS::MutableHandle<JSPropertyDescriptor> desc)
@@ -931,16 +972,30 @@ XrayResolveAttribute(JSContext* cx, JS::
           return true;
         }
       }
     }
   }
   return true;
 }
 
+/* static */ bool
+XrayResolveUnforgeableProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
+                               JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
+                               JS::MutableHandle<JSPropertyDescriptor> desc,
+                               const NativeProperties* nativeProperties)
+{
+  return !nativeProperties || !nativeProperties->unforgeableAttributes ||
+         XrayResolveAttribute(cx, wrapper, obj, id,
+                              nativeProperties->unforgeableAttributes,
+                              nativeProperties->unforgeableAttributeIds,
+                              nativeProperties->unforgeableAttributeSpecs,
+                              desc);
+}
+
 static bool
 XrayResolveProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
                     JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
                     JS::MutableHandle<JSPropertyDescriptor> desc, DOMObjectType type,
                     const NativeProperties* nativeProperties)
 {
   const Prefable<const JSFunctionSpec>* methods;
   jsid* methodIds;
@@ -1003,28 +1058,16 @@ XrayResolveProperty(JSContext* cx, JS::H
                                 nativeProperties->attributeIds,
                                 nativeProperties->attributeSpecs, desc)) {
         return false;
       }
       if (desc.object()) {
         return true;
       }
     }
-    if (nativeProperties->unforgeableAttributes) {
-      if (!XrayResolveAttribute(cx, wrapper, obj, id,
-                                nativeProperties->unforgeableAttributes,
-                                nativeProperties->unforgeableAttributeIds,
-                                nativeProperties->unforgeableAttributeSpecs,
-                                desc)) {
-        return false;
-      }
-      if (desc.object()) {
-        return true;
-      }
-    }
   }
 
   if (nativeProperties->constants) {
     const Prefable<const ConstantSpec>* constant;
     for (constant = nativeProperties->constants; constant->specs; ++constant) {
       if (constant->isEnabled(cx, obj)) {
         // Set i to be the index into our full list of ids/specs that we're
         // looking at now.
@@ -1063,17 +1106,17 @@ ResolvePrototypeOrConstructor(JSContext*
     desc.setAttributes(attrs);
     desc.setGetter(JS_PropertyStub);
     desc.setSetter(JS_StrictPropertyStub);
     desc.value().set(JS::ObjectValue(*protoOrIface));
   }
   return JS_WrapPropertyDescriptor(cx, desc);
 }
 
-bool
+/* static */ bool
 XrayResolveNativeProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
                           const NativePropertyHooks* nativePropertyHooks,
                           DOMObjectType type, JS::Handle<JSObject*> obj,
                           JS::Handle<jsid> id,
                           JS::MutableHandle<JSPropertyDescriptor> desc)
 {
   if (type == eInterface && IdEquals(id, "prototype")) {
     return nativePropertyHooks->mPrototypeID == prototypes::id::_ID_Count ||
@@ -1899,19 +1942,20 @@ InterfaceHasInstance(JSContext* cx, int 
              "Why do we have a hasInstance hook if we don't have a prototype "
              "ID?");
 
   *bp = (domClass && domClass->mInterfaceChain[depth] == prototypeID);
   return true;
 }
 
 bool
-ReportLenientThisUnwrappingFailure(JSContext* cx, JS::Handle<JSObject*> obj)
+ReportLenientThisUnwrappingFailure(JSContext* cx, JSObject* obj)
 {
-  GlobalObject global(cx, obj);
+  JS::Rooted<JSObject*> rootedObj(cx, obj);
+  GlobalObject global(cx, rootedObj);
   if (global.Failed()) {
     return false;
   }
   nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(global.GetAsSupports());
   if (window && window->GetDoc()) {
     window->GetDoc()->WarnOnceAbout(nsIDocument::eLenientThis);
   }
   return true;
--- a/dom/bindings/BindingUtils.h
+++ b/dom/bindings/BindingUtils.h
@@ -12,16 +12,17 @@
 #include "mozilla/Alignment.h"
 #include "mozilla/dom/BindingDeclarations.h"
 #include "mozilla/dom/CallbackObject.h"
 #include "mozilla/dom/DOMJSClass.h"
 #include "mozilla/dom/DOMJSProxyHandler.h"
 #include "mozilla/dom/Exceptions.h"
 #include "mozilla/dom/NonRefcountedDOMObject.h"
 #include "mozilla/dom/Nullable.h"
+#include "mozilla/dom/RootedDictionary.h"
 #include "mozilla/dom/workers/Workers.h"
 #include "mozilla/ErrorResult.h"
 #include "mozilla/Likely.h"
 #include "mozilla/Util.h"
 #include "nsCycleCollector.h"
 #include "nsIXPConnect.h"
 #include "MainThreadUtils.h"
 #include "nsTraceRefcnt.h"
@@ -1752,52 +1753,16 @@ public:
     FallibleTArray<T>* mFallibleArray;
     Nullable<nsTArray<T> >* mNullableArray;
   };
 
   SequenceType mSequenceType;
 };
 
 template<typename T>
-class MOZ_STACK_CLASS RootedDictionary : public T,
-                                         private JS::CustomAutoRooter
-{
-public:
-  RootedDictionary(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) :
-    T(),
-    JS::CustomAutoRooter(cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT)
-  {
-  }
-
-  virtual void trace(JSTracer *trc) MOZ_OVERRIDE
-  {
-    this->TraceDictionary(trc);
-  }
-};
-
-template<typename T>
-class MOZ_STACK_CLASS NullableRootedDictionary : public Nullable<T>,
-                                                 private JS::CustomAutoRooter
-{
-public:
-  NullableRootedDictionary(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) :
-    Nullable<T>(),
-    JS::CustomAutoRooter(cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT)
-  {
-  }
-
-  virtual void trace(JSTracer *trc) MOZ_OVERRIDE
-  {
-    if (!this->IsNull()) {
-      this->Value().TraceDictionary(trc);
-    }
-  }
-};
-
-template<typename T>
 class MOZ_STACK_CLASS RootedUnion : public T,
                                     private JS::CustomAutoRooter
 {
 public:
   RootedUnion(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) :
     T(),
     JS::CustomAutoRooter(cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT)
   {
@@ -2057,17 +2022,17 @@ InterfaceHasInstance(JSContext* cx, JS::
 bool
 InterfaceHasInstance(JSContext* cx, int prototypeID, int depth,
                      JS::Handle<JSObject*> instance,
                      bool* bp);
 
 // Helper for lenient getters/setters to report to console.  If this
 // returns false, we couldn't even get a global.
 bool
-ReportLenientThisUnwrappingFailure(JSContext* cx, JS::Handle<JSObject*> obj);
+ReportLenientThisUnwrappingFailure(JSContext* cx, JSObject* obj);
 
 inline JSObject*
 GetUnforgeableHolder(JSObject* aGlobal, prototypes::ID aId)
 {
   JS::Heap<JSObject*>* protoAndIfaceArray = GetProtoAndIfaceArray(aGlobal);
   JSObject* interfaceProto = protoAndIfaceArray[aId];
   return &js::GetReservedSlot(interfaceProto,
                               DOM_INTERFACE_PROTO_SLOTS_BASE).toObject();
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -821,18 +821,23 @@ def UnionTypes(descriptors, dictionaries
                         for p in providers:
                             try:
                                 typeDesc = p.getDescriptor(f.inner.identifier.name)
                             except NoSuchDescriptorError:
                                 continue
                             declarations.add((typeDesc.nativeType, False))
                             implheaders.add(typeDesc.headerFile)
                 elif f.isDictionary():
-                    declarations.add((f.inner.identifier.name, True))
-                    implheaders.add(CGHeaders.getDeclarationFilename(f.inner))
+                    # For a dictionary, we need to see its declaration in
+                    # UnionTypes.h so we have its sizeof and know how big to
+                    # make our union.
+                    headers.add(CGHeaders.getDeclarationFilename(f.inner))
+                    # And if it needs rooting, we need RootedDictionary too
+                    if typeNeedsRooting(f):
+                        headers.add("mozilla/dom/RootedDictionary.h")
                 elif t.isPrimitive():
                     implheaders.add("mozilla/dom/PrimitiveConversions.h")
 
     map(addInfoForType, getAllTypes(descriptors, dictionaries, callbacks))
 
     return (headers, implheaders, declarations,
             CGList(itertools.chain(SortedDictValues(unionStructs),
                                    SortedDictValues(owningUnionStructs)), "\n"))
@@ -2549,17 +2554,16 @@ def getJSToNativeConversionInfo(type, de
                                 treatUndefinedAs="Default",
                                 isEnforceRange=False,
                                 isClamp=False,
                                 isNullOrUndefined=False,
                                 exceptionCode=None,
                                 lenientFloatCode=None,
                                 allowTreatNonCallableAsNull=False,
                                 isCallbackReturnValue=False,
-                                isInOwningUnion=False,
                                 sourceDescription="value"):
     """
     Get a template for converting a JS value to a native object based on the
     given type and descriptor.  If failureCode is given, then we're actually
     testing whether we can convert the argument to the desired type.  That
     means that failures to convert due to the JS value being the wrong type of
     value need to use failureCode instead of throwing exceptions.  Failures to
     convert that are due to JS exceptions (from toString or valueOf methods) or
@@ -2570,19 +2574,19 @@ def getJSToNativeConversionInfo(type, de
     function must happen via exceptionCode if exceptionCode is not None.
 
     If isDefinitelyObject is True, that means we know the value
     isObject() and we have no need to recheck that.
 
     if isMember is not False, we're being converted from a property of some JS
     object, not from an actual method argument, so we can't rely on our jsval
     being rooted or outliving us in any way.  Callers can pass "Dictionary",
-    "Variadic", or "Sequence" to indicate that the conversion is for something
-    that is a dictionary member, a variadic argument, or a sequence
-    respectively.
+    "Variadic", "Sequence", or "OwningUnion" to indicate that the conversion is
+    for something that is a dictionary member, a variadic argument, a sequence,
+    or an owning union respectively.
 
     If isOptional is true, then we are doing conversion of an optional
     argument with no default value.
 
     invalidEnumValueFatal controls whether an invalid enum value conversion
     attempt will throw (if true) or simply return without doing anything (if
     false).
 
@@ -2715,36 +2719,38 @@ def getJSToNativeConversionInfo(type, de
             if type.nullable():
                 templateBody = handleDefaultNull(templateBody, codeToSetNull)
             else:
                 assert(defaultValue is None)
 
         return templateBody
 
     # A helper function for converting things that look like a JSObject*.
-    def handleJSObjectType(type, isMember, isInOwningUnion, failureCode):
-        if not isMember and not isInOwningUnion:
+    def handleJSObjectType(type, isMember, failureCode):
+        if not isMember:
             if isOptional:
                 # We have a specialization of Optional that will use a
                 # Rooted for the storage here.
                 declType = CGGeneric("JS::Handle<JSObject*>")
             else:
                 declType = CGGeneric("JS::Rooted<JSObject*>")
+            declArgs="cx"
         else:
             assert (isMember == "Sequence" or isMember == "Variadic" or
-                    isMember == "Dictionary" or isInOwningUnion)
+                    isMember == "Dictionary" or isMember == "OwningUnion")
             # We'll get traced by the sequence or dictionary or union tracer
             declType = CGGeneric("JSObject*")
+            declArgs = None
         templateBody = "${declName} = &${val}.toObject();"
         setToNullCode = "${declName} = nullptr;"
         template = wrapObjectTemplate(templateBody, type, setToNullCode,
                                       failureCode)
         return JSToNativeConversionInfo(template, declType=declType,
                                         dealWithOptional=isOptional,
-                                        declArgs="cx")
+                                        declArgs=declArgs)
 
     assert not (isEnforceRange and isClamp) # These are mutually exclusive
 
     if type.isArray():
         raise TypeError("Can't handle array arguments yet")
 
     if type.isSequence():
         assert not isEnforceRange and not isClamp
@@ -2920,58 +2926,62 @@ for (uint32_t i = 0; i < length; ++i) {
             name = memberType.name
             callbackObject = CGGeneric("done = (failed = !%s.TrySetTo%s(cx, ${val}, ${mutableVal}, tryNext)) || !tryNext;" % (unionArgumentObj, name))
             names.append(name)
         else:
             callbackObject = None
 
         dictionaryMemberTypes = filter(lambda t: t.isDictionary(), memberTypes)
         if len(dictionaryMemberTypes) > 0:
-            raise TypeError("No support for unwrapping dictionaries as member "
-                            "of a union")
-        else:
-            dictionaryObject = None
+            assert len(dictionaryMemberTypes) == 1
+            name = dictionaryMemberTypes[0].inner.identifier.name
+            setDictionary = CGGeneric("done = (failed = !%s.TrySetTo%s(cx, ${val}, ${mutableVal}, tryNext)) || !tryNext;" % (unionArgumentObj, name))
+        else:
+            setDictionary = None
 
         objectMemberTypes = filter(lambda t: t.isObject(), memberTypes)
         if len(objectMemberTypes) > 0:
+            assert len(objectMemberTypes) == 1
             object = CGGeneric("%s.SetToObject(cx, argObj);\n"
                                "done = true;" % unionArgumentObj)
         else:
             object = None
 
-        hasObjectTypes = interfaceObject or arrayObject or dateObject or callbackObject or dictionaryObject or object
+        hasObjectTypes = interfaceObject or arrayObject or dateObject or callbackObject or object
         if hasObjectTypes:
             # "object" is not distinguishable from other types
-            assert not object or not (interfaceObject or arrayObject or dateObject or callbackObject or dictionaryObject)
-            if arrayObject or dateObject or callbackObject or dictionaryObject:
+            assert not object or not (interfaceObject or arrayObject or dateObject or callbackObject)
+            if arrayObject or dateObject or callbackObject:
                 # An object can be both an array object and a callback or
                 # dictionary, but we shouldn't have both in the union's members
                 # because they are not distinguishable.
                 assert not (arrayObject and callbackObject)
-                assert not (arrayObject and dictionaryObject)
-                assert not (dictionaryObject and callbackObject)
-                templateBody = CGList([arrayObject, dateObject, callbackObject,
-                                       dictionaryObject], " else ")
+                templateBody = CGList([arrayObject, dateObject, callbackObject],
+                                      " else ")
             else:
                 templateBody = None
             if interfaceObject:
                 assert not object
                 if templateBody:
                     templateBody = CGIfWrapper(templateBody, "!done")
                 templateBody = CGList([interfaceObject, templateBody], "\n")
             else:
                 templateBody = CGList([templateBody, object], "\n")
 
-            if any([arrayObject, dateObject, callbackObject, dictionaryObject,
-                    object]):
+            if any([arrayObject, dateObject, callbackObject, object]):
                 templateBody.prepend(CGGeneric("JS::Rooted<JSObject*> argObj(cx, &${val}.toObject());"))
             templateBody = CGIfWrapper(templateBody, "${val}.isObject()")
         else:
             templateBody = CGGeneric()
 
+        if setDictionary:
+            assert not object
+            templateBody = CGList([templateBody,
+                                   CGIfWrapper(setDictionary, "!done")], "\n")
+
         stringTypes = [t for t in memberTypes if t.isString() or t.isEnum()]
         numericTypes = [t for t in memberTypes if t.isNumeric()]
         booleanTypes = [t for t in memberTypes if t.isBoolean()]
         if stringTypes or numericTypes or booleanTypes:
             assert len(stringTypes) <= 1
             assert len(numericTypes) <= 1
             assert len(booleanTypes) <= 1
             # We will wrap all this stuff in a do { } while (0); so we
@@ -3000,17 +3010,17 @@ for (uint32_t i = 0; i < length; ++i) {
                     other.append(CGIfWrapper(booleanConversion[0],
                                              "${val}.isBoolean()"))
                 other.append(numericConversion[0])
             else:
                 assert booleanConversion
                 other.append(booleanConversion[0])
 
             other = CGWrapper(CGIndenter(other), pre="do {\n", post="\n} while (0);")
-            if hasObjectTypes:
+            if hasObjectTypes or setDictionary:
                 other = CGWrapper(CGIndenter(other), "{\n", post="\n}")
                 if object:
                     join = " else "
                 else:
                     other = CGWrapper(other, pre="if (!done) ")
                     join = "\n"
                 templateBody = CGList([templateBody, other], join)
             else:
@@ -3114,18 +3124,17 @@ for (uint32_t i = 0; i < length; ++i) {
         assert not isEnforceRange and not isClamp
 
         descriptor = descriptorProvider.getDescriptor(
             type.unroll().inner.identifier.name)
 
         if descriptor.nativeType == 'JSObject':
             # XXXbz Workers code does this sometimes
             assert descriptor.workers
-            return handleJSObjectType(type, isMember, isInOwningUnion,
-                                      failureCode)
+            return handleJSObjectType(type, isMember, failureCode)
 
         if descriptor.interface.isCallback():
             name = descriptor.interface.identifier.name
             if type.nullable() or isCallbackReturnValue:
                 declType = CGGeneric("nsRefPtr<%s>" % name);
             else:
                 declType = CGGeneric("OwningNonNull<%s>" % name)
             conversion = (
@@ -3151,17 +3160,16 @@ for (uint32_t i = 0; i < length; ++i) {
         # because they may be returning an addrefed pointer.
         # Also, callback return values always end up
         # addrefing anyway, so there is no point trying to avoid it here and it
         # makes other things simpler since we can assume the return value is a
         # strong ref.
         forceOwningType = ((descriptor.interface.isCallback() and
                             not descriptor.workers) or
                            isMember or
-                           isInOwningUnion or
                            isCallbackReturnValue)
 
         typeName = descriptor.nativeType
         typePtr = typeName + "*"
 
         # Compute a few things:
         #  - declType is the type we want to return as the first element of our
         #    tuple.
@@ -3261,17 +3269,17 @@ for (uint32_t i = 0; i < length; ++i) {
         template = (
             "if (!%s.Init(&${val}.toObject())) {\n"
             "%s" # No newline here because onFailureBadType() handles that
             "}\n" %
             (objRef,
              CGIndenter(onFailureBadType(failureCode, type.name)).define()))
         template = wrapObjectTemplate(template, type, "${declName}.SetNull()",
                                       failureCode)
-        if not isMember and not isInOwningUnion:
+        if not isMember:
             # This is a bit annoying.  In a union we don't want to have a
             # holder, since unions don't support that.  But if we're optional we
             # want to have a holder, so that the callee doesn't see
             # Optional<RootedTypedArray<ArrayType> >.  So do a holder if we're
             # optional and use a RootedTypedArray otherwise.
             if isOptional:
                 holderType = CGTemplatedType("TypedArrayRooter", arrayType)
                 # If our typed array is nullable, this will set the Nullable to
@@ -3353,32 +3361,24 @@ for (uint32_t i = 0; i < length; ++i) {
                 "  %s;\n"
                 "}\n" % (
                     CGIndenter(CGGeneric(getConversionCode("str"))).define(),
                     assignString),
                 declType=declType, dealWithOptional=isOptional)
 
         if isOptional:
             declType = "Optional<nsAString>"
-        elif isInOwningUnion:
-            declType = "nsString"
         else:
             declType = "NonNull<nsAString>"
 
         # No need to deal with optional here; we handled it already
-        decl = ""
-        if isInOwningUnion:
-            decl += "FakeDependentString str;\n"
         return JSToNativeConversionInfo(
-            "%s"
-            "%s\n"
-            "${declName} = %s" %
-              (decl,
-               getConversionCode("str" if isInOwningUnion else "${holderName}"),
-               ("str;" if isInOwningUnion else "&${holderName};")),
+            ("%s\n"
+             "${declName} = &${holderName};" %
+             getConversionCode("${holderName}")),
             declType=CGGeneric(declType),
             holderType=CGGeneric("FakeDependentString"))
 
     if type.isByteString():
         assert not isEnforceRange and not isClamp
 
         nullable = toStringBool(type.nullable())
 
@@ -3521,23 +3521,19 @@ for (uint32_t i = 0; i < length; ++i) {
         templateBody = handleDefaultNull(templateBody, nullHandling)
         return JSToNativeConversionInfo(templateBody,
                                         declType=CGGeneric(declType),
                                         dealWithOptional=isOptional,
                                         declArgs=declArgs)
 
     if type.isObject():
         assert not isEnforceRange and not isClamp
-        return handleJSObjectType(type, isMember, isInOwningUnion, failureCode)
+        return handleJSObjectType(type, isMember, failureCode)
 
     if type.isDictionary():
-        if failureCode is not None and not isDefinitelyObject:
-            raise TypeError("Can't handle dictionaries when failureCode is "
-                            "not None and we don't know we're an object")
-
         # There are no nullable dictionaries
         assert not type.nullable()
         # All optional dictionaries always have default values, so we
         # should be able to assume not isOptional here.
         assert not isOptional
 
         typeName = CGDictionary.makeDictionaryName(type.inner)
         actualTypeName = typeName
@@ -3552,22 +3548,25 @@ for (uint32_t i = 0; i < length; ++i) {
         if (not isNullOrUndefined and not isDefinitelyObject and
             defaultValue is not None):
             assert(isinstance(defaultValue, IDLNullValue))
             val = "(${haveValue}) ? ${val} : JS::NullHandleValue"
         else:
             val = "${val}"
 
         if failureCode is not None:
-            assert isDefinitelyObject
+            if isDefinitelyObject:
+                dictionaryTest = "IsObjectValueConvertibleToDictionary"
+            else:
+                dictionaryTest = "IsConvertibleToDictionary"
             # Check that the value we have can in fact be converted to
             # a dictionary, and return failureCode if not.
             template = CGIfWrapper(
                 CGGeneric(failureCode),
-                "!IsObjectValueConvertibleToDictionary(cx, ${val})").define() + "\n\n"
+                "!%s(cx, ${val})" % dictionaryTest).define() + "\n\n"
         else:
             template = ""
 
         template += ('if (!${declName}.Init(cx, %s, "%s")) {\n'
                      "%s\n"
                      "}" % (val, firstCap(sourceDescription),
                             exceptionCodeIndented.define()))
 
@@ -5316,40 +5315,65 @@ class CGSetterCall(CGPerSignatureCall):
 
 class CGAbstractBindingMethod(CGAbstractStaticMethod):
     """
     Common class to generate the JSNatives for all our methods, getters, and
     setters.  This will generate the function declaration and unwrap the
     |this| object.  Subclasses are expected to override the generate_code
     function to do the rest of the work.  This function should return a
     CGThing which is already properly indented.
+
+    getThisObj should be code for getting a JSObject* for the binding
+    object.  If this is None, we will auto-generate code based on
+    descriptor to do the right thing.  "" can be passed in if the
+    binding object is already stored in 'obj'.
+
+    callArgs should be code for getting a JS::CallArgs into a variable
+    called 'args'.  This can be "" if there is already such a variable
+    around.
     """
     def __init__(self, descriptor, name, args, unwrapFailureCode=None,
-                 getThisObj="args.computeThis(cx).toObjectOrNull()",
+                 getThisObj=None,
                  callArgs="JS::CallArgs args = JS::CallArgsFromVp(argc, vp);"):
         CGAbstractStaticMethod.__init__(self, descriptor, name, "bool", args)
 
         if unwrapFailureCode is None:
             self.unwrapFailureCode = 'return ThrowErrorMessage(cx, MSG_THIS_DOES_NOT_IMPLEMENT_INTERFACE, "Value", "%s");' % descriptor.interface.identifier.name
         else:
             self.unwrapFailureCode = unwrapFailureCode
-        self.getThisObj = getThisObj
+
+        if getThisObj == "":
+            self.getThisObj = None
+        else:
+            if getThisObj is None:
+                if descriptor.interface.isOnGlobalProtoChain():
+                    ensureCondition = "!args.thisv().isNullOrUndefined() && !args.thisv().isObject()"
+                    getThisObj = "args.thisv().isObject() ? &args.thisv().toObject() : js::GetGlobalForObjectCrossCompartment(&args.callee())"
+                else:
+                    ensureCondition = "!args.thisv().isObject()"
+                    getThisObj = "&args.thisv().toObject()"
+                ensureThisObj = CGIfWrapper(CGGeneric(self.unwrapFailureCode),
+                                            ensureCondition)
+            else:
+                ensureThisObj = None
+            self.getThisObj = CGList(
+                [ensureThisObj,
+                 CGGeneric("JS::RootedObject obj(cx, %s);\n" %
+                           getThisObj)],
+                "\n")
         self.callArgs = callArgs
 
     def definition_body(self):
         # Our descriptor might claim that we're not castable, simply because
         # we're someone's consequential interface.  But for this-unwrapping, we
         # know that we're the real deal.  So fake a descriptor here for
         # consumption by CastableObjectUnwrapper.
         getThis = CGList([
                 CGGeneric(self.callArgs) if self.callArgs != "" else None,
-                CGGeneric("JS::RootedObject obj(cx, %s);\n"
-                          "if (!obj) {\n"
-                          "  return false;\n"
-                          "}" % self.getThisObj) if self.getThisObj else None,
+                self.getThisObj,
                 CGGeneric("%s* self;" % self.descriptor.nativeType)
                 ], "\n")
         unwrapThis = CGGeneric(
             str(CastableObjectUnwrapper(
                         self.descriptor,
                         "obj", "self", self.unwrapFailureCode)))
         return CGList([ CGIndenter(getThis), CGIndenter(unwrapThis),
                         self.generate_code() ], "\n").define()
@@ -5580,17 +5604,17 @@ class CGGenericGetter(CGAbstractBindingM
     """
     def __init__(self, descriptor, lenientThis=False):
         args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'),
                 Argument('JS::Value*', 'vp')]
         if lenientThis:
             name = "genericLenientGetter"
             unwrapFailureCode = (
                 "MOZ_ASSERT(!JS_IsExceptionPending(cx));\n"
-                "if (!ReportLenientThisUnwrappingFailure(cx, obj)) {\n"
+                "if (!ReportLenientThisUnwrappingFailure(cx, &args.callee())) {\n"
                 "  return false;\n"
                 "}\n"
                 "args.rval().set(JS::UndefinedValue());\n"
                 "return true;")
         else:
             name = "genericGetter"
             unwrapFailureCode = (
                 'return ThrowInvalidThis(cx, args, MSG_GETTER_THIS_DOES_NOT_IMPLEMENT_INTERFACE, "%s");' %
@@ -5660,17 +5684,17 @@ class CGGenericSetter(CGAbstractBindingM
     """
     def __init__(self, descriptor, lenientThis=False):
         args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'),
                 Argument('JS::Value*', 'vp')]
         if lenientThis:
             name = "genericLenientSetter"
             unwrapFailureCode = (
                 "MOZ_ASSERT(!JS_IsExceptionPending(cx));\n"
-                "if (!ReportLenientThisUnwrappingFailure(cx, obj)) {\n"
+                "if (!ReportLenientThisUnwrappingFailure(cx, &args.callee())) {\n"
                 "  return false;\n"
                 "}\n"
                 "args.rval().set(JS::UndefinedValue());\n"
                 "return true;")
         else:
             name = "genericSetter"
             unwrapFailureCode = (
                 'return ThrowInvalidThis(cx, args, MSG_SETTER_THIS_DOES_NOT_IMPLEMENT_INTERFACE, "%s");' %
@@ -6062,50 +6086,54 @@ def getUnionAccessorSignatureType(type, 
         return CGGeneric(typeName % type.unroll().identifier.name)
 
     if type.isAny():
         return CGGeneric("JS::Value")
 
     if type.isObject():
         return CGGeneric("JSObject*")
 
+    if type.isDictionary():
+        return CGGeneric("const %s&" % type.inner.identifier.name)
+
     if not type.isPrimitive():
         raise TypeError("Need native type for argument type '%s'" % str(type))
 
     typeName = CGGeneric(builtinNames[type.tag()])
     if type.nullable():
         typeName = CGTemplatedType("Nullable", typeName, isReference=True)
     return typeName
 
 def getUnionTypeTemplateVars(unionType, type, descriptorProvider,
                              ownsMembers=False):
     # For dictionaries and sequences we need to pass None as the failureCode
     # for getJSToNativeConversionInfo.
     # Also, for dictionaries we would need to handle conversion of
     # null/undefined to the dictionary correctly.
-    if type.isDictionary() or type.isSequence():
-        raise TypeError("Can't handle dictionaries or sequences in unions")
+    if type.isSequence():
+        raise TypeError("Can't handle sequences in unions")
 
     name = getUnionMemberName(type)
 
-    ctorNeedsCx = type.isSpiderMonkeyInterface() and not ownsMembers
-    ctorArgs = "cx" if ctorNeedsCx else ""
-
     tryNextCode = ("tryNext = true;\n"
                    "return true;")
     if type.isGeckoInterface():
          prefix = "" if ownsMembers else "mUnion."
          tryNextCode = ("if (%smType != %seUninitialized) {"
                         "  %sDestroy%s();"
                         "}") % (prefix, prefix, prefix, name) + tryNextCode
     conversionInfo = getJSToNativeConversionInfo(
         type, descriptorProvider, failureCode=tryNextCode,
-        isDefinitelyObject=True, isInOwningUnion=ownsMembers,
+        isDefinitelyObject=not type.isDictionary(),
+        isMember=("OwningUnion" if ownsMembers else None),
         sourceDescription="member of %s" % unionType)
 
+    ctorNeedsCx = conversionInfo.declArgs == "cx"
+    ctorArgs = "cx" if ctorNeedsCx else ""
+
     # This is ugly, but UnionMember needs to call a constructor with no
     # arguments so the type can't be const.
     structType = conversionInfo.declType.define()
     if structType.startswith("const "):
         structType = structType[6:]
     externalType = getUnionAccessorSignatureType(type, descriptorProvider).define()
 
     if type.isObject():
@@ -6262,16 +6290,21 @@ class CGUnionStruct(CGThing):
                                                      % vars["name"])))
             if self.ownsMembers and typeNeedsRooting(t):
                 if t.isObject():
                     traceCases.append(
                         CGCase("e" + vars["name"],
                                CGGeneric('JS_CallObjectTracer(trc, %s, "%s");' %
                                          ("&mValue.m" + vars["name"] + ".Value()",
                                           "mValue.m" + vars["name"]))))
+                elif t.isDictionary():
+                    traceCases.append(
+                        CGCase("e" + vars["name"],
+                               CGGeneric("mValue.m%s.Value().TraceDictionary(trc);" %
+                                         vars["name"])))
                 else:
                     assert t.isSpiderMonkeyInterface()
                     traceCases.append(
                         CGCase("e" + vars["name"],
                                CGGeneric("mValue.m%s.Value().TraceSelf(trc);" %
                                          vars["name"])))
 
         dtor = CGSwitch("mType", destructorCases).define()
@@ -7280,24 +7313,26 @@ class CGDOMJSProxyHandler_getOwnProperty
                    CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define() + "\n" +
                    "}\n") % (self.descriptor.nativeType)
 
         if UseHolderForUnforgeable(self.descriptor):
             getUnforgeable = """if (!JS_GetPropertyDescriptorById(cx, ${holder}, id, flags, desc)) {
   return false;
 }
 MOZ_ASSERT_IF(desc.object(), desc.object() == ${holder});"""
+            # We don't want to look at the unforgeable holder at all
+            # in the xray case; that part got handled already.
             getUnforgeable = CallOnUnforgeableHolder(self.descriptor,
-                                                     getUnforgeable, "isXray")
+                                                     getUnforgeable)
             getUnforgeable += """if (desc.object()) {
   desc.object().set(proxy);
-  return !isXray || JS_WrapPropertyDescriptor(cx, desc);
-}
-
-"""
+  return true;
+}"""
+            getUnforgeable = CGIfWrapper(CGGeneric(getUnforgeable),
+                                         "!isXray").define() + "\n\n"
         else:
             getUnforgeable = ""
 
         if indexedSetter or self.descriptor.operations['NamedSetter']:
             setOrIndexedGet += "if (flags & JSRESOLVE_ASSIGNING) {\n"
             if indexedSetter:
                 setOrIndexedGet += ("  if (IsArrayIndex(index)) {\n")
                 if not 'IndexedCreator' in self.descriptor.operations:
@@ -8118,23 +8153,36 @@ class CGDictionary(CGThing):
             (member,
              getJSToNativeConversionInfo(
                             member.type,
                             descriptorProvider,
                             isEnforceRange=member.enforceRange,
                             isClamp=member.clamp,
                             isMember="Dictionary",
                             isOptional=(not member.defaultValue),
-                            # Set this to true so that we get an owning union.
-                            isInOwningUnion=True,
                             defaultValue=member.defaultValue,
                             sourceDescription=("'%s' member of %s" %
                                                (member.identifier.name,
                                                 dictionary.identifier.name))))
             for member in dictionary.members ]
+        # If we have a union member containing something in the same
+        # file as us, bail: the C++ includes won't work out.
+        for member in dictionary.members:
+            type = member.type.unroll()
+            if type.isUnion():
+                for t in type.flatMemberTypes:
+                    if (t.isDictionary() and
+                        CGHeaders.getDeclarationFilename(t.inner) ==
+                        CGHeaders.getDeclarationFilename(dictionary)):
+                        raise TypeError(
+                            "Dictionary contains a union that contains a "
+                            "dictionary in the same WebIDL file.  This won't "
+                            "compile.  Move the inner dictionary to a "
+                            "different file.\n%s\n%s" %
+                            (t.location, t.inner.location))
         self.structs = self.getStructs()
 
     def declare(self):
         return self.structs.declare()
 
     def define(self):
         return self.structs.define()
 
--- a/dom/bindings/Makefile.in
+++ b/dom/bindings/Makefile.in
@@ -18,17 +18,17 @@ all_webidl_files = $(webidl_files) $(gen
 # Set exported_binding_headers before adding the test IDL to the mix
 exported_binding_headers := $(subst .webidl,Binding.h,$(all_webidl_files))
 exported_generated_events_headers := $(subst .webidl,.h,$(generated_events_webidl_files))
 
 # Set linked_binding_cpp_files before adding the test IDL to the mix
 linked_binding_cpp_files := $(subst .webidl,Binding.cpp,$(all_webidl_files))
 linked_generated_events_cpp_files := $(subst .webidl,.cpp,$(generated_events_webidl_files))
 
-all_webidl_files += $(test_webidl_files)
+all_webidl_files += $(test_webidl_files) $(preprocessed_test_webidl_files)
 
 generated_header_files := $(subst .webidl,Binding.h,$(all_webidl_files)) $(exported_generated_events_headers)
 generated_cpp_files := $(subst .webidl,Binding.cpp,$(all_webidl_files)) $(linked_generated_events_cpp_files)
 
 # We want to be able to only regenerate the .cpp and .h files that really need
 # to change when a .webidl file changes.  We do this by making the
 # binding_dependency_trackers targets have dependencies on the right .webidl
 # files via generated .pp files, having a .BindingGen target that depends on the
@@ -163,16 +163,22 @@ CSS2Properties.webidl: $(topsrcdir)/layo
 # defined.  Also make sure to remove $@ before writing to it, because otherwise
 # if a file goes from non-preprocessed to preprocessed we can end up writing to
 # a symlink, which will clobber files in the srcdir, which is bad.
 $(preprocessed_webidl_files): %: $(webidl_base)/% $(GLOBAL_DEPS)
 	$(RM) $@
 	PYTHONDONTWRITEBYTECODE=1 $(PYTHON) \
           $(topsrcdir)/config/Preprocessor.py $(DEFINES) $(ACDEFINES) $(XULPPFLAGS) $(webidl_base)/$* -o $@
 
+# See the comment about PP_TARGETS for $(preprocessed_webidl_files)
+$(preprocessed_test_webidl_files): %: $(srcdir)/test/% $(GLOBAL_DEPS)
+	$(RM) $@
+	PYTHONDONTWRITEBYTECODE=1 $(PYTHON) \
+          $(topsrcdir)/config/Preprocessor.py $(DEFINES) $(ACDEFINES) $(XULPPFLAGS) $(srcdir)/test/$* -o $@
+
 # Make is dumb and can get confused between "foo" and "$(CURDIR)/foo".  Make
 # sure that the latter depends on the former, since the latter gets used in .pp
 # files.
 all_webidl_files_absolute = $(addprefix $(CURDIR)/,$(all_webidl_files))
 $(all_webidl_files_absolute): $(CURDIR)/%: %
 
 $(generated_header_files): .BindingGen
 
copy from dom/bindings/BindingUtils.h
copy to dom/bindings/RootedDictionary.h
--- a/dom/bindings/BindingUtils.h
+++ b/dom/bindings/RootedDictionary.h
@@ -1,1766 +1,24 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/
 /* vim: set ts=2 sw=2 et tw=79: */
 /* 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_BindingUtils_h__
-#define mozilla_dom_BindingUtils_h__
+#ifndef mozilla_dom_RootedDictionary_h__
+#define mozilla_dom_RootedDictionary_h__
 
-#include "jsfriendapi.h"
-#include "jswrapper.h"
-#include "mozilla/Alignment.h"
-#include "mozilla/dom/BindingDeclarations.h"
-#include "mozilla/dom/CallbackObject.h"
-#include "mozilla/dom/DOMJSClass.h"
-#include "mozilla/dom/DOMJSProxyHandler.h"
-#include "mozilla/dom/Exceptions.h"
-#include "mozilla/dom/NonRefcountedDOMObject.h"
+#include "mozilla/GuardObjects.h"
 #include "mozilla/dom/Nullable.h"
-#include "mozilla/dom/workers/Workers.h"
-#include "mozilla/ErrorResult.h"
-#include "mozilla/Likely.h"
-#include "mozilla/Util.h"
-#include "nsCycleCollector.h"
-#include "nsIXPConnect.h"
-#include "MainThreadUtils.h"
-#include "nsTraceRefcnt.h"
-#include "qsObjectHelper.h"
-#include "xpcpublic.h"
-#include "nsIVariant.h"
-
-#include "nsWrapperCacheInlines.h"
-
-class nsPIDOMWindow;
-
-extern nsresult
-xpc_qsUnwrapArgImpl(JSContext* cx, jsval v, const nsIID& iid, void** ppArg,
-                    nsISupports** ppArgRef, jsval* vp);
+#include "jsapi.h"
 
 namespace mozilla {
 namespace dom {
 
-struct SelfRef
-{
-  SelfRef() : ptr(nullptr) {}
-  explicit SelfRef(nsISupports *p) : ptr(p) {}
-  ~SelfRef() { NS_IF_RELEASE(ptr); }
-
-  nsISupports* ptr;
-};
-
-/** Convert a jsval to an XPCOM pointer. */
-template <class Interface, class StrongRefType>
-inline nsresult
-UnwrapArg(JSContext* cx, jsval v, Interface** ppArg,
-          StrongRefType** ppArgRef, jsval* vp)
-{
-  nsISupports* argRef = *ppArgRef;
-  nsresult rv = xpc_qsUnwrapArgImpl(cx, v, NS_GET_TEMPLATE_IID(Interface),
-                                    reinterpret_cast<void**>(ppArg), &argRef,
-                                    vp);
-  *ppArgRef = static_cast<StrongRefType*>(argRef);
-  return rv;
-}
-
-bool
-ThrowInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
-                 const ErrNum aErrorNumber,
-                 const char* aInterfaceName);
-
-inline bool
-ThrowMethodFailedWithDetails(JSContext* cx, ErrorResult& rv,
-                             const char* ifaceName,
-                             const char* memberName,
-                             bool reportJSContentExceptions = false)
-{
-  if (rv.IsTypeError()) {
-    rv.ReportTypeError(cx);
-    return false;
-  }
-  if (rv.IsJSException()) {
-    if (reportJSContentExceptions) {
-      rv.ReportJSExceptionFromJSImplementation(cx);
-    } else {
-      rv.ReportJSException(cx);
-    }
-    return false;
-  }
-  if (rv.IsNotEnoughArgsError()) {
-    rv.ReportNotEnoughArgsError(cx, ifaceName, memberName);
-  }
-  return Throw(cx, rv.ErrorCode());
-}
-
-// Returns true if the JSClass is used for DOM objects.
-inline bool
-IsDOMClass(const JSClass* clasp)
-{
-  return clasp->flags & JSCLASS_IS_DOMJSCLASS;
-}
-
-inline bool
-IsDOMClass(const js::Class* clasp)
-{
-  return IsDOMClass(Jsvalify(clasp));
-}
-
-// Returns true if the JSClass is used for DOM interface and interface 
-// prototype objects.
-inline bool
-IsDOMIfaceAndProtoClass(const JSClass* clasp)
-{
-  return clasp->flags & JSCLASS_IS_DOMIFACEANDPROTOJSCLASS;
-}
-
-inline bool
-IsDOMIfaceAndProtoClass(const js::Class* clasp)
-{
-  return IsDOMIfaceAndProtoClass(Jsvalify(clasp));
-}
-
-static_assert(DOM_OBJECT_SLOT == js::PROXY_PRIVATE_SLOT,
-              "js::PROXY_PRIVATE_SLOT doesn't match DOM_OBJECT_SLOT.  "
-              "Expect bad things");
-template <class T>
-inline T*
-UnwrapDOMObject(JSObject* obj)
-{
-  MOZ_ASSERT(IsDOMClass(js::GetObjectClass(obj)) || IsDOMProxy(obj),
-             "Don't pass non-DOM objects to this function");
-
-  JS::Value val = js::GetReservedSlot(obj, DOM_OBJECT_SLOT);
-  return static_cast<T*>(val.toPrivate());
-}
-
-inline const DOMClass*
-GetDOMClass(JSObject* obj)
-{
-  const js::Class* clasp = js::GetObjectClass(obj);
-  if (IsDOMClass(clasp)) {
-    return &DOMJSClass::FromJSClass(clasp)->mClass;
-  }
-
-  if (js::IsProxyClass(clasp)) {
-    js::BaseProxyHandler* handler = js::GetProxyHandler(obj);
-    if (handler->family() == ProxyFamily()) {
-      return &static_cast<DOMProxyHandler*>(handler)->mClass;
-    }
-  }
-
-  return nullptr;
-}
-
-inline nsISupports*
-UnwrapDOMObjectToISupports(JSObject* aObject)
-{
-  const DOMClass* clasp = GetDOMClass(aObject);
-  if (!clasp || !clasp->mDOMObjectIsISupports) {
-    return nullptr;
-  }
- 
-  return UnwrapDOMObject<nsISupports>(aObject);
-}
-
-inline bool
-IsDOMObject(JSObject* obj)
-{
-  const js::Class* clasp = js::GetObjectClass(obj);
-  return IsDOMClass(clasp) || IsDOMProxy(obj, clasp);
-}
-
-#define UNWRAP_OBJECT(Interface, cx, obj, value)                             \
-  mozilla::dom::UnwrapObject<mozilla::dom::prototypes::id::Interface,        \
-    mozilla::dom::Interface##Binding::NativeType>(cx, obj, value)
-
-// Some callers don't want to set an exception when unwrapping fails
-// (for example, overload resolution uses unwrapping to tell what sort
-// of thing it's looking at).
-// U must be something that a T* can be assigned to (e.g. T* or an nsRefPtr<T>).
-template <prototypes::ID PrototypeID, class T, typename U>
-MOZ_ALWAYS_INLINE nsresult
-UnwrapObject(JSContext* cx, JSObject* obj, U& value)
-{
-  /* First check to see whether we have a DOM object */
-  const DOMClass* domClass = GetDOMClass(obj);
-  if (!domClass) {
-    /* Maybe we have a security wrapper or outer window? */
-    if (!js::IsWrapper(obj)) {
-      /* Not a DOM object, not a wrapper, just bail */
-      return NS_ERROR_XPC_BAD_CONVERT_JS;
-    }
-
-    obj = js::CheckedUnwrap(obj, /* stopAtOuter = */ false);
-    if (!obj) {
-      return NS_ERROR_XPC_SECURITY_MANAGER_VETO;
-    }
-    MOZ_ASSERT(!js::IsWrapper(obj));
-    domClass = GetDOMClass(obj);
-    if (!domClass) {
-      /* We don't have a DOM object */
-      return NS_ERROR_XPC_BAD_CONVERT_JS;
-    }
-  }
-
-  /* This object is a DOM object.  Double-check that it is safely
-     castable to T by checking whether it claims to inherit from the
-     class identified by protoID. */
-  if (domClass->mInterfaceChain[PrototypeTraits<PrototypeID>::Depth] ==
-      PrototypeID) {
-    value = UnwrapDOMObject<T>(obj);
-    return NS_OK;
-  }
-
-  /* It's the wrong sort of DOM object */
-  return NS_ERROR_XPC_BAD_CONVERT_JS;
-}
-
-inline bool
-IsNotDateOrRegExp(JSContext* cx, JS::Handle<JSObject*> obj)
-{
-  MOZ_ASSERT(obj);
-  return !JS_ObjectIsDate(cx, obj) && !JS_ObjectIsRegExp(cx, obj);
-}
-
-MOZ_ALWAYS_INLINE bool
-IsArrayLike(JSContext* cx, JS::Handle<JSObject*> obj)
-{
-  return IsNotDateOrRegExp(cx, obj);
-}
-
-MOZ_ALWAYS_INLINE bool
-IsObjectValueConvertibleToDictionary(JSContext* cx,
-                                     JS::Handle<JS::Value> objVal)
-{
-  JS::Rooted<JSObject*> obj(cx, &objVal.toObject());
-  return IsNotDateOrRegExp(cx, obj);
-}
-
-MOZ_ALWAYS_INLINE bool
-IsConvertibleToDictionary(JSContext* cx, JS::Handle<JS::Value> val)
-{
-  return val.isNullOrUndefined() ||
-    (val.isObject() && IsObjectValueConvertibleToDictionary(cx, val));
-}
-
-MOZ_ALWAYS_INLINE bool
-IsConvertibleToCallbackInterface(JSContext* cx, JS::Handle<JSObject*> obj)
-{
-  return IsNotDateOrRegExp(cx, obj);
-}
-
-// The items in the protoAndIfaceArray are indexed by the prototypes::id::ID and
-// constructors::id::ID enums, in that order. The end of the prototype objects
-// should be the start of the interface objects.
-static_assert((size_t)constructors::id::_ID_Start ==
-              (size_t)prototypes::id::_ID_Count,
-              "Overlapping or discontiguous indexes.");
-const size_t kProtoAndIfaceCacheCount = constructors::id::_ID_Count;
-
-inline void
-AllocateProtoAndIfaceCache(JSObject* obj)
-{
-  MOZ_ASSERT(js::GetObjectClass(obj)->flags & JSCLASS_DOM_GLOBAL);
-  MOZ_ASSERT(js::GetReservedSlot(obj, DOM_PROTOTYPE_SLOT).isUndefined());
-
-  JS::Heap<JSObject*>* protoAndIfaceArray = new JS::Heap<JSObject*>[kProtoAndIfaceCacheCount];
-
-  js::SetReservedSlot(obj, DOM_PROTOTYPE_SLOT,
-                      JS::PrivateValue(protoAndIfaceArray));
-}
-
-inline void
-TraceProtoAndIfaceCache(JSTracer* trc, JSObject* obj)
-{
-  MOZ_ASSERT(js::GetObjectClass(obj)->flags & JSCLASS_DOM_GLOBAL);
-
-  if (!HasProtoAndIfaceArray(obj))
-    return;
-  JS::Heap<JSObject*>* protoAndIfaceArray = GetProtoAndIfaceArray(obj);
-  for (size_t i = 0; i < kProtoAndIfaceCacheCount; ++i) {
-    if (protoAndIfaceArray[i]) {
-      JS_CallHeapObjectTracer(trc, &protoAndIfaceArray[i], "protoAndIfaceArray[i]");
-    }
-  }
-}
-
-inline void
-DestroyProtoAndIfaceCache(JSObject* obj)
-{
-  MOZ_ASSERT(js::GetObjectClass(obj)->flags & JSCLASS_DOM_GLOBAL);
-
-  JS::Heap<JSObject*>* protoAndIfaceArray = GetProtoAndIfaceArray(obj);
-
-  delete [] protoAndIfaceArray;
-}
-
-/**
- * Add constants to an object.
- */
-bool
-DefineConstants(JSContext* cx, JS::Handle<JSObject*> obj,
-                const ConstantSpec* cs);
-
-struct JSNativeHolder
-{
-  JSNative mNative;
-  const NativePropertyHooks* mPropertyHooks;
-};
-
-struct NamedConstructor
-{
-  const char* mName;
-  const JSNativeHolder mHolder;
-  unsigned mNargs;
-};
-
-/*
- * Create a DOM interface object (if constructorClass is non-null) and/or a
- * DOM interface prototype object (if protoClass is non-null).
- *
- * global is used as the parent of the interface object and the interface
- *        prototype object
- * protoProto is the prototype to use for the interface prototype object.
- * interfaceProto is the prototype to use for the interface object.
- * protoClass is the JSClass to use for the interface prototype object.
- *            This is null if we should not create an interface prototype
- *            object.
- * protoCache a pointer to a JSObject pointer where we should cache the
- *            interface prototype object. This must be null if protoClass is and
- *            vice versa.
- * constructorClass is the JSClass to use for the interface object.
- *                  This is null if we should not create an interface object or
- *                  if it should be a function object.
- * constructor holds the JSNative to back the interface object which should be a
- *             Function, unless constructorClass is non-null in which case it is
- *             ignored. If this is null and constructorClass is also null then
- *             we should not create an interface object at all.
- * ctorNargs is the length of the constructor function; 0 if no constructor
- * constructorCache a pointer to a JSObject pointer where we should cache the
- *                  interface object. This must be null if both constructorClass
- *                  and constructor are null, and non-null otherwise.
- * domClass is the DOMClass of instance objects for this class.  This can be
- *          null if this is not a concrete proto.
- * properties contains the methods, attributes and constants to be defined on
- *            objects in any compartment.
- * chromeProperties contains the methods, attributes and constants to be defined
- *                  on objects in chrome compartments. This must be null if the
- *                  interface doesn't have any ChromeOnly properties or if the
- *                  object is being created in non-chrome compartment.
- * defineOnGlobal controls whether properties should be defined on the given
- *                global for the interface object (if any) and named
- *                constructors (if any) for this interface.  This can be
- *                false in situations where we want the properties to only
- *                appear on privileged Xrays but not on the unprivileged
- *                underlying global.
- *
- * At least one of protoClass, constructorClass or constructor should be
- * non-null. If constructorClass or constructor are non-null, the resulting
- * interface object will be defined on the given global with property name
- * |name|, which must also be non-null.
- */
-void
-CreateInterfaceObjects(JSContext* cx, JS::Handle<JSObject*> global,
-                       JS::Handle<JSObject*> protoProto,
-                       const JSClass* protoClass, JS::Heap<JSObject*>* protoCache,
-                       JS::Handle<JSObject*> interfaceProto,
-                       const JSClass* constructorClass, const JSNativeHolder* constructor,
-                       unsigned ctorNargs, const NamedConstructor* namedConstructors,
-                       JS::Heap<JSObject*>* constructorCache, const DOMClass* domClass,
-                       const NativeProperties* regularProperties,
-                       const NativeProperties* chromeOnlyProperties,
-                       const char* name, bool defineOnGlobal);
-
-/*
- * Define the unforgeable attributes on an object.
- */
-bool
-DefineUnforgeableAttributes(JSContext* cx, JS::Handle<JSObject*> obj,
-                            const Prefable<const JSPropertySpec>* props);
-
-bool
-DefineWebIDLBindingPropertiesOnXPCProto(JSContext* cx,
-                                        JS::Handle<JSObject*> proto,
-                                        const NativeProperties* properties);
-
-#ifdef _MSC_VER
-#define HAS_MEMBER_CHECK(_name)                                           \
-  template<typename V> static yes& Check(char (*)[(&V::_name == 0) + 1])
-#else
-#define HAS_MEMBER_CHECK(_name)                                           \
-  template<typename V> static yes& Check(char (*)[sizeof(&V::_name) + 1])
-#endif
-
-#define HAS_MEMBER(_name)                                                 \
-template<typename T>                                                      \
-class Has##_name##Member {                                                \
-  typedef char yes[1];                                                    \
-  typedef char no[2];                                                     \
-  HAS_MEMBER_CHECK(_name);                                                \
-  template<typename V> static no& Check(...);                             \
-                                                                          \
-public:                                                                   \
-  static bool const Value = sizeof(Check<T>(nullptr)) == sizeof(yes);     \
-};
-
-HAS_MEMBER(WrapObject)
-
-// HasWrapObject<T>::Value will be true if T has a WrapObject member but it's
-// not nsWrapperCache::WrapObject.
-template<typename T>
-struct HasWrapObject
-{
-private:
-  typedef char yes[1];
-  typedef char no[2];
-  typedef JSObject* (nsWrapperCache::*WrapObject)(JSContext*,
-                                                  JS::Handle<JSObject*>);
-  template<typename U, U> struct SFINAE;
-  template <typename V> static no& Check(SFINAE<WrapObject, &V::WrapObject>*);
-  template <typename V> static yes& Check(...);
-
-public:
-  static bool const Value = HasWrapObjectMember<T>::Value &&
-                            sizeof(Check<T>(nullptr)) == sizeof(yes);
-};
-
-#ifdef DEBUG
-template <class T, bool isISupports=IsBaseOf<nsISupports, T>::value>
-struct
-CheckWrapperCacheCast
-{
-  static bool Check()
-  {
-    return reinterpret_cast<uintptr_t>(
-      static_cast<nsWrapperCache*>(
-        reinterpret_cast<T*>(1))) == 1;
-  }
-};
-template <class T>
-struct
-CheckWrapperCacheCast<T, true>
-{
-  static bool Check()
-  {
-    return true;
-  }
-};
-#endif
-
-MOZ_ALWAYS_INLINE bool
-CouldBeDOMBinding(void*)
-{
-  return true;
-}
-
-MOZ_ALWAYS_INLINE bool
-CouldBeDOMBinding(nsWrapperCache* aCache)
-{
-  return aCache->IsDOMBinding();
-}
-
-// The DOM_OBJECT_SLOT_SOW slot contains a JS::ObjectValue which points to the
-// cached system object wrapper (SOW) or JS::UndefinedValue if this class
-// doesn't need SOWs.
-
-inline const JS::Value&
-GetSystemOnlyWrapperSlot(JSObject* obj)
-{
-  MOZ_ASSERT(IsDOMClass(js::GetObjectJSClass(obj)) &&
-             !(js::GetObjectJSClass(obj)->flags & JSCLASS_DOM_GLOBAL));
-  return js::GetReservedSlot(obj, DOM_OBJECT_SLOT_SOW);
-}
-inline void
-SetSystemOnlyWrapperSlot(JSObject* obj, const JS::Value& v)
-{
-  MOZ_ASSERT(IsDOMClass(js::GetObjectJSClass(obj)) &&
-             !(js::GetObjectJSClass(obj)->flags & JSCLASS_DOM_GLOBAL));
-  js::SetReservedSlot(obj, DOM_OBJECT_SLOT_SOW, v);
-}
-
-inline bool
-GetSameCompartmentWrapperForDOMBinding(JSObject*& obj)
-{
-  const js::Class* clasp = js::GetObjectClass(obj);
-  if (dom::IsDOMClass(clasp)) {
-    if (!(clasp->flags & JSCLASS_DOM_GLOBAL)) {
-      JS::Value v = GetSystemOnlyWrapperSlot(obj);
-      if (v.isObject()) {
-        obj = &v.toObject();
-      }
-    }
-    return true;
-  }
-  return IsDOMProxy(obj, clasp);
-}
-
-inline void
-SetSystemOnlyWrapper(JSObject* obj, nsWrapperCache* cache, JSObject& wrapper)
-{
-  SetSystemOnlyWrapperSlot(obj, JS::ObjectValue(wrapper));
-  cache->SetHasSystemOnlyWrapper();
-}
-
-// Make sure to wrap the given string value into the right compartment, as
-// needed.
-MOZ_ALWAYS_INLINE
-bool
-MaybeWrapStringValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
-{
-  MOZ_ASSERT(rval.isString());
-  JSString* str = rval.toString();
-  if (JS::GetGCThingZone(str) != js::GetContextZone(cx)) {
-    return JS_WrapValue(cx, rval.address());
-  }
-  return true;
-}
-
-// Make sure to wrap the given object value into the right compartment as
-// needed.  This will work correctly, but possibly slowly, on all objects.
-MOZ_ALWAYS_INLINE
-bool
-MaybeWrapObjectValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
-{
-  MOZ_ASSERT(rval.isObject());
-
-  JSObject* obj = &rval.toObject();
-  if (js::GetObjectCompartment(obj) != js::GetContextCompartment(cx)) {
-    return JS_WrapValue(cx, rval.address());
-  }
-
-  // We're same-compartment, but even then we might need to wrap
-  // objects specially.  Check for that.
-  if (GetSameCompartmentWrapperForDOMBinding(obj)) {
-    // We're a new-binding object, and "obj" now points to the right thing
-    rval.set(JS::ObjectValue(*obj));
-    return true;
-  }
-
-  // It's not a WebIDL object.  But it might be an XPConnect one, in which case
-  // we may need to outerize here, so make sure to call JS_WrapValue.
-  return JS_WrapValue(cx, rval.address());
-}
-
-// Like MaybeWrapObjectValue, but also allows null
-MOZ_ALWAYS_INLINE
-bool
-MaybeWrapObjectOrNullValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
-{
-  MOZ_ASSERT(rval.isObjectOrNull());
-  if (rval.isNull()) {
-    return true;
-  }
-  return MaybeWrapObjectValue(cx, rval);
-}
-
-// Wrapping for objects that are known to not be DOM or XPConnect objects
-MOZ_ALWAYS_INLINE
-bool
-MaybeWrapNonDOMObjectValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
-{
-  MOZ_ASSERT(rval.isObject());
-  MOZ_ASSERT(!GetDOMClass(&rval.toObject()));
-  MOZ_ASSERT(!(js::GetObjectClass(&rval.toObject())->flags &
-               JSCLASS_PRIVATE_IS_NSISUPPORTS));
-
-  JSObject* obj = &rval.toObject();
-  if (js::GetObjectCompartment(obj) == js::GetContextCompartment(cx)) {
-    return true;
-  }
-  return JS_WrapValue(cx, rval.address());
-}
-
-// Like MaybeWrapNonDOMObjectValue but allows null
-MOZ_ALWAYS_INLINE
-bool
-MaybeWrapNonDOMObjectOrNullValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
-{
-  MOZ_ASSERT(rval.isObjectOrNull());
-  if (rval.isNull()) {
-    return true;
-  }
-  return MaybeWrapNonDOMObjectValue(cx, rval);
-}
-
-// If rval is a gcthing and is not in the compartment of cx, wrap rval
-// into the compartment of cx (typically by replacing it with an Xray or
-// cross-compartment wrapper around the original object).
-MOZ_ALWAYS_INLINE bool
-MaybeWrapValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
-{
-  if (rval.isString()) {
-    return MaybeWrapStringValue(cx, rval);
-  }
-
-  if (!rval.isObject()) {
-    return true;
-  }
-
-  return MaybeWrapObjectValue(cx, rval);
-}
-
-static inline void
-WrapNewBindingForSameCompartment(JSContext* cx, JSObject* obj, void* value,
-                                 JS::MutableHandle<JS::Value> rval)
-{
-  rval.set(JS::ObjectValue(*obj));
-}
-
-static inline void
-WrapNewBindingForSameCompartment(JSContext* cx, JSObject* obj,
-                                 nsWrapperCache* value,
-                                 JS::MutableHandle<JS::Value> rval)
-{
-  if (value->HasSystemOnlyWrapper()) {
-    rval.set(GetSystemOnlyWrapperSlot(obj));
-    MOZ_ASSERT(rval.isObject());
-  } else {
-    rval.set(JS::ObjectValue(*obj));
-  }
-}
-
-// Create a JSObject wrapping "value", if there isn't one already, and store it
-// in rval.  "value" must be a concrete class that implements a
-// GetWrapperPreserveColor() which can return its existing wrapper, if any, and
-// a WrapObject() which will try to create a wrapper. Typically, this is done by
-// having "value" inherit from nsWrapperCache.
-template <class T>
-MOZ_ALWAYS_INLINE bool
-WrapNewBindingObject(JSContext* cx, JS::Handle<JSObject*> scope, T* value,
-                     JS::MutableHandle<JS::Value> rval)
-{
-  MOZ_ASSERT(value);
-  JSObject* obj = value->GetWrapperPreserveColor();
-  bool couldBeDOMBinding = CouldBeDOMBinding(value);
-  if (obj) {
-    JS::ExposeObjectToActiveJS(obj);
-  } else {
-    // Inline this here while we have non-dom objects in wrapper caches.
-    if (!couldBeDOMBinding) {
-      return false;
-    }
-
-    obj = value->WrapObject(cx, scope);
-    if (!obj) {
-      // At this point, obj is null, so just return false.
-      // Callers seem to be testing JS_IsExceptionPending(cx) to
-      // figure out whether WrapObject() threw.
-      return false;
-    }
-  }
-
-#ifdef DEBUG
-  const DOMClass* clasp = GetDOMClass(obj);
-  // clasp can be null if the cache contained a non-DOM object from a
-  // different compartment than scope.
-  if (clasp) {
-    // Some sanity asserts about our object.  Specifically:
-    // 1)  If our class claims we're nsISupports, we better be nsISupports
-    //     XXXbz ideally, we could assert that reinterpret_cast to nsISupports
-    //     does the right thing, but I don't see a way to do it.  :(
-    // 2)  If our class doesn't claim we're nsISupports we better be
-    //     reinterpret_castable to nsWrapperCache.
-    MOZ_ASSERT(clasp, "What happened here?");
-    MOZ_ASSERT_IF(clasp->mDOMObjectIsISupports, (IsBaseOf<nsISupports, T>::value));
-    MOZ_ASSERT(CheckWrapperCacheCast<T>::Check());
-  }
-
-  // When called via XrayWrapper, we end up here while running in the
-  // chrome compartment.  But the obj we have would be created in
-  // whatever the content compartment is.  So at this point we need to
-  // make sure it's correctly wrapped for the compartment of |scope|.
-  // cx should already be in the compartment of |scope| here.
-  MOZ_ASSERT(js::IsObjectInContextCompartment(scope, cx));
-#endif
-
-  bool sameCompartment =
-    js::GetObjectCompartment(obj) == js::GetContextCompartment(cx);
-  if (sameCompartment && couldBeDOMBinding) {
-    WrapNewBindingForSameCompartment(cx, obj, value, rval);
-    return true;
-  }
-
-  rval.set(JS::ObjectValue(*obj));
-  return JS_WrapValue(cx, rval.address());
-}
-
-// Create a JSObject wrapping "value", for cases when "value" is a
-// non-wrapper-cached object using WebIDL bindings.  "value" must implement a
-// WrapObject() method taking a JSContext and a scope.
-template <class T>
-inline bool
-WrapNewBindingNonWrapperCachedObject(JSContext* cx,
-                                     JS::Handle<JSObject*> scopeArg,
-                                     T* value,
-                                     JS::MutableHandle<JS::Value> rval)
-{
-  MOZ_ASSERT(value);
-  // We try to wrap in the compartment of the underlying object of "scope"
-  JS::Rooted<JSObject*> obj(cx);
-  {
-    // scope for the JSAutoCompartment so that we restore the compartment
-    // before we call JS_WrapValue.
-    Maybe<JSAutoCompartment> ac;
-    // Maybe<Handle> doesn't so much work, and in any case, adding
-    // more Maybe (one for a Rooted and one for a Handle) adds more
-    // code (and branches!) than just adding a single rooted.
-    JS::Rooted<JSObject*> scope(cx, scopeArg);
-    if (js::IsWrapper(scope)) {
-      scope = js::CheckedUnwrap(scope, /* stopAtOuter = */ false);
-      if (!scope)
-        return false;
-      ac.construct(cx, scope);
-    }
-
-    obj = value->WrapObject(cx, scope);
-  }
-
-  if (!obj) {
-    return false;
-  }
-
-  // We can end up here in all sorts of compartments, per above.  Make
-  // sure to JS_WrapValue!
-  rval.set(JS::ObjectValue(*obj));
-  return JS_WrapValue(cx, rval.address());
-}
-
-// Create a JSObject wrapping "value", for cases when "value" is a
-// non-wrapper-cached owned object using WebIDL bindings.  "value" must implement a
-// WrapObject() method taking a JSContext, a scope, and a boolean outparam that
-// is true if the JSObject took ownership
-template <class T>
-inline bool
-WrapNewBindingNonWrapperCachedOwnedObject(JSContext* cx,
-                                          JS::Handle<JSObject*> scopeArg,
-                                          nsAutoPtr<T>& value,
-                                          JS::MutableHandle<JS::Value> rval)
-{
-  // We do a runtime check on value, because otherwise we might in
-  // fact end up wrapping a null and invoking methods on it later.
-  if (!value) {
-    NS_RUNTIMEABORT("Don't try to wrap null objects");
-  }
-  // We try to wrap in the compartment of the underlying object of "scope"
-  JS::Rooted<JSObject*> obj(cx);
-  {
-    // scope for the JSAutoCompartment so that we restore the compartment
-    // before we call JS_WrapValue.
-    Maybe<JSAutoCompartment> ac;
-    // Maybe<Handle> doesn't so much work, and in any case, adding
-    // more Maybe (one for a Rooted and one for a Handle) adds more
-    // code (and branches!) than just adding a single rooted.
-    JS::Rooted<JSObject*> scope(cx, scopeArg);
-    if (js::IsWrapper(scope)) {
-      scope = js::CheckedUnwrap(scope, /* stopAtOuter = */ false);
-      if (!scope)
-        return false;
-      ac.construct(cx, scope);
-    }
-
-    bool tookOwnership = false;
-    obj = value->WrapObject(cx, scope, &tookOwnership);
-    MOZ_ASSERT_IF(obj, tookOwnership);
-    if (tookOwnership) {
-      value.forget();
-    }
-  }
-
-  if (!obj) {
-    return false;
-  }
-
-  // We can end up here in all sorts of compartments, per above.  Make
-  // sure to JS_WrapValue!
-  rval.set(JS::ObjectValue(*obj));
-  return JS_WrapValue(cx, rval.address());
-}
-
-// Helper for smart pointers (nsAutoPtr/nsRefPtr/nsCOMPtr).
-template <template <typename> class SmartPtr, typename T>
-inline bool
-WrapNewBindingNonWrapperCachedObject(JSContext* cx, JS::Handle<JSObject*> scope,
-                                     const SmartPtr<T>& value,
-                                     JS::MutableHandle<JS::Value> rval)
-{
-  return WrapNewBindingNonWrapperCachedObject(cx, scope, value.get(), rval);
-}
-
-// Only set allowNativeWrapper to false if you really know you need it, if in
-// doubt use true. Setting it to false disables security wrappers.
-bool
-NativeInterface2JSObjectAndThrowIfFailed(JSContext* aCx,
-                                         JS::Handle<JSObject*> aScope,
-                                         JS::Value* aRetval,
-                                         xpcObjectHelper& aHelper,
-                                         const nsIID* aIID,
-                                         bool aAllowNativeWrapper);
-
-/**
- * A method to handle new-binding wrap failure, by possibly falling back to
- * wrapping as a non-new-binding object.
- */
-template <class T>
-MOZ_ALWAYS_INLINE bool
-HandleNewBindingWrappingFailure(JSContext* cx, JS::Handle<JSObject*> scope,
-                                T* value, JS::MutableHandle<JS::Value> rval)
-{
-  if (JS_IsExceptionPending(cx)) {
-    return false;
-  }
-
-  qsObjectHelper helper(value, GetWrapperCache(value));
-  return NativeInterface2JSObjectAndThrowIfFailed(cx, scope, rval.address(),
-                                                  helper, nullptr, true);
-}
-
-// Helper for calling HandleNewBindingWrappingFailure with smart pointers
-// (nsAutoPtr/nsRefPtr/nsCOMPtr) or references.
-HAS_MEMBER(get)
-
-template <class T, bool isSmartPtr=HasgetMember<T>::Value>
-struct HandleNewBindingWrappingFailureHelper
-{
-  static inline bool Wrap(JSContext* cx, JS::Handle<JSObject*> scope,
-                          const T& value, JS::MutableHandle<JS::Value> rval)
-  {
-    return HandleNewBindingWrappingFailure(cx, scope, value.get(), rval);
-  }
-};
-
-template <class T>
-struct HandleNewBindingWrappingFailureHelper<T, false>
-{
-  static inline bool Wrap(JSContext* cx, JS::Handle<JSObject*> scope, T& value,
-                          JS::MutableHandle<JS::Value> rval)
-  {
-    return HandleNewBindingWrappingFailure(cx, scope, &value, rval);
-  }
-};
-
-template<class T>
-inline bool
-HandleNewBindingWrappingFailure(JSContext* cx, JS::Handle<JSObject*> scope,
-                                T& value, JS::MutableHandle<JS::Value> rval)
-{
-  return HandleNewBindingWrappingFailureHelper<T>::Wrap(cx, scope, value, rval);
-}
-
-template<bool Fatal>
-inline bool
-EnumValueNotFound(JSContext* cx, const jschar* chars, size_t length,
-                  const char* type, const char* sourceDescription)
-{
-  return false;
-}
-
-template<>
-inline bool
-EnumValueNotFound<false>(JSContext* cx, const jschar* chars, size_t length,
-                         const char* type, const char* sourceDescription)
-{
-  // TODO: Log a warning to the console.
-  return true;
-}
-
-template<>
-inline bool
-EnumValueNotFound<true>(JSContext* cx, const jschar* chars, size_t length,
-                        const char* type, const char* sourceDescription)
-{
-  NS_LossyConvertUTF16toASCII deflated(static_cast<const PRUnichar*>(chars),
-                                       length);
-  return ThrowErrorMessage(cx, MSG_INVALID_ENUM_VALUE, sourceDescription,
-                           deflated.get(), type);
-}
-
-
-template<bool InvalidValueFatal>
-inline int
-FindEnumStringIndex(JSContext* cx, JS::Value v, const EnumEntry* values,
-                    const char* type, const char* sourceDescription, bool* ok)
-{
-  // JS_StringEqualsAscii is slow as molasses, so don't use it here.
-  JSString* str = JS_ValueToString(cx, v);
-  if (!str) {
-    *ok = false;
-    return 0;
-  }
-  JS::Anchor<JSString*> anchor(str);
-  size_t length;
-  const jschar* chars = JS_GetStringCharsAndLength(cx, str, &length);
-  if (!chars) {
-    *ok = false;
-    return 0;
-  }
-  int i = 0;
-  for (const EnumEntry* value = values; value->value; ++value, ++i) {
-    if (length != value->length) {
-      continue;
-    }
-
-    bool equal = true;
-    const char* val = value->value;
-    for (size_t j = 0; j != length; ++j) {
-      if (unsigned(val[j]) != unsigned(chars[j])) {
-        equal = false;
-        break;
-      }
-    }
-
-    if (equal) {
-      *ok = true;
-      return i;
-    }
-  }
-
-  *ok = EnumValueNotFound<InvalidValueFatal>(cx, chars, length, type,
-                                             sourceDescription);
-  return -1;
-}
-
-inline nsWrapperCache*
-GetWrapperCache(const ParentObject& aParentObject)
-{
-  return aParentObject.mWrapperCache;
-}
-
-template<class T>
-inline T*
-GetParentPointer(T* aObject)
-{
-  return aObject;
-}
-
-inline nsISupports*
-GetParentPointer(const ParentObject& aObject)
-{
-  return aObject.mObject;
-}
-
-template<class T>
-inline void
-ClearWrapper(T* p, nsWrapperCache* cache)
-{
-  cache->ClearWrapper();
-}
-
-template<class T>
-inline void
-ClearWrapper(T* p, void*)
-{
-  nsWrapperCache* cache;
-  CallQueryInterface(p, &cache);
-  ClearWrapper(p, cache);
-}
-
-// Attempt to preserve the wrapper, if any, for a Paris DOM bindings object.
-// Return true if we successfully preserved the wrapper, or there is no wrapper
-// to preserve. In the latter case we don't need to preserve the wrapper, because
-// the object can only be obtained by JS once, or they cannot be meaningfully
-// owned from the native side.
-//
-// This operation will return false only for non-nsISupports cycle-collected
-// objects, because we cannot determine if they are wrappercached or not.
-bool
-TryPreserveWrapper(JSObject* obj);
-
-// Can only be called with the immediate prototype of the instance object. Can
-// only be called on the prototype of an object known to be a DOM instance.
-bool
-InstanceClassHasProtoAtDepth(JS::Handle<JSObject*> protoObject, uint32_t protoID,
-                             uint32_t depth);
-
-// Only set allowNativeWrapper to false if you really know you need it, if in
-// doubt use true. Setting it to false disables security wrappers.
-bool
-XPCOMObjectToJsval(JSContext* cx, JS::Handle<JSObject*> scope,
-                   xpcObjectHelper& helper, const nsIID* iid,
-                   bool allowNativeWrapper, JS::Value* rval);
-
-// Special-cased wrapping for variants
-bool
-VariantToJsval(JSContext* aCx, JS::Handle<JSObject*> aScope,
-               nsIVariant* aVariant, JS::Value* aRetval);
-
-// Wrap an object "p" which is not using WebIDL bindings yet.  This _will_
-// actually work on WebIDL binding objects that are wrappercached, but will be
-// much slower than WrapNewBindingObject.  "cache" must either be null or be the
-// nsWrapperCache for "p".
-template<class T>
-inline bool
-WrapObject(JSContext* cx, JS::Handle<JSObject*> scope, T* p,
-           nsWrapperCache* cache, const nsIID* iid,
-           JS::MutableHandle<JS::Value> rval)
-{
-  if (xpc_FastGetCachedWrapper(cache, scope, rval.address()))
-    return true;
-  qsObjectHelper helper(p, cache);
-  return XPCOMObjectToJsval(cx, scope, helper, iid, true, rval.address());
-}
-
-// A specialization of the above for nsIVariant, because that needs to
-// do something different.
-template<>
-inline bool
-WrapObject<nsIVariant>(JSContext* cx, JS::Handle<JSObject*> scope, nsIVariant* p,
-                       nsWrapperCache* cache, const nsIID* iid,
-                       JS::MutableHandle<JS::Value> rval)
-{
-  MOZ_ASSERT(iid);
-  MOZ_ASSERT(iid->Equals(NS_GET_IID(nsIVariant)));
-  return VariantToJsval(cx, scope, p, rval.address());
-}
-
-// Wrap an object "p" which is not using WebIDL bindings yet.  Just like the
-// variant that takes an nsWrapperCache above, but will try to auto-derive the
-// nsWrapperCache* from "p".
-template<class T>
-inline bool
-WrapObject(JSContext* cx, JS::Handle<JSObject*> scope, T* p, const nsIID* iid,
-           JS::MutableHandle<JS::Value> rval)
-{
-  return WrapObject(cx, scope, p, GetWrapperCache(p), iid, rval);
-}
-
-// Just like the WrapObject above, but without requiring you to pick which
-// interface you're wrapping as.  This should only be used for objects that have
-// classinfo, for which it doesn't matter what IID is used to wrap.
-template<class T>
-inline bool
-WrapObject(JSContext* cx, JS::Handle<JSObject*> scope, T* p,
-           JS::MutableHandle<JS::Value> rval)
-{
-  return WrapObject(cx, scope, p, NULL, rval);
-}
-
-// Helper to make it possible to wrap directly out of an nsCOMPtr
-template<class T>
-inline bool
-WrapObject(JSContext* cx, JS::Handle<JSObject*> scope, const nsCOMPtr<T>& p,
-           const nsIID* iid, JS::MutableHandle<JS::Value> rval)
-{
-  return WrapObject(cx, scope, p.get(), iid, rval);
-}
-
-// Helper to make it possible to wrap directly out of an nsCOMPtr
-template<class T>
-inline bool
-WrapObject(JSContext* cx, JS::Handle<JSObject*> scope, const nsCOMPtr<T>& p,
-           JS::MutableHandle<JS::Value> rval)
-{
-  return WrapObject(cx, scope, p, NULL, rval);
-}
-
-// Helper to make it possible to wrap directly out of an nsRefPtr
-template<class T>
-inline bool
-WrapObject(JSContext* cx, JS::Handle<JSObject*> scope, const nsRefPtr<T>& p,
-           const nsIID* iid, JS::MutableHandle<JS::Value> rval)
-{
-  return WrapObject(cx, scope, p.get(), iid, rval);
-}
-
-// Helper to make it possible to wrap directly out of an nsRefPtr
-template<class T>
-inline bool
-WrapObject(JSContext* cx, JS::Handle<JSObject*> scope, const nsRefPtr<T>& p,
-           JS::MutableHandle<JS::Value> rval)
-{
-  return WrapObject(cx, scope, p, NULL, rval);
-}
-
-// Specialization to make it easy to use WrapObject in codegen.
-template<>
-inline bool
-WrapObject<JSObject>(JSContext* cx, JS::Handle<JSObject*> scope, JSObject* p,
-                     JS::MutableHandle<JS::Value> rval)
-{
-  rval.set(JS::ObjectOrNullValue(p));
-  return true;
-}
-
-inline bool
-WrapObject(JSContext* cx, JS::Handle<JSObject*> scope, JSObject& p,
-           JS::MutableHandle<JS::Value> rval)
-{
-  rval.set(JS::ObjectValue(p));
-  return true;
-}
-
-// Given an object "p" that inherits from nsISupports, wrap it and return the
-// result.  Null is returned on wrapping failure.  This is somewhat similar to
-// WrapObject() above, but does NOT allow Xrays around the result, since we
-// don't want those for our parent object.
-template<typename T>
-static inline JSObject*
-WrapNativeISupportsParent(JSContext* cx, JS::Handle<JSObject*> scope, T* p,
-                          nsWrapperCache* cache)
-{
-  qsObjectHelper helper(ToSupports(p), cache);
-  JS::Rooted<JS::Value> v(cx);
-  return XPCOMObjectToJsval(cx, scope, helper, nullptr, false, v.address()) ?
-         JSVAL_TO_OBJECT(v) :
-         nullptr;
-}
-
-
-// Fallback for when our parent is not a WebIDL binding object.
-template<typename T, bool isISupports=IsBaseOf<nsISupports, T>::value>
-struct WrapNativeParentFallback
-{
-  static inline JSObject* Wrap(JSContext* cx, JS::Handle<JSObject*> scope,
-                               T* parent, nsWrapperCache* cache)
-  {
-    return nullptr;
-  }
-};
-
-// Fallback for when our parent is not a WebIDL binding object but _is_ an
-// nsISupports object.
-template<typename T >
-struct WrapNativeParentFallback<T, true >
-{
-  static inline JSObject* Wrap(JSContext* cx, JS::Handle<JSObject*> scope,
-                               T* parent, nsWrapperCache* cache)
-  {
-    return WrapNativeISupportsParent(cx, scope, parent, cache);
-  }
-};
-
-// Wrapping of our native parent, for cases when it's a WebIDL object (though
-// possibly preffed off).
-template<typename T, bool hasWrapObject=HasWrapObject<T>::Value >
-struct WrapNativeParentHelper
-{
-  static inline JSObject* Wrap(JSContext* cx, JS::Handle<JSObject*> scope,
-                               T* parent, nsWrapperCache* cache)
-  {
-    MOZ_ASSERT(cache);
-
-    JSObject* obj;
-    if ((obj = cache->GetWrapper())) {
-      return obj;
-    }
-
-    // Inline this here while we have non-dom objects in wrapper caches.
-    if (!CouldBeDOMBinding(parent)) {
-      obj = WrapNativeParentFallback<T>::Wrap(cx, scope, parent, cache);
-    } else {
-      obj = parent->WrapObject(cx, scope);
-    }
-
-    return obj;
-  }
-};
-
-// Wrapping of our native parent, for cases when it's not a WebIDL object.  In
-// this case it must be nsISupports.
-template<typename T>
-struct WrapNativeParentHelper<T, false >
-{
-  static inline JSObject* Wrap(JSContext* cx, JS::Handle<JSObject*> scope,
-                               T* parent, nsWrapperCache* cache)
-  {
-    JSObject* obj;
-    if (cache && (obj = cache->GetWrapper())) {
-#ifdef DEBUG
-      NS_ASSERTION(WrapNativeISupportsParent(cx, scope, parent, cache) == obj,
-                   "Unexpected object in nsWrapperCache");
-#endif
-      return obj;
-    }
-
-    return WrapNativeISupportsParent(cx, scope, parent, cache);
-  }
-};
-
-// Wrapping of our native parent.
-template<typename T>
-static inline JSObject*
-WrapNativeParent(JSContext* cx, JS::Handle<JSObject*> scope, T* p,
-                 nsWrapperCache* cache)
-{
-  if (!p) {
-    return scope;
-  }
-
-  return WrapNativeParentHelper<T>::Wrap(cx, scope, p, cache);
-}
-
-// Wrapping of our native parent, when we don't want to explicitly pass in
-// things like the nsWrapperCache for it.
-template<typename T>
-static inline JSObject*
-WrapNativeParent(JSContext* cx, JS::Handle<JSObject*> scope, const T& p)
-{
-  return WrapNativeParent(cx, scope, GetParentPointer(p), GetWrapperCache(p));
-}
-
-// A way to differentiate between nodes, which use the parent object
-// returned by native->GetParentObject(), and all other objects, which
-// just use the parent's global.
-static inline JSObject*
-GetRealParentObject(void* aParent, JSObject* aParentObject)
-{
-  return aParentObject ?
-    js::GetGlobalForObjectCrossCompartment(aParentObject) : nullptr;
-}
-
-static inline JSObject*
-GetRealParentObject(Element* aParent, JSObject* aParentObject)
-{
-  return aParentObject;
-}
-
-HAS_MEMBER(GetParentObject)
-
-template<typename T, bool WrapperCached=HasGetParentObjectMember<T>::Value>
-struct GetParentObject
-{
-  static JSObject* Get(JSContext* cx, JS::Handle<JSObject*> obj)
-  {
-    T* native = UnwrapDOMObject<T>(obj);
-    return
-      GetRealParentObject(native,
-                          WrapNativeParent(cx, obj, native->GetParentObject()));
-  }
-};
-
-template<typename T>
-struct GetParentObject<T, false>
-{
-  static JSObject* Get(JSContext* cx, JS::Handle<JSObject*> obj)
-  {
-    MOZ_CRASH();
-    return nullptr;
-  }
-};
-
-MOZ_ALWAYS_INLINE
-JSObject* GetJSObjectFromCallback(CallbackObject* callback)
-{
-  return callback->Callback();
-}
-
-MOZ_ALWAYS_INLINE
-JSObject* GetJSObjectFromCallback(void* noncallback)
-{
-  return nullptr;
-}
-
-template<typename T>
-static inline JSObject*
-WrapCallThisObject(JSContext* cx, JS::Handle<JSObject*> scope, const T& p)
-{
-  // Callbacks are nsISupports, so WrapNativeParent will just happily wrap them
-  // up as an nsISupports XPCWrappedNative... which is not at all what we want.
-  // So we need to special-case them.
-  JS::Rooted<JSObject*> obj(cx, GetJSObjectFromCallback(p));
-  if (!obj) {
-    // WrapNativeParent is a bit of a Swiss army knife that will
-    // wrap anything for us.
-    obj = WrapNativeParent(cx, scope, p);
-    if (!obj) {
-      return nullptr;
-    }
-  }
-
-  // But all that won't necessarily put things in the compartment of cx.
-  if (!JS_WrapObject(cx, obj.address())) {
-    return nullptr;
-  }
-
-  return obj;
-}
-
-// Helper for calling WrapNewBindingObject with smart pointers
-// (nsAutoPtr/nsRefPtr/nsCOMPtr) or references.
-template <class T, bool isSmartPtr=HasgetMember<T>::Value>
-struct WrapNewBindingObjectHelper
-{
-  static inline bool Wrap(JSContext* cx, JS::Handle<JSObject*> scope,
-                          const T& value, JS::MutableHandle<JS::Value> rval)
-  {
-    return WrapNewBindingObject(cx, scope, value.get(), rval);
-  }
-};
-
-template <class T>
-struct WrapNewBindingObjectHelper<T, false>
-{
-  static inline bool Wrap(JSContext* cx, JS::Handle<JSObject*> scope, T& value,
-                          JS::MutableHandle<JS::Value> rval)
-  {
-    return WrapNewBindingObject(cx, scope, &value, rval);
-  }
-};
-
-template<class T>
-inline bool
-WrapNewBindingObject(JSContext* cx, JS::Handle<JSObject*> scope, T& value,
-                     JS::MutableHandle<JS::Value> rval)
-{
-  return WrapNewBindingObjectHelper<T>::Wrap(cx, scope, value, rval);
-}
-
-template <class T>
-inline JSObject*
-GetCallbackFromCallbackObject(T* aObj)
-{
-  return aObj->Callback();
-}
-
-// Helper for getting the callback JSObject* of a smart ptr around a
-// CallbackObject or a reference to a CallbackObject or something like
-// that.
-template <class T, bool isSmartPtr=HasgetMember<T>::Value>
-struct GetCallbackFromCallbackObjectHelper
-{
-  static inline JSObject* Get(const T& aObj)
-  {
-    return GetCallbackFromCallbackObject(aObj.get());
-  }
-};
-
-template <class T>
-struct GetCallbackFromCallbackObjectHelper<T, false>
-{
-  static inline JSObject* Get(T& aObj)
-  {
-    return GetCallbackFromCallbackObject(&aObj);
-  }
-};
-
-template<class T>
-inline JSObject*
-GetCallbackFromCallbackObject(T& aObj)
-{
-  return GetCallbackFromCallbackObjectHelper<T>::Get(aObj);
-}
-
-static inline bool
-InternJSString(JSContext* cx, jsid& id, const char* chars)
-{
-  if (JSString *str = ::JS_InternString(cx, chars)) {
-    id = INTERNED_STRING_TO_JSID(cx, str);
-    return true;
-  }
-  return false;
-}
-
-// Spec needs a name property
-template <typename Spec>
-static bool
-InitIds(JSContext* cx, const Prefable<Spec>* prefableSpecs, jsid* ids)
-{
-  MOZ_ASSERT(prefableSpecs);
-  MOZ_ASSERT(prefableSpecs->specs);
-  do {
-    // We ignore whether the set of ids is enabled and just intern all the IDs,
-    // because this is only done once per application runtime.
-    Spec* spec = prefableSpecs->specs;
-    do {
-      if (!InternJSString(cx, *ids, spec->name)) {
-        return false;
-      }
-    } while (++ids, (++spec)->name);
-
-    // We ran out of ids for that pref.  Put a JSID_VOID in on the id
-    // corresponding to the list terminator for the pref.
-    *ids = JSID_VOID;
-    ++ids;
-  } while ((++prefableSpecs)->specs);
-
-  return true;
-}
-
-bool
-QueryInterface(JSContext* cx, unsigned argc, JS::Value* vp);
-
-template <class T>
-struct
-WantsQueryInterface
-{
-  static_assert(IsBaseOf<nsISupports, T>::value,
-                "QueryInterface can't work without an nsISupports.");
-  static bool Enabled(JSContext* aCx, JSObject* aGlobal)
-  {
-    return NS_IsMainThread() && IsChromeOrXBL(aCx, aGlobal);
-  }
-};
-
-bool
-ThrowingConstructor(JSContext* cx, unsigned argc, JS::Value* vp);
-
-// vp is allowed to be null; in that case no get will be attempted,
-// and *found will simply indicate whether the property exists.
-bool
-GetPropertyOnPrototype(JSContext* cx, JS::Handle<JSObject*> proxy,
-                       JS::Handle<jsid> id, bool* found,
-                       JS::Value* vp);
-
-bool
-HasPropertyOnPrototype(JSContext* cx, JS::Handle<JSObject*> proxy,
-                       JS::Handle<jsid> id);
-
-
-// Append the property names in "names" to "props". If
-// shadowPrototypeProperties is false then skip properties that are also
-// present on the proto chain of proxy.  If shadowPrototypeProperties is true,
-// then the "proxy" argument is ignored.
-bool
-AppendNamedPropertyIds(JSContext* cx, JS::Handle<JSObject*> proxy,
-                       nsTArray<nsString>& names,
-                       bool shadowPrototypeProperties, JS::AutoIdVector& props);
-
-// A struct that has the same layout as an nsDependentString but much
-// faster constructor and destructor behavior
-struct FakeDependentString {
-  FakeDependentString() :
-    mFlags(nsDependentString::F_TERMINATED)
-  {
-  }
-
-  void SetData(const nsDependentString::char_type* aData,
-               nsDependentString::size_type aLength) {
-    MOZ_ASSERT(mFlags == nsDependentString::F_TERMINATED);
-    mData = aData;
-    mLength = aLength;
-  }
-
-  void Truncate() {
-    mData = nsDependentString::char_traits::sEmptyBuffer;
-    mLength = 0;
-  }
-
-  void SetNull() {
-    Truncate();
-    mFlags |= nsDependentString::F_VOIDED;
-  }
-
-  const nsDependentString::char_type* Data() const
-  {
-    return mData;
-  }
-
-  nsDependentString::size_type Length() const
-  {
-    return mLength;
-  }
-
-  // If this ever changes, change the corresponding code in the
-  // Optional<nsAString> specialization as well.
-  const nsAString* ToAStringPtr() const {
-    return reinterpret_cast<const nsDependentString*>(this);
-  }
-
-  nsAString* ToAStringPtr() {
-    return reinterpret_cast<nsDependentString*>(this);
-  }
-
-  operator const nsAString& () const {
-    return *reinterpret_cast<const nsDependentString*>(this);
-  }
-
-private:
-  const nsDependentString::char_type* mData;
-  nsDependentString::size_type mLength;
-  uint32_t mFlags;
-
-  // A class to use for our static asserts to ensure our object layout
-  // matches that of nsDependentString.
-  class DependentStringAsserter;
-  friend class DependentStringAsserter;
-
-  class DepedentStringAsserter : public nsDependentString {
-  public:
-    static void StaticAsserts() {
-      static_assert(sizeof(FakeDependentString) == sizeof(nsDependentString),
-                    "Must have right object size");
-      static_assert(offsetof(FakeDependentString, mData) ==
-                      offsetof(DepedentStringAsserter, mData),
-                    "Offset of mData should match");
-      static_assert(offsetof(FakeDependentString, mLength) ==
-                      offsetof(DepedentStringAsserter, mLength),
-                    "Offset of mLength should match");
-      static_assert(offsetof(FakeDependentString, mFlags) ==
-                      offsetof(DepedentStringAsserter, mFlags),
-                    "Offset of mFlags should match");
-    }
-  };
-};
-
-enum StringificationBehavior {
-  eStringify,
-  eEmpty,
-  eNull
-};
-
-// pval must not be null and must point to a rooted JS::Value
-static inline bool
-ConvertJSValueToString(JSContext* cx, JS::Handle<JS::Value> v,
-                       JS::MutableHandle<JS::Value> pval,
-                       StringificationBehavior nullBehavior,
-                       StringificationBehavior undefinedBehavior,
-                       FakeDependentString& result)
-{
-  JSString *s;
-  if (v.isString()) {
-    s = v.toString();
-  } else {
-    StringificationBehavior behavior;
-    if (v.isNull()) {
-      behavior = nullBehavior;
-    } else if (v.isUndefined()) {
-      behavior = undefinedBehavior;
-    } else {
-      behavior = eStringify;
-    }
-
-    if (behavior != eStringify) {
-      if (behavior == eEmpty) {
-        result.Truncate();
-      } else {
-        result.SetNull();
-      }
-      return true;
-    }
-
-    s = JS_ValueToString(cx, v);
-    if (!s) {
-      return false;
-    }
-    pval.set(JS::StringValue(s));  // Root the new string.
-  }
-
-  size_t len;
-  const jschar *chars = JS_GetStringCharsZAndLength(cx, s, &len);
-  if (!chars) {
-    return false;
-  }
-
-  result.SetData(chars, len);
-  return true;
-}
-
-bool
-ConvertJSValueToByteString(JSContext* cx, JS::Handle<JS::Value> v,
-                           JS::MutableHandle<JS::Value> pval, bool nullable,
-                           nsACString& result);
-
-template<typename T>
-void DoTraceSequence(JSTracer* trc, FallibleTArray<T>& seq);
-template<typename T>
-void DoTraceSequence(JSTracer* trc, InfallibleTArray<T>& seq);
-
-// Class for simple sequence arguments, only used internally by codegen.
-template<typename T>
-class AutoSequence : public AutoFallibleTArray<T, 16>
-{
-public:
-  AutoSequence() : AutoFallibleTArray<T, 16>()
-  {}
-
-  // Allow converting to const sequences as needed
-  operator const Sequence<T>&() const {
-    return *reinterpret_cast<const Sequence<T>*>(this);
-  }
-};
-
-// Class used to trace sequences, with specializations for various
-// sequence types.
-template<typename T,
-         bool isDictionary=IsBaseOf<DictionaryBase, T>::value,
-         bool isTypedArray=IsBaseOf<AllTypedArraysBase, T>::value>
-class SequenceTracer
-{
-  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
-};
-
-// sequence<object> or sequence<object?>
-template<>
-class SequenceTracer<JSObject*, false, false>
-{
-  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
-
-public:
-  static void TraceSequence(JSTracer* trc, JSObject** objp, JSObject** end) {
-    for (; objp != end; ++objp) {
-      JS_CallObjectTracer(trc, objp, "sequence<object>");
-    }
-  }
-};
-
-// sequence<any>
-template<>
-class SequenceTracer<JS::Value, false, false>
-{
-  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
-
-public:
-  static void TraceSequence(JSTracer* trc, JS::Value* valp, JS::Value* end) {
-    for (; valp != end; ++valp) {
-      JS_CallValueTracer(trc, valp, "sequence<any>");
-    }
-  }
-};
-
-// sequence<sequence<T>>
-template<typename T>
-class SequenceTracer<Sequence<T>, false, false>
-{
-  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
-
-public:
-  static void TraceSequence(JSTracer* trc, Sequence<T>* seqp, Sequence<T>* end) {
-    for (; seqp != end; ++seqp) {
-      DoTraceSequence(trc, *seqp);
-    }
-  }
-};
-
-// sequence<sequence<T>> as return value
-template<typename T>
-class SequenceTracer<nsTArray<T>, false, false>
-{
-  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
-
-public:
-  static void TraceSequence(JSTracer* trc, nsTArray<T>* seqp, nsTArray<T>* end) {
-    for (; seqp != end; ++seqp) {
-      DoTraceSequence(trc, *seqp);
-    }
-  }
-};
-
-// sequence<someDictionary>
-template<typename T>
-class SequenceTracer<T, true, false>
-{
-  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
-
-public:
-  static void TraceSequence(JSTracer* trc, T* dictp, T* end) {
-    for (; dictp != end; ++dictp) {
-      dictp->TraceDictionary(trc);
-    }
-  }
-};
-
-// sequence<SomeTypedArray>
-template<typename T>
-class SequenceTracer<T, false, true>
-{
-  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
-
-public:
-  static void TraceSequence(JSTracer* trc, T* arrayp, T* end) {
-    for (; arrayp != end; ++arrayp) {
-      arrayp->TraceSelf(trc);
-    }
-  }
-};
-
-// sequence<T?> with T? being a Nullable<T>
-template<typename T>
-class SequenceTracer<Nullable<T>, false, false>
-{
-  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
-
-public:
-  static void TraceSequence(JSTracer* trc, Nullable<T>* seqp,
-                            Nullable<T>* end) {
-    for (; seqp != end; ++seqp) {
-      if (!seqp->IsNull()) {
-        // Pretend like we actually have a length-one sequence here so
-        // we can do template instantiation correctly for T.
-        T& val = seqp->Value();
-        T* ptr = &val;
-        SequenceTracer<T>::TraceSequence(trc, ptr, ptr+1);
-      }
-    }
-  }
-};
-
-template<typename T>
-void DoTraceSequence(JSTracer* trc, FallibleTArray<T>& seq)
-{
-  SequenceTracer<T>::TraceSequence(trc, seq.Elements(),
-                                   seq.Elements() + seq.Length());
-}
-
-template<typename T>
-void DoTraceSequence(JSTracer* trc, InfallibleTArray<T>& seq)
-{
-  SequenceTracer<T>::TraceSequence(trc, seq.Elements(),
-                                   seq.Elements() + seq.Length());
-}
-
-// Rooter class for sequences; this is what we mostly use in the codegen
-template<typename T>
-class MOZ_STACK_CLASS SequenceRooter : private JS::CustomAutoRooter
-{
-public:
-  SequenceRooter(JSContext *aCx, FallibleTArray<T>* aSequence
-                 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
-    : JS::CustomAutoRooter(aCx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT),
-      mFallibleArray(aSequence),
-      mSequenceType(eFallibleArray)
-  {
-  }
-
-  SequenceRooter(JSContext *aCx, InfallibleTArray<T>* aSequence
-                 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
-    : JS::CustomAutoRooter(aCx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT),
-      mInfallibleArray(aSequence),
-      mSequenceType(eInfallibleArray)
-  {
-  }
-
-  SequenceRooter(JSContext *aCx, Nullable<nsTArray<T> >* aSequence
-                 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
-    : JS::CustomAutoRooter(aCx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT),
-      mNullableArray(aSequence),
-      mSequenceType(eNullableArray)
-  {
-  }
-
- private:
-  enum SequenceType {
-    eInfallibleArray,
-    eFallibleArray,
-    eNullableArray
-  };
-
-  virtual void trace(JSTracer *trc) MOZ_OVERRIDE
-  {
-    if (mSequenceType == eFallibleArray) {
-      DoTraceSequence(trc, *mFallibleArray);
-    } else if (mSequenceType == eInfallibleArray) {
-      DoTraceSequence(trc, *mInfallibleArray);
-    } else {
-      MOZ_ASSERT(mSequenceType == eNullableArray);
-      if (!mNullableArray->IsNull()) {
-        DoTraceSequence(trc, mNullableArray->Value());
-      }
-    }
-  }
-
-  union {
-    InfallibleTArray<T>* mInfallibleArray;
-    FallibleTArray<T>* mFallibleArray;
-    Nullable<nsTArray<T> >* mNullableArray;
-  };
-
-  SequenceType mSequenceType;
-};
-
 template<typename T>
 class MOZ_STACK_CLASS RootedDictionary : public T,
                                          private JS::CustomAutoRooter
 {
 public:
   RootedDictionary(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) :
     T(),
     JS::CustomAutoRooter(cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT)
@@ -1787,502 +45,12 @@ public:
   virtual void trace(JSTracer *trc) MOZ_OVERRIDE
   {
     if (!this->IsNull()) {
       this->Value().TraceDictionary(trc);
     }
   }
 };
 
-template<typename T>
-class MOZ_STACK_CLASS RootedUnion : public T,
-                                    private JS::CustomAutoRooter
-{
-public:
-  RootedUnion(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) :
-    T(),
-    JS::CustomAutoRooter(cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT)
-  {
-  }
-
-  virtual void trace(JSTracer *trc) MOZ_OVERRIDE
-  {
-    this->TraceUnion(trc);
-  }
-};
-
-template<typename T>
-class MOZ_STACK_CLASS NullableRootedUnion : public Nullable<T>,
-                                            private JS::CustomAutoRooter
-{
-public:
-  NullableRootedUnion(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) :
-    Nullable<T>(),
-    JS::CustomAutoRooter(cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT)
-  {
-  }
-
-  virtual void trace(JSTracer *trc) MOZ_OVERRIDE
-  {
-    if (!this->IsNull()) {
-      this->Value().TraceUnion(trc);
-    }
-  }
-};
-
-inline bool
-IdEquals(jsid id, const char* string)
-{
-  return JSID_IS_STRING(id) &&
-         JS_FlatStringEqualsAscii(JSID_TO_FLAT_STRING(id), string);
-}
-
-inline bool
-AddStringToIDVector(JSContext* cx, JS::AutoIdVector& vector, const char* name)
-{
-  return vector.growBy(1) &&
-         InternJSString(cx, vector[vector.length() - 1], name);
-}
-
-// Implementation of the bits that XrayWrapper needs
-
-/**
- * This resolves indexed or named properties of obj.
- *
- * wrapper is the Xray JS object.
- * obj is the target object of the Xray, a binding's instance object or a
- *     interface or interface prototype object.
- */
-bool
-XrayResolveOwnProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
-                       JS::Handle<JSObject*> obj,
-                       JS::Handle<jsid> id,
-                       JS::MutableHandle<JSPropertyDescriptor> desc, unsigned flags);
-
-/**
- * This resolves operations, attributes and constants of the interfaces for obj.
- *
- * wrapper is the Xray JS object.
- * obj is the target object of the Xray, a binding's instance object or a
- *     interface or interface prototype object.
- */
-bool
-XrayResolveNativeProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
-                          JS::Handle<JSObject*> obj,
-                          JS::Handle<jsid> id, JS::MutableHandle<JSPropertyDescriptor> desc);
-
-/**
- * Define a property on obj through an Xray wrapper.
- *
- * wrapper is the Xray JS object.
- * obj is the target object of the Xray, a binding's instance object or a
- *     interface or interface prototype object.
- * defined will be set to true if a property was set as a result of this call.
- */
-bool
-XrayDefineProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
-                   JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
-                   JS::MutableHandle<JSPropertyDescriptor> desc, bool* defined);
-
-/**
- * This enumerates indexed or named properties of obj and operations, attributes
- * and constants of the interfaces for obj.
- *
- * wrapper is the Xray JS object.
- * obj is the target object of the Xray, a binding's instance object or a
- *     interface or interface prototype object.
- * flags are JSITER_* flags.
- */
-bool
-XrayEnumerateProperties(JSContext* cx, JS::Handle<JSObject*> wrapper,
-                        JS::Handle<JSObject*> obj,
-                        unsigned flags, JS::AutoIdVector& props);
-
-extern NativePropertyHooks sWorkerNativePropertyHooks;
-
-// We use one constructor JSNative to represent all DOM interface objects (so
-// we can easily detect when we need to wrap them in an Xray wrapper). We store
-// the real JSNative in the mNative member of a JSNativeHolder in the
-// CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT slot of the JSFunction object for a
-// specific interface object. We also store the NativeProperties in the
-// JSNativeHolder. The CONSTRUCTOR_XRAY_EXPANDO_SLOT is used to store the
-// expando chain of the Xray for the interface object.
-// Note that some interface objects are not yet a JSFunction but a normal
-// JSObject with a DOMJSClass, those do not use these slots.
-
-enum {
-  CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT = 0,
-  CONSTRUCTOR_XRAY_EXPANDO_SLOT
-};
-
-bool
-Constructor(JSContext* cx, unsigned argc, JS::Value* vp);
-
-inline bool
-UseDOMXray(JSObject* obj)
-{
-  const js::Class* clasp = js::GetObjectClass(obj);
-  return IsDOMClass(clasp) ||
-         IsDOMProxy(obj, clasp) ||
-         JS_IsNativeFunction(obj, Constructor) ||
-         IsDOMIfaceAndProtoClass(clasp);
-}
-
-#ifdef DEBUG
-inline bool
-HasConstructor(JSObject* obj)
-{
-  return JS_IsNativeFunction(obj, Constructor) ||
-         js::GetObjectClass(obj)->construct;
-}
- #endif
- 
-// Transfer reference in ptr to smartPtr.
-template<class T>
-inline void
-Take(nsRefPtr<T>& smartPtr, T* ptr)
-{
-  smartPtr = dont_AddRef(ptr);
-}
-
-// Transfer ownership of ptr to smartPtr.
-template<class T>
-inline void
-Take(nsAutoPtr<T>& smartPtr, T* ptr)
-{
-  smartPtr = ptr;
-}
-
-inline void
-MustInheritFromNonRefcountedDOMObject(NonRefcountedDOMObject*)
-{
-}
-
-// Set the chain of expando objects for various consumers of the given object.
-// For Paris Bindings only. See the relevant infrastructure in XrayWrapper.cpp.
-JSObject* GetXrayExpandoChain(JSObject *obj);
-void SetXrayExpandoChain(JSObject *obj, JSObject *chain);
-
-/**
- * This creates a JSString containing the value that the toString function for
- * obj should create according to the WebIDL specification, ignoring any
- * modifications by script. The value is prefixed with pre and postfixed with
- * post, unless this is called for an object that has a stringifier. It is
- * specifically for use by Xray code.
- *
- * wrapper is the Xray JS object.
- * obj is the target object of the Xray, a binding's instance object or a
- *     interface or interface prototype object.
- * pre is a string that should be prefixed to the value.
- * post is a string that should be prefixed to the value.
- * v contains the JSString for the value if the function returns true.
- */
-bool
-NativeToString(JSContext* cx, JS::Handle<JSObject*> wrapper,
-               JS::Handle<JSObject*> obj, const char* pre,
-               const char* post, JS::Value* v);
-
-HAS_MEMBER(JSBindingFinalized)
-
-template<class T, bool hasCallback=HasJSBindingFinalizedMember<T>::Value>
-struct JSBindingFinalized
-{
-  static void Finalized(T* self)
-  {
-  }
-};
-
-template<class T>
-struct JSBindingFinalized<T, true>
-{
-  static void Finalized(T* self)
-  {
-    self->JSBindingFinalized();
-  }
-};
-
-// Helpers for creating a const version of a type.
-template<typename T>
-const T& Constify(T& arg)
-{
-  return arg;
-}
-
-// Helper for turning (Owning)NonNull<T> into T&
-template<typename T>
-T& NonNullHelper(T& aArg)
-{
-  return aArg;
-}
-
-template<typename T>
-T& NonNullHelper(NonNull<T>& aArg)
-{
-  return aArg;
-}
-
-template<typename T>
-const T& NonNullHelper(const NonNull<T>& aArg)
-{
-  return aArg;
-}
-
-template<typename T>
-T& NonNullHelper(OwningNonNull<T>& aArg)
-{
-  return aArg;
-}
-
-template<typename T>
-const T& NonNullHelper(const OwningNonNull<T>& aArg)
-{
-  return aArg;
-}
-
-// Reparent the wrapper of aObj to whatever its native now thinks its
-// parent should be.
-nsresult
-ReparentWrapper(JSContext* aCx, JS::HandleObject aObj);
-
-/**
- * Used to implement the hasInstance hook of an interface object.
- *
- * instance should not be a security wrapper.
- */
-bool
-InterfaceHasInstance(JSContext* cx, JS::Handle<JSObject*> obj,
-                     JS::Handle<JSObject*> instance,
-                     bool* bp);
-bool
-InterfaceHasInstance(JSContext* cx, JS::Handle<JSObject*> obj, JS::MutableHandle<JS::Value> vp,
-                     bool* bp);
-bool
-InterfaceHasInstance(JSContext* cx, int prototypeID, int depth,
-                     JS::Handle<JSObject*> instance,
-                     bool* bp);
-
-// Helper for lenient getters/setters to report to console.  If this
-// returns false, we couldn't even get a global.
-bool
-ReportLenientThisUnwrappingFailure(JSContext* cx, JS::Handle<JSObject*> obj);
-
-inline JSObject*
-GetUnforgeableHolder(JSObject* aGlobal, prototypes::ID aId)
-{
-  JS::Heap<JSObject*>* protoAndIfaceArray = GetProtoAndIfaceArray(aGlobal);
-  JSObject* interfaceProto = protoAndIfaceArray[aId];
-  return &js::GetReservedSlot(interfaceProto,
-                              DOM_INTERFACE_PROTO_SLOTS_BASE).toObject();
-}
-
-// Given a JSObject* that represents the chrome side of a JS-implemented WebIDL
-// interface, get the nsPIDOMWindow corresponding to the content side, if any.
-// A false return means an exception was thrown.
-bool
-GetWindowForJSImplementedObject(JSContext* cx, JS::Handle<JSObject*> obj,
-                                nsPIDOMWindow** window);
-
-already_AddRefed<nsPIDOMWindow>
-ConstructJSImplementation(JSContext* aCx, const char* aContractId,
-                          const GlobalObject& aGlobal,
-                          JS::MutableHandle<JSObject*> aObject,
-                          ErrorResult& aRv);
-
-/**
- * Convert an nsCString to jsval, returning true on success.
- * These functions are intended for ByteString implementations.
- * As such, the string is not UTF-8 encoded.  Any UTF8 strings passed to these
- * methods will be mangled.
- */
-bool NonVoidByteStringToJsval(JSContext *cx, const nsACString &str,
-                              JS::MutableHandle<JS::Value> rval);
-inline bool ByteStringToJsval(JSContext *cx, const nsACString &str,
-                              JS::MutableHandle<JS::Value> rval)
-{
-    if (str.IsVoid()) {
-        rval.setNull();
-        return true;
-    }
-    return NonVoidByteStringToJsval(cx, str, rval);
-}
-
-template<class T, bool isISupports=IsBaseOf<nsISupports, T>::value>
-struct PreserveWrapperHelper
-{
-  static void PreserveWrapper(T* aObject)
-  {
-    aObject->PreserveWrapper(aObject, NS_CYCLE_COLLECTION_PARTICIPANT(T));
-  }
-};
-
-template<class T>
-struct PreserveWrapperHelper<T, true>
-{
-  static void PreserveWrapper(T* aObject)
-  {
-    aObject->PreserveWrapper(reinterpret_cast<nsISupports*>(aObject));
-  }
-};
-
-template<class T>
-void PreserveWrapper(T* aObject)
-{
-  PreserveWrapperHelper<T>::PreserveWrapper(aObject);
-}
-
-template<class T, bool isISupports=IsBaseOf<nsISupports, T>::value>
-struct CastingAssertions
-{
-  static bool ToSupportsIsCorrect(T*)
-  {
-    return true;
-  }
-  static bool ToSupportsIsOnPrimaryInheritanceChain(T*, nsWrapperCache*)
-  {
-    return true;
-  }
-};
-
-template<class T>
-struct CastingAssertions<T, true>
-{
-  static bool ToSupportsIsCorrect(T* aObject)
-  {
-    return ToSupports(aObject) ==  reinterpret_cast<nsISupports*>(aObject);
-  }
-  static bool ToSupportsIsOnPrimaryInheritanceChain(T* aObject,
-                                                    nsWrapperCache* aCache)
-  {
-    return reinterpret_cast<void*>(aObject) != aCache;
-  }
-};
-
-template<class T>
-bool
-ToSupportsIsCorrect(T* aObject)
-{
-  return CastingAssertions<T>::ToSupportsIsCorrect(aObject);
-}
-
-template<class T>
-bool
-ToSupportsIsOnPrimaryInheritanceChain(T* aObject, nsWrapperCache* aCache)
-{
-  return CastingAssertions<T>::ToSupportsIsOnPrimaryInheritanceChain(aObject,
-                                                                     aCache);
-}
-
-template<class T, template <typename> class SmartPtr,
-         bool isISupports=IsBaseOf<nsISupports, T>::value>
-class DeferredFinalizer
-{
-  typedef nsTArray<SmartPtr<T> > SmartPtrArray;
-
-  static void*
-  AppendDeferredFinalizePointer(void* aData, void* aObject)
-  {
-    SmartPtrArray* pointers = static_cast<SmartPtrArray*>(aData);
-    if (!pointers) {
-      pointers = new SmartPtrArray();
-    }
-
-    T* self = static_cast<T*>(aObject);
-
-    SmartPtr<T>* defer = pointers->AppendElement();
-    Take(*defer, self);
-    return pointers;
-  }
-  static bool
-  DeferredFinalize(uint32_t aSlice, void* aData)
-  {
-    MOZ_ASSERT(aSlice > 0, "nonsensical/useless call with aSlice == 0");
-    SmartPtrArray* pointers = static_cast<SmartPtrArray*>(aData);
-    uint32_t oldLen = pointers->Length();
-    if (oldLen < aSlice) {
-      aSlice = oldLen;
-    }
-    uint32_t newLen = oldLen - aSlice;
-    pointers->RemoveElementsAt(newLen, aSlice);
-    if (newLen == 0) {
-      delete pointers;
-      return true;
-    }
-    return false;
-  }
-
-public:
-  static void
-  AddForDeferredFinalization(T* aObject)
-  {
-    cyclecollector::DeferredFinalize(AppendDeferredFinalizePointer,
-                                     DeferredFinalize, aObject);
-  }
-};
-
-template<class T, template <typename> class SmartPtr>
-class DeferredFinalizer<T, SmartPtr, true>
-{
-public:
-  static void
-  AddForDeferredFinalization(T* aObject)
-  {
-    cyclecollector::DeferredFinalize(reinterpret_cast<nsISupports*>(aObject));
-  }
-};
-
-template<class T, template <typename> class SmartPtr>
-static void
-AddForDeferredFinalization(T* aObject)
-{
-  DeferredFinalizer<T, SmartPtr>::AddForDeferredFinalization(aObject);
-}
-
-// This returns T's CC participant if it participates in CC or null if it
-// doesn't. This also returns null for classes that don't inherit from
-// nsISupports (QI should be used to get the participant for those).
-template<class T, bool isISupports=IsBaseOf<nsISupports, T>::value>
-class GetCCParticipant
-{
-  // Helper for GetCCParticipant for classes that participate in CC.
-  template<class U>
-  static MOZ_CONSTEXPR nsCycleCollectionParticipant*
-  GetHelper(int, typename U::NS_CYCLE_COLLECTION_INNERCLASS* dummy=nullptr)
-  {
-    return T::NS_CYCLE_COLLECTION_INNERCLASS::GetParticipant();
-  }
-  // Helper for GetCCParticipant for classes that don't participate in CC.
-  template<class U>
-  static MOZ_CONSTEXPR nsCycleCollectionParticipant*
-  GetHelper(double)
-  {
-    return nullptr;
-  }
-
-public:
-  static MOZ_CONSTEXPR nsCycleCollectionParticipant*
-  Get()
-  {
-    // Passing int() here will try to call the GetHelper that takes an int as
-    // its firt argument. If T doesn't participate in CC then substitution for
-    // the second argument (with a default value) will fail and because of
-    // SFINAE the next best match (the variant taking a double) will be called.
-    return GetHelper<T>(int());
-  }
-};
-
-template<class T>
-class GetCCParticipant<T, true>
-{
-public:
-  static MOZ_CONSTEXPR nsCycleCollectionParticipant*
-  Get()
-  {
-    return nullptr;
-  }
-};
-
-bool
-ThreadsafeCheckIsChrome(JSContext* aCx, JSObject* aObj);
-
 } // namespace dom
 } // namespace mozilla
 
-#endif /* mozilla_dom_BindingUtils_h__ */
+#endif /* mozilla_dom_RootedDictionary_h__ */
--- a/dom/bindings/moz.build
+++ b/dom/bindings/moz.build
@@ -22,16 +22,17 @@ EXPORTS.mozilla.dom += [
     'Date.h',
     'Errors.msg',
     'Exceptions.h',
     'JSSlots.h',
     'NonRefcountedDOMObject.h',
     'Nullable.h',
     'OwningNonNull.h',
     'PrimitiveConversions.h',
+    'RootedDictionary.h',
     'TypedArray.h',
     'UnionMember.h',
 ]
 
 FAIL_ON_WARNINGS = True
 
 LIBXUL_LIBRARY = True
 
--- a/dom/bindings/parser/WebIDL.py
+++ b/dom/bindings/parser/WebIDL.py
@@ -518,16 +518,17 @@ class IDLInterface(IDLObjectWithScope):
         # self.interfacesBasedOnSelf is the set of interfaces that inherit from
         # self or have self as a consequential interface, including self itself.
         # Used for distinguishability checking.
         self.interfacesBasedOnSelf = set([self])
         # self.interfacesImplementingSelf is the set of interfaces that directly
         # have self as a consequential interface
         self.interfacesImplementingSelf = set()
         self._hasChildInterfaces = False
+        self._isOnGlobalProtoChain = False
 
         IDLObjectWithScope.__init__(self, location, parentScope, name)
 
         if not isPartial:
             self.setNonPartial(location, parent, members)
         else:
             # Just remember our members for now
             self.members = members
@@ -581,16 +582,25 @@ class IDLInterface(IDLObjectWithScope):
 
         assert iter(self.members)
 
         if self.parent:
             self.parent.finish(scope)
 
             self.parent._hasChildInterfaces = True
 
+            # Interfaces with [Global] must not have anything inherit from them
+            if self.parent.getExtendedAttribute("Global"):
+                # Note: This is not a self.parent.isOnGlobalProtoChain() check
+                # because ancestors of a [Global] interface can have other
+                # descendants.
+                raise WebIDLError("[Global] interface has another interface "
+                                  "inheriting from it",
+                                  [self.location, self.parent.location])
+
             # Callbacks must not inherit from non-callbacks or inherit from
             # anything that has consequential interfaces.
             # XXXbz Can non-callbacks inherit from callbacks?  Spec issue pending.
             # XXXbz Can callbacks have consequential interfaces?  Spec issue pending
             if self.isCallback():
                 if not self.parent.isCallback():
                     raise WebIDLError("Callback interface %s inheriting from "
                                       "non-callback interface %s" %
@@ -736,16 +746,41 @@ class IDLInterface(IDLObjectWithScope):
             if memberType in specialMembersSeen:
                 raise WebIDLError("Multiple " + memberType + " on %s" % (self),
                                    [self.location,
                                     specialMembersSeen[memberType].location,
                                     member.location])
 
             specialMembersSeen[memberType] = member
 
+        if self._isOnGlobalProtoChain:
+            # Make sure we have no named setters, creators, or deleters
+            for memberType in ["setter", "creator", "deleter"]:
+                memberId = "named " + memberType + "s"
+                if memberId in specialMembersSeen:
+                    raise WebIDLError("Interface with [Global] has a named %s" %
+                                      memberType,
+                                      [self.location,
+                                       specialMembersSeen[memberId].location])
+            # Make sure we're not [OverrideBuiltins]
+            if self.getExtendedAttribute("OverrideBuiltins"):
+                raise WebIDLError("Interface with [Global] also has "
+                                  "[OverrideBuiltins]",
+                                  [self.location])
+            # Mark all of our ancestors as being on the global's proto chain too
+            parent = self.parent
+            while parent:
+                # Must not inherit from an interface with [OverrideBuiltins]
+                if parent.getExtendedAttribute("OverrideBuiltins"):
+                    raise WebIDLError("Interface with [Global] inherits from "
+                                      "interface with [OverrideBuiltins]",
+                                      [self.location, parent.location])
+                parent._isOnGlobalProtoChain = True
+                parent = parent.parent
+
     def validate(self):
         for member in self.members:
             member.validate()
 
             # Check that PutForwards refers to another attribute and that no
             # cycles exist in forwarded assignments.
             if member.isAttr():
                 iface = self
@@ -919,16 +954,21 @@ class IDLInterface(IDLObjectWithScope):
             elif (identifier == "ArrayClass"):
                 if not attr.noArguments():
                     raise WebIDLError("[ArrayClass] must take no arguments",
                                       [attr.location])
                 if self.parent:
                     raise WebIDLError("[ArrayClass] must not be specified on "
                                       "an interface with inherited interfaces",
                                       [attr.location, self.location])
+            elif identifier == "Global":
+                if not attr.noArguments():
+                    raise WebIDLError("[Global] must take no arguments",
+                                      [attr.location])
+                self._isOnGlobalProtoChain = True
             elif (identifier == "PrefControlled" or
                   identifier == "NeedNewResolve" or
                   identifier == "OverrideBuiltins" or
                   identifier == "ChromeOnly"):
                 # Known extended attributes that do not take values
                 if not attr.noArguments():
                     raise WebIDLError("[%s] must take no arguments" % identifier,
                                       [attr.location])
@@ -1037,16 +1077,19 @@ class IDLInterface(IDLObjectWithScope):
         assert len(naviProp) == 1
         assert isinstance(naviProp, list)
         assert len(naviProp[0]) != 0
         return naviProp[0]
 
     def hasChildInterfaces(self):
         return self._hasChildInterfaces
 
+    def isOnGlobalProtoChain(self):
+        return self._isOnGlobalProtoChain
+
     def _getDependentObjects(self):
         deps = set(self.members)
         deps.union(self.implementedInterfaces)
         if self.parent:
             deps.add(self.parent)
         return deps
 
 class IDLDictionary(IDLObjectWithScope):
@@ -2453,16 +2496,17 @@ class IDLNullValue(IDLObject):
     def __init__(self, location):
         IDLObject.__init__(self, location)
         self.type = None
         self.value = None
 
     def coerceToType(self, type, location):
         if (not isinstance(type, IDLNullableType) and
             not (type.isUnion() and type.hasNullableType) and
+            not (type.isUnion() and type.hasDictionaryType) and
             not type.isDictionary() and
             not type.isAny()):
             raise WebIDLError("Cannot coerce null value to type %s." % type,
                               [location])
 
         nullValue = IDLNullValue(self.location)
         nullValue.type = type
         return nullValue
@@ -2792,17 +2836,19 @@ class IDLArgument(IDLObjectWithIdentifie
 
         if not self.type.isComplete():
             type = self.type.complete(scope)
             assert not isinstance(type, IDLUnresolvedType)
             assert not isinstance(type, IDLTypedefType)
             assert not isinstance(type.name, IDLUnresolvedIdentifier)
             self.type = type
 
-        if self.type.isDictionary() and self.optional and not self.defaultValue:
+        if ((self.type.isDictionary() or
+             self.type.isUnion() and self.type.unroll().hasDictionaryType) and
+            self.optional and not self.defaultValue):
             # Default optional dictionaries to null, for simplicity,
             # so the codegen doesn't have to special-case this.
             self.defaultValue = IDLNullValue(self.location)
 
         # Now do the coercing thing; this needs to happen after the
         # above creation of a default value.
         if self.defaultValue:
             self.defaultValue = self.defaultValue.coerceToType(self.type,
new file mode 100644
--- /dev/null
+++ b/dom/bindings/parser/tests/test_global_extended_attr.py
@@ -0,0 +1,122 @@
+def WebIDLTest(parser, harness):
+    parser.parse("""
+      [Global]
+      interface Foo : Bar {
+        getter any(DOMString name);
+      };
+      interface Bar {};
+    """)
+
+    results = parser.finish()
+
+    harness.ok(results[0].isOnGlobalProtoChain(),
+               "[Global] interface should be on global's proto chain")
+    harness.ok(results[1].isOnGlobalProtoChain(),
+               "[Global] interface should be on global's proto chain")
+
+    parser = parser.reset()
+    threw = False
+    try:
+        parser.parse("""
+          [Global]
+          interface Foo {
+            getter any(DOMString name);
+            setter void(DOMString name, any arg);
+          };
+        """)
+        results = parser.finish()
+    except:
+        threw = True
+
+    harness.ok(threw,
+               "Should have thrown for [Global] used on an interface with a "
+               "named setter")
+
+    parser = parser.reset()
+    threw = False
+    try:
+        parser.parse("""
+          [Global]
+          interface Foo {
+            getter any(DOMString name);
+            creator void(DOMString name, any arg);
+          };
+        """)
+        results = parser.finish()
+    except:
+        threw = True
+
+    harness.ok(threw,
+               "Should have thrown for [Global] used on an interface with a "
+               "named creator")
+
+    parser = parser.reset()
+    threw = False
+    try:
+        parser.parse("""
+          [Global]
+          interface Foo {
+            getter any(DOMString name);
+            deleter void(DOMString name);
+          };
+        """)
+        results = parser.finish()
+    except:
+        threw = True
+
+    harness.ok(threw,
+               "Should have thrown for [Global] used on an interface with a "
+               "named deleter")
+
+    parser = parser.reset()
+    threw = False
+    try:
+        parser.parse("""
+          [Global, OverrideBuiltins]
+          interface Foo {
+          };
+        """)
+        results = parser.finish()
+    except:
+        threw = True
+
+    harness.ok(threw,
+               "Should have thrown for [Global] used on an interface with a "
+               "[OverrideBuiltins]")
+
+    parser = parser.reset()
+    threw = False
+    try:
+        parser.parse("""
+          [Global]
+          interface Foo : Bar {
+          };
+          [OverrideBuiltins]
+          interface Bar {
+          };
+        """)
+        results = parser.finish()
+    except:
+        threw = True
+
+    harness.ok(threw,
+               "Should have thrown for [Global] used on an interface with an "
+               "[OverrideBuiltins] ancestor")
+
+    parser = parser.reset()
+    threw = False
+    try:
+        parser.parse("""
+          [Global]
+          interface Foo {
+          };
+          interface Bar : Foo {
+          };
+        """)
+        results = parser.finish()
+    except:
+        threw = True
+
+    harness.ok(threw,
+               "Should have thrown for [Global] used on an interface with a "
+               "descendant")
--- a/dom/bindings/test/Makefile.in
+++ b/dom/bindings/test/Makefile.in
@@ -8,21 +8,25 @@
 # pymake can't handle descending into dom/bindings several times simultaneously
 ifdef .PYMAKE
 .NOTPARALLEL:
 endif
 
 # Need this to find all our DOM source files.
 include $(topsrcdir)/dom/dom-config.mk
 
-# And need this for $(test_webidl_files)
+# And need this for $(test_webidl_files) and $(preprocessed_test_webidl_files)
 include ../webidlsrcs.mk
 
 # But the webidl actually lives in our parent dir
 test_webidl_files := $(addprefix ../,$(test_webidl_files))
+# Store the actual locations of our source preprocessed files, so we
+# can depend on them sanely.
+source_preprocessed_test_webidl_files := $(addprefix $(srcdir)/,$(preprocessed_test_webidl_files))
+preprocessed_test_webidl_files := $(addprefix ../,$(preprocessed_test_webidl_files))
 
 LOCAL_INCLUDES += \
   -I$(topsrcdir)/js/xpconnect/src \
   -I$(topsrcdir)/js/xpconnect/wrappers \
   -I$(topsrcdir)/dom/bindings \
   $(NULL)
 
 
@@ -63,35 +67,38 @@ MOCHITEST_FILES := \
   test_bug852846.html \
   test_bug862092.html \
   test_bug560072.html \
   test_lenientThis.html \
   test_ByteString.html \
   test_exception_messages.html \
   test_bug707564.html \
   test_defineProperty.html \
+  file_document_location_set_via_xray.html \
   $(NULL)
 
 MOCHITEST_CHROME_FILES = \
   test_bug775543.html \
   test_bug707564-chrome.html \
+  test_document_location_set_via_xray.html \
   $(NULL)
 
 ifdef GNU_CC
 CXXFLAGS += -Wno-uninitialized
 endif
 
 # Include rules.mk before any of our targets so our first target is coming from
 # rules.mk and running make with no target in this dir does the right thing.
 include $(topsrcdir)/config/rules.mk
 
 $(CPPSRCS): .BindingGen
 
 .BindingGen: $(bindinggen_dependencies) \
              $(test_webidl_files) \
+             $(source_preprocessed_test_webidl_files) \
              $(NULL)
 	# The export phase in dom/bindings is what actually looks at
 	# dependencies and regenerates things as needed, so just go ahead and
 	# make that phase here.  Also make our example interface files.  If the
 	# target used here ever changes, change the conditional around
 	# $(CPPSRCS) in dom/bindings/Makefile.in.
 	$(MAKE) -C .. export TestExampleInterface-example TestExampleProxyInterface-example
 	@$(TOUCH) $@
--- a/dom/bindings/test/TestBindingHeader.h
+++ b/dom/bindings/test/TestBindingHeader.h
@@ -497,16 +497,28 @@ public:
       JS_GetClass(obj);
       returnValue.SetAsObject() = obj;
     } else {
       int32_t i = arg.GetAsLong();
       i += 1;
       returnValue.SetAsLong() = i;
     }
   }
+#ifdef DEBUG
+  void PassUnion2(const LongOrBoolean& arg);
+  void PassUnion3(JSContext*, const ObjectOrLongOrBoolean& arg);
+  void PassUnion4(const NodeOrLongOrBoolean& arg);
+  void PassUnion5(JSContext*, const ObjectOrBoolean& arg);
+  void PassUnion6(JSContext*, const ObjectOrString& arg);
+  void PassUnion7(JSContext*, const ObjectOrStringOrLong& arg);
+  void PassUnion8(JSContext*, const ObjectOrStringOrBoolean& arg);
+  void PassUnion9(JSContext*, const ObjectOrStringOrLongOrBoolean& arg);
+  void PassUnion10(const EventInitOrLong& arg);
+  void PassUnion11(JSContext*, const CustomEventInitOrLong& arg);
+#endif
   void PassNullableUnion(JSContext*, const Nullable<ObjectOrLong>&);
   void PassOptionalUnion(JSContext*, const Optional<ObjectOrLong>&);
   void PassOptionalNullableUnion(JSContext*, const Optional<Nullable<ObjectOrLong> >&);
   void PassOptionalNullableUnionWithDefaultValue(JSContext*, const Nullable<ObjectOrLong>&);
   //void PassUnionWithInterfaces(const TestInterfaceOrTestExternalInterface& arg);
   //void PassUnionWithInterfacesAndNullable(const TestInterfaceOrNullOrTestExternalInterface& arg);
   void PassUnionWithArrayBuffer(const ArrayBufferOrLong&);
   void PassUnionWithString(JSContext*, const StringOrObject&);
--- a/dom/bindings/test/TestCodeGen.webidl
+++ b/dom/bindings/test/TestCodeGen.webidl
@@ -435,25 +435,30 @@ interface TestInterface {
   void passNullableSequenceOfObject(sequence<object>? arg);
   void passOptionalNullableSequenceOfNullableSequenceOfObject(optional sequence<sequence<object>?>? arg);
   void passOptionalNullableSequenceOfNullableSequenceOfNullableObject(optional sequence<sequence<object?>?>? arg);
   object receiveObject();
   object? receiveNullableObject();
 
   // Union types
   void passUnion((object or long) arg);
-  // Commented out tests 2-9 to avoid creating all those unused union types
-  /* void passUnion2((long or boolean) arg);
+  // Some  union tests are debug-only to avoid creating all those
+  // unused union types in opt builds.
+#ifdef DEBUG
+  void passUnion2((long or boolean) arg);
   void passUnion3((object or long or boolean) arg);
   void passUnion4((Node or long or boolean) arg);
   void passUnion5((object or boolean) arg);
   void passUnion6((object or DOMString) arg);
   void passUnion7((object or DOMString or long) arg);
   void passUnion8((object or DOMString or boolean) arg);
-  void passUnion9((object or DOMString or long or boolean) arg); */
+  void passUnion9((object or DOMString or long or boolean) arg);
+  void passUnion10(optional (EventInit or long) arg);
+  void passUnion11(optional (CustomEventInit or long) arg);
+#endif
   void passUnionWithNullable((object? or long) arg);
   void passNullableUnion((object or long)? arg);
   void passOptionalUnion(optional (object or long) arg);
   void passOptionalNullableUnion(optional (object or long)? arg);
   void passOptionalNullableUnionWithDefaultValue(optional (object or long)? arg = null);
   //void passUnionWithInterfaces((TestInterface or TestExternalInterface) arg);
   //void passUnionWithInterfacesAndNullable((TestInterface? or TestExternalInterface) arg);
   //void passUnionWithSequence((sequence<object> or long) arg);
@@ -739,16 +744,25 @@ dictionary Dict : ParentDict {
   unrestricted double  urDouble3 = -1.1;
   unrestricted double? urDouble4 = null;
   unrestricted double  infUrDouble = Infinity;
   unrestricted double  negativeInfUrDouble = -Infinity;
   unrestricted double  nanUrDouble = NaN;
 
   (float or DOMString) floatOrString = "str";
   (object or long) objectOrLong;
+#ifdef DEBUG
+  (EventInit or long) eventInitOrLong;
+  // CustomEventInit is useful to test because it needs rooting.
+  (CustomEventInit or long) eventInitOrLong2;
+  (EventInit or long) eventInitOrLongWithDefaultValue = null;
+  (CustomEventInit or long) eventInitOrLongWithDefaultValue2 = null;
+  (EventInit or long) eventInitOrLongWithDefaultValue3 = 5;
+  (CustomEventInit or long) eventInitOrLongWithDefaultValue4 = 5;
+#endif
 
   ArrayBuffer arrayBuffer;
   ArrayBuffer? nullableArrayBuffer;
   Uint8Array uint8Array;
   Float64Array? float64Array = null;
 };
 
 dictionary ParentDict : GrandparentDict {
--- a/dom/bindings/test/TestExampleGen.webidl
+++ b/dom/bindings/test/TestExampleGen.webidl
@@ -331,25 +331,30 @@ interface TestExampleInterface {
   void passNullableSequenceOfObject(sequence<object>? arg);
   void passOptionalNullableSequenceOfNullableSequenceOfObject(optional sequence<sequence<object>?>? arg);
   void passOptionalNullableSequenceOfNullableSequenceOfNullableObject(optional sequence<sequence<object?>?>? arg);
   object receiveObject();
   object? receiveNullableObject();
 
   // Union types
   void passUnion((object or long) arg);
-  // Commented out tests 2-9 to avoid creating all those unused union types
-  /* void passUnion2((long or boolean) arg);
+  // Some union tests are debug-only to avoid creating all those
+  // unused union types in opt builds.
+#ifdef DEBUG
+  void passUnion2((long or boolean) arg);
   void passUnion3((object or long or boolean) arg);
   void passUnion4((Node or long or boolean) arg);
   void passUnion5((object or boolean) arg);
   void passUnion6((object or DOMString) arg);
   void passUnion7((object or DOMString or long) arg);
   void passUnion8((object or DOMString or boolean) arg);
-  void passUnion9((object or DOMString or long or boolean) arg); */
+  void passUnion9((object or DOMString or long or boolean) arg);
+  void passUnion10(optional (EventInit or long) arg);
+  void passUnion11(optional (CustomEventInit or long) arg);
+#endif
   void passUnionWithNullable((object? or long) arg);
   void passNullableUnion((object or long)? arg);
   void passOptionalUnion(optional (object or long) arg);
   void passOptionalNullableUnion(optional (object or long)? arg);
   void passOptionalNullableUnionWithDefaultValue(optional (object or long)? arg = null);
   //void passUnionWithInterfaces((TestInterface or TestExternalInterface) arg);
   //void passUnionWithInterfacesAndNullable((TestInterface? or TestExternalInterface) arg);
   //void passUnionWithSequence((sequence<object> or long) arg);
--- a/dom/bindings/test/TestJSImplGen.webidl
+++ b/dom/bindings/test/TestJSImplGen.webidl
@@ -353,25 +353,30 @@ interface TestJSImplInterface {
   void passNullableSequenceOfObject(sequence<object>? arg);
   void passOptionalNullableSequenceOfNullableSequenceOfObject(optional sequence<sequence<object>?>? arg);
   void passOptionalNullableSequenceOfNullableSequenceOfNullableObject(optional sequence<sequence<object?>?>? arg);
   object receiveObject();
   object? receiveNullableObject();
 
   // Union types
   void passUnion((object or long) arg);
-  // Commented out tests 2-9 to avoid creating all those unused union types
-  /* void passUnion2((long or boolean) arg);
+  // Some union tests are debug-only to avoid creating all those
+  // unused union types in opt builds.
+#ifdef DEBUG
+  void passUnion2((long or boolean) arg);
   void passUnion3((object or long or boolean) arg);
   void passUnion4((Node or long or boolean) arg);
   void passUnion5((object or boolean) arg);
   void passUnion6((object or DOMString) arg);
   void passUnion7((object or DOMString or long) arg);
   void passUnion8((object or DOMString or boolean) arg);
-  void passUnion9((object or DOMString or long or boolean) arg); */
+  void passUnion9((object or DOMString or long or boolean) arg);
+  void passUnion10(optional (EventInit or long) arg);
+  void passUnion11(optional (CustomEventInit or long) arg);
+#endif
   void passUnionWithNullable((object? or long) arg);
   // FIXME: Bug 863948 Nullable unions not supported yet
   //   void passNullableUnion((object or long)? arg);
   void passOptionalUnion(optional (object or long) arg);
   // FIXME: Bug 863948 Nullable unions not supported yet
   //  void passOptionalNullableUnion(optional (object or long)? arg);
   //  void passOptionalNullableUnionWithDefaultValue(optional (object or long)? arg = null);
   //void passUnionWithInterfaces((TestJSImplInterface or TestExternalInterface) arg);
new file mode 100644
--- /dev/null
+++ b/dom/bindings/test/file_document_location_set_via_xray.html
@@ -0,0 +1,5 @@
+<body>
+<script>
+document.x = 5;
+</script>
+</body>
--- a/dom/bindings/test/moz.build
+++ b/dom/bindings/test/moz.build
@@ -3,16 +3,17 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 MODULE = 'dom'
 
 CPP_SOURCES += [
     '$(subst .webidl,Binding.cpp,$(test_webidl_files))',
+    '$(subst .webidl,Binding.cpp,$(preprocessed_test_webidl_files))',
 ]
 
 LIBXUL_LIBRARY = True
 # Do NOT export this library.  We don't actually want our test code
 # being added to libxul or anything.
 
 LIBRARY_NAME = 'dombindings_test_s'
 
new file mode 100644
--- /dev/null
+++ b/dom/bindings/test/test_document_location_set_via_xray.html
@@ -0,0 +1,49 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=905493
+-->
+<head>
+  <meta charset="utf-8">
+  <title>Test for Bug 905493</title>
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=905493">Mozilla Bug 905493</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+<iframe id="t" src="http://example.org/tests/dom/bindings/test/file_document_location_set_via_xray.html"></iframe>
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 905493 **/
+
+function test()
+{
+  var doc = document.getElementById("t").contentWindow.document;
+  ok(!("x" in doc), "Should have an Xray here");
+  is(doc.x, undefined, "Really should have an Xray here");
+  is(doc.wrappedJSObject.x, 5, "And wrapping the right thing");
+  document.getElementById("t").onload = function() {
+    ok(true, "Load happened");
+    SimpleTest.finish();
+  };
+  try {
+    // Test the forwarding location setter
+    doc.location = "chrome://mochikit/content/tests/SimpleTest/test.css";
+  } catch (e) {
+    // Load failed
+    ok(false, "Load failed");
+    SimpleTest.finish();
+  }
+}
+
+SimpleTest.waitForExplicitFinish();
+addLoadEvent(test);
+
+</script>
+</pre>
+</body>
+</html>
--- a/dom/ipc/PBrowser.ipdl
+++ b/dom/ipc/PBrowser.ipdl
@@ -158,16 +158,22 @@ parent:
      *
      *  if cancel is PR_TRUE,
      *    widget should return empty string for composition
      *  if cancel is PR_FALSE,
      *    widget should return the current composition text
      */
     sync EndIMEComposition(bool cancel) returns (nsString composition);
 
+    /**
+     * Request that the parent process move focus to the browser's frame. If
+     * canRaise is true, the window can be raised if it is inactive.
+     */
+    RequestFocus(bool canRaise);
+
     sync GetInputContext() returns (int32_t IMEEnabled, int32_t IMEOpen,
                                     intptr_t NativeIMEContext);
 
     SetInputContext(int32_t IMEEnabled,
                     int32_t IMEOpen,
                     nsString type,
                     nsString inputmode,
                     nsString actionHint,
--- a/dom/ipc/TabParent.cpp
+++ b/dom/ipc/TabParent.cpp
@@ -890,16 +890,38 @@ TabParent::RecvNotifyIMESelection(const 
 bool
 TabParent::RecvNotifyIMETextHint(const nsString& aText)
 {
   // Replace our cache with new text
   mIMECacheText = aText;
   return true;
 }
 
+bool
+TabParent::RecvRequestFocus(const bool& aCanRaise)
+{
+  nsCOMPtr<nsIFocusManager> fm = nsFocusManager::GetFocusManager();
+  if (!fm) {
+    return true;
+  }
+
+  nsCOMPtr<nsIContent> content = do_QueryInterface(mFrameElement);
+  if (!content || !content->OwnerDoc()) {
+    return true;
+  }
+
+  uint32_t flags = nsIFocusManager::FLAG_NOSCROLL;
+  if (aCanRaise)
+    flags |= nsIFocusManager::FLAG_RAISE;
+
+  nsCOMPtr<nsIDOMElement> node = do_QueryInterface(mFrameElement);
+  fm->SetFocus(node, flags);
+  return true;
+}
+
 /**
  * Try to answer query event using cached text.
  *
  * For NS_QUERY_SELECTED_TEXT, fail if the cache doesn't contain the whole
  *  selected range. (This shouldn't happen because PuppetWidget should have
  *  already sent the whole selection.)
  *
  * For NS_QUERY_TEXT_CONTENT, fail only if the cache doesn't overlap with
--- a/dom/ipc/TabParent.h
+++ b/dom/ipc/TabParent.h
@@ -140,16 +140,17 @@ public:
                                      intptr_t* aNativeIMEContext);
     virtual bool RecvSetInputContext(const int32_t& aIMEEnabled,
                                      const int32_t& aIMEOpen,
                                      const nsString& aType,
                                      const nsString& aInputmode,
                                      const nsString& aActionHint,
                                      const int32_t& aCause,
                                      const int32_t& aFocusChange);
+    virtual bool RecvRequestFocus(const bool& aCanRaise);
     virtual bool RecvSetCursor(const uint32_t& aValue);
     virtual bool RecvSetBackgroundColor(const nscolor& aValue);
     virtual bool RecvSetStatus(const uint32_t& aType, const nsString& aStatus);
     virtual bool RecvGetDPI(float* aValue);
     virtual bool RecvGetDefaultScale(double* aValue);
     virtual bool RecvGetWidgetNativeData(WindowsHandle* aValue);
     virtual bool RecvZoomToRect(const CSSRect& aRect);
     virtual bool RecvUpdateZoomConstraints(const bool& aAllowZoom,
--- a/dom/media/PeerConnection.js
+++ b/dom/media/PeerConnection.js
@@ -160,16 +160,17 @@ function RTCPeerConnection() {
   this._onCreateOfferSuccess = null;
   this._onCreateOfferFailure = null;
   this._onCreateAnswerSuccess = null;
   this._onCreateAnswerFailure = null;
 
   this._pendingType = null;
   this._localType = null;
   this._remoteType = null;
+  this._trickleIce = false;
 
   /**
    * Everytime we get a request from content, we put it in the queue. If
    * there are no pending operations though, we will execute it immediately.
    * In PeerConnectionObserver, whenever we are notified that an operation
    * has finished, we will check the queue for the next operation and execute
    * if neccesary. The _pending flag indicates whether an operation is currently
    * in progress.
@@ -188,16 +189,17 @@ RTCPeerConnection.prototype = {
   classID: PC_CID,
   contractID: PC_CONTRACT,
   QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
                                          Ci.nsIDOMGlobalPropertyInitializer,
                                          Ci.nsISupportsWeakReference]),
   init: function(win) { this._win = win; },
 
   __init: function(rtcConfig) {
+    this._trickleIce = Services.prefs.getBoolPref("media.peerconnection.trickle_ice");
     if (!rtcConfig.iceServers ||
         !Services.prefs.getBoolPref("media.peerconnection.use_document_iceservers")) {
       rtcConfig = {iceServers:
         JSON.parse(Services.prefs.getCharPref("media.peerconnection.default_iceservers"))};
     }
     this._mustValidateRTCConfiguration(rtcConfig,
         "RTCPeerConnection constructor passed invalid RTCConfiguration");
     if (_globalPCList._networkdown) {
@@ -219,21 +221,21 @@ RTCPeerConnection.prototype = {
              createInstance(Ci.IPeerConnection);
     this._observer = new PeerConnectionObserver(this);
     this._winID = this._win.QueryInterface(Ci.nsIInterfaceRequestor)
                            .getInterface(Ci.nsIDOMWindowUtils).currentInnerWindowID;
 
     // Add a reference to the PeerConnection to global list (before init).
     _globalPCList.addPC(this);
 
-    // Nothing starts until ICE gathering completes.
     this._queueOrRun({
       func: this._getPC().initialize,
       args: [this._observer, this._win, rtcConfig, Services.tm.currentThread],
-      wait: true
+      // If not trickling, suppress start.
+      wait: !this._trickleIce
     });
   },
 
   _getPC: function() {
     if (!this._pc) {
       throw new this._win.DOMError("",
           "RTCPeerConnection is gone (did you enter Offline mode?)");
     }
@@ -889,23 +891,21 @@ PeerConnectionObserver.prototype = {
     this._dompc._executeNext();
   },
 
   onSetLocalDescriptionSuccess: function() {
     this._dompc._localType = this._dompc._pendingType;
     this._dompc._pendingType = null;
     this.callCB(this._dompc._onSetLocalDescriptionSuccess);
 
-    // Until we support generating trickle ICE candidates,
-    // we go ahead and trigger a call of onicecandidate here.
-    // This is to provide some level of compatibility with
-    // scripts that expect this behavior (which is how Chrome
-    // signals that no further trickle candidates will be sent).
-    // TODO: This needs to be removed when Bug 842459 lands.
-    this.foundIceCandidate(null);
+    if (this._iceGatheringState == "complete") {
+        // If we are not trickling or we completed gathering prior
+        // to setLocal, then trigger a call of onicecandidate here.
+        this.foundIceCandidate(null);
+    }
 
     this._dompc._executeNext();
   },
 
   onSetRemoteDescriptionSuccess: function() {
     this._dompc._remoteType = this._dompc._pendingType;
     this._dompc._pendingType = null;
     this.callCB(this._dompc._onSetRemoteDescriptionSuccess);
@@ -933,25 +933,45 @@ PeerConnectionObserver.prototype = {
   },
 
   onAddIceCandidateError: function(code, message) {
     this._dompc._pendingType = null;
     this.callCB(this._dompc._onAddIceCandidateError, new RTCError(code, message));
     this._dompc._executeNext();
   },
 
+  onIceCandidate: function(level, mid, candidate) {
+    this.foundIceCandidate(new this._dompc._win.mozRTCIceCandidate(
+        {
+            candidate: candidate,
+            sdpMid: mid,
+            sdpMLineIndex: level
+        }
+    ));
+  },
+
   handleIceStateChanges: function(iceState) {
     var histogram = Services.telemetry.getHistogramById("WEBRTC_ICE_SUCCESS_RATE");
     switch (iceState) {
       case Ci.IPeerConnection.kIceWaiting:
         this._dompc.changeIceConnectionState("new");
         this.callCB(this._dompc.ongatheringchange, "complete");
         this.callCB(this._onicechange, "starting");
-        // Now that the PC is ready to go, execute any pending operations.
-        this._dompc._executeNext();
+
+        if (!this._dompc._trickleIce) {
+          // If we are not trickling, then the queue is in a pending state
+          // waiting for ICE gathering and executeNext frees it
+          this._dompc._executeNext();
+        }
+        else if (this.localDescription) {
+          // If we are trickling but we have already done setLocal,
+          // then we need to send a final foundIceCandidate(null) to indicate
+          // that we are done gathering.
+          this.foundIceCandidate(null);
+        }
         break;
       case Ci.IPeerConnection.kIceChecking:
         this._dompc.changeIceConnectionState("checking");
         this.callCB(this._onicechange, "checking");
         break;
       case Ci.IPeerConnection.kIceGathering:
         this._dompc.changeIceGatheringState("gathering");
         this.callCB(this._ongatheringchange, "gathering");
@@ -1004,19 +1024,23 @@ PeerConnectionObserver.prototype = {
                                                              { stream: stream }));
   },
 
   onRemoveStream: function(stream, type) {
     this.dispatchEvent(new this._dompc._win.MediaStreamEvent("removestream",
                                                              { stream: stream }));
   },
 
-  foundIceCandidate: function(c) {
+  foundIceCandidate: function(cand, mid, line) {
     this.dispatchEvent(new this._dompc._win.RTCPeerConnectionIceEvent("icecandidate",
-                                                                      { candidate: c }));
+                                                                      {
+                                                                          candidate: cand,
+                                                                          sdpMid: mid,
+                                                                          sdpMLineIndex: line
+                                                                      }));
   },
 
   notifyDataChannel: function(channel) {
     this.dispatchEvent(new this._dompc._win.RTCDataChannelEvent("datachannel",
                                                                 { channel: channel }));
   },
 
   notifyConnection: function() {
--- a/dom/media/bridge/IPeerConnection.idl
+++ b/dom/media/bridge/IPeerConnection.idl
@@ -19,17 +19,17 @@ interface IPeerConnectionManager : nsISu
 %}
 
 /* Do not confuse with nsIDOMRTCPeerConnection. This interface is purely for
  * communication between the PeerConnection JS DOM binding and the C++
  * implementation in SIPCC.
  *
  * See media/webrtc/signaling/include/PeerConnectionImpl.h
  */
-[scriptable, uuid(cf9152f0-c9a8-4093-9435-1daa056e0177)]
+[scriptable, uuid(896dc16a-05d6-45e4-bdbf-aba57123ed3e)]
 interface IPeerConnectionObserver : nsISupports
 {
   /* Constants */
   const long kReadyState = 0x1;
   const long kIceState = 0x2;
   const long kSdpState = 0x3;
   const long kSipccState = 0x4;
   const long kSignalingState = 0x5;
@@ -40,37 +40,31 @@ interface IPeerConnectionObserver : nsIS
   void onCreateAnswerSuccess(in string answer);
   void onCreateAnswerError(in unsigned long name, in string message);
   void onSetLocalDescriptionSuccess();
   void onSetRemoteDescriptionSuccess();
   void onSetLocalDescriptionError(in unsigned long name, in string message);
   void onSetRemoteDescriptionError(in unsigned long name, in string message);
   void onAddIceCandidateSuccess();
   void onAddIceCandidateError(in unsigned long name, in string message);
+  void onIceCandidate(in unsigned short level, in string mid, in string candidate);
 
   /* Data channel callbacks */
   void notifyDataChannel(in nsIDOMDataChannel channel);
   void notifyConnection();
   void notifyClosedConnection();
 
   /* Notification of one of several types of state changed */
   void onStateChange(in unsigned long state);
 
   /* Changes to MediaStreams */
   void onAddStream(in nsIDOMMediaStream stream);
   void onRemoveStream();
   void onAddTrack();
   void onRemoveTrack();
-
-  /* When SDP is parsed and a candidate line is found this method is called.
-   * It should hook back into the media transport to notify it of ICE candidates
-   * listed in the SDP PeerConnectionImpl does not parse ICE candidates, just
-   * pulls them out of the SDP.
-   */
-  void foundIceCandidate(in string candidate);
 };
 
 [scriptable, uuid(930dce8b-7c5e-4393-b8c0-cb3a928f68bd)]
 interface IPeerConnection : nsISupports
 {
   const unsigned long kHintAudio = 0x00000001;
   const unsigned long kHintVideo = 0x00000002;
 
--- a/dom/tests/mochitest/chrome/test_sandbox_bindings.xul
+++ b/dom/tests/mochitest/chrome/test_sandbox_bindings.xul
@@ -44,16 +44,24 @@ https://bugzilla.mozilla.org/show_bug.cg
       } catch (e) {
         ok(false, "'EventTarget' shouldn't throw in a sandbox");
       }
       try {
         var xhr = Components.utils.evalInSandbox("XMLHttpRequest.prototype", sandbox);
         ok(xhr, "'XMLHttpRequest.prototype' in a sandbox should return the XMLHttpRequest interface prototype object");
         ok(isXrayWrapper(xhr), "Getting an interface prototype object on an Xray wrapper should return an Xray wrapper");
         ok(isXrayWrapper(xhr.constructor), "Getting the constructor property on an Xray wrapper of an interface prototype object should return an Xray wrapper");
+        isnot(Object.getOwnPropertyDescriptor(xhr, "send"), undefined,
+              "We should claim to have a send() method");
+        isnot(Object.keys(xhr).indexOf("responseType"), -1,
+              "We should claim to have a responseType property");
+        isnot(Object.getOwnPropertyNames(xhr).indexOf("open"), -1,
+              "We should claim to have an open() method");
+        isnot(Object.getOwnPropertyDescriptor(xhr, "constructor"), undefined,
+              "We should claim to have a 'constructor' property");
       } catch (e) {
         ok(false, "'XMLHttpRequest.prototype' shouldn't throw in a sandbox");
       }
       try {
         var img = Components.utils.evalInSandbox("Image.prototype", sandbox);
         ok(img, "'Image.prototype' in a sandbox should return the interface prototype object");
         ok(isXrayWrapper(img), "Getting an interface prototype object on an Xray wrapper should return an Xray wrapper");
       } catch (e) {
@@ -82,16 +90,24 @@ https://bugzilla.mozilla.org/show_bug.cg
         delete xhr.constructor;
       } catch (e) {
         is(xhr.constructor, undefined, "'XMLHttpRequest.prototype.constructor' should be permanent");
       }
       try {
         var xhr = Components.utils.evalInSandbox("XMLHttpRequest", sandbox);
         is(xhr, "[object XrayWrapper " + XMLHttpRequest + "]", "'XMLHttpRequest' in a sandbox should return the XMLHttpRequest interface object");
         ok(isXrayWrapper(xhr.prototype), "Getting the prototype property on an Xray wrapper of an interface object should return an Xray wrapper");
+        isnot(Object.getOwnPropertyDescriptor(xhr, "UNSENT"), undefined,
+              "We should claim to have an UNSENT constant");
+        isnot(Object.keys(xhr).indexOf("OPENED"), -1,
+              "We should claim to have an OPENED constant");
+        isnot(Object.getOwnPropertyNames(xhr).indexOf("DONE"), -1,
+              "We should claim to have a DONE constant");
+        isnot(Object.getOwnPropertyDescriptor(xhr, "prototype"), undefined,
+              "We should claim to have 'prototype' property");
       } catch (e) {
         ok(false, "'XMLHttpRequest' shouldn't throw in a sandbox");
       }
       try {
         var xhr = Components.utils.evalInSandbox("XMLHttpRequest()", sandbox);
         is("" + xhr, "[object XrayWrapper " + XMLHttpRequest() + "]", "'XMLHttpRequest()' in a sandbox should create an XMLHttpRequest object");
       } catch (e) {
         ok(false, "'XMLHttpRequest()' shouldn't throw in a sandbox");
--- a/dom/webidl/DummyBinding.webidl
+++ b/dom/webidl/DummyBinding.webidl
@@ -2,17 +2,18 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
 // Dummy bindings that we need to force generation of things that
 // aren't actually referenced anywhere in IDL yet but are used in C++.
 
-interface DummyInterface {
+[Global]
+interface DummyInterface : EventTarget {
   readonly attribute OnErrorEventHandlerNonNull onErrorEventHandler;
   FilePropertyBag fileBag();
   InspectorRGBTriple rgbTriple();
   Function getFunction();
   void funcSocketsDict(optional SocketsDict arg);
   void funcHttpConnDict(optional HttpConnDict arg);
   void funcWebSocketDict(optional WebSocketDict arg);
   void funcDNSCacheDict(optional DNSCacheDict arg);
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -517,22 +517,24 @@ if CONFIG['MOZ_WEBSPEECH']:
 
 if CONFIG['MOZ_B2G_FM']:
     WEBIDL_FILES += [
         'FMRadio.webidl',
     ]
 
 if CONFIG['ENABLE_TESTS']:
     TEST_WEBIDL_FILES += [
+        'TestDictionary.webidl',
+        'TestJSImplInheritanceGen.webidl',
+        'TestTypedef.webidl',
+    ]
+    PREPROCESSED_TEST_WEBIDL_FILES += [
         'TestCodeGen.webidl',
-        'TestDictionary.webidl',
         'TestExampleGen.webidl',
         'TestJSImplGen.webidl',
-        'TestJSImplInheritanceGen.webidl',
-        'TestTypedef.webidl',
     ]
 
 if CONFIG['MOZ_B2G']:
     WEBIDL_FILES += [
         'InputMethod.webidl',
     ]
 
 GENERATED_EVENTS_WEBIDL_FILES = [
--- a/gfx/layers/composite/LayerManagerComposite.cpp
+++ b/gfx/layers/composite/LayerManagerComposite.cpp
@@ -339,16 +339,17 @@ LayerManagerComposite::Render()
     mCompositor->BeginFrame(&rect, mWorldMatrix, bounds, nullptr, &actualBounds);
   } else {
     gfx::Rect rect;
     mCompositor->BeginFrame(nullptr, mWorldMatrix, bounds, &rect, &actualBounds);
     clipRect = nsIntRect(rect.x, rect.y, rect.width, rect.height);
   }
 
   if (actualBounds.IsEmpty()) {
+    mCompositor->GetWidget()->PostRender(this);
     return;
   }
 
   // Allow widget to render a custom background.
   mCompositor->GetWidget()->DrawWindowUnderlay(this, nsIntRect(actualBounds.x,
                                                                actualBounds.y,
                                                                actualBounds.width,
                                                                actualBounds.height));
@@ -364,16 +365,18 @@ LayerManagerComposite::Render()
 
   // Debugging
   RenderDebugOverlay(actualBounds);
 
   {
     PROFILER_LABEL("LayerManagerComposite", "EndFrame");
     mCompositor->EndFrame();
   }
+
+  mCompositor->GetWidget()->PostRender(this);
 }
 
 void
 LayerManagerComposite::SetWorldTransform(const gfxMatrix& aMatrix)
 {
   NS_ASSERTION(aMatrix.PreservesAxisAlignedRectangles(),
                "SetWorldTransform only accepts matrices that satisfy PreservesAxisAlignedRectangles");
   NS_ASSERTION(!aMatrix.HasNonIntegerScale(),
--- a/js/public/MemoryMetrics.h
+++ b/js/public/MemoryMetrics.h
@@ -2,33 +2,33 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef js_MemoryMetrics_h
 #define js_MemoryMetrics_h
 
-// These declarations are not within jsapi.h because they are highly likely to
-// change in the future. Depend on them at your own risk.
+// These declarations are highly likely to change in the future. Depend on them
+// at your own risk.
 
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/NullPtr.h"
 #include "mozilla/PodOperations.h"
 
 #include <string.h>
 
 #include "jsalloc.h"
 #include "jspubtd.h"
 
 #include "js/HashTable.h"
 #include "js/Utility.h"
 #include "js/Vector.h"
 
-class nsISupports;      // This is needed for ObjectPrivateVisitor.
+class nsISupports;      // Needed for ObjectPrivateVisitor.
 
 namespace js {
 
 // In memory reporting, we have concept of "sundries", line items which are too
 // small to be worth reporting individually.  Under some circumstances, a memory
 // reporter gets tossed into the sundries bucket if it's smaller than
 // MemoryReportingSundriesThreshold() bytes.
 //
@@ -41,133 +41,170 @@ JS_FRIEND_API(size_t) MemoryReportingSun
 // on every hash and match! Beware.
 struct InefficientNonFlatteningStringHashPolicy
 {
     typedef JSString *Lookup;
     static HashNumber hash(const Lookup &l);
     static bool match(const JSString *const &k, const Lookup &l);
 };
 
+// This file features many classes with numerous size_t fields, and each such
+// class has one or more methods that need to operate on all of these fields.
+// Writing these individually is error-prone -- it's easy to add a new field
+// without updating all the required methods.  So we define a single macro list
+// in each class to name the fields (and notable characteristics of them), and
+// then use the following macros to transform those lists into the required
+// methods.
+//
+// In some classes, one or more of the macro arguments aren't used.  We use '_'
+// for those.
+//
+#define DECL_SIZE(gc, mSize)                      size_t mSize;
+#define ZERO_SIZE(gc, mSize)                      mSize(0),
+#define COPY_OTHER_SIZE(gc, mSize)                mSize(other.mSize),
+#define ADD_OTHER_SIZE(gc, mSize)                 mSize += other.mSize;
+#define ADD_SIZE_TO_N_IF_LIVE_GC_THING(gc, mSize) n += (gc == js::IsLiveGCThing) ? mSize : 0;
+
+// Used to annotate which size_t fields measure live GC things and which don't.
+enum {
+    IsLiveGCThing,
+    NotLiveGCThing
+};
+
 struct ZoneStatsPod
 {
-    ZoneStatsPod() {
-        mozilla::PodZero(this);
-    }
+#define FOR_EACH_SIZE(macro) \
+    macro(NotLiveGCThing, gcHeapArenaAdmin) \
+    macro(NotLiveGCThing, gcHeapUnusedGcThings) \
+    macro(IsLiveGCThing,  gcHeapStringsNormal) \
+    macro(IsLiveGCThing,  gcHeapStringsShort) \
+    macro(IsLiveGCThing,  gcHeapLazyScripts) \
+    macro(IsLiveGCThing,  gcHeapTypeObjects) \
+    macro(IsLiveGCThing,  gcHeapIonCodes) \
+    macro(NotLiveGCThing, stringCharsNonNotable) \
+    macro(NotLiveGCThing, lazyScripts) \
+    macro(NotLiveGCThing, typeObjects) \
+    macro(NotLiveGCThing, typePool)
+
+    ZoneStatsPod()
+      : FOR_EACH_SIZE(ZERO_SIZE)
+        extra()
+    {}
 
     void add(const ZoneStatsPod &other) {
-        #define ADD(x)  this->x += other.x
-
-        ADD(gcHeapArenaAdmin);
-        ADD(gcHeapUnusedGcThings);
-
-        ADD(gcHeapStringsNormal);
-        ADD(gcHeapStringsShort);
-        ADD(gcHeapLazyScripts);
-        ADD(gcHeapTypeObjects);
-        ADD(gcHeapIonCodes);
-
-        ADD(stringCharsNonNotable);
-        ADD(lazyScripts);
-        ADD(typeObjects);
-        ADD(typePool);
-
-        #undef ADD
+        FOR_EACH_SIZE(ADD_OTHER_SIZE)
+        // Do nothing with |extra|.
     }
 
-    // This field can be used by embedders.
-    void   *extra;
-
-    size_t gcHeapArenaAdmin;
-    size_t gcHeapUnusedGcThings;
-
-    size_t gcHeapStringsNormal;
-    size_t gcHeapStringsShort;
+    size_t sizeOfLiveGCThings() const {
+        size_t n = 0;
+        FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING)
+        // Do nothing with |extra|.
+        return n;
+    }
 
-    size_t gcHeapLazyScripts;
-    size_t gcHeapTypeObjects;
-    size_t gcHeapIonCodes;
+    FOR_EACH_SIZE(DECL_SIZE)
+    void *extra;    // This field can be used by embedders.
 
-    size_t stringCharsNonNotable;
-    size_t lazyScripts;
-    size_t typeObjects;
-    size_t typePool;
+#undef FOR_EACH_SIZE
 };
 
 } // namespace js
 
 namespace JS {
 
 // Data for tracking memory usage of things hanging off objects.
 struct ObjectsExtraSizes
 {
-    size_t slots;
-    size_t elementsNonAsmJS;
-    size_t elementsAsmJSHeap;
-    size_t elementsAsmJSNonHeap;
-    size_t asmJSModuleCode;
-    size_t asmJSModuleData;
-    size_t argumentsData;
-    size_t regExpStatics;
-    size_t propertyIteratorData;
-    size_t ctypesData;
-    size_t private_;    // The '_' suffix is required because |private| is a keyword.
-                        // Note that this field is measured separately from the others.
+#define FOR_EACH_SIZE(macro) \
+    macro(js::NotLiveGCThing, slots) \
+    macro(js::NotLiveGCThing, elementsNonAsmJS) \
+    macro(js::NotLiveGCThing, elementsAsmJSHeap) \
+    macro(js::NotLiveGCThing, elementsAsmJSNonHeap) \
+    macro(js::NotLiveGCThing, asmJSModuleCode) \
+    macro(js::NotLiveGCThing, asmJSModuleData) \
+    macro(js::NotLiveGCThing, argumentsData) \
+    macro(js::NotLiveGCThing, regExpStatics) \
+    macro(js::NotLiveGCThing, propertyIteratorData) \
+    macro(js::NotLiveGCThing, ctypesData)
 
-    ObjectsExtraSizes() { memset(this, 0, sizeof(ObjectsExtraSizes)); }
+    ObjectsExtraSizes()
+      : FOR_EACH_SIZE(ZERO_SIZE)
+        dummy()
+    {}
+
+    void add(const ObjectsExtraSizes &other) {
+        FOR_EACH_SIZE(ADD_OTHER_SIZE)
+    }
 
-    void add(ObjectsExtraSizes &sizes) {
-        this->slots                += sizes.slots;
-        this->elementsNonAsmJS     += sizes.elementsNonAsmJS;
-        this->elementsAsmJSHeap    += sizes.elementsAsmJSHeap;
-        this->elementsAsmJSNonHeap += sizes.elementsAsmJSNonHeap;
-        this->asmJSModuleCode      += sizes.asmJSModuleCode;
-        this->asmJSModuleData      += sizes.asmJSModuleData;
-        this->argumentsData        += sizes.argumentsData;
-        this->regExpStatics        += sizes.regExpStatics;
-        this->propertyIteratorData += sizes.propertyIteratorData;
-        this->ctypesData           += sizes.ctypesData;
-        this->private_             += sizes.private_;
+    size_t sizeOfLiveGCThings() const {
+        size_t n = 0;
+        FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING)
+        return n;
     }
+
+    FOR_EACH_SIZE(DECL_SIZE)
+    int dummy;  // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE)
+
+#undef FOR_EACH_SIZE
 };
 
 // Data for tracking analysis/inference memory usage.
 struct TypeInferenceSizes
 {
-    size_t typeScripts;
-    size_t typeResults;
-    size_t pendingArrays;
-    size_t allocationSiteTables;
-    size_t arrayTypeTables;
-    size_t objectTypeTables;
+#define FOR_EACH_SIZE(macro) \
+    macro(js::NotLiveGCThing, typeScripts) \
+    macro(js::NotLiveGCThing, typeResults) \
+    macro(js::NotLiveGCThing, pendingArrays) \
+    macro(js::NotLiveGCThing, allocationSiteTables) \
+    macro(js::NotLiveGCThing, arrayTypeTables) \
+    macro(js::NotLiveGCThing, objectTypeTables)
 
-    TypeInferenceSizes() { memset(this, 0, sizeof(TypeInferenceSizes)); }
+    TypeInferenceSizes()
+      : FOR_EACH_SIZE(ZERO_SIZE)
+        dummy()
+    {}
 
-    void add(TypeInferenceSizes &sizes) {
-        this->typeScripts          += sizes.typeScripts;
-        this->typeResults          += sizes.typeResults;
-        this->pendingArrays        += sizes.pendingArrays;
-        this->allocationSiteTables += sizes.allocationSiteTables;
-        this->arrayTypeTables      += sizes.arrayTypeTables;
-        this->objectTypeTables     += sizes.objectTypeTables;
+    void add(const TypeInferenceSizes &other) {
+        FOR_EACH_SIZE(ADD_OTHER_SIZE)
     }
+
+    size_t sizeOfLiveGCThings() const {
+        size_t n = 0;
+        FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING)
+        return n;
+    }
+
+    FOR_EACH_SIZE(DECL_SIZE)
+    int dummy;  // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE)
+
+#undef FOR_EACH_SIZE
 };
 
 // Data for tracking JIT-code memory usage.
 struct CodeSizes
 {
-    size_t ion;
-    size_t baseline;
-    size_t regexp;
-    size_t other;
-    size_t unused;
+#define FOR_EACH_SIZE(macro) \
+    macro(_, ion) \
+    macro(_, baseline) \
+    macro(_, regexp) \
+    macro(_, other) \
+    macro(_, unused)
 
-    CodeSizes() { memset(this, 0, sizeof(CodeSizes)); }
+    CodeSizes()
+      : FOR_EACH_SIZE(ZERO_SIZE)
+        dummy()
+    {}
+
+    FOR_EACH_SIZE(DECL_SIZE)
+    int dummy;  // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE)
+
+#undef FOR_EACH_SIZE
 };
 
-
 // This class holds information about the memory taken up by identical copies of
 // a particular string.  Multiple JSStrings may have their sizes aggregated
 // together into one StringInfo object.
 struct StringInfo
 {
     StringInfo()
       : length(0), numCopies(0), sizeOfShortStringGCThings(0),
         sizeOfNormalStringGCThings(0), sizeOfAllStringChars(0)
@@ -242,35 +279,42 @@ struct NotableStringInfo : public String
     }
 
     // The amount of memory we requested for |buffer|; i.e.
     // buffer = malloc(bufferSize).
     size_t bufferSize;
     char *buffer;
 };
 
-// These measurements relate directly to the JSRuntime, and not to
+// These measurements relate directly to the JSRuntime, and not to zones and
 // compartments within it.
 struct RuntimeSizes
 {
-    RuntimeSizes() { memset(this, 0, sizeof(RuntimeSizes)); }
+#define FOR_EACH_SIZE(macro) \
+    macro(_, object) \
+    macro(_, atomsTable) \
+    macro(_, contexts) \
+    macro(_, dtoa) \
+    macro(_, temporary) \
+    macro(_, regexpData) \
+    macro(_, interpreterStack) \
+    macro(_, gcMarker) \
+    macro(_, mathCache) \
+    macro(_, scriptData) \
+    macro(_, scriptSources)
 
-    size_t object;
-    size_t atomsTable;
-    size_t contexts;
-    size_t dtoa;
-    size_t temporary;
-    size_t regexpData;
-    size_t interpreterStack;
-    size_t gcMarker;
-    size_t mathCache;
-    size_t scriptData;
-    size_t scriptSources;
+    RuntimeSizes()
+      : FOR_EACH_SIZE(ZERO_SIZE)
+        code()
+    {}
 
+    FOR_EACH_SIZE(DECL_SIZE)
     CodeSizes code;
+
+#undef FOR_EACH_SIZE
 };
 
 struct ZoneStats : js::ZoneStatsPod
 {
     ZoneStats() {
         strings.init();
     }
 
@@ -305,178 +349,106 @@ struct ZoneStats : js::ZoneStatsPod
 
     typedef js::HashMap<JSString*,
                         StringInfo,
                         js::InefficientNonFlatteningStringHashPolicy,
                         js::SystemAllocPolicy> StringsHashMap;
 
     StringsHashMap strings;
     js::Vector<NotableStringInfo, 0, js::SystemAllocPolicy> notableStrings;
-
-    // The size of all the live things in the GC heap that don't belong to any
-    // compartment.
-    size_t GCHeapThingsSize();
 };
 
 struct CompartmentStats
 {
+#define FOR_EACH_SIZE(macro) \
+    macro(js::IsLiveGCThing,  gcHeapObjectsOrdinary) \
+    macro(js::IsLiveGCThing,  gcHeapObjectsFunction) \
+    macro(js::IsLiveGCThing,  gcHeapObjectsDenseArray) \
+    macro(js::IsLiveGCThing,  gcHeapObjectsSlowArray) \
+    macro(js::IsLiveGCThing,  gcHeapObjectsCrossCompartmentWrapper) \
+    macro(js::IsLiveGCThing,  gcHeapShapesTreeGlobalParented) \
+    macro(js::IsLiveGCThing,  gcHeapShapesTreeNonGlobalParented) \
+    macro(js::IsLiveGCThing,  gcHeapShapesDict) \
+    macro(js::IsLiveGCThing,  gcHeapShapesBase) \
+    macro(js::IsLiveGCThing,  gcHeapScripts) \
+    macro(js::NotLiveGCThing, objectsPrivate) \
+    macro(js::NotLiveGCThing, shapesExtraTreeTables) \
+    macro(js::NotLiveGCThing, shapesExtraDictTables) \
+    macro(js::NotLiveGCThing, shapesExtraTreeShapeKids) \
+    macro(js::NotLiveGCThing, shapesCompartmentTables) \
+    macro(js::NotLiveGCThing, scriptData) \
+    macro(js::NotLiveGCThing, baselineData) \
+    macro(js::NotLiveGCThing, baselineStubsFallback) \
+    macro(js::NotLiveGCThing, baselineStubsOptimized) \
+    macro(js::NotLiveGCThing, ionData) \
+    macro(js::NotLiveGCThing, compartmentObject) \
+    macro(js::NotLiveGCThing, crossCompartmentWrappersTable) \
+    macro(js::NotLiveGCThing, regexpCompartment) \
+    macro(js::NotLiveGCThing, debuggeesSet) \
+
     CompartmentStats()
-      : extra(nullptr),
-        gcHeapObjectsOrdinary(0),
-        gcHeapObjectsFunction(0),
-        gcHeapObjectsDenseArray(0),
-        gcHeapObjectsSlowArray(0),
-        gcHeapObjectsCrossCompartmentWrapper(0),
-        gcHeapShapesTreeGlobalParented(0),
-        gcHeapShapesTreeNonGlobalParented(0),
-        gcHeapShapesDict(0),
-        gcHeapShapesBase(0),
-        gcHeapScripts(0),
+      : FOR_EACH_SIZE(ZERO_SIZE)
         objectsExtra(),
-        shapesExtraTreeTables(0),
-        shapesExtraDictTables(0),
-        shapesExtraTreeShapeKids(0),
-        shapesCompartmentTables(0),
-        scriptData(0),
-        baselineData(0),
-        baselineStubsFallback(0),
-        baselineStubsOptimized(0),
-        ionData(0),
-        compartmentObject(0),
-        crossCompartmentWrappersTable(0),
-        regexpCompartment(0),
-        debuggeesSet(0),
-        typeInference()
+        typeInference(),
+        extra()
     {}
 
     CompartmentStats(const CompartmentStats &other)
-      : extra(other.extra),
-        gcHeapObjectsOrdinary(other.gcHeapObjectsOrdinary),
-        gcHeapObjectsFunction(other.gcHeapObjectsFunction),
-        gcHeapObjectsDenseArray(other.gcHeapObjectsDenseArray),
-        gcHeapObjectsSlowArray(other.gcHeapObjectsSlowArray),
-        gcHeapObjectsCrossCompartmentWrapper(other.gcHeapObjectsCrossCompartmentWrapper),
-        gcHeapShapesTreeGlobalParented(other.gcHeapShapesTreeGlobalParented),
-        gcHeapShapesTreeNonGlobalParented(other.gcHeapShapesTreeNonGlobalParented),
-        gcHeapShapesDict(other.gcHeapShapesDict),
-        gcHeapShapesBase(other.gcHeapShapesBase),
-        gcHeapScripts(other.gcHeapScripts),
+      : FOR_EACH_SIZE(COPY_OTHER_SIZE)
         objectsExtra(other.objectsExtra),
-        shapesExtraTreeTables(other.shapesExtraTreeTables),
-        shapesExtraDictTables(other.shapesExtraDictTables),
-        shapesExtraTreeShapeKids(other.shapesExtraTreeShapeKids),
-        shapesCompartmentTables(other.shapesCompartmentTables),
-        scriptData(other.scriptData),
-        baselineData(other.baselineData),
-        baselineStubsFallback(other.baselineStubsFallback),
-        baselineStubsOptimized(other.baselineStubsOptimized),
-        ionData(other.ionData),
-        compartmentObject(other.compartmentObject),
-        crossCompartmentWrappersTable(other.crossCompartmentWrappersTable),
-        regexpCompartment(other.regexpCompartment),
-        debuggeesSet(other.debuggeesSet),
-        typeInference(other.typeInference)
-    {
+        typeInference(other.typeInference),
+        extra(other.extra)
+    {}
+
+    void add(const CompartmentStats &other) {
+        FOR_EACH_SIZE(ADD_OTHER_SIZE)
+        objectsExtra.add(other.objectsExtra);
+        typeInference.add(other.typeInference);
+        // Do nothing with |extra|.
     }
 
-    // This field can be used by embedders.
-    void   *extra;
-
-    // If you add a new number, remember to update the constructors, add(), and
-    // maybe gcHeapThingsSize()!
-    size_t gcHeapObjectsOrdinary;
-    size_t gcHeapObjectsFunction;
-    size_t gcHeapObjectsDenseArray;
-    size_t gcHeapObjectsSlowArray;
-    size_t gcHeapObjectsCrossCompartmentWrapper;
-    size_t gcHeapShapesTreeGlobalParented;
-    size_t gcHeapShapesTreeNonGlobalParented;
-    size_t gcHeapShapesDict;
-    size_t gcHeapShapesBase;
-    size_t gcHeapScripts;
-    ObjectsExtraSizes objectsExtra;
-
-    size_t shapesExtraTreeTables;
-    size_t shapesExtraDictTables;
-    size_t shapesExtraTreeShapeKids;
-    size_t shapesCompartmentTables;
-    size_t scriptData;
-    size_t baselineData;
-    size_t baselineStubsFallback;
-    size_t baselineStubsOptimized;
-    size_t ionData;
-    size_t compartmentObject;
-    size_t crossCompartmentWrappersTable;
-    size_t regexpCompartment;
-    size_t debuggeesSet;
-
-    TypeInferenceSizes typeInference;
-
-    // Add cStats's numbers to this object's numbers.
-    void add(CompartmentStats &cStats) {
-        #define ADD(x)  this->x += cStats.x
-
-        ADD(gcHeapObjectsOrdinary);
-        ADD(gcHeapObjectsFunction);
-        ADD(gcHeapObjectsDenseArray);
-        ADD(gcHeapObjectsSlowArray);
-        ADD(gcHeapObjectsCrossCompartmentWrapper);
-        ADD(gcHeapShapesTreeGlobalParented);
-        ADD(gcHeapShapesTreeNonGlobalParented);
-        ADD(gcHeapShapesDict);
-        ADD(gcHeapShapesBase);
-        ADD(gcHeapScripts);
-        objectsExtra.add(cStats.objectsExtra);
-
-        ADD(shapesExtraTreeTables);
-        ADD(shapesExtraDictTables);
-        ADD(shapesExtraTreeShapeKids);
-        ADD(shapesCompartmentTables);
-        ADD(scriptData);
-        ADD(baselineData);
-        ADD(baselineStubsFallback);
-        ADD(baselineStubsOptimized);
-        ADD(ionData);
-        ADD(compartmentObject);
-        ADD(crossCompartmentWrappersTable);
-        ADD(regexpCompartment);
-        ADD(debuggeesSet);
-
-        #undef ADD
-
-        typeInference.add(cStats.typeInference);
+    size_t sizeOfLiveGCThings() const {
+        size_t n = 0;
+        FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING)
+        n += objectsExtra.sizeOfLiveGCThings();
+        n += typeInference.sizeOfLiveGCThings();
+        // Do nothing with |extra|.
+        return n;
     }
 
-    // The size of all the live things in the GC heap.
-    size_t GCHeapThingsSize();
+    FOR_EACH_SIZE(DECL_SIZE)
+    ObjectsExtraSizes  objectsExtra;
+    TypeInferenceSizes typeInference;
+    void               *extra;  // This field can be used by embedders.
+
+#undef FOR_EACH_SIZE
 };
 
 struct RuntimeStats
 {
+#define FOR_EACH_SIZE(macro) \
+    macro(_, gcHeapChunkTotal) \
+    macro(_, gcHeapDecommittedArenas) \
+    macro(_, gcHeapUnusedChunks) \
+    macro(_, gcHeapUnusedArenas) \
+    macro(_, gcHeapUnusedGcThings) \
+    macro(_, gcHeapChunkAdmin) \
+    macro(_, gcHeapGcThings) \
+
     RuntimeStats(mozilla::MallocSizeOf mallocSizeOf)
-      : runtime(),
-        gcHeapChunkTotal(0),
-        gcHeapDecommittedArenas(0),
-        gcHeapUnusedChunks(0),
-        gcHeapUnusedArenas(0),
-        gcHeapUnusedGcThings(0),
-        gcHeapChunkAdmin(0),
-        gcHeapGcThings(0),
+      : FOR_EACH_SIZE(ZERO_SIZE)
+        runtime(),
         cTotals(),
         zTotals(),
         compartmentStatsVector(),
         zoneStatsVector(),
         currZoneStats(nullptr),
         mallocSizeOf_(mallocSizeOf)
     {}
 
-    RuntimeSizes runtime;
-
-    // If you add a new number, remember to update the constructor!
-
     // Here's a useful breakdown of the GC heap.
     //
     // - rtStats.gcHeapChunkTotal
     //   - decommitted bytes
     //     - rtStats.gcHeapDecommittedArenas (decommitted arenas in non-empty chunks)
     //   - unused bytes
     //     - rtStats.gcHeapUnusedChunks (empty chunks)
     //     - rtStats.gcHeapUnusedArenas (empty arenas within non-empty chunks)
@@ -486,37 +458,34 @@ struct RuntimeStats
     //     - rtStats.total.gcHeapArenaAdmin
     //     - rtStats.gcHeapGcThings (in-use GC things)
     //
     // It's possible that some arenas in empty chunks may be decommitted, but
     // we don't count those under rtStats.gcHeapDecommittedArenas because (a)
     // it's rare, and (b) this means that rtStats.gcHeapUnusedChunks is a
     // multiple of the chunk size, which is good.
 
-    size_t gcHeapChunkTotal;
-    size_t gcHeapDecommittedArenas;
-    size_t gcHeapUnusedChunks;
-    size_t gcHeapUnusedArenas;
-    size_t gcHeapUnusedGcThings;
-    size_t gcHeapChunkAdmin;
-    size_t gcHeapGcThings;
+    FOR_EACH_SIZE(DECL_SIZE)
 
-    // The sum of all compartment's measurements.
-    CompartmentStats cTotals;
-    ZoneStats zTotals;
+    RuntimeSizes runtime;
+
+    CompartmentStats cTotals;   // The sum of this runtime's compartments' measurements.
+    ZoneStats zTotals;          // The sum of this runtime's zones' measurements.
 
     js::Vector<CompartmentStats, 0, js::SystemAllocPolicy> compartmentStatsVector;
     js::Vector<ZoneStats, 0, js::SystemAllocPolicy> zoneStatsVector;
 
     ZoneStats *currZoneStats;
 
     mozilla::MallocSizeOf mallocSizeOf_;
 
     virtual void initExtraCompartmentStats(JSCompartment *c, CompartmentStats *cstats) = 0;
     virtual void initExtraZoneStats(JS::Zone *zone, ZoneStats *zstats) = 0;
+
+#undef FOR_EACH_SIZE
 };
 
 class ObjectPrivateVisitor
 {
   public:
     // Within CollectRuntimeStats, this method is called for each JS object
     // that has an nsISupports pointer.
     virtual size_t sizeOfIncludingThis(nsISupports *aSupports) = 0;
--- a/js/src/config/check_spidermonkey_style.py
+++ b/js/src/config/check_spidermonkey_style.py
@@ -312,20 +312,16 @@ def is_module_header(enclosing_inclname,
     if module == module_name(header_inclname):
         return True
 
     # A public header, e.g. module == "foo/Bar", header_inclname == "js/Bar.h".
     m = re.match(r'js\/(.*)\.h', header_inclname)
     if m is not None and module.endswith('/' + m.group(1)):
         return True
 
-    # A weird public header case.
-    if module == 'jsmemorymetrics' and header_inclname == 'js/MemoryMetrics.h':
-        return True
-
     return False
 
 
 class Include(object):
     '''Important information for a single #include statement.'''
 
     def __init__(self, inclname, linenum, is_system):
         self.inclname = inclname
--- a/js/src/editline/Makefile.ref
+++ b/js/src/editline/Makefile.ref
@@ -55,17 +55,17 @@ DEPTH           = ..
 include $(DEPTH)/config.mk
 
 LOCAL_OBJDIR = $(OBJDIR)/editline
 
 #
 # Default IEEE libm
 #
 CFLAGS          += -DXP_UNIX $(OPTIMIZER) $(OS_CFLAGS) $(DEFINES) $(INCLUDES) \
-		  -DJSFILE $(XCFLAGS) $(DEFS)
+		  $(XCFLAGS) $(DEFS)
 
 INCFILES = editline.h
 .INIT: $(INCFILES)
 .KEEP_STATE:
 EDITLINE_CFILES = editline.c sysunix.c
 
 EDITLINE_OBJS = $(addprefix $(LOCAL_OBJDIR)/, $(EDITLINE_CFILES:.c=.o))
 
--- a/js/src/jit/MIR.h
+++ b/js/src/jit/MIR.h
@@ -8576,17 +8576,18 @@ class MAsmJSHeapAccess
     void setSkipBoundsCheck(bool v) { skipBoundsCheck_ = v; }
 };
 
 class MAsmJSLoadHeap : public MUnaryInstruction, public MAsmJSHeapAccess
 {
     MAsmJSLoadHeap(ArrayBufferView::ViewType vt, MDefinition *ptr)
       : MUnaryInstruction(ptr), MAsmJSHeapAccess(vt, false)
     {
-        setMovable();
+        // Disabled due to errors, see bug 919958
+        // setMovable();
         if (vt == ArrayBufferView::TYPE_FLOAT32 || vt == ArrayBufferView::TYPE_FLOAT64)
             setResultType(MIRType_Double);
         else
             setResultType(MIRType_Int32);
     }
 
   public:
     INSTRUCTION_HEADER(AsmJSLoadHeap);
--- a/js/src/jsscript.cpp
+++ b/js/src/jsscript.cpp
@@ -730,17 +730,17 @@ js::XDRScript(XDRState<mode> *xdr, Handl
                     JS_ASSERT(blockEnclosingScopeIndex < i);
                     blockEnclosingScope = script->objects()->vector[blockEnclosingScopeIndex];
                 } else {
                     blockEnclosingScope = fun;
                 }
             }
 
             Rooted<StaticBlockObject*> tmp(cx, static_cast<StaticBlockObject *>(objp->get()));
-            if (!XDRStaticBlockObject(xdr, blockEnclosingScope, script, tmp.address()))
+            if (!XDRStaticBlockObject(xdr, blockEnclosingScope, tmp.address()))
                 return false;
             *objp = tmp;
         }
     }
     for (i = 0; i != nregexps; ++i) {
         if (!XDRScriptRegExpObject(xdr, &script->regexps()->vector[i]))
             return false;
     }
--- a/js/src/moz.build
+++ b/js/src/moz.build
@@ -94,16 +94,17 @@ CPP_SOURCES += [
     'Id.cpp',
     'Interpreter.cpp',
     'Intl.cpp',
     'Iteration.cpp',
     'LifoAlloc.cpp',
     'MapObject.cpp',
     'Marking.cpp',
     'Memory.cpp',
+    'MemoryMetrics.cpp',
     'Module.cpp',
     'Monitor.cpp',
     'NameFunctions.cpp',
     'Nursery.cpp',
     'Object.cpp',
     'ObjectImpl.cpp',
     'OldDebugAPI.cpp',
     'PageBlock.cpp',
@@ -159,17 +160,16 @@ CPP_SOURCES += [
     'jsdtoa.cpp',
     'jsexn.cpp',
     'jsfriendapi.cpp',
     'jsfun.cpp',
     'jsgc.cpp',
     'jsinfer.cpp',
     'jsiter.cpp',
     'jsmath.cpp',
-    'jsmemorymetrics.cpp',
     'jsnativestack.cpp',
     'jsnum.cpp',
     'jsobj.cpp',
     'json.cpp',
     'jsonparser.cpp',
     'jsopcode.cpp',
     'jsperf.cpp',
     'jsprf.cpp',
rename from js/src/jsmemorymetrics.cpp
rename to js/src/vm/MemoryMetrics.cpp
--- a/js/src/jsmemorymetrics.cpp
+++ b/js/src/vm/MemoryMetrics.cpp
@@ -148,60 +148,27 @@ NotableStringInfo &NotableStringInfo::op
     new (this) NotableStringInfo(info);
     return *this;
 }
 
 } // namespace JS
 
 typedef HashSet<ScriptSource *, DefaultHasher<ScriptSource *>, SystemAllocPolicy> SourceSet;
 
-struct IteratorClosure
+struct StatsClosure
 {
     RuntimeStats *rtStats;
     ObjectPrivateVisitor *opv;
     SourceSet seenSources;
-    IteratorClosure(RuntimeStats *rt, ObjectPrivateVisitor *v) : rtStats(rt), opv(v) {}
+    StatsClosure(RuntimeStats *rt, ObjectPrivateVisitor *v) : rtStats(rt), opv(v) {}
     bool init() {
         return seenSources.init();
     }
 };
 
-size_t
-ZoneStats::GCHeapThingsSize()
-{
-    // These are just the GC-thing measurements.
-    size_t n = 0;
-    n += gcHeapStringsNormal;
-    n += gcHeapStringsShort;
-    n += gcHeapLazyScripts;
-    n += gcHeapTypeObjects;
-    n += gcHeapIonCodes;
-
-    return n;
-}
-
-size_t
-CompartmentStats::GCHeapThingsSize()
-{
-    // These are just the GC-thing measurements.
-    size_t n = 0;
-    n += gcHeapObjectsOrdinary;
-    n += gcHeapObjectsFunction;
-    n += gcHeapObjectsDenseArray;
-    n += gcHeapObjectsSlowArray;
-    n += gcHeapObjectsCrossCompartmentWrapper;
-    n += gcHeapShapesTreeGlobalParented;
-    n += gcHeapShapesTreeNonGlobalParented;
-    n += gcHeapShapesDict;
-    n += gcHeapShapesBase;
-    n += gcHeapScripts;
-
-    return n;
-}
-
 static void
 DecommittedArenasChunkCallback(JSRuntime *rt, void *data, gc::Chunk *chunk)
 {
     // This case is common and fast to check.  Do it first.
     if (chunk->decommittedArenas.isAllClear())
         return;
 
     size_t n = 0;
@@ -212,17 +179,17 @@ DecommittedArenasChunkCallback(JSRuntime
     JS_ASSERT(n > 0);
     *static_cast<size_t *>(data) += n;
 }
 
 static void
 StatsCompartmentCallback(JSRuntime *rt, void *data, JSCompartment *compartment)
 {
     // Append a new CompartmentStats to the vector.
-    RuntimeStats *rtStats = static_cast<IteratorClosure *>(data)->rtStats;
+    RuntimeStats *rtStats = static_cast<StatsClosure *>(data)->rtStats;
 
     // CollectRuntimeStats reserves enough space.
     MOZ_ALWAYS_TRUE(rtStats->compartmentStatsVector.growBy(1));
     CompartmentStats &cStats = rtStats->compartmentStatsVector.back();
     rtStats->initExtraCompartmentStats(compartment, &cStats);
 
     compartment->compartmentStats = &cStats;
 
@@ -236,33 +203,33 @@ StatsCompartmentCallback(JSRuntime *rt, 
                                      &cStats.debuggeesSet,
                                      &cStats.baselineStubsOptimized);
 }
 
 static void
 StatsZoneCallback(JSRuntime *rt, void *data, Zone *zone)
 {
     // Append a new CompartmentStats to the vector.
-    RuntimeStats *rtStats = static_cast<IteratorClosure *>(data)->rtStats;
+    RuntimeStats *rtStats = static_cast<StatsClosure *>(data)->rtStats;
 
     // CollectRuntimeStats reserves enough space.
     MOZ_ALWAYS_TRUE(rtStats->zoneStatsVector.growBy(1));
     ZoneStats &zStats = rtStats->zoneStatsVector.back();
     rtStats->initExtraZoneStats(zone, &zStats);
     rtStats->currZoneStats = &zStats;
 
     zone->sizeOfIncludingThis(rtStats->mallocSizeOf_,
                               &zStats.typePool);
 }
 
 static void
 StatsArenaCallback(JSRuntime *rt, void *data, gc::Arena *arena,
                    JSGCTraceKind traceKind, size_t thingSize)
 {
-    RuntimeStats *rtStats = static_cast<IteratorClosure *>(data)->rtStats;
+    RuntimeStats *rtStats = static_cast<StatsClosure *>(data)->rtStats;
 
     // The admin space includes (a) the header and (b) the padding between the
     // end of the header and the start of the first GC thing.
     size_t allocationSpace = arena->thingsSpan(thingSize);
     rtStats->currZoneStats->gcHeapArenaAdmin += gc::ArenaSize - allocationSpace;
 
     // We don't call the callback on unused things.  So we compute the
     // unused space like this:  arenaUnused = maxArenaUnused - arenaUsed.
@@ -276,17 +243,17 @@ GetCompartmentStats(JSCompartment *comp)
 {
     return static_cast<CompartmentStats *>(comp->compartmentStats);
 }
 
 static void
 StatsCellCallback(JSRuntime *rt, void *data, void *thing, JSGCTraceKind traceKind,
                   size_t thingSize)
 {
-    IteratorClosure *closure = static_cast<IteratorClosure *>(data);
+    StatsClosure *closure = static_cast<StatsClosure *>(data);
     RuntimeStats *rtStats = closure->rtStats;
     ZoneStats *zStats = rtStats->currZoneStats;
     switch (traceKind) {
       case JSTRACE_OBJECT: {
         JSObject *obj = static_cast<JSObject *>(thing);
         CompartmentStats *cStats = GetCompartmentStats(obj->compartment());
         if (obj->is<JSFunction>())
             cStats->gcHeapObjectsFunction += thingSize;
@@ -296,22 +263,22 @@ StatsCellCallback(JSRuntime *rt, void *d
             cStats->gcHeapObjectsCrossCompartmentWrapper += thingSize;
         else
             cStats->gcHeapObjectsOrdinary += thingSize;
 
         JS::ObjectsExtraSizes objectsExtra;
         obj->sizeOfExcludingThis(rtStats->mallocSizeOf_, &objectsExtra);
         cStats->objectsExtra.add(objectsExtra);
 
-        // JSObject::sizeOfExcludingThis() doesn't measure objectsExtraPrivate,
+        // JSObject::sizeOfExcludingThis() doesn't measure objectsPrivate,
         // so we do it here.
         if (ObjectPrivateVisitor *opv = closure->opv) {
             nsISupports *iface;
             if (opv->getISupports_(obj, &iface) && iface) {
-                cStats->objectsExtra.private_ += opv->sizeOfIncludingThis(iface);
+                cStats->objectsPrivate += opv->sizeOfIncludingThis(iface);
             }
         }
         break;
       }
 
       case JSTRACE_STRING: {
         JSString *str = static_cast<JSString *>(thing);
 
@@ -468,50 +435,50 @@ JS::CollectRuntimeStats(JSRuntime *rt, R
 
     rtStats->gcHeapUnusedChunks =
         size_t(JS_GetGCParameter(rt, JSGC_UNUSED_CHUNKS)) * gc::ChunkSize;
 
     IterateChunks(rt, &rtStats->gcHeapDecommittedArenas,
                   DecommittedArenasChunkCallback);
 
     // Take the per-compartment measurements.
-    IteratorClosure closure(rtStats, opv);
+    StatsClosure closure(rtStats, opv);
     if (!closure.init())
         return false;
     rtStats->runtime.scriptSources = 0;
     IterateZonesCompartmentsArenasCells(rt, &closure, StatsZoneCallback, StatsCompartmentCallback,
                                         StatsArenaCallback, StatsCellCallback);
 
     // Take the "explicit/js/runtime/" measurements.
     rt->sizeOfIncludingThis(rtStats->mallocSizeOf_, &rtStats->runtime);
 
     DebugOnly<size_t> totalArenaSize = 0;
 
     rtStats->gcHeapGcThings = 0;
     for (size_t i = 0; i < rtStats->zoneStatsVector.length(); i++) {
         ZoneStats &zStats = rtStats->zoneStatsVector[i];
 
         rtStats->zTotals.add(zStats);
-        rtStats->gcHeapGcThings += zStats.GCHeapThingsSize();
+        rtStats->gcHeapGcThings += zStats.sizeOfLiveGCThings();
 #ifdef DEBUG
         totalArenaSize += zStats.gcHeapArenaAdmin + zStats.gcHeapUnusedGcThings;
 #endif
 
         // Move any strings which take up more than the sundries threshold
         // (counting all of their copies together) into notableStrings.
         FindNotableStrings(zStats);
     }
 
     FindNotableStrings(rtStats->zTotals);
 
     for (size_t i = 0; i < rtStats->compartmentStatsVector.length(); i++) {
         CompartmentStats &cStats = rtStats->compartmentStatsVector[i];
 
         rtStats->cTotals.add(cStats);
-        rtStats->gcHeapGcThings += cStats.GCHeapThingsSize();
+        rtStats->gcHeapGcThings += cStats.sizeOfLiveGCThings();
     }
 
 #ifdef DEBUG
     totalArenaSize += rtStats->gcHeapGcThings;
     JS_ASSERT(totalArenaSize % gc::ArenaSize == 0);
 #endif
 
     for (CompartmentsIter comp(rt); !comp.done(); comp.next())
--- a/js/src/vm/ScopeObject.cpp
+++ b/js/src/vm/ScopeObject.cpp
@@ -725,17 +725,17 @@ const Class BlockObject::class_ = {
     JS_StrictPropertyStub,   /* setProperty */
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub
 };
 
 template<XDRMode mode>
 bool
-js::XDRStaticBlockObject(XDRState<mode> *xdr, HandleObject enclosingScope, HandleScript script,
+js::XDRStaticBlockObject(XDRState<mode> *xdr, HandleObject enclosingScope,
                          StaticBlockObject **objp)
 {
     /* NB: Keep this in sync with CloneStaticBlockObject. */
 
     JSContext *cx = xdr->cx();
 
     Rooted<StaticBlockObject*> obj(cx);
     uint32_t count = 0;
@@ -829,20 +829,20 @@ js::XDRStaticBlockObject(XDRState<mode> 
             if (!xdr->codeUint32(&aliased))
                 return false;
         }
     }
     return true;
 }
 
 template bool
-js::XDRStaticBlockObject(XDRState<XDR_ENCODE> *, HandleObject, HandleScript, StaticBlockObject **);
+js::XDRStaticBlockObject(XDRState<XDR_ENCODE> *, HandleObject, StaticBlockObject **);
 
 template bool
-js::XDRStaticBlockObject(XDRState<XDR_DECODE> *, HandleObject, HandleScript, StaticBlockObject **);
+js::XDRStaticBlockObject(XDRState<XDR_DECODE> *, HandleObject, StaticBlockObject **);
 
 JSObject *
 js::CloneStaticBlockObject(JSContext *cx, HandleObject enclosingScope, Handle<StaticBlockObject*> srcBlock)
 {
     /* NB: Keep this in sync with XDRStaticBlockObject. */
 
     Rooted<StaticBlockObject*> clone(cx, StaticBlockObject::create(cx));
     if (!clone)
--- a/js/src/vm/ScopeObject.h
+++ b/js/src/vm/ScopeObject.h
@@ -465,17 +465,17 @@ class ClonedBlockObject : public BlockOb
     }
 
     /* Copy in all the unaliased formals and locals. */
     void copyUnaliasedValues(AbstractFramePtr frame);
 };
 
 template<XDRMode mode>
 bool
-XDRStaticBlockObject(XDRState<mode> *xdr, HandleObject enclosingScope, HandleScript script,
+XDRStaticBlockObject(XDRState<mode> *xdr, HandleObject enclosingScope,
                      StaticBlockObject **objp);
 
 extern JSObject *
 CloneStaticBlockObject(JSContext *cx, HandleObject enclosingScope, Handle<StaticBlockObject*> src);
 
 /*****************************************************************************/
 
 class ScopeIterKey;
--- a/js/xpconnect/loader/Makefile.in
+++ b/js/xpconnect/loader/Makefile.in
@@ -6,11 +6,10 @@ LOCAL_INCLUDES += \
   -I$(srcdir)/../src \
   -I$(srcdir)/../wrappers \
   -I$(topsrcdir)/content/base/src \
   $(NULL)
 
 include $(topsrcdir)/config/rules.mk
 
 DEFINES += \
-  -DJSFILE \
   -DJS_THREADSAFE \
   $(NULL)
--- a/js/xpconnect/src/Makefile.in
+++ b/js/xpconnect/src/Makefile.in
@@ -41,19 +41,17 @@ extra_export_files_FILES := \
   $(NULL)
 extra_export_files_DEST = $(DIST)/include
 extra_export_files_TARGET := export
 
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
 
 DEFINES += \
-  -DJSFILE \
   -DJS_THREADSAFE \
-  -DEXPORT_XPC_API \
   $(NULL)
 
 ifdef MOZ_JSDEBUGGER
 DEFINES += -DMOZ_JSDEBUGGER
 endif
 
 nsXPConnect.$(OBJ_SUFFIX): dom_quickstubs.h
 
--- a/js/xpconnect/src/XPCJSRuntime.cpp
+++ b/js/xpconnect/src/XPCJSRuntime.cpp
@@ -1726,17 +1726,17 @@ private:
         rv = cb->Callback(EmptyCString(), _path,                              \
                           nsIMemoryReporter::_kind,                           \
                           nsIMemoryReporter::UNITS_BYTES, amount,             \
                           NS_LITERAL_CSTRING(_desc), closure);                \
         NS_ENSURE_SUCCESS(rv, rv);                                            \
         rtTotal += amount;                                                    \
     } while (0)
 
-NS_MEMORY_REPORTER_MALLOC_SIZEOF_FUN(JsMallocSizeOf)
+NS_MEMORY_REPORTER_MALLOC_SIZEOF_FUN(JSMallocSizeOf)
 
 namespace xpc {
 
 static nsresult
 ReportZoneStats(const JS::ZoneStats &zStats,
                 const xpc::ZoneStatsExtras &extras,
                 nsIMemoryReporterCallback *cb,
                 nsISupports *closure, size_t *gcTotalOut = NULL)
@@ -2062,17 +2062,17 @@ ReportCompartmentStats(const JS::Compart
     ZCREPORT_BYTES(cJSPathPrefix + NS_LITERAL_CSTRING("objects/malloc-heap/ctypes-data"),
                    cStats.objectsExtra.ctypesData,
                    "Memory allocated on the malloc heap for data belonging to ctypes objects.");
 
     // Note that we use cDOMPathPrefix here.  This is because we measure orphan
     // DOM nodes in the JS reporter, but we want to report them in a "dom"
     // sub-tree rather than a "js" sub-tree.
     ZCREPORT_BYTES(cDOMPathPrefix + NS_LITERAL_CSTRING("orphan-nodes"),
-                   cStats.objectsExtra.private_,
+                   cStats.objectsPrivate,
                    "Memory used by orphan DOM nodes that are only reachable "
                    "from JavaScript objects.");
 
     ZCREPORT_BYTES(cJSPathPrefix + NS_LITERAL_CSTRING("shapes/malloc-heap/tree-tables"),
                    cStats.shapesExtraTreeTables,
                    "Memory allocated on the malloc heap for the property tables "
                    "that belong to shapes that are in a property tree.");
 
@@ -2436,17 +2436,17 @@ class XPCJSRuntimeStats : public JS::Run
 {
     WindowPaths *mWindowPaths;
     WindowPaths *mTopWindowPaths;
     bool mGetLocations;
 
   public:
     XPCJSRuntimeStats(WindowPaths *windowPaths, WindowPaths *topWindowPaths,
                       bool getLocations)
-      : JS::RuntimeStats(JsMallocSizeOf),
+      : JS::RuntimeStats(JSMallocSizeOf),
         mWindowPaths(windowPaths),
         mTopWindowPaths(topWindowPaths),
         mGetLocations(getLocations)
     {}
 
     ~XPCJSRuntimeStats() {
         for (size_t i = 0; i != compartmentStatsVector.length(); ++i)
             delete static_cast<xpc::CompartmentStatsExtras*>(compartmentStatsVector[i].extra);
@@ -2569,18 +2569,18 @@ JSReporter::CollectReports(WindowPaths *
       do_GetService("@mozilla.org/addons/integration;1");
     bool getLocations = !!addonManager;
     XPCJSRuntimeStats rtStats(windowPaths, topWindowPaths, getLocations);
     OrphanReporter orphanReporter(XPCConvert::GetISupportsFromJSObject);
     if (!JS::CollectRuntimeStats(xpcrt->Runtime(), &rtStats, &orphanReporter))
         return NS_ERROR_FAILURE;
 
     size_t xpconnect =
-        xpcrt->SizeOfIncludingThis(JsMallocSizeOf) +
-        XPCWrappedNativeScope::SizeOfAllScopesIncludingThis(JsMallocSizeOf);
+        xpcrt->SizeOfIncludingThis(JSMallocSizeOf) +
+        XPCWrappedNativeScope::SizeOfAllScopesIncludingThis(JSMallocSizeOf);
 
     // This is the second step (see above).  First we report stuff in the
     // "explicit" tree, then we report other stuff.
 
     nsresult rv;
     size_t rtTotal = 0;
     rv = xpc::ReportJSRuntimeExplicitTreeStats(rtStats,
                                                NS_LITERAL_CSTRING("explicit/js-non-window/"),
@@ -3042,17 +3042,17 @@ XPCJSRuntime::XPCJSRuntime(nsXPConnect* 
 XPCJSRuntime*
 XPCJSRuntime::newXPCJSRuntime(nsXPConnect* aXPConnect)
 {
     NS_PRECONDITION(aXPConnect,"bad param");
 
     XPCJSRuntime* self = new XPCJSRuntime(aXPConnect);
 
     if (self                                    &&
-        self->Runtime()                    &&
+        self->Runtime()                         &&
         self->GetWrappedJSMap()                 &&
         self->GetWrappedJSClassMap()            &&
         self->GetIID2NativeInterfaceMap()       &&
         self->GetClassInfo2NativeSetMap()       &&
         self->GetNativeSetMap()                 &&
         self->GetThisTranslatorMap()            &&
         self->GetNativeScriptableSharedMap()    &&
         self->GetDyingWrappedNativeProtoMap()   &&
--- a/layout/base/StackArena.cpp
+++ b/layout/base/StackArena.cpp
@@ -3,157 +3,152 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "StackArena.h"
 #include "nsAlgorithm.h"
 #include "nsDebug.h"
 
 namespace mozilla {
 
-#define STACK_ARENA_MARK_INCREMENT 50
-/* a bit under 4096, for malloc overhead */
-#define STACK_ARENA_BLOCK_INCREMENT 4044
-
-/**A block of memory that the stack will 
- * chop up and hand out
- */
+// A block of memory that the stack will chop up and hand out.
 struct StackBlock {
-   
-   // a block of memory.  Note that this must be first so that it will
-   // be aligned.
-   char mBlock[STACK_ARENA_BLOCK_INCREMENT];
+  // Subtract sizeof(StackBlock*) to give space for the |mNext| field.
+  static const size_t MAX_USABLE_SIZE = 4096 - sizeof(StackBlock*);
+
+  // A block of memory.
+  char mBlock[MAX_USABLE_SIZE];
 
-   // another block of memory that would only be created
-   // if our stack overflowed. Yes we have the ability
-   // to grow on a stack overflow
-   StackBlock* mNext;
+  // Another block of memory that would only be created if our stack
+  // overflowed.
+  StackBlock* mNext;
 
-   StackBlock() : mNext(nullptr) { }
-   ~StackBlock() { }
+  StackBlock() : mNext(nullptr) { }
+  ~StackBlock() { }
 };
 
-/* we hold an array of marks. A push pushes a mark on the stack
- * a pop pops it off.
- */
+static_assert(sizeof(StackBlock) == 4096, "StackBlock must be 4096 bytes");
+
+// We hold an array of marks. A push pushes a mark on the stack.
+// A pop pops it off.
 struct StackMark {
-   // the block of memory we are currently handing out chunks of
-   StackBlock* mBlock;
-   
-   // our current position in the memory
-   size_t mPos;
+  // The block of memory from which we are currently handing out chunks.
+  StackBlock* mBlock;
+
+  // Our current position in the block.
+  size_t mPos;
 };
 
 StackArena* AutoStackArena::gStackArena;
 
 StackArena::StackArena()
 {
   mMarkLength = 0;
   mMarks = nullptr;
 
-  // allocate our stack memory
+  // Allocate our stack memory.
   mBlocks = new StackBlock();
   mCurBlock = mBlocks;
 
   mStackTop = 0;
   mPos = 0;
 }
 
 StackArena::~StackArena()
 {
-  // free up our data
-  delete[] mMarks;
-  while(mBlocks)
-  {
+  // Free up our data.
+  delete [] mMarks;
+  while (mBlocks) {
     StackBlock* toDelete = mBlocks;
     mBlocks = mBlocks->mNext;
     delete toDelete;
   }
-} 
+}
 
 size_t
 StackArena::SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const
 {
   size_t n = 0;
   StackBlock *block = mBlocks;
   while (block) {
     n += aMallocSizeOf(block);
     block = block->mNext;
   }
   n += aMallocSizeOf(mMarks);
   return n;
 }
 
+static const int STACK_ARENA_MARK_INCREMENT = 50;
+
 void
 StackArena::Push()
 {
   // Resize the mark array if we overrun it.  Failure to allocate the
   // mark array is not fatal; we just won't free to that mark.  This
   // allows callers not to worry about error checking.
-  if (mStackTop >= mMarkLength)
-  {
+  if (mStackTop >= mMarkLength) {
     uint32_t newLength = mStackTop + STACK_ARENA_MARK_INCREMENT;
     StackMark* newMarks = new StackMark[newLength];
     if (newMarks) {
-      if (mMarkLength)
+      if (mMarkLength) {
         memcpy(newMarks, mMarks, sizeof(StackMark)*mMarkLength);
+      }
       // Fill in any marks that we couldn't allocate during a prior call
       // to Push().
       for (; mMarkLength < mStackTop; ++mMarkLength) {
         NS_NOTREACHED("should only hit this on out-of-memory");
         newMarks[mMarkLength].mBlock = mCurBlock;
         newMarks[mMarkLength].mPos = mPos;
       }
       delete [] mMarks;
       mMarks = newMarks;
       mMarkLength = newLength;
     }
   }
 
-  // set a mark at the top (if we can)
+  // Set a mark at the top (if we can).
   NS_ASSERTION(mStackTop < mMarkLength, "out of memory");
   if (mStackTop < mMarkLength) {
     mMarks[mStackTop].mBlock = mCurBlock;
     mMarks[mStackTop].mPos = mPos;
   }
 
   mStackTop++;
 }
 
 void*
 StackArena::Allocate(size_t aSize)
 {
   NS_ASSERTION(mStackTop > 0, "Allocate called without Push");
 
-  // make sure we are aligned. Beard said 8 was safer then 4. 
-  // Round size to multiple of 8
+  // Align to a multiple of 8.
   aSize = NS_ROUNDUP<size_t>(aSize, 8);
 
-  // if the size makes the stack overflow. Grab another block for the stack
-  if (mPos + aSize >= STACK_ARENA_BLOCK_INCREMENT)
-  {
-    NS_ASSERTION(aSize <= STACK_ARENA_BLOCK_INCREMENT,
+  // On stack overflow, grab another block.
+  if (mPos + aSize >= StackBlock::MAX_USABLE_SIZE) {
+    NS_ASSERTION(aSize <= StackBlock::MAX_USABLE_SIZE,
                  "Requested memory is greater that our block size!!");
-    if (mCurBlock->mNext == nullptr)
+    if (mCurBlock->mNext == nullptr) {
       mCurBlock->mNext = new StackBlock();
+    }
 
-    mCurBlock =  mCurBlock->mNext;
+    mCurBlock = mCurBlock->mNext;
     mPos = 0;
   }
 
-  // return the chunk they need.
+  // Return the chunk they need.
   void *result = mCurBlock->mBlock + mPos;
   mPos += aSize;
 
   return result;
 }
 
 void
 StackArena::Pop()
 {
-  // pop off the mark
+  // Pop off the mark.
   NS_ASSERTION(mStackTop > 0, "unmatched pop");
   mStackTop--;
 
   if (mStackTop >= mMarkLength) {
     // We couldn't allocate the marks array at the time of the push, so
     // we don't know where we're freeing to.
     NS_NOTREACHED("out of memory");
     if (mStackTop == 0) {
--- a/layout/base/StackArena.h
+++ b/layout/base/StackArena.h
@@ -7,71 +7,69 @@
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/NullPtr.h"
 
 namespace mozilla {
 
 struct StackBlock;
 struct StackMark;
 class AutoStackArena;
- 
-/**
- * Private helper class for AutoStackArena.
- */
+
+// Private helper class for AutoStackArena.
 class StackArena {
 private:
   friend class AutoStackArena;
   StackArena();
   ~StackArena();
 
   nsresult Init() { return mBlocks ? NS_OK : NS_ERROR_OUT_OF_MEMORY; }
 
-  // Memory management functions
+  // Memory management functions.
   void* Allocate(size_t aSize);
   void Push();
   void Pop();
 
   size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
 
-  // our current position in memory
+  // Our current position in memory.
   size_t mPos;
 
-  // a list of memory block. Usually there is only one
+  // A list of memory blocks. Usually there is only one
   // but if we overrun our stack size we can get more memory.
   StackBlock* mBlocks;
 
-  // the current block of memory we are passing our chucks of
+  // The current block.
   StackBlock* mCurBlock;
 
-  // our stack of mark where push has been called
+  // Our stack of mark where push has been called.
   StackMark* mMarks;
 
-  // the current top of the mark list
+  // The current top of the mark list.
   uint32_t mStackTop;
 
-  // the size of the mark array
+  // The size of the mark array.
   uint32_t mMarkLength;
 };
 
-
-/**
- * Class for stack scoped arena memory allocations.
- *
- * Callers who wish to allocate memory whose lifetime corresponds to
- * the lifetime of a stack-allocated object can use this class.
- * First, declare an AutoStackArena object on the stack.
- * Then all subsequent calls to Allocate will allocate memory from an
- * arena pool that will be freed when that variable goes out of scope.
- * Nesting is allowed.
- *
- * The allocations cannot be for more than 4044 bytes.
- */
+// Class for stack scoped arena memory allocations.
+//
+// Callers who wish to allocate memory whose lifetime corresponds to the
+// lifetime of a stack-allocated object can use this class.  First,
+// declare an AutoStackArena object on the stack.  Then all subsequent
+// calls to Allocate will allocate memory from an arena pool that will
+// be freed when that variable goes out of scope.  Nesting is allowed.
+//
+// Individual allocations cannot exceed StackBlock::MAX_USABLE_SIZE
+// bytes.
+//
 class MOZ_STACK_CLASS AutoStackArena {
 public:
-  AutoStackArena() : mOwnsStackArena(false) {
+  AutoStackArena()
+    : mOwnsStackArena(false)
+  {
     if (!gStackArena) {
       gStackArena = new StackArena();
       mOwnsStackArena = true;
       gStackArena->Init();
     }
     gStackArena->Push();
   }
 
@@ -79,19 +77,17 @@ public:
     gStackArena->Pop();
     if (mOwnsStackArena) {
       delete gStackArena;
       gStackArena = nullptr;
     }
   }
 
   static void* Allocate(size_t aSize) {
-    MOZ_ASSERT(aSize <= 4044);
     return gStackArena->Allocate(aSize);
   }
 
 private:
   static StackArena* gStackArena;
   bool mOwnsStackArena;
 };
 
-
 } // namespace mozilla
--- a/media/mtransport/nricectx.cpp
+++ b/media/mtransport/nricectx.cpp
@@ -247,17 +247,17 @@ int NrIceCtx::select_pair(void *obj,nr_i
             << potential_ct);
 
   return 0;
 }
 
 int NrIceCtx::stream_ready(void *obj, nr_ice_media_stream *stream) {
   MOZ_MTLOG(ML_DEBUG, "stream_ready called");
 
-  // Get the ICE ctx
+  // Get the ICE ctx.
   NrIceCtx *ctx = static_cast<NrIceCtx *>(obj);
 
   RefPtr<NrIceMediaStream> s = ctx->FindStream(stream);
 
   // Streams which do not exist should never be ready.
   MOZ_ASSERT(s);
 
   s->Ready();
@@ -301,16 +301,40 @@ int NrIceCtx::msg_recvd(void *obj, nr_ic
   // Streams which do not exist should never have packets.
   MOZ_ASSERT(s);
 
   s->SignalPacketReceived(s, component_id, msg, len);
 
   return 0;
 }
 
+void NrIceCtx::trickle_cb(void *arg, nr_ice_ctx *ice_ctx,
+                          nr_ice_media_stream *stream,
+                          int component_id,
+                          nr_ice_candidate *candidate) {
+  // Get the ICE ctx
+  NrIceCtx *ctx = static_cast<NrIceCtx *>(arg);
+  RefPtr<NrIceMediaStream> s = ctx->FindStream(stream);
+
+  // Streams which do not exist shouldn't have candidates.
+  MOZ_ASSERT(s);
+
+  // Format the candidate.
+  char candidate_str[NR_ICE_MAX_ATTRIBUTE_SIZE];
+  int r = nr_ice_format_candidate_attribute(candidate, candidate_str,
+                                            sizeof(candidate_str));
+  MOZ_ASSERT(!r);
+  if (r)
+    return;
+
+  MOZ_MTLOG(ML_INFO, "NrIceCtx(" << ctx->name_ << "): trickling candidate "
+            << candidate_str);
+
+  s->SignalCandidate(s, candidate_str);
+}
 
 RefPtr<NrIceCtx> NrIceCtx::Create(const std::string& name,
                                   bool offerer,
                                   bool set_interface_priorities) {
   RefPtr<NrIceCtx> ctx = new NrIceCtx(name, offerer);
 
   // Initialize the crypto callbacks
   if (!initialized) {
@@ -378,16 +402,24 @@ RefPtr<NrIceCtx> NrIceCtx::Create(const 
 
   r = nr_ice_ctx_set_interface_prioritizer(ctx->ctx_, prioritizer);
   if (r) {
     MOZ_MTLOG(PR_LOG_ERROR, "Couldn't set interface prioritizer.");
     return nullptr;
   }
 #endif  // USE_INTERFACE_PRIORITIZER
 
+  if (ctx->generating_trickle()) {
+    r = nr_ice_ctx_set_trickle_cb(ctx->ctx_, &NrIceCtx::trickle_cb, ctx);
+    if (r) {
+      MOZ_MTLOG(ML_ERROR, "Couldn't set trickle cb for '" << name << "'");
+      return nullptr;
+    }
+  }
+
   // Create the handler objects
   ctx->ice_handler_vtbl_ = new nr_ice_handler_vtbl();
   ctx->ice_handler_vtbl_->select_pair = &NrIceCtx::select_pair;
   ctx->ice_handler_vtbl_->stream_ready = &NrIceCtx::stream_ready;
   ctx->ice_handler_vtbl_->stream_failed = &NrIceCtx::stream_failed;
   ctx->ice_handler_vtbl_->ice_completed = &NrIceCtx::ice_completed;
   ctx->ice_handler_vtbl_->msg_recvd = &NrIceCtx::msg_recvd;
 
@@ -530,25 +562,16 @@ nsresult NrIceCtx::StartGathering() {
       return NS_ERROR_FAILURE;
   }
 
   SetState(ICE_CTX_GATHERING);
 
   return NS_OK;
 }
 
-void NrIceCtx::EmitAllCandidates() {
-  MOZ_MTLOG(ML_NOTICE, "Gathered all ICE candidates for '"
-            << name_ << "'");
-
-  for(size_t i=0; i<streams_.size(); ++i) {
-    streams_[i]->EmitAllCandidates();
-  }
-}
-
 RefPtr<NrIceMediaStream> NrIceCtx::FindStream(
     nr_ice_media_stream *stream) {
   for (size_t i=0; i<streams_.size(); ++i) {
     if (streams_[i]->stream() == stream) {
       return streams_[i];
     }
   }
 
@@ -625,18 +648,16 @@ nsresult NrIceCtx::StartChecks() {
 
   return NS_OK;
 }
 
 
 void NrIceCtx::initialized_cb(NR_SOCKET s, int h, void *arg) {
   NrIceCtx *ctx = static_cast<NrIceCtx *>(arg);
 
-  ctx->EmitAllCandidates();
-
   ctx->SetState(ICE_CTX_GATHERED);
 }
 
 nsresult NrIceCtx::Finalize() {
   int r = nr_ice_ctx_finalize(ctx_, peer_);
 
   if (r) {
     MOZ_MTLOG(ML_ERROR, "Couldn't finalize "
--- a/media/mtransport/nricectx.h
+++ b/media/mtransport/nricectx.h
@@ -64,16 +64,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 
 #include "m_cpp_utils.h"
 
 typedef struct nr_ice_ctx_ nr_ice_ctx;
 typedef struct nr_ice_peer_ctx_ nr_ice_peer_ctx;
 typedef struct nr_ice_media_stream_ nr_ice_media_stream;
 typedef struct nr_ice_handler_ nr_ice_handler;
 typedef struct nr_ice_handler_vtbl_ nr_ice_handler_vtbl;
+typedef struct nr_ice_candidate_ nr_ice_candidate;
 typedef struct nr_ice_cand_pair_ nr_ice_cand_pair;
 typedef struct nr_ice_stun_server_ nr_ice_stun_server;
 typedef struct nr_ice_turn_server_ nr_ice_turn_server;
 typedef struct nr_resolver_ nr_resolver;
 
 typedef void* NR_SOCKET;
 
 namespace mozilla {
@@ -216,16 +217,19 @@ class NrIceCtx {
 
   // Start checking
   nsresult StartChecks();
 
   // Finalize the ICE negotiation. I.e., there will be no
   // more forking.
   nsresult Finalize();
 
+  // Are we trickling?
+  bool generating_trickle() const { return trickle_; }
+
   // Signals to indicate events. API users can (and should)
   // register for these.
   // TODO(ekr@rtfm.com): refactor this to be state change instead
   // so we don't need to keep adding signals?
   sigslot::signal1<NrIceCtx *> SignalGatheringCompleted;  // Done gathering
   sigslot::signal1<NrIceCtx *> SignalCompleted;  // Done handshaking
   sigslot::signal1<NrIceCtx *> SignalFailed;  // Failure.
 
@@ -239,18 +243,18 @@ class NrIceCtx {
            bool offerer)
   : state_(ICE_CTX_INIT),
     name_(name),
     offerer_(offerer),
     streams_(),
     ctx_(nullptr),
     peer_(nullptr),
     ice_handler_vtbl_(nullptr),
-    ice_handler_(nullptr)
-  {
+    ice_handler_(nullptr),
+    trickle_(true) {
     // XXX: offerer_ will be used eventually;  placate clang in the meantime.
     (void)offerer_;
   }
 
   DISALLOW_COPY_ASSIGN(NrIceCtx);
 
   // Callbacks for nICEr
   static void initialized_cb(NR_SOCKET s, int h, void *arg);  // ICE initialized
@@ -260,33 +264,32 @@ class NrIceCtx {
                          int component_id, nr_ice_cand_pair **potentials,
                          int potential_ct);
   static int stream_ready(void *obj, nr_ice_media_stream *stream);
   static int stream_failed(void *obj, nr_ice_media_stream *stream);
   static int ice_completed(void *obj, nr_ice_peer_ctx *pctx);
   static int msg_recvd(void *obj, nr_ice_peer_ctx *pctx,
                        nr_ice_media_stream *stream, int component_id,
                        unsigned char *msg, int len);
-
-  // Iterate through all media streams and emit the candidates
-  // Note that we don't do trickle ICE yet
-  void EmitAllCandidates();
+  static void trickle_cb(void *arg, nr_ice_ctx *ctx, nr_ice_media_stream *stream,
+                         int component_id, nr_ice_candidate *candidate);
 
   // Find a media stream by stream ptr. Gross
   RefPtr<NrIceMediaStream> FindStream(nr_ice_media_stream *stream);
 
   // Set the state
   void SetState(State state);
 
   State state_;
   const std::string name_;
   bool offerer_;
   std::vector<RefPtr<NrIceMediaStream> > streams_;
   nr_ice_ctx *ctx_;
   nr_ice_peer_ctx *peer_;
   nr_ice_handler_vtbl* ice_handler_vtbl_;  // Must be pointer
   nr_ice_handler* ice_handler_;  // Must be pointer
+  bool trickle_;
   nsCOMPtr<nsIEventTarget> sts_target_; // The thread to run on
 };
 
 
 }  // close namespace
 #endif
--- a/media/mtransport/nricemediastream.cpp
+++ b/media/mtransport/nricemediastream.cpp
@@ -238,36 +238,16 @@ nsresult NrIceMediaStream::GetActivePair
     *localp = local.forget();
   if (remotep)
     *remotep = remote.forget();
 
   return NS_OK;
 }
 
 
-void NrIceMediaStream::EmitAllCandidates() {
-  char **attrs = 0;
-  int attrct;
-  int r;
-  r = nr_ice_media_stream_get_attributes(stream_,
-                                         &attrs, &attrct);
-  if (r) {
-    MOZ_MTLOG(ML_ERROR, "Couldn't get ICE candidates for '"
-         << name_ << "'");
-    return;
-  }
-
-  for (int i=0; i<attrct; i++) {
-    SignalCandidate(this, attrs[i]);
-    RFREE(attrs[i]);
-  }
-
-  RFREE(attrs);
-}
-
 nsresult NrIceMediaStream::GetCandidatePairs(std::vector<NrIceCandidatePair>*
                                              out_pairs) const {
   MOZ_ASSERT(out_pairs);
 
   // Get the check_list on the peer stream (this is where the check_list
   // actually lives, not in stream_)
   nr_ice_media_stream* peer_stream;
   int r = nr_ice_peer_ctx_find_pstream(ctx_->peer(), stream_, &peer_stream);
@@ -327,33 +307,45 @@ nsresult NrIceMediaStream::GetDefaultCan
                                                std::string *addrp,
                                                int *portp) {
   nr_ice_candidate *cand;
   int r;
 
   r = nr_ice_media_stream_get_default_candidate(stream_,
                                                 component, &cand);
   if (r) {
-    MOZ_MTLOG(ML_ERROR, "Couldn't get default ICE candidate for '"
-              << name_ << "'");
-    return NS_ERROR_NOT_AVAILABLE;
-  }
+    if (ctx_->generating_trickle()) {
+      // Generate default trickle candidates.
+      // draft-ivov-mmusic-trickle-ice-01.txt says to use port 9
+      // but "::" instead of "0.0.0.0". Since we don't do any
+      // IPv6 we are ignoring that for now.
+      *addrp = "0.0.0.0";
+      *portp = 9;
+    }
+    else {
+      MOZ_MTLOG(ML_ERROR, "Couldn't get default ICE candidate for '"
+                << name_ << "'");
 
-  char addr[64];  // Enough for IPv6 with colons.
-  r = nr_transport_addr_get_addrstring(&cand->addr,addr,sizeof(addr));
-  if (r)
-    return NS_ERROR_FAILURE;
+      return NS_ERROR_NOT_AVAILABLE;
+    }
+  }
+  else {
+    char addr[64];  // Enough for IPv6 with colons.
+    r = nr_transport_addr_get_addrstring(&cand->addr,addr,sizeof(addr));
+    if (r)
+      return NS_ERROR_FAILURE;
 
-  int port;
-  r=nr_transport_addr_get_port(&cand->addr,&port);
-  if (r)
-    return NS_ERROR_FAILURE;
+    int port;
+    r=nr_transport_addr_get_port(&cand->addr,&port);
+    if (r)
+      return NS_ERROR_FAILURE;
 
-  *addrp = addr;
-  *portp = port;
+    *addrp = addr;
+    *portp = port;
+  }
 
   return NS_OK;
 }
 
 std::vector<std::string> NrIceMediaStream::GetCandidates() const {
   char **attrs = 0;
   int attrct;
   int r;
--- a/media/mtransport/nricemediastream.h
+++ b/media/mtransport/nricemediastream.h
@@ -101,16 +101,22 @@ struct NrIceCandidatePair {
   // Set if this candidate pair has been selected. Note: Since we are using
   // aggressive nomination, this could change frequently as ICE runs.
   bool selected;
   NrIceCandidate local;
   NrIceCandidate remote;
   // TODO(bcampen@mozilla.com): Is it important to put the foundation in here?
 };
 
+// Abstract base class for opaque values.
+class NrIceOpaque {
+ public:
+  virtual ~NrIceOpaque() {}
+};
+
 class NrIceMediaStream {
  public:
   static RefPtr<NrIceMediaStream> Create(NrIceCtx *ctx,
                                          const std::string& name,
                                          int components);
   ~NrIceMediaStream();
 
   enum State { ICE_CONNECTING, ICE_OPEN, ICE_CLOSED};
@@ -159,42 +165,46 @@ class NrIceMediaStream {
   void Ready();
 
   // Close the stream. Called by the NrIceCtx.
   // Different from the destructor because other people
   // might be holding RefPtrs but we want those writes to fail once
   // the context has been destroyed.
   void Close();
 
+  // Set an opaque value. Owned by the media stream.
+  void SetOpaque(NrIceOpaque *opaque) { opaque_ = opaque; }
+
+  // Get the opaque
+  NrIceOpaque* opaque() const { return opaque_; }
+
   sigslot::signal2<NrIceMediaStream *, const std::string& >
   SignalCandidate;  // A new ICE candidate:
   sigslot::signal1<NrIceMediaStream *> SignalReady;  // Candidate pair ready.
   sigslot::signal1<NrIceMediaStream *> SignalFailed;  // Candidate pair failed.
   sigslot::signal4<NrIceMediaStream *, int, const unsigned char *, int>
   SignalPacketReceived;  // Incoming packet
 
-  // Emit all the ICE candidates. Note that this doesn't
-  // work for trickle ICE yet--called internally
-  void EmitAllCandidates();
-
   NS_INLINE_DECL_THREADSAFE_REFCOUNTING(NrIceMediaStream)
 
  private:
   NrIceMediaStream(NrIceCtx *ctx,  const std::string& name,
                    int components) :
       state_(ICE_CONNECTING),
       ctx_(ctx),
       name_(name),
       components_(components),
-      stream_(nullptr) {}
+      stream_(nullptr),
+      opaque_(nullptr) {}
 
   DISALLOW_COPY_ASSIGN(NrIceMediaStream);
 
   State state_;
   NrIceCtx *ctx_;
   const std::string name_;
   const int components_;
   nr_ice_media_stream *stream_;
+  ScopedDeletePtr<NrIceOpaque> opaque_;
 };
 
 
 }  // close namespace
 #endif
--- a/media/mtransport/test/ice_unittest.cpp
+++ b/media/mtransport/test/ice_unittest.cpp
@@ -49,23 +49,26 @@ const std::string kDefaultStunServerAddr
 const std::string kDefaultStunServerHostname(
     (char *)"ec2-23-21-150-121.compute-1.amazonaws.com");
 const std::string kBogusStunServerHostname(
     (char *)"stun-server-nonexistent.invalid");
 const uint16_t kDefaultStunServerPort=3478;
 const std::string kBogusIceCandidate(
     (char *)"candidate:0 2 UDP 2113601790 192.168.178.20 50769 typ");
 
+std::string g_stun_server_address(kDefaultStunServerAddress);
+std::string g_stun_server_hostname(kDefaultStunServerHostname);
 std::string g_turn_server;
 std::string g_turn_user;
 std::string g_turn_password;
 
 namespace {
 
-enum TrickleMode { TRICKLE_NONE, TRICKLE_DEFERRED };
+enum TrickleMode { TRICKLE_NONE, TRICKLE_SIMULATE, TRICKLE_REAL };
+
 typedef bool (*CandidateFilter)(const std::string& candidate);
 
 static bool IsRelayCandidate(const std::string& candidate) {
   return candidate.find("typ relay") != std::string::npos;
 }
 
 bool ContainsSucceededPair(const std::vector<NrIceCandidatePair>& pairs) {
   for (size_t i = 0; i < pairs.size(); ++i) {
@@ -123,17 +126,19 @@ class IceTestPeer : public sigslot::has_
       ice_complete_(false),
       received_(0),
       sent_(0),
       fake_resolver_(),
       dns_resolver_(new NrIceResolver()),
       remote_(nullptr),
       candidate_filter_(nullptr),
       expected_local_type_(NrIceCandidate::ICE_HOST),
-      expected_remote_type_(NrIceCandidate::ICE_HOST) {
+      expected_remote_type_(NrIceCandidate::ICE_HOST),
+      trickle_mode_(TRICKLE_NONE),
+      trickled_(0) {
     ice_ctx_->SignalGatheringCompleted.connect(this,
                                                &IceTestPeer::GatheringComplete);
     ice_ctx_->SignalCompleted.connect(this, &IceTestPeer::IceCompleted);
   }
 
   ~IceTestPeer() {
     test_utils->sts_target()->Dispatch(WrapRunnable(this,
                                                     &IceTestPeer::Shutdown),
@@ -149,17 +154,17 @@ class IceTestPeer : public sigslot::has_
     snprintf(name, sizeof(name), "%s:stream%d", name_.c_str(),
              (int)streams_.size());
 
     mozilla::RefPtr<NrIceMediaStream> stream =
         ice_ctx_->CreateStream(static_cast<char *>(name), components);
 
     ASSERT_TRUE(stream);
     streams_.push_back(stream);
-    stream->SignalCandidate.connect(this, &IceTestPeer::GotCandidate);
+    stream->SignalCandidate.connect(this, &IceTestPeer::CandidateInitialized);
     stream->SignalReady.connect(this, &IceTestPeer::StreamReady);
     stream->SignalFailed.connect(this, &IceTestPeer::StreamFailed);
     stream->SignalPacketReceived.connect(this, &IceTestPeer::PacketReceived);
   }
 
   void SetStunServer(const std::string addr, uint16_t port) {
     std::vector<NrIceStunServer> stun_servers;
     ScopedDeletePtr<NrIceStunServer> server(NrIceStunServer::Create(addr,
@@ -184,21 +189,21 @@ class IceTestPeer : public sigslot::has_
         addr, port, username, password));
     turn_servers.push_back(*server);
     ASSERT_TRUE(NS_SUCCEEDED(ice_ctx_->SetTurnServers(turn_servers)));
   }
 
   void SetFakeResolver() {
     ASSERT_TRUE(NS_SUCCEEDED(dns_resolver_->Init()));
     PRNetAddr addr;
-    PRStatus status = PR_StringToNetAddr(kDefaultStunServerAddress.c_str(),
-                                         &addr);
+    PRStatus status = PR_StringToNetAddr(g_stun_server_address.c_str(),
+                                          &addr);
     addr.inet.port = kDefaultStunServerPort;
     ASSERT_EQ(PR_SUCCESS, status);
-    fake_resolver_.SetAddr(kDefaultStunServerHostname, addr);
+    fake_resolver_.SetAddr(g_stun_server_hostname, addr);
     ASSERT_TRUE(NS_SUCCEEDED(ice_ctx_->SetResolver(
         fake_resolver_.AllocateResolver())));
   }
 
   void SetDNSResolver() {
     ASSERT_TRUE(NS_SUCCEEDED(dns_resolver_->Init()));
     ASSERT_TRUE(NS_SUCCEEDED(ice_ctx_->SetResolver(
         dns_resolver_->AllocateResolver())));
@@ -214,17 +219,28 @@ class IceTestPeer : public sigslot::has_
     ASSERT_TRUE(NS_SUCCEEDED(res));
   }
 
   // Get various pieces of state
   std::vector<std::string> GetGlobalAttributes() {
     return ice_ctx_->GetGlobalAttributes();
   }
 
-  std::vector<std::string> GetCandidates(size_t stream) {
+   std::vector<std::string> GetCandidates(size_t stream) {
+    std::vector<std::string> v;
+
+    RUN_ON_THREAD(
+        test_utils->sts_target(),
+        WrapRunnableRet(this, &IceTestPeer::GetCandidates_s, stream, &v),
+        NS_DISPATCH_SYNC);
+
+    return v;
+  }
+
+  std::vector<std::string> GetCandidates_s(size_t stream) {
     std::vector<std::string> candidates;
 
     if (stream >= streams_.size())
       return candidates;
 
     std::vector<std::string> candidates_in =
       streams_[stream]->GetCandidates();
 
@@ -234,71 +250,79 @@ class IceTestPeer : public sigslot::has_
         std::cerr << "Returning candidate: " << candidates_in[i] << std::endl;
         candidates.push_back(candidates_in[i]);
       }
     }
 
     return candidates;
   }
 
-  void SetExpectedTypes(NrIceCandidate::Type local, NrIceCandidate::Type remote) {
+  void SetExpectedTypes(NrIceCandidate::Type local,
+                        NrIceCandidate::Type remote) {
     expected_local_type_ = local;
     expected_remote_type_ = remote;
   }
 
   bool gathering_complete() { return gathering_complete_; }
   int ready_ct() { return ready_ct_; }
   bool is_ready(size_t stream) {
     return streams_[stream]->state() == NrIceMediaStream::ICE_OPEN;
   }
   bool ice_complete() { return ice_complete_; }
   size_t received() { return received_; }
   size_t sent() { return sent_; }
 
   // Start connecting to another peer
-  void Connect(IceTestPeer *remote, TrickleMode trickle_mode,
-               bool start = true) {
+  void Connect_s(IceTestPeer *remote, TrickleMode trickle_mode,
+                 bool start = true) {
     nsresult res;
 
     remote_ = remote;
 
-    test_utils->sts_target()->Dispatch(
-      WrapRunnableRet(ice_ctx_,
-        &NrIceCtx::ParseGlobalAttributes, remote->GetGlobalAttributes(), &res),
-      NS_DISPATCH_SYNC);
+    trickle_mode_ = trickle_mode;
+    res = ice_ctx_->ParseGlobalAttributes(remote->GetGlobalAttributes());
     ASSERT_TRUE(NS_SUCCEEDED(res));
 
-    if (trickle_mode == TRICKLE_NONE) {
+    if (trickle_mode == TRICKLE_NONE ||
+        trickle_mode == TRICKLE_REAL) {
       for (size_t i=0; i<streams_.size(); ++i) {
-        test_utils->sts_target()->Dispatch(
-            WrapRunnableRet(streams_[i], &NrIceMediaStream::ParseAttributes,
-                            remote->GetCandidates(i),
-                            &res), NS_DISPATCH_SYNC);
+        std::vector<std::string> candidates =
+            remote->GetCandidates(i);
 
+        for (size_t j=0; j<candidates.size(); ++j) {
+          std::cerr << "Candidate: " + candidates[j] << std::endl;
+        }
+        res = streams_[i]->ParseAttributes(candidates);
         ASSERT_TRUE(NS_SUCCEEDED(res));
       }
     } else {
       // Parse empty attributes and then trickle them out later
       for (size_t i=0; i<streams_.size(); ++i) {
         std::vector<std::string> empty_attrs;
-        test_utils->sts_target()->Dispatch(
-            WrapRunnableRet(streams_[i], &NrIceMediaStream::ParseAttributes,
-                            empty_attrs,
-                            &res), NS_DISPATCH_SYNC);
-
+        res = streams_[i]->ParseAttributes(empty_attrs);
         ASSERT_TRUE(NS_SUCCEEDED(res));
       }
     }
 
     if (start) {
-      StartChecks();
+      // Now start checks
+      res = ice_ctx_->StartChecks();
+      ASSERT_TRUE(NS_SUCCEEDED(res));
     }
   }
 
-  void DoTrickle(size_t stream) {
+  void Connect(IceTestPeer *remote, TrickleMode trickle_mode,
+               bool start = true) {
+    test_utils->sts_target()->Dispatch(
+        WrapRunnable(
+            this, &IceTestPeer::Connect_s, remote, trickle_mode, start),
+        NS_DISPATCH_SYNC);
+  }
+
+  void SimulateTrickle(size_t stream) {
     std::cerr << "Doing trickle for stream " << stream << std::endl;
     // If we are in trickle deferred mode, now trickle in the candidates
     // for |stream}
     nsresult res;
 
     ASSERT_GT(remote_->streams_.size(), stream);
 
     std::vector<std::string> candidates =
@@ -387,22 +411,51 @@ class IceTestPeer : public sigslot::has_
     test_utils->sts_target()->Dispatch(
         WrapRunnableRet(ice_ctx_, &NrIceCtx::StartChecks, &res),
         NS_DISPATCH_SYNC);
     ASSERT_TRUE(NS_SUCCEEDED(res));
   }
 
   // Handle events
   void GatheringComplete(NrIceCtx *ctx) {
+    std::cerr << "Gathering complete for " <<  name_ << std::endl;
     gathering_complete_ = true;
+
+    std::cerr << "CANDIDATES:" << std::endl;
+    for (size_t i=0; i<streams_.size(); ++i) {
+      std::cerr << "Stream " << name_ << std::endl;
+      std::vector<std::string> candidates =
+          streams_[i]->GetCandidates();
+
+      for(size_t j=0; j<candidates.size(); ++j) {
+        std::cerr << candidates[j] << std::endl;
+      }
+    }
+    std::cerr << std::endl;
+
   }
 
-  void GotCandidate(NrIceMediaStream *stream, const std::string &candidate) {
-    std::cerr << "Got candidate " << candidate << std::endl;
+  void CandidateInitialized(NrIceMediaStream *stream, const std::string &candidate) {
+    std::cerr << "Candidate initialized: " << candidate << std::endl;
     candidates_[stream->name()].push_back(candidate);
+
+    // If we are connected, then try to trickle to the
+    // other side.
+    if (remote_ && remote_->remote_) {
+      std::vector<mozilla::RefPtr<NrIceMediaStream> >::iterator it =
+          std::find(streams_.begin(), streams_.end(), stream);
+      ASSERT_NE(streams_.end(), it);
+      size_t index = it - streams_.begin();
+
+      ASSERT_GT(remote_->streams_.size(), index);
+      nsresult res = remote_->streams_[index]->ParseTrickleCandidate(
+          candidate);
+      ASSERT_TRUE(NS_SUCCEEDED(res));
+      ++trickled_;
+    }
   }
 
   nsresult GetCandidatePairs(size_t stream_index,
                              std::vector<NrIceCandidatePair>* pairs) {
     MOZ_ASSERT(pairs);
     if (stream_index >= streams_.size()) {
       // Is there a better error for "no such index"?
       ADD_FAILURE() << "No such media stream index: " << stream_index;
@@ -565,47 +618,57 @@ class IceTestPeer : public sigslot::has_
   }
 
   void DisableComponent(size_t stream, int component_id) {
     ASSERT_LT(stream, streams_.size());
     nsresult res = streams_[stream]->DisableComponent(component_id);
     ASSERT_TRUE(NS_SUCCEEDED(res));
   }
 
+  int trickled() { return trickled_; }
+
  private:
   std::string name_;
   nsRefPtr<NrIceCtx> ice_ctx_;
   std::vector<mozilla::RefPtr<NrIceMediaStream> > streams_;
   std::map<std::string, std::vector<std::string> > candidates_;
   bool gathering_complete_;
   int ready_ct_;
   bool ice_complete_;
   size_t received_;
   size_t sent_;
   NrIceResolverFake fake_resolver_;
   nsRefPtr<NrIceResolver> dns_resolver_;
   IceTestPeer *remote_;
   CandidateFilter candidate_filter_;
   NrIceCandidate::Type expected_local_type_;
   NrIceCandidate::Type expected_remote_type_;
+  TrickleMode trickle_mode_;
+  int trickled_;
 };
 
 class IceGatherTest : public ::testing::Test {
  public:
   void SetUp() {
     test_utils->sts_target()->Dispatch(WrapRunnable(TestStunServer::GetInstance(),
                                                     &TestStunServer::Reset),
                                        NS_DISPATCH_SYNC);
     peer_ = new IceTestPeer("P1", true, false);
     peer_->AddStream(1);
   }
 
-  void Gather() {
-    peer_->Gather();
+  void Gather(bool wait = true) {
+     peer_->Gather();
 
+    if (wait) {
+      WaitForGather();
+    }
+  }
+
+  void WaitForGather() {
     ASSERT_TRUE_WAIT(peer_->gathering_complete(), 10000);
   }
 
   void UseFakeStunServerWithResponse(const std::string& fake_addr,
                                      uint16_t fake_port) {
     TestStunServer::GetInstance()->SetResponseAddr(fake_addr, fake_port);
     // Sets an additional stun server
     peer_->SetStunServer(TestStunServer::GetInstance()->addr(),
@@ -650,28 +713,29 @@ class IceConnectTest : public ::testing:
       p1_ = new IceTestPeer("P1", true, set_priorities);
       p2_ = new IceTestPeer("P2", false, set_priorities);
     }
     initted_ = true;
   }
 
   bool Gather(bool wait) {
     Init(false);
-    p1_->SetStunServer(kDefaultStunServerAddress, kDefaultStunServerPort);
-    p2_->SetStunServer(kDefaultStunServerAddress, kDefaultStunServerPort);
+    p1_->SetStunServer(g_stun_server_address, kDefaultStunServerPort);
+    p2_->SetStunServer(g_stun_server_address, kDefaultStunServerPort);
     p1_->Gather();
     p2_->Gather();
 
-    EXPECT_TRUE_WAIT(p1_->gathering_complete(), 10000);
-    if (!p1_->gathering_complete())
-      return false;
-    EXPECT_TRUE_WAIT(p2_->gathering_complete(), 10000);
-    if (!p2_->gathering_complete())
-      return false;
-
+    if (wait) {
+      EXPECT_TRUE_WAIT(p1_->gathering_complete(), 10000);
+      if (!p1_->gathering_complete())
+        return false;
+      EXPECT_TRUE_WAIT(p2_->gathering_complete(), 10000);
+      if (!p2_->gathering_complete())
+        return false;
+    }
     return true;
   }
 
   void SetTurnServer(const std::string addr, uint16_t port,
                      const std::string username,
                      const std::string password) {
     p1_->SetTurnServer(addr, port, username, password);
     p2_->SetTurnServer(addr, port, username, password);
@@ -715,34 +779,39 @@ class IceConnectTest : public ::testing:
   }
 
   void WaitForComplete(int expected_streams = 1) {
     ASSERT_TRUE_WAIT(p1_->ready_ct() == expected_streams &&
                      p2_->ready_ct() == expected_streams, 5000);
     ASSERT_TRUE_WAIT(p1_->ice_complete() && p2_->ice_complete(), 5000);
   }
 
-  void ConnectTrickle() {
-    p1_->Connect(p2_, TRICKLE_DEFERRED);
-    p2_->Connect(p1_, TRICKLE_DEFERRED);
+  void WaitForGather() {
+    ASSERT_TRUE_WAIT(p1_->gathering_complete(), 10000);
+    ASSERT_TRUE_WAIT(p2_->gathering_complete(), 10000);
   }
 
-  void DoTrickle(size_t stream) {
-    p1_->DoTrickle(stream);
-    p2_->DoTrickle(stream);
+  void ConnectTrickle(TrickleMode trickle = TRICKLE_SIMULATE) {
+    p1_->Connect(p2_, trickle);
+    p2_->Connect(p1_, trickle);
+  }
+
+  void SimulateTrickle(size_t stream) {
+    p1_->SimulateTrickle(stream);
+    p2_->SimulateTrickle(stream);
     ASSERT_TRUE_WAIT(p1_->is_ready(stream), 5000);
     ASSERT_TRUE_WAIT(p2_->is_ready(stream), 5000);
   }
 
-  void DoTrickleP1(size_t stream) {
-    p1_->DoTrickle(stream);
+  void SimulateTrickleP1(size_t stream) {
+    p1_->SimulateTrickle(stream);
   }
 
-  void DoTrickleP2(size_t stream) {
-    p2_->DoTrickle(stream);
+  void SimulateTrickleP2(size_t stream) {
+    p2_->SimulateTrickle(stream);
   }
 
   void VerifyConnected() {
   }
 
   void CloseP1() {
     p1_->Close();
   }
@@ -823,47 +892,47 @@ class PrioritizerTest : public ::testing
 
  private:
   nr_interface_prioritizer *prioritizer_;
 };
 
 }  // end namespace
 
 TEST_F(IceGatherTest, TestGatherFakeStunServerHostnameNoResolver) {
-  peer_->SetStunServer(kDefaultStunServerHostname, kDefaultStunServerPort);
+  peer_->SetStunServer(g_stun_server_hostname, kDefaultStunServerPort);
   Gather();
 }
 
 TEST_F(IceGatherTest, TestGatherFakeStunServerIpAddress) {
-  peer_->SetStunServer(kDefaultStunServerAddress, kDefaultStunServerPort);
+  peer_->SetStunServer(g_stun_server_address, kDefaultStunServerPort);
   peer_->SetFakeResolver();
   Gather();
 }
 
 TEST_F(IceGatherTest, TestGatherFakeStunServerHostname) {
-  peer_->SetStunServer(kDefaultStunServerHostname, kDefaultStunServerPort);
+  peer_->SetStunServer(g_stun_server_hostname, kDefaultStunServerPort);
   peer_->SetFakeResolver();
   Gather();
 }
 
 TEST_F(IceGatherTest, TestGatherFakeStunBogusHostname) {
   peer_->SetStunServer(kBogusStunServerHostname, kDefaultStunServerPort);
   peer_->SetFakeResolver();
   Gather();
 }
 
 TEST_F(IceGatherTest, TestGatherDNSStunServerIpAddress) {
-  peer_->SetStunServer(kDefaultStunServerAddress, kDefaultStunServerPort);
+  peer_->SetStunServer(g_stun_server_address, kDefaultStunServerPort);
   peer_->SetDNSResolver();
   Gather();
   // TODO(jib@mozilla.com): ensure we get server reflexive candidates Bug 848094
 }
 
 TEST_F(IceGatherTest, TestGatherDNSStunServerHostname) {
-  peer_->SetStunServer(kDefaultStunServerHostname, kDefaultStunServerPort);
+  peer_->SetStunServer(g_stun_server_hostname, kDefaultStunServerPort);
   peer_->SetDNSResolver();
   Gather();
 }
 
 TEST_F(IceGatherTest, TestGatherDNSStunBogusHostname) {
   peer_->SetStunServer(kBogusStunServerHostname, kDefaultStunServerPort);
   peer_->SetDNSResolver();
   Gather();
@@ -918,16 +987,26 @@ TEST_F(IceGatherTest, TestStunServerRetu
 }
 
 TEST_F(IceGatherTest, TestStunServerReturnsLoopbackAddr) {
   UseFakeStunServerWithResponse("127.0.0.133", 3333);
   Gather();
   ASSERT_FALSE(StreamHasMatchingCandidate(0, " 127.0.0.133 "));
 }
 
+TEST_F(IceGatherTest, TestStunServerTrickle) {
+  UseFakeStunServerWithResponse("192.0.2.1", 3333);
+  TestStunServer::GetInstance()->SetActive(false);
+  Gather(false);
+  ASSERT_FALSE(StreamHasMatchingCandidate(0, "192.0.2.1"));
+  TestStunServer::GetInstance()->SetActive(true);
+  WaitForGather();
+  ASSERT_TRUE(StreamHasMatchingCandidate(0, "192.0.2.1"));
+}
+
 TEST_F(IceConnectTest, TestGather) {
   AddStream("first", 1);
   ASSERT_TRUE(Gather(true));
 }
 
 TEST_F(IceConnectTest, TestGatherAutoPrioritize) {
   Init(false);
   AddStream("first", 1);
@@ -965,63 +1044,72 @@ TEST_F(IceConnectTest, TestConnectP2Then
   WaitForComplete();
 }
 
 TEST_F(IceConnectTest, TestConnectP2ThenP1Trickle) {
   AddStream("first", 1);
   ASSERT_TRUE(Gather(true));
   ConnectP2();
   PR_Sleep(1000);
-  ConnectP1(TRICKLE_DEFERRED);
-  DoTrickleP1(0);
+  ConnectP1(TRICKLE_SIMULATE);
+  SimulateTrickleP1(0);
   WaitForComplete();
 }
 
 TEST_F(IceConnectTest, TestConnectP2ThenP1TrickleTwoComponents) {
   AddStream("first", 1);
   AddStream("second", 2);
   ASSERT_TRUE(Gather(true));
   ConnectP2();
   PR_Sleep(1000);
-  ConnectP1(TRICKLE_DEFERRED);
-  DoTrickleP1(0);
+  ConnectP1(TRICKLE_SIMULATE);
+  SimulateTrickleP1(0);
   std::cerr << "Sleeping between trickle streams" << std::endl;
   PR_Sleep(1000);  // Give this some time to settle but not complete
                    // all of ICE.
-  DoTrickleP1(1);
+  SimulateTrickleP1(1);
   WaitForComplete(2);
 }
 
 TEST_F(IceConnectTest, TestConnectAutoPrioritize) {
   Init(false);
   AddStream("first", 1);
   ASSERT_TRUE(Gather(true));
   Connect();
 }
 
 TEST_F(IceConnectTest, TestConnectTrickleOneStreamOneComponent) {
   AddStream("first", 1);
   ASSERT_TRUE(Gather(true));
   ConnectTrickle();
-  DoTrickle(0);
+  SimulateTrickle(0);
   ASSERT_TRUE_WAIT(p1_->ice_complete(), 1000);
   ASSERT_TRUE_WAIT(p2_->ice_complete(), 1000);
 }
 
 TEST_F(IceConnectTest, TestConnectTrickleTwoStreamsOneComponent) {
   AddStream("first", 1);
   AddStream("second", 1);
   ASSERT_TRUE(Gather(true));
   ConnectTrickle();
-  DoTrickle(0);
-  DoTrickle(1);
+  SimulateTrickle(0);
+  SimulateTrickle(1);
   ASSERT_TRUE_WAIT(p1_->ice_complete(), 1000);
   ASSERT_TRUE_WAIT(p2_->ice_complete(), 1000);
 }
 
+TEST_F(IceConnectTest, TestConnectRealTrickleOneStreamOneComponent) {
+  AddStream("first", 1);
+  AddStream("second", 1);
+  ASSERT_TRUE(Gather(false));
+  ConnectTrickle(TRICKLE_REAL);
+  ASSERT_TRUE_WAIT(p1_->ice_complete(), 5000);
+  ASSERT_TRUE_WAIT(p2_->ice_complete(), 5000);
+  WaitForGather();  // ICE can complete before we finish gathering.
+}
 
 TEST_F(IceConnectTest, TestSendReceive) {
   AddStream("first", 1);
   ASSERT_TRUE(Gather(true));
   Connect();
   SendReceive();
 }
 
@@ -1190,16 +1278,25 @@ int main(int argc, char **argv)
       g_turn_user.empty(),
       g_turn_password.empty()) {
     printf(
         "Set TURN_SERVER_ADDRESS, TURN_SERVER_USER, and TURN_SERVER_PASSWORD\n"
         "environment variables to run this test\n");
     g_turn_server="";
   }
 
+  std::string tmp = get_environment("STUN_SERVER_ADDRESS");
+  if (tmp != "")
+    g_stun_server_address = tmp;
+
+
+  tmp = get_environment("STUN_SERVER_HOSTNAME");
+  if (tmp != "")
+    g_stun_server_hostname = tmp;
+
   test_utils = new MtransportTestUtils();
   NSS_NoDB_Init(nullptr);
   NSS_SetDomesticPolicy();
 
   // Start the tests
   ::testing::InitGoogleTest(&argc, argv);
 
   test_utils->sts_target()->Dispatch(
--- a/media/mtransport/third_party/nICEr/src/ice/ice_candidate.c
+++ b/media/mtransport/third_party/nICEr/src/ice/ice_candidate.c
@@ -411,18 +411,18 @@ int nr_ice_candidate_compute_priority(nr
   abort:
     return(_status);
   }
 
 static void nr_ice_candidate_fire_ready_cb(NR_SOCKET s, int how, void *cb_arg)
   {
     nr_ice_candidate *cand = cb_arg;
 
+    cand->ready_cb_timer = 0;
     cand->ready_cb(0, 0, cand->ready_cb_arg);
-    cand->ready_cb_timer = 0;
   }
 
 int nr_ice_candidate_initialize(nr_ice_candidate *cand, NR_async_cb ready_cb, void *cb_arg)
   {
     int r,_status;
     int protocol=NR_RESOLVE_PROTOCOL_STUN;
     cand->done_cb=ready_cb;
     cand->cb_arg=cb_arg;
--- a/media/mtransport/third_party/nICEr/src/ice/ice_component.c
+++ b/media/mtransport/third_party/nICEr/src/ice/ice_component.c
@@ -244,17 +244,17 @@ int nr_ice_component_initialize(struct n
 
         /* srvrflx */
         if(r=nr_ice_candidate_create(ctx,component,
           isock,sock,SERVER_REFLEXIVE,
           &ctx->turn_servers[j].turn_server,component->component_id,&cand))
           ABORT(r);
         cand->state=NR_ICE_CAND_STATE_INITIALIZING; /* Don't start */
         cand->done_cb=nr_ice_initialize_finished_cb;
-        cand->cb_arg=ctx;
+        cand->cb_arg=cand;
 
         TAILQ_INSERT_TAIL(&component->candidates,cand,entry_comp);
         component->candidate_ct++;
         srvflx_cand=cand;
 
         /* relayed*/
         if(r=nr_socket_turn_create(sock, &turn_sock))
           ABORT(r);
@@ -310,99 +310,89 @@ int nr_ice_component_initialize(struct n
       ctx->uninitialized_candidates++;
       cand=TAILQ_NEXT(cand,entry_comp);
     }
 
     /* Now initialize all the candidates */
     cand=TAILQ_FIRST(&component->candidates);
     while(cand){
       if(cand->state!=NR_ICE_CAND_STATE_INITIALIZING){
-        if(r=nr_ice_candidate_initialize(cand,nr_ice_initialize_finished_cb,ctx)){
+        if(r=nr_ice_candidate_initialize(cand,nr_ice_initialize_finished_cb,cand)){
           if(r!=R_WOULDBLOCK){
             ctx->uninitialized_candidates--;
             cand->state=NR_ICE_CAND_STATE_FAILED;
           }
         }
       }
       cand=TAILQ_NEXT(cand,entry_comp);
     }
 
     _status=0;
   abort:
     return(_status);
   }
 
-/* Prune redundant candidates. We use an n^2 algorithm for now.
+/*
+  Compare this newly initialized candidate against the other initialized
+  candidates and discard the lower-priority one if they are redundant.
 
    This algorithm combined with the other algorithms, favors
    host > srflx > relay
 
    This actually won't prune relayed in the very rare
    case that relayed is the same. Not relevant in practice.
-*/
+ */
+int nr_ice_component_maybe_prune_candidate(nr_ice_ctx *ctx, nr_ice_component *comp, nr_ice_candidate *c1, int *was_pruned)
+  {
+    nr_ice_candidate *c2, *tmp = NULL;
 
-int nr_ice_component_prune_candidates(nr_ice_ctx *ctx, nr_ice_component *comp)
-  {
-    nr_ice_candidate *c1,*c1n,*c2;
+    *was_pruned = 0;
+    c2 = TAILQ_FIRST(&comp->candidates);
+    while(c2){
+      if((c1 != c2) &&
+         (c2->state == NR_ICE_CAND_STATE_INITIALIZED) &&
+         !nr_transport_addr_cmp(&c1->base,&c2->base,NR_TRANSPORT_ADDR_CMP_MODE_ALL) &&
+         !nr_transport_addr_cmp(&c1->addr,&c2->addr,NR_TRANSPORT_ADDR_CMP_MODE_ALL)){
 
-    c1=TAILQ_FIRST(&comp->candidates);
-    while(c1){
-      c1n=TAILQ_NEXT(c1,entry_comp);
-      if(c1->state!=NR_ICE_CAND_STATE_INITIALIZED){
-        r_log(LOG_ICE,LOG_DEBUG,"ICE(%s): Removing non-initialized candidate %s",
-          ctx->label,c1->label);
-        if (c1->state == NR_ICE_CAND_STATE_INITIALIZING) {
-          r_log(LOG_ICE,LOG_NOTICE, "ICE(%s): Removing candidate %s which is in INITIALIZING state",
-            ctx->label, c1->label);
+        if((c1->type == c2->type) ||
+           (c1->type==HOST && c2->type == SERVER_REFLEXIVE) ||
+           (c2->type==HOST && c1->type == SERVER_REFLEXIVE)){
+
+          /*
+             These are redundant. Remove the lower pri one.
+
+             Since this algorithmis run whenever a new candidate
+             is initialized, there should at most one duplicate.
+           */
+          if (c1->priority < c2->priority) {
+            tmp = c1;
+            *was_pruned = 1;
+          }
+          else {
+            tmp = c2;
+          }
+          break;
         }
-        TAILQ_REMOVE(&comp->candidates,c1,entry_comp);
-        comp->candidate_ct--;
-        TAILQ_REMOVE(&c1->isock->candidates,c1,entry_sock);
-        /* schedule this delete for later as we don't want to delete the underlying
-         * objects while in the middle of a callback on one of those objects */
-        NR_ASYNC_SCHEDULE(nr_ice_candidate_destroy_cb,c1);
-        goto next_c1;
       }
 
-      c2=TAILQ_NEXT(c1,entry_comp);
-
-      while(c2){
-        nr_ice_candidate *tmp;
-
-        if(!nr_transport_addr_cmp(&c1->base,&c2->base,NR_TRANSPORT_ADDR_CMP_MODE_ALL) && !nr_transport_addr_cmp(&c1->addr,&c2->addr,NR_TRANSPORT_ADDR_CMP_MODE_ALL)){
-
-          if((c1->type == c2->type) ||
-            (c1->type==HOST && c2->type == SERVER_REFLEXIVE) ||
-            (c2->type==HOST && c1->type == SERVER_REFLEXIVE)){
-
-            /* OK these are redundant. Remove the lower pri one */
-            tmp=c2;
-            c2=TAILQ_NEXT(c2,entry_comp);
-            if(c1n==tmp)
-              c1n=c2;
-
-            r_log(LOG_ICE,LOG_DEBUG,"ICE(%s): Removing redundant candidate %s",
-              ctx->label,tmp->label);
-
-            TAILQ_REMOVE(&comp->candidates,tmp,entry_comp);
-            comp->candidate_ct--;
-            TAILQ_REMOVE(&tmp->isock->candidates,tmp,entry_sock);
-
-            nr_ice_candidate_destroy(&tmp);
-          }
-        }
-        else{
-          c2=TAILQ_NEXT(c2,entry_comp);
-        }
-      }
-    next_c1:
-      c1=c1n;
+      c2=TAILQ_NEXT(c2,entry_comp);
     }
 
-    return(0);
+    if (tmp) {
+      r_log(LOG_ICE,LOG_DEBUG,"ICE(%s): Removing redundant candidate %s",
+            ctx->label,tmp->label);
+
+      TAILQ_REMOVE(&comp->candidates,tmp,entry_comp);
+      comp->candidate_ct--;
+      TAILQ_REMOVE(&tmp->isock->candidates,tmp,entry_sock);
+
+      nr_ice_candidate_destroy(&tmp);
+    }
+
+    return 0;
   }
 
 /* Section 7.2.1 */
 static int nr_ice_component_process_incoming_check(nr_ice_component *comp, nr_transport_addr *local_addr, nr_stun_server_request *req, int *error)
   {
     nr_ice_cand_pair *pair;
     nr_ice_candidate *pcand=0;
     nr_stun_message *sreq=req->request;
@@ -647,84 +637,95 @@ int nr_ice_component_service_pre_answer_
       }
     }
 
     _status=0;
  abort:
     return(_status);
   }
 
+int nr_ice_component_pair_candidate(nr_ice_peer_ctx *pctx, nr_ice_component *pcomp, nr_ice_candidate *lcand, int pair_all_remote)
+  {
+    int r, _status;
+    nr_ice_candidate *pcand;
+    nr_ice_cand_pair *pair=0;
+    char codeword[5];
+
+    nr_ice_compute_codeword(lcand->label,strlen(lcand->label),codeword);
+    r_log(LOG_ICE,LOG_DEBUG,"Pairing local candidate %s:%s",codeword,lcand->label);
+
+    switch(lcand->type){
+      case HOST:
+        break;
+      case SERVER_REFLEXIVE:
+      case PEER_REFLEXIVE:
+        /* Don't actually pair these candidates */
+        goto done;
+        break;
+      case RELAYED:
+        break;
+      default:
+        assert(0);
+        ABORT(R_INTERNAL);
+        break;
+    }
+
+    pcand=TAILQ_FIRST(&pcomp->candidates);
+    while(pcand){
+      /*
+        Two modes, depending on |pair_all_remote|
+
+        1. Pair remote candidates which have not been paired
+           (used in initial pairing or in processing the other side's
+           trickle candidates).
+        2. Pair any remote candidate (used when processing our own
+           trickle candidates).
+      */
+      if (pair_all_remote || (pcand->state == NR_ICE_CAND_PEER_CANDIDATE_UNPAIRED)) {
+        /* If we are pairing our own trickle candidates, the remote candidate should
+           all be paired */
+        if (pair_all_remote)
+          assert (pcand->state == NR_ICE_CAND_PEER_CANDIDATE_PAIRED);
+
+        nr_ice_compute_codeword(pcand->label,strlen(pcand->label),codeword);
+        r_log(LOG_ICE,LOG_DEBUG,"Pairing with peer candidate %s:%s",codeword,pcand->label);
+
+        if(r=nr_ice_candidate_pair_create(pctx,lcand,pcand,&pair))
+          ABORT(r);
+
+        if(r=nr_ice_candidate_pair_insert(&pcomp->stream->check_list,
+                                          pair))
+          ABORT(r);
+      }
+
+      pcand=TAILQ_NEXT(pcand,entry_comp);
+    }
+
+   done:
+    _status = 0;
+   abort:
+    return(_status);
+  }
+
 int nr_ice_component_pair_candidates(nr_ice_peer_ctx *pctx, nr_ice_component *lcomp,nr_ice_component *pcomp)
   {
-    nr_ice_candidate *lcand,*pcand;
-    nr_ice_cand_pair *pair=0;
+    nr_ice_candidate *lcand, *pcand;
     nr_ice_socket *isock;
     int r,_status;
-    char codeword[5];
 
     r_log(LOG_ICE,LOG_DEBUG,"Pairing candidates======");
+
     /* Create the candidate pairs */
     lcand=TAILQ_FIRST(&lcomp->candidates);
     while(lcand){
-      int was_paired = 0;
-
-      nr_ice_compute_codeword(lcand->label,strlen(lcand->label),codeword);
-      r_log(LOG_ICE,LOG_DEBUG,"Examining local candidate %s:%s",codeword,lcand->label);
-
-      switch(lcand->type){
-        case HOST:
-          break;
-        case SERVER_REFLEXIVE:
-        case PEER_REFLEXIVE:
-          /* Don't actually pair these candidates */
-          goto next_cand;
-          break;
-        case RELAYED:
-          break;
-        default:
-          assert(0);
-          ABORT(R_INTERNAL);
-          break;
+      if (lcand->state == NR_ICE_CAND_STATE_INITIALIZED) {
+        if ((r = nr_ice_component_pair_candidate(pctx, pcomp, lcand, 0)))
+          ABORT(r);
       }
 
-      /* PAIR with each peer*/
-      if(TAILQ_EMPTY(&pcomp->candidates)) {
-          /* can happen if our peer proposes no (or all bogus) candidates */
-          goto next_cand;
-      }
-      pcand=TAILQ_FIRST(&pcomp->candidates);
-      while(pcand){
-        /* Only pair peer candidates which have not yet been paired.
-           This allows "trickle ICE". (Not yet standardized, but
-           part of WebRTC).
-
-           TODO(ekr@rtfm.com): Add refernece to the spec when there
-           is one.
-         */
-        if (pcand->state == NR_ICE_CAND_PEER_CANDIDATE_UNPAIRED) {
-          nr_ice_compute_codeword(pcand->label,strlen(pcand->label),codeword);
-          r_log(LOG_ICE,LOG_DEBUG,"Examining peer candidate %s:%s",codeword,pcand->label);
-
-          if(r=nr_ice_candidate_pair_create(pctx,lcand,pcand,&pair))
-            ABORT(r);
-
-          if(r=nr_ice_candidate_pair_insert(&pcomp->stream->check_list,
-              pair))
-            ABORT(r);
-        }
-        else {
-          was_paired = 1;
-        }
-        pcand=TAILQ_NEXT(pcand,entry_comp);
-      }
-
-      if(!pair)
-        goto next_cand;
-
-    next_cand:
       lcand=TAILQ_NEXT(lcand,entry_comp);
     }
 
     /* Mark all peer candidates as paired */
     pcand=TAILQ_FIRST(&pcomp->candidates);
     while(pcand){
       pcand->state = NR_ICE_CAND_PEER_CANDIDATE_PAIRED;
 
--- a/media/mtransport/third_party/nICEr/src/ice/ice_component.h
+++ b/media/mtransport/third_party/nICEr/src/ice/ice_component.h
@@ -77,18 +77,19 @@ struct nr_ice_component_ {
   STAILQ_ENTRY(nr_ice_component_)entry;
 };
 
 typedef STAILQ_HEAD(nr_ice_component_head_,nr_ice_component_) nr_ice_component_head;
 
 int nr_ice_component_create(struct nr_ice_media_stream_ *stream, int component_id, nr_ice_component **componentp);
 int nr_ice_component_destroy(nr_ice_component **componentp);
 int nr_ice_component_initialize(struct nr_ice_ctx_ *ctx,nr_ice_component *component);
-int nr_ice_component_prune_candidates(nr_ice_ctx *ctx, nr_ice_component *comp);
-int nr_ice_component_pair_candidates(nr_ice_peer_ctx *pctx, nr_ice_component *lcomp,nr_ice_component *pcomp);
+int nr_ice_component_maybe_prune_candidate(nr_ice_ctx *ctx, nr_ice_component *comp, nr_ice_candidate *c1, int *was_pruned);
+int nr_ice_component_pair_candidate(nr_ice_peer_ctx *pctx, nr_ice_component *pcomp, nr_ice_candidate *lcand, int pair_all_remote);
+int nr_ice_component_pair_candidates(nr_ice_peer_ctx *pctx, nr_ice_component *lcomp, nr_ice_component *pcomp);
 int nr_ice_component_service_pre_answer_requests(nr_ice_peer_ctx *pctx, nr_ice_component *pcomp, char *username, int *serviced);
 int nr_ice_component_nominated_pair(nr_ice_component *comp, nr_ice_cand_pair *pair);
 int nr_ice_component_failed_pair(nr_ice_component *comp, nr_ice_cand_pair *pair);
 int nr_ice_component_select_pair(nr_ice_peer_ctx *pctx, nr_ice_component *comp);
 int nr_ice_component_set_failed(nr_ice_component *comp);
 int nr_ice_component_finalize(nr_ice_component *lcomp, nr_ice_component *rcomp);
 
 #ifdef __cplusplus
--- a/media/mtransport/third_party/nICEr/src/ice/ice_ctx.c
+++ b/media/mtransport/third_party/nICEr/src/ice/ice_ctx.c
@@ -59,16 +59,17 @@ static char *RCSSTRING __UNUSED__="$Id: 
 int LOG_ICE = 0;
 
 static int nr_ice_random_string(char *str, int len);
 static int nr_ice_fetch_stun_servers(int ct, nr_ice_stun_server **out);
 #ifdef USE_TURN
 static int nr_ice_fetch_turn_servers(int ct, nr_ice_turn_server **out);
 #endif /* USE_TURN */
 static void nr_ice_ctx_destroy_cb(NR_SOCKET s, int how, void *cb_arg);
+static int nr_ice_ctx_pair_new_trickle_candidates(nr_ice_ctx *ctx, nr_ice_candidate *cand);
 
 int nr_ice_fetch_stun_servers(int ct, nr_ice_stun_server **out)
   {
     int r,_status;
     nr_ice_stun_server *servers = 0;
     int i;
     NR_registry child;
     char *addr=0;
@@ -426,48 +427,96 @@ static void nr_ice_ctx_destroy_cb(NR_SOC
   }
 
 int nr_ice_ctx_destroy(nr_ice_ctx **ctxp)
   {
     if(!ctxp || !*ctxp)
       return(0);
 
     (*ctxp)->done_cb=0;
+    (*ctxp)->trickle_cb=0;
 
     NR_ASYNC_SCHEDULE(nr_ice_ctx_destroy_cb,*ctxp);
 
     *ctxp=0;
 
     return(0);
   }
 
 void nr_ice_initialize_finished_cb(NR_SOCKET s, int h, void *cb_arg)
   {
-    nr_ice_ctx *ctx=cb_arg;
+    int r,_status;
+    nr_ice_candidate *cand=cb_arg;
+    nr_ice_ctx *ctx;
+
+
+    assert(cb_arg);
+    if (!cb_arg)
+      return;
+    ctx = cand->ctx;
+
+    ctx->uninitialized_candidates--;
+
+    if (cand->state == NR_ICE_CAND_STATE_INITIALIZED) {
+      int was_pruned = 0;
 
-/*    r_log(LOG_ICE,LOG_DEBUG,"ICE(%s): Candidate %s %s",ctx->label,
-      cand->label, cand->state==NR_ICE_CAND_STATE_INITIALIZED?"INITIALIZED":"FAILED");
-*/
-    ctx->uninitialized_candidates--;
+      if (r=nr_ice_component_maybe_prune_candidate(ctx, cand->component,
+                                                   cand, &was_pruned)) {
+          r_log(LOG_ICE, LOG_NOTICE, "ICE(%s): Problem pruning candidates",ctx->label);
+      }
+
+      /* If we are initialized, the candidate wasn't pruned,
+         and we have a trickle ICE callback fire the callback */
+      if (ctx->trickle_cb && !was_pruned) {
+        ctx->trickle_cb(ctx->trickle_cb_arg, ctx, cand->stream, cand->component_id, cand);
+
+        if (r==nr_ice_ctx_pair_new_trickle_candidates(ctx, cand)) {
+          r_log(LOG_ICE,LOG_ERR, "ICE(%s): All could not pair new trickle candidate",ctx->label);
+          /* But continue */
+        }
+      }
+    }
 
     if(ctx->uninitialized_candidates==0){
       r_log(LOG_ICE,LOG_DEBUG,"ICE(%s): All candidates initialized",ctx->label);
       ctx->state=NR_ICE_STATE_INITIALIZED;
       if (ctx->done_cb) {
         ctx->done_cb(0,0,ctx->cb_arg);
       }
       else {
         r_log(LOG_ICE,LOG_DEBUG,"ICE(%s): No done_cb. We were probably destroyed.",ctx->label);
       }
     }
     else {
       r_log(LOG_ICE,LOG_DEBUG,"ICE(%s): Waiting for %d candidates to be initialized",ctx->label, ctx->uninitialized_candidates);
     }
   }
 
+static int nr_ice_ctx_pair_new_trickle_candidates(nr_ice_ctx *ctx, nr_ice_candidate *cand)
+  {
+    int r,_status;
+    nr_ice_peer_ctx *pctx;
+
+    pctx=STAILQ_FIRST(&ctx->peers);
+    while(pctx){
+      if (pctx->state == NR_ICE_PEER_STATE_PAIRED) {
+        r = nr_ice_peer_ctx_pair_new_trickle_candidate(ctx, pctx, cand);
+        if (r)
+          ABORT(r);
+      }
+
+      pctx=STAILQ_NEXT(pctx,entry);
+    }
+
+    _status=0;
+ abort:
+    return(_status);
+  }
+
+
 #define MAXADDRS 100 // Ridiculously high
 int nr_ice_initialize(nr_ice_ctx *ctx, NR_async_cb done_cb, void *cb_arg)
   {
     int r,_status;
     nr_ice_media_stream *stream;
     nr_local_addr addrs[MAXADDRS];
     int i,addr_ct;
 
@@ -684,8 +733,16 @@ int nr_ice_ctx_finalize(nr_ice_ctx *ctx,
       nr_ice_media_stream_finalize(lstr,rstr);
 
       lstr=STAILQ_NEXT(lstr,entry);
     }
 
     return(0);
   }
 
+
+int nr_ice_ctx_set_trickle_cb(nr_ice_ctx *ctx, nr_ice_trickle_candidate_cb cb, void *cb_arg)
+{
+  ctx->trickle_cb = cb;
+  ctx->trickle_cb_arg = cb_arg;
+
+  return 0;
+}
--- a/media/mtransport/third_party/nICEr/src/ice/ice_ctx.h
+++ b/media/mtransport/third_party/nICEr/src/ice/ice_ctx.h
@@ -84,16 +84,19 @@ typedef STAILQ_HEAD(nr_ice_foundation_he
 typedef TAILQ_HEAD(nr_ice_candidate_head_,nr_ice_candidate_) nr_ice_candidate_head;
 typedef TAILQ_HEAD(nr_ice_cand_pair_head_,nr_ice_cand_pair_) nr_ice_cand_pair_head;
 typedef struct nr_ice_component_ nr_ice_component;
 typedef struct nr_ice_media_stream_ nr_ice_media_stream;
 typedef struct nr_ice_ctx_ nr_ice_ctx;
 typedef struct nr_ice_peer_ctx_ nr_ice_peer_ctx;
 typedef struct nr_ice_candidate_ nr_ice_candidate;
 typedef struct nr_ice_cand_pair_ nr_ice_cand_pair;
+typedef void (*nr_ice_trickle_candidate_cb) (void *cb_arg,
+  nr_ice_ctx *ctx, nr_ice_media_stream *stream, int component_id,
+  nr_ice_candidate *candidate);
 
 #include "ice_socket.h"
 #include "ice_component.h"
 #include "ice_media_stream.h"
 #include "ice_candidate.h"
 #include "ice_candidate_pair.h"
 #include "ice_handler.h"
 #include "ice_peer_ctx.h"
@@ -139,16 +142,19 @@ struct nr_ice_ctx_ {
   UINT4 gather_rto;
   UINT4 stun_delay;
 
   nr_ice_peer_ctx_head peers;
   nr_ice_stun_id_head ids;
 
   NR_async_cb done_cb;
   void *cb_arg;
+
+  nr_ice_trickle_candidate_cb trickle_cb;
+  void *trickle_cb_arg;
 };
 
 int nr_ice_ctx_create(char *label, UINT4 flags, nr_ice_ctx **ctxp);
 #define NR_ICE_CTX_FLAGS_OFFERER                           1
 #define NR_ICE_CTX_FLAGS_ANSWERER                          (1<<1)
 #define NR_ICE_CTX_FLAGS_AGGRESSIVE_NOMINATION             (1<<2)
 #define NR_ICE_CTX_FLAGS_LITE                              (1<<3)
 
@@ -161,16 +167,19 @@ int nr_ice_get_global_attributes(nr_ice_
 int nr_ice_ctx_deliver_packet(nr_ice_ctx *ctx, nr_ice_component *comp, nr_transport_addr *source_addr, UCHAR *data, int len);
 int nr_ice_ctx_is_known_id(nr_ice_ctx *ctx, UCHAR id[12]);
 int nr_ice_ctx_remember_id(nr_ice_ctx *ctx, nr_stun_message *msg);
 int nr_ice_ctx_finalize(nr_ice_ctx *ctx, nr_ice_peer_ctx *pctx);
 int nr_ice_ctx_set_stun_servers(nr_ice_ctx *ctx,nr_ice_stun_server *servers, int ct);
 int nr_ice_ctx_set_turn_servers(nr_ice_ctx *ctx,nr_ice_turn_server *servers, int ct);
 int nr_ice_ctx_set_resolver(nr_ice_ctx *ctx, nr_resolver *resolver);
 int nr_ice_ctx_set_interface_prioritizer(nr_ice_ctx *ctx, nr_interface_prioritizer *prioritizer);
+int nr_ice_ctx_set_trickle_cb(nr_ice_ctx *ctx, nr_ice_trickle_candidate_cb cb, void *cb_arg);
+
+#define NR_ICE_MAX_ATTRIBUTE_SIZE 256
 
 extern int LOG_ICE;
 
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
 #endif
 
--- a/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.c
+++ b/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.c
@@ -135,69 +135,74 @@ int nr_ice_media_stream_initialize(nr_ic
       comp=STAILQ_NEXT(comp,entry);
     }
 
     _status=0;
   abort:
     return(_status);
   }
 
-#define MAX_ATTRIBUTE_SIZE 256
-
 int nr_ice_media_stream_get_attributes(nr_ice_media_stream *stream, char ***attrsp, int *attrctp)
   {
     int attrct=0;
     nr_ice_component *comp;
     char **attrs=0;
     int index=0;
+    nr_ice_candidate *cand;
     int r,_status;
 
     *attrctp=0;
 
     /* First find out how many attributes we need */
     comp=STAILQ_FIRST(&stream->components);
     while(comp){
       if (comp->state != NR_ICE_COMPONENT_DISABLED) {
-        if(r=nr_ice_component_prune_candidates(stream->ctx,comp))
-          ABORT(r);
+        cand = TAILQ_FIRST(&comp->candidates);
+        while(cand){
+          if (cand->state == NR_ICE_CAND_STATE_INITIALIZED) {
+            ++attrct;
+          }
 
-        attrct+=comp->candidate_ct;
+          cand = TAILQ_NEXT(cand, entry_comp);
+        }
       }
-
       comp=STAILQ_NEXT(comp,entry);
     }
 
     if(attrct < 1){
       r_log(LOG_ICE,LOG_WARNING,"ICE-STREAM(%s): Failed to find any components for stream",stream->label);
       ABORT(R_FAILED);
     }
 
     /* Make the array we'll need */
     if(!(attrs=RCALLOC(sizeof(char *)*attrct)))
       ABORT(R_NO_MEMORY);
     for(index=0;index<attrct;index++){
-      if(!(attrs[index]=RMALLOC(MAX_ATTRIBUTE_SIZE)))
+      if(!(attrs[index]=RMALLOC(NR_ICE_MAX_ATTRIBUTE_SIZE)))
         ABORT(R_NO_MEMORY);
     }
 
     index=0;
     /* Now format the attributes */
     comp=STAILQ_FIRST(&stream->components);
     while(comp){
       if (comp->state != NR_ICE_COMPONENT_DISABLED) {
         nr_ice_candidate *cand;
 
         cand=TAILQ_FIRST(&comp->candidates);
         while(cand){
-          assert(index < attrct);
+          if (cand->state == NR_ICE_CAND_STATE_INITIALIZED) {
+            assert(index < attrct);
+
 
-          if(r=nr_ice_format_candidate_attribute(cand, attrs[index],MAX_ATTRIBUTE_SIZE))
-            ABORT(r);
+            if(r=nr_ice_format_candidate_attribute(cand, attrs[index],NR_ICE_MAX_ATTRIBUTE_SIZE))
+              ABORT(r);
 
-          index++;
+            index++;
+          }
 
           cand=TAILQ_NEXT(cand,entry_comp);
         }
       }
       comp=STAILQ_NEXT(comp,entry);
     }
 
     *attrsp=attrs;
@@ -238,25 +243,27 @@ int nr_ice_media_stream_get_default_cand
 
     /* We have the component. Now find the "best" candidate, making
        use of the fact that more "reliable" candidate types have
        higher numbers. So, we sort by type and then priority within
        type
     */
     cand=TAILQ_FIRST(&comp->candidates);
     while(cand){
-      if (!best_cand) {
-        best_cand = cand;
-      }
-      else {
-        if (best_cand->type < cand->type) {
+      if (cand->state == NR_ICE_CAND_STATE_INITIALIZED) {
+        if (!best_cand) {
           best_cand = cand;
-        } else if (best_cand->type == cand->type) {
-          if (best_cand->priority < cand->priority)
+        }
+        else {
+          if (best_cand->type < cand->type) {
             best_cand = cand;
+          } else if (best_cand->type == cand->type) {
+            if (best_cand->priority < cand->priority)
+              best_cand = cand;
+          }
         }
       }
 
       cand=TAILQ_NEXT(cand,entry_comp);
     }
 
     /* No candidates */
     if (!best_cand)
@@ -806,16 +813,31 @@ int nr_ice_media_stream_finalize(nr_ice_
       if(rcomp){
         rcomp=STAILQ_NEXT(rcomp,entry);
       }
     }
 
     return(0);
   }
 
+int nr_ice_media_stream_pair_new_trickle_candidate(nr_ice_peer_ctx *pctx, nr_ice_media_stream *pstream, nr_ice_candidate *cand)
+  {
+    int r,_status;
+    nr_ice_component *comp;
+
+    if ((r=nr_ice_media_stream_find_component(pstream, cand->component_id, &comp)))
+      ABORT(R_NOT_FOUND);
+
+    if (r=nr_ice_component_pair_candidate(pctx, comp, cand, 1))
+      ABORT(r);
+
+    _status=0;
+ abort:
+    return(_status);
+  }
 
 int nr_ice_media_stream_disable_component(nr_ice_media_stream *stream, int component_id)
   {
     int r,_status;
     nr_ice_component *comp;
 
     if (stream->ice_state != NR_ICE_MEDIA_STREAM_UNPAIRED)
       ABORT(R_FAILED);
--- a/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.h
+++ b/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.h
@@ -90,15 +90,15 @@ int nr_ice_media_stream_set_state(nr_ice
 int nr_ice_media_stream_get_best_candidate(nr_ice_media_stream *str, int component, nr_ice_candidate **candp);
 int nr_ice_media_stream_send(nr_ice_peer_ctx *pctx, nr_ice_media_stream *str, int component, UCHAR *data, int len);
 int nr_ice_media_stream_get_active(nr_ice_peer_ctx *pctx, nr_ice_media_stream *str, int component, nr_ice_candidate **local, nr_ice_candidate **remote);
 int nr_ice_media_stream_find_component(nr_ice_media_stream *str, int comp_id, nr_ice_component **compp);
 int nr_ice_media_stream_addrs(nr_ice_peer_ctx *pctx, nr_ice_media_stream *str, int component, nr_transport_addr *local, nr_transport_addr *remote);
 int
 nr_ice_peer_ctx_parse_media_stream_attribute(nr_ice_peer_ctx *pctx, nr_ice_media_stream *stream, char *attr);
 int nr_ice_media_stream_disable_component(nr_ice_media_stream *stream, int component_id);
-
+int nr_ice_media_stream_pair_new_trickle_candidate(nr_ice_peer_ctx *pctx, nr_ice_media_stream *pstream, nr_ice_candidate *cand);
 
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
 #endif
 
--- a/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.c
+++ b/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.c
@@ -51,16 +51,18 @@ static int nr_ice_ctx_parse_candidate(nr
 int nr_ice_peer_ctx_create(nr_ice_ctx *ctx, nr_ice_handler *handler,char *label, nr_ice_peer_ctx **pctxp)
   {
     int r,_status;
     nr_ice_peer_ctx *pctx=0;
 
     if(!(pctx=RCALLOC(sizeof(nr_ice_peer_ctx))))
       ABORT(R_NO_MEMORY);
 
+    pctx->state = NR_ICE_PEER_STATE_UNPAIRED;
+
     if(!(pctx->label=r_strdup(label)))
       ABORT(R_NO_MEMORY);
 
     pctx->ctx=ctx;
     pctx->handler=handler;
 
     /* Decide controlling vs. controlled */
     if(ctx->flags & NR_ICE_CTX_FLAGS_LITE){
@@ -252,35 +254,24 @@ int nr_ice_peer_ctx_find_pstream(nr_ice_
 
     _status=0;
  abort:
     return(_status);
   }
 
 int nr_ice_peer_ctx_parse_trickle_candidate(nr_ice_peer_ctx *pctx, nr_ice_media_stream *stream, char *candidate)
   {
-    /* First need to find the stream. Because we don't have forward pointers,
-       iterate through all the peer streams to find one that matches us */
     nr_ice_media_stream *pstream;
     int r,_status;
     int needs_pairing = 0;
 
     r_log(LOG_ICE,LOG_ERR,"ICE(%s): peer (%s) parsing trickle ICE candidate %s",pctx->ctx->label,pctx->label,candidate);
-
-    pstream=STAILQ_FIRST(&pctx->peer_streams);
-    while(pstream) {
-      if (pstream->local_stream == stream)
-        break;
-
-      pstream = STAILQ_NEXT(pstream, entry);
-    }
-    if (!pstream) {
-      r_log(LOG_ICE,LOG_ERR,"ICE(%s): peer (%s) has no stream matching stream %s",pctx->ctx->label,pctx->label,stream->label);
-      ABORT(R_NOT_FOUND);
-    }
+    r = nr_ice_peer_ctx_find_pstream(pctx, stream, &pstream);
+    if (r)
+      ABORT(r);
 
     switch(pstream->ice_state) {
       case NR_ICE_MEDIA_STREAM_UNPAIRED:
         break;
       case NR_ICE_MEDIA_STREAM_CHECKS_FROZEN:
       case NR_ICE_MEDIA_STREAM_CHECKS_ACTIVE:
         needs_pairing = 1;
         break;
@@ -349,27 +340,46 @@ int nr_ice_peer_ctx_pair_candidates(nr_i
     while(stream){
       if(r=nr_ice_media_stream_pair_candidates(pctx, stream->local_stream,
         stream))
         ABORT(r);
 
       stream=STAILQ_NEXT(stream,entry);
     }
 
+    pctx->state = NR_ICE_PEER_STATE_PAIRED;
+
     _status=0;
   abort:
     return(_status);
   }
 
+
+int nr_ice_peer_ctx_pair_new_trickle_candidate(nr_ice_ctx *ctx, nr_ice_peer_ctx *pctx, nr_ice_candidate *cand)
+  {
+    int r, _status;
+    nr_ice_media_stream *pstream;
+
+    r_log(LOG_ICE,LOG_ERR,"ICE(%s): peer (%s) pairing local trickle ICE candidate %s",pctx->ctx->label,pctx->label,cand->label);
+    if ((r = nr_ice_peer_ctx_find_pstream(pctx, cand->stream, &pstream)))
+      ABORT(r);
+
+    if ((r = nr_ice_media_stream_pair_new_trickle_candidate(pctx, pstream, cand)))
+      ABORT(r);
+
+    _status=0;
+ abort:
+    return _status;
+  }
+
 int nr_ice_peer_ctx_disable_component(nr_ice_peer_ctx *pctx, nr_ice_media_stream *lstream, int component_id)
   {
     int r, _status;
     nr_ice_media_stream *pstream;
     nr_ice_component *component;
-    int j;
 
     if ((r=nr_ice_peer_ctx_find_pstream(pctx, lstream, &pstream)))
       ABORT(r);
 
     /* We shouldn't be calling this after we have started pairing */
     if (pstream->ice_state != NR_ICE_MEDIA_STREAM_UNPAIRED)
       ABORT(R_FAILED);
 
@@ -538,17 +548,16 @@ static void nr_ice_peer_ctx_fire_done(NR
     pctx->done_cb_timer=0;
 
     /* Fire the handler callback to say we're done */
     if (pctx->handler) {
       pctx->handler->vtbl->ice_completed(pctx->handler->obj, pctx);
     }
   }
 
-
 /* OK, a stream just went ready. Examine all the streams to see if we're
    maybe miraculously done */
 int nr_ice_peer_ctx_stream_done(nr_ice_peer_ctx *pctx, nr_ice_media_stream *stream)
   {
     int _status;
     nr_ice_media_stream *str;
     int failed=0;
     int succeeded=0;
--- a/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.h
+++ b/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.h
@@ -35,16 +35,20 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 #ifndef _ice_peer_ctx_h
 #define _ice_peer_ctx_h
 #ifdef __cplusplus
 using namespace std;
 extern "C" {
 #endif /* __cplusplus */
 
 struct nr_ice_peer_ctx_ {
+  int state;
+#define NR_ICE_PEER_STATE_UNPAIRED 1
+#define NR_ICE_PEER_STATE_PAIRED   2
+
   char *label;
   nr_ice_ctx *ctx;
   nr_ice_handler *handler;
 
   UCHAR controlling; /* 1 for controlling, 0 for controlled */
   UINT8 tiebreaker;
 
   char *peer_ufrag;
@@ -75,14 +79,15 @@ int nr_ice_peer_ctx_parse_global_attribu
 int nr_ice_peer_ctx_start_checks(nr_ice_peer_ctx *pctx);
 int nr_ice_peer_ctx_start_checks2(nr_ice_peer_ctx *pctx, int allow_non_first);
 int nr_ice_peer_ctx_dump_state(nr_ice_peer_ctx *pctx,FILE *out);
 int nr_ice_peer_ctx_log_state(nr_ice_peer_ctx *pctx);
 int nr_ice_peer_ctx_stream_done(nr_ice_peer_ctx *pctx, nr_ice_media_stream *stream);
 int nr_ice_peer_ctx_find_component(nr_ice_peer_ctx *pctx, nr_ice_media_stream *str, int component_id, nr_ice_component **compp);
 int nr_ice_peer_ctx_deliver_packet_maybe(nr_ice_peer_ctx *pctx, nr_ice_component *comp, nr_transport_addr *source_addr, UCHAR *data, int len);
 int nr_ice_peer_ctx_disable_component(nr_ice_peer_ctx *pctx, nr_ice_media_stream *lstream, int component_id);
+int nr_ice_peer_ctx_pair_new_trickle_candidate(nr_ice_ctx *ctx, nr_ice_peer_ctx *pctx, nr_ice_candidate *cand);
 
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
 #endif
 
--- a/media/webrtc/signaling/include/CC_CallInfo.h
+++ b/media/webrtc/signaling/include/CC_CallInfo.h
@@ -357,10 +357,15 @@ namespace CSF
          */
         virtual MediaStreamTable* getMediaStreams() const = 0;
 
         /**
           Get the current operation's timecard (if any), and assume ownership
           of its memory.
          */
         virtual Timecard *takeTimecard() = 0;
+
+	/**
+          Get the latest candidate.
+	*/
+	virtual std::string getCandidate() = 0;
     };
 };
--- a/media/webrtc/signaling/src/common/Wrapper.h
+++ b/media/webrtc/signaling/src/common/Wrapper.h
@@ -147,16 +147,17 @@ public:
 		handleMap.clear();
 	}
 };
 
 #define CSF_DECLARE_WRAP(classname, handletype) \
 	public: \
 		static classname ## Ptr wrap(handletype handle); \
 		static void reset(); \
+                static void release(handletype handle); \
 	private: \
 		friend class Wrapper<classname>; \
 		typedef classname ## Ptr Ptr; \
 		typedef handletype Handle; \
 		static Wrapper<classname>& getWrapper() { \
 			static Wrapper<classname> wrapper; \
 			return wrapper; \
 		}
@@ -164,10 +165,13 @@ public:
 #define CSF_IMPLEMENT_WRAP(classname, handletype) \
 	classname ## Ptr classname::wrap(handletype handle) \
 	{ \
 		return getWrapper().wrap(handle); \
 	} \
 	void classname::reset() \
 	{ \
 		getWrapper().reset(); \
-	}
-
+	} \
+        void classname::release(handletype handle) \
+        { \
+                getWrapper().release(handle); \
+        }
--- a/media/webrtc/signaling/src/media/VcmSIPCCBinding.cpp
+++ b/media/webrtc/signaling/src/media/VcmSIPCCBinding.cpp
@@ -29,16 +29,17 @@
 #include <stdio.h>
 #include <ssl.h>
 #include <sslproto.h>
 #include <algorithm>
 
 extern "C" {
 #include "ccsdp.h"
 #include "vcm.h"
+#include "cc_call_feature.h"
 #include "cip_mmgr_mediadefinitions.h"
 #include "cip_Sipcc_CodecMask.h"
 
 extern void lsm_start_multipart_tone_timer (vcm_tones_t tone,
                                             uint32_t delay,
                                             cc_call_handle_t callId);
 extern void lsm_start_continuous_tone_timer (vcm_tones_t tone,
                                              uint32_t delay,
@@ -63,16 +64,17 @@ typedef enum {
 /* static */
 
 using namespace CSF;
 
 VcmSIPCCBinding * VcmSIPCCBinding::gSelf = NULL;
 int VcmSIPCCBinding::gAudioCodecMask = 0;
 int VcmSIPCCBinding::gVideoCodecMask = 0;
 nsIThread *VcmSIPCCBinding::gMainThread = NULL;
+nsIEventTarget *VcmSIPCCBinding::gSTSThread = NULL;
 
 static mozilla::RefPtr<TransportFlow> vcmCreateTransportFlow(
     sipcc::PeerConnectionImpl *pc,
     int level,
     bool rtcp,
     sdp_setup_type_e setup_type,
     const char *fingerprint_alg,
     const char *fingerprint);
@@ -97,20 +99,68 @@ static mozilla::RefPtr<TransportFlow> vc
 
 VcmSIPCCBinding::VcmSIPCCBinding ()
   : streamObserver(NULL)
 {
     delete gSelf;//delete is NULL safe, so I don't need to check if it's NULL
     gSelf = this;
 }
 
+class VcmIceOpaque : public NrIceOpaque {
+ public:
+  VcmIceOpaque(cc_streamid_t stream_id,
+               cc_call_handle_t call_handle,
+               uint16_t level) :
+      stream_id_(stream_id),
+      call_handle_(call_handle),
+      level_(level) {}
+
+  virtual ~VcmIceOpaque() {}
+
+  cc_streamid_t stream_id_;
+  cc_call_handle_t call_handle_;
+  uint16_t level_;
+};
+
+
 VcmSIPCCBinding::~VcmSIPCCBinding ()
 {
     assert(gSelf);
     gSelf = NULL;
+    // In case we're torn down while STS is still running,
+    // we try to dispatch to STS to disconnect all of the
+    // ICE signals. If STS is no longer running, this will
+    // harmlessly fail.
+    SyncRunnable::DispatchToThread(
+      gSTSThread,
+      WrapRunnable(this, &VcmSIPCCBinding::disconnect_all),
+      true);
+}
+
+void VcmSIPCCBinding::CandidateReady(NrIceMediaStream* stream,
+                                     const std::string& candidate)
+{
+    // This is called on the STS thread
+    NrIceOpaque *opaque = stream->opaque();
+    MOZ_ASSERT(opaque);
+
+    VcmIceOpaque *vcm_opaque = static_cast<VcmIceOpaque *>(opaque);
+    CSFLogDebug(logTag, "Candidate ready on call %u, level %u",
+                vcm_opaque->call_handle_, vcm_opaque->level_);
+
+    char *candidate_tmp = (char *)malloc(candidate.size() + 1);
+    if (!candidate_tmp)
+	return;
+    sstrncpy(candidate_tmp, candidate.c_str(), candidate.size() + 1);
+    // Send a message to the GSM thread.
+    CC_CallFeature_FoundICECandidate(vcm_opaque->call_handle_,
+				     candidate_tmp,
+				     NULL,
+				     vcm_opaque->level_,
+				     NULL);
 }
 
 void VcmSIPCCBinding::setStreamObserver(StreamObserver* obs)
 {
 	streamObserver = obs;
 }
 
 /* static */
@@ -158,21 +208,33 @@ int VcmSIPCCBinding::getVideoCodecs()
   return VcmSIPCCBinding::gVideoCodecMask;
 }
 
 void VcmSIPCCBinding::setMainThread(nsIThread *thread)
 {
   gMainThread = thread;
 }
 
+void VcmSIPCCBinding::setSTSThread(nsIEventTarget *thread)
+{
+  gSTSThread = thread;
+}
+
 nsIThread* VcmSIPCCBinding::getMainThread()
 {
   return gMainThread;
 }
 
+void VcmSIPCCBinding::connectCandidateSignal(
+    NrIceMediaStream *stream)
+{
+  stream->SignalCandidate.connect(gSelf,
+                                  &VcmSIPCCBinding::CandidateReady);
+}
+
 /* static */
 AudioTermination * VcmSIPCCBinding::getAudioTermination()
 {
     // commenting as part of media provider removal
     return NULL;
 }
 
 /* static */
@@ -457,16 +519,22 @@ static short vcmRxAllocICE_m(cc_mcapid_t
   CSFLogDebug( logTag, "%s: Getting stream %d", __FUNCTION__, level);
   mozilla::RefPtr<NrIceMediaStream> stream = pc.impl()->media()->
     ice_media_stream(level-1);
   MOZ_ASSERT(stream);
   if (!stream) {
     return VCM_ERROR;
   }
 
+  // Set the opaque so we can correlate events.
+  stream->SetOpaque(new VcmIceOpaque(stream_id, call_handle, level));
+
+  // Attach ourself to the candidate signal.
+  VcmSIPCCBinding::connectCandidateSignal(stream);
+
   std::vector<std::string> candidates = stream->GetCandidates();
   CSFLogDebug( logTag, "%s: Got %lu candidates", __FUNCTION__, candidates.size());
 
   std::string default_addr;
   int default_port;
 
   nsresult res = stream->GetDefaultCandidate(1, &default_addr, &default_port);
   MOZ_ASSERT(NS_SUCCEEDED(res));
@@ -728,16 +796,17 @@ static short vcmSetIceCandidate_m(const 
   }
 
   // TODO(ekr@rtfm.com): generate an error if the parse
   // fails. Bug 847449.
 
   return 0;
 }
 
+
 /* Set ice candidate for trickle ICE.
  *
  * This is a thunk to vcmSetIceCandidate_m
  *
  *  @param[in]  peerconnection - the peerconnection in use
  *  @param[in]  icecandidate - the icecandidate
  *  @param[in]  level - the m line level
  *
@@ -787,17 +856,16 @@ static short vcmStartIceChecks_m(const c
   if (!NS_SUCCEEDED(rv)) {
     CSFLogError( logTag, "%s(): Could not dispatch to ICE thread", __FUNCTION__);
     return VCM_ERROR;
   }
 
   return 0;
 }
 
-
 /* Start ICE checks
  *
  * This is a thunk to vcmStartIceChecks_m
  *
  *  @param[in]  peerconnection - the peerconnection in use
  *  @return 0 success, error failure
  */
 short vcmStartIceChecks(const char *peerconnection, cc_boolean isControlling)
--- a/media/webrtc/signaling/src/media/VcmSIPCCBinding.h
+++ b/media/webrtc/signaling/src/media/VcmSIPCCBinding.h
@@ -5,17 +5,24 @@
 #ifndef _CSF_VCM_SIPCC_BINDING_H_
 #define _CSF_VCM_SIPCC_BINDING_H_
 
 extern "C"
 {
 #include "ccapi_types.h"
 }
 
+#include "sigslot.h"
+
 class nsIThread;
+class nsIEventTarget;
+
+namespace mozilla {
+    class NrIceMediaStream;
+};
 
 namespace CSF
 {
     class AudioTermination;
     class VideoTermination;
     class AudioControl;
     class VideoControl;
     class MediaProvider;
@@ -24,23 +31,22 @@ namespace CSF
     class StreamObserver
     {
     public:
     	virtual void registerStream(cc_call_handle_t call, int streamId, bool isVideo) = 0;
     	virtual void deregisterStream(cc_call_handle_t call, int streamId) = 0;
     	virtual void dtmfBurst(int digit, int direction, int duration) = 0;
     	virtual void sendIFrame(cc_call_handle_t call) = 0;
     };
-    class VcmSIPCCBinding
+    class VcmSIPCCBinding : public sigslot::has_slots<>
     {
     public:
         VcmSIPCCBinding ();
         virtual ~VcmSIPCCBinding();
 
-
         // The getter is only for use by the vcm_* impl functions.
         void setStreamObserver(StreamObserver*);
         static StreamObserver* getStreamObserver();
 
         static AudioTermination * getAudioTermination();
         static VideoTermination * getVideoTermination();
 
         static AudioControl * getAudioControl();
@@ -53,21 +59,29 @@ namespace CSF
         static void setVideoCodecs(int codecMask);
 
         static int getAudioCodecs();
         static int getVideoCodecs();
 
 	static void setMainThread(nsIThread *thread);
 	static nsIThread *getMainThread();
 
+	static void setSTSThread(nsIEventTarget *thread);
+
+	static void connectCandidateSignal(mozilla::NrIceMediaStream* stream);
+
     private:
+	void CandidateReady(mozilla::NrIceMediaStream* stream,
+			    const std::string& candidate);
+
         static VcmSIPCCBinding * gSelf;
         StreamObserver* streamObserver;
         MediaProviderObserver *mediaProviderObserver;
         static int gAudioCodecMask;
         static int gVideoCodecMask;
 	static nsIThread *gMainThread;
+	static nsIEventTarget *gSTSThread;
     };
 }
 
 #endif
 
 
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.cpp
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.cpp
@@ -117,27 +117,30 @@ static void thread_ended_dispatcher(thre
     CSFLogError( logTag, "%s(): Could not dispatch to main thread", __FUNCTION__);
   }
 }
 
 static void join_waiter() {
   NS_ProcessPendingEvents(PeerConnectionCtx::gMainThread);
 }
 
-nsresult PeerConnectionCtx::InitializeGlobal(nsIThread *mainThread) {
+nsresult PeerConnectionCtx::InitializeGlobal(nsIThread *mainThread,
+  nsIEventTarget* stsThread) {
   if (!gMainThread) {
     gMainThread = mainThread;
     CSF::VcmSIPCCBinding::setMainThread(gMainThread);
     init_thread_monitor(&thread_ended_dispatcher, &join_waiter);
   } else {
 #ifdef MOZILLA_INTERNAL_API
     MOZ_ASSERT(gMainThread == mainThread);
 #endif
   }
 
+  CSF::VcmSIPCCBinding::setSTSThread(stsThread);
+
   nsresult res;
 
 #ifdef MOZILLA_INTERNAL_API
   // This check fails on the unit tests because they do not
   // have the right thread behavior.
   bool on;
   res = gMainThread->IsOnCurrentThread(&on);
   NS_ENSURE_SUCCESS(res, res);
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.h
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.h
@@ -29,17 +29,17 @@ namespace sipcc {
 
 // A class to hold some of the singleton objects we need:
 // * The global PeerConnectionImpl table and its associated lock.
 // * Currently SIPCC only allows a single stack instance to exist in a process
 //   at once. This class implements a singleton object that wraps that.
 // * The observer class that demuxes events onto individual PCs.
 class PeerConnectionCtx : public CSF::CC_Observer {
  public:
-  static nsresult InitializeGlobal(nsIThread *mainThread);
+  static nsresult InitializeGlobal(nsIThread *mainThread, nsIEventTarget *stsThread);
   static PeerConnectionCtx* GetInstance();
   static bool isActive();
   static void Destroy();
 
   // Implementations of CC_Observer methods
   virtual void onDeviceEvent(ccapi_device_event_e deviceEvent, CSF::CC_DevicePtr device, CSF::CC_DeviceInfoPtr info);
   virtual void onFeatureEvent(ccapi_device_event_e deviceEvent, CSF::CC_DevicePtr device, CSF::CC_FeatureInfoPtr feature_info) {}
   virtual void onLineEvent(ccapi_line_event_e lineEvent, CSF::CC_LinePtr line, CSF::CC_LineInfoPtr info) {}
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp
@@ -1,13 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <string>
+#include <cstdlib>
+#include <cerrno>
 
 #include "base/histogram.h"
 #include "vcm.h"
 #include "CSFLog.h"
 #include "timecard.h"
 #include "ccapi_call_info.h"
 #include "CC_SIPCCCallInfo.h"
 #include "ccapi_device_info.h"
@@ -134,27 +136,30 @@ public:
   PeerConnectionObserverDispatch(CSF::CC_CallInfoPtr aInfo,
                                  nsRefPtr<PeerConnectionImpl> aPC,
                                  IPeerConnectionObserver* aObserver)
       : mPC(aPC),
         mObserver(aObserver),
         mCode(static_cast<PeerConnectionImpl::Error>(aInfo->getStatusCode())),
         mReason(aInfo->getStatus()),
         mSdpStr(),
+	mCandidateStr(),
         mCallState(aInfo->getCallState()),
         mFsmState(aInfo->getFsmState()),
         mStateStr(aInfo->callStateToString(mCallState)),
         mFsmStateStr(aInfo->fsmStateToString(mFsmState)) {
     if (mCallState == REMOTESTREAMADD) {
       MediaStreamTable *streams = NULL;
       streams = aInfo->getMediaStreams();
       mRemoteStream = mPC->media()->GetRemoteStream(streams->media_stream_id);
       MOZ_ASSERT(mRemoteStream);
-    }
-    if ((mCallState == CREATEOFFERSUCCESS) || (mCallState == CREATEANSWERSUCCESS)) {
+    } else if (mCallState == FOUNDICECANDIDATE) {
+	mCandidateStr = aInfo->getCandidate();
+    } else if ((mCallState == CREATEOFFERSUCCESS) ||
+	       (mCallState == CREATEANSWERSUCCESS)) {
         mSdpStr = aInfo->getSDP();
     }
   }
 
   ~PeerConnectionObserverDispatch(){}
 
 #ifdef MOZILLA_INTERNAL_API
   class TracksAvailableCallback : public DOMMediaStream::OnTracksAvailableCallback
@@ -274,16 +279,55 @@ public:
       case ADDICECANDIDATE:
         mObserver->OnAddIceCandidateSuccess();
         break;
 
       case ADDICECANDIDATEERROR:
         mObserver->OnAddIceCandidateError(mCode, mReason.c_str());
         break;
 
+      case FOUNDICECANDIDATE:
+        {
+            size_t end_of_level = mCandidateStr.find('\t');
+            if (end_of_level == std::string::npos) {
+                MOZ_ASSERT(false);
+                return NS_OK;
+            }
+            std::string level = mCandidateStr.substr(0, end_of_level);
+            if (!level.size()) {
+                MOZ_ASSERT(false);
+                return NS_OK;
+            }
+            char *endptr;
+            errno = 0;
+            unsigned long level_long =
+                strtoul(level.c_str(), &endptr, 10);
+            if (errno || *endptr != 0 || level_long > 65535) {
+                /* Conversion failure */
+                MOZ_ASSERT(false);
+                return NS_OK;
+            }
+            size_t end_of_mid = mCandidateStr.find('\t', end_of_level + 1);
+            if (end_of_mid == std::string::npos) {
+                MOZ_ASSERT(false);
+                return NS_OK;
+            }
+
+            std::string mid = mCandidateStr.substr(end_of_level + 1,
+                                                   end_of_mid - (end_of_level + 1));
+
+            std::string candidate = mCandidateStr.substr(end_of_mid + 1);
+
+
+            mObserver->OnIceCandidate(
+                level_long & 0xffff,
+                mid.c_str(),
+                candidate.c_str());
+        }
+        break;
       case REMOTESTREAMADD:
         {
           DOMMediaStream* stream = nullptr;
 
           if (!mRemoteStream) {
             CSFLogError(logTag, "%s: GetRemoteStream returned NULL", __FUNCTION__);
           } else {
             stream = mRemoteStream->GetMediaStream();
@@ -318,16 +362,17 @@ public:
   }
 
 private:
   nsRefPtr<PeerConnectionImpl> mPC;
   nsCOMPtr<IPeerConnectionObserver> mObserver;
   PeerConnectionImpl::Error mCode;
   std::string mReason;
   std::string mSdpStr;
+  std::string mCandidateStr;
   cc_call_state_t mCallState;
   fsmdef_states_t mFsmState;
   std::string mStateStr;
   std::string mFsmStateStr;
   nsRefPtr<RemoteSourceStreamInfo> mRemoteStream;
 };
 
 NS_IMPL_ISUPPORTS1(PeerConnectionImpl, IPeerConnection)
@@ -341,17 +386,19 @@ PeerConnectionImpl::PeerConnectionImpl()
   , mIceState(kIceGathering)
   , mPCObserver(NULL)
   , mWindow(NULL)
   , mIdentity(NULL)
   , mSTSThread(NULL)
   , mMedia(NULL)
   , mNumAudioStreams(0)
   , mNumVideoStreams(0)
-  , mHaveDataStream(false) {
+  , mHaveDataStream(false)
+  , mTrickle(true) // TODO(ekr@rtfm.com): Use pref
+{
 #ifdef MOZILLA_INTERNAL_API
   MOZ_ASSERT(NS_IsMainThread());
 #endif
   CSFLogInfo(logTag, "%s: PeerConnectionImpl constructor for %s",
              __FUNCTION__, mHandle.c_str());
   STAMP_TIMECARD(mTimeCard, "Constructor Completed");
 }
 
@@ -601,17 +648,17 @@ PeerConnectionImpl::Initialize(IPeerConn
     handle_bin[4],
     handle_bin[5],
     handle_bin[6],
     handle_bin[7]);
 
   mHandle = hex;
 
   STAMP_TIMECARD(mTimeCard, "Initializing PC Ctx");
-  res = PeerConnectionCtx::InitializeGlobal(mThread);
+  res = PeerConnectionCtx::InitializeGlobal(mThread, mSTSThread);
   NS_ENSURE_SUCCESS(res, res);
 
   PeerConnectionCtx *pcctx = PeerConnectionCtx::GetInstance();
   MOZ_ASSERT(pcctx);
   STAMP_TIMECARD(mTimeCard, "Done Initializing PC Ctx");
 
   mCall = pcctx->createCall();
   if(!mCall.get()) {
@@ -1306,17 +1353,17 @@ PeerConnectionImpl::GetIceState(uint32_t
   *aState = mIceState;
   return NS_OK;
 }
 
 nsresult
 PeerConnectionImpl::CheckApiState(bool assert_ice_ready) const
 {
   PC_AUTO_ENTER_API_CALL_NO_CHECK();
-  PR_ASSERT(!assert_ice_ready || (mIceState != kIceGathering));
+  MOZ_ASSERT(mTrickle || !assert_ice_ready || (mIceState != kIceGathering));
 
   if (mReadyState == kClosed)
     return NS_ERROR_FAILURE;
   if (!mMedia)
     return NS_ERROR_FAILURE;
   return NS_OK;
 }
 
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h
@@ -381,16 +381,18 @@ private:
   int mNumAudioStreams;
   int mNumVideoStreams;
 
   bool mHaveDataStream;
 
   // Holder for error messages from parsing SDP
   std::vector<std::string> mSDPParseErrorMessages;
 
+  bool mTrickle;
+
 public:
   //these are temporary until the DataChannel Listen/Connect API is removed
   unsigned short listenPort;
   unsigned short connectPort;
   char *connectStr; // XXX ownership/free
 };
 
 // This is what is returned when you acquire on a handle
--- a/media/webrtc/signaling/src/sipcc/core/ccapp/CCProvider.h
+++ b/media/webrtc/signaling/src/sipcc/core/ccapp/CCProvider.h
@@ -102,16 +102,17 @@ typedef struct cc_call_info_t_{
     cc_call_log_t call_log;
     cc_boolean    audio_mute;
     cc_boolean    video_mute;
     cc_call_conference_Info_t call_conference;
     cc_string_t   sdp;
     unsigned int  media_stream_track_id;
     unsigned int  media_stream_id;
     cc_media_constraints_t* cc_constraints;
+    string_t      candidate;
     Timecard *    timecard;
 } session_data_t;
 
 typedef enum {
     NO_ACTION=0,
     RESET_ACTION,
     RESTART_ACTION,
     RE_REGISTER_ACTION,
--- a/media/webrtc/signaling/src/sipcc/core/ccapp/cc_call_feature.c
+++ b/media/webrtc/signaling/src/sipcc/core/ccapp/cc_call_feature.c
@@ -144,16 +144,20 @@ cc_return_t cc_invokeFeatureSDPMode(cc_c
     case CC_FEATURE_SETPEERCONNECTION:
     	callFeature.featData.ccData.info = strlib_malloc(data, strlen(data));
         callFeature.featData.ccData.info1 = NULL;
     	break;
     case CC_FEATURE_ADDICECANDIDATE:
     	callFeature.featData.ccData.info = strlib_malloc(data, strlen(data));
         callFeature.featData.ccData.info1 = strlib_malloc(data1, strlen(data1));
     	break;
+    case CC_FEATURE_FOUNDICECANDIDATE:
+    	callFeature.featData.ccData.info = strlib_malloc(data, strlen(data));
+        callFeature.featData.ccData.info1 = NULL;
+    	break;
 
     default:
         callFeature.featData.ccData.info = NULL;
         callFeature.featData.ccData.info1 = NULL;
     	break;
     }
 
     if (ccappTaskPostMsg(CCAPP_INVOKE_FEATURE, &callFeature, sizeof(session_feature_t), CCAPP_CCPROVIER) == CPR_FAILURE) {
@@ -369,16 +373,29 @@ cc_return_t CC_CallFeature_AddICECandida
     cc_media_constraints_t *constraints = NULL;
     CCAPP_DEBUG(DEB_L_C_F_PREFIX, DEB_L_C_F_PREFIX_ARGS(SIP_CC_PROV, GET_CALL_ID(call_handle),
             GET_LINE_ID(call_handle), __FUNCTION__));
 
     return cc_invokeFeatureSDPMode(call_handle, CC_FEATURE_ADDICECANDIDATE, JSEP_NO_ACTION,
                                    0, 0, NO_STREAM, (uint16_t)level, constraints, candidate, mid, tc);
 }
 
+cc_return_t CC_CallFeature_FoundICECandidate(cc_call_handle_t call_handle,
+					     const char* candidate,
+					     const char *mid,
+					     cc_level_t level,
+					     Timecard *tc) {
+    cc_media_constraints_t *constraints = NULL;
+    CCAPP_DEBUG(DEB_L_C_F_PREFIX, DEB_L_C_F_PREFIX_ARGS(SIP_CC_PROV, GET_CALL_ID(call_handle),
+            GET_LINE_ID(call_handle), __FUNCTION__));
+
+    return cc_invokeFeatureSDPMode(call_handle, CC_FEATURE_FOUNDICECANDIDATE, JSEP_NO_ACTION,
+                                   0, 0, NO_STREAM, (uint16_t)level, constraints, candidate, mid, tc);
+}
+
 /**
  * Initiate a speed dial.
  * @param call handle
  * @param callid call id
  * @param speed dial numbers.
  * @return SUCCESS or FAILURE
  */
 cc_return_t CC_CallFeature_speedDial(cc_call_handle_t call_handle, cc_sdp_direction_t video_pref, const string_t speed_dial_number) {
--- a/media/webrtc/signaling/src/sipcc/core/ccapp/ccapi_call_info.c
+++ b/media/webrtc/signaling/src/sipcc/core/ccapp/ccapi_call_info.c
@@ -743,16 +743,34 @@ cc_string_t CCAPI_CallInfo_getSDP(cc_cal
      CCAPP_DEBUG(DEB_F_PREFIX"returned %s", DEB_F_PREFIX_ARGS(SIP_CC_PROV, fname), data->sdp);
      return data->sdp;
   }
 
   return strlib_empty();
 }
 
 /**
+ * get candidate for trickle ICE
+ * @param handle - call handle
+ * @return sdp
+ */
+cc_string_t CCAPI_CallInfo_getCandidate(cc_callinfo_ref_t handle){
+  static const char *fname="CCAPI_CallInfo_getCandiate";
+  session_data_t *data = (session_data_t *)handle;
+  CCAPP_DEBUG(DEB_F_PREFIX"Entering", DEB_F_PREFIX_ARGS(SIP_CC_PROV, fname));
+
+  if (data){
+     CCAPP_DEBUG(DEB_F_PREFIX"returned %s", DEB_F_PREFIX_ARGS(SIP_CC_PROV, fname), data->candidate);
+     return data->candidate;
+  }
+
+  return strlib_empty();
+}
+
+/**
  * get status code from internal JSEP functions
  * @param handle - call handle
  * @return status code
  */
 cc_int32_t  CCAPI_CallInfo_getStatusCode(cc_callinfo_ref_t handle){
   static const char *fname="CCAPI_CallInfo_getStatusCode";
   session_data_t *data = (session_data_t *)handle;
   CCAPP_DEBUG(DEB_F_PREFIX"Entering", DEB_F_PREFIX_ARGS(SIP_CC_PROV, fname));
--- a/media/webrtc/signaling/src/sipcc/core/ccapp/ccprovider.c
+++ b/media/webrtc/signaling/src/sipcc/core/ccapp/ccprovider.c
@@ -705,16 +705,23 @@ processSessionEvent (line_t line_id, cal
            break;
          case CC_FEATURE_ADDICECANDIDATE:
            STAMP_TIMECARD(timecard, "Processing add candidate event");
            featdata.candidate.level = ccData.level;
            sstrncpy(featdata.candidate.candidate, data, sizeof(featdata.candidate.candidate)-1);
            sstrncpy(featdata.candidate.mid, data1, sizeof(featdata.candidate.mid)-1);
            cc_int_feature2(CC_MSG_ADDCANDIDATE, CC_SRC_UI, CC_SRC_GSM, call_id, (line_t)instance, CC_FEATURE_ADDICECANDIDATE, &featdata, timecard);
            break;
+         case CC_FEATURE_FOUNDICECANDIDATE:
+           STAMP_TIMECARD(timecard, "Processing found candidate event");
+           featdata.candidate.level = ccData.level;
+           sstrncpy(featdata.candidate.candidate, data, sizeof(featdata.candidate.candidate)-1);
+           sstrncpy(featdata.candidate.mid, data1, sizeof(featdata.candidate.mid)-1);
+           cc_int_feature2(CC_MSG_FOUNDCANDIDATE, CC_SRC_UI, CC_SRC_GSM, call_id, (line_t)instance, CC_FEATURE_FOUNDICECANDIDATE, &featdata, timecard);
+           break;
          case CC_FEATURE_DIALSTR:
              if (CheckAndGetAvailableLine(&line_id, &call_id) == TRUE) {
                  getDigits(data, digits, sizeof(digits));
                  if (strlen(digits) == 0) {
                     //if dial string is empty then go offhook
                     cc_offhook(CC_SRC_UI, call_id, line_id);
                  } else {
                  dp_int_init_dialing_data(line_id, call_id);
@@ -1056,17 +1063,18 @@ session_data_t * getDeepCopyOfSessionDat
            newData->orig_called_name =  strlib_copy(data->orig_called_name);
            newData->orig_called_number =  strlib_copy(data->orig_called_number);
            newData->last_redir_name =  strlib_copy(data->last_redir_name);
            newData->last_redir_number =  strlib_copy(data->last_redir_number);
            newData->plcd_name =  strlib_copy(data->plcd_name);
            newData->plcd_number =  strlib_copy(data->plcd_number);
            newData->status =  strlib_copy(data->status);
            newData->sdp = strlib_copy(data->sdp);
-
+	   newData->candidate = data->candidate ?
+	       strlib_copy(data->candidate) : strlib_empty();
            /* The timecard can have only one owner */
            newData->timecard = data->timecard;
            data->timecard = NULL;
 
            calllogger_copy_call_log(&newData->call_log, &data->call_log);
        } else {
            newData->ref_count = 1;
            newData->state = ONHOOK;
@@ -1080,16 +1088,17 @@ session_data_t * getDeepCopyOfSessionDat
            newData->orig_called_name = strlib_empty();
            newData->orig_called_number = strlib_empty();
            newData->last_redir_name = strlib_empty();
            newData->last_redir_number = strlib_empty();
            newData->plcd_name =  strlib_empty();
            newData->plcd_number =  strlib_empty();
            newData->status = strlib_empty();
            newData->sdp = strlib_empty();
+	   newData->candidate = strlib_empty();
            newData->timecard = NULL;
            calllogger_init_call_log(&newData->call_log);
        }
 
    }
    return newData;
 }
 
@@ -1127,16 +1136,19 @@ void cleanSessionData(session_data_t *da
         strlib_free(data->plcd_name);
         data->plcd_name = strlib_empty();
         strlib_free(data->plcd_number);
         data->plcd_number = strlib_empty();
         strlib_free(data->status);
         data->status = strlib_empty();
         strlib_free(data->sdp);
         data->sdp = strlib_empty();
+	if (data->candidate)
+	    strlib_free(data->candidate);
+	data->candidate = strlib_empty();
         data->timecard = NULL;
         calllogger_free_call_log(&data->call_log);
     }
 }
 
 /**
  *
  * CCApp Provider check for CONNECTED calls for preservation
@@ -1445,16 +1457,17 @@ static void ccappUpdateSessionData (sess
         if (sessUpd->eventID == CALL_NEWCALL ||
             sessUpd->eventID == CREATE_OFFER ||
             sessUpd->eventID == CREATE_ANSWER ||
             sessUpd->eventID == SET_LOCAL_DESC ||
             sessUpd->eventID == SET_REMOTE_DESC ||
             sessUpd->eventID == UPDATE_LOCAL_DESC ||
             sessUpd->eventID == UPDATE_REMOTE_DESC ||
             sessUpd->eventID == ICE_CANDIDATE_ADD ||
+            sessUpd->eventID == ICE_CANDIDATE_FOUND ||
             sessUpd->eventID == REMOTE_STREAM_ADD ) {
             data->attr = sessUpd->update.ccSessionUpd.data.state_data.attr;
             data->inst = sessUpd->update.ccSessionUpd.data.state_data.inst;
         }
         data->cause = sessUpd->update.ccSessionUpd.data.state_data.cause;
         data->clg_name = strlib_empty();
         data->clg_number =  strlib_empty();
         data->alt_number = strlib_empty();
@@ -1827,16 +1840,22 @@ static void ccappUpdateSessionData (sess
         break;
     case CREATE_OFFER:
     case CREATE_ANSWER:
     case SET_LOCAL_DESC:
     case SET_REMOTE_DESC:
     case UPDATE_LOCAL_DESC:
     case UPDATE_REMOTE_DESC:
     case ICE_CANDIDATE_ADD:
+    case ICE_CANDIDATE_FOUND:
+	if (sessUpd->update.ccSessionUpd.data.state_data.extra) {
+	    if (sessUpd->eventID == ICE_CANDIDATE_FOUND) {
+		data->candidate = sessUpd->update.ccSessionUpd.data.state_data.extra;
+	    }
+	}
         data->sdp = sessUpd->update.ccSessionUpd.data.state_data.sdp;
         /* Fall through to the next case... */
     case REMOTE_STREAM_ADD:
         data->timecard = sessUpd->update.ccSessionUpd.data.state_data.timecard;
         data->cause = sessUpd->update.ccSessionUpd.data.state_data.cause;
         data->state = sessUpd->update.ccSessionUpd.data.state_data.state;
         data->fsm_state =
             sessUpd->update.ccSessionUpd.data.state_data.fsm_state;
--- a/media/webrtc/signaling/src/sipcc/core/common/ui.c
+++ b/media/webrtc/signaling/src/sipcc/core/common/ui.c
@@ -1551,16 +1551,17 @@ ui_control_feature (line_t line_id, call
  */
 static void post_message_helper(group_call_event_t eventId,
                                 call_events event,
                                 fsmdef_states_t new_state,
                                 line_t nLine,
                                 callid_t nCallId,
                                 uint16_t call_instance_id,
                                 string_t sdp,
+				string_t extra,
                                 Timecard *timecard,
                                 pc_error error,
                                 const char *format,
                                 va_list args)
 {
     flex_string fs;
     session_update_t msg;
     memset( &msg, 0, sizeof(session_update_t));
@@ -1575,16 +1576,17 @@ static void post_message_helper(group_ca
     msg.sessionID = createSessionId(nLine, nCallId);
 
     msg.eventID = eventId;
     msg.update.ccSessionUpd.data.state_data.state = event;
     msg.update.ccSessionUpd.data.state_data.fsm_state = new_state;
     msg.update.ccSessionUpd.data.state_data.inst = call_instance_id;
     msg.update.ccSessionUpd.data.state_data.line_id = nLine;
     msg.update.ccSessionUpd.data.state_data.sdp = sdp;
+    msg.update.ccSessionUpd.data.state_data.extra = extra;
     msg.update.ccSessionUpd.data.state_data.cause = error;
     msg.update.ccSessionUpd.data.state_data.timecard = timecard;
 
     if (format) {
       flex_string_init(&fs);
       flex_string_vsprintf(&fs, format, args);
       msg.update.ccSessionUpd.data.state_data.reason_text =
         strlib_malloc(fs.buffer, -1);
@@ -1622,17 +1624,17 @@ void ui_create_offer(call_events event,
 
     TNP_DEBUG(DEB_L_C_F_PREFIX"state=%d call_instance=%d",
               DEB_L_C_F_PREFIX_ARGS(UI_API, nLine, nCallID, __FUNCTION__),
               event, call_instance_id);
 
 
     va_start(ap, format);
     post_message_helper(CREATE_OFFER, event, new_state, nLine, nCallID,
-                        call_instance_id, sdp, timecard, error, format, ap);
+                        call_instance_id, sdp, NULL, timecard, error, format, ap);
     va_end(ap);
 
     return;
 }
 
 /**
  *  Send data from createAnswer to the UI, can send success with SDP string
  *  or can send error
@@ -1650,17 +1652,17 @@ void ui_create_answer(call_events event,
                       const char *format, ...)
 {
     va_list ap;
     TNP_DEBUG(DEB_L_C_F_PREFIX"state=%d call_instance=%d",
               DEB_L_C_F_PREFIX_ARGS(UI_API, nLine, nCallID, __FUNCTION__), event, call_instance_id);
 
     va_start(ap, format);
     post_message_helper(CREATE_ANSWER, event, new_state, nLine, nCallID,
-                        call_instance_id, sdp, timecard, error, format, ap);
+                        call_instance_id, sdp, NULL, timecard, error, format, ap);
     va_end(ap);
 
     return;
 }
 
 /**
  *  Send data from setLocalDescription to the UI
  *
@@ -1678,17 +1680,17 @@ void ui_set_local_description(call_event
                               const char *format, ...)
 {
     va_list ap;
     TNP_DEBUG(DEB_L_C_F_PREFIX"state=%d call_instance=%d",
               DEB_L_C_F_PREFIX_ARGS(UI_API, nLine, nCallID, __FUNCTION__), event, call_instance_id);
 
     va_start(ap, format);
     post_message_helper(SET_LOCAL_DESC, event, new_state, nLine, nCallID,
-                        call_instance_id, sdp, timecard, error, format, ap);
+                        call_instance_id, sdp, NULL, timecard, error, format, ap);
     va_end(ap);
 
     return;
 }
 
 /**
  *  Send data from setRemoteDescription to the UI
  *
@@ -1706,17 +1708,17 @@ void ui_set_remote_description(call_even
                                const char *format, ...)
 {
     va_list ap;
     TNP_DEBUG(DEB_L_C_F_PREFIX"state=%d call_instance=%d",
               DEB_L_C_F_PREFIX_ARGS(UI_API, nLine, nCallID, __FUNCTION__), event, call_instance_id);
 
     va_start(ap, format);
     post_message_helper(SET_REMOTE_DESC, event, new_state, nLine, nCallID,
-                        call_instance_id, sdp, timecard, error, format, ap);
+                        call_instance_id, sdp, NULL, timecard, error, format, ap);
     va_end(ap);
 
     return;
 }
 
 /**
  *  Let PeerConnection know about an updated local session description
  *
@@ -1735,17 +1737,17 @@ void ui_update_local_description(call_ev
 {
     va_list ap;
     TNP_DEBUG(DEB_L_C_F_PREFIX"state=%d call_instance=%d",
               DEB_L_C_F_PREFIX_ARGS(UI_API, nLine, nCallID, __FUNCTION__),
               event, call_instance_id);
 
     va_start(ap, format);
     post_message_helper(UPDATE_LOCAL_DESC, event, new_state, nLine, nCallID,
-                        call_instance_id, sdp, timecard, error, format, ap);
+                        call_instance_id, sdp, NULL, timecard, error, format, ap);
     va_end(ap);
 
     return;
 }
 
 /**
  * Send data from addIceCandidate to the UI
  *
@@ -1763,17 +1765,45 @@ void ui_ice_candidate_add(call_events ev
                           const char *format, ...)
 {
     va_list ap;
     TNP_DEBUG(DEB_L_C_F_PREFIX"state=%d call_instance=%d",
               DEB_L_C_F_PREFIX_ARGS(UI_API, nLine, nCallID, __FUNCTION__), event, call_instance_id);
 
     va_start(ap, format);
     post_message_helper(ICE_CANDIDATE_ADD, event, new_state, nLine, nCallID,
-                        call_instance_id, sdp, timecard, error, format, ap);
+                        call_instance_id, sdp, NULL, timecard, error, format, ap);
+    va_end(ap);
+}
+
+
+/**
+ * Send data from foundIceCandidate to the UI
+ *
+ * @return none
+ */
+
+void ui_ice_candidate_found(call_events event,
+			    fsmdef_states_t new_state,
+			    line_t nLine,
+			    callid_t nCallID,
+			    uint16_t call_instance_id,
+			    string_t sdp,
+			    string_t candidate,
+			    Timecard *timecard,
+			    pc_error error,
+			    const char *format, ...)
+{
+    va_list ap;
+    TNP_DEBUG(DEB_L_C_F_PREFIX"state=%d call_instance=%d",
+              DEB_L_C_F_PREFIX_ARGS(UI_API, nLine, nCallID, __FUNCTION__), event, call_instance_id);
+
+    va_start(ap, format);
+    post_message_helper(ICE_CANDIDATE_FOUND, event, new_state, nLine, nCallID,
+                        call_instance_id, sdp, candidate, timecard, error, format, ap);
     va_end(ap);
 }
 
 /**
  *  Send Remote Stream data to the UI
  *
  *  @return none
  */
--- a/media/webrtc/signaling/src/sipcc/core/gsm/fsmdef.c
+++ b/media/webrtc/signaling/src/sipcc/core/gsm/fsmdef.c
@@ -32,16 +32,17 @@
 #include "prot_configmgr.h"
 #include "sip_interface_regmgr.h"
 #include "dialplanint.h"
 #include "subapi.h"
 #include "text_strings.h"
 #include "platform_api.h"
 #include "peer_connection_types.h"
 #include "prlog.h"
+#include "prprf.h"
 #include "sessionHash.h"
 
 extern void update_kpmlconfig(int kpmlVal);
 extern boolean g_disable_mass_reg_debug_print;
 void escalateDeescalate();
 
 #define FSMDEF_NO_NUMBER    (NULL)
 #define DIGIT_POUND         ('#')
@@ -88,16 +89,17 @@ static const char *fsmdef_state_names[] 
 static sm_rcs_t fsmdef_ev_createoffer(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_createanswer(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_setlocaldesc(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_setremotedesc(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_setpeerconnection(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_addstream(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_removestream(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_addcandidate(sm_event_t *event);
+static sm_rcs_t fsmdef_ev_foundcandidate(sm_event_t *event);
 
 static sm_rcs_t fsmdef_ev_default(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_default_feature_ack(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_idle_setup(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_idle_feature(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_idle_offhook(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_idle_dialstring(sm_event_t *event);
 static sm_rcs_t fsmdef_ev_onhook(sm_event_t *event);
@@ -197,17 +199,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_setpeerconnection,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_COLLECT_INFO ---------------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -227,17 +230,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_CALL_SENT ------------------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_proceeding,
     /* CC_MSG_ALERTING         */ fsmdef_ev_out_alerting,
@@ -257,17 +261,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_OUTGOING_PROCEEDING --------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_out_alerting,
@@ -287,17 +292,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_KPML_COLLECT_INFO ----------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_out_alerting,
@@ -317,17 +323,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_OUTGOING_ALERTING ----------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_out_alerting,
@@ -347,17 +354,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_INCOMING_ALERTING ----------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -377,17 +385,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_CONNECTING ------------------------------------------------------ */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -407,17 +416,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_JOINING --------------------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -437,17 +447,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_CONNECTED ------------------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -467,17 +478,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_CONNECTED_MEDIA_PEND  ------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -497,17 +509,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_RELEASING ------------------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -527,17 +540,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_HOLD_PENDING ---------------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -557,17 +571,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_HOLDING --------------------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -587,17 +602,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_RESUME_PENDING -------------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -617,17 +633,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_PRESERVED  ------------------------------------------------------ */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -647,17 +664,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_session_audit,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 
 /* FSMDEF_S_STABLE  --------------------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
@@ -678,17 +696,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_default,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_createoffer,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_createanswer,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_setlocaldesc,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_setremotedesc,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_addstream,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_removestream,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_addcandidate
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_addcandidate,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_foundcandidate
     },
 
 /* FSMDEF_S_HAVE_LOCAL_OFFER  ----------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -708,18 +727,19 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_default,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_createoffer,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_createanswer,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_setlocaldesc,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_setremotedesc,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default /* Reject lame-duck
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default, /* Reject lame-duck
                                                        candidates */
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_foundcandidate
     },
 
 /* FSMDEF_S_HAVE_REMOTE_OFFER  ---------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -739,17 +759,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_default,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_createoffer,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_createanswer,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_setlocaldesc,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_setremotedesc,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_addstream,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_removestream,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_addcandidate
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_addcandidate,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     },
 
 /* FSMDEF_S_HAVE_LOCAL_PRANSWER  -------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -769,17 +790,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_default,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_createoffer,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_createanswer,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_setlocaldesc,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default, /* Should not happen */
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_addcandidate
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_addcandidate,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_foundcandidate
     },
 
 /* FSMDEF_S_HAVE_REMOTE_PRANSWER  ------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -799,17 +821,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_default,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_createoffer,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_createanswer,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default, /* Should not happen */
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_setremotedesc,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_addcandidate
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_addcandidate,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_foundcandidate
     },
 
 /* FSMDEF_S_CLOSED  --------------------------------------------------------- */
     {
     /* CC_MSG_SETUP            */ fsmdef_ev_default,
     /* CC_MSG_SETUP_ACK        */ fsmdef_ev_default,
     /* CC_MSG_PROCEEDING       */ fsmdef_ev_default,
     /* CC_MSG_ALERTING         */ fsmdef_ev_default,
@@ -829,17 +852,18 @@ static sm_function_t fsmdef_function_tab
     /* CC_MSG_SESSION_AUDIT    */ fsmdef_ev_default,
     /* CC_MSG_CREATEOFFER      */ fsmdef_ev_default,
     /* CC_MSG_CREATEANSWER     */ fsmdef_ev_default,
     /* CC_MSG_SETLOCALDESC     */ fsmdef_ev_default,
     /* CC_MSG_SETREMOTEDESC    */ fsmdef_ev_default,
     /* CC_MSG_SETPEERCONNECTION */fsmdef_ev_default,
     /* CC_MSG_ADDSTREAM        */ fsmdef_ev_default,
     /* CC_MSG_REMOVESTREAM     */ fsmdef_ev_default,
-    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default
+    /* CC_MSG_ADDCANDIDATE     */ fsmdef_ev_default,
+    /* CC_MSG_FOUNDCANDIDATE   */ fsmdef_ev_default
     }
 };
 
 static sm_table_t fsmdef_sm_table;
 sm_table_t *pfsmdef_sm_table = &fsmdef_sm_table;
 
 /*--------------------------------------------------------------------------
  * Global data
@@ -1297,16 +1321,18 @@ fsmdef_init_dcb (fsmdef_dcb_t *dcb, call
     dcb->callref = 0;
 
     dcb->ice_ufrag = NULL;
     dcb->ice_pwd = NULL;
     dcb->ice_default_candidate_addr[0] = '\0';
 
     dcb->digest_alg[0] = '\0';
     dcb->digest[0] = '\0';
+
+    sll_lite_init(&dcb->candidate_list);
 }
 
 
 static void
 fsmdef_free_dcb (fsmdef_dcb_t *dcb)
 {
     if (dcb == NULL) {
         return;
@@ -1346,16 +1372,19 @@ fsmdef_free_dcb (fsmdef_dcb_t *dcb)
     // Free the call instance id
     if (dcb->caller_id.call_instance_id != 0) {
         fsmutil_free_ci_id(dcb->caller_id.call_instance_id, dcb->line);
     }
 
     /* clean media list */
     gsmsdp_clean_media_list(dcb);
 
+    /* clean candidate list */
+    gsmsdp_clean_candidate_list(dcb);
+
     gsmsdp_free(dcb);
 
     fsmdef_init_dcb(dcb, CC_NO_CALL_ID, FSMDEF_CALL_TYPE_NONE, NULL,
                     LSM_NO_LINE, NULL);
 
     /*
      * Cache random numbers for SRTP keys
      */
@@ -2450,16 +2479,24 @@ fsmdef_ev_default (sm_event_t *event)
       case CC_MSG_ADDCANDIDATE:
           ui_ice_candidate_add(evAddIceCandidateError, fcb->state, msg->line,
               msg->call_id, dcb->caller_id.call_instance_id, strlib_empty(),
               msg->timecard,
               PC_INVALID_STATE, "Cannot add ICE candidate in state %s",
               fsmdef_state_name(fcb->state));
         break;
 
+      case CC_MSG_FOUNDCANDIDATE:
+          ui_ice_candidate_found(evFoundIceCandidateError, fcb->state, msg->line,
+              msg->call_id, dcb->caller_id.call_instance_id, strlib_empty(),
+              NULL, msg->timecard,
+              PC_INVALID_STATE, "Cannot add found ICE candidate in state %s",
+              fsmdef_state_name(fcb->state));
+        break;
+
       case CC_MSG_ADDSTREAM:
       case CC_MSG_REMOVESTREAM:
           /* This shouldn't happen, since PeerConnection should check
            * the state before sending these events to us. The debug message
            * here is to catch the unexpected situation of such an event
            * getting through anyway. */
           FSM_DEBUG_SM(DEB_L_C_F_PREFIX"Cannot add or remove streams "
               "in state %s", DEB_L_C_F_PREFIX_ARGS(FSM, dcb->line,
@@ -3165,16 +3202,19 @@ fsmdef_ev_createoffer (sm_event_t *event
 
         ui_create_offer(evCreateOfferSuccess, fcb->state, line, call_id,
             dcb->caller_id.call_instance_id, strlib_malloc(local_sdp,-1),
             msg->timecard, PC_NO_ERROR, NULL);
         free(local_sdp);
         return (SM_RC_END);
     }
 
+    /* clean candidate list, since we are about to return the candidates */
+    gsmsdp_clean_candidate_list(dcb);
+
     dcb->inbound = FALSE;
 
     if (msg->data.session.constraints) {
        gsmsdp_process_cap_constraints(dcb, msg->data.session.constraints);
        fsmdef_free_constraints(msg->data.session.constraints);
        msg->data.session.constraints = 0;
     }
 
@@ -3326,16 +3366,19 @@ fsmdef_ev_createanswer (sm_event_t *even
 
         ui_create_answer(evCreateAnswerSuccess, fcb->state, line, call_id,
             dcb->caller_id.call_instance_id, strlib_malloc(local_sdp,-1),
             msg->timecard, PC_NO_ERROR, NULL);
         free(local_sdp);
         return (SM_RC_END);
     }
 
+    /* clean candidate list, since we are about to return the candidates */
+    gsmsdp_clean_candidate_list(dcb);
+
     dcb->inbound = TRUE;
 
     if (msg->data.session.constraints) {
        gsmsdp_process_cap_constraints(dcb, msg->data.session.constraints);
        fsmdef_free_constraints(msg->data.session.constraints);
        msg->data.session.constraints = 0;
     }
 
@@ -3454,16 +3497,17 @@ fsmdef_ev_setlocaldesc(sm_event_t *event
     int                 action = msg->action;
     string_t            sdp = msg->sdp;
     int                 sdpmode = 0;
     callid_t            call_id = msg->call_id;
     line_t              line = msg->line;
     cc_causes_t         lsm_rc;
     char                *local_sdp = NULL;
     uint32_t            local_sdp_len = 0;
+    fsmdef_candidate_t *candidate = NULL;
 
     FSM_DEBUG_SM(DEB_F_PREFIX"Entered.", DEB_F_PREFIX_ARGS(FSM, __FUNCTION__));
 
     if (dcb == NULL) {
         FSM_DEBUG_SM(DEB_F_PREFIX"dcb is NULL.",
           DEB_F_PREFIX_ARGS(FSM, __FUNCTION__));
         fsm_change_state(fcb, __LINE__, FSMDEF_S_CLOSED);
         ui_set_local_description(evSetLocalDescError, fcb->state, line, call_id,
@@ -3598,16 +3642,31 @@ fsmdef_ev_setlocaldesc(sm_event_t *event
             "description");
         return (SM_RC_END);
     }
 
     ui_set_local_description(evSetLocalDescSuccess, fcb->state, msg->line,
         msg->call_id, dcb->caller_id.call_instance_id,
         strlib_malloc(local_sdp,-1), msg->timecard, PC_NO_ERROR, NULL);
 
+    /* If we have pending candidates flush them too */
+    while (TRUE) {
+        /* unlink head and free the media */
+        candidate = (fsmdef_candidate_t *)sll_lite_unlink_head(&dcb->candidate_list);
+        if (candidate) {
+            ui_ice_candidate_found(evFoundIceCandidate, fcb->state, line, call_id,
+                                   dcb->caller_id.call_instance_id, strlib_malloc(local_sdp,-1),
+                                   candidate->candidate, /* Transfer ownership */
+                                   NULL, PC_NO_ERROR, NULL);
+            free(candidate);
+        } else {
+            break;
+        }
+    }
+
     free(local_sdp);
     return (SM_RC_END);
 }
 
 /**
  * SetRemoteDescription
  *
  * Because the PeerConnection relies on receiving either a success or
@@ -4117,16 +4176,127 @@ fsmdef_ev_addcandidate(sm_event_t *event
     ui_ice_candidate_add(evAddIceCandidate, fcb->state, line, call_id,
         dcb->caller_id.call_instance_id, strlib_malloc(remote_sdp,-1),
         msg->timecard, PC_NO_ERROR, NULL);
 
     free(remote_sdp);
     return (SM_RC_END);
 }
 
+
+static sm_rcs_t
+fsmdef_ev_foundcandidate(sm_event_t *event) {
+    fsm_fcb_t           *fcb = (fsm_fcb_t *) event->data;
+    fsmdef_dcb_t        *dcb = fcb->dcb;
+    cc_causes_t         cause = CC_CAUSE_NORMAL;
+    cc_feature_t        *msg = (cc_feature_t *) event->msg;
+    int                 sdpmode = 0;
+    short               vcm_res;
+    uint16_t            level;
+    line_t              line = msg->line;
+    callid_t            call_id = msg->call_id;
+    char                *local_sdp = 0;
+    uint32_t            local_sdp_len = 0;
+    string_t            candidate = 0;
+    char                candidate_tmp[CANDIDATE_SIZE + 32]; /* Sort of arbitrary */
+
+    FSM_DEBUG_SM(DEB_F_PREFIX"Entered.", DEB_F_PREFIX_ARGS(FSM, __FUNCTION__));
+
+    if (!dcb) {
+        FSM_DEBUG_SM(DEB_F_PREFIX"dcb is NULL.", DEB_F_PREFIX_ARGS(FSM, __FUNCTION__));
+        ui_ice_candidate_add(evAddIceCandidateError, fcb->state, line, call_id,
+            0, strlib_empty(), msg->timecard, PC_INTERNAL_ERROR,
+            "DCB has not been created.");
+        return SM_RC_CLEANUP;
+    }
+
+    config_get_value(CFGID_SDPMODE, &sdpmode, sizeof(sdpmode));
+    if (!sdpmode) {
+        MOZ_CRASH();
+    }
+
+    MOZ_ASSERT(dcb->sdp && dcb->sdp->src_sdp);
+    if (!dcb->sdp || !dcb->sdp->src_sdp) {
+        FSM_DEBUG_SM(DEB_F_PREFIX"Has the "
+            "local description been set yet?\n",
+            DEB_F_PREFIX_ARGS(FSM, __FUNCTION__));
+
+        ui_ice_candidate_found(evFoundIceCandidateError, fcb->state, line, call_id,
+                               dcb->caller_id.call_instance_id, strlib_empty(),
+                               NULL, msg->timecard,
+            PC_INVALID_STATE, "Cannot add found ICE candidates without"
+                              "local SDP.");
+
+        return SM_RC_END;
+    }
+
+    /* Store the candidate in the SDP for future reference */
+    level = msg->data.candidate.level;
+    gsmsdp_set_ice_attribute (SDP_ATTR_ICE_CANDIDATE, level,
+                              dcb->sdp->src_sdp,
+                              (char *)msg->data.candidate.candidate);
+
+    local_sdp = sipsdp_write_to_buf(dcb->sdp->src_sdp, &local_sdp_len);
+
+    if (!local_sdp) {
+        ui_ice_candidate_found(evFoundIceCandidateError, fcb->state, line, call_id,
+            dcb->caller_id.call_instance_id, strlib_empty(), NULL,
+            msg->timecard,
+            PC_INTERNAL_ERROR, "Could not serialize new SDP after adding ICE "
+            "candidate.");
+        return (SM_RC_END);
+    }
+
+    /* Distinguish between the following two cases:
+
+       1. CreateOffer() has been called but SetLocalDesc() has not.
+       2. We are mid-call.
+
+       Both of these are in state STABLE but only in one do we
+       pass up trickle candidates. In the other we buffer them
+       and send them later.
+    */
+    /* Smuggle the entire candidate structure in a string */
+    PR_snprintf(candidate_tmp, sizeof(candidate_tmp), "%d\t%s\t%s",
+                msg->data.candidate.level,
+                (char *)msg->data.candidate.mid,
+                (char *)msg->data.candidate.candidate);
+
+    if (fcb->state == FSMDEF_S_STABLE) {
+        if (!dcb->sdp->dest_sdp) {
+            fsmdef_candidate_t *buffered_cand = NULL;
+
+            FSM_DEBUG_SM(DEB_F_PREFIX"dcb->sdp->dest_sdp is null."
+                         "assuming CreateOffer called but not SetLocal...\n",
+                         DEB_F_PREFIX_ARGS(FSM, __FUNCTION__));
+
+            buffered_cand = (fsmdef_candidate_t *)cpr_malloc(sizeof(fsmdef_candidate_t));
+            if (!buffered_cand)
+                return SM_RC_END;
+
+            buffered_cand->candidate = strlib_malloc(candidate_tmp, -1);
+
+            if (sll_lite_link_head(&dcb->candidate_list,
+                                   (sll_lite_node_t *)buffered_cand) != SLL_LITE_RET_SUCCESS)
+                return SM_RC_END;
+
+            /* Don't notify upward */
+            return SM_RC_END;
+        }
+    }
+
+    ui_ice_candidate_found(evFoundIceCandidate, fcb->state, line, call_id,
+        dcb->caller_id.call_instance_id, strlib_malloc(local_sdp,-1),
+        strlib_malloc(candidate_tmp, -1),
+        msg->timecard, PC_NO_ERROR, NULL);
+
+    return SM_RC_END;
+}
+
+
 static void
 fsmdef_check_active_feature (fsmdef_dcb_t *dcb, cc_features_t ftr_id)
 {
     if ((dcb) && (dcb->active_feature != ftr_id)) {
         FSM_DEBUG_SM(get_debug_string(FSMDEF_DBG_FTR_REQ_ACT),
                      dcb->call_id, dcb->line,
                      cc_feature_name(ftr_id),
                      cc_feature_name(dcb->active_feature));
--- a/media/webrtc/signaling/src/sipcc/core/gsm/gsm_sdp.c
+++ b/media/webrtc/signaling/src/sipcc/core/gsm/gsm_sdp.c
@@ -7322,8 +7322,36 @@ gsmsdp_find_level_from_mid(fsmdef_dcb_t 
         snprintf(buf, sizeof(buf), "%u", mid_id);
         if (strcmp(mid, buf) == 0) {
         	*level = media->level;
         	return CC_CAUSE_OK;
         }
     }
     return CC_CAUSE_VALUE_NOT_FOUND;
 }
+
+/**
+ * The function performs cleaning candidate list of a given call. It walks
+ * through the list and deallocates each candidate entry.
+ *
+ * @param[in]dcb   - pointer to fsmdef_def_t for the dcb whose
+ *                   media list to be cleaned.
+ *
+ * @return  none
+ *
+ * @pre     (dcb not_eq NULL)
+ */
+void gsmsdp_clean_candidate_list (fsmdef_dcb_t *dcb_p)
+{
+    fsmdef_candidate_t *candidate = NULL;
+
+    while (TRUE) {
+        /* unlink head and free the media */
+        candidate = (fsmdef_candidate_t *)sll_lite_unlink_head(&dcb_p->candidate_list);
+        if (candidate) {
+            strlib_free(candidate->candidate);
+            free(candidate);
+        } else {
+            break;
+        }
+    }
+}
+
--- a/media/webrtc/signaling/src/sipcc/core/gsm/h/fsm.h
+++ b/media/webrtc/signaling/src/sipcc/core/gsm/h/fsm.h
@@ -424,16 +424,17 @@ typedef struct {
 
     char *ice_ufrag;
     char *ice_pwd;
     char ice_default_candidate_addr[MAX_IPADDR_STR_LEN];
 
     char digest_alg[FSMDEF_MAX_DIGEST_ALG_LEN];
     char digest[FSMDEF_MAX_DIGEST_LEN];
 
+    sll_lite_list_t candidate_list;
 } fsmdef_dcb_t;
 
 typedef enum fsm_types_t_ {
     FSM_TYPE_MIN = -1,
     FSM_TYPE_NONE = FSM_TYPE_MIN,
     FSM_TYPE_HEAD,
     FSM_TYPE_CNF,
     FSM_TYPE_B2BCNF,
@@ -493,16 +494,21 @@ typedef enum fsmxfr_types_t_ {
 
 typedef enum fsmxfr_modes_t_ {
     FSMXFR_MODE_MIN = -1,
     FSMXFR_MODE_TRANSFEROR,
     FSMXFR_MODE_TRANSFEREE,
     FSMXFR_MODE_TARGET
 } fsmxfr_modes_t;
 
+typedef struct fsmdef_candidate_t_ {
+    sll_lite_node_t node;     /* link node, must be first member of struct */
+    string_t candidate;       /* the candidate value */
+} fsmdef_candidate_t;
+
 struct fsmxfr_xcb_t_;
 typedef struct fsmxfr_xcb_t_ {
     cc_srcs_t         xfr_orig;
     int               xfr_id;
     callid_t          xfr_call_id;
     callid_t          cns_call_id;
     line_t            xfr_line;
     line_t            cns_line;
--- a/media/webrtc/signaling/src/sipcc/core/gsm/h/gsm_sdp.h
+++ b/media/webrtc/signaling/src/sipcc/core/gsm/h/gsm_sdp.h
@@ -136,11 +136,12 @@ cc_causes_t gsmsdp_find_level_from_mid(f
 void gsmsdp_process_cap_constraints(fsmdef_dcb_t *dcb,
                                     cc_media_constraints_t* constraints);
 cc_causes_t
 gsmsdp_get_offered_media_types (fsm_fcb_t *fcb_p, cc_sdp_t *sdp_p, boolean *has_audio, boolean *has_video, boolean *has_data);
 fsmdef_media_t* gsmsdp_find_media_by_media_type(fsmdef_dcb_t *dcb, sdp_media_e 	media_type);
 
 extern void gsmsdp_set_ice_attribute (sdp_attr_e sdp_attr, uint16_t level,
                                       void *sdp_p, char *ice_attrib);
+extern void gsmsdp_clean_candidate_list(fsmdef_dcb_t *dcb);
 
 #endif
 
--- a/media/webrtc/signaling/src/sipcc/core/includes/ccapi.h
+++ b/media/webrtc/signaling/src/sipcc/core/includes/ccapi.h
@@ -98,16 +98,17 @@ typedef enum {
     CC_FEATURE_CREATEOFFER,
     CC_FEATURE_CREATEANSWER,
     CC_FEATURE_SETLOCALDESC,
     CC_FEATURE_SETREMOTEDESC,
     CC_FEATURE_SETPEERCONNECTION,
     CC_FEATURE_ADDSTREAM,
     CC_FEATURE_REMOVESTREAM,
     CC_FEATURE_ADDICECANDIDATE,
+    CC_FEATURE_FOUNDICECANDIDATE,
     CC_FEATURE_MAX
 } group_cc_feature_t;
 
 #define skNewCall CC_FEATURE_NEW_CALL
 #define skConfrn CC_FEATURE_CONF
 
 /* please update the following cc_feature_names whenever this feature list is changed */
 
@@ -163,16 +164,17 @@ static const char *const cc_feature_name
     "CREATEOFFER",
     "CREATEANSWER",
     "SETLOCALDESC",
     "SETREMOTEDESC",
     "SETPEERCONNECTION",
     "ADDSTREAM",
     "REMOVESTREAM",
     "ADDICECANDIDATE",
+    "FOUNDICECANDIDATE",
     "MAX"
 };
 
 /* This checks at compile-time that the cc_feature_names list
  * is the same size as the cc_group_feature_t enum
  */
 MOZ_STATIC_ASSERT(MOZ_ARRAY_LENGTH(cc_feature_names) == CC_FEATURE_MAX + 1,
                   "cc_feature_names size == cc_group_feature_t size?");
@@ -236,16 +238,17 @@ typedef enum cc_msgs_t_ {
     CC_MSG_CREATEOFFER,
     CC_MSG_CREATEANSWER,
     CC_MSG_SETLOCALDESC,
     CC_MSG_SETREMOTEDESC,
     CC_MSG_SETPEERCONNECTION,
     CC_MSG_ADDSTREAM,
     CC_MSG_REMOVESTREAM,
     CC_MSG_ADDCANDIDATE,
+    CC_MSG_FOUNDCANDIDATE,
     CC_MSG_AUDIT_ACK,
     CC_MSG_OPTIONS,
     CC_MSG_OPTIONS_ACK,
     CC_MSG_SUBSCRIBE,
     CC_MSG_NOTIFY,
     CC_MSG_FAILOVER_FALLBACK,
     CC_MSG_INFO,
     /* update the following strings table if this is changed */
@@ -275,16 +278,17 @@ static const char *const cc_msg_names[] 
     "CREATEOFFER",
     "CREATEANSWER",
     "SETLOCALDESC",
     "SETREMOTEDESC",
     "SETPEERCONNECTION",
     "ADDSTREAM",
     "REMOVESTREAM",
     "ADDCANDIDATE",
+    "FOUNDCANDIDATE",
     "AUDIT_ACK",
     "OPTIONS",
     "OPTIONS_ACK",
     "SUBSCRIBE",
     "NOTIFY",
     "FAILOVER_FALLBACK",
     "INFO",
     "INVALID",
--- a/media/webrtc/signaling/src/sipcc/core/includes/sessionConstants.h
+++ b/media/webrtc/signaling/src/sipcc/core/includes/sessionConstants.h
@@ -218,17 +218,18 @@ typedef enum {
     MEDIA_INTERFACE_UPDATE_FAIL,
     CREATE_OFFER,
     CREATE_ANSWER,
     SET_LOCAL_DESC,
     SET_REMOTE_DESC,
     UPDATE_LOCAL_DESC,
     UPDATE_REMOTE_DESC,
     REMOTE_STREAM_ADD,
-    ICE_CANDIDATE_ADD
+    ICE_CANDIDATE_ADD,
+    ICE_CANDIDATE_FOUND
 } group_call_event_t;
 
 /* File Player Session Events */
 typedef enum {
     FILEPLAYER_PLAYED = 300L,
     FILEPLAYER_ALLOCATED
 } group_fileplayer_t;
 
--- a/media/webrtc/signaling/src/sipcc/core/includes/sessionTypes.h
+++ b/media/webrtc/signaling/src/sipcc/core/includes/sessionTypes.h
@@ -61,16 +61,17 @@ typedef struct {
   int          state;
   int          fsm_state;
   int          attr;
   int          inst;
   line_t       line_id;
   int          cause;
   string_t     reason_text;
   string_t     sdp;
+  string_t     extra;
   unsigned int media_stream_id;
   unsigned int media_stream_track_id;
   Timecard *   timecard;
 } cc_call_state_data_t;
 /* CALL_SESSION_CREATED shall use the call_state as data*/
 
 typedef struct
 {
--- a/media/webrtc/signaling/src/sipcc/core/includes/uiapi.h
+++ b/media/webrtc/signaling/src/sipcc/core/includes/uiapi.h
@@ -39,16 +39,18 @@ typedef enum {
     evSetLocalDescSuccess = SETLOCALDESCSUCCESS,
     evSetRemoteDescSuccess = SETREMOTEDESCSUCCESS,
     evUpdateLocalDesc = UPDATELOCALDESC,
     evSetLocalDescError = SETLOCALDESCERROR,
     evSetRemoteDescError = SETREMOTEDESCERROR,
     evOnRemoteStreamAdd = REMOTESTREAMADD,
     evAddIceCandidate = ADDICECANDIDATE,
     evAddIceCandidateError = ADDICECANDIDATEERROR,
+    evFoundIceCandidate = FOUNDICECANDIDATE,
+    evFoundIceCandidateError = FOUNDICECANDIDATEERROR,
     evMaxEvent
 } call_events;
 
 /* These values must be kept in sync with the equivalent values in:
  *
  *   PeerConnectionImpl.h
  *   Peerconnection.js
  *   nsIDOMPeerConnection.idl
@@ -235,16 +237,27 @@ void ui_ice_candidate_add(call_events ev
                           line_t nLine,
                           callid_t nCallID,
                           uint16_t call_instance_id,
                           string_t sdp,
                           Timecard *timecard,
                           pc_error error,
                           const char *format, ...);
 
+void ui_ice_candidate_found(call_events event,
+                            fsmdef_states_t new_state,
+                            line_t nLine,
+                            callid_t nCallID,
+                            uint16_t call_instance_id,
+                            string_t sdp,
+                            string_t candidate,
+                            Timecard *timecard,
+                            pc_error error,
+                            const char *format, ...);
+
 void ui_on_remote_stream_added(call_events event,
                                fsmdef_states_t new_state,
                                line_t nLine,
                                callid_t nCallID,
                                uint16_t call_instance_id,
                                cc_media_remote_track_table_t media_tracks);
 
 
--- a/media/webrtc/signaling/src/sipcc/include/cc_call_feature.h
+++ b/media/webrtc/signaling/src/sipcc/include/cc_call_feature.h
@@ -181,16 +181,21 @@ cc_return_t CC_CallFeature_AddStream(cc_
 
 cc_return_t CC_CallFeature_RemoveStream(cc_call_handle_t call_handle, cc_media_stream_id_t stream_id, cc_media_track_id_t id, cc_media_type_t media_type);
 
 cc_return_t CC_CallFeature_AddICECandidate(cc_call_handle_t call_handle,
                                            const char* candidate,
                                            const char *mid,
                                            cc_level_t level,
                                            Timecard *tc);
+cc_return_t CC_CallFeature_FoundICECandidate(cc_call_handle_t call_handle,
+					     const char* candidate,
+					     const char *mid,
+					     cc_level_t level,
+					     Timecard *tc);
 
 /**
  * Initiate a speed dial.
  * @param call_handle call handle
  * @param speed_dial_number speed dial number to be dialed.
  * @param video_pref the sdp direction
  * @return SUCCESS or FAILURE
  */
--- a/media/webrtc/signaling/src/sipcc/include/cc_constants.h
+++ b/media/webrtc/signaling/src/sipcc/include/cc_constants.h
@@ -284,16 +284,18 @@ typedef enum {
 	SETREMOTEDESCSUCCESS,
 	UPDATELOCALDESC,
 	UPDATEREMOTEDESC,
 	SETLOCALDESCERROR,
 	SETREMOTEDESCERROR,
 	REMOTESTREAMADD,
 	ADDICECANDIDATE,
 	ADDICECANDIDATEERROR,
+	FOUNDICECANDIDATE,
+	FOUNDICECANDIDATEERROR,
     MAX_CALL_STATES
 } cc_call_state_t;
 
 /**
  * Defines call attribute
  */
 typedef enum {
 	CC_ATTR_NOT_DEFINED = -1,
--- a/media/webrtc/signaling/src/sipcc/include/ccapi_call_info.h
+++ b/media/webrtc/signaling/src/sipcc/include/ccapi_call_info.h
@@ -298,16 +298,23 @@ cc_boolean CCAPI_CallInfo_isVideoMuted(c
 /**
  * get SDP string CreateOffer and CreateAnswer callback
  * @param [in] handle - call info handle
  * @return sdp
  */
 cc_string_t CCAPI_CallInfo_getSDP(cc_callinfo_ref_t handle);
 
 /**
+ * get trickle candidate
+ * @param [in] handle - call info handle
+ * @return sdp
+ */
+cc_string_t CCAPI_CallInfo_getCandidate(cc_callinfo_ref_t handle);
+
+/**
  * get status code from internal JSEP functions
  * @param [in] handle - call info handle
  * @return status code
  */
 cc_int32_t  CCAPI_CallInfo_getStatusCode(cc_callinfo_ref_t handle);
 
 /**
  * get media stream table
--- a/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCallInfo.cpp
+++ b/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCallInfo.cpp
@@ -449,16 +449,21 @@ MediaStreamTable* CC_SIPCCCallInfo::getM
 	return CCAPI_CallInfo_getMediaStreams(callinfo_ref);
 }
 
 Timecard *CC_SIPCCCallInfo::takeTimecard()
 {
     return CCAPI_CallInfo_takeTimecard(callinfo_ref);
 }
 
+std::string CC_SIPCCCallInfo::getCandidate()
+{
+    return CCAPI_CallInfo_getCandidate(callinfo_ref);
+}
+
 bool CC_SIPCCCallInfo::isMediaStateAvailable()
 {
     // for softphone it will always be possible to query the mute state and video direction
     return true;
 }
 
 
 #define PRINT_IF_CC_CAP_TRUE(cap) ((hasFeature(cap)) ? string(#cap) + ",": "")
--- a/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCallInfo.h
+++ b/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCallInfo.h
@@ -75,16 +75,17 @@ namespace CSF
         virtual std::string getINFOBody();
         virtual cc_calllog_ref_t getCallLogRef();
         virtual cc_sdp_direction_t getVideoDirection();
         virtual int getVolume();
         virtual bool isMediaStateAvailable();
         virtual bool isAudioMuted();
         virtual bool isVideoMuted();
         virtual std::string getSDP();
+        virtual std::string getCandidate();
         virtual cc_int32_t getStatusCode();
         virtual MediaStreamTable* getMediaStreams() const;
         virtual Timecard *takeTimecard();
 
         virtual void setMediaData(CC_SIPCCCallMediaDataPtr  pMediaData);
 
     private:
         // Helper to generate the caps once - then we serve then from this cache.
--- a/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCService.cpp
+++ b/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCService.cpp
@@ -718,16 +718,28 @@ void CC_SIPCCService::onCallEvent(ccapi_
 
     infoPtr->setMediaData(callPtr->getMediaData());
 
 	set<CSF::CC_CallCapabilityEnum::CC_CallCapability> capSet = infoPtr->getCapabilitySet();
     CSFLogInfo( logTag, "onCallEvent(%s, %s, [%s|%s]",
         call_event_getname(eventType), callPtr->toString().c_str(),
     	call_state_getname(infoPtr->getCallState()), CC_CallCapabilityEnum::toString(capSet).c_str());
     _self->notifyCallEventObservers(eventType, callPtr.get(), infoPtr.get());
+
+    // To prevent leaking CC_SIPCCCalls, we remove them from the wrapper
+    // map when the call event information indicates an "on hook" event.
+    if (infoPtr->getCallState() == ONHOOK) {
+        CSFLogDebug( logTag, "Removing call info from wrapper map (handle=%u)",
+                     handle);
+        CC_SIPCCCall::release(handle);
+    }
+
+    // Once the call info is dispatched to the observers, we never need to
+    // refer to it again. The next operation will contain its own unique info.
+    CC_SIPCCCallInfo::release(info);
 }
 
 void CC_SIPCCService::addCCObserver ( CC_Observer * observer )
 {
 	mozilla::MutexAutoLock lock(m_lock);
     if (observer == NULL)
     {
         CSFLogError( logTag, "NULL value for \"observer\" passed to addCCObserver().");
--- a/media/webrtc/signaling/test/Makefile.in
+++ b/media/webrtc/signaling/test/Makefile.in
@@ -109,16 +109,18 @@ endif
 ifeq ($(OS_TARGET),WINNT)
 LIBS += \
   $(DEPTH)/staticlib/components/$(LIB_PREFIX)windowsproxy.$(LIB_SUFFIX) \
   $(NULL)
 endif
 
 DEFINES += \
   -DUSE_FAKE_MEDIA_STREAMS \
+  -DNR_SOCKET_IS_VOID_PTR \
+  -DHAVE_STRDUP \
   $(NULL)
 
 ifeq ($(OS_TARGET),Darwin)
 DEFINES += \
   -DGTEST_USE_OWN_TR1_TUPLE=1 \
   $(NULL)
 endif
 
@@ -136,19 +138,45 @@ LOCAL_INCLUDES += \
  -I$(topsrcdir)/media/webrtc/signaling/src/common/time_profiling \
  -I$(topsrcdir)/media/webrtc/signaling/src/media \
  -I$(topsrcdir)/media/webrtc/signaling/src/media-conduit \
  -I$(topsrcdir)/media/webrtc/signaling/src/mediapipeline \
  -I$(topsrcdir)/media/webrtc/signaling/src/sipcc/include \
  -I$(topsrcdir)/media/webrtc/signaling/src/peerconnection \
  -I$(topsrcdir)/media/webrtc/signaling/media-conduit\
  -I$(topsrcdir)/media/webrtc/trunk/third_party/libjingle/source/ \
+ -I$(topsrcdir)/media/mtransport/third_party/nICEr/src/ice \
+ -I$(topsrcdir)/media/mtransport/third_party/nICEr/src/net \
+ -I$(topsrcdir)/media/mtransport/third_party/nICEr/src/stun \
+ -I$(topsrcdir)/media/mtransport/third_party/nrappkit/src/share \
+ -I$(topsrcdir)/media/mtransport/third_party/nrappkit/src/util/libekr \
+ -I$(topsrcdir)/media/mtransport/third_party/nrappkit/src/log \
+ -I$(topsrcdir)/media/mtransport/third_party/nrappkit/src/registry \
+ -I$(topsrcdir)/media/mtransport/third_party/nrappkit/src/stats \
+ -I$(topsrcdir)/media/mtransport/third_party/nrappkit/src/plugin \
+ -I$(topsrcdir)/media/mtransport/third_party/nrappkit/src/event \
  -I$(topsrcdir)/xpcom/base/ \
  $(NULL)
 
+ifneq (,$(filter Darwin DragonFly FreeBSD NetBSD OpenBSD,$(OS_TARGET)))
+LOCAL_INCLUDES +=  -I$(topsrcdir)/media/mtransport/third_party/nrappkit/src/port/darwin/include
+ifneq (,$(filter DragonFly FreeBSD NetBSD OpenBSD,$(OS_TARGET)))
+LOCAL_INCLUDES +=  -I$(topsrcdir)/media/mtransport/third_party/nrappkit/src/port/generic/include
+endif
+endif
+
+ifeq ($(OS_TARGET), Linux)
+LOCAL_INCLUDES +=  -I$(topsrcdir)/media/mtransport/third_party/nrappkit/src/port/linux/include
+endif
+
+ifeq ($(OS_TARGET), Android)
+LOCAL_INCLUDES +=  -I$(topsrcdir)/media/mtransport/third_party/nrappkit/src/port/android/include
+endif
+
+
 ifneq ($(OS_TARGET),WINNT)
 ifneq (gonk,$(MOZ_WIDGET_TOOLKIT))
 ifdef JS_SHARED_LIBRARY
 LIBS += $(MOZ_ZLIB_LIBS)
 endif
 endif
 endif
 
--- a/media/webrtc/signaling/test/sdp_unittests.cpp
+++ b/media/webrtc/signaling/test/sdp_unittests.cpp
@@ -35,17 +35,18 @@ static bool SetupGlobalThread() {
   if (!gThread) {
     nsIThread *thread;
 
     nsresult rv = NS_NewNamedThread("pseudo-main",&thread);
     if (NS_FAILED(rv))
       return false;
 
     gThread = thread;
-    sipcc::PeerConnectionCtx::InitializeGlobal(gThread);
+    sipcc::PeerConnectionCtx::InitializeGlobal(gThread,
+                                               test_utils->sts_target());
   }
   return true;
 }
 
 class SdpTest : public ::testing::Test {
   public:
     SdpTest() : sdp_ptr_(nullptr) {
       sdp_media_e supported_media[] = {
--- a/media/webrtc/signaling/test/signaling_unittests.cpp
+++ b/media/webrtc/signaling/test/signaling_unittests.cpp
@@ -4,16 +4,17 @@
 
 #include <iostream>
 #include <map>
 #include <algorithm>
 #include <string>
 #include <unistd.h>
 
 #include "base/basictypes.h"
+#include "logging.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
 #include "nspr.h"
 #include "nss.h"
 #include "ssl.h"
@@ -26,32 +27,40 @@
 #include "runnable_utils.h"
 #include "nsServiceManagerUtils.h"
 #include "nsNetUtil.h"
 #include "nsIIOService.h"
 #include "nsIDNSService.h"
 #include "nsWeakReference.h"
 #include "nricectx.h"
 #include "mozilla/SyncRunnable.h"
+#include "logging.h"
+#include "stunserver.h"
+#include "stunserver.cpp"
 
 #include "mtransport_test_utils.h"
 MtransportTestUtils *test_utils;
 nsCOMPtr<nsIThread> gThread;
 
 static int kDefaultTimeout = 5000;
 static bool fRtcpMux = true;
 
 static std::string callerName = "caller";
 static std::string calleeName = "callee";
 
 #define ARRAY_TO_STL(container, type, array) \
         (container<type>((array), (array) + PR_ARRAY_SIZE(array)))
 
 #define ARRAY_TO_SET(type, array) ARRAY_TO_STL(std::set, type, array)
 
+std::string g_stun_server_address((char *)"23.21.150.121");
+uint16_t g_stun_server_port(3478);
+std::string kBogusSrflxAddress((char *)"192.0.2.1");
+uint16_t kBogusSrflxPort(1001);
+
 namespace test {
 
 std::string indent(const std::string &s, int width = 4) {
   std::string prefix;
   std::string out;
   char previous = '\n';
   prefix.assign(width, ' ');
   for (std::string::const_iterator i = s.begin(); i != s.end(); i++) {
@@ -181,33 +190,46 @@ public:
     stateError
   };
 
   TestObserver(sipcc::PeerConnectionImpl *peerConnection,
                const std::string &aName) :
     state(stateNoResponse), addIceSuccessCount(0),
     onAddStreamCalled(false),
     name(aName),
+    candidates(),
     pc(peerConnection) {
   }
 
   virtual ~TestObserver() {}
 
   std::vector<DOMMediaStream *> GetStreams() { return streams; }
 
+  size_t MatchingCandidates(const std::string& cand) {
+    size_t count = 0;
+
+    for (size_t i=0; i<candidates.size(); ++i) {
+      if (candidates[i].find(cand) != std::string::npos)
+        ++count;
+    }
+
+    return count;
+  }
+
   NS_DECL_THREADSAFE_ISUPPORTS
   NS_DECL_IPEERCONNECTIONOBSERVER
 
   ResponseState state;
   char *lastString;
   sipcc::PeerConnectionImpl::Error lastStatusCode;
   uint32_t lastStateType;
   int addIceSuccessCount;
   bool onAddStreamCalled;
   std::string name;
+  std::vector<std::string> candidates;
 
 private:
   sipcc::PeerConnectionImpl *pc;
   std::vector<DOMMediaStream *> streams;
 };
 
 NS_IMPL_ISUPPORTS2(TestObserver,
                    IPeerConnectionObserver,
@@ -424,18 +446,23 @@ TestObserver::OnAddTrack()
 NS_IMETHODIMP
 TestObserver::OnRemoveTrack()
 {
   state = stateSuccess;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-TestObserver::FoundIceCandidate(const char* strCandidate)
+TestObserver::OnIceCandidate(uint16_t level,
+                             const char * mid,
+                             const char * candidate)
 {
+  std::cout << name << ": onIceCandidate [" << level << "/"
+            << mid << "] " << candidate << std::endl;
+  candidates.push_back(candidate);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TestObserver::OnAddIceCandidateSuccess()
 {
   lastStatusCode = sipcc::PeerConnectionImpl::kNoError;
   state = stateSuccess;
@@ -627,22 +654,31 @@ class ParsedSDP {
   std::multimap<std::string, SdpLine> sdp_map_;
   int levels_;
   int num_lines;
 };
 
 class SignalingAgent {
  public:
   SignalingAgent(const std::string &aName) : pc(nullptr), name(aName) {
-    cfg_.addStunServer("23.21.150.121", 3478);
+    cfg_.addStunServer(g_stun_server_address, g_stun_server_port);
 
     pc = sipcc::PeerConnectionImpl::CreatePeerConnection();
     EXPECT_TRUE(pc);
   }
 
+  SignalingAgent(const std::string &aName, const std::string stun_addr,
+                 uint16_t stun_port) : pc(nullptr), name(aName) {
+    cfg_.addStunServer(stun_addr, stun_port);
+
+    pc = sipcc::PeerConnectionImpl::CreatePeerConnection();
+    EXPECT_TRUE(pc);
+  }
+
+
   ~SignalingAgent() {
     mozilla::SyncRunnable::DispatchToThread(gThread,
       WrapRunnable(this, &SignalingAgent::Close));
   }
 
   void Init_m(nsCOMPtr<nsIThread> thread)
   {
     pObserver = new TestObserver(pc, name);
@@ -653,28 +689,25 @@ class SignalingAgent {
 
   void Init(nsCOMPtr<nsIThread> thread)
   {
     mozilla::SyncRunnable::DispatchToThread(thread,
       WrapRunnable(this, &SignalingAgent::Init_m, thread));
 
     ASSERT_TRUE_WAIT(sipcc_state() == sipcc::PeerConnectionImpl::kStarted,
                      kDefaultTimeout);
+  }
+
+  void WaitForGather() {
     ASSERT_TRUE_WAIT(ice_state() == sipcc::PeerConnectionImpl::kIceWaiting, 5000);
-    ASSERT_EQ(signaling_state(), sipcc::PeerConnectionImpl::kSignalingStable);
+
     std::cout << name << ": Init Complete" << std::endl;
   }
 
-  bool InitAllowFail(nsCOMPtr<nsIThread> thread)
-  {
-    mozilla::SyncRunnable::DispatchToThread(thread,
-        WrapRunnable(this, &SignalingAgent::Init_m, thread));
-
-    EXPECT_TRUE_WAIT(sipcc_state() == sipcc::PeerConnectionImpl::kStarted,
-                     kDefaultTimeout);
+  bool WaitForGatherAllowFail() {
     EXPECT_TRUE_WAIT(ice_state() == sipcc::PeerConnectionImpl::kIceWaiting ||
                      ice_state() == sipcc::PeerConnectionImpl::kIceFailed, 5000);
 
     if (ice_state() == sipcc::PeerConnectionImpl::kIceFailed) {
       std::cout << name << ": Init Failed" << std::endl;
       return false;
     }
 
@@ -697,17 +730,17 @@ class SignalingAgent {
     pc->GetIceState(&res);
     return res;
   }
 
   sipcc::PeerConnectionImpl::SignalingState signaling_state()
   {
     uint32_t res;
 
-    pc->GetSignalingState(&res);
+   pc->GetSignalingState(&res);
     return static_cast<sipcc::PeerConnectionImpl::SignalingState>(res);
   }
 
   void Close()
   {
     if (pc) {
       std::cout << name << ": Close" << std::endl;
 
@@ -715,16 +748,32 @@ class SignalingAgent {
       pc = nullptr;
     }
 
     // Shutdown is synchronous evidently.
     // ASSERT_TRUE(pObserver->WaitForObserverCall());
     // ASSERT_EQ(pc->sipcc_state(), sipcc::PeerConnectionInterface::kIdle);
   }
 
+  bool OfferContains(const std::string& str) {
+    std::string o(offer());
+
+    return o.find(str) != std::string::npos;
+  }
+
+  bool AnswerContains(const std::string& str) {
+    std::string o(answer());
+
+    return o.find(str) != std::string::npos;
+  }
+
+  size_t MatchingCandidates(const std::string& cand) {
+    return pObserver->MatchingCandidates(cand);
+  }
+
   char* offer() const { return offer_; }
   char* answer() const { return answer_; }
 
   std::string getLocalDescription() const {
     char *sdp = nullptr;
     pc->GetLocalDescription(&sdp);
     if (!sdp) {
       return "";
@@ -1196,173 +1245,217 @@ class SignalingAgentTest : public ::test
   void TearDown() {
     // Delete all the agents.
     for (size_t i=0; i < agents_.size(); i++) {
       delete agents_[i];
     }
   }
 
   bool CreateAgent() {
-    ScopedDeletePtr<SignalingAgent> agent(new SignalingAgent("agent"));
-
-    if (!agent->InitAllowFail(gThread))
-      return false;
+    return CreateAgent(g_stun_server_address, g_stun_server_port);
+  }
+
+  bool CreateAgent(const std::string stun_addr, uint16_t stun_port,
+                   bool wait_for_gather = true) {
+    ScopedDeletePtr<SignalingAgent> agent(
+        new SignalingAgent("agent", stun_addr, stun_port));
+
+    agent->Init(gThread);
+
+    if (wait_for_gather) {
+      if (!agent->WaitForGatherAllowFail())
+        return false;
+    }
 
     agents_.push_back(agent.forget());
 
     return true;
   }
 
   void CreateAgentNoInit() {
     ScopedDeletePtr<SignalingAgent> agent(new SignalingAgent("agent"));
     agents_.push_back(agent.forget());
   }
 
-  bool InitAgent(size_t i) {
-    return agents_[i]->InitAllowFail(gThread);
-  }
-
   SignalingAgent *agent(size_t i) {
     return agents_[i];
   }
 
  private:
   std::vector<SignalingAgent *> agents_;
 };
 
 
 class SignalingTest : public ::testing::Test {
 public:
-  SignalingTest() : a1_(callerName),
-                    a2_(calleeName) {}
+  SignalingTest()
+      : init_(false),
+        a1_(nullptr),
+        a2_(nullptr),
+        wait_for_gather_(true),
+        stun_addr_(g_stun_server_address),
+        stun_port_(g_stun_server_port) {}
+
+  SignalingTest(const std::string& stun_addr, uint16_t stun_port)
+      : a1_(nullptr),
+        a2_(nullptr),
+        wait_for_gather_(true),
+        stun_addr_(stun_addr),
+        stun_port_(stun_port) {}
 
   static void SetUpTestCase() {
     ASSERT_TRUE(SetupGlobalThread());
   }
 
-  void SetUp() {
-    a1_.Init(gThread);
-    a2_.Init(gThread);
+  void EnsureInit() {
+
+    if (init_)
+      return;
+
+    a1_ = new SignalingAgent(callerName, stun_addr_, stun_port_);
+    a2_ = new SignalingAgent(calleeName, stun_addr_, stun_port_);
+
+    a1_->Init(gThread);
+    a2_->Init(gThread);
+
+    if (wait_for_gather_) {
+      WaitForGather();
+    }
+  }
+
+  void WaitForGather() {
+    a1_->WaitForGather();
+    a2_->WaitForGather();
   }
 
   static void TearDownTestCase() {
     gThread = nullptr;
   }
 
   void CreateOffer(sipcc::MediaConstraints& constraints,
                    uint32_t offerFlags, uint32_t sdpCheck) {
-    a1_.CreateOffer(constraints, offerFlags, sdpCheck);
+    EnsureInit();
+    a1_->CreateOffer(constraints, offerFlags, sdpCheck);
   }
 
   void CreateSetOffer(sipcc::MediaConstraints& constraints, uint32_t sdpCheck) {
-    a1_.CreateOffer(constraints, OFFER_AV, sdpCheck);
-    a1_.SetLocal(TestObserver::OFFER, a1_.offer());
+    EnsureInit();
+    a1_->CreateOffer(constraints, OFFER_AV, sdpCheck);
+    a1_->SetLocal(TestObserver::OFFER, a1_->offer());
   }
 
   void OfferAnswer(sipcc::MediaConstraints& aconstraints,
                    sipcc::MediaConstraints& bconstraints,
                    uint32_t offerAnswerFlags,
                    bool finishAfterAnswer, uint32_t offerSdpCheck,
                    uint32_t answerSdpCheck) {
-    a1_.CreateOffer(aconstraints, offerAnswerFlags, offerSdpCheck);
-    a1_.SetLocal(TestObserver::OFFER, a1_.offer());
-    a2_.SetRemote(TestObserver::OFFER, a1_.offer());
-    a2_.CreateAnswer(bconstraints, a1_.offer(),
+    EnsureInit();
+    a1_->CreateOffer(aconstraints, offerAnswerFlags, offerSdpCheck);
+    a1_->SetLocal(TestObserver::OFFER, a1_->offer());
+    a2_->SetRemote(TestObserver::OFFER, a1_->offer());
+    a2_->CreateAnswer(bconstraints, a1_->offer(),
                      offerAnswerFlags, answerSdpCheck);
     if(true == finishAfterAnswer) {
-        a2_.SetLocal(TestObserver::ANSWER, a2_.answer());
-        a1_.SetRemote(TestObserver::ANSWER, a2_.answer());
-
-        ASSERT_TRUE_WAIT(a1_.IceCompleted() == true, kDefaultTimeout);
-        ASSERT_TRUE_WAIT(a2_.IceCompleted() == true, kDefaultTimeout);
+        a2_->SetLocal(TestObserver::ANSWER, a2_->answer());
+        a1_->SetRemote(TestObserver::ANSWER, a2_->answer());
+
+        ASSERT_TRUE_WAIT(a1_->IceCompleted() == true, kDefaultTimeout);
+        ASSERT_TRUE_WAIT(a2_->IceCompleted() == true, kDefaultTimeout);
     }
   }
 
   void OfferModifiedAnswer(sipcc::MediaConstraints& aconstraints,
                            sipcc::MediaConstraints& bconstraints,
                            uint32_t offerSdpCheck, uint32_t answerSdpCheck) {
-    a1_.CreateOffer(aconstraints, OFFER_AUDIO, offerSdpCheck);
-    a1_.SetLocal(TestObserver::OFFER, a1_.offer());
-    a2_.SetRemote(TestObserver::OFFER, a1_.offer());
-    a2_.CreateAnswer(bconstraints, a1_.offer(), OFFER_AUDIO | ANSWER_AUDIO,
+    EnsureInit();
+    a1_->CreateOffer(aconstraints, OFFER_AUDIO, offerSdpCheck);
+    a1_->SetLocal(TestObserver::OFFER, a1_->offer());
+    a2_->SetRemote(TestObserver::OFFER, a1_->offer());
+    a2_->CreateAnswer(bconstraints, a1_->offer(), OFFER_AUDIO | ANSWER_AUDIO,
                      answerSdpCheck);
-    a2_.SetLocal(TestObserver::ANSWER, a2_.answer());
-    ParsedSDP sdpWrapper(a2_.answer());
+    a2_->SetLocal(TestObserver::ANSWER, a2_->answer());
+    ParsedSDP sdpWrapper(a2_->answer());
     sdpWrapper.ReplaceLine("m=audio", "m=audio 65375 RTP/SAVPF 109 8 101\r\n");
     sdpWrapper.AddLine("a=rtpmap:8 PCMA/8000\r\n");
     std::cout << "Modified SDP " << std::endl
               << indent(sdpWrapper.getSdp()) << std::endl;
-    a1_.SetRemote(TestObserver::ANSWER, sdpWrapper.getSdp());
-    ASSERT_TRUE_WAIT(a1_.IceCompleted() == true, kDefaultTimeout);
-    ASSERT_TRUE_WAIT(a2_.IceCompleted() == true, kDefaultTimeout);
+    a1_->SetRemote(TestObserver::ANSWER, sdpWrapper.getSdp());
+    ASSERT_TRUE_WAIT(a1_->IceCompleted() == true, kDefaultTimeout);
+    ASSERT_TRUE_WAIT(a2_->IceCompleted() == true, kDefaultTimeout);
   }
 
   void OfferAnswerTrickle(sipcc::MediaConstraints& aconstraints,
                           sipcc::MediaConstraints& bconstraints,
                           uint32_t offerSdpCheck, uint32_t answerSdpCheck) {
-    a1_.CreateOffer(aconstraints, OFFER_AV, offerSdpCheck);
-    a1_.SetLocal(TestObserver::OFFER, a1_.offer());
-    ParsedSDP a1_offer(a1_.offer());
-    a2_.SetRemote(TestObserver::OFFER, a1_offer.sdp_without_ice_);
-    a2_.CreateAnswer(bconstraints, a1_offer.sdp_without_ice_,
+    EnsureInit();
+    a1_->CreateOffer(aconstraints, OFFER_AV, offerSdpCheck);
+    a1_->SetLocal(TestObserver::OFFER, a1_->offer());
+    ParsedSDP a1_offer(a1_->offer());
+    a2_->SetRemote(TestObserver::OFFER, a1_offer.sdp_without_ice_);
+    a2_->CreateAnswer(bconstraints, a1_offer.sdp_without_ice_,
                      OFFER_AV|ANSWER_AV, answerSdpCheck);
-    a2_.SetLocal(TestObserver::ANSWER, a2_.answer());
-    ParsedSDP a2_answer(a2_.answer());
-    a1_.SetRemote(TestObserver::ANSWER, a2_answer.sdp_without_ice_);
+    a2_->SetLocal(TestObserver::ANSWER, a2_->answer());
+    ParsedSDP a2_answer(a2_->answer());
+    a1_->SetRemote(TestObserver::ANSWER, a2_answer.sdp_without_ice_);
     // Now set the trickle ICE candidates
-    a1_.DoTrickleIce(a2_answer);
-    a2_.DoTrickleIce(a1_offer);
-    ASSERT_TRUE_WAIT(a1_.IceCompleted() == true, kDefaultTimeout);
-    ASSERT_TRUE_WAIT(a2_.IceCompleted() == true, kDefaultTimeout);
+    a1_->DoTrickleIce(a2_answer);
+    a2_->DoTrickleIce(a1_offer);
+    ASSERT_TRUE_WAIT(a1_->IceCompleted() == true, kDefaultTimeout);
+    ASSERT_TRUE_WAIT(a2_->IceCompleted() == true, kDefaultTimeout);
   }
 
 
   void OfferAnswerTrickleChrome(sipcc::MediaConstraints& aconstraints,
                           sipcc::MediaConstraints& bconstraints,
                           uint32_t offerSdpCheck, uint32_t answerSdpCheck) {
-    a1_.CreateOffer(aconstraints, OFFER_AV, offerSdpCheck);
-    a1_.SetLocal(TestObserver::OFFER, a1_.offer());
-    ParsedSDP a1_offer(a1_.offer());
-    a2_.SetRemote(TestObserver::OFFER, a1_offer.sdp_without_ice_);
-    a2_.CreateAnswer(bconstraints, a1_offer.sdp_without_ice_,
+    EnsureInit();
+    a1_->CreateOffer(aconstraints, OFFER_AV, offerSdpCheck);
+    a1_->SetLocal(TestObserver::OFFER, a1_->offer());
+    ParsedSDP a1_offer(a1_->offer());
+    a2_->SetRemote(TestObserver::OFFER, a1_offer.sdp_without_ice_);
+    a2_->CreateAnswer(bconstraints, a1_offer.sdp_without_ice_,
                      OFFER_AV|ANSWER_AV, answerSdpCheck);
-    a2_.SetLocal(TestObserver::ANSWER, a2_.answer());
-    ParsedSDP a2_answer(a2_.answer());
-    a1_.SetRemote(TestObserver::ANSWER, a2_answer.sdp_without_ice_);
+    a2_->SetLocal(TestObserver::ANSWER, a2_->answer());
+    ParsedSDP a2_answer(a2_->answer());
+    a1_->SetRemote(TestObserver::ANSWER, a2_answer.sdp_without_ice_);
     // Now set the trickle ICE candidates
-    a1_.DoTrickleIceChrome(a2_answer);
-    a2_.DoTrickleIceChrome(a1_offer);
-    ASSERT_TRUE_WAIT(a1_.IceCompleted() == true, kDefaultTimeout);
-    ASSERT_TRUE_WAIT(a2_.IceCompleted() == true, kDefaultTimeout);
+    a1_->DoTrickleIceChrome(a2_answer);
+    a2_->DoTrickleIceChrome(a1_offer);
+    ASSERT_TRUE_WAIT(a1_->IceCompleted() == true, kDefaultTimeout);
+    ASSERT_TRUE_WAIT(a2_->IceCompleted() == true, kDefaultTimeout);
   }
 
   void CreateOfferRemoveStream(sipcc::MediaConstraints& constraints,
                                uint32_t hints, uint32_t sdpCheck) {
+    EnsureInit();
     sipcc::MediaConstraints aconstraints;
     aconstraints.setBooleanConstraint("OfferToReceiveAudio", true, false);
     aconstraints.setBooleanConstraint("OfferToReceiveVideo", true, false);
-    a1_.CreateOffer(aconstraints, OFFER_AV, SHOULD_SENDRECV_AV );
-    a1_.CreateOfferRemoveStream(constraints, hints, sdpCheck);
+    a1_->CreateOffer(aconstraints, OFFER_AV, SHOULD_SENDRECV_AV );
+    a1_->CreateOfferRemoveStream(constraints, hints, sdpCheck);
   }
 
   void CreateOfferAudioOnly(sipcc::MediaConstraints& constraints,
                             uint32_t sdpCheck) {
-    a1_.CreateOffer(constraints, OFFER_AUDIO, sdpCheck);
+    EnsureInit();
+    a1_->CreateOffer(constraints, OFFER_AUDIO, sdpCheck);
   }
 
   void CreateOfferAddCandidate(sipcc::MediaConstraints& constraints,
                                const char * candidate, const char * mid,
                                unsigned short level, uint32_t sdpCheck) {
-    a1_.CreateOffer(constraints, OFFER_AV, sdpCheck);
-    a1_.AddIceCandidate(candidate, mid, level, true);
+    EnsureInit();
+    a1_->CreateOffer(constraints, OFFER_AV, sdpCheck);
+    a1_->AddIceCandidate(candidate, mid, level, true);
   }
 
   void AddIceCandidateEarly(const char * candidate, const char * mid,
                             unsigned short level) {
-    a1_.AddIceCandidate(candidate, mid, level, false);
+    EnsureInit();
+    a1_->AddIceCandidate(candidate, mid, level, false);
   }
 
   void CheckRtcpFbSdp(const std::string &sdp,
                       const std::set<std::string>& expected) {
 
     std::set<std::string>::const_iterator it;
 
     // Iterate through the list of expected feedback types and ensure
@@ -1383,22 +1476,23 @@ public:
                 << "'" << std::endl;
       ASSERT_NE(0U, expected.count(*it2));
     }
   }
 
   void TestRtcpFb(const std::set<std::string>& feedback,
                   uint32_t rtcpFbFlags,
                   VideoSessionConduit::FrameRequestType frameRequestMethod) {
+    EnsureInit();
     sipcc::MediaConstraints constraints;
 
-    a1_.CreateOffer(constraints, OFFER_AV, SHOULD_SENDRECV_AV);
-    a1_.SetLocal(TestObserver::OFFER, a1_.offer());
-
-    ParsedSDP sdpWrapper(a1_.offer());
+    a1_->CreateOffer(constraints, OFFER_AV, SHOULD_SENDRECV_AV);
+    a1_->SetLocal(TestObserver::OFFER, a1_->offer());
+
+    ParsedSDP sdpWrapper(a1_->offer());
 
     // Strip out any existing rtcp-fb lines
     sdpWrapper.DeleteAllLines("a=rtcp-fb:120");
 
     // Add rtcp-fb lines for the desired feedback types
     // We know that the video section is generated second (last),
     // so appending these to the end of the SDP has the desired effect.
     std::set<std::string>::const_iterator it;
@@ -1407,44 +1501,57 @@ public:
     }
 
     std::cout << "Modified SDP " << std::endl
               << indent(sdpWrapper.getSdp()) << std::endl;
 
     // Double-check that the offered SDP matches what we expect
     CheckRtcpFbSdp(sdpWrapper.getSdp(), feedback);
 
-    a2_.SetRemote(TestObserver::OFFER, sdpWrapper.getSdp());
-    a2_.CreateAnswer(constraints, sdpWrapper.getSdp(), OFFER_AV | ANSWER_AV);
-
-    CheckRtcpFbSdp(a2_.answer(), feedback);
-
-    a2_.SetLocal(TestObserver::ANSWER, a2_.answer());
-    a1_.SetRemote(TestObserver::ANSWER, a2_.answer());
-
-    ASSERT_TRUE_WAIT(a1_.IceCompleted() == true, kDefaultTimeout);
-    ASSERT_TRUE_WAIT(a2_.IceCompleted() == true, kDefaultTimeout);
-
-    a1_.CloseSendStreams();
-    a1_.CloseReceiveStreams();
-    a2_.CloseSendStreams();
-    a2_.CloseReceiveStreams();
+    a2_->SetRemote(TestObserver::OFFER, sdpWrapper.getSdp());
+    a2_->CreateAnswer(constraints, sdpWrapper.getSdp(), OFFER_AV | ANSWER_AV);
+
+    CheckRtcpFbSdp(a2_->answer(), feedback);
+
+    a2_->SetLocal(TestObserver::ANSWER, a2_->answer());
+    a1_->SetRemote(TestObserver::ANSWER, a2_->answer());
+
+    ASSERT_TRUE_WAIT(a1_->IceCompleted() == true, kDefaultTimeout);
+    ASSERT_TRUE_WAIT(a2_->IceCompleted() == true, kDefaultTimeout);
+
+    a1_->CloseSendStreams();
+    a1_->CloseReceiveStreams();
+    a2_->CloseSendStreams();
+    a2_->CloseReceiveStreams();
 
     // Check caller video settings for remote pipeline
-    a1_.CheckMediaPipeline(0, 2, (fRtcpMux ? PIPELINE_RTCP_MUX : 0) |
+    a1_->CheckMediaPipeline(0, 2, (fRtcpMux ? PIPELINE_RTCP_MUX : 0) |
       PIPELINE_SEND | PIPELINE_VIDEO | rtcpFbFlags, frameRequestMethod);
 
     // Check callee video settings for remote pipeline
-    a2_.CheckMediaPipeline(0, 2, (fRtcpMux ? PIPELINE_RTCP_MUX : 0) |
+    a2_->CheckMediaPipeline(0, 2, (fRtcpMux ? PIPELINE_RTCP_MUX : 0) |
       PIPELINE_VIDEO | rtcpFbFlags, frameRequestMethod);
   }
 
+  void SetTestStunServer() {
+    stun_addr_ = TestStunServer::GetInstance()->addr();
+    stun_port_ = TestStunServer::GetInstance()->port();
+
+    TestStunServer::GetInstance()->SetActive(false);
+    TestStunServer::GetInstance()->SetResponseAddr(
+        kBogusSrflxAddress, kBogusSrflxPort);
+  }
+
  protected:
-  SignalingAgent a1_;  // Canonically "caller"
-  SignalingAgent a2_;  // Canonically "callee"
+  bool init_;
+  ScopedDeletePtr<SignalingAgent> a1_;  // Canonically "caller"
+  ScopedDeletePtr<SignalingAgent> a2_;  // Canonically "callee"
+  bool wait_for_gather_;
+  std::string stun_addr_;
+  uint16_t stun_port_;
 };
 
 TEST_F(SignalingTest, JustInit)
 {
 }
 
 TEST_F(SignalingTest, CreateSetOffer)
 {
@@ -1811,131 +1918,133 @@ TEST_F(SignalingTest, OfferAnswerDontAdd
 
 TEST_F(SignalingTest, FullCall)
 {
   sipcc::MediaConstraints constraints;
   OfferAnswer(constraints, constraints, OFFER_AV | ANSWER_AV,
               true, SHOULD_SENDRECV_AV, SHOULD_SENDRECV_AV);
 
   // Wait for some data to get written