Merge m-c to fx-team.
authorRyan VanderMeulen <ryanvm@gmail.com>
Fri, 16 Aug 2013 15:34:58 -0400
changeset 143016 f304a101e40b31128e7b7baf3e00ba455f291f47
parent 143015 9fb8a7b295e6a9b85f6324aaee999a08e0ddfd34 (current diff)
parent 142875 72800965e07b9c35f8abeca0e553b2d342c0c1e3 (diff)
child 143017 b0bab66c0cabca60fac913d3a8895b0d9ac54d3c
push id32605
push userphilringnalda@gmail.com
push dateMon, 19 Aug 2013 00:51:46 +0000
treeherdermozilla-inbound@7f882e063eaf [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone26.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge m-c to fx-team.
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -31,16 +31,17 @@ MOCHITEST_FILES = \
         offlineEvent.cacheManifest^headers^ \
         offlineEvent.html \
         test_bug364677.html \
         test_bug395533.html \
         test_feed_discovery.html \
         test_offline_gzip.html \
         test_offlineNotification.html \
         video.ogg \
+        offlineByDefault.js \
         $(NULL)
 
 # test_contextmenu.html and test_contextmenu_input are disabled on Linux due to bug 513558
 ifndef MOZ_WIDGET_GTK
 MOCHITEST_FILES += \
         audio.ogg \
         privateBrowsingMode.js \
         subtst_contextmenu.html \
--- a/browser/base/content/test/browser_offlineQuotaNotification.js
+++ b/browser/base/content/test/browser_offlineQuotaNotification.js
@@ -9,16 +9,17 @@
 const URL = "http://mochi.test:8888/browser/browser/base/content/test/offlineQuotaNotification.html";
 
 registerCleanupFunction(function() {
   // Clean up after ourself
   let uri = Services.io.newURI(URL, null, null);
   var principal = Services.scriptSecurityManager.getNoAppCodebasePrincipal(uri);
   Services.perms.removeFromPrincipal(principal, "offline-app");
   Services.prefs.clearUserPref("offline-apps.quota.warn");
+  Services.prefs.clearUserPref("offline-apps.allow_by_default");
 });
 
 // Check that the "preferences" UI is opened and showing which websites have
 // offline storage permissions - currently this is the "network" tab in the
 // "advanced" pane.
 function checkPreferences(prefsWin) {
   // We expect a 'paneload' event for the 'advanced' pane, then
   // a 'select' event on the 'network' tab inside that pane.
@@ -65,10 +66,11 @@ function test() {
     };
     Services.prefs.setIntPref("offline-apps.quota.warn", 1);
 
     // Click the notification panel's "Allow" button.  This should kick
     // off updates which will call our oncached handler above.
     PopupNotifications.panel.firstElementChild.button.click();
   }, true);
 
+  Services.prefs.setBoolPref("offline-apps.allow_by_default", false);
   gBrowser.contentWindow.location = URL;
 }
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/offlineByDefault.js
@@ -0,0 +1,17 @@
+var offlineByDefault = {
+  defaultValue: false,
+  prefBranch: SpecialPowers.Cc["@mozilla.org/preferences-service;1"].getService(SpecialPowers.Ci.nsIPrefBranch),
+  set: function(allow) {
+    try {
+      this.defaultValue = this.prefBranch.getBoolPref("offline-apps.allow_by_default");
+    } catch (e) {
+      this.defaultValue = false
+    }
+    this.prefBranch.setBoolPref("offline-apps.allow_by_default", allow);
+  },
+  reset: function() {
+    this.prefBranch.setBoolPref("offline-apps.allow_by_default", this.defaultValue);
+  }
+}
+
+offlineByDefault.set(false);
--- a/browser/base/content/test/test_offlineNotification.html
+++ b/browser/base/content/test/test_offlineNotification.html
@@ -1,16 +1,17 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=462856
 -->
 <head>
   <title>Test offline app notification</title>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="offlineByDefault.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body onload="loaded()">
 <p id="display">
 <!-- Load the test frame twice from the same domain,
      to make sure we get notifications for both -->
 <iframe name="testFrame" src="offlineChild.html"></iframe>
 <iframe name="testFrame2" src="offlineChild2.html"></iframe>
@@ -47,16 +48,18 @@ window.addEventListener("message", funct
                         .getNoAppCodebasePrincipal(uri1);
       var principal2 = Cc["@mozilla.org/scriptsecuritymanager;1"]
                         .getService(SpecialPowers.Ci.nsIScriptSecurityManager)
                         .getNoAppCodebasePrincipal(uri2);
 
       pm.removeFromPrincipal(principal1, "offline-app");
       pm.removeFromPrincipal(principal2, "offline-app");
 
+      offlineByDefault.reset();
+
       SimpleTest.finish();
     }
   }, false);
 
 var count = 0;
 var expectedEvent = "";
 function eventHandler(evt) {
   ++count;
--- a/browser/base/content/test/test_offline_gzip.html
+++ b/browser/base/content/test/test_offline_gzip.html
@@ -8,16 +8,17 @@ Content-Type: gzip is added to the offli
 cache, it can be fetched from the cache successfully.
 -->
 <head>
   <title>Test gzipped offline resources</title>
   <script type="text/javascript" 
           src="/MochiKit/MochiKit.js"></script>
   <script type="text/javascript"
           src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="offlineByDefault.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
 </head>
 <body onload="loaded()">
 <p id="display">
 <iframe name="testFrame" src="gZipOfflineChild.html"></iframe>
 
 <div id="content" style="display: none">
 </div>
@@ -41,16 +42,17 @@ function finishTest() {
   var principal = Cc["@mozilla.org/scriptsecuritymanager;1"]
                    .getService(SpecialPowers.Ci.nsIScriptSecurityManager)
                    .getNoAppCodebasePrincipal(uri);
 
   pm.removeFromPrincipal(principal, "offline-app");
 
   window.removeEventListener("message", handleMessageEvents, false);
 
+  offlineByDefault.reset();
   SimpleTest.finish();  
 }
 
 ////
 // Handle "message" events which are posted from the iframe upon
 // offline cache events.
 //
 function handleMessageEvents(event) {
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -1499,16 +1499,22 @@ public:
   static bool OfflineAppAllowed(nsIURI *aURI);
 
   /**
    * Check whether an application should be allowed to use offline APIs.
    */
   static bool OfflineAppAllowed(nsIPrincipal *aPrincipal);
 
   /**
+   * If offline-apps.allow_by_default is true, we set offline-app permission
+   * for the principal and return true.  Otherwise false.
+   */
+  static bool MaybeAllowOfflineAppByDefault(nsIPrincipal *aPrincipal);
+
+  /**
    * Increases the count of blockers preventing scripts from running.
    * NOTE: You might want to use nsAutoScriptBlocker rather than calling
    * this directly
    */
   static void AddScriptBlocker();
 
   /**
    * Decreases the count of blockers preventing scripts from running.
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -1056,18 +1056,21 @@ nsContentSink::ProcessOfflineManifest(co
     }
 
     // Documents must list a manifest from the same origin
     rv = mDocument->NodePrincipal()->CheckMayLoad(manifestURI, true, false);
     if (NS_FAILED(rv)) {
       action = CACHE_SELECTION_RESELECT_WITHOUT_MANIFEST;
     }
     else {
-      // Only continue if the document has permission to use offline APIs.
-      if (!nsContentUtils::OfflineAppAllowed(mDocument->NodePrincipal())) {
+      // Only continue if the document has permission to use offline APIs or
+      // when preferences indicate to permit it automatically.
+      if (!nsContentUtils::OfflineAppAllowed(mDocument->NodePrincipal()) &&
+          !nsContentUtils::MaybeAllowOfflineAppByDefault(mDocument->NodePrincipal()) &&
+          !nsContentUtils::OfflineAppAllowed(mDocument->NodePrincipal())) {
         return;
       }
 
       bool fetchedWithHTTPGetOrEquiv = false;
       nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(mDocument->GetChannel()));
       if (httpChannel) {
         nsAutoCString method;
         rv = httpChannel->GetRequestMethod(method);
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -1400,16 +1400,48 @@ nsContentUtils::OfflineAppAllowed(nsIPri
 
   bool allowed;
   nsresult rv = updateService->OfflineAppAllowed(aPrincipal,
                                                  Preferences::GetRootBranch(),
                                                  &allowed);
   return NS_SUCCEEDED(rv) && allowed;
 }
 
+bool
+nsContentUtils::MaybeAllowOfflineAppByDefault(nsIPrincipal *aPrincipal)
+{
+  if (!Preferences::GetRootBranch())
+    return false;
+
+  nsresult rv;
+
+  bool allowedByDefault;
+  rv = Preferences::GetRootBranch()->GetBoolPref(
+    "offline-apps.allow_by_default", &allowedByDefault);
+  if (NS_FAILED(rv))
+    return false;
+
+  if (!allowedByDefault)
+    return false;
+
+  nsCOMPtr<nsIPermissionManager> permissionManager =
+      do_GetService(NS_PERMISSIONMANAGER_CONTRACTID);
+  if (!permissionManager)
+    return false;
+
+  rv = permissionManager->AddFromPrincipal(
+    aPrincipal, "offline-app", nsIPermissionManager::ALLOW_ACTION,
+    nsIPermissionManager::EXPIRE_NEVER, 0);
+  if (NS_FAILED(rv))
+    return false;
+
+  // We have added the permission
+  return true;
+}
+
 // static
 void
 nsContentUtils::Shutdown()
 {
   sInitialized = false;
 
   NS_IF_RELEASE(sContentPolicyService);
   sTriedToGetContentPolicy = false;
@@ -3186,19 +3218,22 @@ nsContentUtils::IsEventAttributeName(nsI
   EventNameMapping mapping;
   return (sAtomEventTable->Get(aName, &mapping) && mapping.mType & aType);
 }
 
 // static
 uint32_t
 nsContentUtils::GetEventId(nsIAtom* aName)
 {
-  EventNameMapping mapping;
-  if (sAtomEventTable->Get(aName, &mapping))
-    return mapping.mId;
+  if (aName) {
+    EventNameMapping mapping;
+    if (sAtomEventTable->Get(aName, &mapping)) {
+      return mapping.mId;
+    }
+  }
 
   return NS_USER_DEFINED_EVENT;
 }
 
 // static
 uint32_t
 nsContentUtils::GetEventCategory(const nsAString& aName)
 {
--- a/content/base/src/nsINode.cpp
+++ b/content/base/src/nsINode.cpp
@@ -2165,23 +2165,25 @@ nsINode::SizeOfExcludingThis(MallocSizeO
   // - mParent, mNextSibling, mPreviousSibling, mFirstChild: because they're
   //   non-owning
   return n;
 }
 
 #define EVENT(name_, id_, type_, struct_)                                    \
   EventHandlerNonNull* nsINode::GetOn##name_() {                             \
     nsEventListenerManager *elm = GetListenerManager(false);                 \
-    return elm ? elm->GetEventHandler(nsGkAtoms::on##name_) : nullptr;       \
+    return elm ? elm->GetEventHandler(nsGkAtoms::on##name_, EmptyString())   \
+               : nullptr;                                                    \
   }                                                                          \
   void nsINode::SetOn##name_(EventHandlerNonNull* handler,                   \
                              ErrorResult& error) {                           \
     nsEventListenerManager *elm = GetListenerManager(true);                  \
     if (elm) {                                                               \
-      error = elm->SetEventHandler(nsGkAtoms::on##name_, handler);           \
+      error = elm->SetEventHandler(nsGkAtoms::on##name_,                     \
+                                   EmptyString(), handler);                  \
     } else {                                                                 \
       error.Throw(NS_ERROR_OUT_OF_MEMORY);                                   \
     }                                                                        \
   }                                                                          \
   NS_IMETHODIMP nsINode::GetOn##name_(JSContext *cx, JS::Value *vp) {        \
     EventHandlerNonNull* h = GetOn##name_();                                 \
     vp->setObjectOrNull(h ? h->Callable().get() : nullptr);                  \
     return NS_OK;                                                            \
--- a/content/events/public/EventTarget.h
+++ b/content/events/public/EventTarget.h
@@ -43,42 +43,41 @@ public:
                                 const Nullable<bool>& aWantsUntrusted,
                                 ErrorResult& aRv) = 0;
   virtual void RemoveEventListener(const nsAString& aType,
                                    nsIDOMEventListener* aCallback,
                                    bool aCapture,
                                    ErrorResult& aRv);
   bool DispatchEvent(nsDOMEvent& aEvent, ErrorResult& aRv);
 
+  // Note, this takes the type in onfoo form!
   EventHandlerNonNull* GetEventHandler(const nsAString& aType)
   {
     nsCOMPtr<nsIAtom> type = do_GetAtom(aType);
-    return GetEventHandler(type);
+    return GetEventHandler(type, EmptyString());
   }
 
+  // Note, this takes the type in onfoo form!
   void SetEventHandler(const nsAString& aType, EventHandlerNonNull* aHandler,
-                       ErrorResult& rv)
-  {
-    nsCOMPtr<nsIAtom> type = do_GetAtom(aType);
-    return SetEventHandler(type, aHandler, rv);
-  }
+                       ErrorResult& rv);
 
   // Note, for an event 'foo' aType will be 'onfoo'.
   virtual void EventListenerAdded(nsIAtom* aType) {}
   virtual void EventListenerRemoved(nsIAtom* aType) {}
 
   // Returns an outer window that corresponds to the inner window this event
   // target is associated with.  Will return null if the inner window is not the
   // current inner or if there is no window around at all.
   virtual nsIDOMWindow* GetOwnerGlobal() = 0;
 
 protected:
-  EventHandlerNonNull* GetEventHandler(nsIAtom* aType);
-  void SetEventHandler(nsIAtom* aType, EventHandlerNonNull* aHandler,
-                       ErrorResult& rv);
+  EventHandlerNonNull* GetEventHandler(nsIAtom* aType,
+                                       const nsAString& aTypeString);
+  void SetEventHandler(nsIAtom* aType, const nsAString& aTypeString,
+                       EventHandlerNonNull* aHandler, ErrorResult& rv);
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(EventTarget, NS_EVENTTARGET_IID)
 
 } // namespace dom
 } // namespace mozilla
 
 #endif // mozilla_dom_EventTarget_h_
--- a/content/events/src/EventTarget.cpp
+++ b/content/events/src/EventTarget.cpp
@@ -18,23 +18,40 @@ EventTarget::RemoveEventListener(const n
 {
   nsEventListenerManager* elm = GetListenerManager(false);
   if (elm) {
     elm->RemoveEventListener(aType, aListener, aUseCapture);
   }
 }
 
 EventHandlerNonNull*
-EventTarget::GetEventHandler(nsIAtom* aType)
+EventTarget::GetEventHandler(nsIAtom* aType, const nsAString& aTypeString)
 {
   nsEventListenerManager* elm = GetListenerManager(false);
-  return elm ? elm->GetEventHandler(aType) : nullptr;
+  return elm ? elm->GetEventHandler(aType, aTypeString) : nullptr;
 }
 
 void
-EventTarget::SetEventHandler(nsIAtom* aType, EventHandlerNonNull* aHandler,
+EventTarget::SetEventHandler(const nsAString& aType,
+                             EventHandlerNonNull* aHandler,
                              ErrorResult& rv)
 {
-  rv = GetListenerManager(true)->SetEventHandler(aType, aHandler);
+  if (NS_IsMainThread()) {
+    nsCOMPtr<nsIAtom> type = do_GetAtom(aType);
+    return SetEventHandler(type, EmptyString(), aHandler, rv);
+  }
+  return SetEventHandler(nullptr,
+                         Substring(aType, 2), // Remove "on"
+                         aHandler, rv);
+}
+
+void
+EventTarget::SetEventHandler(nsIAtom* aType, const nsAString& aTypeString,
+                             EventHandlerNonNull* aHandler,
+                             ErrorResult& rv)
+{
+  rv = GetListenerManager(true)->SetEventHandler(aType,
+                                                 aTypeString,
+                                                 aHandler);
 }
 
 } // namespace dom
 } // namespace mozilla
--- a/content/events/src/nsDOMEvent.cpp
+++ b/content/events/src/nsDOMEvent.cpp
@@ -53,16 +53,17 @@ nsDOMEvent::nsDOMEvent(nsPIDOMWindow* aP
 }
 
 void
 nsDOMEvent::ConstructorInit(mozilla::dom::EventTarget* aOwner,
                             nsPresContext* aPresContext, nsEvent* aEvent)
 {
   SetIsDOMBinding();
   SetOwner(aOwner);
+  mIsMainThreadEvent = mOwner || NS_IsMainThread();
 
   mPrivateDataDuplicated = false;
 
   if (aEvent) {
     mEvent = aEvent;
     mEventIsInternal = false;
   }
   else {
@@ -217,29 +218,28 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mExplicitOriginalTarget)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOwner)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 // nsIDOMEventInterface
 NS_METHOD nsDOMEvent::GetType(nsAString& aType)
 {
-  if (!mCachedType.IsEmpty()) {
-    aType = mCachedType;
+  if (!mIsMainThreadEvent || !mEvent->typeString.IsEmpty()) {
+    aType = mEvent->typeString;
     return NS_OK;
   }
   const char* name = GetEventName(mEvent->message);
 
   if (name) {
     CopyASCIItoUTF16(name, aType);
-    mCachedType = aType;
     return NS_OK;
   } else if (mEvent->message == NS_USER_DEFINED_EVENT && mEvent->userType) {
     aType = Substring(nsDependentAtomString(mEvent->userType), 2); // Remove "on"
-    mCachedType = aType;
+    mEvent->typeString = aType;
     return NS_OK;
   }
 
   aType.Truncate();
   return NS_OK;
 }
 
 static EventTarget*
@@ -455,19 +455,25 @@ nsDOMEvent::PreventDefault()
   }
 
   return NS_OK;
 }
 
 void
 nsDOMEvent::SetEventType(const nsAString& aEventTypeArg)
 {
-  mEvent->userType =
-    nsContentUtils::GetEventIdAndAtom(aEventTypeArg, mEvent->eventStructType,
-                                      &(mEvent->message));
+  if (mIsMainThreadEvent) {
+    mEvent->userType =
+      nsContentUtils::GetEventIdAndAtom(aEventTypeArg, mEvent->eventStructType,
+                                        &(mEvent->message));
+  } else {
+    mEvent->userType = nullptr;
+    mEvent->message = NS_USER_DEFINED_EVENT;
+    mEvent->typeString = aEventTypeArg;
+  }
 }
 
 NS_IMETHODIMP
 nsDOMEvent::InitEvent(const nsAString& aEventTypeArg, bool aCanBubbleArg, bool aCancelableArg)
 {
   // Make sure this event isn't already being dispatched.
   NS_ENSURE_TRUE(!mEvent->mFlags.mIsBeingDispatched, NS_OK);
 
@@ -484,17 +490,16 @@ nsDOMEvent::InitEvent(const nsAString& a
   mEvent->mFlags.mCancelable = aCancelableArg;
 
   mEvent->mFlags.mDefaultPrevented = false;
 
   // Clearing the old targets, so that the event is targeted correctly when
   // re-dispatching it.
   mEvent->target = nullptr;
   mEvent->originalTarget = nullptr;
-  mCachedType = aEventTypeArg;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMEvent::DuplicatePrivateData()
 {
   // FIXME! Simplify this method and make it somehow easily extendable,
   //        Bug 329127
--- a/content/events/src/nsDOMEvent.h
+++ b/content/events/src/nsDOMEvent.h
@@ -180,19 +180,19 @@ protected:
   // Internal helper functions
   void SetEventType(const nsAString& aEventTypeArg);
   already_AddRefed<nsIContent> GetTargetFromFrame();
 
   nsEvent*                    mEvent;
   nsRefPtr<nsPresContext>     mPresContext;
   nsCOMPtr<mozilla::dom::EventTarget> mExplicitOriginalTarget;
   nsCOMPtr<nsPIDOMWindow>     mOwner; // nsPIDOMWindow for now.
-  nsString                    mCachedType;
   bool                        mEventIsInternal;
   bool                        mPrivateDataDuplicated;
+  bool                        mIsMainThreadEvent;
 };
 
 #define NS_FORWARD_TO_NSDOMEVENT \
   NS_FORWARD_NSIDOMEVENT(nsDOMEvent::)
 
 #define NS_FORWARD_NSIDOMEVENT_NO_SERIALIZATION_NO_DUPLICATION(_to) \
   NS_IMETHOD GetType(nsAString& aType){ return _to GetType(aType); } \
   NS_IMETHOD GetTarget(nsIDOMEventTarget * *aTarget) { return _to GetTarget(aTarget); } \
--- a/content/events/src/nsDOMEventTargetHelper.cpp
+++ b/content/events/src/nsDOMEventTargetHelper.cpp
@@ -287,26 +287,26 @@ nsDOMEventTargetHelper::SetEventHandler(
 {
   nsRefPtr<EventHandlerNonNull> handler;
   JSObject* callable;
   if (aValue.isObject() &&
       JS_ObjectIsCallable(aCx, callable = &aValue.toObject())) {
     handler = new EventHandlerNonNull(callable);
   }
   ErrorResult rv;
-  SetEventHandler(aType, handler, rv);
+  SetEventHandler(aType, EmptyString(), handler, rv);
   return rv.ErrorCode();
 }
 
 void
 nsDOMEventTargetHelper::GetEventHandler(nsIAtom* aType,
                                         JSContext* aCx,
                                         JS::Value* aValue)
 {
-  EventHandlerNonNull* handler = GetEventHandler(aType);
+  EventHandlerNonNull* handler = GetEventHandler(aType, EmptyString());
   if (handler) {
     *aValue = JS::ObjectValue(*handler->Callable());
   } else {
     *aValue = JS::NullValue();
   }
 }
 
 nsresult
--- a/content/events/src/nsDOMEventTargetHelper.h
+++ b/content/events/src/nsDOMEventTargetHelper.h
@@ -163,22 +163,31 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsDOMEvent
     {                                                                         \
       return _baseclass::SetOn##_event(aCx, aValue);                          \
     }
 
 // WebIDL event handlers
 #define IMPL_EVENT_HANDLER(_event)                                        \
   inline mozilla::dom::EventHandlerNonNull* GetOn##_event()               \
   {                                                                       \
-    return GetEventHandler(nsGkAtoms::on##_event);                        \
+    if (NS_IsMainThread()) {                                              \
+      return GetEventHandler(nsGkAtoms::on##_event, EmptyString());       \
+    }                                                                     \
+    return GetEventHandler(nullptr, NS_LITERAL_STRING(#_event));          \
   }                                                                       \
   inline void SetOn##_event(mozilla::dom::EventHandlerNonNull* aCallback, \
                             mozilla::ErrorResult& aRv)                    \
   {                                                                       \
-    SetEventHandler(nsGkAtoms::on##_event, aCallback, aRv);               \
+    if (NS_IsMainThread()) {                                              \
+      SetEventHandler(nsGkAtoms::on##_event, EmptyString(),               \
+                      aCallback, aRv);                                    \
+    } else {                                                              \
+      SetEventHandler(nullptr, NS_LITERAL_STRING(#_event),                \
+                      aCallback, aRv);                                    \
+    }                                                                     \
   }
 
 /* Use this macro to declare functions that forward the behavior of this
  * interface to another object.
  * This macro doesn't forward PreHandleEvent because sometimes subclasses
  * want to override it.
  */
 #define NS_FORWARD_NSIDOMEVENTTARGET_NOPREHANDLEEVENT(_to) \
--- a/content/events/src/nsEventDispatcher.cpp
+++ b/content/events/src/nsEventDispatcher.cpp
@@ -47,74 +47,37 @@ private:
 #define NS_TARGET_CHAIN_FORCE_CONTENT_DISPATCH  (1 << 0)
 #define NS_TARGET_CHAIN_WANTS_WILL_HANDLE_EVENT (1 << 1)
 #define NS_TARGET_CHAIN_MAY_HAVE_MANAGER        (1 << 2)
 
 // nsEventTargetChainItem represents a single item in the event target chain.
 class nsEventTargetChainItem
 {
 private:
-  nsEventTargetChainItem(EventTarget* aTarget,
-                         nsEventTargetChainItem* aChild = nullptr);
-
-  // This is the ETCI recycle pool, which is used to avoid some malloc/free
-  // churn.  It's implemented as a linked list.
-  static nsEventTargetChainItem* sEtciRecyclePool;
-  static uint32_t sNumRecycledEtcis;
-  static const uint32_t kMaxNumRecycledEtcis = 128;
-
+  nsEventTargetChainItem(EventTarget* aTarget);
 public:
-  static nsEventTargetChainItem* Create(EventTarget* aTarget,
-                                        nsEventTargetChainItem* aChild = nullptr)
+  nsEventTargetChainItem()
+  : mFlags(0), mItemFlags(0)
   {
-    // Allocate from the ETCI recycle pool if possible.
-    void* place = nullptr;
-    if (sNumRecycledEtcis > 0) {
-      MOZ_ASSERT(sEtciRecyclePool);
-      place = sEtciRecyclePool;
-      sEtciRecyclePool = sEtciRecyclePool->mNext;
-      --sNumRecycledEtcis;
-    } else {
-      place = malloc(sizeof(nsEventTargetChainItem));
-    }
-    return place
-      ? ::new (place) nsEventTargetChainItem(aTarget, aChild)
-      : nullptr;
   }
 
-  static void Destroy(nsEventTargetChainItem* aItem)
+  static nsEventTargetChainItem* Create(nsTArray<nsEventTargetChainItem>& aChain,
+                                        EventTarget* aTarget,
+                                        nsEventTargetChainItem* aChild = nullptr)
   {
-    // ::Destroy deletes ancestor chain.
-    nsEventTargetChainItem* item = aItem;
-    if (item->mChild) {
-      item->mChild->mParent = nullptr;
-      item->mChild = nullptr;
-    }
-    // Put destroyed ETCIs into the recycle pool if it's not already full.
-    while (item) {
-      nsEventTargetChainItem* parent = item->mParent;
-      item->~nsEventTargetChainItem();
-      if (sNumRecycledEtcis < kMaxNumRecycledEtcis) {
-        item->mNext = sEtciRecyclePool;
-        sEtciRecyclePool = item;
-        ++sNumRecycledEtcis;
-      } else {
-        free(item);
-      }
-      item = parent;
-    }
+    MOZ_ASSERT(!aChild || &aChain.ElementAt(aChain.Length() - 1) == aChild);
+    return new (aChain.AppendElement()) nsEventTargetChainItem(aTarget);
   }
 
-  static void ShutdownRecyclePool()
+  static void DestroyLast(nsTArray<nsEventTargetChainItem>& aChain,
+                          nsEventTargetChainItem* aItem)
   {
-    while (sEtciRecyclePool) {
-      nsEventTargetChainItem* tmp = sEtciRecyclePool;
-      sEtciRecyclePool = sEtciRecyclePool->mNext;
-      free(tmp);
-    }
+    uint32_t lastIndex = aChain.Length() - 1;
+    MOZ_ASSERT(&aChain[lastIndex] == aItem);
+    aChain.RemoveElementAt(lastIndex);
   }
 
   bool IsValid()
   {
     NS_WARN_IF_FALSE(!!(mTarget), "Event target is not valid!");
     return !!(mTarget);
   }
 
@@ -176,20 +139,21 @@ public:
   }
 
   /**
    * Dispatches event through the event target chain.
    * Handles capture, target and bubble phases both in default
    * and system event group and calls also PostHandleEvent for each
    * item in the chain.
    */
-  nsresult HandleEventTargetChain(nsEventChainPostVisitor& aVisitor,
-                                  nsDispatchingCallback* aCallback,
-                                  ELMCreationDetector& aCd,
-                                  nsCxPusher* aPusher);
+  static void HandleEventTargetChain(nsTArray<nsEventTargetChainItem>& aChain,
+                                     nsEventChainPostVisitor& aVisitor,
+                                     nsDispatchingCallback* aCallback,
+                                     ELMCreationDetector& aCd,
+                                     nsCxPusher* aPusher);
 
   /**
    * Resets aVisitor object and calls PreHandleEvent.
    * Copies mItemFlags and mItemData to the current nsEventTargetChainItem.
    */
   nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
 
   /**
@@ -228,54 +192,30 @@ public:
   }
 
   /**
    * Copies mItemFlags and mItemData to aVisitor and calls PostHandleEvent.
    */
   nsresult PostHandleEvent(nsEventChainPostVisitor& aVisitor,
                            nsCxPusher* aPusher);
 
-  static uint32_t MaxEtciCount() { return sMaxEtciCount; }
-
-  static void ResetMaxEtciCount()
-  {
-    MOZ_ASSERT(!sCurrentEtciCount, "Wrong time to call ResetMaxEtciCount()!");
-    sMaxEtciCount = 0;
-  }
-
   nsCOMPtr<EventTarget>             mTarget;
-  nsEventTargetChainItem*           mChild;
-  union {
-    nsEventTargetChainItem*         mParent;
-     // This is used only when recycling ETCIs.
-    nsEventTargetChainItem*         mNext;
-  };
   uint16_t                          mFlags;
   uint16_t                          mItemFlags;
   nsCOMPtr<nsISupports>             mItemData;
   // Event retargeting must happen whenever mNewTarget is non-null.
   nsCOMPtr<EventTarget>             mNewTarget;
   // Cache mTarget's event listener manager.
   nsRefPtr<nsEventListenerManager>  mManager;
-
-  static uint32_t                   sMaxEtciCount;
-  static uint32_t                   sCurrentEtciCount;
 };
 
-nsEventTargetChainItem* nsEventTargetChainItem::sEtciRecyclePool = nullptr;
-uint32_t nsEventTargetChainItem::sNumRecycledEtcis = 0;
-
-nsEventTargetChainItem::nsEventTargetChainItem(EventTarget* aTarget,
-                                               nsEventTargetChainItem* aChild)
-: mTarget(aTarget), mChild(aChild), mParent(nullptr), mFlags(0), mItemFlags(0)
+nsEventTargetChainItem::nsEventTargetChainItem(EventTarget* aTarget)
+: mTarget(aTarget), mFlags(0), mItemFlags(0)
 {
   MOZ_ASSERT(!aTarget || mTarget == aTarget->GetTargetForEventTargetChain());
-  if (mChild) {
-    mChild->mParent = this;
-  }
 }
 
 nsresult
 nsEventTargetChainItem::PreHandleEvent(nsEventChainPreVisitor& aVisitor)
 {
   aVisitor.Reset();
   nsresult rv = mTarget->PreHandleEvent(aVisitor);
   SetForceContentDispatch(aVisitor.mForceContentDispatch);
@@ -292,86 +232,85 @@ nsEventTargetChainItem::PostHandleEvent(
 {
   aPusher->Pop();
   aVisitor.mItemFlags = mItemFlags;
   aVisitor.mItemData = mItemData;
   mTarget->PostHandleEvent(aVisitor);
   return NS_OK;
 }
 
-nsresult
+void
 nsEventTargetChainItem::HandleEventTargetChain(
+                          nsTArray<nsEventTargetChainItem>& aChain,
                           nsEventChainPostVisitor& aVisitor,
                           nsDispatchingCallback* aCallback,
                           ELMCreationDetector& aCd,
                           nsCxPusher* aPusher)
 {
   // Save the target so that it can be restored later.
   nsCOMPtr<EventTarget> firstTarget = aVisitor.mEvent->target;
+  uint32_t chainLength = aChain.Length();
 
   // Capture
-  nsEventTargetChainItem* item = this;
   aVisitor.mEvent->mFlags.mInCapturePhase = true;
   aVisitor.mEvent->mFlags.mInBubblingPhase = false;
-  while (item->mChild) {
+  for (uint32_t i = chainLength - 1; i > 0; --i) {
+    nsEventTargetChainItem& item = aChain[i];
     if ((!aVisitor.mEvent->mFlags.mNoContentDispatch ||
-         item->ForceContentDispatch()) &&
+         item.ForceContentDispatch()) &&
         !aVisitor.mEvent->mFlags.mPropagationStopped) {
-      item->HandleEvent(aVisitor, aCd, aPusher);
+      item.HandleEvent(aVisitor, aCd, aPusher);
     }
 
-    if (item->GetNewTarget()) {
+    if (item.GetNewTarget()) {
       // item is at anonymous boundary. Need to retarget for the child items.
-      nsEventTargetChainItem* nextTarget = item->mChild;
-      while (nextTarget) {
-        EventTarget* newTarget = nextTarget->GetNewTarget();
+      for (uint32_t j = i; j > 0; --j) {
+        uint32_t childIndex = j - 1;
+        EventTarget* newTarget = aChain[childIndex].GetNewTarget();
         if (newTarget) {
           aVisitor.mEvent->target = newTarget;
           break;
         }
-        nextTarget = nextTarget->mChild;
       }
     }
-
-    item = item->mChild;
   }
 
   // Target
   aVisitor.mEvent->mFlags.mInBubblingPhase = true;
+  nsEventTargetChainItem& targetItem = aChain[0];
   if (!aVisitor.mEvent->mFlags.mPropagationStopped &&
       (!aVisitor.mEvent->mFlags.mNoContentDispatch ||
-       item->ForceContentDispatch())) {
-    item->HandleEvent(aVisitor, aCd, aPusher);
+       targetItem.ForceContentDispatch())) {
+    targetItem.HandleEvent(aVisitor, aCd, aPusher);
   }
   if (aVisitor.mEvent->mFlags.mInSystemGroup) {
-    item->PostHandleEvent(aVisitor, aPusher);
+    targetItem.PostHandleEvent(aVisitor, aPusher);
   }
 
   // Bubble
   aVisitor.mEvent->mFlags.mInCapturePhase = false;
-  item = item->mParent;
-  while (item) {
-    EventTarget* newTarget = item->GetNewTarget();
+  for (uint32_t i = 1; i < chainLength; ++i) {
+    nsEventTargetChainItem& item = aChain[i];
+    EventTarget* newTarget = item.GetNewTarget();
     if (newTarget) {
       // Item is at anonymous boundary. Need to retarget for the current item
       // and for parent items.
       aVisitor.mEvent->target = newTarget;
     }
 
     if (aVisitor.mEvent->mFlags.mBubbles || newTarget) {
       if ((!aVisitor.mEvent->mFlags.mNoContentDispatch ||
-           item->ForceContentDispatch()) &&
+           item.ForceContentDispatch()) &&
           !aVisitor.mEvent->mFlags.mPropagationStopped) {
-        item->HandleEvent(aVisitor, aCd, aPusher);
+        item.HandleEvent(aVisitor, aCd, aPusher);
       }
       if (aVisitor.mEvent->mFlags.mInSystemGroup) {
-        item->PostHandleEvent(aVisitor, aPusher);
+        item.PostHandleEvent(aVisitor, aPusher);
       }
     }
-    item = item->mParent;
   }
   aVisitor.mEvent->mFlags.mInBubblingPhase = false;
 
   if (!aVisitor.mEvent->mFlags.mInSystemGroup) {
     // Dispatch to the system event group.  Make sure to clear the
     // STOP_DISPATCH flag since this resets for each event group.
     aVisitor.mEvent->mFlags.mPropagationStopped = false;
     aVisitor.mEvent->mFlags.mImmediatePropagationStopped = false;
@@ -385,53 +324,48 @@ nsEventTargetChainItem::HandleEventTarge
       aPusher->Pop();
       aCallback->HandleEvent(aVisitor);
     }
 
     // Retarget for system event group (which does the default handling too).
     // Setting back the target which was used also for default event group.
     aVisitor.mEvent->target = firstTarget;
     aVisitor.mEvent->mFlags.mInSystemGroup = true;
-    HandleEventTargetChain(aVisitor,
+    HandleEventTargetChain(aChain,
+                           aVisitor,
                            aCallback,
                            aCd,
                            aPusher);
     aVisitor.mEvent->mFlags.mInSystemGroup = false;
 
     // After dispatch, clear all the propagation flags so that
     // system group listeners don't affect to the event.
     aVisitor.mEvent->mFlags.mPropagationStopped = false;
     aVisitor.mEvent->mFlags.mImmediatePropagationStopped = false;
   }
-
-  return NS_OK;
-}
-
-void NS_ShutdownEventTargetChainItemRecyclePool()
-{
-  nsEventTargetChainItem::ShutdownRecyclePool();
 }
 
 nsEventTargetChainItem*
-EventTargetChainItemForChromeTarget(nsINode* aNode,
+EventTargetChainItemForChromeTarget(nsTArray<nsEventTargetChainItem>& aChain,
+                                    nsINode* aNode,
                                     nsEventTargetChainItem* aChild = nullptr)
 {
   if (!aNode->IsInDoc()) {
     return nullptr;
   }
   nsPIDOMWindow* win = aNode->OwnerDoc()->GetInnerWindow();
   EventTarget* piTarget = win ? win->GetParentTarget() : nullptr;
   NS_ENSURE_TRUE(piTarget, nullptr);
 
   nsEventTargetChainItem* etci =
-    nsEventTargetChainItem::Create(piTarget->GetTargetForEventTargetChain(),
+    nsEventTargetChainItem::Create(aChain,
+                                   piTarget->GetTargetForEventTargetChain(),
                                    aChild);
-  NS_ENSURE_TRUE(etci, nullptr);
   if (!etci->IsValid()) {
-    nsEventTargetChainItem::Destroy(etci);
+    nsEventTargetChainItem::DestroyLast(aChain, etci);
     return nullptr;
   }
   return etci;
 }
 
 /* static */ nsresult
 nsEventDispatcher::Dispatch(nsISupports* aTarget,
                             nsPresContext* aPresContext,
@@ -517,22 +451,23 @@ nsEventDispatcher::Dispatch(nsISupports*
 
   nsresult rv = NS_OK;
   bool externalDOMEvent = !!(aDOMEvent);
 
   // If we have a PresContext, make sure it doesn't die before
   // event dispatching is finished.
   nsRefPtr<nsPresContext> kungFuDeathGrip(aPresContext);
 
+  nsTArray<nsEventTargetChainItem> chain(128);
+
   // Create the event target chain item for the event target.
   nsEventTargetChainItem* targetEtci =
-    nsEventTargetChainItem::Create(target->GetTargetForEventTargetChain());
-  NS_ENSURE_TRUE(targetEtci, NS_ERROR_OUT_OF_MEMORY);
+    nsEventTargetChainItem::Create(chain, target->GetTargetForEventTargetChain());
   if (!targetEtci->IsValid()) {
-    nsEventTargetChainItem::Destroy(targetEtci);
+    nsEventTargetChainItem::DestroyLast(chain, targetEtci);
     return NS_ERROR_FAILURE;
   }
 
   // Make sure that nsIDOMEvent::target and nsIDOMEvent::originalTarget
   // point to the last item in the chain.
   if (!aEvent->target) {
     // Note, CurrentTarget() points always to the object returned by
     // GetTargetForEventTargetChain().
@@ -565,60 +500,58 @@ nsEventDispatcher::Dispatch(nsISupports*
   // PreHandleEvent for the original target.
   nsEventStatus status = aEventStatus ? *aEventStatus : nsEventStatus_eIgnore;
   nsEventChainPreVisitor preVisitor(aPresContext, aEvent, aDOMEvent, status,
                                     isInAnon);
   targetEtci->PreHandleEvent(preVisitor);
 
   if (!preVisitor.mCanHandle && preVisitor.mAutomaticChromeDispatch && content) {
     // Event target couldn't handle the event. Try to propagate to chrome.
-    nsEventTargetChainItem::Destroy(targetEtci);
-    targetEtci = EventTargetChainItemForChromeTarget(content);
+    nsEventTargetChainItem::DestroyLast(chain, targetEtci);
+    targetEtci = EventTargetChainItemForChromeTarget(chain, content);
     NS_ENSURE_STATE(targetEtci);
     targetEtci->PreHandleEvent(preVisitor);
   }
   if (preVisitor.mCanHandle) {
     // At least the original target can handle the event.
     // Setting the retarget to the |target| simplifies retargeting code.
     nsCOMPtr<EventTarget> t = do_QueryInterface(aEvent->target);
     targetEtci->SetNewTarget(t);
     nsEventTargetChainItem* topEtci = targetEtci;
     while (preVisitor.mParentTarget) {
       EventTarget* parentTarget = preVisitor.mParentTarget;
       nsEventTargetChainItem* parentEtci =
-        nsEventTargetChainItem::Create(preVisitor.mParentTarget, topEtci);
-      if (!parentEtci) {
-        rv = NS_ERROR_OUT_OF_MEMORY;
-        break;
-      }
+        nsEventTargetChainItem::Create(chain, preVisitor.mParentTarget, topEtci);
       if (!parentEtci->IsValid()) {
+        nsEventTargetChainItem::DestroyLast(chain, parentEtci);
         rv = NS_ERROR_FAILURE;
         break;
       }
 
       // Item needs event retargetting.
       if (preVisitor.mEventTargetAtParent) {
         // Need to set the target of the event
         // so that also the next retargeting works.
         preVisitor.mEvent->target = preVisitor.mEventTargetAtParent;
         parentEtci->SetNewTarget(preVisitor.mEventTargetAtParent);
       }
 
       parentEtci->PreHandleEvent(preVisitor);
       if (preVisitor.mCanHandle) {
         topEtci = parentEtci;
       } else {
-        nsEventTargetChainItem::Destroy(parentEtci);
+        nsEventTargetChainItem::DestroyLast(chain, parentEtci);
         parentEtci = nullptr;
         if (preVisitor.mAutomaticChromeDispatch && content) {
           // Even if the current target can't handle the event, try to
           // propagate to chrome.
           nsCOMPtr<nsINode> disabledTarget = do_QueryInterface(parentTarget);
           if (disabledTarget) {
-            parentEtci = EventTargetChainItemForChromeTarget(disabledTarget,
+            parentEtci = EventTargetChainItemForChromeTarget(chain,
+                                                             disabledTarget,
                                                              topEtci);
             if (parentEtci) {
               parentEtci->PreHandleEvent(preVisitor);
               if (preVisitor.mCanHandle) {
                 targetEtci->SetNewTarget(parentTarget);
                 topEtci = parentEtci;
                 continue;
               }
@@ -626,41 +559,43 @@ nsEventDispatcher::Dispatch(nsISupports*
           }
         }
         break;
       }
     }
     if (NS_SUCCEEDED(rv)) {
       if (aTargets) {
         aTargets->Clear();
-        nsEventTargetChainItem* item = targetEtci;
-        while(item) {
-          aTargets->AppendObject(item->CurrentTarget()->GetTargetForDOMEvent());
-          item = item->mParent;
+        aTargets->SetCapacity(chain.Length());
+        for (uint32_t i = 0; i < chain.Length(); ++i) {
+          aTargets->AppendObject(chain[i].CurrentTarget()->GetTargetForDOMEvent());
         }
       } else {
         // Event target chain is created. Handle the chain.
         nsEventChainPostVisitor postVisitor(preVisitor);
         nsCxPusher pusher;
         ELMCreationDetector cd;
-        rv = topEtci->HandleEventTargetChain(postVisitor,
-                                             aCallback,
-                                             cd,
-                                             &pusher);
+        nsEventTargetChainItem::HandleEventTargetChain(chain,
+                                                       postVisitor,
+                                                       aCallback,
+                                                       cd,
+                                                       &pusher);
 
         preVisitor.mEventStatus = postVisitor.mEventStatus;
         // If the DOM event was created during event flow.
         if (!preVisitor.mDOMEvent && postVisitor.mDOMEvent) {
           preVisitor.mDOMEvent = postVisitor.mDOMEvent;
         }
       }
     }
   }
 
-  nsEventTargetChainItem::Destroy(targetEtci);
+  // Note, nsEventTargetChainItem objects are deleted when the chain goes out of
+  // the scope.
+
   targetEtci = nullptr;
 
   aEvent->mFlags.mIsBeingDispatched = false;
   aEvent->mFlags.mDispatchedAtLeastOnce = true;
 
   if (!externalDOMEvent && preVisitor.mDOMEvent) {
     // An nsDOMEvent was created while dispatching the event.
     // Duplicate private data if someone holds a pointer to it.
--- a/content/events/src/nsEventListenerManager.cpp
+++ b/content/events/src/nsEventListenerManager.cpp
@@ -54,19 +54,21 @@
 #include "xpcpublic.h"
 #include "nsSandboxFlags.h"
 #include "mozilla/dom/time/TimeChangeObserver.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::hal;
 
-#define EVENT_TYPE_EQUALS(ls, type, userType, allEvents) \
-  ((ls->mEventType == type && \
-   (ls->mEventType != NS_USER_DEFINED_EVENT || ls->mTypeAtom == userType)) || \
+#define EVENT_TYPE_EQUALS(ls, type, userType, typeString, allEvents) \
+  ((ls->mEventType == type &&                                        \
+    (ls->mEventType != NS_USER_DEFINED_EVENT ||                      \
+    (mIsMainThreadELM && ls->mTypeAtom == userType) ||               \
+    (!mIsMainThreadELM && ls->mTypeString.Equals(typeString)))) ||   \
    (allEvents && ls->mAllEvents))
 
 static NS_DEFINE_CID(kDOMScriptObjectFactoryCID,
                      NS_DOM_SCRIPT_OBJECT_FACTORY_CID);
 
 static const uint32_t kAllMutationBits =
   NS_EVENT_BITS_MUTATION_SUBTREEMODIFIED |
   NS_EVENT_BITS_MUTATION_NODEINSERTED |
@@ -106,22 +108,23 @@ nsEventListenerManager::nsEventListenerM
   mMayHavePaintEventListener(false),
   mMayHaveMutationListeners(false),
   mMayHaveCapturingListeners(false),
   mMayHaveSystemGroupListeners(false),
   mMayHaveAudioAvailableEventListener(false),
   mMayHaveTouchEventListener(false),
   mMayHaveMouseEnterLeaveEventListener(false),
   mClearingListeners(false),
+  mIsMainThreadELM(NS_IsMainThread()),
   mNoListenerForEvent(0),
   mTarget(aTarget)
 {
   NS_ASSERTION(aTarget, "unexpected null pointer");
 
-  if (NS_IsMainThread()) {
+  if (mIsMainThreadELM) {
     ++sMainThreadCreatedCount;
   }
 }
 
 nsEventListenerManager::~nsEventListenerManager() 
 {
   // If your code fails this assertion, a possible reason is that
   // a class did not call our Disconnect() manually. Note that
@@ -218,48 +221,53 @@ nsEventListenerManager::GetTargetAsInner
   return window.forget();
 }
 
 void
 nsEventListenerManager::AddEventListenerInternal(
                           const EventListenerHolder& aListener,
                           uint32_t aType,
                           nsIAtom* aTypeAtom,
+                          const nsAString& aTypeString,
                           const EventListenerFlags& aFlags,
                           bool aHandler,
                           bool aAllEvents)
 {
-  NS_ABORT_IF_FALSE((aType && aTypeAtom) || aAllEvents, "Missing type");
+  MOZ_ASSERT((NS_IsMainThread() && aType && aTypeAtom) || // Main thread
+             (!NS_IsMainThread() && aType && !aTypeString.IsEmpty()) || // non-main-thread
+             aAllEvents, "Missing type"); // all-events listener
 
   if (!aListener || mClearingListeners) {
     return;
   }
 
   // Since there is no public API to call us with an EventListenerHolder, we
   // know that there's an EventListenerHolder on the stack holding a strong ref
   // to the listener.
 
   nsListenerStruct* ls;
   uint32_t count = mListeners.Length();
   for (uint32_t i = 0; i < count; i++) {
     ls = &mListeners.ElementAt(i);
     if (ls->mListener == aListener &&
         ls->mListenerIsHandler == aHandler &&
         ls->mFlags == aFlags &&
-        EVENT_TYPE_EQUALS(ls, aType, aTypeAtom, aAllEvents)) {
+        EVENT_TYPE_EQUALS(ls, aType, aTypeAtom, aTypeString, aAllEvents)) {
       return;
     }
   }
 
   mNoListenerForEvent = NS_EVENT_TYPE_NULL;
   mNoListenerForEventAtom = nullptr;
 
   ls = aAllEvents ? mListeners.InsertElementAt(0) : mListeners.AppendElement();
   ls->mListener = aListener;
+  MOZ_ASSERT(aType < PR_UINT16_MAX);
   ls->mEventType = aType;
+  ls->mTypeString = aTypeString;
   ls->mTypeAtom = aTypeAtom;
   ls->mFlags = aFlags;
   ls->mListenerIsHandler = aHandler;
   ls->mHandlerIsString = false;
   ls->mAllEvents = aAllEvents;
 
   // Detect the type of event listener.
   nsCOMPtr<nsIXPConnectWrappedJS> wjs;
@@ -452,16 +460,17 @@ nsEventListenerManager::DisableDevice(ui
   }
 }
 
 void
 nsEventListenerManager::RemoveEventListenerInternal(
                           const EventListenerHolder& aListener, 
                           uint32_t aType,
                           nsIAtom* aUserType,
+                          const nsAString& aTypeString,
                           const EventListenerFlags& aFlags,
                           bool aAllEvents)
 {
   if (!aListener || !aType || mClearingListeners) {
     return;
   }
 
   nsListenerStruct* ls;
@@ -472,17 +481,17 @@ nsEventListenerManager::RemoveEventListe
 #ifdef MOZ_B2G
   bool timeChangeEvent = (aType == NS_MOZ_TIME_CHANGE_EVENT);
   bool networkEvent = (aType == NS_NETWORK_UPLOAD_EVENT ||
                        aType == NS_NETWORK_DOWNLOAD_EVENT);
 #endif // MOZ_B2G
 
   for (uint32_t i = 0; i < count; ++i) {
     ls = &mListeners.ElementAt(i);
-    if (EVENT_TYPE_EQUALS(ls, aType, aUserType, aAllEvents)) {
+    if (EVENT_TYPE_EQUALS(ls, aType, aUserType, aTypeString, aAllEvents)) {
       ++typeCount;
       if (ls->mListener == aListener &&
           ls->mFlags.EqualsIgnoringTrustness(aFlags)) {
         nsRefPtr<nsEventListenerManager> kungFuDeathGrip = this;
         mListeners.RemoveElementAt(i);
         --count;
         mNoListenerForEvent = NS_EVENT_TYPE_NULL;
         mNoListenerForEventAtom = nullptr;
@@ -514,96 +523,109 @@ nsEventListenerManager::RemoveEventListe
     nsCOMPtr<nsPIDOMWindow> window = GetTargetAsInnerWindow();
     if (window) {
       window->DisableNetworkEvent(aType);
     }
 #endif // MOZ_B2G
   }
 }
 
-static inline bool
-ListenerCanHandle(nsListenerStruct* aLs, nsEvent* aEvent)
+bool
+nsEventListenerManager::ListenerCanHandle(nsListenerStruct* aLs, nsEvent* aEvent)
 {
   // This is slightly different from EVENT_TYPE_EQUALS in that it returns
   // true even when aEvent->message == NS_USER_DEFINED_EVENT and
   // aLs=>mEventType != NS_USER_DEFINED_EVENT as long as the atoms are the same
-  return (aEvent->message == NS_USER_DEFINED_EVENT ?
-    (aLs->mTypeAtom == aEvent->userType) :
-    (aLs->mEventType == aEvent->message)) || aLs->mAllEvents;
+  if (aLs->mAllEvents) {
+    return true;
+  }
+  if (aEvent->message == NS_USER_DEFINED_EVENT) {
+    if (mIsMainThreadELM) {
+      return aLs->mTypeAtom == aEvent->userType;
+    }
+    return aLs->mTypeString.Equals(aEvent->typeString);
+  }
+  MOZ_ASSERT(mIsMainThreadELM);
+  return aLs->mEventType == aEvent->message;
 }
 
 void
 nsEventListenerManager::AddEventListenerByType(const EventListenerHolder& aListener, 
                                                const nsAString& aType,
                                                const EventListenerFlags& aFlags)
 {
-  nsCOMPtr<nsIAtom> atom = do_GetAtom(NS_LITERAL_STRING("on") + aType);
+  nsCOMPtr<nsIAtom> atom =
+    mIsMainThreadELM ? do_GetAtom(NS_LITERAL_STRING("on") + aType) : nullptr;
   uint32_t type = nsContentUtils::GetEventId(atom);
-  AddEventListenerInternal(aListener, type, atom, aFlags);
+  AddEventListenerInternal(aListener, type, atom, aType, aFlags);
 }
 
 void
 nsEventListenerManager::RemoveEventListenerByType(
                           const EventListenerHolder& aListener,
                           const nsAString& aType,
                           const EventListenerFlags& aFlags)
 {
-  nsCOMPtr<nsIAtom> atom = do_GetAtom(NS_LITERAL_STRING("on") + aType);
+  nsCOMPtr<nsIAtom> atom =
+    mIsMainThreadELM ? do_GetAtom(NS_LITERAL_STRING("on") + aType) : nullptr;
   uint32_t type = nsContentUtils::GetEventId(atom);
-  RemoveEventListenerInternal(aListener, type, atom, aFlags);
+  RemoveEventListenerInternal(aListener, type, atom, aType, aFlags);
 }
 
 nsListenerStruct*
 nsEventListenerManager::FindEventHandler(uint32_t aEventType,
-                                         nsIAtom* aTypeAtom)
+                                         nsIAtom* aTypeAtom,
+                                         const nsAString& aTypeString)
 {
   // Run through the listeners for this type and see if a script
   // listener is registered
   nsListenerStruct *ls;
   uint32_t count = mListeners.Length();
   for (uint32_t i = 0; i < count; ++i) {
     ls = &mListeners.ElementAt(i);
     if (ls->mListenerIsHandler &&
-        EVENT_TYPE_EQUALS(ls, aEventType, aTypeAtom, false)) {
+        EVENT_TYPE_EQUALS(ls, aEventType, aTypeAtom, aTypeString, false)) {
       return ls;
     }
   }
   return nullptr;
 }
 
 nsresult
 nsEventListenerManager::SetEventHandlerInternal(nsIScriptContext *aContext,
                                                 JS::Handle<JSObject*> aScopeObject,
                                                 nsIAtom* aName,
+                                                const nsAString& aTypeString,
                                                 const nsEventHandler& aHandler,
                                                 bool aPermitUntrustedEvents,
                                                 nsListenerStruct **aListenerStruct)
 {
   NS_ASSERTION((aContext && aScopeObject) || aHandler.HasEventHandler(),
                "Must have one or the other!");
 
   nsresult rv = NS_OK;
   uint32_t eventType = nsContentUtils::GetEventId(aName);
-  nsListenerStruct* ls = FindEventHandler(eventType, aName);
+  nsListenerStruct* ls = FindEventHandler(eventType, aName, aTypeString);
 
   if (!ls) {
     // If we didn't find a script listener or no listeners existed
     // create and add a new one.
     EventListenerFlags flags;
     flags.mListenerIsJSListener = true;
 
     nsCOMPtr<nsIJSEventListener> scriptListener;
     rv = NS_NewJSEventListener(aContext, aScopeObject, mTarget, aName,
                                aHandler, getter_AddRefs(scriptListener));
 
     if (NS_SUCCEEDED(rv)) {
       EventListenerHolder holder(scriptListener);
-      AddEventListenerInternal(holder, eventType, aName, flags, true);
+      AddEventListenerInternal(holder, eventType, aName, aTypeString, flags,
+                               true);
 
-      ls = FindEventHandler(eventType, aName);
+      ls = FindEventHandler(eventType, aName, aTypeString);
     }
   } else {
     nsIJSEventListener* scriptListener = ls->GetJSListener();
     MOZ_ASSERT(scriptListener,
                "How can we have an event handler with no nsIJSEventListener?");
 
     bool same = scriptListener->GetHandler() == aHandler;
     // Possibly the same listener, but update still the context and scope.
@@ -748,36 +770,37 @@ nsEventListenerManager::SetEventHandler(
   nsIScriptContext* context = global->GetScriptContext();
   NS_ENSURE_TRUE(context, NS_ERROR_FAILURE);
 
   JSAutoRequest ar(context->GetNativeContext());
   JS::Rooted<JSObject*> scope(context->GetNativeContext(),
                               global->GetGlobalJSObject());
 
   nsListenerStruct *ls;
-  rv = SetEventHandlerInternal(context, scope, aName, nsEventHandler(),
-                               aPermitUntrustedEvents, &ls);
+  rv = SetEventHandlerInternal(context, scope, aName, EmptyString(),
+                               nsEventHandler(), aPermitUntrustedEvents, &ls);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!aDeferCompilation) {
     return CompileEventHandlerInternal(ls, true, &aBody);
   }
 
   return NS_OK;
 }
 
 void
-nsEventListenerManager::RemoveEventHandler(nsIAtom* aName)
+nsEventListenerManager::RemoveEventHandler(nsIAtom* aName,
+                                           const nsAString& aTypeString)
 {
   if (mClearingListeners) {
     return;
   }
 
   uint32_t eventType = nsContentUtils::GetEventId(aName);
-  nsListenerStruct* ls = FindEventHandler(eventType, aName);
+  nsListenerStruct* ls = FindEventHandler(eventType, aName, aTypeString);
 
   if (ls) {
     mListeners.RemoveElementAt(uint32_t(ls - &mListeners.ElementAt(0)));
     mNoListenerForEvent = NS_EVENT_TYPE_NULL;
     mNoListenerForEventAtom = nullptr;
     if (mTarget) {
       mTarget->EventListenerRemoved(aName);
     }
@@ -1079,31 +1102,31 @@ nsEventListenerManager::AddListenerForAl
                                                 bool aWantsUntrusted,
                                                 bool aSystemEventGroup)
 {
   EventListenerFlags flags;
   flags.mCapture = aUseCapture;
   flags.mAllowUntrustedEvents = aWantsUntrusted;
   flags.mInSystemGroup = aSystemEventGroup;
   EventListenerHolder holder(aListener);
-  AddEventListenerInternal(holder, NS_EVENT_TYPE_ALL, nullptr, flags,
-                           false, true);
+  AddEventListenerInternal(holder, NS_EVENT_TYPE_ALL, nullptr, EmptyString(),
+                           flags, false, true);
 }
 
 void
 nsEventListenerManager::RemoveListenerForAllEvents(nsIDOMEventListener* aListener, 
                                                    bool aUseCapture,
                                                    bool aSystemEventGroup)
 {
   EventListenerFlags flags;
   flags.mCapture = aUseCapture;
   flags.mInSystemGroup = aSystemEventGroup;
   EventListenerHolder holder(aListener);
-  RemoveEventListenerInternal(holder, NS_EVENT_TYPE_ALL, nullptr, flags,
-                              true);
+  RemoveEventListenerInternal(holder, NS_EVENT_TYPE_ALL, nullptr, EmptyString(),
+                              flags, true);
 }
 
 bool
 nsEventListenerManager::HasMutationListeners()
 {
   if (mMayHaveMutationListeners) {
     uint32_t count = mListeners.Length();
     for (uint32_t i = 0; i < count; ++i) {
@@ -1214,68 +1237,76 @@ nsEventListenerManager::HasUnloadListene
       return true;
     }
   }
   return false;
 }
 
 nsresult
 nsEventListenerManager::SetEventHandler(nsIAtom* aEventName,
+                                        const nsAString& aTypeString,
                                         EventHandlerNonNull* aHandler)
 {
   if (!aHandler) {
-    RemoveEventHandler(aEventName);
+    RemoveEventHandler(aEventName, aTypeString);
     return NS_OK;
   }
 
   // Untrusted events are always permitted for non-chrome script
   // handlers.
   nsListenerStruct *ignored;
   return SetEventHandlerInternal(nullptr, JS::NullPtr(), aEventName,
-                                 nsEventHandler(aHandler),
-                                 !nsContentUtils::IsCallerChrome(), &ignored);
+                                 aTypeString, nsEventHandler(aHandler),
+                                 !mIsMainThreadELM ||
+                                 !nsContentUtils::IsCallerChrome(),
+                                 &ignored);
 }
 
 nsresult
 nsEventListenerManager::SetEventHandler(OnErrorEventHandlerNonNull* aHandler)
 {
   if (!aHandler) {
-    RemoveEventHandler(nsGkAtoms::onerror);
+    RemoveEventHandler(nsGkAtoms::onerror, EmptyString());
     return NS_OK;
   }
 
   // Untrusted events are always permitted for non-chrome script
   // handlers.
   nsListenerStruct *ignored;
   return SetEventHandlerInternal(nullptr, JS::NullPtr(), nsGkAtoms::onerror,
-                                 nsEventHandler(aHandler),
-                                 !nsContentUtils::IsCallerChrome(), &ignored);
+                                 EmptyString(), nsEventHandler(aHandler),
+                                 !mIsMainThreadELM ||
+                                 !nsContentUtils::IsCallerChrome(),
+                                 &ignored);
 }
 
 nsresult
 nsEventListenerManager::SetEventHandler(BeforeUnloadEventHandlerNonNull* aHandler)
 {
   if (!aHandler) {
-    RemoveEventHandler(nsGkAtoms::onbeforeunload);
+    RemoveEventHandler(nsGkAtoms::onbeforeunload, EmptyString());
     return NS_OK;
   }
 
   // Untrusted events are always permitted for non-chrome script
   // handlers.
   nsListenerStruct *ignored;
   return SetEventHandlerInternal(nullptr, JS::NullPtr(), nsGkAtoms::onbeforeunload,
-                                 nsEventHandler(aHandler),
-                                 !nsContentUtils::IsCallerChrome(), &ignored);
+                                 EmptyString(), nsEventHandler(aHandler),
+                                 !mIsMainThreadELM ||
+                                 !nsContentUtils::IsCallerChrome(),
+                                 &ignored);
 }
 
 const nsEventHandler*
-nsEventListenerManager::GetEventHandlerInternal(nsIAtom *aEventName)
+nsEventListenerManager::GetEventHandlerInternal(nsIAtom *aEventName,
+                                                const nsAString& aTypeString)
 {
   uint32_t eventType = nsContentUtils::GetEventId(aEventName);
-  nsListenerStruct* ls = FindEventHandler(eventType, aEventName);
+  nsListenerStruct* ls = FindEventHandler(eventType, aEventName, aTypeString);
 
   if (!ls) {
     return nullptr;
   }
 
   nsIJSEventListener *listener = ls->GetJSListener();
     
   if (ls->mHandlerIsString) {
--- a/content/events/src/nsEventListenerManager.h
+++ b/content/events/src/nsEventListenerManager.h
@@ -158,18 +158,19 @@ typedef enum
     eWrappedJSListener,
     eWebIDLListener,
     eListenerTypeCount
 } nsListenerType;
 
 struct nsListenerStruct
 {
   mozilla::dom::EventListenerHolder mListener;
-  nsCOMPtr<nsIAtom>             mTypeAtom;
-  uint32_t                      mEventType;
+  nsCOMPtr<nsIAtom>             mTypeAtom;   // for the main thread
+  nsString                      mTypeString; // for non-main-threads
+  uint16_t                      mEventType;
   uint8_t                       mListenerType;
   bool                          mListenerIsHandler : 1;
   bool                          mHandlerIsString : 1;
   bool                          mAllEvents : 1;
 
   mozilla::dom::EventListenerFlags mFlags;
 
   nsIJSEventListener* GetJSListener() const {
@@ -293,17 +294,17 @@ public:
   nsresult SetEventHandler(nsIAtom *aName,
                            const nsAString& aFunc,
                            uint32_t aLanguage,
                            bool aDeferCompilation,
                            bool aPermitUntrustedEvents);
   /**
    * Remove the current "inline" event listener for aName.
    */
-  void RemoveEventHandler(nsIAtom *aName);
+  void RemoveEventHandler(nsIAtom *aName, const nsAString& aTypeString);
 
   void HandleEvent(nsPresContext* aPresContext,
                    nsEvent* aEvent, 
                    nsIDOMEvent** aDOMEvent,
                    mozilla::dom::EventTarget* aCurrentTarget,
                    nsEventStatus* aEventStatus,
                    nsCxPusher* aPusher)
   {
@@ -427,116 +428,128 @@ protected:
    */
   nsresult CompileEventHandlerInternal(nsListenerStruct *aListenerStruct,
                                        bool aNeedsCxPush,
                                        const nsAString* aBody);
 
   /**
    * Find the nsListenerStruct for the "inline" event listener for aTypeAtom.
    */
-  nsListenerStruct* FindEventHandler(uint32_t aEventType, nsIAtom* aTypeAtom);
+  nsListenerStruct* FindEventHandler(uint32_t aEventType, nsIAtom* aTypeAtom,
+                                     const nsAString& aTypeString);
 
   /**
    * Set the "inline" event listener for aName to aHandler.  aHandler may be
    * have no actual handler set to indicate that we should lazily get and
    * compile the string for this listener, but in that case aContext and
    * aScopeGlobal must be non-null.  Otherwise, aContext and aScopeGlobal are
    * allowed to be null.  The nsListenerStruct that results, if any, is returned
    * in aListenerStruct.
    */
   nsresult SetEventHandlerInternal(nsIScriptContext *aContext,
                                    JS::Handle<JSObject*> aScopeGlobal,
                                    nsIAtom* aName,
+                                   const nsAString& aTypeString,
                                    const nsEventHandler& aHandler,
                                    bool aPermitUntrustedEvents,
                                    nsListenerStruct **aListenerStruct);
 
   bool IsDeviceType(uint32_t aType);
   void EnableDevice(uint32_t aType);
   void DisableDevice(uint32_t aType);
 
 public:
   /**
    * Set the "inline" event listener for aEventName to aHandler.  If
    * aHandler is null, this will actually remove the event listener
    */
   nsresult SetEventHandler(nsIAtom* aEventName,
+                           const nsAString& aTypeString,
                            mozilla::dom::EventHandlerNonNull* aHandler);
   nsresult SetEventHandler(mozilla::dom::OnErrorEventHandlerNonNull* aHandler);
   nsresult SetEventHandler(mozilla::dom::BeforeUnloadEventHandlerNonNull* aHandler);
 
   /**
    * Get the value of the "inline" event listener for aEventName.
    * This may cause lazy compilation if the listener is uncompiled.
    *
    * Note: It's the caller's responsibility to make sure to call the right one
    * of these methods.  In particular, "onerror" events use
    * OnErrorEventHandlerNonNull for some event targets and EventHandlerNonNull
    * for others.
    */
-  mozilla::dom::EventHandlerNonNull* GetEventHandler(nsIAtom *aEventName)
+  mozilla::dom::EventHandlerNonNull* GetEventHandler(nsIAtom *aEventName,
+                                                     const nsAString& aTypeString)
   {
-    const nsEventHandler* handler = GetEventHandlerInternal(aEventName);
+    const nsEventHandler* handler =
+      GetEventHandlerInternal(aEventName, aTypeString);
     return handler ? handler->EventHandler() : nullptr;
   }
   mozilla::dom::OnErrorEventHandlerNonNull* GetOnErrorEventHandler()
   {
-    const nsEventHandler* handler = GetEventHandlerInternal(nsGkAtoms::onerror);
+    const nsEventHandler* handler =
+      GetEventHandlerInternal(nsGkAtoms::onerror, EmptyString());
     return handler ? handler->OnErrorEventHandler() : nullptr;
   }
   mozilla::dom::BeforeUnloadEventHandlerNonNull* GetOnBeforeUnloadEventHandler()
   {
     const nsEventHandler* handler =
-      GetEventHandlerInternal(nsGkAtoms::onbeforeunload);
+      GetEventHandlerInternal(nsGkAtoms::onbeforeunload, EmptyString());
     return handler ? handler->BeforeUnloadEventHandler() : nullptr;
   }
 
 protected:
   /**
    * Helper method for implementing the various Get*EventHandler above.  Will
    * return null if we don't have an event handler for this event name.
    */
-  const nsEventHandler* GetEventHandlerInternal(nsIAtom* aEventName);
+  const nsEventHandler* GetEventHandlerInternal(nsIAtom* aEventName,
+                                                const nsAString& aTypeString);
 
   void AddEventListener(const nsAString& aType,
                         const mozilla::dom::EventListenerHolder& aListener,
                         bool aUseCapture,
                         bool aWantsUntrusted);
   void RemoveEventListener(const nsAString& aType,
                            const mozilla::dom::EventListenerHolder& aListener,
                            bool aUseCapture);
 
   void AddEventListenerInternal(
          const mozilla::dom::EventListenerHolder& aListener,
          uint32_t aType,
          nsIAtom* aTypeAtom,
+         const nsAString& aTypeString,
          const mozilla::dom::EventListenerFlags& aFlags,
          bool aHandler = false,
          bool aAllEvents = false);
   void RemoveEventListenerInternal(
          const mozilla::dom::EventListenerHolder& aListener,
          uint32_t aType,
          nsIAtom* aUserType,
+         const nsAString& aTypeString,
          const mozilla::dom::EventListenerFlags& aFlags,
          bool aAllEvents = false);
   void RemoveAllListeners();
   const EventTypeData* GetTypeDataForIID(const nsIID& aIID);
   const EventTypeData* GetTypeDataForEventName(nsIAtom* aName);
   nsPIDOMWindow* GetInnerWindowForTarget();
   already_AddRefed<nsPIDOMWindow> GetTargetAsInnerWindow() const;
 
+  bool ListenerCanHandle(nsListenerStruct* aLs, nsEvent* aEvent);
+
   uint32_t mMayHavePaintEventListener : 1;
   uint32_t mMayHaveMutationListeners : 1;
   uint32_t mMayHaveCapturingListeners : 1;
   uint32_t mMayHaveSystemGroupListeners : 1;
   uint32_t mMayHaveAudioAvailableEventListener : 1;
   uint32_t mMayHaveTouchEventListener : 1;
   uint32_t mMayHaveMouseEnterLeaveEventListener : 1;
   uint32_t mClearingListeners : 1;
-  uint32_t mNoListenerForEvent : 24;
+  uint32_t mIsMainThreadELM : 1;
+  uint32_t mNoListenerForEvent : 23;
 
   nsAutoTObserverArray<nsListenerStruct, 2> mListeners;
   mozilla::dom::EventTarget*                mTarget;  //WEAK
   nsCOMPtr<nsIAtom>                         mNoListenerForEventAtom;
 
   friend class ELMCreationDetector;
   static uint32_t                           sMainThreadCreatedCount;
 };
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -1005,17 +1005,17 @@ nsGenericHTMLElement::UnsetAttr(int32_t 
     else if (aAttribute == nsGkAtoms::accesskey) {
       // Have to unregister before clearing flag. See UnregAccessKey
       UnregAccessKey();
       UnsetFlags(NODE_HAS_ACCESSKEY);
     }
     else if (IsEventAttributeName(aAttribute)) {
       nsEventListenerManager* manager = GetListenerManager(false);
       if (manager) {
-        manager->RemoveEventHandler(aAttribute);
+        manager->RemoveEventHandler(aAttribute, EmptyString());
       }
     }
   }
 
   nsresult rv = nsGenericHTMLElementBase::UnsetAttr(aNameSpaceID, aAttribute,
                                                     aNotify);
   NS_ENSURE_SUCCESS(rv, rv);
 
--- a/content/media/AudioNodeStream.cpp
+++ b/content/media/AudioNodeStream.cpp
@@ -281,17 +281,17 @@ AudioNodeStream::ObtainInputBlock(AudioC
     AudioNodeStream* a = static_cast<AudioNodeStream*>(s);
     MOZ_ASSERT(a == s->AsAudioNodeStream());
     if (a->IsFinishedOnGraphThread() ||
         a->IsAudioParamStream()) {
       continue;
     }
     AudioChunk* chunk = &a->mLastChunks[mInputs[i]->OutputNumber()];
     MOZ_ASSERT(chunk);
-    if (chunk->IsNull()) {
+    if (chunk->IsNull() || chunk->mChannelData.IsEmpty()) {
       continue;
     }
 
     inputChunks.AppendElement(chunk);
     outputChannelCount =
       GetAudioChannelsSuperset(outputChannelCount, chunk->mChannelData.Length());
   }
 
--- a/content/media/MediaDecoderStateMachine.cpp
+++ b/content/media/MediaDecoderStateMachine.cpp
@@ -2924,14 +2924,15 @@ void MediaDecoderStateMachine::QueueMeta
 {
   NS_ASSERTION(OnDecodeThread(), "Should be on decode thread.");
   mDecoder->GetReentrantMonitor().AssertCurrentThreadIn();
   TimedMetadata* metadata = new TimedMetadata;
   metadata->mPublishTime = aPublishTime;
   metadata->mChannels = aChannels;
   metadata->mRate = aRate;
   metadata->mHasAudio = aHasAudio;
+  metadata->mHasVideo = aHasVideo;
   metadata->mTags = aTags;
   mMetadataManager.QueueMetadata(metadata);
 }
 
 } // namespace mozilla
 
--- a/content/svg/content/src/nsSVGElement.cpp
+++ b/content/svg/content/src/nsSVGElement.cpp
@@ -661,17 +661,17 @@ nsSVGElement::UnsetAttrInternal(int32_t 
     // If this is an svg presentation attribute, remove rule to force an update
     if (IsAttributeMapped(aName))
       mContentStyleRule = nullptr;
 
     if (IsEventAttributeName(aName)) {
       nsEventListenerManager* manager = GetListenerManager(false);
       if (manager) {
         nsIAtom* eventName = GetEventNameForAttr(aName);
-        manager->RemoveEventHandler(eventName);
+        manager->RemoveEventHandler(eventName, EmptyString());
       }
       return;
     }
     
     // Check if this is a length attribute going away
     LengthAttributesInfo lenInfo = GetLengthInfo();
 
     for (uint32_t i = 0; i < lenInfo.mLengthCount; i++) {
--- a/dom/base/nsGlobalWindow.h
+++ b/dom/base/nsGlobalWindow.h
@@ -698,24 +698,26 @@ public:
   void EnableGamepadUpdates();
   void DisableGamepadUpdates();
 
 
 #define EVENT(name_, id_, type_, struct_)                                     \
   mozilla::dom::EventHandlerNonNull* GetOn##name_()                           \
   {                                                                           \
     nsEventListenerManager *elm = GetListenerManager(false);                  \
-    return elm ? elm->GetEventHandler(nsGkAtoms::on##name_) : nullptr;        \
+    return elm ? elm->GetEventHandler(nsGkAtoms::on##name_, EmptyString())    \
+               : nullptr;                                                     \
   }                                                                           \
   void SetOn##name_(mozilla::dom::EventHandlerNonNull* handler,               \
                     mozilla::ErrorResult& error)                              \
   {                                                                           \
     nsEventListenerManager *elm = GetListenerManager(true);                   \
     if (elm) {                                                                \
-      error = elm->SetEventHandler(nsGkAtoms::on##name_, handler);            \
+      error = elm->SetEventHandler(nsGkAtoms::on##name_, EmptyString(),       \
+                                   handler);                                  \
     } else {                                                                  \
       error.Throw(NS_ERROR_OUT_OF_MEMORY);                                    \
     }                                                                         \
   }
 #define ERROR_EVENT(name_, id_, type_, struct_)                               \
   mozilla::dom::OnErrorEventHandlerNonNull* GetOn##name_()                    \
   {                                                                           \
     nsEventListenerManager *elm = GetListenerManager(false);                  \
--- a/dom/src/offline/nsDOMOfflineResourceList.cpp
+++ b/dom/src/offline/nsDOMOfflineResourceList.cpp
@@ -79,17 +79,16 @@ NS_IMPL_EVENT_HANDLER(nsDOMOfflineResour
 
 nsDOMOfflineResourceList::nsDOMOfflineResourceList(nsIURI *aManifestURI,
                                                    nsIURI *aDocumentURI,
                                                    nsPIDOMWindow *aWindow)
   : mInitialized(false)
   , mManifestURI(aManifestURI)
   , mDocumentURI(aDocumentURI)
   , mExposeCacheUpdateStatus(true)
-  , mDontSetDocumentCache(false)
   , mStatus(nsIDOMOfflineResourceList::IDLE)
   , mCachedKeys(nullptr)
   , mCachedKeysCount(0)
 {
   BindToOwner(aWindow);
   SetIsDOMBinding();
 }
 
@@ -424,16 +423,21 @@ nsDOMOfflineResourceList::GetStatus(uint
   // If there is an update in process, use its status.
   if (mCacheUpdate && mExposeCacheUpdateStatus) {
     rv = mCacheUpdate->GetStatus(aStatus);
     if (NS_SUCCEEDED(rv) && *aStatus != nsIDOMOfflineResourceList::IDLE) {
       return NS_OK;
     }
   }
 
+  if (mAvailableApplicationCache) {
+    *aStatus = nsIDOMOfflineResourceList::UPDATEREADY;
+    return NS_OK;
+  }
+
   *aStatus = mStatus;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMOfflineResourceList::Update()
 {
   nsresult rv = Init();
@@ -450,20 +454,16 @@ nsDOMOfflineResourceList::Update()
   nsCOMPtr<nsIDOMWindow> window = 
     do_QueryInterface(GetOwner());
 
   nsCOMPtr<nsIOfflineCacheUpdate> update;
   rv = updateService->ScheduleUpdate(mManifestURI, mDocumentURI,
                                      window, getter_AddRefs(update));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  // Since we are invoking the cache update, cache on the document must not
-  // be updated until swapCache() method is called on applicationCache object.
-  mDontSetDocumentCache = true;
-
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMOfflineResourceList::SwapCache()
 {
   nsresult rv = Init();
   NS_ENSURE_SUCCESS(rv, rv);
@@ -483,16 +483,18 @@ nsDOMOfflineResourceList::SwapCache()
   }
 
   if (mAvailableApplicationCache) {
     nsCString currClientId, availClientId;
     currentAppCache->GetClientID(currClientId);
     mAvailableApplicationCache->GetClientID(availClientId);
     if (availClientId == currClientId)
       return NS_ERROR_DOM_INVALID_STATE_ERR;
+  } else if (mStatus != OBSOLETE) {
+    return NS_ERROR_DOM_INVALID_STATE_ERR;
   }
 
   ClearCachedKeys();
 
   nsCOMPtr<nsIApplicationCacheContainer> appCacheContainer =
     GetDocumentAppCacheContainer();
 
   // In the case of an obsolete cache group, newAppCache might be null.
@@ -624,26 +626,46 @@ nsDOMOfflineResourceList::UpdateStateCha
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMOfflineResourceList::ApplicationCacheAvailable(nsIApplicationCache *aApplicationCache)
 {
-  mAvailableApplicationCache = aApplicationCache;
+  nsCOMPtr<nsIApplicationCache> currentAppCache = GetDocumentAppCache();
+  if (currentAppCache) {
+    // Document already has a cache, we cannot override it.  swapCache is
+    // here to do it on demand.
 
-  if (!mDontSetDocumentCache) {
-    nsCOMPtr<nsIApplicationCacheContainer> appCacheContainer =
-      GetDocumentAppCacheContainer();
+    // If the newly available cache is identical to the current cache, then
+    // just ignore this event.
+    if (aApplicationCache == currentAppCache) {
+      return NS_OK;
+    }
 
-    if (appCacheContainer)
-      appCacheContainer->SetApplicationCache(aApplicationCache);
+    nsCString currClientId, availClientId;
+    currentAppCache->GetClientID(currClientId);
+    aApplicationCache->GetClientID(availClientId);
+    if (availClientId == currClientId) {
+      return NS_OK;
+    }
+
+    mAvailableApplicationCache = aApplicationCache;
+    return NS_OK;
   }
 
+  nsCOMPtr<nsIApplicationCacheContainer> appCacheContainer =
+    GetDocumentAppCacheContainer();
+
+  if (appCacheContainer) {
+    appCacheContainer->SetApplicationCache(aApplicationCache);
+  }
+
+  mAvailableApplicationCache = nullptr;
   return NS_OK;
 }
 
 nsresult
 nsDOMOfflineResourceList::GetCacheKey(const nsAString &aURI, nsCString &aKey)
 {
   nsCOMPtr<nsIURI> requestedURI;
   nsresult rv = NS_NewURI(getter_AddRefs(requestedURI), aURI);
@@ -732,24 +754,22 @@ nsDOMOfflineResourceList::UpdateComplete
   bool isUpgrade;
   mCacheUpdate->GetIsUpgrade(&isUpgrade);
 
   bool succeeded;
   nsresult rv = mCacheUpdate->GetSucceeded(&succeeded);
 
   mCacheUpdate->RemoveObserver(this);
   mCacheUpdate = nullptr;
-  mDontSetDocumentCache = false;
 
   if (NS_SUCCEEDED(rv) && succeeded && !partial) {
+    mStatus = nsIDOMOfflineResourceList::IDLE;
     if (isUpgrade) {
-      mStatus = nsIDOMOfflineResourceList::UPDATEREADY;
       SendEvent(NS_LITERAL_STRING(UPDATEREADY_STR));
     } else {
-      mStatus = nsIDOMOfflineResourceList::IDLE;
       SendEvent(NS_LITERAL_STRING(CACHED_STR));
     }
   }
 
   return NS_OK;
 }
 
 nsresult
--- a/dom/src/offline/nsDOMOfflineResourceList.h
+++ b/dom/src/offline/nsDOMOfflineResourceList.h
@@ -152,17 +152,16 @@ private:
   // AsciiSpec of mManifestURI
   nsCString mManifestSpec;
 
   nsCOMPtr<nsIURI> mDocumentURI;
   nsCOMPtr<nsIApplicationCacheService> mApplicationCacheService;
   nsCOMPtr<nsIApplicationCache> mAvailableApplicationCache;
   nsCOMPtr<nsIOfflineCacheUpdate> mCacheUpdate;
   bool mExposeCacheUpdateStatus;
-  bool mDontSetDocumentCache;
   uint16_t mStatus;
 
   // The set of dynamic keys for this application cache object.
   char **mCachedKeys;
   uint32_t mCachedKeysCount;
 
   nsCOMArray<nsIDOMEvent> mPendingEvents;
 };
--- a/dom/tests/mochitest/ajax/offline/460353_iframe_samemanifest.html
+++ b/dom/tests/mochitest/ajax/offline/460353_iframe_samemanifest.html
@@ -7,15 +7,19 @@
 applicationCache.onerror = function() {
   parent.frameOnUpdate("same", false);
 }
 
 applicationCache.oncached = function() {
   parent.frameOnUpdate("same", true, applicationCache.status);
 }
 
+applicationCache.onnoupdate = function() {
+  parent.frameOnUpdate("same", true, applicationCache.status);
+}
+
 </script>
 
 </head>
 <body onload="parent.frameOnLoad('same', applicationCache.status);">
   This is an iframe with the same manifest reference
 </body>
 </html>
--- a/dom/tests/mochitest/ajax/offline/bypass.html
+++ b/dom/tests/mochitest/ajax/offline/bypass.html
@@ -23,18 +23,17 @@ function testScriptPresence(scriptPath, 
 
 function startTest()
 {
   testScriptPresence("namespace1/script.js", "scriptNo0Function();", false);
   testScriptPresence("namespace1/sub/script1.js", "scriptNo1Function();", true);
   testScriptPresence("namespace1/sub2/script2.js", "scriptNo2Function();", true);
   testScriptPresence("namespace2/script3.js", "scriptNo3Function();", true);
 
-  opener.OfflineTest.teardown();
-  opener.OfflineTest.finish();
+  opener.OfflineTest.teardownAndFinish();
   window.close(window);
 }
 
 </script>
 
 </head>
 
 <body onload="startTest();">
--- a/dom/tests/mochitest/ajax/offline/foreign2.html
+++ b/dom/tests/mochitest/ajax/offline/foreign2.html
@@ -11,63 +11,59 @@
 function manifestUpdated()
 {
   var appCacheService = SpecialPowers.Components.classes["@mozilla.org/network/application-cache-service;1"]
     .getService(SpecialPowers.Ci.nsIApplicationCacheService);
 
   var foreign2cache = appCacheService.chooseApplicationCache(
     "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.html", OfflineTest.loadContext());
 
-  OfflineTest.ok(foreign2cache, "Foreign 2 cache present, chosen for foreign2.html");
-  OfflineTest.is(foreign2cache.manifestURI.asciiSpec, "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.cacheManifest")
+  window.opener.OfflineTest.ok(foreign2cache, "Foreign 2 cache present, chosen for foreign2.html");
+  window.opener.OfflineTest.is(foreign2cache.manifestURI.asciiSpec, "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.cacheManifest")
 
   var foreign1cache = OfflineTest.getActiveCache(
     "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign1.cacheManifest");
-  OfflineTest.ok(foreign1cache, "Foreign 1 cache loaded");
+  window.opener.OfflineTest.ok(foreign1cache, "Foreign 1 cache loaded");
   foreign1cache.discard();
 
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  window.opener.onDone();
 }
 
 function onLoaded()
 {
   var appCacheService = SpecialPowers.Components.classes["@mozilla.org/network/application-cache-service;1"]
     .getService(SpecialPowers.Ci.nsIApplicationCacheService);
 
-  var foreign1cache = OfflineTest.getActiveCache(
+  var foreign1cache = window.opener.OfflineTest.getActiveCache(
     "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign1.cacheManifest");
-  OfflineTest.ok(foreign1cache, "Foreign 1 cache loaded");
+  window.opener.OfflineTest.ok(foreign1cache, "Foreign 1 cache loaded");
 
-  var foreign2cache = OfflineTest.getActiveCache(
+  var foreign2cache = window.opener.OfflineTest.getActiveCache(
     "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.cacheManifest");
-  OfflineTest.ok(!foreign2cache, "Foreign 2 cache not present");
+  window.opener.OfflineTest.ok(!foreign2cache, "Foreign 2 cache not present");
 
   foreign1cache = appCacheService.chooseApplicationCache(
-    "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.html", OfflineTest.loadContext());
-  OfflineTest.ok(!foreign1cache, "foreign2.html not chosen from foreign1 cache");
+    "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.html", window.opener.OfflineTest.loadContext());
+  window.opener.OfflineTest.ok(!foreign1cache, "foreign2.html not chosen from foreign1 cache");
 
   try
   {
-    OfflineTest.ok(applicationCache.status == SpecialPowers.Ci.nsIDOMOfflineResourceList.UNCACHED,
+    window.opener.OfflineTest.ok(applicationCache.status == SpecialPowers.Ci.nsIDOMOfflineResourceList.UNCACHED,
         "there is no associated application cache");
   }
   catch (ex)
   {
-    OfflineTest.ok(false, "applicationCache.status must not throw an exception");
+    window.opener.OfflineTest.ok(false, "applicationCache.status must not throw an exception");
   }
 }
 
-if (OfflineTest.setup())
-{
-  applicationCache.onerror = OfflineTest.failEvent;
-  applicationCache.onupdateready = OfflineTest.failEvent;
-  applicationCache.onnoupdate = OfflineTest.failEvent;
-  applicationCache.oncached = OfflineTest.priv(manifestUpdated);
-}
+applicationCache.onerror = window.opener.OfflineTest.failEvent;
+applicationCache.onupdateready = window.opener.OfflineTest.failEvent;
+applicationCache.onnoupdate = window.opener.OfflineTest.failEvent;
+applicationCache.oncached = window.opener.OfflineTest.priv(manifestUpdated);
 
 </script>
 
 </head>
 
 <body onload="OfflineTest.priv(onLoaded)();">
 </body>
 </html>
--- a/dom/tests/mochitest/ajax/offline/offlineChild.html
+++ b/dom/tests/mochitest/ajax/offline/offlineChild.html
@@ -7,17 +7,17 @@
 
 
 <script type="text/javascript">
 
 // This is called by the parent when the offline update is complete
 // (since we don't get those events)
 function doneLoading()
 {
-  window.top.childFinished();
+  window.parent.childFinished();
 }
 
 if (OfflineTest.setupChild()) {
   // Child frames shouldn't be receiving cache events.
   applicationCache.onerror = OfflineTest.failEvent;
   applicationCache.onnoupdate = OfflineTest.failEvent;
   applicationCache.ondownloading = OfflineTest.failEvent;
   applicationCache.onprogress = OfflineTest.failEvent;
--- a/dom/tests/mochitest/ajax/offline/offlineTests.js
+++ b/dom/tests/mochitest/ajax/offline/offlineTests.js
@@ -53,29 +53,36 @@ fetch: function(callback)
 
   var cacheSession = OfflineTest.getActiveSession();
   cacheSession.asyncOpenCacheEntry(url, Ci.nsICache.ACCESS_READ, this);
 }
 };
 
 var OfflineTest = {
 
+_allowedByDefault: false,
+
 _hasSlave: false,
 
 // The window where test results should be sent.
 _masterWindow: null,
 
 // Array of all PUT overrides on the server
 _pathOverrides: [],
 
 // SJSs whom state was changed to be reverted on teardown
 _SJSsStated: [],
 
 setupChild: function()
 {
+  if (this._allowedByDefault) {
+    this._masterWindow = window;
+    return true;
+  }
+
   if (window.parent.OfflineTest._hasSlave) {
     return false;
   }
 
   this._masterWindow = window.top;
 
   return true;
 },
@@ -86,16 +93,27 @@ setupChild: function()
  *
  * @return boolean Whether this window is the slave window
  *                 to actually run the test in.
  */
 setup: function()
 {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
+  var prefBranch = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
+  try {
+    this._allowedByDefault = prefBranch.getBoolPref("offline-apps.allow_by_default");
+  } catch (e) {}
+
+  if (this._allowedByDefault) {
+    this._masterWindow = window;
+
+    return true;
+  }
+
   if (!window.opener || !window.opener.OfflineTest ||
       !window.opener.OfflineTest._hasSlave) {
     // Offline applications must be toplevel windows and have the
     // offline-app permission.  Because we were loaded without the
     // offline-app permission and (probably) in an iframe, we need to
     // enable the pref and spawn a new window to perform the actual
     // tests.  It will use this window to report successes and
     // failures.
@@ -121,45 +139,56 @@ setup: function()
     return false;
   }
 
   this._masterWindow = window.opener;
 
   return true;
 },
 
-teardown: function()
+teardownAndFinish: function()
 {
-  // Remove the offline-app permission we gave ourselves.
+  this.teardown(function(self) { self.finish(); });
+},
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+teardown: function(callback)
+{
+  // First wait for any pending scheduled updates to finish
+  this.waitForUpdates(function(self) {
+    // Remove the offline-app permission we gave ourselves.
+
+    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
-  var pm = Cc["@mozilla.org/permissionmanager;1"]
-           .getService(Ci.nsIPermissionManager);
-  var uri = Cc["@mozilla.org/network/io-service;1"]
-            .getService(Ci.nsIIOService)
-            .newURI(window.location.href, null, null);
-  var principal = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
-                    .getService(Ci.nsIScriptSecurityManager)
-                    .getNoAppCodebasePrincipal(uri);
+    var pm = Cc["@mozilla.org/permissionmanager;1"]
+             .getService(Ci.nsIPermissionManager);
+    var uri = Cc["@mozilla.org/network/io-service;1"]
+              .getService(Ci.nsIIOService)
+              .newURI(window.location.href, null, null);
+    var principal = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
+                      .getService(Ci.nsIScriptSecurityManager)
+                      .getNoAppCodebasePrincipal(uri);
 
-  pm.removeFromPrincipal(principal, "offline-app");
+    pm.removeFromPrincipal(principal, "offline-app");
 
-  // Clear all overrides on the server
-  for (override in this._pathOverrides)
-    this.deleteData(this._pathOverrides[override]);
-  for (statedSJS in this._SJSsStated)
-    this.setSJSState(this._SJSsStated[statedSJS], "");
+    // Clear all overrides on the server
+    for (override in self._pathOverrides)
+      self.deleteData(self._pathOverrides[override]);
+    for (statedSJS in self._SJSsStated)
+      self.setSJSState(self._SJSsStated[statedSJS], "");
 
-  this.clear();
+    self.clear();
+    callback(self);
+  });
 },
 
 finish: function()
 {
-  if (this._masterWindow) {
+  if (this._allowedByDefault) {
+    SimpleTest.executeSoon(SimpleTest.finish);
+  } else if (this._masterWindow) {
     // Slave window: pass control back to master window, close itself.
     this._masterWindow.SimpleTest.executeSoon(this._masterWindow.OfflineTest.finish);
     window.close();
   } else {
     // Master window: finish test.
     SimpleTest.finish();
   }
 },
@@ -191,16 +220,58 @@ clear: function()
 {
   // XXX: maybe we should just wipe out the entire disk cache.
   var applicationCache = this.getActiveCache();
   if (applicationCache) {
     applicationCache.discard();
   }
 },
 
+waitForUpdates: function(callback)
+{
+  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+
+  var self = this;
+  var observer = {
+    notified: false,
+    observe: function(subject, topic, data) {
+      if (subject) {
+        subject.QueryInterface(SpecialPowers.Ci.nsIOfflineCacheUpdate);
+        dump("Update of " + subject.manifestURI.spec + " finished\n");
+      }
+
+      SimpleTest.executeSoon(function() {
+        if (observer.notified) {
+          return;
+        }
+
+        var updateservice = SpecialPowers.Cc["@mozilla.org/offlinecacheupdate-service;1"]
+                            .getService(SpecialPowers.Ci.nsIOfflineCacheUpdateService);
+        var updatesPending = updateservice.numUpdates;
+        if (updatesPending == 0) {
+          try {
+            SpecialPowers.removeObserver(observer, "offline-cache-update-completed");
+          } catch(ex) {}
+          dump("All pending updates done\n");
+          observer.notified = true;
+          callback(self);
+          return;
+        }
+
+        dump("Waiting for " + updateservice.numUpdates + " update(s) to finish\n");
+      });
+    }
+  }
+
+  SpecialPowers.addObserver(observer, "offline-cache-update-completed", false);
+
+  // Call now to check whether there are some updates scheduled
+  observer.observe();
+},
+
 failEvent: function(e)
 {
   OfflineTest.ok(false, "Unexpected event: " + e.type);
 },
 
 // The offline API as specified has no way to watch the load of a resource
 // added with applicationCache.mozAdd().
 waitForAdd: function(url, onFinished) {
@@ -232,17 +303,29 @@ waitForAdd: function(url, onFinished) {
                                      waitForAddListener);
   }
 
   setTimeout(this.priv(waitFunc), 500);
 },
 
 manifestURL: function(overload)
 {
-  var manifestURLspec = overload || window.top.document.documentElement.getAttribute("manifest");
+  var manifestURLspec;
+  if (overload) {
+    manifestURLspec = overload;
+  } else {
+    var win = window;
+    while (win && !win.document.documentElement.getAttribute("manifest")) {
+      if (win == win.parent)
+        break;
+      win = win.parent;
+    }
+    if (win)
+      manifestURLspec = win.document.documentElement.getAttribute("manifest");
+  }
 
   var ios = Cc["@mozilla.org/network/io-service;1"]
             .getService(Ci.nsIIOService)
 
   var baseURI = ios.newURI(window.location.href, null, null);
   return ios.newURI(manifestURLspec, null, baseURI);
 },
 
@@ -262,18 +345,19 @@ getActiveCache: function(overload)
              .getService(Ci.nsIApplicationCacheService);
   var groupID = serv.buildGroupID(this.manifestURL(overload), this.loadContext());
   return serv.getActiveCache(groupID);
 },
 
 getActiveSession: function()
 {
   var cache = this.getActiveCache();
-  if (!cache)
+  if (!cache) {
     return null;
+  }
 
   var cacheService = Cc["@mozilla.org/network/cache-service;1"]
                      .getService(Ci.nsICacheService);
   return cacheService.createSession(cache.clientID,
                                     Ci.nsICache.STORE_OFFLINE,
                                     true);
 },
 
@@ -297,29 +381,30 @@ checkCacheEntries: function(entries, cal
     }
   }
 
   checkNextEntry();
 },
 
 checkCache: function(url, expectEntry, callback)
 {
+  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   var cacheSession = this.getActiveSession();
   this._checkCache(cacheSession, url, expectEntry, callback);
 },
 
 _checkCache: function(cacheSession, url, expectEntry, callback)
 {
   if (!cacheSession) {
     if (expectEntry) {
-      this.ok(false, url + " should exist in the offline cache");
+      this.ok(false, url + " should exist in the offline cache (no session)");
     } else {
-      this.ok(true, url + " should not exist in the offline cache");
+      this.ok(true, url + " should not exist in the offline cache (no session)");
     }
-    setTimeout(this.priv(callback), 0);
+    if (callback) setTimeout(this.priv(callback), 0);
     return;
   }
 
   var _checkCacheListener = {
     onCacheEntryAvailable: function(entry, access, status) {
       netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
       if (entry) {
         if (expectEntry) {
@@ -341,17 +426,17 @@ checkCache: function(url, expectEntry, c
             OfflineTest.ok(!mustBeValid, url + " should exist in the offline cache");
           } else {
             OfflineTest.ok(mustBeValid, url + " should not exist in the offline cache");
           }
         } else {
           OfflineTest.ok(false, "got invalid error for " + url);
         }
       }
-      setTimeout(OfflineTest.priv(callback), 0);
+      if (callback) setTimeout(OfflineTest.priv(callback), 0);
     }
   };
 
   cacheSession.asyncOpenCacheEntry(url,
                                    Ci.nsICache.ACCESS_READ,
                                    _checkCacheListener,
                                    false);
 },
--- a/dom/tests/mochitest/ajax/offline/test_badManifestMagic.html
+++ b/dom/tests/mochitest/ajax/offline/test_badManifestMagic.html
@@ -6,18 +6,17 @@
 <script type="text/javascript" src="/tests/dom/tests/mochitest/ajax/offline/offlineTests.js"></script>
 <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 <script type="text/javascript">
 
 var gGotChecking = false;
 
 function finishTest() {
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 function handleError() {
   OfflineTest.ok(gGotChecking, "Expected checking event");
   OfflineTest.ok(true, "Expected error event");
 
   // These items are listed in the manifest, but the error should have
   // prevented them from being committed to the cache.
--- a/dom/tests/mochitest/ajax/offline/test_bug445544.html
+++ b/dom/tests/mochitest/ajax/offline/test_bug445544.html
@@ -12,18 +12,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 <script type="text/javascript">
 
 var gTestWin;
 var gTimeoutId;
 
 function finish()
 {
   gTestWin.close();
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 function error()
 {
   OfflineTest.ok(false, "Part 2 did not successfully load.");
   finish();
 }
 
--- a/dom/tests/mochitest/ajax/offline/test_bug460353.html
+++ b/dom/tests/mochitest/ajax/offline/test_bug460353.html
@@ -11,35 +11,44 @@
 
 <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
 <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 <script type="text/javascript" src="/tests/dom/tests/mochitest/ajax/offline/offlineTests.js"></script>
 
 <script class="testbody" type="text/javascript">
 
 var result = new Array();
-var expectedUpdates = 2;
+var expectedUpdates = 3; // 2 iframes and our self
 
 init();
 
+function onUpdatePassed()
+{
+  if (!(--expectedUpdates))
+    SimpleTest.executeSoon(finish);
+}
+
 function init()
 {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
   var Cc = Components.classes;
   var Ci = Components.interfaces;
   var pm = Cc["@mozilla.org/permissionmanager;1"]
     .getService(Ci.nsIPermissionManager);
   var uri = Cc["@mozilla.org/network/io-service;1"]
     .getService(Ci.nsIIOService)
     .newURI(window.location.href, null, null);
   var principal = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
                     .getService(Ci.nsIScriptSecurityManager)
                     .getNoAppCodebasePrincipal(uri);
   pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION);
+
+  applicationCache.oncached = onUpdatePassed;
+  applicationCache.onnoupdate = onUpdatePassed;
 }
 
 function frameOnLoad(frameid, status)
 {
   var obj = new Object();
   result[frameid] = obj;
 
   result[frameid].load = true;
@@ -47,18 +56,17 @@ function frameOnLoad(frameid, status)
 }
 
 function frameOnUpdate(frameid, ok, status)
 {
   result[frameid].update = true;
   result[frameid].updateOK = ok;
   result[frameid].cacheStatus = status;
 
-  if (!(--expectedUpdates))
-    finish();
+  onUpdatePassed();
 }
 
 function finish()
 {
   SimpleTest.ok(result["same"].load || false, "Frame with the same manifest loads");
   SimpleTest.ok(result["same"].update || false, "Frame with the same manifest cache update notification");
   SimpleTest.ok(result["same"].updateOK || false, "Frame with the same manifest cache update passed OK");
   SimpleTest.is(result["same"].cacheStatus || -1, 1, "Frame with the same manifest cache status was IDLE");
@@ -82,27 +90,30 @@ function finish()
   var uri = Cc["@mozilla.org/network/io-service;1"]
             .getService(Ci.nsIIOService)
             .newURI(window.location.href, null, null);
   var principal = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
                     .getService(Ci.nsIScriptSecurityManager)
                     .getNoAppCodebasePrincipal(uri);
   pm.removeFromPrincipal(principal, "offline-app");
 
-  cleanCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/simpleManifest.cacheManifest");
-  cleanCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/updatingManifest.sjs");
+  OfflineTest.waitForUpdates(function() {
+    cleanCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/simpleManifest.cacheManifest");
+    cleanCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/updatingManifest.sjs");
 
-  SimpleTest.finish();
+    SimpleTest.finish();
+  });
 }
 
 function cleanCache(manifestURL)
 {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
   var cache = OfflineTest.getActiveCache(manifestURL);
+  dump("Discarding cache for " + manifestURL + " cache=" + cache + "\n");
   if (cache)
     cache.discard();
 }
 
 SimpleTest.waitForExplicitFinish();
 
 </script>
 
--- a/dom/tests/mochitest/ajax/offline/test_bug474696.html
+++ b/dom/tests/mochitest/ajax/offline/test_bug474696.html
@@ -10,28 +10,27 @@
 function manifestUpdated()
 {
   fallbackFrame.location = "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/namespace1/redirectToDifferentOrigin.sjs";
   // Invokes load of fallback.html
 }
 
 function onFallbackLoad(fallbackIdentification)
 {
-  OfflineTest.is(fallbackIdentification, 1, "Got correct fallback for namespace1");
+  OfflineTest.is(fallbackIdentification, 1, "Got correct fallback for namespace1 (2)");
 
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  applicationCache.onerror = function() {}; // the update invoked by the iframe will finish after we discard the cache, ignore error
+  OfflineTest.teardownAndFinish();
 }
 
 SimpleTest.waitForExplicitFinish();
 
 if (OfflineTest.setup()) {
   applicationCache.onerror = OfflineTest.failEvent;
   applicationCache.onupdateready = OfflineTest.failEvent;
-  applicationCache.onnoupdate = OfflineTest.failEvent;
   applicationCache.oncached = OfflineTest.priv(manifestUpdated);
 }
 
 </script>
 
 </head>
 
 <body>
--- a/dom/tests/mochitest/ajax/offline/test_bug544462.html
+++ b/dom/tests/mochitest/ajax/offline/test_bug544462.html
@@ -26,18 +26,17 @@ function manifestUpdated()
 {
   window.location.reload();
 }
 
 function finishTheTest()
 {
   OfflineTest.is(gImageLoaded[1], true, "Image from a different origin not cointained in the offline cache has loaded");
   OfflineTest.is(gImageLoaded[2], true, "Image not cointained in the offline cache has loaded");
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 if (OfflineTest.setup()) {
   applicationCache.onerror = OfflineTest.failEvent;
   applicationCache.oncached = OfflineTest.priv(manifestUpdated);
   applicationCache.onnoupdate = OfflineTest.priv(finishTheTest);
 }
 
--- a/dom/tests/mochitest/ajax/offline/test_bug744719-cancel.html
+++ b/dom/tests/mochitest/ajax/offline/test_bug744719-cancel.html
@@ -14,56 +14,54 @@
   after cancelation.
 */
 
 ok(applicationCache.mozItems.length == 0,
    "applicationCache.mozItems should be available and empty before associating with a cache.");
 
 function updateCanceled()
 {
-  OfflineTest.checkCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/744719-cancel.cacheManifest", false);
-  OfflineTest.checkCache("http://mochi.test:8888/tests/SimpleTest/SimpleTest.js", false);
-  OfflineTest.checkCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/offlineTests.js", false);
+  OfflineTest.checkCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/744719-cancel.cacheManifest", false, null);
+  OfflineTest.checkCache("http://mochi.test:8888/tests/SimpleTest/SimpleTest.js", false, null);
+  OfflineTest.checkCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/offlineTests.js", false, null);
 
-  OfflineTest.checkCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/nonexistent744719?010", false);
+  OfflineTest.checkCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/nonexistent744719?010", false, null);
 
   var URL = "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/subresource744719.html?";
-  OfflineTest.checkCache(URL + "001", false);
-  OfflineTest.checkCache(URL + "002", false);
-  OfflineTest.checkCache(URL + "003", false);
-  OfflineTest.checkCache(URL + "004", false);
-  OfflineTest.checkCache(URL + "005", false);
-  OfflineTest.checkCache(URL + "006", false);
-  OfflineTest.checkCache(URL + "007", false);
-  OfflineTest.checkCache(URL + "008", false);
-  OfflineTest.checkCache(URL + "009", false);
-  OfflineTest.checkCache(URL + "011", false);
-  OfflineTest.checkCache(URL + "012", false);
-  OfflineTest.checkCache(URL + "013", false);
-  OfflineTest.checkCache(URL + "014", false);
-  OfflineTest.checkCache(URL + "015", false);
-  OfflineTest.checkCache(URL + "016", false);
-  OfflineTest.checkCache(URL + "017", false);
-  OfflineTest.checkCache(URL + "018", false);
-  OfflineTest.checkCache(URL + "019", false);
-  OfflineTest.checkCache(URL + "020", false);
-  OfflineTest.checkCache(URL + "021", false);
-  OfflineTest.checkCache(URL + "022", false);
-  OfflineTest.checkCache(URL + "023", false);
-  OfflineTest.checkCache(URL + "024", false);
-  OfflineTest.checkCache(URL + "025", false);
-  OfflineTest.checkCache(URL + "026", false);
-  OfflineTest.checkCache(URL + "027", false);
-  OfflineTest.checkCache(URL + "028", false);
-  OfflineTest.checkCache(URL + "029", false);
-  OfflineTest.checkCache(URL + "030", false);
+  OfflineTest.checkCache(URL + "001", false, null);
+  OfflineTest.checkCache(URL + "002", false, null);
+  OfflineTest.checkCache(URL + "003", false, null);
+  OfflineTest.checkCache(URL + "004", false, null);
+  OfflineTest.checkCache(URL + "005", false, null);
+  OfflineTest.checkCache(URL + "006", false, null);
+  OfflineTest.checkCache(URL + "007", false, null);
+  OfflineTest.checkCache(URL + "008", false, null);
+  OfflineTest.checkCache(URL + "009", false, null);
+  OfflineTest.checkCache(URL + "011", false, null);
+  OfflineTest.checkCache(URL + "012", false, null);
+  OfflineTest.checkCache(URL + "013", false, null);
+  OfflineTest.checkCache(URL + "014", false, null);
+  OfflineTest.checkCache(URL + "015", false, null);
+  OfflineTest.checkCache(URL + "016", false, null);
+  OfflineTest.checkCache(URL + "017", false, null);
+  OfflineTest.checkCache(URL + "018", false, null);
+  OfflineTest.checkCache(URL + "019", false, null);
+  OfflineTest.checkCache(URL + "020", false, null);
+  OfflineTest.checkCache(URL + "021", false, null);
+  OfflineTest.checkCache(URL + "022", false, null);
+  OfflineTest.checkCache(URL + "023", false, null);
+  OfflineTest.checkCache(URL + "024", false, null);
+  OfflineTest.checkCache(URL + "025", false, null);
+  OfflineTest.checkCache(URL + "026", false, null);
+  OfflineTest.checkCache(URL + "027", false, null);
+  OfflineTest.checkCache(URL + "028", false, null);
+  OfflineTest.checkCache(URL + "029", false, null);
+  OfflineTest.checkCache(URL + "030", false, null);
 
-  OfflineTest.teardown();
-
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 if (OfflineTest.setup()) {
   // Wait some time after the update has been canceled to catch potential leaks of channels that would cause
   // unwanted items to be cached regardless the update has been canceled with a failure.
   var privUpdateCanceled = OfflineTest.priv(updateCanceled);
   applicationCache.onerror = function() {window.setTimeout(privUpdateCanceled, 1000)};
 
--- a/dom/tests/mochitest/ajax/offline/test_bug744719.html
+++ b/dom/tests/mochitest/ajax/offline/test_bug744719.html
@@ -47,21 +47,19 @@ function manifestUpdated()
   OfflineTest.checkCache(URL + "022", true);
   OfflineTest.checkCache(URL + "023", true);
   OfflineTest.checkCache(URL + "024", true);
   OfflineTest.checkCache(URL + "025", true);
   OfflineTest.checkCache(URL + "026", true);
   OfflineTest.checkCache(URL + "027", true);
   OfflineTest.checkCache(URL + "028", true);
   OfflineTest.checkCache(URL + "029", true);
-  OfflineTest.checkCache(URL + "030", true);
-
-  OfflineTest.teardown();
-
-  OfflineTest.finish();
+  OfflineTest.checkCache(URL + "030", true, function() {
+    OfflineTest.teardownAndFinish();
+  });
 }
 
 if (OfflineTest.setup()) {
   applicationCache.onerror = OfflineTest.failEvent;
   applicationCache.oncached = OfflineTest.priv(manifestUpdated);
 }
 
 SimpleTest.waitForExplicitFinish();
--- a/dom/tests/mochitest/ajax/offline/test_bug765203.html
+++ b/dom/tests/mochitest/ajax/offline/test_bug765203.html
@@ -30,18 +30,17 @@ function manifestUpdated()
     ["http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/offlineTests.js", true],
 
     // The bad entries from the manifest should not be in the cache
     ["http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/jupiter.jpg", false]
   ];
   OfflineTest.checkCacheEntries(
     entries,
     function() {
-       OfflineTest.teardown();
-       OfflineTest.finish();
+       OfflineTest.teardownAndFinish();
     });
 }
 
 if (OfflineTest.setup()) {
   OfflineTest.ok(applicationCache instanceof EventTarget,
                  "applicationCache should be an event target");
 
   applicationCache.onerror = OfflineTest.failEvent;
--- a/dom/tests/mochitest/ajax/offline/test_cancelOfflineCache.html
+++ b/dom/tests/mochitest/ajax/offline/test_cancelOfflineCache.html
@@ -13,41 +13,40 @@ var manifestURI = Cc["@mozilla.org/netwo
                   .getService(Ci.nsIIOService)
                   .newURI(manifest, null, null);
 var updateService = Cc['@mozilla.org/offlinecacheupdate-service;1']
                     .getService(Ci.nsIOfflineCacheUpdateService);
 
 function manifestCached () {
   OfflineTest.ok(false, "The update was supposed to be canceled");
 
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 function onError () {
   OfflineTest.ok(true, "Expected error: Update canceled");
 
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 function onProgress () {
   var i = 0;
   while (i < updateService.numUpdates) {
     var update = updateService.getUpdate(i);
     if (update.manifestURI.spec == manifestURI.spec) {
       update.cancel();
       return;
     }
     i++;
   }
 }
 
 if (OfflineTest.setup()) {
   applicationCache.onerror = OfflineTest.priv(onError);
+  applicationCache.onnoupdate = OfflineTest.failEvent;
   applicationCache.onprogress = OfflineTest.priv(onProgress);
   applicationCache.oncached = OfflineTest.priv(manifestCached);
 }
 
 SimpleTest.waitForExplicitFinish();
 
 </script>
 
--- a/dom/tests/mochitest/ajax/offline/test_changingManifest.html
+++ b/dom/tests/mochitest/ajax/offline/test_changingManifest.html
@@ -13,18 +13,17 @@ var gGotDownloading = false;
 
 var g1SecUrl =  "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/changing1Sec.sjs";
 var g1HourUrl = "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/changing1Hour.sjs";
 
 var gCacheContents = null;
 
 function finish()
 {
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 function manifestUpdatedAgain()
 {
   OfflineTest.ok(gGotChecking, "Should get a checking event on the second update");
   OfflineTest.ok(gGotDownloading, "Should get a downloading event on the second update");
 
   // The second manifest has no NETWORK entry, but we are still
--- a/dom/tests/mochitest/ajax/offline/test_fallback.html
+++ b/dom/tests/mochitest/ajax/offline/test_fallback.html
@@ -91,18 +91,17 @@ function onFallbackLoad(fallbackIdentifi
   }
 
   ++gStep;
 }
 
 
 function finishTest()
 {
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 function finalize()
 {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
   var entries = [
     ["http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/namespace1/sub-non-existing.html", false],
--- a/dom/tests/mochitest/ajax/offline/test_foreign.html
+++ b/dom/tests/mochitest/ajax/offline/test_foreign.html
@@ -14,28 +14,36 @@
  * foreign2.html page is checked we redirect to foreign2.html
  * page. Then the test continues inside that page as follows:
  * On load of foreign2.html we check there is no associated cache
  * because the foreign2.html page was marked as FOREIGN in foreign1 cache.
  * After the foreign2 manifest is updated we check foreign2 cache is
  * chosen by foreign.html page.
  */
 
+var win;
+
 function manifestUpdated()
 {
-  var appCacheService = SpecialPowers.Components.classes["@mozilla.org/network/application-cache-service;1"]
+  var appCacheService = SpecialPowers.Cc["@mozilla.org/network/application-cache-service;1"]
     .getService(SpecialPowers.Ci.nsIApplicationCacheService);
 
   foreign1cache = appCacheService.chooseApplicationCache(
     "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.html", OfflineTest.loadContext());
 
   OfflineTest.ok(foreign1cache, "foreign2.html chosen from foreign1 cache");
   OfflineTest.is(foreign1cache.manifestURI.asciiSpec, "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign1.cacheManifest")
 
-  window.location = "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.html";
+  win = window.open("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.html");
+}
+
+function onDone() // called by the open window after stuff is finished
+{
+  win.close();
+  OfflineTest.teardownAndFinish();
 }
 
 SimpleTest.waitForExplicitFinish();
 
 if (OfflineTest.setup()) {
   applicationCache.onerror = OfflineTest.failEvent;
   applicationCache.onupdateready = OfflineTest.failEvent;
   applicationCache.onnoupdate = OfflineTest.failEvent;
--- a/dom/tests/mochitest/ajax/offline/test_identicalManifest.html
+++ b/dom/tests/mochitest/ajax/offline/test_identicalManifest.html
@@ -8,18 +8,17 @@
 
 <script type="text/javascript">
 
 var gGotChecking = false;
 var gGotDownloading = false;
 
 function finishTest()
 {
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 function noUpdate()
 {
   OfflineTest.ok(gGotChecking, "Should get a checking event");
   OfflineTest.ok(!gGotDownloading, "Should not get a downloading event");
 
   var entries = [
--- a/dom/tests/mochitest/ajax/offline/test_lowDeviceStorage.html
+++ b/dom/tests/mochitest/ajax/offline/test_lowDeviceStorage.html
@@ -27,31 +27,29 @@ var updateService = SpecialPowers.Cc['@m
 var obs = SpecialPowers.Cc["@mozilla.org/observer-service;1"]
                        .getService(SpecialPowers.Ci.nsIObserverService);
 
 var errorReceived = false;
 
 function finish() {
   obs.notifyObservers(updateService, "disk-space-watcher", "free");
 
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 if (OfflineTest.setup()) {
   obs.notifyObservers(updateService, "disk-space-watcher", "full");
 
   var updateObserver = {
     updateStateChanged: function (aUpdate, aState) {
       switch(aState) {
         case Ci.nsIOfflineCacheUpdateObserver.STATE_ERROR:
           aUpdate.removeObserver(this);
           errorReceived = true;
           OfflineTest.ok(true, "Expected error. Update canceled");
-          finish();
         break;
         case Ci.nsIOfflineCacheUpdateObserver.STATE_FINISHED:
           OfflineTest.ok(errorReceived,
                          "Finished after receiving the expected error");
           finish();
         break;
         case Ci.nsIOfflineCacheUpdateObserver.STATE_NOUPDATE:
           aUpdate.removeObserver(this);
--- a/dom/tests/mochitest/ajax/offline/test_lowDeviceStorageDuringUpdate.html
+++ b/dom/tests/mochitest/ajax/offline/test_lowDeviceStorageDuringUpdate.html
@@ -17,18 +17,17 @@ var updateService = Cc['@mozilla.org/off
                     .getService(Ci.nsIOfflineCacheUpdateService);
 
 var obs = SpecialPowers.Cc["@mozilla.org/observer-service;1"]
                        .getService(SpecialPowers.Ci.nsIObserverService);
 
 function finish() {
   obs.notifyObservers(updateService, "disk-space-watcher", "free");
 
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 function onError() {
   OfflineTest.ok(true, "Expected error: Update canceled");
   finish();
 }
 
 function onUnexpectedEvent() {
--- a/dom/tests/mochitest/ajax/offline/test_missingFile.html
+++ b/dom/tests/mochitest/ajax/offline/test_missingFile.html
@@ -7,18 +7,17 @@
 <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 <script type="text/javascript">
 
 var gGotChecking = false;
 var gGotDownloading = false;
 
 function finishTest() {
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 function handleError() {
   OfflineTest.ok(gGotChecking, "Expected checking event");
   OfflineTest.ok(gGotDownloading, "Expected downloading event");
   OfflineTest.ok(true, "Expected error event");
 
   // These items are listed in the manifest, but the error should have
--- a/dom/tests/mochitest/ajax/offline/test_offlineIFrame.html
+++ b/dom/tests/mochitest/ajax/offline/test_offlineIFrame.html
@@ -18,18 +18,17 @@ function checkEntries() {
     ["http://mochi.test:8888/tests/SimpleTest/SimpleTest.js", true],
     ["http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/offlineTests.js", true]
   ];
   OfflineTest.checkCacheEntries(entries, function() { window.frames["offlineChild"].doneLoading(); });
 }
 
 function childFinished()
 {
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 if (OfflineTest.setup()) {
   applicationCache.onerror = OfflineTest.failEvent;
 
   applicationCache.oncached = OfflineTest.priv(checkEntries);
 }
 
--- a/dom/tests/mochitest/ajax/offline/test_offlineMode.html
+++ b/dom/tests/mochitest/ajax/offline/test_offlineMode.html
@@ -94,18 +94,17 @@ function finalize()
 
     ioserv.offline = false;
 
     OfflineTest.is(gGotExplicitVersion, 1, "Explicit entry loaded");
     OfflineTest.is(gGotImplicitVersion, 1, "Bug 461325 - Implicit entry loaded");
     OfflineTest.is(gGotDynamicVersion, 1, "Dynamic entry loaded");
     OfflineTest.ok(gGotOnError, "Got onerror event invoked by implicit page load in offline mode");
 
-    OfflineTest.teardown();
-    OfflineTest.finish();
+    OfflineTest.teardownAndFinish();
   }
 }
 
 function goOffline()
 {
   var listener = {
     onCacheEntryDoomed: function (status) {
       OfflineTest.priv(goOfflineContinue)();
--- a/dom/tests/mochitest/ajax/offline/test_overlap.html
+++ b/dom/tests/mochitest/ajax/offline/test_overlap.html
@@ -10,18 +10,17 @@
 
 function manifestUpdated()
 {
   var xhr = new XMLHttpRequest();
   xhr.open("GET", "bogus/specific/test.html", false);
   xhr.send();
 
   OfflineTest.is(xhr.status, 200, "Should have fallen back.");
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 if (OfflineTest.setup()) {
   applicationCache.onerror = OfflineTest.failEvent;
   applicationCache.oncached = OfflineTest.priv(manifestUpdated);
 }
 
 SimpleTest.waitForExplicitFinish();
--- a/dom/tests/mochitest/ajax/offline/test_redirectManifest.html
+++ b/dom/tests/mochitest/ajax/offline/test_redirectManifest.html
@@ -20,18 +20,17 @@ function manifestCached()
 function manifestError()
 {
   OfflineTest.ok(true, "Error expected");
   finish();
 }
 
 function finish()
 {
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 SimpleTest.waitForExplicitFinish();
 
 if (OfflineTest.setup()) {
   applicationCache.onerror = OfflineTest.priv(manifestError);
   applicationCache.oncached = OfflineTest.priv(manifestCached);
 }
--- a/dom/tests/mochitest/ajax/offline/test_redirectUpdateItem.html
+++ b/dom/tests/mochitest/ajax/offline/test_redirectUpdateItem.html
@@ -103,18 +103,17 @@ function manifestError()
       OfflineTest.ok(true, "Error expected when updating to third version of the manifest");
       finish();
       break;
   }
 }
 
 function finish()
 {
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 SimpleTest.waitForExplicitFinish();
 
 if (OfflineTest.setup()) {
   applicationCache.onerror = OfflineTest.priv(manifestError);
   applicationCache.onupdateready = OfflineTest.priv(manifestUpdated);
   applicationCache.oncached = OfflineTest.priv(manifestCached);
--- a/dom/tests/mochitest/ajax/offline/test_refetchManifest.html
+++ b/dom/tests/mochitest/ajax/offline/test_refetchManifest.html
@@ -4,18 +4,17 @@
 
 <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
 <script type="text/javascript" src="/tests/dom/tests/mochitest/ajax/offline/offlineTests.js"></script>
 
 <script type="text/javascript">
 
 function finish()
 {
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 function failAndFinish(e)
 {
   OfflineTest.ok(false, "Unexpected event: " + e.type);
   finish();
 }
 
--- a/dom/tests/mochitest/ajax/offline/test_simpleManifest.html
+++ b/dom/tests/mochitest/ajax/offline/test_simpleManifest.html
@@ -44,18 +44,17 @@ function removeItem()
                  "applicationCache should have no dynamic entries");
   OfflineTest.ok(!applicationCache.mozHasItem("http://mochi.test:8888/tests/SimpleTest/EventUtils.js"),
                  "applicationCache.mozHasItem() should not see the removed dynamic entry");
 
   OfflineTest.checkCache("http://mochi.test:8888/tests/SimpleTest/EventUtils.js",
                          false,
                          function() {
                            // We're done
-                           OfflineTest.teardown();
-                           OfflineTest.finish();
+                           OfflineTest.teardownAndFinish();
                          });
 }
 
 function manifestUpdated()
 {
   OfflineTest.ok(gGotChecking, "Should get a checking event");
   OfflineTest.ok(gGotDownloading, "Should get a downloading event");
 
--- a/dom/tests/mochitest/ajax/offline/test_updateCheck.html
+++ b/dom/tests/mochitest/ajax/offline/test_updateCheck.html
@@ -63,18 +63,17 @@ function manifestCached()
 
 function manifestUpdated()
 {
   // Check for an update after manifest has been updated
   updateService.checkForUpdate(manifestURI, 0, false, {
     observe: function(subject, topic, data) {
       OfflineTest.is(topic, "offline-cache-update-unavailable", "No update avail (2)");
 
-      OfflineTest.teardown();
-      OfflineTest.finish();
+      OfflineTest.teardownAndFinish();
     }
   });
 }
 
 if (OfflineTest.setup()) {
   applicationCache.onerror = OfflineTest.failEvent;
   applicationCache.oncached = OfflineTest.priv(manifestCached);
 }
--- a/dom/tests/mochitest/ajax/offline/test_updatingManifest.html
+++ b/dom/tests/mochitest/ajax/offline/test_updatingManifest.html
@@ -33,17 +33,17 @@ function reloadLocations(frames)
 }
 
 function waitForLocations(frames, doneFunc)
 {
   frame = frames.shift();
   if (frame)
     // toString() might cause problems when this test will
     // completely be changed to test IDN behavior.
-    OfflineTest.waitForAdd(frame.location.toString(), function()
+    OfflineTest.waitForAdd(frame, function()
       {
         waitForLocations(frames, doneFunc);
       }
     );
   else
   {
     doneFunc();
   }
@@ -89,17 +89,17 @@ function checkFallbackAndWhitelisting(ke
 
 function frameLoad(version)
 {
   gGotFrameVersion = version;
   if (gCallOnUpdatingFrameLoad)
   {
     var call = gCallOnUpdatingFrameLoad;
     gCallOnUpdatingFrameLoad = null;
-    OfflineTest.priv(call)();
+    SimpleTest.executeSoon(OfflineTest.priv(call));
   }
 }
 
 function whitelistOnLoad(version)
 {
   // Whitelisting is not tested by this test...
 }
 
@@ -107,31 +107,34 @@ function whitelistOnLoad(version)
 // Start of the test function chain
 // ================================
 
 function manifestCached()
 {
   OfflineTest.is(gStep, 0, "Got manifestCached in step 0, gStep=" + gStep);
 
   reloadLocations([fallbackFrame1, fallbackFrame2]);
-  waitForLocations([fallbackFrame1, fallbackFrame2],
-      fallbackLoaded);
+  waitForLocations(
+    ["http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/fallback.html"],
+    fallbackLoaded
+  );
 }
 
 function fallbackLoaded()
 {
+  dump("in fallbackLoaded\n");
   applicationCache.mozAdd("http://mochi.test:8888/tests/SimpleTest/EventUtils.js");
   OfflineTest.waitForAdd("http://mochi.test:8888/tests/SimpleTest/EventUtils.js",
       dynamicLoaded);
 }
 
 function dynamicLoaded()
 {
   window.open("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/updatingImplicit.html");
-  // window.onload invokes implicitLoaded()
+  // window.applicationCache.noupdate invokes implicitLoaded()
 }
 
 function implicitLoaded(aWindow, errorOccured)
 {
   aWindow.close();
 
   OfflineTest.ok(!errorOccured, "No error on new implicit page manifest update");
 
@@ -232,18 +235,18 @@ function manifestUpdated()
       entries,
       function() {
         ++gStep;
 
         OfflineTest.setSJSState("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/updatingManifest.sjs", "third");
         OfflineTest.setSJSState("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/updatingIframe.sjs", "second");
 
         gGotFrameVersion = 0;
-        gCallOnUpdatingFrameLoad = function() {applicationCache.update();};
         updatingFrame.location.reload();
+        // Since the frame is offline-cached, reload of it invokes update
       });
 
     break;
 
   case 2:
     // Processing third version of the manifest.
 
     // Whitelist entries
@@ -293,34 +296,34 @@ function manifestUpdated()
   }
 }
 
 function manifestNoUpdate()
 {
   applicationCache.onnoupdate = null;
 
   OfflineTest.ok(gStep == 3, "Got manifestNoUpdate in step 3, gStep=" + gStep);
+  ++gStep;
 
   OfflineTest.is(applicationCache.status, SpecialPowers.Ci.nsIDOMOfflineResourceList.UPDATEREADY,
         "we have associated application cache and update is pending (4)");
   applicationCache.swapCache();
   OfflineTest.is(applicationCache.status, SpecialPowers.Ci.nsIDOMOfflineResourceList.IDLE,
         "we have associated application cache (4)");
 
   gGotFrameVersion = 0;
   gCallOnUpdatingFrameLoad = checkNewVersionOfIFrame;
   updatingFrame.location.reload();
 }
 
 function checkNewVersionOfIFrame()
 {
   OfflineTest.is(gGotFrameVersion, 2, "IFrame version 2");
 
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 // End of the test function chain
 // ==============================
 
 SimpleTest.waitForExplicitFinish();
 
 if (OfflineTest.setup()) {
--- a/dom/tests/mochitest/ajax/offline/test_xhtmlManifest.xhtml
+++ b/dom/tests/mochitest/ajax/offline/test_xhtmlManifest.xhtml
@@ -7,18 +7,17 @@
 <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 <script type="text/javascript">
 
 function manifestUpdated()
 {
   OfflineTest.ok(true, "Application cache updated.");
 
-  OfflineTest.teardown();
-  OfflineTest.finish();
+  OfflineTest.teardownAndFinish();
 }
 
 if (OfflineTest.setup()) {
   applicationCache.onerror = OfflineTest.failEvent;
   applicationCache.oncached = OfflineTest.priv(manifestUpdated);
 }
 
 SimpleTest.waitForExplicitFinish();
--- a/gfx/layers/basic/BasicCanvasLayer.h
+++ b/gfx/layers/basic/BasicCanvasLayer.h
@@ -24,17 +24,18 @@ namespace layers {
 class CanvasClient2D;
 class CanvasClientWebGL;
 
 class BasicCanvasLayer : public CopyableCanvasLayer,
                          public BasicImplData
 {
 public:
   BasicCanvasLayer(BasicLayerManager* aLayerManager) :
-    CopyableCanvasLayer(aLayerManager, static_cast<BasicImplData*>(this))
+    CopyableCanvasLayer(aLayerManager,
+                        static_cast<BasicImplData*>(MOZ_THIS_IN_INITIALIZER_LIST()))
   { }
   
   virtual void SetVisibleRegion(const nsIntRegion& aRegion)
   {
     NS_ASSERTION(BasicManager()->InConstruction(),
                  "Can only set properties in construction phase");
     CanvasLayer::SetVisibleRegion(aRegion);
   }
--- a/gfx/layers/basic/BasicColorLayer.cpp
+++ b/gfx/layers/basic/BasicColorLayer.cpp
@@ -9,17 +9,18 @@
 using namespace mozilla::gfx;
 
 namespace mozilla {
 namespace layers {
 
 class BasicColorLayer : public ColorLayer, public BasicImplData {
 public:
   BasicColorLayer(BasicLayerManager* aLayerManager) :
-    ColorLayer(aLayerManager, static_cast<BasicImplData*>(this))
+    ColorLayer(aLayerManager,
+               static_cast<BasicImplData*>(MOZ_THIS_IN_INITIALIZER_LIST()))
   {
     MOZ_COUNT_CTOR(BasicColorLayer);
   }
   virtual ~BasicColorLayer()
   {
     MOZ_COUNT_DTOR(BasicColorLayer);
   }
 
--- a/gfx/layers/basic/BasicContainerLayer.h
+++ b/gfx/layers/basic/BasicContainerLayer.h
@@ -173,17 +173,18 @@ class BasicContainerLayer : public Conta
   template<class Container>
   friend void ContainerRepositionChild(Layer* aChild, Layer* aAfter, Container* aContainer);
   template<class Container>
   friend void ContainerComputeEffectiveTransforms(const gfx3DMatrix& aTransformToSurface,
                                                   Container* aContainer);
 
 public:
   BasicContainerLayer(BasicLayerManager* aManager) :
-    ContainerLayer(aManager, static_cast<BasicImplData*>(this))
+    ContainerLayer(aManager,
+                   static_cast<BasicImplData*>(MOZ_THIS_IN_INITIALIZER_LIST()))
   {
     MOZ_COUNT_CTOR(BasicContainerLayer);
     mSupportsComponentAlphaChildren = true;
   }
   virtual ~BasicContainerLayer();
 
   virtual void SetVisibleRegion(const nsIntRegion& aRegion)
   {
--- a/gfx/layers/basic/BasicImageLayer.cpp
+++ b/gfx/layers/basic/BasicImageLayer.cpp
@@ -17,17 +17,18 @@
 using namespace mozilla::gfx;
 
 namespace mozilla {
 namespace layers {
 
 class BasicImageLayer : public ImageLayer, public BasicImplData {
 public:
   BasicImageLayer(BasicLayerManager* aLayerManager) :
-    ImageLayer(aLayerManager, static_cast<BasicImplData*>(this)),
+    ImageLayer(aLayerManager,
+               static_cast<BasicImplData*>(MOZ_THIS_IN_INITIALIZER_LIST())),
     mSize(-1, -1)
   {
     MOZ_COUNT_CTOR(BasicImageLayer);
   }
   virtual ~BasicImageLayer()
   {
     MOZ_COUNT_DTOR(BasicImageLayer);
   }
--- a/gfx/layers/basic/BasicLayersImpl.h
+++ b/gfx/layers/basic/BasicLayersImpl.h
@@ -36,17 +36,18 @@ private:
   nsRefPtr<gfxContext> mContext;
 };
 
 class BasicReadbackLayer : public ReadbackLayer,
                            public BasicImplData
 {
 public:
   BasicReadbackLayer(BasicLayerManager* aLayerManager) :
-    ReadbackLayer(aLayerManager, static_cast<BasicImplData*>(this))
+    ReadbackLayer(aLayerManager,
+                  static_cast<BasicImplData*>(MOZ_THIS_IN_INITIALIZER_LIST()))
   {
     MOZ_COUNT_CTOR(BasicReadbackLayer);
   }
   virtual ~BasicReadbackLayer()
   {
     MOZ_COUNT_DTOR(BasicReadbackLayer);
   }
 
--- a/gfx/layers/basic/BasicThebesLayer.h
+++ b/gfx/layers/basic/BasicThebesLayer.h
@@ -14,17 +14,18 @@ namespace mozilla {
 namespace layers {
 
 class BasicThebesLayer : public ThebesLayer, public BasicImplData {
 public:
   typedef ThebesLayerBuffer::PaintState PaintState;
   typedef ThebesLayerBuffer::ContentType ContentType;
 
   BasicThebesLayer(BasicLayerManager* aLayerManager) :
-    ThebesLayer(aLayerManager, static_cast<BasicImplData*>(this)),
+    ThebesLayer(aLayerManager,
+                static_cast<BasicImplData*>(MOZ_THIS_IN_INITIALIZER_LIST())),
     mContentClient(nullptr)
   {
     MOZ_COUNT_CTOR(BasicThebesLayer);
   }
   virtual ~BasicThebesLayer()
   {
     MOZ_COUNT_DTOR(BasicThebesLayer);
   }
--- a/gfx/layers/client/ClientCanvasLayer.h
+++ b/gfx/layers/client/ClientCanvasLayer.h
@@ -23,17 +23,18 @@ class CanvasClient2D;
 class CanvasClientWebGL;
 
 class ClientCanvasLayer : public CopyableCanvasLayer,
                           public ClientLayer
 {
   typedef CanvasClient::CanvasClientType CanvasClientType;
 public:
   ClientCanvasLayer(ClientLayerManager* aLayerManager) :
-    CopyableCanvasLayer(aLayerManager, static_cast<ClientLayer*>(this))
+    CopyableCanvasLayer(aLayerManager,
+                        static_cast<ClientLayer*>(MOZ_THIS_IN_INITIALIZER_LIST()))
   {
     MOZ_COUNT_CTOR(ClientCanvasLayer);
   }
   virtual ~ClientCanvasLayer()
   {
     MOZ_COUNT_DTOR(ClientCanvasLayer);
     if (mCanvasClient) {
       mCanvasClient->OnDetach();
--- a/gfx/layers/client/ClientColorLayer.cpp
+++ b/gfx/layers/client/ClientColorLayer.cpp
@@ -10,17 +10,18 @@ using namespace mozilla::gfx;
 
 namespace mozilla {
 namespace layers {
 
 class ClientColorLayer : public ColorLayer, 
                          public ClientLayer {
 public:
   ClientColorLayer(ClientLayerManager* aLayerManager) :
-    ColorLayer(aLayerManager, static_cast<ClientLayer*>(this))
+    ColorLayer(aLayerManager,
+               static_cast<ClientLayer*>(MOZ_THIS_IN_INITIALIZER_LIST()))
   {
     MOZ_COUNT_CTOR(ClientColorLayer);
   }
   virtual ~ClientColorLayer()
   {
     MOZ_COUNT_DTOR(ClientColorLayer);
   }
 
--- a/gfx/layers/client/ClientContainerLayer.h
+++ b/gfx/layers/client/ClientContainerLayer.h
@@ -134,17 +134,18 @@ class ClientContainerLayer : public Cont
   friend void ContainerInsertAfter(Layer* aChild, Layer* aAfter, Container* aContainer);
   template<class Container>
   friend void ContainerRemoveChild(Layer* aChild, Container* aContainer);
   template<class Container>
   friend void ContainerRepositionChild(Layer* aChild, Layer* aAfter, Container* aContainer);
 
 public:
   ClientContainerLayer(ClientLayerManager* aManager) :
-    ContainerLayer(aManager, static_cast<ClientLayer*>(this))
+    ContainerLayer(aManager,
+                   static_cast<ClientLayer*>(MOZ_THIS_IN_INITIALIZER_LIST()))
   {
     MOZ_COUNT_CTOR(ClientContainerLayer);
     mSupportsComponentAlphaChildren = true;
   }
   virtual ~ClientContainerLayer()
   {
     while (mFirstChild) {
       ContainerRemoveChild(mFirstChild, this);
@@ -245,17 +246,18 @@ protected:
     return static_cast<ClientLayerManager*>(mManager);
   }
 };
 
 class ClientRefLayer : public RefLayer,
                        public ClientLayer {
 public:
   ClientRefLayer(ClientLayerManager* aManager) :
-    RefLayer(aManager, static_cast<ClientLayer*>(this))
+    RefLayer(aManager,
+             static_cast<ClientLayer*>(MOZ_THIS_IN_INITIALIZER_LIST()))
   {
     MOZ_COUNT_CTOR(ClientRefLayer);
   }
   virtual ~ClientRefLayer()
   {
     MOZ_COUNT_DTOR(ClientRefLayer);
   }
 
--- a/gfx/layers/client/ClientImageLayer.cpp
+++ b/gfx/layers/client/ClientImageLayer.cpp
@@ -12,17 +12,18 @@ using namespace mozilla::gfx;
 
 namespace mozilla {
 namespace layers {
 
 class ClientImageLayer : public ImageLayer, 
                          public ClientLayer {
 public:
   ClientImageLayer(ClientLayerManager* aLayerManager)
-    : ImageLayer(aLayerManager, static_cast<ClientLayer*>(this))
+    : ImageLayer(aLayerManager,
+                 static_cast<ClientLayer*>(MOZ_THIS_IN_INITIALIZER_LIST()))
     , mImageClientTypeContainer(BUFFER_UNKNOWN)
   {
     MOZ_COUNT_CTOR(ClientImageLayer);
   }
   virtual ~ClientImageLayer()
   {
     DestroyBackBuffer();
     MOZ_COUNT_DTOR(ClientImageLayer);
--- a/gfx/layers/client/ClientThebesLayer.h
+++ b/gfx/layers/client/ClientThebesLayer.h
@@ -15,17 +15,18 @@ namespace layers {
 
 class ClientThebesLayer : public ThebesLayer, 
                           public ClientLayer {
 public:
   typedef ThebesLayerBuffer::PaintState PaintState;
   typedef ThebesLayerBuffer::ContentType ContentType;
 
   ClientThebesLayer(ClientLayerManager* aLayerManager) :
-    ThebesLayer(aLayerManager, static_cast<ClientLayer*>(this)),
+    ThebesLayer(aLayerManager,
+                static_cast<ClientLayer*>(MOZ_THIS_IN_INITIALIZER_LIST())),
     mContentClient(nullptr)
   {
     MOZ_COUNT_CTOR(ClientThebesLayer);
   }
   virtual ~ClientThebesLayer()
   {
     if (mContentClient) {
       mContentClient->OnDetach();
--- a/gfx/layers/client/ClientTiledThebesLayer.cpp
+++ b/gfx/layers/client/ClientTiledThebesLayer.cpp
@@ -9,17 +9,18 @@
 #include "gfxPlatform.h"
 
 
 namespace mozilla {
 namespace layers {
 
 
 ClientTiledThebesLayer::ClientTiledThebesLayer(ClientLayerManager* const aManager)
-  : ThebesLayer(aManager, static_cast<ClientLayer*>(this))
+  : ThebesLayer(aManager,
+                static_cast<ClientLayer*>(MOZ_THIS_IN_INITIALIZER_LIST()))
   , mContentClient()
 {
   MOZ_COUNT_CTOR(ClientTiledThebesLayer);
   mPaintData.mLastScrollOffset = CSSPoint(0, 0);
   mPaintData.mFirstPaint = true;
 }
 
 ClientTiledThebesLayer::~ClientTiledThebesLayer()
--- a/gfx/layers/ipc/AsyncPanZoomController.cpp
+++ b/gfx/layers/ipc/AsyncPanZoomController.cpp
@@ -166,18 +166,18 @@ AsyncPanZoomController::AsyncPanZoomCont
                                                GeckoContentController* aGeckoContentController,
                                                GestureBehavior aGestures)
   :  mLayersId(aLayersId),
      mPaintThrottler(GetFrameTime()),
      mGeckoContentController(aGeckoContentController),
      mRefPtrMonitor("RefPtrMonitor"),
      mMonitor("AsyncPanZoomController"),
      mTouchListenerTimeoutTask(nullptr),
-     mX(this),
-     mY(this),
+     mX(MOZ_THIS_IN_INITIALIZER_LIST()),
+     mY(MOZ_THIS_IN_INITIALIZER_LIST()),
      mAllowZoom(true),
      mMinZoom(MIN_ZOOM),
      mMaxZoom(MAX_ZOOM),
      mLastSampleTime(GetFrameTime()),
      mState(NOTHING),
      mLastAsyncScrollTime(GetFrameTime()),
      mLastAsyncScrollOffset(0, 0),
      mCurrentAsyncScrollOffset(0, 0),
--- a/gfx/thebes/gfxPlatform.cpp
+++ b/gfx/thebes/gfxPlatform.cpp
@@ -242,17 +242,18 @@ static const char *gPrefLangNames[] = {
     "x-knda",
     "x-sinh",
     "x-tibt",
     "x-unicode",
     "x-user-def"
 };
 
 gfxPlatform::gfxPlatform()
-  : mAzureCanvasBackendCollector(this, &gfxPlatform::GetAzureBackendInfo)
+  : mAzureCanvasBackendCollector(MOZ_THIS_IN_INITIALIZER_LIST(),
+                                 &gfxPlatform::GetAzureBackendInfo)
   , mDrawLayerBorders(false)
   , mDrawTileBorders(false)
   , mDrawBigImageBorders(false)
 {
     mUseHarfBuzzScripts = UNINITIALIZED_VALUE;
     mAllowDownloadableFonts = UNINITIALIZED_VALUE;
     mFallbackUsesCmaps = UNINITIALIZED_VALUE;
 
@@ -1999,9 +2000,9 @@ bool
 gfxPlatform::ComponentAlphaEnabled()
 {
 #ifdef MOZ_GFX_OPTIMIZE_MOBILE
   return false;
 #endif
 
   InitLayersAccelerationPrefs();
   return sComponentAlphaEnabled;
-}
\ No newline at end of file
+}
--- a/js/public/Value.h
+++ b/js/public/Value.h
@@ -901,27 +901,16 @@ class Value
      * N.B. the default constructor leaves Value unitialized. Adding a default
      * constructor prevents Value from being stored in a union.
      */
 #if defined(JS_VALUE_IS_CONSTEXPR)
     Value() = default;
     Value(const Value& v) = default;
 #endif
 
-    /*
-     * clang 4.1 doesn't corectly create a default assignment operator
-     * for this class, so we need to explicitly declare one.
-     */
-#if defined(__clang__) && (__clang_major__ == 4) && (__clang_minor__ <= 1)
-    Value &operator=(const Value &r) {
-        data = r.data;
-        return *this;
-    }
-#endif
-
     /*** Mutators ***/
 
     void setNull() {
         data.asBits = BUILD_JSVAL(JSVAL_TAG_NULL, 0).asBits;
     }
 
     void setUndefined() {
         data.asBits = BUILD_JSVAL(JSVAL_TAG_UNDEFINED, 0).asBits;
--- a/js/src/builtin/TestingFunctions.cpp
+++ b/js/src/builtin/TestingFunctions.cpp
@@ -888,16 +888,26 @@ static bool
 DisableSPSProfiling(JSContext *cx, unsigned argc, jsval *vp)
 {
     if (cx->runtime()->spsProfiler.installed())
         cx->runtime()->spsProfiler.enable(false);
     return true;
 }
 
 static bool
+EnableOsiPointRegisterChecks(JSContext *, unsigned, jsval *vp)
+{
+#ifdef CHECK_OSIPOINT_REGISTERS
+    ion::js_IonOptions.checkOsiPointRegisters = true;
+#endif
+    JS_SET_RVAL(cx, vp, JSVAL_VOID);
+    return true;
+}
+
+static bool
 DisplayName(JSContext *cx, unsigned argc, jsval *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     if (argc == 0 || !args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
         RootedObject arg(cx, &args.callee());
         ReportUsageError(cx, arg, "Must have one function argument");
         return false;
     }
@@ -1131,16 +1141,21 @@ static const JSFunctionSpecWithHelp Test
 "  true, then even slower assertions are enabled for all generated JIT code.\n"
 "  When 'slow' is false, then instrumentation is enabled, but the slow\n"
 "  assertions are disabled."),
 
     JS_FN_HELP("disableSPSProfiling", DisableSPSProfiling, 1, 0,
 "disableSPSProfiling()",
 "  Disables SPS instrumentation"),
 
+    JS_FN_HELP("enableOsiPointRegisterChecks", EnableOsiPointRegisterChecks, 0, 0,
+"enableOsiPointRegisterChecks()",
+"Emit extra code to verify live regs at the start of a VM call are not\n"
+"modified before its OsiPoint."),
+
     JS_FN_HELP("displayName", DisplayName, 1, 0,
 "displayName(fn)",
 "  Gets the display name for a function, which can possibly be a guessed or\n"
 "  inferred name based on where the function was defined. This can be\n"
 "  different from the 'name' property on the function."),
 
     JS_FN_HELP("isAsmJSCompilationAvailable", IsAsmJSCompilationAvailable, 0, 0,
 "isAsmJSCompilationAvailable",
--- a/js/src/jit-test/tests/basic/testStringToNumber.js
+++ b/js/src/jit-test/tests/basic/testStringToNumber.js
@@ -1,8 +1,10 @@
+enableOsiPointRegisterChecks();
+
 function convertToInt(str) {
     return str | 0;
 }
 
 function convertToIntOnTrace(str) {
     var z;
     for (var i = 0; i < 9; ++i) {
         z = str | 0;
--- a/js/src/jit-test/tests/ion/bug860838.js
+++ b/js/src/jit-test/tests/ion/bug860838.js
@@ -1,8 +1,10 @@
+enableOsiPointRegisterChecks();
+
 function DiagModule(stdlib, foreign) {
     "use asm";
 
     var sqrt = stdlib.Math.sqrt;
     var test = foreign.test;
 
     function square(x) {
         x = x|0;
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/ion/try-catch-6.js
@@ -0,0 +1,14 @@
+var o = {
+    valueOf: function() {}
+};
+var threw = false;
+function test(t) {
+    try {
+        for (x[t++] in o) {}
+    } catch (err) {
+	assertEq(t, 3.14);
+	threw = true;
+    }
+}
+test(3.14);
+assertEq(threw, true);
--- a/js/src/jit-test/tests/jaeger/bug832670.js
+++ b/js/src/jit-test/tests/jaeger/bug832670.js
@@ -1,8 +1,9 @@
+enableOsiPointRegisterChecks();
 
 gczeal(4);
 eval("(function() { " + "\
 for ( var CHARCODE = 1024; CHARCODE < 65536; CHARCODE+= 1234 ) {\
 	unescape( '%u'+(ToUnicodeString(CHARCODE)).substring(0,3) )\
 }\
 function ToUnicodeString( n ) {\
   var string = ToHexString(n);\
--- a/js/src/jit/CodeGenerator.cpp
+++ b/js/src/jit/CodeGenerator.cpp
@@ -813,16 +813,35 @@ CodeGenerator::visitOsiPoint(LOsiPoint *
 
     uint32_t osiCallPointOffset;
     if (!markOsiPoint(lir, &osiCallPointOffset))
         return false;
 
     LSafepoint *safepoint = lir->associatedSafepoint();
     JS_ASSERT(!safepoint->osiCallPointOffset());
     safepoint->setOsiCallPointOffset(osiCallPointOffset);
+
+#ifdef DEBUG
+    // There should be no movegroups or other instructions between
+    // an instruction and its OsiPoint. This is necessary because
+    // we use the OsiPoint's snapshot from within VM calls.
+    for (LInstructionReverseIterator iter(current->rbegin(lir)); iter != current->rend(); iter++) {
+        if (*iter == lir || iter->isNop())
+            continue;
+        JS_ASSERT(!iter->isMoveGroup());
+        JS_ASSERT(iter->safepoint() == safepoint);
+        break;
+    }
+#endif
+
+#ifdef CHECK_OSIPOINT_REGISTERS
+    if (shouldVerifyOsiPointRegs(safepoint))
+        verifyOsiPointRegs(safepoint);
+#endif
+
     return true;
 }
 
 bool
 CodeGenerator::visitGoto(LGoto *lir)
 {
     jumpToBlock(lir->target());
     return true;
@@ -2712,16 +2731,30 @@ CodeGenerator::generateBody()
             if (counts)
                 blockCounts.ref().visitInstruction(*iter);
 
             if (iter->safepoint() && pushedArgumentSlots_.length()) {
                 if (!markArgumentSlots(iter->safepoint()))
                     return false;
             }
 
+#ifdef CHECK_OSIPOINT_REGISTERS
+            if (iter->safepoint() && shouldVerifyOsiPointRegs(iter->safepoint())) {
+                // Set checkRegs to 0. If we perform a VM call, the instruction
+                // will set it to 1.
+                GeneralRegisterSet allRegs(GeneralRegisterSet::All());
+                Register scratch = allRegs.takeAny();
+                masm.push(scratch);
+                masm.loadJitActivation(scratch);
+                Address checkRegs(scratch, JitActivation::offsetOfCheckRegs());
+                masm.store32(Imm32(0), checkRegs);
+                masm.pop(scratch);
+            }
+#endif
+
             if (!callTraceLIR(i, *iter))
                 return false;
 
             if (!iter->accept(this))
                 return false;
         }
         if (masm.oom())
             return false;
--- a/js/src/jit/Ion.h
+++ b/js/src/jit/Ion.h
@@ -87,16 +87,24 @@ struct IonOptions
     // Default: true
     bool eaa;
 
     // Toggles whether compilation occurs off the main thread.
     //
     // Default: true iff there are at least two CPUs available
     bool parallelCompilation;
 
+#ifdef CHECK_OSIPOINT_REGISTERS
+    // Emit extra code to verify live regs at the start of a VM call
+    // are not modified before its OsiPoint.
+    //
+    // Default: false
+    bool checkOsiPointRegisters;
+#endif
+
     // How many invocations or loop iterations are needed before functions
     // are compiled with the baseline compiler.
     //
     // Default: 10
     uint32_t baselineUsesBeforeCompile;
 
     // How many invocations or loop iterations are needed before functions
     // are compiled.
@@ -202,16 +210,19 @@ struct IonOptions
         limitScriptSize(true),
         registerAllocator(RegisterAllocator_LSRA),
         inlining(true),
         edgeCaseAnalysis(true),
         rangeAnalysis(true),
         uce(true),
         eaa(true),
         parallelCompilation(false),
+#ifdef CHECK_OSIPOINT_REGISTERS
+        checkOsiPointRegisters(false),
+#endif
         baselineUsesBeforeCompile(10),
         usesBeforeCompile(1000),
         usesBeforeInliningFactor(.125),
         osrPcMismatchesBeforeRecompile(6000),
         frequentBailoutThreshold(10),
         exceptionBailoutThreshold(10),
         compileTryCatch(false),
         maxStackArgs(4096),
--- a/js/src/jit/IonFrames.cpp
+++ b/js/src/jit/IonFrames.cpp
@@ -286,24 +286,24 @@ IonFrameIterator::spillBase() const
 }
 
 MachineState
 IonFrameIterator::machineState() const
 {
     SafepointReader reader(ionScript(), safepoint());
     uintptr_t *spill = spillBase();
 
-    // see CodeGeneratorShared::saveLive, we are only copying GPRs for now, FPUs
-    // are stored after but are not saved in the safepoint.  This means that we
-    // are unable to restore any FPUs registers from an OOL VM call.  This can
-    // cause some trouble for f.arguments.
     MachineState machine;
-    for (GeneralRegisterBackwardIterator iter(reader.allSpills()); iter.more(); iter++)
+    for (GeneralRegisterBackwardIterator iter(reader.allGprSpills()); iter.more(); iter++)
         machine.setRegisterLocation(*iter, --spill);
 
+    double *floatSpill = reinterpret_cast<double *>(spill);
+    for (FloatRegisterBackwardIterator iter(reader.allFloatSpills()); iter.more(); iter++)
+        machine.setRegisterLocation(*iter, --floatSpill);
+
     return machine;
 }
 
 static void
 CloseLiveIterator(JSContext *cx, const InlineFrameIterator &frame, uint32_t localSlot)
 {
     SnapshotIterator si = frame.snapshotIterator();
 
@@ -774,17 +774,17 @@ MarkIonJSFrame(JSTracer *trc, const IonF
     while (safepoint.getValueSlot(&slot)) {
         Value *v = (Value *)layout->slotRef(slot);
         gc::MarkValueRoot(trc, v, "ion-gc-slot");
     }
 
     uintptr_t *spill = frame.spillBase();
     GeneralRegisterSet gcRegs = safepoint.gcSpills();
     GeneralRegisterSet valueRegs = safepoint.valueSpills();
-    for (GeneralRegisterBackwardIterator iter(safepoint.allSpills()); iter.more(); iter++) {
+    for (GeneralRegisterBackwardIterator iter(safepoint.allGprSpills()); iter.more(); iter++) {
         --spill;
         if (gcRegs.has(*iter))
             gc::MarkGCThingRoot(trc, reinterpret_cast<void **>(spill), "ion-gc-spill");
         else if (valueRegs.has(*iter))
             gc::MarkValueRoot(trc, reinterpret_cast<Value *>(spill), "ion-value-spill");
     }
 
 #ifdef JS_NUNBOX32
@@ -807,17 +807,17 @@ MarkIonJSFrame(JSTracer *trc, const IonF
 
 #ifdef JSGC_GENERATIONAL
     if (trc->runtime->isHeapMinorCollecting()) {
         // Minor GCs may move slots/elements allocated in the nursery. Update
         // any slots/elements pointers stored in this frame.
 
         GeneralRegisterSet slotsRegs = safepoint.slotsOrElementsSpills();
         spill = frame.spillBase();
-        for (GeneralRegisterBackwardIterator iter(safepoint.allSpills()); iter.more(); iter++) {
+        for (GeneralRegisterBackwardIterator iter(safepoint.allGprSpills()); iter.more(); iter++) {
             --spill;
             if (slotsRegs.has(*iter))
                 trc->runtime->gcNursery.forwardBufferPointer(reinterpret_cast<HeapSlot **>(spill));
         }
 
         while (safepoint.getSlotsOrElementsSlot(&slot)) {
             HeapSlot **slots = reinterpret_cast<HeapSlot **>(layout->slotRef(slot));
             trc->runtime->gcNursery.forwardBufferPointer(slots);
@@ -1016,16 +1016,26 @@ MarkIonExitFrame(JSTracer *trc, const Io
             break;
         }
     }
 }
 
 static void
 MarkJitActivation(JSTracer *trc, const JitActivationIterator &activations)
 {
+#ifdef CHECK_OSIPOINT_REGISTERS
+    if (js_IonOptions.checkOsiPointRegisters) {
+        // GC can modify spilled registers, breaking our register checks.
+        // To handle this, we disable these checks for the current VM call
+        // when a GC happens.
+        JitActivation *activation = activations.activation()->asJit();
+        activation->setCheckRegs(false);
+    }
+#endif
+
     for (IonFrameIterator frames(activations); !frames.done(); ++frames) {
         switch (frames.type()) {
           case IonFrame_Exit:
             MarkIonExitFrame(trc, frames);
             break;
           case IonFrame_BaselineJS:
             frames.baselineFrame()->trace(trc);
             break;
--- a/js/src/jit/IonTypes.h
+++ b/js/src/jit/IonTypes.h
@@ -199,14 +199,18 @@ static inline bool
 IsNullOrUndefined(MIRType type)
 {
     return type == MIRType_Null || type == MIRType_Undefined;
 }
 
 #ifdef DEBUG
 // Track the pipeline of opcodes which has produced a snapshot.
 #define TRACK_SNAPSHOTS 1
+
+// Make sure registers are not modified between an instruction and
+// its OsiPoint.
+#define CHECK_OSIPOINT_REGISTERS 1
 #endif
 
 } // namespace ion
 } // namespace js
 
 #endif /* jit_IonTypes_h */
--- a/js/src/jit/LIR.h
+++ b/js/src/jit/LIR.h
@@ -980,16 +980,22 @@ class LSafepoint : public TempObject
     // registers: if passed to the call, the values passed will be marked via
     // MarkIonExitFrame, and no registers can be live after the instruction
     // except its outputs.
     RegisterSet liveRegs_;
 
     // The subset of liveRegs which contains gcthing pointers.
     GeneralRegisterSet gcRegs_;
 
+#ifdef CHECK_OSIPOINT_REGISTERS
+    // Temp regs of the current instruction. This set is never written to the
+    // safepoint; it's only used by assertions during compilation.
+    RegisterSet tempRegs_;
+#endif
+
     // Offset to a position in the safepoint stream, or
     // INVALID_SAFEPOINT_OFFSET.
     uint32_t safepointOffset_;
 
     // Assembler buffer displacement to OSI point's call location.
     uint32_t osiCallPointOffset_;
 
     // List of stack slots which have gcthing pointers.
@@ -1024,16 +1030,24 @@ class LSafepoint : public TempObject
 #endif
     { }
     void addLiveRegister(AnyRegister reg) {
         liveRegs_.addUnchecked(reg);
     }
     const RegisterSet &liveRegs() const {
         return liveRegs_;
     }
+#ifdef CHECK_OSIPOINT_REGISTERS
+    void addTempRegister(AnyRegister reg) {
+        tempRegs_.addUnchecked(reg);
+    }
+    const RegisterSet &tempRegs() const {
+        return tempRegs_;
+    }
+#endif
     void addGcRegister(Register reg) {
         gcRegs_.addUnchecked(reg);
     }
     GeneralRegisterSet gcRegs() const {
         return gcRegs_;
     }
     bool addGcSlot(uint32_t slot) {
         return gcSlots_.append(slot);
--- a/js/src/jit/LinearScan.cpp
+++ b/js/src/jit/LinearScan.cpp
@@ -304,16 +304,35 @@ bool
 LinearScanAllocator::moveInputAlloc(CodePosition pos, LAllocation *from, LAllocation *to)
 {
     if (*from == *to)
         return true;
     LMoveGroup *moves = getInputMoveGroup(pos);
     return moves->add(from, to);
 }
 
+static inline void
+SetOsiPointUses(LiveInterval *interval, CodePosition defEnd, const LAllocation &allocation)
+{
+    // Moves are inserted after OsiPoint instructions. This function sets
+    // any OsiPoint uses of this interval to the allocation of the value
+    // before the move.
+
+    JS_ASSERT(interval->index() == 0);
+
+    for (UsePositionIterator usePos(interval->usesBegin());
+         usePos != interval->usesEnd();
+         usePos++)
+    {
+        if (usePos->pos > defEnd)
+            break;
+        *static_cast<LAllocation *>(usePos->use) = allocation;
+    }
+}
+
 /*
  * This function takes the allocations assigned to the live intervals and
  * erases all virtual registers in the function with the allocations
  * corresponding to the appropriate interval.
  */
 bool
 LinearScanAllocator::reifyAllocations()
 {
@@ -344,34 +363,27 @@ LinearScanAllocator::reifyAllocations()
         }
 
         // Erase the def of this interval if it's the first one
         if (interval->index() == 0)
         {
             LDefinition *def = reg->def();
             LAllocation *spillFrom;
 
+            // Insert the moves after any OsiPoint or Nop instructions
+            // following this one. See minimalDefEnd for more info.
+            CodePosition defEnd = minimalDefEnd(reg->ins());
+
             if (def->policy() == LDefinition::PRESET && def->output()->isRegister()) {
                 AnyRegister fixedReg = def->output()->toRegister();
                 LiveInterval *from = fixedIntervals[fixedReg.code()];
 
-                // Insert the move after any OsiPoint or Nop instructions
-                // following this one. See minimalDefEnd for more info.
-                CodePosition defEnd = minimalDefEnd(reg->ins());
-
-                // If we just skipped an OsiPoint, and it uses this vreg, it
-                // should use the fixed register instead.
-                for (UsePositionIterator usePos(interval->usesBegin());
-                     usePos != interval->usesEnd();
-                     usePos++)
-                {
-                    if (usePos->pos > defEnd)
-                        break;
-                    *static_cast<LAllocation *>(usePos->use) = LAllocation(fixedReg);
-                }
+                // If we insert the move after an OsiPoint that uses this vreg,
+                // it should use the fixed register instead.
+                SetOsiPointUses(interval, defEnd, LAllocation(fixedReg));
 
                 if (!moveAfter(defEnd, from, interval))
                     return false;
                 spillFrom = from->getAllocation();
             } else {
                 if (def->policy() == LDefinition::MUST_REUSE_INPUT) {
                     LAllocation *alloc = reg->ins()->getOperand(def->getReusedInput());
                     LAllocation *origAlloc = LAllocation::New(*alloc);
@@ -396,21 +408,24 @@ LinearScanAllocator::reifyAllocations()
                     if (entry->isUse() && entry->toUse()->policy() == LUse::RECOVERED_INPUT)
                         *entry = *def->output();
                 }
             }
 
             if (reg->mustSpillAtDefinition() && !reg->ins()->isPhi() &&
                 (*reg->canonicalSpill() != *spillFrom))
             {
-                // Insert a spill at the input of the next instruction. Control
-                // instructions never have outputs, so the next instruction is
-                // always valid. Note that we explicitly ignore phis, which
-                // should have been handled in resolveControlFlow().
-                LMoveGroup *moves = getMoveGroupAfter(outputOf(reg->ins()));
+                // If we move the spill after an OsiPoint, the OsiPoint should
+                // use the original location instead.
+                SetOsiPointUses(interval, defEnd, *spillFrom);
+
+                // Insert a spill after this instruction (or after any OsiPoint
+                // or Nop instructions). Note that we explicitly ignore phis,
+                // which should have been handled in resolveControlFlow().
+                LMoveGroup *moves = getMoveGroupAfter(defEnd);
                 if (!moves->add(spillFrom, reg->canonicalSpill()))
                     return false;
             }
         }
         else if (interval->start() > inputOf(insData[interval->start()].block()->firstId()) &&
                  (!reg->canonicalSpill() ||
                   (reg->canonicalSpill() == interval->getAllocation() &&
                    !reg->mustSpillAtDefinition()) ||
--- a/js/src/jit/LiveRangeAllocator.h
+++ b/js/src/jit/LiveRangeAllocator.h
@@ -620,16 +620,21 @@ class LiveRangeAllocator : public Regist
             if (interval->end() < pos)
                 break;
 
             if (!interval->covers(pos))
                 continue;
 
             LSafepoint *safepoint = ins->safepoint();
             safepoint->addLiveRegister(a->toRegister());
+
+#ifdef CHECK_OSIPOINT_REGISTERS
+            if (reg->isTemp())
+                safepoint->addTempRegister(a->toRegister());
+#endif
         }
     }
 
     // Finds the first safepoint that is within range of an interval.
     size_t findFirstSafepoint(const LiveInterval *interval, size_t startFrom) const
     {
         size_t i = startFrom;
         for (; i < graph.numSafepoints(); i++) {
--- a/js/src/jit/RegisterAllocator.h
+++ b/js/src/jit/RegisterAllocator.h
@@ -352,18 +352,17 @@ class RegisterAllocator
         }
         return i;
     }
 
     CodePosition minimalDefEnd(LInstruction *ins) {
         // Compute the shortest interval that captures vregs defined by ins.
         // Watch for instructions that are followed by an OSI point and/or Nop.
         // If moves are introduced between the instruction and the OSI point then
-        // safepoint information for the instruction may be incorrect. This is
-        // pretty disgusting and should be fixed somewhere else in the compiler.
+        // safepoint information for the instruction may be incorrect.
         while (true) {
             LInstruction *next = insData[outputOf(ins).next()].ins();
             if (!next->isNop() && !next->isOsiPoint())
                 break;
             ins = next;
         }
 
         return outputOf(ins);
--- a/js/src/jit/Registers.h
+++ b/js/src/jit/Registers.h
@@ -80,16 +80,31 @@ struct FloatRegister {
     bool operator !=(const FloatRegister &other) const {
         return code_ != other.code_;
     }
     bool volatile_() const {
         return !!((1 << code()) & FloatRegisters::VolatileMask);
     }
 };
 
+class RegisterDump
+{
+  protected: // Silence Clang warning.
+    uintptr_t regs_[Registers::Total];
+    double fpregs_[FloatRegisters::Total];
+
+  public:
+    static size_t offsetOfRegister(Register reg) {
+        return offsetof(RegisterDump, regs_) + reg.code() * sizeof(uintptr_t);
+    }
+    static size_t offsetOfRegister(FloatRegister reg) {
+        return offsetof(RegisterDump, fpregs_) + reg.code() * sizeof(double);
+    }
+};
+
 // Information needed to recover machine register state.
 class MachineState
 {
     mozilla::Array<uintptr_t *, Registers::Total> regs_;
     mozilla::Array<double *, FloatRegisters::Total> fpregs_;
 
   public:
     static MachineState FromBailout(uintptr_t regs[Registers::Total],
--- a/js/src/jit/Safepoints.cpp
+++ b/js/src/jit/Safepoints.cpp
@@ -47,47 +47,52 @@ WriteRegisterMask(CompactBufferWriter &s
     else
         stream.writeUnsigned(bits);
 }
 
 void
 SafepointWriter::writeGcRegs(LSafepoint *safepoint)
 {
     GeneralRegisterSet gc = safepoint->gcRegs();
-    GeneralRegisterSet spilled = safepoint->liveRegs().gprs();
+    GeneralRegisterSet spilledGpr = safepoint->liveRegs().gprs();
+    FloatRegisterSet spilledFloat = safepoint->liveRegs().fpus();
     GeneralRegisterSet slots = safepoint->slotsOrElementsRegs();
     GeneralRegisterSet valueRegs;
 
-    WriteRegisterMask(stream_, spilled.bits());
-    if (!spilled.empty()) {
+    WriteRegisterMask(stream_, spilledGpr.bits());
+    if (!spilledGpr.empty()) {
         WriteRegisterMask(stream_, gc.bits());
         WriteRegisterMask(stream_, slots.bits());
 
 #ifdef JS_PUNBOX64
         valueRegs = safepoint->valueRegs();
         WriteRegisterMask(stream_, valueRegs.bits());
 #endif
     }
 
     // GC registers are a subset of the spilled registers.
-    JS_ASSERT((valueRegs.bits() & ~spilled.bits()) == 0);
-    JS_ASSERT((gc.bits() & ~spilled.bits()) == 0);
+    JS_ASSERT((valueRegs.bits() & ~spilledGpr.bits()) == 0);
+    JS_ASSERT((gc.bits() & ~spilledGpr.bits()) == 0);
+
+    WriteRegisterMask(stream_, spilledFloat.bits());
 
 #ifdef DEBUG
     if (IonSpewEnabled(IonSpew_Safepoints)) {
-        for (GeneralRegisterForwardIterator iter(spilled); iter.more(); iter++) {
+        for (GeneralRegisterForwardIterator iter(spilledGpr); iter.more(); iter++) {
             const char *type = gc.has(*iter)
                                ? "gc"
                                : slots.has(*iter)
                                  ? "slots"
                                  : valueRegs.has(*iter)
                                    ? "value"
                                    : "any";
             IonSpew(IonSpew_Safepoints, "    %s reg: %s", type, (*iter).name());
         }
+        for (FloatRegisterForwardIterator iter(spilledFloat); iter.more(); iter++)
+            IonSpew(IonSpew_Safepoints, "    float reg: %s", (*iter).name());
     }
 #endif
 }
 
 static void
 MapSlotsToBitset(BitSet *set, CompactBufferWriter &stream, uint32_t nslots, uint32_t *slots)
 {
     set->clear();
@@ -327,30 +332,32 @@ SafepointWriter::endEntry()
 
 SafepointReader::SafepointReader(IonScript *script, const SafepointIndex *si)
   : stream_(script->safepoints() + si->safepointOffset(),
             script->safepoints() + script->safepointsSize()),
     frameSlots_(script->frameSlots())
 {
     osiCallPointOffset_ = stream_.readUnsigned();
 
-    // gcSpills is a subset of allSpills.
-    allSpills_ = GeneralRegisterSet(stream_.readUnsigned());
-    if (allSpills_.empty()) {
-        gcSpills_ = allSpills_;
-        valueSpills_ = allSpills_;
-        slotsOrElementsSpills_ = allSpills_;
+    // gcSpills is a subset of allGprSpills.
+    allGprSpills_ = GeneralRegisterSet(stream_.readUnsigned());
+    if (allGprSpills_.empty()) {
+        gcSpills_ = allGprSpills_;
+        valueSpills_ = allGprSpills_;
+        slotsOrElementsSpills_ = allGprSpills_;
     } else {
         gcSpills_ = GeneralRegisterSet(stream_.readUnsigned());
         slotsOrElementsSpills_ = GeneralRegisterSet(stream_.readUnsigned());
 #ifdef JS_PUNBOX64
         valueSpills_ = GeneralRegisterSet(stream_.readUnsigned());
 #endif
     }
 
+    allFloatSpills_ = FloatRegisterSet(stream_.readUnsigned());
+
     advanceFromGcRegs();
 }
 
 uint32_t
 SafepointReader::osiReturnPointOffset() const
 {
     return osiCallPointOffset_ + Assembler::patchWrite_NearCallSize();
 }
--- a/js/src/jit/Safepoints.h
+++ b/js/src/jit/Safepoints.h
@@ -62,17 +62,18 @@ class SafepointReader
     CompactBufferReader stream_;
     uint32_t frameSlots_;
     uint32_t currentSlotChunk_;
     uint32_t currentSlotChunkNumber_;
     uint32_t osiCallPointOffset_;
     GeneralRegisterSet gcSpills_;
     GeneralRegisterSet valueSpills_;
     GeneralRegisterSet slotsOrElementsSpills_;
-    GeneralRegisterSet allSpills_;
+    GeneralRegisterSet allGprSpills_;
+    FloatRegisterSet allFloatSpills_;
     uint32_t nunboxSlotsRemaining_;
     uint32_t slotsOrElementsSlotsRemaining_;
 
   private:
     void advanceFromGcRegs();
     void advanceFromGcSlots();
     void advanceFromValueSlots();
     void advanceFromNunboxSlots();
@@ -90,18 +91,21 @@ class SafepointReader
         return gcSpills_;
     }
     GeneralRegisterSet slotsOrElementsSpills() const {
         return slotsOrElementsSpills_;
     }
     GeneralRegisterSet valueSpills() const {
         return valueSpills_;
     }
-    GeneralRegisterSet allSpills() const {
-        return allSpills_;
+    GeneralRegisterSet allGprSpills() const {
+        return allGprSpills_;
+    }
+    FloatRegisterSet allFloatSpills() const {
+        return allFloatSpills_;
     }
     uint32_t osiReturnPointOffset() const;
 
     // Returns true if a slot was read, false if there are no more slots.
     bool getGcSlot(uint32_t *slot);
 
     // Returns true if a slot was read, false if there are no more value slots.
     bool getValueSlot(uint32_t *slot);
--- a/js/src/jit/shared/CodeGenerator-shared.cpp
+++ b/js/src/jit/shared/CodeGenerator-shared.cpp
@@ -417,16 +417,169 @@ CodeGeneratorShared::markOsiPoint(LOsiPo
 
     ensureOsiSpace();
 
     *callPointOffset = masm.currentOffset();
     SnapshotOffset so = ins->snapshot()->snapshotOffset();
     return osiIndices_.append(OsiIndex(*callPointOffset, so));
 }
 
+#ifdef CHECK_OSIPOINT_REGISTERS
+template <class Op>
+static void
+HandleRegisterDump(Op op, MacroAssembler &masm, RegisterSet liveRegs, Register activation,
+                   Register scratch)
+{
+    const size_t baseOffset = JitActivation::offsetOfRegs();
+
+    // Handle live GPRs.
+    for (GeneralRegisterIterator iter(liveRegs.gprs()); iter.more(); iter++) {
+        Register reg = *iter;
+        Address dump(activation, baseOffset + RegisterDump::offsetOfRegister(reg));
+
+        if (reg == activation) {
+            // To use the original value of the activation register (that's
+            // now on top of the stack), we need the scratch register.
+            masm.push(scratch);
+            masm.loadPtr(Address(StackPointer, sizeof(uintptr_t)), scratch);
+            op(scratch, dump);
+            masm.pop(scratch);
+        } else {
+            op(reg, dump);
+        }
+    }
+
+    // Handle live FPRs.
+    for (FloatRegisterIterator iter(liveRegs.fpus()); iter.more(); iter++) {
+        FloatRegister reg = *iter;
+        Address dump(activation, baseOffset + RegisterDump::offsetOfRegister(reg));
+        op(reg, dump);
+    }
+}
+
+class StoreOp
+{
+    MacroAssembler &masm;
+
+  public:
+    StoreOp(MacroAssembler &masm)
+      : masm(masm)
+    {}
+
+    void operator()(Register reg, Address dump) {
+        masm.storePtr(reg, dump);
+    }
+    void operator()(FloatRegister reg, Address dump) {
+        masm.storeDouble(reg, dump);
+    }
+};
+
+static void
+StoreAllLiveRegs(MacroAssembler &masm, RegisterSet liveRegs)
+{
+    // Store a copy of all live registers before performing the call.
+    // When we reach the OsiPoint, we can use this to check nothing
+    // modified them in the meantime.
+
+    // Load pointer to the JitActivation in a scratch register.
+    GeneralRegisterSet allRegs(GeneralRegisterSet::All());
+    Register scratch = allRegs.takeAny();
+    masm.push(scratch);
+    masm.loadJitActivation(scratch);
+
+    Address checkRegs(scratch, JitActivation::offsetOfCheckRegs());
+    masm.store32(Imm32(1), checkRegs);
+
+    StoreOp op(masm);
+    HandleRegisterDump<StoreOp>(op, masm, liveRegs, scratch, allRegs.getAny());
+
+    masm.pop(scratch);
+}
+
+class VerifyOp
+{
+    MacroAssembler &masm;
+    Label *failure_;
+
+  public:
+    VerifyOp(MacroAssembler &masm, Label *failure)
+      : masm(masm), failure_(failure)
+    {}
+
+    void operator()(Register reg, Address dump) {
+        masm.branchPtr(Assembler::NotEqual, dump, reg, failure_);
+    }
+    void operator()(FloatRegister reg, Address dump) {
+        masm.loadDouble(dump, ScratchFloatReg);
+        masm.branchDouble(Assembler::DoubleNotEqual, ScratchFloatReg, reg, failure_);
+    }
+};
+
+static void
+OsiPointRegisterCheckFailed()
+{
+    // Any live register captured by a safepoint (other than temp registers)
+    // must remain unchanged between the call and the OsiPoint instruction.
+    MOZ_ASSUME_UNREACHABLE("Modified registers between VM call and OsiPoint");
+}
+
+void
+CodeGeneratorShared::verifyOsiPointRegs(LSafepoint *safepoint)
+{
+    // Ensure the live registers stored by callVM did not change between
+    // the call and this OsiPoint. Try-catch relies on this invariant.
+
+    // Load pointer to the JitActivation in a scratch register.
+    GeneralRegisterSet allRegs(GeneralRegisterSet::All());
+    Register scratch = allRegs.takeAny();
+    masm.push(scratch);
+    masm.loadJitActivation(scratch);
+
+    // If we should not check registers (because the instruction did not call
+    // into the VM, or a GC happened), we're done.
+    Label failure, done;
+    Address checkRegs(scratch, JitActivation::offsetOfCheckRegs());
+    masm.branch32(Assembler::Equal, checkRegs, Imm32(0), &done);
+
+    // Ignore temp registers. Some instructions (like LValueToInt32) modify
+    // temps after calling into the VM. This is fine because no other
+    // instructions (including this OsiPoint) will depend on them.
+    RegisterSet liveRegs = safepoint->liveRegs();
+    liveRegs = RegisterSet::Intersect(liveRegs, RegisterSet::Not(safepoint->tempRegs()));
+
+    VerifyOp op(masm, &failure);
+    HandleRegisterDump<VerifyOp>(op, masm, liveRegs, scratch, allRegs.getAny());
+
+    masm.jump(&done);
+
+    masm.bind(&failure);
+    masm.setupUnalignedABICall(0, scratch);
+    masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, OsiPointRegisterCheckFailed));
+    masm.breakpoint();
+
+    masm.bind(&done);
+    masm.pop(scratch);
+}
+
+bool
+CodeGeneratorShared::shouldVerifyOsiPointRegs(LSafepoint *safepoint)
+{
+    if (!js_IonOptions.checkOsiPointRegisters)
+        return false;
+
+    if (gen->info().executionMode() != SequentialExecution)
+        return false;
+
+    if (safepoint->liveRegs().empty(true) && safepoint->liveRegs().empty(false))
+        return false; // No registers to check.
+
+    return true;
+}
+#endif
+
 // Before doing any call to Cpp, you should ensure that volatile
 // registers are evicted by the register allocator.
 bool
 CodeGeneratorShared::callVM(const VMFunction &fun, LInstruction *ins, const Register *dynStack)
 {
     // Different execution modes have different sets of VM functions.
     JS_ASSERT(fun.executionMode == gen->info().executionMode());
 
@@ -450,16 +603,21 @@ CodeGeneratorShared::callVM(const VMFunc
     pushedArgs_ = 0;
 #endif
 
     // Get the wrapper of the VM function.
     IonCode *wrapper = gen->ionRuntime()->getVMWrapper(fun);
     if (!wrapper)
         return false;
 
+#ifdef CHECK_OSIPOINT_REGISTERS
+    if (shouldVerifyOsiPointRegs(ins->safepoint()))
+        StoreAllLiveRegs(masm, ins->safepoint()->liveRegs());
+#endif
+
     // Call the wrapper function.  The wrapper is in charge to unwind the stack
     // when returning from the call.  Failures are handled with exceptions based
     // on the return value of the C functions.  To guard the outcome of the
     // returned value, use another LIR instruction.
     uint32_t callOffset;
     if (dynStack)
         callOffset = masm.callWithExitFrame(wrapper, *dynStack);
     else
--- a/js/src/jit/shared/CodeGenerator-shared.h
+++ b/js/src/jit/shared/CodeGenerator-shared.h
@@ -195,16 +195,21 @@ class CodeGeneratorShared : public LInst
     // class.
     size_t allocateCache(const IonCache &, size_t size) {
         size_t dataOffset = allocateData(size);
         size_t index = cacheList_.length();
         masm.propagateOOM(cacheList_.append(dataOffset));
         return index;
     }
 
+#ifdef CHECK_OSIPOINT_REGISTERS
+    bool shouldVerifyOsiPointRegs(LSafepoint *safepoint);
+    void verifyOsiPointRegs(LSafepoint *safepoint);
+#endif
+
   public:
     // This is needed by addCache to update the cache with the jump
     // informations provided by the out-of-line path.
     IonCache *getCache(size_t index) {
         return reinterpret_cast<IonCache *>(&runtimeData_[cacheList_[index]]);
     }
 
   protected:
--- a/js/src/vm/Stack.h
+++ b/js/src/vm/Stack.h
@@ -1286,16 +1286,24 @@ namespace ion {
 // A JitActivation is used for frames running in Baseline or Ion.
 class JitActivation : public Activation
 {
     uint8_t *prevIonTop_;
     JSContext *prevIonJSContext_;
     bool firstFrameIsConstructing_;
     bool active_;
 
+#ifdef CHECK_OSIPOINT_REGISTERS
+  protected:
+    // Used to verify that live registers don't change between a VM call and
+    // the OsiPoint that follows it. Protected to silence Clang warning.
+    uint32_t checkRegs_;
+    RegisterDump regs_;
+#endif
+
   public:
     JitActivation(JSContext *cx, bool firstFrameIsConstructing, bool active = true);
     ~JitActivation();
 
     bool isActive() const {
         return active_;
     }
     void setActive(JSContext *cx, bool active = true);
@@ -1304,16 +1312,28 @@ class JitActivation : public Activation
         return prevIonTop_;
     }
     JSCompartment *compartment() const {
         return compartment_;
     }
     bool firstFrameIsConstructing() const {
         return firstFrameIsConstructing_;
     }
+
+#ifdef CHECK_OSIPOINT_REGISTERS
+    void setCheckRegs(bool check) {
+        checkRegs_ = check;
+    }
+    static size_t offsetOfCheckRegs() {
+        return offsetof(JitActivation, checkRegs_);
+    }
+    static size_t offsetOfRegs() {
+        return offsetof(JitActivation, regs_);
+    }
+#endif
 };
 
 // A filtering of the ActivationIterator to only stop at JitActivations.
 class JitActivationIterator : public ActivationIterator
 {
     void settle() {
         while (!done() && !activation_->isJit())
             ActivationIterator::operator++();
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -6175,17 +6175,19 @@ PresShell::HandleEvent(nsIFrame        *
 
     // Get the frame at the event point. However, don't do this if we're
     // capturing and retargeting the event because the captured frame will
     // be used instead below. Also keep using the root frame if we're dealing
     // with a window-level mouse exit event since we want to start sending
     // mouse out events at the root EventStateManager.
     if (!captureRetarget && !isWindowLevelMouseExit) {
       nsPoint eventPoint;
+      uint32_t flags;
       if (aEvent->message == NS_TOUCH_START) {
+        flags |= INPUT_IGNORE_ROOT_SCROLL_FRAME;
         nsTouchEvent* touchEvent = static_cast<nsTouchEvent*>(aEvent);
         // if this is a continuing session, ensure that all these events are
         // in the same document by taking the target of the events already in
         // the capture list
         nsCOMPtr<nsIContent> anyTarget;
         if (gCaptureTouchList.Count() > 0) {
           gCaptureTouchList.Enumerate(&FindAnyTarget, &anyTarget);
         } else {
@@ -6194,17 +6196,16 @@ PresShell::HandleEvent(nsIFrame        *
 
         for (int32_t i = touchEvent->touches.Length(); i; ) {
           --i;
           dom::Touch* touch = touchEvent->touches[i];
 
           int32_t id = touch->Identifier();
           if (!gCaptureTouchList.Get(id, nullptr)) {
             // find the target for this touch
-            uint32_t flags = 0;
             eventPoint = nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent,
                                                               touch->mRefPoint,
                                                               frame);
             nsIFrame* target = FindFrameTargetedByInputEvent(aEvent,
                                                              frame,
                                                              eventPoint,
                                                              flags);
             if (target && !anyTarget) {
@@ -6256,17 +6257,16 @@ PresShell::HandleEvent(nsIFrame        *
             if (oldTouch) {
               touch->SetTarget(oldTouch->mTarget);
             }
           }
         }
       } else {
         eventPoint = nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent, frame);
       }
-      uint32_t flags = 0;
       if (aEvent->eventStructType == NS_MOUSE_EVENT &&
           static_cast<nsMouseEvent*>(aEvent)->ignoreRootScrollFrame) {
         flags |= INPUT_IGNORE_ROOT_SCROLL_FRAME;
       }
       nsIFrame* target =
         FindFrameTargetedByInputEvent(aEvent, frame, eventPoint, flags);
       if (target) {
         frame = target;
--- a/layout/build/nsLayoutStatics.cpp
+++ b/layout/build/nsLayoutStatics.cpp
@@ -114,18 +114,16 @@ using namespace mozilla::system;
 #include "nsPermissionManager.h"
 #include "nsCookieService.h"
 #include "nsApplicationCacheService.h"
 #include "mozilla/dom/time/DateCacheCleaner.h"
 #include "nsIMEStateManager.h"
 #include "nsDocument.h"
 #include "mozilla/dom/HTMLVideoElement.h"
 
-extern void NS_ShutdownEventTargetChainItemRecyclePool();
-
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::dom::ipc;
 using namespace mozilla::dom::time;
 
 nsrefcnt nsLayoutStatics::sLayoutStaticRefcnt = 0;
 
 nsresult
@@ -373,18 +371,16 @@ nsLayoutStatics::Shutdown()
   nsIPresShell::ReleaseStatics();
 
   nsTreeSanitizer::ReleaseStatics();
 
   nsHtml5Module::ReleaseStatics();
 
   nsRegion::ShutdownStatic();
 
-  NS_ShutdownEventTargetChainItemRecyclePool();
-
   HTMLInputElement::DestroyUploadLastDir();
 
   nsLayoutUtils::Shutdown();
 
   nsHyphenationManager::Shutdown();
   nsDOMMutationObserver::Shutdown();
 
   AudioChannelService::Shutdown();
--- a/mobile/android/base/tests/testDoorHanger.java.in
+++ b/mobile/android/base/tests/testDoorHanger.java.in
@@ -1,11 +1,21 @@
 #filter substitution
 package @ANDROID_PACKAGE_NAME@.tests;
 
+import @ANDROID_PACKAGE_NAME@.*;
+
+import android.app.Activity;
+import android.content.SharedPreferences;
+import java.lang.reflect.Method;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
 /* This test will test if doorhangers are displayed and dismissed
    The test will test:
    * geolocation doorhangers - sharing and not sharing the location dismisses the doorhanger
    * opening a new tab hides the doorhanger
    * offline storage permission doorhangers - allowing and not allowing offline storage dismisses the doorhanger
    * Password Manager doorhangers - Remember and Not Now options dismiss the doorhanger
 */
 public class testDoorHanger extends BaseTest {
@@ -60,16 +70,55 @@ public class testDoorHanger extends Base
         waitForText(GEO_MESSAGE);
 
         // Add a new tab
         addTab(BLANK_URL);
 
         // Make sure doorhanger is hidden
         mAsserter.is(mSolo.searchText(GEO_MESSAGE), false, "Geolocation doorhanger notification is hidden when opening a new tab");
 
+
+        boolean offlineAllowedByDefault = true;
+        try {
+            // Save offline-allow-by-default preferences first
+            JSONArray getPrefData = new JSONArray();
+            getPrefData.put("offline-apps.allow_by_default");
+            JSONObject message = new JSONObject();
+            message.put("requestId", "testDoorHanger");
+            message.put("preferences", getPrefData);
+
+            Actions.RepeatedEventExpecter eventExpecter = mActions.expectGeckoEvent("Preferences:Data");
+            mActions.sendGeckoEvent("Preferences:Get", message.toString());
+
+            JSONObject data = null;
+            String requestId = "";
+
+            // Wait until we get the correct "Preferences:Data" event
+            while (!requestId.equals("testDoorHanger")) {
+                data = new JSONObject(eventExpecter.blockForEventData());
+                requestId = data.getString("requestId");
+            }
+            eventExpecter.unregisterListener();
+
+            JSONArray preferences = data.getJSONArray("preferences");
+            if (preferences.length() > 0) {
+                JSONObject pref = (JSONObject) preferences.get(0);
+                offlineAllowedByDefault = pref.getBoolean("value");
+            }
+
+            // Turn off offline-allow-by-default
+            JSONObject jsonPref = new JSONObject();
+            jsonPref.put("name", "offline-apps.allow_by_default");
+            jsonPref.put("type", "bool");
+            jsonPref.put("value", false);
+            mActions.sendGeckoEvent("Preferences:Set", jsonPref.toString());
+        } catch (JSONException e) {
+            mAsserter.ok(false, "exception getting preference", e.toString());
+        }
+
         // Load offline storage page
         loadUrl(OFFLINE_STORAGE_URL);
         waitForText(OFFLINE_MESSAGE);
 
         // Test doorhanger dismissed when tapping "Don't share"
         mSolo.clickOnCheckBox(0);
         mSolo.clickOnButton(OFFLINE_DENY);
         mAsserter.is(mSolo.searchText(OFFLINE_MESSAGE), false, "Offline storage doorhanger notification is hidden when denying storage");
@@ -79,16 +128,28 @@ public class testDoorHanger extends Base
         waitForText(OFFLINE_MESSAGE);
 
         // Test doorhanger dismissed when tapping "Allow" and is not displayed again
         mSolo.clickOnButton(OFFLINE_ALLOW);
         mAsserter.is(mSolo.searchText(OFFLINE_MESSAGE), false, "Offline storage doorhanger notification is hidden when allowing storage");
         loadUrl(OFFLINE_STORAGE_URL);
         mAsserter.is(mSolo.searchText(OFFLINE_MESSAGE), false, "Offline storage doorhanger is no longer triggered");
 
+        try {
+            // Revert offline setting
+            JSONObject jsonPref = new JSONObject();
+            jsonPref.put("name", "offline-apps.allow_by_default");
+            jsonPref.put("type", "boolean");
+            jsonPref.put("value", offlineAllowedByDefault);
+            mActions.sendGeckoEvent("Preferences:Set", jsonPref.toString());
+        } catch (JSONException e) {
+            mAsserter.ok(false, "exception setting preference", e.toString());
+        }
+
+
         // Load login page
         loadUrl(LOGIN_URL);
         waitForText(LOGIN_MESSAGE);
 
         // Test doorhanger is dismissed when tapping "Don't save"
         mSolo.clickOnButton(LOGIN_DENY);
         mAsserter.is(mSolo.searchText(LOGIN_MESSAGE), false, "Login doorhanger notification is hidden when denying saving password");
 
--- a/modules/libpref/src/init/all.js
+++ b/modules/libpref/src/init/all.js
@@ -56,16 +56,18 @@ pref("browser.cache.memory.enable",     
 // Max-size (in KB) for entries in memory cache. Set to -1 for no limit.  
 // (Note: entries bigger than than 90% of the mem-cache are never cached)
 pref("browser.cache.memory.max_entry_size",  5120);
 pref("browser.cache.disk_cache_ssl",        true);
 // 0 = once-per-session, 1 = each-time, 2 = never, 3 = when-appropriate/automatically
 pref("browser.cache.check_doc_frequency",   3);
 
 pref("browser.cache.offline.enable",           true);
+// enable offline apps by default, disable prompt
+pref("offline-apps.allow_by_default",          true);
 
 // offline cache capacity in kilobytes
 pref("browser.cache.offline.capacity",         512000);
 
 // the user should be warned if offline app disk usage exceeds this amount
 // (in kilobytes)
 pref("offline-apps.quota.warn",        51200);
 
--- a/toolkit/content/license.html
+++ b/toolkit/content/license.html
@@ -7,60 +7,63 @@
   <head>
     <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
     <title>about:license</title>
 
     <style type="text/css">
       .path {
         font-family: monospace;
       }
-      
+
       dt {
         font-weight: bold;
-      }      
+      }
     </style>
     <link rel="stylesheet" href="chrome://global/skin/about.css" type="text/css">
   </head>
 
   <body id="lic-info" class="aboutPageWideContainer">
     <h1><a id="top"></a>about:license</h1>
 
     <div>
 
 #ifdef APP_LICENSE_BLOCK
 #includesubst @APP_LICENSE_BLOCK@
 #endif
-    
-    <p>All of the <b>source code</b> to this product is 
-       available under licenses which are both 
-       <a href="http://www.gnu.org/philosophy/free-sw.html">free</a> and 
+
+    <p>All of the <b>source code</b> to this product is
+       available under licenses which are both
+       <a href="http://www.gnu.org/philosophy/free-sw.html">free</a> and
        <a href="http://www.opensource.org/docs/definition.php">open source</a>.
        A URL identifying the specific source code used to create this copy can be found
-       on the <a href="about:buildconfig">build configuration page</a>, and you can read 
-       <a href="https://developer.mozilla.org/en/Mozilla_Source_Code_%28Mercurial%29">instructions 
+       on the <a href="about:buildconfig">build configuration page</a>, and you can read
+       <a href="https://developer.mozilla.org/en/Mozilla_Source_Code_%28Mercurial%29">instructions
        on how to download and build the code for yourself</a>.
     </p>
 
-    <p>More specifically, most of the source code is available under the 
+    <p>More specifically, most of the source code is available under the
        <a href="about:license#mpl">Mozilla Public License 2.0</a> (MPL).
-       The MPL has a 
+       The MPL has a
        <a href="http://www.mozilla.org/MPL/2.0/FAQ.html">FAQ</a> to help
-       you understand it. The remainder of the software which is not 
-       under the MPL is available under one of a variety of other 
-       permissive licenses. Those that require reproduction 
-       of the license text in the distribution are given below. 
-       (Note: your copy of this product may not contain code covered by one 
-       or more of the licenses listed here, depending on the exact product 
+       you understand it. The remainder of the software which is not
+       under the MPL is available under one of a variety of other
+       free and open source licenses. Those that require reproduction
+       of the license text in the distribution are given below.
+       (Note: your copy of this product may not contain code covered by one
+       or more of the licenses listed here, depending on the exact product
        and version you choose.)
     </p>
-    
+
     <ul>
       <li><a href="about:license#mpl">Mozilla Public License 2.0</a>
       <br><br>
       </li>
+      <li><a href="about:license#lgpl">GNU Lesser General Public License 2.1</a>
+      <br><br>
+      </li>
       <li><a href="about:license#ACE">ACE License</a></li>
       <li><a href="about:license#android">Android Open Source License</a></li>
       <li><a href="about:license#angle">ANGLE License</a></li>
       <li><a href="about:license#apache">Apache License 2.0</a></li>
       <li><a href="about:license#apple">Apple License</a></li>
       <li><a href="about:license#apple-mozilla">Apple/Mozilla NPRuntime License</a></li>
       <li><a href="about:license#apple-torch">Apple/Torch Mobile License</a></li>
       <li><a href="about:license#bspatch">bspatch License</a></li>
@@ -107,38 +110,38 @@
       <li><a href="about:license#xdg">Red Hat xdg_user_dir_lookup License</a></li>
       <li><a href="about:license#hunspell-ru">Russian Spellchecking Dictionary License</a></li>
       <li><a href="about:license#sctp">SCTP Licenses</a></li>
       <li><a href="about:license#skia">Skia License</a></li>
       <li><a href="about:license#snappy">Snappy License</a></li>
       <li><a href="about:license#sparkle">Sparkle License</a></li>
       <li><a href="about:license#suitable">Suitable Systems License</a></li>
       <li><a href="about:license#sunsoft">SunSoft License</a></li>
-      <li><a href="about:license#unicode">Unicode License</a></li>      
-      <li><a href="about:license#ucal">University of California License</a></li>      
-      <li><a href="about:license#uszeged">University of Szeged License</a></li>      
+      <li><a href="about:license#unicode">Unicode License</a></li>
+      <li><a href="about:license#ucal">University of California License</a></li>
+      <li><a href="about:license#uszeged">University of Szeged License</a></li>
       <li><a href="about:license#hunspell-en-US">US English Spellchecking Dictionary Licenses</a></li>
       <li><a href="about:license#v8">V8 License</a></li>
       <li><a href="about:license#vtune">VTune License</a></li>
       <li><a href="about:license#webrtc">WebRTC License</a></li>
       <li><a href="about:license#xiph">Xiph.org Foundation License</a></li>
     </ul>
 
 <br>
 
-    <ul>      
+    <ul>
       <li><a href="about:license#other-notices">Other Required Notices</a>
       <li><a href="about:license#optional-notices">Optional Notices</a>
 #ifdef XP_WIN
       <li><a href="about:license#proprietary-notices">Proprietary Operating System Components</a>
-#endif    
+#endif
     </ul>
-    
+
     </div>
-    
+
     <hr>
 
   <h1 id="mpl">Mozilla Public License 2.0</h1>
 
   <h2 id="definitions">1. Definitions</h2>
 
   <dl>
     <dt>1.1. "Contributor"</dt>
@@ -437,42 +440,42 @@
   text file included with all distributions of the Covered Software under
   this License. Except to the extent prohibited by statute or regulation,
   such description must be sufficiently detailed for a recipient of ordinary
   skill to be able to understand it.</p>
 
   <h2 id="termination">5. Termination</h2>
 
   <h3>5.1.</h3>
-  
+
   <p>The rights granted under this License will terminate automatically
   if You fail to comply with any of its terms. However, if You become
   compliant, then the rights granted under this License from a particular
   Contributor are reinstated (a) provisionally, unless and until such
   Contributor explicitly and finally terminates Your grants, and (b) on an
   ongoing basis, if such Contributor fails to notify You of the
   non-compliance by some reasonable means prior to 60 days after You have
   come back into compliance. Moreover, Your grants from a particular
   Contributor are reinstated on an ongoing basis if such Contributor notifies
   You of the non-compliance by some reasonable means, this is the first time
   You have received notice of non-compliance with this License from such
   Contributor, and You become compliant prior to 30 days after Your receipt
   of the notice.</p>
 
   <h3>5.2.</h3>
-  
+
   <p>If You initiate litigation against any entity by asserting a patent
   infringement claim (excluding declaratory judgment actions, counter-claims,
   and cross-claims) alleging that a Contributor Version directly or
   indirectly infringes any patent, then the rights granted to You by any and
   all Contributors for the Covered Software under Section 2.1 of this License
   shall terminate.</p>
 
   <h3>5.3.</h3>
-  
+
   <p>In the event of termination under Sections 5.1 or 5.2 above, all
   end user license agreements (excluding distributors and resellers) which
   have been validly granted by You or Your distributors under this License
   prior to termination shall survive termination.</p>
 
   <h2 id="disclaimer-of-warranty">6. Disclaimer of Warranty</h2>
 
   <p><em>Covered Software is provided under this License on an "as is" basis,
@@ -575,16 +578,572 @@
   <blockquote>
     <p>This Source Code Form is "Incompatible With Secondary Licenses", as
     defined by the Mozilla Public License, v. 2.0.</p>
   </blockquote>
 
 
     <hr>
 
+  <h1 id="lgpl">GNU Lesser General Public License 2.1</h1>
+
+<p>This product contains code from the following LGPLed libraries:</p>
+
+<ul>
+<li><a href="http://www.surina.net/soundtouch/">libsoundtouch</a>
+</ul>
+
+<pre>
+Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+</pre>
+
+<h3><a id="SEC2">Preamble</a></h3>
+
+<p>
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+</p>
+<p>
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+</p>
+<p>
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+</p>
+<p>
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+</p>
+<p>
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+</p>
+<p>
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+</p>
+<p>
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+</p>
+<p>
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+</p>
+<p>
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+</p>
+<p>
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+</p>
+<p>
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+</p>
+<p>
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+</p>
+<p>
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+</p>
+<p>
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+</p>
+<p>
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+</p>
+
+<h3><a id="SEC3">TERMS AND CONDITIONS FOR COPYING,
+DISTRIBUTION AND MODIFICATION</a></h3>
+
+
+<p>
+<strong>0.</strong>
+This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+</p>
+<p>
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+</p>
+<p>
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+</p>
+<p>
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+</p>
+<p>
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+</p>
+<p>
+<strong>1.</strong>
+You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+</p>
+<p>
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+</p>
+<p>
+<strong>2.</strong>
+You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+</p>
+
+<ul>
+  <li><strong>a)</strong>
+       The modified work must itself be a software library.</li>
+  <li><strong>b)</strong>
+       You must cause the files modified to carry prominent notices
+       stating that you changed the files and the date of any change.</li>
+
+  <li><strong>c)</strong>
+       You must cause the whole of the work to be licensed at no
+       charge to all third parties under the terms of this License.</li>
+
+  <li><strong>d)</strong>
+       If a facility in the modified Library refers to a function or a
+       table of data to be supplied by an application program that uses
+       the facility, other than as an argument passed when the facility
+       is invoked, then you must make a good faith effort to ensure that,
+       in the event an application does not supply such function or
+       table, the facility still operates, and performs whatever part of
+       its purpose remains meaningful.
+       <p>
+       (For example, a function in a library to compute square roots has
+       a purpose that is entirely well-defined independent of the
+       application.  Therefore, Subsection 2d requires that any
+       application-supplied function or table used by this function must
+       be optional: if the application does not supply it, the square
+       root function must still compute square roots.)</p></li>
+</ul>
+
+<p>
+These requirements apply to the modified work as a whole.  If identifiable
+sections of that work are not derived from the Library, and can be
+reasonably considered independent and separate works in themselves, then
+this License, and its terms, do not apply to those sections when you
+distribute them as separate works.  But when you distribute the same
+sections as part of a whole which is a work based on the Library, the
+distribution of the whole must be on the terms of this License, whose
+permissions for other licensees extend to the entire whole, and thus to
+each and every part regardless of who wrote it.
+</p>
+<p>
+Thus, it is not the intent of this section to claim rights or contest your
+rights to work written entirely by you; rather, the intent is to exercise
+the right to control the distribution of derivative or collective works
+based on the Library.
+</p>
+<p>
+In addition, mere aggregation of another work not based on the Library with
+the Library (or with a work based on the Library) on a volume of a storage
+or distribution medium does not bring the other work under the scope of
+this License.
+</p>
+<p>
+<strong>3.</strong>
+You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+</p>
+<p>
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+</p>
+<p>
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+</p>
+<p>
+<strong>4.</strong>
+You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+</p>
+<p>
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+</p>
+<p>
+<strong>5.</strong>
+A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+</p>
+<p>
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+</p>
+<p>
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+</p>
+<p>
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+</p>
+<p>
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+</p>
+<p>
+<strong>6.</strong>
+As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+</p>
+<p>
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+</p>
+
+<ul>
+    <li><strong>a)</strong> Accompany the work with the complete
+    corresponding machine-readable source code for the Library
+    including whatever changes were used in the work (which must be
+    distributed under Sections 1 and 2 above); and, if the work is an
+    executable linked with the Library, with the complete
+    machine-readable "work that uses the Library", as object code
+    and/or source code, so that the user can modify the Library and
+    then relink to produce a modified executable containing the
+    modified Library.  (It is understood that the user who changes the
+    contents of definitions files in the Library will not necessarily
+    be able to recompile the application to use the modified
+    definitions.)</li>
+
+    <li><strong>b)</strong> Use a suitable shared library mechanism
+    for linking with the Library.  A suitable mechanism is one that
+    (1) uses at run time a copy of the library already present on the
+    user's computer system, rather than copying library functions into
+    the executable, and (2) will operate properly with a modified
+    version of the library, if the user installs one, as long as the
+    modified version is interface-compatible with the version that the
+    work was made with.</li>
+
+    <li><strong>c)</strong> Accompany the work with a written offer,
+    valid for at least three years, to give the same user the
+    materials specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.</li>
+
+    <li><strong>d)</strong> If distribution of the work is made by
+    offering access to copy from a designated place, offer equivalent
+    access to copy the above specified materials from the same
+    place.</li>
+
+    <li><strong>e)</strong> Verify that the user has already received
+    a copy of these materials or that you have already sent this user
+    a copy.</li>
+</ul>
+
+<p>
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+</p>
+<p>
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+</p>
+<p>
+<strong>7.</strong> You may place library facilities that are a work
+based on the Library side-by-side in a single library together with
+other library facilities not covered by this License, and distribute
+such a combined library, provided that the separate distribution of
+the work based on the Library and of the other library facilities is
+otherwise permitted, and provided that you do these two things:
+</p>
+
+<ul>
+    <li><strong>a)</strong> Accompany the combined library with a copy
+    of the same work based on the Library, uncombined with any other
+    library facilities.  This must be distributed under the terms of
+    the Sections above.</li>
+
+    <li><strong>b)</strong> Give prominent notice with the combined
+    library of the fact that part of it is a work based on the
+    Library, and explaining where to find the accompanying uncombined
+    form of the same work.</li>
+</ul>
+
+<p>
+<strong>8.</strong> You may not copy, modify, sublicense, link with,
+or distribute the Library except as expressly provided under this
+License.  Any attempt otherwise to copy, modify, sublicense, link
+with, or distribute the Library is void, and will automatically
+terminate your rights under this License.  However, parties who have
+received copies, or rights, from you under this License will not have
+their licenses terminated so long as such parties remain in full
+compliance.
+</p>
+<p>
+<strong>9.</strong>
+You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+</p>
+<p>
+<strong>10.</strong>
+Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+</p>
+<p>
+<strong>11.</strong>
+If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+</p>
+<p>
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+</p>
+<p>
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+</p>
+<p>
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+</p>
+<p>
+<strong>12.</strong>
+If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+</p>
+<p>
+<strong>13.</strong>
+The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+</p>
+<p>
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+</p>
+<p>
+<strong>14.</strong>
+If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+</p>
+<p>
+<strong>NO WARRANTY</strong>
+</p>
+<p>
+<strong>15.</strong>
+BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+</p>
+<p>
+<strong>16.</strong>
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+</p>
+
+    <hr>
+
     <h1><a id="ACE"></a>ACE License</h1>
 
     <p>This license applies to the file
     <span class="path">media/webrtc/trunk/src/system_wrappers/source/condition_variable_win.cc</span>.</p>
 
 <pre>
 ACE(TM), TAO(TM), CIAO(TM), DAnCE(TM), and CoSMIC(TM)
 (henceforth referred to as "DOC software") are copyrighted by
@@ -636,40 +1195,40 @@ executables of your software products.
 </pre>
 
 
     <hr>
 
     <h1><a id="angle"></a>ANGLE License</h1>
 
     <p>This license applies to files in the directory <span class="path">gfx/angle/</span>.</p>
-    
+
 <pre>
-Copyright (C) 2002-2010 The ANGLE Project Authors. 
+Copyright (C) 2002-2010 The ANGLE Project Authors.
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 
     Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
 
-    Redistributions in binary form must reproduce the above 
+    Redistributions in binary form must reproduce the above
     copyright notice, this list of conditions and the following
     disclaimer in the documentation and/or other materials provided
     with the distribution.
 
     Neither the name of TransGaming Inc., Google Inc., 3DLabs Inc.
     Ltd., nor the names of their contributors may be used to endorse
     or promote products derived from this software without specific
     prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
@@ -679,17 +1238,17 @@ POSSIBILITY OF SUCH DAMAGE.
 
 
 
     <hr>
 
     <h1><a id="apache"></a>Apache License 2.0</h1>
 
     <p>This license applies to various files in the Mozilla codebase.</p>
-    
+
 <pre>
                                  Apache License
                            Version 2.0, January 2004
                         http://www.apache.org/licenses/
 
    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
 
    1. Definitions.
@@ -866,17 +1425,17 @@ POSSIBILITY OF SUCH DAMAGE.
 
 
 
     <hr>
 
     <h1><a id="apple"></a>Apple License</h1>
 
     <p>This license applies to certain files in the directories <span class="path">js/src/assembler/assembler/</span>, <span class="path">js/src/assembler/wtf/</span>, <span class="path">js/src/yarr</span>, <span class="path">content/media/webaudio/blink</span>, and <span class="path">widget/cocoa</span>.</p>
-    
+
 <pre>
 Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
@@ -892,26 +1451,26 @@ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, I
 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 </pre>
 
-    
+
     <hr>
 
     <h1><a id="apple-mozilla"></a>Apple/Mozilla NPRuntime License</h1>
 
     <p>This license applies to the file
     <span class="path">dom/plugins/base/npruntime.h</span>.</p>
 
 <pre>
-Copyright &copy; 2004, Apple Computer, Inc. and The Mozilla Foundation. 
+Copyright &copy; 2004, Apple Computer, Inc. and The Mozilla Foundation.
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are
 met:
 
 1. Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
@@ -937,22 +1496,22 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBI
 </pre>
 
 
     <hr>
 
     <h1><a id="apple-torch"></a>Apple/Torch Mobile License</h1>
 
     <p>This license applies to the following files:</p>
-    
+
     <ul>
       <li class="path">js/src/assembler/wtf/Assertions.cpp</li>
       <li class="path">js/src/assembler/wtf/Platform.h</li>
     </ul>
-    
+
 <pre>
 Copyright (C) 2003, 2006, 2007 Apple Inc.  All rights reserved.
 Copyright (C) 2007-2009 Torch Mobile, Inc.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
@@ -1029,21 +1588,21 @@ POSSIBILITY OF SUCH DAMAGE.
 <li>2000 Keith Packard, member of The XFree86 Project, Inc.
 <li>2005 Lars Knoll &amp; Zack Rusin, Trolltech
 <li>1998, 2000, 2002, 2004 Keith Packard
 <li>2004 Nicholas Miell
 <li>2005 Trolltech AS
 <li>2000 SuSE, Inc.
 <li>2003 Carl Worth
 <li>1987, 1988, 1989, 1998 The Open Group
-<li>1987, 1988, 1989 Digital Equipment Corporation, Maynard, Massachusetts. 
+<li>1987, 1988, 1989 Digital Equipment Corporation, Maynard, Massachusetts.
 <li>1998 Keith Packard
 <li>2003 Richard Henderson
     </ul>
-    
+
 <pre>
 Copyright &copy; &lt;date&gt; &lt;copyright holder&gt;
 
 Permission to use, copy, modify, distribute, and sell this software
 and its documentation for any purpose is hereby granted without
 fee, provided that the above copyright notice appear in all copies
 and that both that copyright notice and this permission notice
 appear in supporting documentation, and that the name of
@@ -1146,27 +1705,27 @@ OF THIS SOFTWARE OR ITS FITNESS FOR ANY 
 
 <pre>
 Copyright (c) 2006, 2007 OpenTaal
 Copyright (c) 2001, 2002, 2003, 2005 Simon Brouwer e.a.
 Copyright (c) 1996 Nederlandstalige Tex Gebruikersgroep
 
 All rights reserved.
 
-Redistribution and use in source and binary forms, with or without 
+Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 
-* Redistributions of source code must retain the above copyright notice, this 
+* Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.
-* Redistributions in binary form must reproduce the above copyright notice, 
-this list of conditions and the following disclaimer in the documentation 
+* Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
-* Neither the name of the OpenTaal, Simon Brouwer e.a., or Nederlandstalige Tex 
-Gebruikersgroep nor the names of its contributors may be used to endorse or 
-promote products derived from this software without specific prior written 
+* Neither the name of the OpenTaal, Simon Brouwer e.a., or Nederlandstalige Tex
+Gebruikersgroep nor the names of its contributors may be used to endorse or
+promote products derived from this software without specific prior written
 permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
@@ -1591,18 +2150,18 @@ OTHERWISE) ARISING IN ANY WAY OUT OF THE
 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 The contents of this file are taken from Apple80211.h from the iStumbler
 project (http://www.istumbler.net). This project is released under the BSD
 license with the following restrictions.
 
 Copyright (c) 02006, Alf Watt (alf@istumbler.net). All rights reserved.
 
-Redistribution and use in source and binary forms, with or without 
-modification, are permitted provided that the following conditions 
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
 are met:
 
 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 
 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
@@ -1815,34 +2374,34 @@ ARISING OUT OF OR IN CONNECTION WITH THE
 SOFTWARE.
 
 Except as contained in this notice, the name of a copyright holder shall
 not be used in advertising or otherwise to promote the sale, use or other
 dealings in this Software without prior written authorization of the
 copyright holder.
 
 All trademarks and registered trademarks mentioned herein are the property
-of their respective owners. 
+of their respective owners.
 </pre>
 
 
     <hr>
 
     <h1><a id="jpnic"></a>Japan Network Information Center License</h1>
 
     <p>This license applies to certain files in the
     directory <span class="path">netwerk/dns/src/</span>.</p>
 
 <pre>
 Copyright (c) 2001,2002 Japan Network Information Center.
 All rights reserved.
- 
+
 By using this file, you agree to the terms and conditions set forth below.
 
-     LICENSE TERMS AND CONDITIONS 
+     LICENSE TERMS AND CONDITIONS
 
 The following License Terms and Conditions apply, unless a different
 license is obtained from Japan Network Information Center ("JPNIC"),
 a Japanese association, Kokusai-Kougyou-Kanda Bldg 6F, 2-3-4 Uchi-Kanda,
 Chiyoda-ku, Tokyo 101-0047, Japan.
 
 1. Use, Modification and Redistribution (including distribution of any
    modified or derived work) in source and/or binary forms is permitted
@@ -1915,17 +2474,17 @@ OR OTHERWISE) ARISING IN ANY WAY OUT OF 
 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 </pre>
 
     <hr>
 
     <h1><a id="jquery"></a>jQuery License</h1>
 
     <p>This license applies to files in the directory
-      <span class="path">mail/jquery/</span>. 
+      <span class="path">mail/jquery/</span>.
       Furthermore, the file <span class="path">browser/base/content/tabview/iq.js</span>
       incorporates work from jQuery.</p>
 
 <pre>
 Copyright (c) 2010 John Resig, http://jquery.com/
 
 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
@@ -2047,17 +2606,17 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE PO
 
     <h1><a id="libffi"></a>libffi License</h1>
 
     <p>This license applies to files in the directory
     <span class="path">js/ctypes/libffi/</span>.
     </p>
 
 <pre>
-libffi - Copyright (c) 1996-2008 Red Hat, Inc and others.  
+libffi - Copyright (c) 1996-2008 Red Hat, Inc and others.
 See source files for details.
 
 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
 ``Software''), to deal in the Software without restriction, including
 without limitation the rights to use, copy, modify, merge, publish,
 distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to
@@ -2138,17 +2697,17 @@ WHATSOEVER RESULTING FROM LOSS OF USE, D
 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 </pre>
 
     <hr>
 
     <h1><a id="libsoundtouch"></a>libsoundtouch License</h1>
 
-    <p>This license applies to certain files in the directory 
+    <p>This license applies to certain files in the directory
     <span class="path">media/libsoundtouch/src/</span>.
     </p>
 
 <pre>
 The SoundTouch Library Copyright &copy; Olli Parviainen 2001-2012
 
 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
@@ -2243,17 +2802,17 @@ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAM
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 </pre>
 
     <hr>
-    
+
     <h1><a id="hunspell-lt"></a>Lithuanian Spellchecking Dictionary License</h1>
 
     <p>This license applies to certain files in the directory
       <span class="path">l10n/lt/extensions/spellcheck/hunspell/</span>. (This
       code only ships in some localized versions of this product.)</p>
 
 <pre>
 Copyright (c) 2000-2013, Albertas Agejevas and contributors.
@@ -2358,23 +2917,23 @@ 2. Redistributions in binary form must r
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 
 3. All modifications to the source code must be clearly marked as
    such.  Binary redistributions based on modified source code
    must be clearly marked as modified versions in the documentation
    and/or other materials provided with the distribution.
 
-THIS SOFTWARE IS PROVIDED BY KEVIN B. HENDRICKS AND CONTRIBUTORS 
-``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
-FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL 
-KEVIN B. HENDRICKS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
-BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
+THIS SOFTWARE IS PROVIDED BY KEVIN B. HENDRICKS AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
+KEVIN B. HENDRICKS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGE.
 </pre>
 
 
@@ -2469,28 +3028,28 @@ modification, are permitted provided tha
 are met:
 
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 3. Neither the name of Network Resonance, Inc. nor the name of any
-   contributors to this software may be used to endorse or promote 
+   contributors to this software may be used to endorse or promote
    products derived from this software without specific prior written
    permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
-LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
-CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 </pre>
 
     <p>This license applies to certain files in the directory
     <span class="path">media/mtransport/third_party/nrappkit</span>.</p>
 
@@ -2532,18 +3091,18 @@ OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 SUCH DAMAGE.
 </pre>
 
    <p>Note that RTFM, Inc. has waived clause (3) above as of June 20, 2012
    for files appearing in this distribution. This waiver applies only to
    files included in this distribution. it does not apply to any other
    part of ssldump not included in this distribution.</p>
 
-    <p>This license applies to 
-The following license applies to each copy of the file 
+    <p>This license applies to
+The following license applies to each copy of the file
   <span class="path">sys/queue.h</span>
   in <span class="path">media/mtransport/third_party/nrappkit/</span>.</p>
 
 <pre>
 Copyright (c) 1991, 1993
 	The Regents of the University of California.  All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
@@ -2567,17 +3126,17 @@ DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGE.
 </pre>
 
 
-    <p>This license applies to 
+    <p>This license applies to
   The following license applies to the file:
   <span class="path">media/mtransport/third_party/nrappkit/src/util/util.c</span>.</p>
 
 <pre>
 Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
@@ -2597,17 +3156,17 @@ AND FITNESS FOR A PARTICULAR PURPOSE ARE
 THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 </pre>
-  
+
 
     <hr>
 
     <h1><a id="praton"></a>praton License</h1>
 
     <p>This license applies to the file
     <span class="path">nsprpub/pr/src/misc/praton.c</span>.</p>
 
@@ -2682,56 +3241,56 @@ OF OR IN CONNECTION WITH THE USE OR PERF
 
     <p>This license applies to certain files in the directory
       <span class="path">gfx/qcms/</span>.</p>
 <pre>
 Copyright (C) 2009 Mozilla Corporation
 Copyright (C) 1998-2007 Marti Maria
 
 Permission is hereby granted, free of charge, to any person
-obtaining a copy of this software and associated documentation 
-files (the "Software"), to deal in the Software without restriction, 
-including without limitation the rights to use, copy, modify, merge, 
-publish, distribute, sublicense, and/or sell copies of the Software, 
-and to permit persons to whom the Software is furnished to do so, subject 
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software,
+and to permit persons to whom the Software is furnished to do so, subject
 to the following conditions:
 
-The above copyright notice and this permission notice shall be included 
+The above copyright notice and this permission notice shall be included
 in all copies or substantial portions of the Software.
 
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
-WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 </pre>
 
 
     <hr>
 
     <h1><a id="xdg"></a>Red Hat xdg_user_dir_lookup License</h1>
 
     <p>This license applies to the
     <span class="path">xdg_user_dir_lookup</span> function in
     <span class="path">xpcom/io/SpecialSystemDirectory.cpp</span>.</p>
-    
+
 <pre>
 Copyright (c) 2007 Red Hat, Inc.
 
 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation files
 (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge,
 publish, distribute, sublicense, and/or sell copies of the Software,
 and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions: 
+subject to the following conditions:
 
 The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software. 
+included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
@@ -2826,33 +3385,33 @@ Copyright (C) 1995, 1996, 1997, and 1998
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 a) Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
 b) Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the distribution.
 c) Neither the name of Cisco Systems, Inc, the name of the university,
-   the WIDE project, nor the names of its contributors may be used to 
+   the WIDE project, nor the names of its contributors may be used to
    endorse or promote products derived from this software without specific
    prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 THE POSSIBILITY OF SUCH DAMAGE.
 </pre>
-    
+
     <hr>
 
     <h1><a id="skia"></a>Skia License</h1>
 
     <p>This license applies to certain files in the directory
     <span class="path">gfx/skia/</span>.</p>
 
 <pre>
@@ -2879,17 +3438,17 @@ A PARTICULAR PURPOSE ARE DISCLAIMED. IN 
 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 </pre>
-    
+
     <hr>
 
     <h1><a id="snappy"></a>Snappy License</h1>
 
     <p>This license applies to certain files in the directory
     <span class="path">other-licenses/snappy/</span>.</p>
 
 <pre>
@@ -3008,46 +3567,46 @@ or contact
 
     <hr>
 
     <h1><a id="sunsoft"></a>SunSoft License</h1>
 
     <p>This license applies to the
       <span class="path">ICC_H</span> block in
       <span class="path">gfx/qcms/qcms.h</span>.</p>
-      
+
 <pre>
 Copyright (c) 1994-1996 SunSoft, Inc.
 
                     Rights Reserved
 
-Permission is hereby granted, free of charge, to any person 
+Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
-files (the "Software"), to deal in the Software without restrict- 
-ion, including without limitation the rights to use, copy, modify, 
-merge, publish distribute, sublicense, and/or sell copies of the 
-Software, and to permit persons to whom the Software is furnished 
-to do so, subject to the following conditions: 
- 
-The above copyright notice and this permission notice shall be 
-included in all copies or substantial portions of the Software. 
- 
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
+files (the "Software"), to deal in the Software without restrict-
+ion, including without limitation the rights to use, copy, modify,
+merge, publish distribute, sublicense, and/or sell copies of the
+Software, and to permit persons to whom the Software is furnished
+to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-
-INFRINGEMENT.  IN NO EVENT SHALL SUNSOFT, INC. OR ITS PARENT 
-COMPANY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
-WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 
-OTHER DEALINGS IN THE SOFTWARE. 
- 
-Except as contained in this notice, the name of SunSoft, Inc. 
-shall not be used in advertising or otherwise to promote the 
-sale, use or other dealings in this Software without written 
-authorization from SunSoft Inc. 
+INFRINGEMENT.  IN NO EVENT SHALL SUNSOFT, INC. OR ITS PARENT
+COMPANY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of SunSoft, Inc.
+shall not be used in advertising or otherwise to promote the
+sale, use or other dealings in this Software without written
+authorization from SunSoft Inc.
 </pre>
 
 
     <hr>
 
     <h1><a id="unicode"></a>Unicode License</h1>
 
     <p>This license applies to certain files in the directories
@@ -3090,25 +3649,25 @@ authorization of the copyright holder.</
 
 
     <hr>
 
     <h1><a id="ucal"></a>University of California License</h1>
 
     <p>This license applies to the following files or, in the case of
     directories, certain files in those directories:</p>
-    
+
     <ul>
       <li class="path">dbm/</li>
       <li class="path">db/mork/src/morkQuickSort.cpp</li>
       <li class="path">xpcom/glue/nsQuickSort.cpp</li>
       <li class="path">nsprpub/pr/src/misc/praton.c</li>
       <li class="path">media/mtransport/third_party/nICEr/src/stun/addrs.c</li>
     </ul>
-    
+
 <pre>
 Copyright (c) 1990, 1993
  The Regents of the University of California.  All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
@@ -3131,23 +3690,23 @@ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SP
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGE.
 </pre>
 
-    
+
     <hr>
 
     <h1><a id="uszeged"></a>University of Szeged License</h1>
 
     <p>This license applies to certain files in the directory <span class="path">js/src/assembler/assembler/</span>.</p>
-    
+
 <pre>
 Copyright (C) 2009 University of Szeged
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
@@ -3192,33 +3751,33 @@ associated scripts, the output created f
 for any purpose is hereby granted without fee, provided that the above
 copyright notice appears in all copies and that both that copyright notice and
 this permission notice appear in supporting documentation. Kevin Atkinson makes
 no representations about the suitability of this array for any purpose. It is
 provided  "as is" without express or implied warranty.
 
 The WordNet database is under the following copyright:
 
-This software and database is being provided to you, the LICENSEE, by Princeton 
+This software and database is being provided to you, the LICENSEE, by Princeton
 University under the following license.  By obtaining, using and/or copying
 this software and database, you agree that you have read, understood, and will
 comply with these terms and conditions:
 Permission to use, copy, modify and distribute this software and database and
 its documentation for any purpose and without fee or royalty is hereby granted,
 provided that you agree to comply with the following copyright notice and
 statements, including the disclaimer, and that the same appear on ALL copies of
 the software, database and documentation, including modifications that you make
 for internal use or for distribution.
 WordNet 1.6 Copyright 1997 by Princeton University.  All rights reserved.
-THIS SOFTWARE AND DATABASE IS PROVIDED "AS IS" AND PRINCETON UNIVERSITY 
-MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF 
-EXAMPLE, BUT NOT LIMITATION, PRINCETON UNIVERSITY MAKES NO 
-REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY 
-PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE, DATABASE OR 
-DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, 
+THIS SOFTWARE AND DATABASE IS PROVIDED "AS IS" AND PRINCETON UNIVERSITY
+MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
+EXAMPLE, BUT NOT LIMITATION, PRINCETON UNIVERSITY MAKES NO
+REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY
+PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE, DATABASE OR
+DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
 TRADEMARKS OR OTHER RIGHTS.
 The name of Princeton University or Princeton may not be used in advertising or
 publicity pertaining to distribution of the software and/or database.  Title to
 copyright in this software, database and any associated documentation shall at
 all times remain with Princeton University and LICENSEE agrees to preserve same.
 
 The "UK Advanced Cryptics Dictionary" is under the following copyright:
 
@@ -3242,26 +3801,26 @@ this list of conditions and the followin
 and/or other materials provided with the distribution.
   3. All modifications to the source code must be clearly marked as such.
 Binary redistributions based on modified source code must be clearly marked as
 modified versions in the documentation and/or other materials provided with
 the distribution.
   (clause 4 removed with permission from Geoff Kuenning)
   5. The name of Geoff Kuenning may not be used to endorse or promote products
 derived from this software without specific prior written permission.
- THIS SOFTWARE IS PROVIDED BY GEOFF KUENNING AND CONTRIBUTORS ``AS  IS'' AND 
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
-PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL GEOFF KUENNING OR CONTRIBUTORS 
-BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
-CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
-SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
-INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
-CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
-ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE  
+ THIS SOFTWARE IS PROVIDED BY GEOFF KUENNING AND CONTRIBUTORS ``AS  IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL GEOFF KUENNING OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 
 Additional Contributors:
 
  Alan Beale &lt;biljir@pobox.com&gt;
  M Cooper &lt;thegrendel@theriver.com&gt;
 </pre>
 
@@ -3427,34 +3986,34 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 </pre>
 
 
     <hr>
 
     <h1><a id="other-notices"></a>Other Required Notices</h1>
 
     <ul>
-      <li>This software is based in part on the work of the Independent 
+      <li>This software is based in part on the work of the Independent
           JPEG Group.</li>
       <li>Portions of the OS/2 and Android versions
           of this software are copyright &copy;1996-2012
           <a href="http://www.freetype.org/">The FreeType Project</a>.
           All rights reserved.</li>
     </ul>
 
 
     <hr>
 
     <h1><a id="optional-notices"></a>Optional Notices</h1>
 
     <p>Some permissive software licenses request but do not require an
     acknowledgement of the use of their software. We are very grateful
     to the following people and projects for their contributions to
     this product:</p>
-    
+
     <ul>
       <li>The <a href="http://www.zlib.net/">zlib</a> compression library
           (Jean-loup Gailly, Mark Adler and team)</li>
       <li>The <a href="http://www.bzip.org/">bzip2</a> compression library
           (Julian Seward)</li>
       <li>The <a href="http://www.libpng.org/pub/png/">libpng</a> graphics library
           (Glenn Randers-Pehrson and team)</li>
       <li>The <a href="http://www.sqlite.org/">sqlite</a> database engine
@@ -3473,17 +4032,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 
     <p>Under some circumstances, under our
     <a href="http://www.mozilla.org/foundation/licensing/binary-components/">binary components policy</a>,
     Mozilla may decide to include additional
     operating system vendor code with the installer of our products designed
     for that vendor's proprietary platform, to make our products work well on
     that specific operating system. The following license statements
     apply to such inclusions.</p>
-    
+
     <h2><a id="directx"></a>Microsoft Windows: Terms for 'Microsoft Distributable Code'</h2>
 
     <p>These terms apply to the following files;
     they are referred to below as "Distributable Code":
       <ul>
         <li><span class="path">d3d*.dll</span> (Direct3D libraries)</li>
         <li><span class="path">msvc*.dll</span> (C and C++ runtime libraries)</li>
       </ul>
@@ -3506,16 +4065,16 @@ following terms:
 (v)   You must comply with any technical limitations in the Distributable Code
       that only allow you to use it in certain ways; and
 (vi)  You must comply with all domestic and international export laws and
       regulations that apply to the Distributable Code.
 </pre>
 
 #endif
 
-    
+
     <hr>
-    
+
     <p><a href="about:license#top">Return to top</a>.</p>
-    
+
   </body>
 </html>
 
--- a/uriloader/prefetch/nsOfflineCacheUpdateService.cpp
+++ b/uriloader/prefetch/nsOfflineCacheUpdateService.cpp
@@ -681,32 +681,24 @@ OfflineAppPermForURI(nsIURI *aURI,
     if (!permissionManager) {
         return NS_OK;
     }
 
     uint32_t perm;
     const char *permName = pinned ? "pin-app" : "offline-app";
     permissionManager->TestExactPermission(innerURI, permName, &perm);
 
-    if (perm == nsIPermissionManager::UNKNOWN_ACTION && !pinned) {
-        static const char kPrefName[] = "offline-apps.allow_by_default";
-        if (aPrefBranch) {
-            aPrefBranch->GetBoolPref(kPrefName, aAllowed);
-        } else {
-            *aAllowed = Preferences::GetBool(kPrefName, false);
-        }
-
-        return NS_OK;
-    }
-
     if (perm == nsIPermissionManager::ALLOW_ACTION ||
         perm == nsIOfflineCacheUpdateService::ALLOW_NO_WARN) {
         *aAllowed = true;
     }
 
+    // offline-apps.allow_by_default is now effective at the cache selection
+    // algorithm code (nsContentSink).
+
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsOfflineCacheUpdateService::OfflineAppAllowedForURI(nsIURI *aURI,
                                                      nsIPrefBranch *aPrefBranch,
                                                      bool *aAllowed)
 {
--- a/widget/cocoa/Makefile.in
+++ b/widget/cocoa/Makefile.in
@@ -48,16 +48,17 @@ CMMSRCS = \
   nsIdleServiceX.mm \
   TextInputHandler.mm \
   nsMacDockSupport.mm \
   nsStandaloneNativeMenu.mm \
   nsMacWebAppUtils.mm \
   GfxInfo.mm \
   WidgetTraceEvent.mm \
   NativeKeyBindings.mm \
+  nsColorPicker.mm \
   $(NULL)
 
 ifeq (x86_64,$(TARGET_CPU))
 CMMSRCS += ComplexTextInputPanel.mm
 endif
 
 SHARED_LIBRARY_LIBS = ../xpwidgets/libxpwidgets_s.a
 
new file mode 100644
--- /dev/null
+++ b/widget/cocoa/nsColorPicker.h
@@ -0,0 +1,42 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef nsColorPicker_h_
+#define nsColorPicker_h_
+
+#include "nsIColorPicker.h"
+#include "nsString.h"
+#include "nsCOMPtr.h"
+
+class nsIColorPickerShownCallback;
+class nsIDOMWindow;
+@class NSColorPanelWrapper;
+@class NSColor;
+
+class nsColorPicker MOZ_FINAL : public nsIColorPicker
+{
+public:
+  NS_DECL_ISUPPORTS
+
+  NS_IMETHOD Init(nsIDOMWindow* aParent, const nsAString& aTitle,
+                  const nsAString& aInitialColor);
+  NS_IMETHOD Open(nsIColorPickerShownCallback* aCallback);
+
+  // For NSColorPanelWrapper.
+  void Update(NSColor* aColor);
+  void Done();
+
+private:
+  static NSColor* GetNSColorFromHexString(const nsAString& aColor);
+  static void GetHexStringFromNSColor(NSColor* aColor, nsAString& aResult);
+
+  nsString             mTitle;
+  nsString             mColor;
+  NSColorPanelWrapper* mColorPanel;
+  nsCOMPtr<nsIColorPickerShownCallback> mCallback;
+};
+
+#endif // nsColorPicker_h_
new file mode 100644
--- /dev/null
+++ b/widget/cocoa/nsColorPicker.mm
@@ -0,0 +1,157 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#import <Cocoa/Cocoa.h>
+
+#include "nsColorPicker.h"
+#include "nsCocoaUtils.h"
+
+using namespace mozilla;
+
+static unsigned int
+HexStrToInt(NSString* str)
+{
+  unsigned int result = 0;
+
+  for (unsigned int i = 0; i < [str length]; ++i) {
+    char c = [str characterAtIndex:i];
+    result *= 16;
+    if (c >= '0' && c <= '9') {
+      result += c - '0';
+    } else if (c >= 'A' && c <= 'F') {
+      result += 10 + (c - 'A');
+    } else {
+      result += 10 + (c - 'a');
+    }
+  }
+
+  return result;
+}
+
+@interface NSColorPanelWrapper : NSObject <NSWindowDelegate>
+{
+  NSColorPanel*  mColorPanel;
+  nsColorPicker* mColorPicker;
+}
+- (id)initWithPicker:(nsColorPicker*)aPicker;
+- (void)open:(NSColor*)aInitialColor title:(NSString*)aTitle;
+- (void)colorChanged:(NSColorPanel*)aPanel;
+@end
+
+@implementation NSColorPanelWrapper
+- (id)initWithPicker:(nsColorPicker*)aPicker
+{
+  mColorPicker = aPicker;
+  mColorPanel = [NSColorPanel sharedColorPanel];
+
+  self = [super init];
+  return self;
+}
+
+- (void)open:(NSColor*)aInitialColor title:(NSString*)aTitle
+{
+  [mColorPanel setTitle:aTitle];
+  [mColorPanel setColor:aInitialColor];
+  [mColorPanel setTarget:self];
+  [mColorPanel setAction:@selector(colorChanged:)];
+  [mColorPanel setDelegate:self];
+  [mColorPanel makeKeyAndOrderFront:nil];
+}
+
+- (void)colorChanged:(NSColorPanel*)aPanel
+{
+  mColorPicker->Update([mColorPanel color]);
+}
+
+- (void)windowWillClose:(NSNotification*)aNotification
+{
+  mColorPicker->Done();
+}
+
+- (void)dealloc
+{
+  if ([mColorPanel delegate] == self) {
+    [mColorPanel setTarget:nil];
+    [mColorPanel setAction:nil];
+    [mColorPanel setDelegate:nil];
+  }
+
+  mColorPanel = nil;
+  mColorPicker = nullptr;
+
+  [super dealloc];
+}
+@end
+
+NS_IMPL_ISUPPORTS1(nsColorPicker, nsIColorPicker)
+
+NS_IMETHODIMP
+nsColorPicker::Init(nsIDOMWindow* aParent, const nsAString& aTitle,
+                    const nsAString& aInitialColor)
+{
+  mTitle = aTitle;
+  mColor = aInitialColor;
+
+  mColorPanel = [[NSColorPanelWrapper alloc] initWithPicker:this];
+
+  return NS_OK;
+}
+
+/* static */ NSColor*
+nsColorPicker::GetNSColorFromHexString(const nsAString& aColor)
+{
+  NSString* str = nsCocoaUtils::ToNSString(aColor);
+
+  double red = HexStrToInt([str substringWithRange:NSMakeRange(1, 2)]) / 255.0;
+  double green = HexStrToInt([str substringWithRange:NSMakeRange(3, 2)]) / 255.0;
+  double blue = HexStrToInt([str substringWithRange:NSMakeRange(5, 2)]) / 255.0;
+
+  return [NSColor colorWithDeviceRed: red green: green blue: blue alpha: 1.0];
+}
+
+/* static */ void
+nsColorPicker::GetHexStringFromNSColor(NSColor* aColor, nsAString& aResult)
+{
+  CGFloat redFloat, greenFloat, blueFloat;
+  [aColor getRed: &redFloat green: &greenFloat blue: &blueFloat alpha: nil];
+
+  nsCocoaUtils::GetStringForNSString([NSString stringWithFormat:@"#%02x%02x%02x",
+                                       (int)(redFloat * 255),
+                                       (int)(greenFloat * 255),
+                                       (int)(blueFloat * 255)],
+                                     aResult);
+}
+
+NS_IMETHODIMP
+nsColorPicker::Open(nsIColorPickerShownCallback* aCallback)
+{
+  MOZ_ASSERT(aCallback);
+  mCallback = aCallback;
+
+  [mColorPanel open:GetNSColorFromHexString(mColor)
+              title:nsCocoaUtils::ToNSString(mTitle)];
+
+  NS_ADDREF_THIS();
+
+  return NS_OK;
+}
+
+void
+nsColorPicker::Update(NSColor* aColor)
+{
+  GetHexStringFromNSColor(aColor, mColor);
+  mCallback->Update(mColor);
+}
+
+void
+nsColorPicker::Done()
+{
+  mCallback->Done(EmptyString());
+  mCallback = nullptr;
+
+  [mColorPanel release];
+
+  NS_RELEASE_THIS();
+}
--- a/widget/cocoa/nsWidgetFactory.mm
+++ b/widget/cocoa/nsWidgetFactory.mm
@@ -10,16 +10,17 @@
 
 #include "nsWidgetsCID.h"
 
 #include "nsChildView.h"
 #include "nsCocoaWindow.h"
 #include "nsAppShell.h"
 #include "nsAppShellSingleton.h"
 #include "nsFilePicker.h"
+#include "nsColorPicker.h"
 
 #include "nsClipboard.h"
 #include "nsClipboardHelper.h"
 #include "nsTransferable.h"
 #include "nsHTMLFormatConverter.h"
 #include "nsDragService.h"
 #include "nsToolkit.h"
 
@@ -32,16 +33,17 @@
 #include "nsDeviceContextSpecX.h"
 #include "nsPrintOptionsX.h"
 #include "nsPrintDialogX.h"
 #include "nsPrintSession.h"
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsCocoaWindow)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsChildView)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsFilePicker)
+NS_GENERIC_FACTORY_CONSTRUCTOR(nsColorPicker)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsSound)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsTransferable)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsHTMLFormatConverter)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsClipboard)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsClipboardHelper)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDragService)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsScreenManagerCocoa)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDeviceContextSpecX)
@@ -128,16 +130,17 @@ NativeKeyBindingsEditorConstructor(nsISu
 
 } // namespace widget
 } // namespace mozilla
 
 NS_DEFINE_NAMED_CID(NS_WINDOW_CID);
 NS_DEFINE_NAMED_CID(NS_POPUP_CID);
 NS_DEFINE_NAMED_CID(NS_CHILD_CID);
 NS_DEFINE_NAMED_CID(NS_FILEPICKER_CID);
+NS_DEFINE_NAMED_CID(NS_COLORPICKER_CID);
 NS_DEFINE_NAMED_CID(NS_APPSHELL_CID);
 NS_DEFINE_NAMED_CID(NS_SOUND_CID);
 NS_DEFINE_NAMED_CID(NS_TRANSFERABLE_CID);
 NS_DEFINE_NAMED_CID(NS_HTMLFORMATCONVERTER_CID);
 NS_DEFINE_NAMED_CID(NS_CLIPBOARD_CID);
 NS_DEFINE_NAMED_CID(NS_CLIPBOARDHELPER_CID);
 NS_DEFINE_NAMED_CID(NS_DRAGSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_BIDIKEYBOARD_CID);
@@ -158,16 +161,17 @@ NS_DEFINE_NAMED_CID(NS_NATIVEKEYBINDINGS
 NS_DEFINE_NAMED_CID(NS_NATIVEKEYBINDINGS_EDITOR_CID);
 
 
 static const mozilla::Module::CIDEntry kWidgetCIDs[] = {
   { &kNS_WINDOW_CID, false, NULL, nsCocoaWindowConstructor },
   { &kNS_POPUP_CID, false, NULL, nsCocoaWindowConstructor },
   { &kNS_CHILD_CID, false, NULL, nsChildViewConstructor },
   { &kNS_FILEPICKER_CID, false, NULL, nsFilePickerConstructor },
+  { &kNS_COLORPICKER_CID, false, NULL, nsColorPickerConstructor },
   { &kNS_APPSHELL_CID, false, NULL, nsAppShellConstructor },
   { &kNS_SOUND_CID, false, NULL, nsSoundConstructor },
   { &kNS_TRANSFERABLE_CID, false, NULL, nsTransferableConstructor },
   { &kNS_HTMLFORMATCONVERTER_CID, false, NULL, nsHTMLFormatConverterConstructor },
   { &kNS_CLIPBOARD_CID, false, NULL, nsClipboardConstructor },
   { &kNS_CLIPBOARDHELPER_CID, false, NULL, nsClipboardHelperConstructor },
   { &kNS_DRAGSERVICE_CID, false, NULL, nsDragServiceConstructor },
   { &kNS_BIDIKEYBOARD_CID, false, NULL, nsBidiKeyboardConstructor },
@@ -192,16 +196,17 @@ static const mozilla::Module::CIDEntry k
   { NULL }
 };
 
 static const mozilla::Module::ContractIDEntry kWidgetContracts[] = {
   { "@mozilla.org/widgets/window/mac;1", &kNS_WINDOW_CID },
   { "@mozilla.org/widgets/popup/mac;1", &kNS_POPUP_CID },
   { "@mozilla.org/widgets/childwindow/mac;1", &kNS_CHILD_CID },
   { "@mozilla.org/filepicker;1", &kNS_FILEPICKER_CID },
+  { "@mozilla.org/colorpicker;1", &kNS_COLORPICKER_CID },
   { "@mozilla.org/widget/appshell/mac;1", &kNS_APPSHELL_CID },
   { "@mozilla.org/sound;1", &kNS_SOUND_CID },
   { "@mozilla.org/widget/transferable;1", &kNS_TRANSFERABLE_CID },
   { "@mozilla.org/widget/htmlformatconverter;1", &kNS_HTMLFORMATCONVERTER_CID },
   { "@mozilla.org/widget/clipboard;1", &kNS_CLIPBOARD_CID },
   { "@mozilla.org/widget/clipboardhelper;1", &kNS_CLIPBOARDHELPER_CID },
   { "@mozilla.org/widget/dragservice;1", &kNS_DRAGSERVICE_CID },
   { "@mozilla.org/widget/bidikeyboard;1", &kNS_BIDIKEYBOARD_CID },
--- a/widget/nsGUIEvent.h
+++ b/widget/nsGUIEvent.h
@@ -683,16 +683,19 @@ public:
   // Elapsed time, in milliseconds, from a platform-specific zero time
   // to the time the message was created
   uint64_t    time;
   // See BaseEventFlags definition for the detail.
   mozilla::widget::BaseEventFlags mFlags;
 
   // Additional type info for user defined events
   nsCOMPtr<nsIAtom>     userType;
+
+  nsString typeString; // always set on non-main-thread events
+
   // Event targets, needed by DOM Events
   nsCOMPtr<mozilla::dom::EventTarget> target;
   nsCOMPtr<mozilla::dom::EventTarget> currentTarget;
   nsCOMPtr<mozilla::dom::EventTarget> originalTarget;
 };
 
 /**
  * General graphic user interface event