Merge MC -> JM
authorBrian Hackett <bhackett1024@gmail.com>
Fri, 15 Jul 2011 14:40:15 -0700
changeset 76043 6b9bd44373e70c0841070a1eb6607d7426224093
parent 76042 b769a2b79e6b3192c33f01b9016ab91659f4304f (current diff)
parent 72873 d3f9f34116128fd9bc6356672945e74ebc7cc620 (diff)
child 76044 a37127f33d2290c78ed3973868a66101c81d98a6
push id3
push userfelipc@gmail.com
push dateFri, 30 Sep 2011 20:09:13 +0000
milestone8.0a1
Merge MC -> JM
browser/app/README.txt
browser/base/content/browser.js
browser/base/content/highlighter.xhtml
browser/base/content/test/tabview/browser_tabview_bug625666.js
browser/locales/en-US/README.txt
browser/themes/gnomestripe/browser/highlighter.css
browser/themes/pinstripe/browser/highlighter.css
browser/themes/winstripe/browser/highlighter.css
content/html/content/test/test_bug601061.html
content/html/content/test/test_bug630889.html
dom/base/nsDOMClassInfo.cpp
dom/base/nsGlobalWindow.cpp
dom/base/nsJSEnvironment.cpp
dom/interfaces/base/nsIDOMWindowInternal.idl
dom/interfaces/storage/nsIDOMStorageWindow.idl
js/src/Makefile.in
js/src/config/autoconf.mk.in
js/src/configure.in
js/src/jsapi-tests/Makefile.in
js/src/jsapi.cpp
js/src/jsapi.h
js/src/jsarray.cpp
js/src/jsbuiltins.h
js/src/jscntxt.cpp
js/src/jscntxt.h
js/src/jscntxtinlines.h
js/src/jscompartment.cpp
js/src/jscompartment.h
js/src/jsdate.cpp
js/src/jsemit.cpp
js/src/jsemit.h
js/src/jsfun.cpp
js/src/jsfun.h
js/src/jsgc.cpp
js/src/jsgcmark.cpp
js/src/jsinfer.cpp
js/src/jsinterp.cpp
js/src/jsmath.cpp
js/src/jsnum.cpp
js/src/jsobj.cpp
js/src/jsobj.h
js/src/jsobjinlines.h
js/src/json.cpp
js/src/jsopcode.cpp
js/src/jsopcode.tbl
js/src/jsparse.cpp
js/src/jsprobes.cpp
js/src/jsproxy.cpp
js/src/jsprvtd.h
js/src/jsregexp.cpp
js/src/jsregexpinlines.h
js/src/jsscope.cpp
js/src/jsscript.cpp
js/src/jsscript.h
js/src/jsstr.cpp
js/src/jstracer.cpp
js/src/jstracer.h
js/src/jstypedarray.cpp
js/src/jsvalue.h
js/src/jswrapper.cpp
js/src/jswrapper.h
js/src/jsxdrapi.h
js/src/jsxml.cpp
js/src/methodjit/Compiler.cpp
js/src/methodjit/FastArithmetic.cpp
js/src/methodjit/InvokeHelpers.cpp
js/src/methodjit/MethodJIT.cpp
js/src/methodjit/MonoIC.cpp
js/src/methodjit/StubCalls.cpp
js/src/shell/js.cpp
js/src/tests/e4x/XML/jstests.list
js/src/tests/js1_5/Array/regress-350256-03.js
js/src/tests/js1_8_5/extensions/jstests.list
js/src/tests/js1_8_5/regress/jstests.list
js/src/vm/GlobalObject.cpp
js/src/vm/Stack-inl.h
js/src/vm/Stack.cpp
js/src/vm/Stack.h
js/src/xpconnect/shell/xpcshell.cpp
js/src/xpconnect/src/xpcjsruntime.cpp
js/src/xpconnect/src/xpcprivate.h
layout/xul/base/public/nsIMenuFrame.h
layout/xul/base/src/nsIBoxLayout.h
layout/xul/base/src/nsIScrollbarFrame.h
modules/libpref/src/init/all.js
services/sync/tests/unit/head_appinfo.js.in
toolkit/components/console/hudservice/tests/browser/browser_webconsole_bug_642108_refForOutputNode.js
toolkit/components/console/hudservice/tests/browser/browser_webconsole_display_accessors.js
toolkit/components/console/hudservice/tests/browser/browser_webconsole_get_content_window_from_hud_id.js
toolkit/components/console/hudservice/tests/browser/browser_webconsole_get_heads_up_display.js
toolkit/components/console/hudservice/tests/browser/test-bug-595934-getselection.html
toolkit/components/console/hudservice/tests/browser/test-bug-595934-getselection.js
--- a/accessible/src/atk/nsApplicationAccessibleWrap.cpp
+++ b/accessible/src/atk/nsApplicationAccessibleWrap.cpp
@@ -50,17 +50,17 @@
 #include "nsAccessibilityService.h"
 #include "AtkSocketAccessible.h"
 
 #include <gtk/gtk.h>
 #include <atk/atk.h>
 
 typedef GType (* AtkGetTypeType) (void);
 GType g_atk_hyperlink_impl_type = G_TYPE_INVALID;
-static PRBool sATKChecked = PR_FALSE;
+static bool sATKChecked = false;
 static PRLibrary *sATKLib = nsnull;
 static const char sATKLibName[] = "libatk-1.0.so.0";
 static const char sATKHyperlinkImplGetTypeSymbol[] =
     "atk_hyperlink_impl_get_type";
 static const char sAccEnv [] = "GNOME_ACCESSIBILITY";
 static const char sSysPrefService [] =
     "@mozilla.org/system-preference-service;1";
 static const char sAccessibilityKey [] =
@@ -95,33 +95,37 @@ static guint add_listener (GSignalEmissi
                            const gchar *hook_data,
                            guint gail_listenerid = 0);
 static AtkKeyEventStruct *atk_key_event_from_gdk_event_key(GdkEventKey *key);
 static gboolean notify_hf(gpointer key, gpointer value, gpointer data);
 static void insert_hf(gpointer key, gpointer value, gpointer data);
 static gint mai_key_snooper(GtkWidget *the_widget, GdkEventKey *event,
                             gpointer func_data);
 
-static GHashTable *listener_list = NULL;
-static gint listener_idx = 1;
+static GHashTable* sListener_list = NULL;
+static gint sListener_idx = 1;
 
 #define MAI_TYPE_UTIL              (mai_util_get_type ())
 #define MAI_UTIL(obj)              (G_TYPE_CHECK_INSTANCE_CAST ((obj), \
                                     MAI_TYPE_UTIL, MaiUtil))
 #define MAI_UTIL_CLASS(klass)      (G_TYPE_CHECK_CLASS_CAST ((klass), \
                                     MAI_TYPE_UTIL, MaiUtilClass))
 #define MAI_IS_UTIL(obj)           (G_TYPE_CHECK_INSTANCE_TYPE ((obj), \
                                     MAI_TYPE_UTIL))
 #define MAI_IS_UTIL_CLASS(klass)   (G_TYPE_CHECK_CLASS_TYPE ((klass), \
                                     MAI_TYPE_UTIL))
 #define MAI_UTIL_GET_CLASS(obj)    (G_TYPE_INSTANCE_GET_CLASS ((obj), \
                                     MAI_TYPE_UTIL, MaiUtilClass))
 
-static GHashTable *key_listener_list = NULL;
-static guint key_snooper_id = 0;
+static GHashTable* sKey_listener_list = NULL;
+static guint sKey_snooper_id = 0;
+static GQuark sQuark_gecko_acc_obj = g_quark_from_static_string("GeckoAccObj");
+static bool sToplevel_event_hook_added = false;
+static gulong sToplevel_show_hook = 0;
+static gulong sToplevel_hide_hook = 0;
 
 G_BEGIN_DECLS
 typedef void (*GnomeAccessibilityInit) (void);
 typedef void (*GnomeAccessibilityShutdown) (void);
 G_END_DECLS
 
 struct MaiUtil
 {
@@ -218,26 +222,32 @@ mai_util_get_type(void)
     return type;
 }
 
 static void
 window_added (AtkObject *atk_obj,
               guint     index,
               AtkObject *child)
 {
-  guint id =  g_signal_lookup ("create", MAI_TYPE_ATK_OBJECT);
+  if (!IS_MAI_OBJECT(child))
+      return;
+
+  static guint id =  g_signal_lookup ("create", MAI_TYPE_ATK_OBJECT);
   g_signal_emit (child, id, 0);
 }
 
 static void
 window_removed (AtkObject *atk_obj,
                 guint     index,
                 AtkObject *child)
 {
-  guint id =  g_signal_lookup ("destroy", MAI_TYPE_ATK_OBJECT);
+  if (!IS_MAI_OBJECT(child))
+      return;
+
+  static guint id =  g_signal_lookup ("destroy", MAI_TYPE_ATK_OBJECT);
   g_signal_emit (child, id, 0);
 }
 
 /* intialize the the atk interface (function pointers) with MAI implementation.
  * When atk bridge get loaded, these interface can be used.
  */
 static void
 mai_util_class_init(MaiUtilClass *klass)
@@ -259,18 +269,18 @@ mai_util_class_init(MaiUtilClass *klass)
     atk_class->remove_global_event_listener =
         mai_util_remove_global_event_listener;
     atk_class->add_key_event_listener = mai_util_add_key_event_listener;
     atk_class->remove_key_event_listener = mai_util_remove_key_event_listener;
     atk_class->get_root = mai_util_get_root;
     atk_class->get_toolkit_name = mai_util_get_toolkit_name;
     atk_class->get_toolkit_version = mai_util_get_toolkit_version;
 
-    listener_list = g_hash_table_new_full(g_int_hash, g_int_equal, NULL,
-                                          _listener_info_destroy);
+    sListener_list = g_hash_table_new_full(g_int_hash, g_int_equal, NULL,
+                                           _listener_info_destroy);
     // Keep track of added/removed windows.
     AtkObject *root = atk_get_root ();
     g_signal_connect (root, "children-changed::add", (GCallback) window_added, NULL);
     g_signal_connect (root, "children-changed::remove", (GCallback) window_removed, NULL);
 }
 
 static guint
 mai_util_add_global_event_listener(GSignalEmissionHook listener,
@@ -284,17 +294,17 @@ mai_util_add_global_event_listener(GSign
     if (split_string) {
         if (!strcmp ("window", split_string[0])) {
             guint gail_listenerid = 0;
             if (gail_add_global_event_listener) {
                 // call gail's function to track gtk native window events
                 gail_listenerid =
                     gail_add_global_event_listener(listener, event_type);
             }
-            
+
             rc = add_listener (listener, "MaiAtkObject", split_string[1],
                                event_type, gail_listenerid);
         }
         else {
             rc = add_listener (listener, split_string[1], split_string[2],
                                event_type);
         }
         g_strfreev(split_string);
@@ -305,32 +315,32 @@ mai_util_add_global_event_listener(GSign
 static void
 mai_util_remove_global_event_listener(guint remove_listener)
 {
     if (remove_listener > 0) {
         MaiUtilListenerInfo *listener_info;
         gint tmp_idx = remove_listener;
 
         listener_info = (MaiUtilListenerInfo *)
-            g_hash_table_lookup(listener_list, &tmp_idx);
+            g_hash_table_lookup(sListener_list, &tmp_idx);
 
         if (listener_info != NULL) {
             if (gail_remove_global_event_listener &&
                 listener_info->gail_listenerid) {
               gail_remove_global_event_listener(listener_info->gail_listenerid);
             }
-            
+
             /* Hook id of 0 and signal id of 0 are invalid */
             if (listener_info->hook_id != 0 && listener_info->signal_id != 0) {
                 /* Remove the emission hook */
                 g_signal_remove_emission_hook(listener_info->signal_id,
                                               listener_info->hook_id);
 
                 /* Remove the element from the hash */
-                g_hash_table_remove(listener_list, &tmp_idx);
+                g_hash_table_remove(sListener_list, &tmp_idx);
             }
             else {
                 g_warning("Invalid listener hook_id %ld or signal_id %d\n",
                           listener_info->hook_id, listener_info->signal_id);
             }
         }
         else {
             // atk-bridge is initialized with gail (e.g. yelp)
@@ -361,24 +371,24 @@ atk_key_event_from_gdk_event_key (GdkEve
         break;
     default:
         g_assert_not_reached ();
         return NULL;
     }
     event->state = key->state;
     event->keyval = key->keyval;
     event->length = key->length;
-    if (key->string && key->string [0] && 
+    if (key->string && key->string [0] &&
         (key->state & GDK_CONTROL_MASK ||
          g_unichar_isgraph (g_utf8_get_char (key->string)))) {
         event->string = key->string;
     }
     else if (key->type == GDK_KEY_PRESS ||
              key->type == GDK_KEY_RELEASE) {
-        event->string = gdk_keyval_name (key->keyval);	    
+        event->string = gdk_keyval_name (key->keyval);
     }
     event->keycode = key->hardware_keycode;
     event->timestamp = key->time;
 
     MAI_LOG_DEBUG(("MaiKey:\tsym %u\n\tmods %x\n\tcode %u\n\ttime %lx\n",
                    (unsigned int) event->keyval,
                    (unsigned int) event->state,
                    (unsigned int) event->keycode,
@@ -404,19 +414,19 @@ insert_hf(gpointer key, gpointer value, 
 
 static gint
 mai_key_snooper(GtkWidget *the_widget, GdkEventKey *event, gpointer func_data)
 {
     /* notify each AtkKeySnoopFunc in turn... */
 
     MaiKeyEventInfo *info = g_new0(MaiKeyEventInfo, 1);
     gint consumed = 0;
-    if (key_listener_list) {
+    if (sKey_listener_list) {
         GHashTable *new_hash = g_hash_table_new(NULL, NULL);
-        g_hash_table_foreach (key_listener_list, insert_hf, new_hash);
+        g_hash_table_foreach (sKey_listener_list, insert_hf, new_hash);
         info->key_event = atk_key_event_from_gdk_event_key (event);
         info->func_data = func_data;
         consumed = g_hash_table_foreach_steal (new_hash, notify_hf, info);
         g_hash_table_destroy (new_hash);
         g_free(info->key_event);
     }
     g_free(info);
     return (consumed ? 1 : 0);
@@ -425,39 +435,39 @@ mai_key_snooper(GtkWidget *the_widget, G
 static guint
 mai_util_add_key_event_listener (AtkKeySnoopFunc listener,
                                  gpointer data)
 {
     NS_ENSURE_TRUE(listener, 0);
 
     static guint key=0;
 
-    if (!key_listener_list) {
-        key_listener_list = g_hash_table_new(NULL, NULL);
-        key_snooper_id = gtk_key_snooper_install(mai_key_snooper, data);
+    if (!sKey_listener_list) {
+        sKey_listener_list = g_hash_table_new(NULL, NULL);
+        sKey_snooper_id = gtk_key_snooper_install(mai_key_snooper, data);
     }
     AtkKeySnoopFuncPointer atkKeySnoop;
     atkKeySnoop.func_ptr = listener;
-    g_hash_table_insert(key_listener_list, GUINT_TO_POINTER (key++),
+    g_hash_table_insert(sKey_listener_list, GUINT_TO_POINTER (key++),
                         atkKeySnoop.data);
     return key;
 }
 
 static void
 mai_util_remove_key_event_listener (guint remove_listener)
 {
-    if (!key_listener_list) {
+    if (!sKey_listener_list) {
         // atk-bridge is initialized with gail (e.g. yelp)
         // try gail_remove_key_event_listener
         return gail_remove_key_event_listener(remove_listener);
     }
 
-    g_hash_table_remove(key_listener_list, GUINT_TO_POINTER (remove_listener));
-    if (g_hash_table_size(key_listener_list) == 0) {
-        gtk_key_snooper_remove(key_snooper_id);
+    g_hash_table_remove(sKey_listener_list, GUINT_TO_POINTER (remove_listener));
+    if (g_hash_table_size(sKey_listener_list) == 0) {
+        gtk_key_snooper_remove(sKey_snooper_id);
     }
 }
 
 AtkObject *
 mai_util_get_root(void)
 {
     if (nsAccessibilityService::IsShutdown()) {
         // We've shutdown, try to use gail instead
@@ -507,31 +517,31 @@ add_listener (GSignalEmissionHook listen
     gint rc = 0;
 
     type = g_type_from_name(object_type);
     if (type) {
         signal_id = g_signal_lookup(signal, type);
         if (signal_id > 0) {
             MaiUtilListenerInfo *listener_info;
 
-            rc = listener_idx;
+            rc = sListener_idx;
 
             listener_info =  (MaiUtilListenerInfo *)
                 g_malloc(sizeof(MaiUtilListenerInfo));
-            listener_info->key = listener_idx;
+            listener_info->key = sListener_idx;
             listener_info->hook_id =
                 g_signal_add_emission_hook(signal_id, 0, listener,
                                            g_strdup(hook_data),
                                            (GDestroyNotify)g_free);
             listener_info->signal_id = signal_id;
             listener_info->gail_listenerid = gail_listenerid;
 
-            g_hash_table_insert(listener_list, &(listener_info->key),
+            g_hash_table_insert(sListener_list, &(listener_info->key),
                                 listener_info);
-            listener_idx++;
+            sListener_idx++;
         }
         else {
             g_warning("Invalid signal type %s\n", signal);
         }
     }
     else {
         g_warning("Invalid object type %s\n", object_type);
     }
@@ -549,16 +559,59 @@ nsApplicationAccessibleWrap::nsApplicati
 }
 
 nsApplicationAccessibleWrap::~nsApplicationAccessibleWrap()
 {
     MAI_LOG_DEBUG(("======Destory AppRootAcc=%p\n", (void*)this));
     nsAccessibleWrap::ShutdownAtkObject();
 }
 
+static gboolean
+toplevel_event_watcher(GSignalInvocationHint* ihint,
+                       guint                  n_param_values,
+                       const GValue*          param_values,
+                       gpointer               data)
+{
+  if (nsAccessibilityService::IsShutdown())
+    return TRUE;
+
+  GObject* object = reinterpret_cast<GObject*>(g_value_get_object(param_values));
+  if (!GTK_IS_WINDOW(object))
+    return TRUE;
+
+  AtkObject* child = gtk_widget_get_accessible(GTK_WIDGET(object));
+
+  // GTK native dialog
+  if (!IS_MAI_OBJECT(child) &&
+      (atk_object_get_role(child) == ATK_ROLE_DIALOG)) {
+
+    if (data == reinterpret_cast<gpointer>(nsIAccessibleEvent::EVENT_SHOW)) {
+
+      // Attach the dialog accessible to app accessible tree
+      nsAccessible* windowAcc = GetAccService()->AddNativeRootAccessible(child);
+      g_object_set_qdata(G_OBJECT(child), sQuark_gecko_acc_obj,
+                         reinterpret_cast<gpointer>(windowAcc));
+
+    } else {
+
+      // Deattach the dialog accessible
+      nsAccessible* windowAcc =
+        reinterpret_cast<nsAccessible*>
+                        (g_object_get_qdata(G_OBJECT(child), sQuark_gecko_acc_obj));
+      if (windowAcc) {
+        GetAccService()->RemoveNativeRootAccessible(windowAcc);
+        g_object_set_qdata(G_OBJECT(child), sQuark_gecko_acc_obj, NULL);
+      }
+
+    }
+  }
+
+  return TRUE;
+}
+
 PRBool
 nsApplicationAccessibleWrap::Init()
 {
     // XXX following code is copied from widget/src/gtk2/nsWindow.cpp
     // we should put it to somewhere that can be used from both modules
     // see bug 390761
 
     // check if accessibility enabled/disabled by environment variable
@@ -597,24 +650,44 @@ nsApplicationAccessibleWrap::Init()
         // load and initialize atk-bridge library
         rv = LoadGtkModule(sAtkBridge);
         if (NS_SUCCEEDED(rv)) {
             // init atk-bridge
             (*sAtkBridge.init)();
         }
         else
             MAI_LOG_DEBUG(("Fail to load lib: %s\n", sAtkBridge.libName));
+
+        if (!sToplevel_event_hook_added) {
+          sToplevel_event_hook_added = true;
+          sToplevel_show_hook =
+            g_signal_add_emission_hook(g_signal_lookup("show", GTK_TYPE_WINDOW),
+              0, toplevel_event_watcher,
+              reinterpret_cast<gpointer>(nsIAccessibleEvent::EVENT_SHOW), NULL);
+          sToplevel_hide_hook =
+            g_signal_add_emission_hook(g_signal_lookup("hide", GTK_TYPE_WINDOW),
+              0, toplevel_event_watcher,
+              reinterpret_cast<gpointer>(nsIAccessibleEvent::EVENT_HIDE), NULL);
+        }
     }
 
     return nsApplicationAccessible::Init();
 }
 
 void
 nsApplicationAccessibleWrap::Unload()
 {
+    if (sToplevel_event_hook_added) {
+      sToplevel_event_hook_added = false;
+      g_signal_remove_emission_hook(g_signal_lookup("show", GTK_TYPE_WINDOW),
+                                    sToplevel_show_hook);
+      g_signal_remove_emission_hook(g_signal_lookup("hide", GTK_TYPE_WINDOW),
+                                    sToplevel_hide_hook);
+    }
+
     if (sAtkBridge.lib) {
         // Do not shutdown/unload atk-bridge,
         // an exit function registered will take care of it
         // if (sAtkBridge.shutdown)
         //     (*sAtkBridge.shutdown)();
         // PR_UnloadLibrary(sAtkBridge.lib);
         sAtkBridge.lib = NULL;
         sAtkBridge.init = NULL;
@@ -666,17 +739,17 @@ struct AtkRootAccessibleAddedEvent {
 gboolean fireRootAccessibleAddedCB(gpointer data)
 {
     AtkRootAccessibleAddedEvent* eventData = (AtkRootAccessibleAddedEvent*)data;
     g_signal_emit_by_name(eventData->app_accessible, "children_changed::add",
                           eventData->index, eventData->root_accessible, NULL);
     g_object_unref(eventData->app_accessible);
     g_object_unref(eventData->root_accessible);
     free(data);
-    
+
     return FALSE;
 }
 
 PRBool
 nsApplicationAccessibleWrap::AppendChild(nsAccessible *aChild)
 {
     if (!nsApplicationAccessible::AppendChild(aChild))
       return PR_FALSE;
@@ -736,17 +809,17 @@ nsApplicationAccessibleWrap::PreCreate()
                   PR_FindFunctionSymbol(sATKLib,
                                         AtkSocketAccessible
                                           ::sATKSocketEmbedSymbol);
             AtkSocketAccessible::gCanEmbed =
               AtkSocketAccessible::g_atk_socket_type != G_TYPE_INVALID &&
               AtkSocketAccessible::g_atk_socket_embed;
             }
         }
-        sATKChecked = PR_TRUE;
+        sATKChecked = true;
     }
 }
 
 static nsresult
 LoadGtkModule(GnomeAccessibilityModule& aModule)
 {
     NS_ENSURE_ARG(aModule.libName);
 
--- a/accessible/src/atk/nsMaiInterfaceComponent.cpp
+++ b/accessible/src/atk/nsMaiInterfaceComponent.cpp
@@ -38,21 +38,16 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsMaiInterfaceComponent.h"
 
 #include "nsAccessibleWrap.h"
 #include "nsAccUtils.h"
 #include "nsCoreUtils.h"
 
-#include "nsIDOMDocument.h"
-#include "nsIDOMWindowInternal.h"
-#include "nsIDocShellTreeItem.h"
-#include "nsIInterfaceRequestorUtils.h"
-
 void
 componentInterfaceInitCB(AtkComponentIface *aIface)
 {
     NS_ASSERTION(aIface, "Invalid Interface");
     if(!aIface)
         return;
 
     /*
--- a/accessible/src/base/nsCoreUtils.cpp
+++ b/accessible/src/base/nsCoreUtils.cpp
@@ -41,19 +41,18 @@
 #include "nsIAccessibleTypes.h"
 
 #include "nsAccessNode.h"
 
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsIDOMHTMLElement.h"
-#include "nsIDOMNodeList.h"
 #include "nsIDOMRange.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIDOMXULElement.h"
 #include "nsIDocShell.h"
 #include "nsIContentViewer.h"
 #include "nsEventListenerManager.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIScrollableFrame.h"
 #include "nsEventStateManager.h"
@@ -422,22 +421,21 @@ nsCoreUtils::GetScreenCoordsForWindow(ns
   nsCOMPtr<nsIDocShellTreeItem> rootTreeItem;
   treeItem->GetRootTreeItem(getter_AddRefs(rootTreeItem));
   nsCOMPtr<nsIDOMDocument> domDoc = do_GetInterface(rootTreeItem);
   if (!domDoc)
     return coords;
 
   nsCOMPtr<nsIDOMWindow> window;
   domDoc->GetDefaultView(getter_AddRefs(window));
-  nsCOMPtr<nsIDOMWindowInternal> windowInter(do_QueryInterface(window));
-  if (!windowInter)
+  if (!window)
     return coords;
 
-  windowInter->GetScreenX(&coords.x);
-  windowInter->GetScreenY(&coords.y);
+  window->GetScreenX(&coords.x);
+  window->GetScreenY(&coords.y);
   return coords;
 }
 
 already_AddRefed<nsIDocShellTreeItem>
 nsCoreUtils::GetDocShellTreeItemFor(nsINode *aNode)
 {
   if (!aNode)
     return nsnull;
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -62,17 +62,17 @@
 #include "nsIDOMNSEvent.h"
 #include "nsIDOMXULMenuListElement.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDOMXULPopupElement.h"
 #include "nsIDocument.h"
 #include "nsEventListenerManager.h"
 #include "nsIFrame.h"
-#include "nsIMenuFrame.h"
+#include "nsMenuFrame.h"
 #include "nsIHTMLDocument.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsISelectionPrivate.h"
 #include "nsIServiceManager.h"
 #include "nsPIDOMWindow.h"
 #include "nsIWebBrowserChrome.h"
 #include "nsReadableUtils.h"
 #include "nsRootAccessible.h"
@@ -683,26 +683,23 @@ nsRootAccessible::ProcessDOMEvent(nsIDOM
   else if (eventType.EqualsLiteral("DOMMenuItemActive")) {
     PRBool fireFocus = PR_FALSE;
     if (!treeItemAccessible) {
 #ifdef MOZ_XUL
       if (isTree) {
         return; // Tree with nothing selected
       }
 #endif
-      nsIFrame* menuFrame = accessible->GetFrame();
-      if (!menuFrame)
-        return;
 
-      nsIMenuFrame* imenuFrame = do_QueryFrame(menuFrame);
-      if (imenuFrame)
+      nsMenuFrame* menuFrame = do_QueryFrame(accessible->GetFrame());
+      if (menuFrame)
         fireFocus = PR_TRUE;
-      // QI failed for nsIMenuFrame means it's not on menu bar
-      if (imenuFrame && imenuFrame->IsOnMenuBar() &&
-                       !imenuFrame->IsOnActiveMenuBar()) {
+      // QI failed for nsMenuFrame means it's not on menu bar
+      if (menuFrame && menuFrame->IsOnMenuBar() &&
+                       !menuFrame->IsOnActiveMenuBar()) {
         // It is a top level menuitem. Only fire a focus event when the menu bar
         // is active.
         return;
       } else {
         nsAccessible *containerAccessible = accessible->GetParent();
         if (!containerAccessible)
           return;
         // It is not top level menuitem
--- a/accessible/src/html/nsHTMLImageAccessible.cpp
+++ b/accessible/src/html/nsHTMLImageAccessible.cpp
@@ -174,17 +174,17 @@ nsHTMLImageAccessible::DoAction(PRUint8 
     NS_ENSURE_TRUE(element, NS_ERROR_FAILURE);
 
     nsAutoString longDesc;
     nsresult rv = element->GetLongDesc(longDesc);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsIDocument* document = mContent->GetOwnerDoc();
     nsCOMPtr<nsPIDOMWindow> piWindow = document->GetWindow();
-    nsCOMPtr<nsIDOMWindowInternal> win(do_QueryInterface(piWindow));
+    nsCOMPtr<nsIDOMWindow> win = do_QueryInterface(piWindow);
     NS_ENSURE_TRUE(win, NS_ERROR_FAILURE);
     nsCOMPtr<nsIDOMWindow> tmp;
     return win->Open(longDesc, EmptyString(), EmptyString(),
                      getter_AddRefs(tmp));
   }
   return nsLinkableAccessible::DoAction(aIndex);
 }
 
--- a/accessible/src/html/nsHTMLTableAccessible.cpp
+++ b/accessible/src/html/nsHTMLTableAccessible.cpp
@@ -506,17 +506,17 @@ nsHTMLTableAccessible::GetAttributesInte
 NS_IMETHODIMP
 nsHTMLTableAccessible::GetRelationByType(PRUint32 aRelationType,
                                          nsIAccessibleRelation **aRelation)
 {
   nsresult rv = nsAccessibleWrap::GetRelationByType(aRelationType,
                                                     aRelation);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (aRelationType == nsIAccessibleRelation::RELATION_DESCRIBED_BY)
+  if (aRelationType == nsIAccessibleRelation::RELATION_LABELLED_BY)
     return nsRelUtils::AddTarget(aRelationType, aRelation, Caption());
 
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLTableAccessible: nsIAccessibleTable implementation
 
@@ -1523,21 +1523,18 @@ nsHTMLTableAccessible::IsProbablyForLayo
 NS_IMETHODIMP
 nsHTMLCaptionAccessible::GetRelationByType(PRUint32 aRelationType,
                                            nsIAccessibleRelation **aRelation)
 {
   nsresult rv = nsHyperTextAccessible::GetRelationByType(aRelationType,
                                                          aRelation);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (aRelationType == nsIAccessibleRelation::RELATION_DESCRIPTION_FOR) {
-    nsCOMPtr<nsIAccessible> accParent;
-    GetParent(getter_AddRefs(accParent));
-    return nsRelUtils::AddTarget(aRelationType, aRelation, accParent);
-  }
+  if (aRelationType == nsIAccessibleRelation::RELATION_LABEL_FOR)
+    return nsRelUtils::AddTarget(aRelationType, aRelation, GetParent());
 
   return NS_OK;
 }
 
 PRUint32
 nsHTMLCaptionAccessible::NativeRole()
 {
   return nsIAccessibleRole::ROLE_CAPTION;
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -44,20 +44,18 @@
 #include "nsAccessibilityService.h"
 #include "nsAccUtils.h"
 #include "nsTextAttrs.h"
 
 #include "nsIClipboard.h"
 #include "nsContentCID.h"
 #include "nsIDOMCharacterData.h"
 #include "nsIDOMDocument.h"
-#include "nsPIDOMWindow.h"        
 #include "nsIDOMRange.h"
 #include "nsIDOMNSRange.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIEditingSession.h"
 #include "nsIEditor.h"
 #include "nsIFrame.h"
 #include "nsFrameSelection.h"
 #include "nsILineIterator.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIPlaintextEditor.h"
--- a/accessible/tests/mochitest/relations/test_general.html
+++ b/accessible/tests/mochitest/relations/test_general.html
@@ -97,18 +97,18 @@
       // output 'for' relations
       testRelation("output", RELATION_CONTROLLED_BY, ["input", "input2"]);
       testRelation("output2", RELATION_CONTROLLED_BY, ["input", "input2"]);
       testRelation("input", RELATION_CONTROLLER_FOR, ["output", "output2"]);
       testRelation("input2", RELATION_CONTROLLER_FOR, ["output", "output2"]);
 
       // 'described by'/'description for' relation for html:table and
       // html:caption
-      testRelation("caption", RELATION_DESCRIPTION_FOR, "table");
-      testRelation("table", RELATION_DESCRIBED_BY, "caption");
+      testRelation("caption", RELATION_LABEL_FOR, "table");
+      testRelation("table", RELATION_LABELLED_BY, "caption");
 
       // 'labelled by'/'label for' relation for html:fieldset and
       // html:legend
       testRelation("legend", RELATION_LABEL_FOR, "fieldset");
       testRelation("fieldset", RELATION_LABELLED_BY, "legend");
 
       // 'embeds' relation for root accessible
       var docAcc = null;
deleted file mode 100644
--- a/browser/app/README.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-For information about installing, running and configuring Firefox 
-including a list of known issues and troubleshooting information, 
-refer to: http://getfirefox.com/releases/
-
--- a/browser/app/blocklist.xml
+++ b/browser/app/blocklist.xml
@@ -1,193 +1,201 @@
 <?xml version="1.0"?>
-<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist">
+<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist" lastupdate="1306529826000">
   <emItems>
-    <emItem id="fdm_ffext@freedownloadmanager.org">
-      <versionRange minVersion="1.0" maxVersion="1.3.1">
-        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-           <versionRange minVersion="3.0a1" maxVersion="*"/>
-        </targetApplication>
-      </versionRange>
-    </emItem>
-    <emItem id="firefox@bandoo.com">
-      <versionRange minVersion="5.0" maxVersion="5.0" severity="1">
-        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-           <versionRange minVersion="3.7a1pre" maxVersion="*"/>
-        </targetApplication>
-      </versionRange>
-    </emItem>
-    <emItem id="langpack-vi-VN@firefox.mozilla.org">
-      <versionRange minVersion="2.0" maxVersion="2.0"/>
-    </emItem>
-    <emItem id="masterfiler@gmail.com">
-      <versionRange severity="3"/>
-    </emItem>
-    <emItem id="mozilla_cc@internetdownloadmanager.com">
-      <versionRange minVersion=" " maxVersion="6.9.8">
-        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-           <versionRange minVersion="3.7a1pre" maxVersion="*"/>
-        </targetApplication>
-      </versionRange>
-      <versionRange minVersion="2.1" maxVersion="3.3">
-        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-           <versionRange minVersion="3.0a1" maxVersion="*"/>
-        </targetApplication>
-      </versionRange>
-    </emItem>
-    <emItem id="msntoolbar@msn.com">
-      <versionRange minVersion=" " maxVersion="6.*"/>
-    </emItem>
-    <emItem id="personas@christopher.beard">
-      <versionRange minVersion="1.6" maxVersion="1.6">
-        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-           <versionRange minVersion="3.6" maxVersion="3.6.*"/>
-        </targetApplication>
-      </versionRange>
-    </emItem>
-    <emItem id="ShopperReports@ShopperReports.com">
-      <versionRange minVersion="3.1.22.0" maxVersion="3.1.22.0"/>
-    </emItem>
-    <emItem id="support@daemon-tools.cc">
-      <versionRange minVersion=" " maxVersion="1.0.0.5"/>
-    </emItem>
-    <emItem id="support@update-firefox.com"/>
-    <emItem id="yslow@yahoo-inc.com">
-      <versionRange minVersion="2.0.5" maxVersion="2.0.5">
-        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-           <versionRange minVersion="3.5.7" maxVersion="*"/>
-        </targetApplication>
-      </versionRange>
-    </emItem>
-    <emItem id="{2224e955-00e9-4613-a844-ce69fccaae91}"/>
-    <emItem id="{27182e60-b5f3-411c-b545-b44205977502}">
-      <versionRange minVersion="1.0" maxVersion="1.0"/>
-    </emItem>
-    <emItem id="{3252b9ae-c69a-4eaf-9502-dc9c1f6c009e}">
-      <versionRange minVersion="2.2" maxVersion="2.2"/>
-    </emItem>
-    <emItem id="{3f963a5b-e555-4543-90e2-c3908898db71}">
-      <versionRange minVersion=" " maxVersion="8.5"/>
-    </emItem>
-    <emItem id="{46551EC9-40F0-4e47-8E18-8E5CF550CFB8}">
-      <versionRange minVersion="1.1b1" maxVersion="1.1b1"/>
-    </emItem>
-    <emItem id="{4B3803EA-5230-4DC3-A7FC-33638F3D3542}">
-      <versionRange minVersion="1.2" maxVersion="1.2">
-        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-           <versionRange minVersion="3.0a1" maxVersion="*"/>
-        </targetApplication>
-      </versionRange>
-    </emItem>
-    <emItem id="{6E19037A-12E3-4295-8915-ED48BC341614}">
-      <versionRange minVersion="0.1" maxVersion="1.3.328.4" severity="1">
-        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-           <versionRange minVersion="3.7a1pre" maxVersion="*"/>
-        </targetApplication>
-      </versionRange>
-    </emItem>
-    <emItem id="{8CE11043-9A15-4207-A565-0C94C42D590D}"/>
-    <emItem id="{AB2CE124-6272-4b12-94A9-7303C7397BD1}">
-      <versionRange minVersion="0.1" maxVersion="5.2.0.7164" severity="1"/>
-    </emItem>
-    <emItem id="{B13721C7-F507-4982-B2E5-502A71474FED}">
-      <versionRange severity="1"/>
-    </emItem>
-    <emItem id="{B7082FAA-CB62-4872-9106-E42DD88EDE45}">
-      <versionRange minVersion="0.1" maxVersion="3.3.0.*">
-        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-           <versionRange minVersion="3.7a1" maxVersion="*"/>
-        </targetApplication>
-      </versionRange>
-      <versionRange minVersion="3.3.1" maxVersion="*">
-        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-           <versionRange minVersion="5.0a1" maxVersion="*"/>
-        </targetApplication>
-      </versionRange>
-    </emItem>
-    <emItem id="{E8E88AB0-7182-11DF-904E-6045E0D72085}"/>
-  </emItems>
-<pluginItems>
-  <pluginItem>
-    <match name="name" exp="^Yahoo Application State Plugin$"/>
-    <match name="description" exp="^Yahoo Application State Plugin$"/>
-    <match name="filename" exp="npYState.dll"/>
-    <versionRange>
-      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-        <versionRange minVersion="3.0a1" maxVersion="3.*"/>
-      </targetApplication>
-    </versionRange>
-  </pluginItem>
-  <pluginItem>
-    <match name="name" exp="QuickTime Plug-in 7[.]1[.]"/>
-    <match name="filename" exp="npqtplugin.?[.]dll"/>
-    <versionRange>
-      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-        <versionRange minVersion="3.0a1" maxVersion="3.*"/>
-      </targetApplication>
-    </versionRange>
-  </pluginItem>
-  <pluginItem>
-    <match name="filename" exp="NPFFAddOn.dll"/>
-    <versionRange>
-    </versionRange>
-  </pluginItem>
-  <pluginItem>
-    <match name="filename" exp="NPMySrch.dll"/>
-    <versionRange>
-    </versionRange>
-  </pluginItem>
-  <pluginItem>
-    <match name="filename" exp="npViewpoint.dll"/>
-    <versionRange>
-      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-        <versionRange minVersion="3.0" maxVersion="*"/>
-      </targetApplication>
-    </versionRange>
-  </pluginItem>
-  <pluginItem>
-    <match name="name" exp="[0-6]\.0\.[01]\d{2}\.\d+"/>
-    <match name="filename" exp="npdeploytk.dll"/>
-    <versionRange severity="1">
-    </versionRange>
-  </pluginItem>
-  <pluginItem>
-    <match name="filename" exp="[Nn][Pp][Jj][Pp][Ii]1[56]0_[0-9]+\.[Dd][Ll][Ll]"/>
-    <versionRange>
-      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-        <versionRange minVersion="3.6a1pre" maxVersion="*"/>
-      </targetApplication>
-    </versionRange>
-  </pluginItem>
-</pluginItems>
-<gfxItems>
-  <gfxBlacklistEntry>
-    <os>WINNT 6.1</os>
-    <vendor>0x10de</vendor>
-    <devices>
-      <device>0x0a6c</device>
-    </devices>
-    <feature>DIRECT2D</feature>
-    <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus>
-    <driverVersion>8.17.12.5896</driverVersion>
-    <driverVersionComparator>LESS_THAN_OR_EQUAL</driverVersionComparator>
-  </gfxBlacklistEntry>
-  <gfxBlacklistEntry>
-    <os>WINNT 6.1</os>
-    <vendor>0x10de</vendor>
-    <devices>
-      <device>0x0a6c</device>
-    </devices>
-    <feature>DIRECT3D_9_LAYERS</feature>
-    <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus>
-    <driverVersion>8.17.12.5896</driverVersion>
-    <driverVersionComparator>LESS_THAN_OR_EQUAL</driverVersionComparator>
-  </gfxBlacklistEntry>
-  <gfxBlacklistEntry>
-    <os>WINNT 5.1</os>
-    <vendor>0x10de</vendor>
-    <feature>DIRECT3D_9_LAYERS</feature>
-    <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus>
-    <driverVersion>7.0.0.0</driverVersion>
-    <driverVersionComparator>GREATER_THAN_OR_EQUAL</driverVersionComparator>
-  </gfxBlacklistEntry>
-</gfxItems>
-</blocklist>
+      <emItem  blockID="i8" id="{B13721C7-F507-4982-B2E5-502A71474FED}">
+                        <versionRange  minVersion=" " severity="1">
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i38" id="{B7082FAA-CB62-4872-9106-E42DD88EDE45}">
+                        <versionRange  minVersion="0.1" maxVersion="3.3.0.*">
+                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+                              <versionRange  minVersion="3.7a1" maxVersion="*" />
+                          </targetApplication>
+                    </versionRange>
+                                <versionRange  minVersion="3.3.1" maxVersion="*">
+                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+                              <versionRange  minVersion="5.0a1" maxVersion="*" />
+                          </targetApplication>
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i19" id="{46551EC9-40F0-4e47-8E18-8E5CF550CFB8}">
+                        <versionRange  minVersion="1.1b1" maxVersion="1.1b1">
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i16" id="{27182e60-b5f3-411c-b545-b44205977502}">
+                        <versionRange  minVersion="1.0" maxVersion="1.0">
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i10" id="{8CE11043-9A15-4207-A565-0C94C42D590D}">
+                        </emItem>
+      <emItem  blockID="i1" id="mozilla_cc@internetdownloadmanager.com">
+                        <versionRange  minVersion="2.1" maxVersion="3.3">
+                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+                              <versionRange  minVersion="3.0a1" maxVersion="*" />
+                          </targetApplication>
+                    </versionRange>
+                                <versionRange  minVersion=" " maxVersion="6.9.8">
+                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+                              <versionRange  minVersion="3.7a1pre" maxVersion="*" />
+                          </targetApplication>
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i18" id="msntoolbar@msn.com">
+                        <versionRange  minVersion=" " maxVersion="6.*">
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i13" id="{E8E88AB0-7182-11DF-904E-6045E0D72085}">
+                        </emItem>
+      <emItem  blockID="i4" id="{4B3803EA-5230-4DC3-A7FC-33638F3D3542}">
+                        <versionRange  minVersion="1.2" maxVersion="1.2">
+                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+                              <versionRange  minVersion="3.0a1" maxVersion="*" />
+                          </targetApplication>
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i23" id="firefox@bandoo.com">
+                        <versionRange  minVersion="5.0" maxVersion="5.0" severity="1">
+                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+                              <versionRange  minVersion="3.7a1pre" maxVersion="*" />
+                          </targetApplication>
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i22" id="ShopperReports@ShopperReports.com">
+                        <versionRange  minVersion="3.1.22.0" maxVersion="3.1.22.0">
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i2" id="fdm_ffext@freedownloadmanager.org">
+                        <versionRange  minVersion="1.0" maxVersion="1.3.1">
+                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+                              <versionRange  minVersion="3.0a1" maxVersion="*" />
+                          </targetApplication>
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i5" id="support@daemon-tools.cc">
+                        <versionRange  minVersion=" " maxVersion="1.0.0.5">
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i6" id="{3f963a5b-e555-4543-90e2-c3908898db71}">
+                        <versionRange  minVersion=" " maxVersion="8.5">
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i12" id="masterfiler@gmail.com">
+                        <versionRange  severity="3">
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i20" id="{AB2CE124-6272-4b12-94A9-7303C7397BD1}">
+                        <versionRange  minVersion="0.1" maxVersion="5.2.0.7164" severity="1">
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i11" id="yslow@yahoo-inc.com">
+                        <versionRange  minVersion="2.0.5" maxVersion="2.0.5">
+                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+                              <versionRange  minVersion="3.5.7" maxVersion="*" />
+                          </targetApplication>
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i17" id="{3252b9ae-c69a-4eaf-9502-dc9c1f6c009e}">
+                        <versionRange  minVersion="2.2" maxVersion="2.2">
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i3" id="langpack-vi-VN@firefox.mozilla.org">
+                        <versionRange  minVersion="2.0" maxVersion="2.0">
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i7" id="{2224e955-00e9-4613-a844-ce69fccaae91}">
+                        </emItem>
+      <emItem  blockID="i24" id="{6E19037A-12E3-4295-8915-ED48BC341614}">
+                        <versionRange  minVersion="0.1" maxVersion="1.3.328.4" severity="1">
+                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+                              <versionRange  minVersion="3.7a1pre" maxVersion="*" />
+                          </targetApplication>
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i15" id="personas@christopher.beard">
+                        <versionRange  minVersion="1.6" maxVersion="1.6">
+                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+                              <versionRange  minVersion="3.6" maxVersion="3.6.*" />
+                          </targetApplication>
+                    </versionRange>
+                  </emItem>
+      <emItem  blockID="i21" id="support@update-firefox.com">
+                        </emItem>
+    </emItems>
+
+  <pluginItems>
+      <pluginItem  blockID="p26">
+      <match name="name" exp="^Yahoo Application State Plugin$" />      <match name="description" exp="^Yahoo Application State Plugin$" />      <match name="filename" exp="npYState.dll" />              <versionRange >
+                      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+              <versionRange  minVersion="3.0a1" maxVersion="3.*" />
+            </targetApplication>
+                  </versionRange>
+          </pluginItem>
+      <pluginItem  blockID="p27">
+      <match name="name" exp="QuickTime Plug-in 7[.]1[.]" />            <match name="filename" exp="npqtplugin.?[.]dll" />              <versionRange >
+                      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+              <versionRange  minVersion="3.0a1" maxVersion="3.*" />
+            </targetApplication>
+                  </versionRange>
+          </pluginItem>
+      <pluginItem  blockID="p28">
+                  <match name="filename" exp="NPFFAddOn.dll" />              <versionRange >
+                  </versionRange>
+          </pluginItem>
+      <pluginItem  blockID="p31">
+                  <match name="filename" exp="NPMySrch.dll" />              <versionRange >
+                  </versionRange>
+          </pluginItem>
+      <pluginItem  blockID="p32">
+                  <match name="filename" exp="npViewpoint.dll" />              <versionRange >
+                      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+              <versionRange  minVersion="3.0" maxVersion="*" />
+            </targetApplication>
+                  </versionRange>
+          </pluginItem>
+      <pluginItem  blockID="p33">
+      <match name="name" exp="[0-6]\.0\.[01]\d{2}\.\d+" />            <match name="filename" exp="npdeploytk.dll" />              <versionRange  severity="1">
+                  </versionRange>
+          </pluginItem>
+      <pluginItem  blockID="p34">
+                  <match name="filename" exp="[Nn][Pp][Jj][Pp][Ii]1[56]0_[0-9]+\.[Dd][Ll][Ll]" />              <versionRange >
+                      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+              <versionRange  minVersion="3.6a1pre" maxVersion="*" />
+            </targetApplication>
+                  </versionRange>
+          </pluginItem>
+    </pluginItems>
+
+  <gfxItems>
+    <gfxBlacklistEntry  blockID="g35">
+      <os>WINNT 6.1</os>
+      <vendor>0x10de</vendor>
+              <devices>
+                      <device>0x0a6c</device>
+                  </devices>
+            <feature>DIRECT2D</feature>
+      <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus>
+      <driverVersion>8.17.12.5896</driverVersion>
+      <driverVersionComparator>LESS_THAN_OR_EQUAL</driverVersionComparator>
+    </gfxBlacklistEntry>
+    <gfxBlacklistEntry  blockID="g36">
+      <os>WINNT 6.1</os>
+      <vendor>0x10de</vendor>
+              <devices>
+                      <device>0x0a6c</device>
+                  </devices>
+            <feature>DIRECT3D_9_LAYERS</feature>
+      <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus>
+      <driverVersion>8.17.12.5896</driverVersion>
+      <driverVersionComparator>LESS_THAN_OR_EQUAL</driverVersionComparator>
+    </gfxBlacklistEntry>
+    <gfxBlacklistEntry  blockID="g37">
+      <os>WINNT 5.1</os>
+      <vendor>0x10de</vendor>
+            <feature>DIRECT3D_9_LAYERS</feature>
+      <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus>
+      <driverVersion>7.0.0.0</driverVersion>
+      <driverVersionComparator>GREATER_THAN_OR_EQUAL</driverVersionComparator>
+    </gfxBlacklistEntry>
+    </gfxItems>
+
+
+</blocklist>
\ No newline at end of file
old mode 100755
new mode 100644
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -562,17 +562,17 @@ pref("accessibility.typeaheadfind.flashB
 // plugin finder service url
 pref("pfs.datasource.url", "https://pfs.mozilla.org/plugins/PluginFinderService.php?mimetype=%PLUGIN_MIMETYPE%&appID=%APP_ID%&appVersion=%APP_VERSION%&clientOS=%CLIENT_OS%&chromeLocale=%CHROME_LOCALE%&appRelease=%APP_RELEASE%");
 
 // by default we show an infobar message when pages require plugins the user has not installed, or are outdated
 pref("plugins.hide_infobar_for_missing_plugin", false);
 pref("plugins.hide_infobar_for_outdated_plugin", false);
 
 #ifdef XP_MACOSX
-pref("plugins.use_layers", false);
+pref("plugins.use_layers", true);
 pref("plugins.hide_infobar_for_carbon_failure_plugin", false);
 #endif
 
 pref("plugins.update.url", "https://www.mozilla.com/%LOCALE%/plugincheck/");
 pref("plugins.update.notifyUser", false);
 
 #ifdef XP_WIN
 pref("browser.preferences.instantApply", false);
@@ -895,16 +895,20 @@ pref("dom.ipc.plugins.enabled.i386.flash
 pref("dom.ipc.plugins.enabled.i386.javaplugin2_npapi.plugin", true);
 pref("dom.ipc.plugins.enabled.i386.javaappletplugin.plugin", true);
 // x86_64 ipc preferences
 pref("dom.ipc.plugins.enabled.x86_64", true);
 #else
 pref("dom.ipc.plugins.enabled", true);
 #endif
 
+#ifdef MOZ_E10S_COMPAT
+pref("browser.tabs.remote", true);
+#endif
+
 // This pref governs whether we attempt to work around problems caused by
 // plugins using OS calls to manipulate the cursor while running out-of-
 // process.  These workarounds all involve intercepting (hooking) certain
 // OS calls in the plugin process, then arranging to make certain OS calls
 // in the browser process.  Eventually plugins will be required to use the
 // NPAPI to manipulate the cursor, and these workarounds will be removed.
 // See bug 621117.
 #ifdef XP_MACOSX
--- a/browser/base/content/browser-tabPreviews.js
+++ b/browser/base/content/browser-tabPreviews.js
@@ -590,16 +590,17 @@ var allTabs = {
   get container () {
     delete this.container;
     return this.container = document.getElementById("allTabs-container");
   },
   get tabCloseButton () {
     delete this.tabCloseButton;
     return this.tabCloseButton = document.getElementById("allTabs-tab-close-button");
   },
+  get toolbarButton() document.getElementById("alltabs-button"),
   get previews () this.container.getElementsByClassName("allTabs-preview"),
   get isOpen () this.panel.state == "open" || this.panel.state == "showing",
 
   init: function allTabs_init() {
     if (this._initiated)
       return;
     this._initiated = true;
 
@@ -627,17 +628,17 @@ var allTabs = {
     while (this.container.hasChildNodes())
       this.container.removeChild(this.container.firstChild);
 
     this._initiated = false;
   },
 
   prefName: "browser.allTabs.previews",
   readPref: function allTabs_readPref() {
-    var allTabsButton = document.getElementById("alltabs-button");
+    var allTabsButton = this.toolbarButton;
     if (!allTabsButton)
       return;
 
     if (gPrefService.getBoolPref(this.prefName)) {
       allTabsButton.removeAttribute("type");
       allTabsButton.setAttribute("command", "Browser:ShowAllTabs");
     } else {
       allTabsButton.setAttribute("type", "menu");
@@ -692,16 +693,27 @@ var allTabs = {
         preview.hidden = false;
       }
     }, this);
 
     this._reflow();
   },
 
   open: function allTabs_open() {
+    var allTabsButton = this.toolbarButton;
+    if (allTabsButton &&
+        allTabsButton.getAttribute("type") == "menu") {
+      // Without setTimeout, the menupopup won't stay open when invoking
+      // "View > Show All Tabs" and the menu bar auto-hides.
+      setTimeout(function () {
+        allTabsButton.open = true;
+      }, 0);
+      return;
+    }
+
     this.init();
 
     if (this.isOpen)
       return;
 
     this._maxPanelHeight = Math.max(gBrowser.clientHeight, screen.availHeight / 2);
     this._maxPanelWidth = Math.max(gBrowser.clientWidth, screen.availWidth / 2);
 
--- a/browser/base/content/browser-tabview.js
+++ b/browser/base/content/browser-tabview.js
@@ -430,12 +430,17 @@ let TabView = {
       return;
 
     // do nothing if we already enabled session restore once
     if (this.sessionRestoreEnabledOnce)
       return;
 
     this.sessionRestoreEnabledOnce = true;
 
-    // enable session restore
-    Services.prefs.setIntPref(this.PREF_STARTUP_PAGE, 3);
+    // enable session restore if necessary
+    if (Services.prefs.getIntPref(this.PREF_STARTUP_PAGE) != 3) {
+      Services.prefs.setIntPref(this.PREF_STARTUP_PAGE, 3);
+
+      // show banner
+      this._window.UI.notifySessionRestoreEnabled();
+    }
   }
 };
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -495,8 +495,11 @@ statuspanel[label=""] {
   height: 3em;
   width: 100%;
   -moz-box-align: end;
 }
 
 .panel-inner-arrowcontentfooter[footertype="promobox"] {
   -moz-binding: url("chrome://browser/content/urlbarBindings.xml#promobox");
 }
+
+/* highlighter */
+%include highlighter.css
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -1410,16 +1410,18 @@ function prepareForStartup() {
     if (!webNavigation)
       throw "no XBL binding for browser";
   } catch (e) {
     alert("Error launching browser window:" + e);
     window.close(); // Give up.
     return;
   }
 
+  messageManager.loadFrameScript("chrome://browser/content/content.js", true);
+
   // initialize observers and listeners
   // and give C++ access to gBrowser
   gBrowser.init();
   XULBrowserWindow.init();
   window.QueryInterface(Ci.nsIInterfaceRequestor)
         .getInterface(nsIWebNavigation)
         .QueryInterface(Ci.nsIDocShellTreeItem).treeOwner
         .QueryInterface(Ci.nsIInterfaceRequestor)
@@ -1454,19 +1456,23 @@ function prepareForStartup() {
 
   // enable global history
   try {
     gBrowser.docShell.QueryInterface(Components.interfaces.nsIDocShellHistory).useGlobalHistory = true;
   } catch(ex) {
     Components.utils.reportError("Places database may be locked: " + ex);
   }
 
+#ifdef MOZ_E10S_COMPAT
+  // Bug 666801 - WebProgress support for e10s
+#else
   // hook up UI through progress listener
   gBrowser.addProgressListener(window.XULBrowserWindow);
   gBrowser.addTabsProgressListener(window.TabsProgressListener);
+#endif
 
   // setup our common DOMLinkAdded listener
   gBrowser.addEventListener("DOMLinkAdded", DOMLinkHandler, false);
 
   // setup our MozApplicationManifest listener
   gBrowser.addEventListener("MozApplicationManifest",
                             OfflineApps, false);
 
@@ -1578,19 +1584,23 @@ function delayedStartup(isLoadingBlank, 
   // apply full zoom settings to tabs restored by the session restore service.
   try {
     FullZoom.init();
   }
   catch(ex) {
     Components.utils.reportError("Failed to init content pref service:\n" + ex);
   }
 
+#ifdef MOZ_E10S_COMPAT
+  // Bug 666804 - NetworkPrioritizer support for e10s
+#else
   let NP = {};
   Cu.import("resource:///modules/NetworkPrioritizer.jsm", NP);
   NP.trackBrowserWindow(window);
+#endif
 
   // initialize the session-restore service (in case it's not already running)
   try {
     Cc["@mozilla.org/browser/sessionstore;1"]
       .getService(Ci.nsISessionStore)
       .init(window);
   } catch (ex) {
     dump("nsSessionStore could not be initialized: " + ex + "\n");
@@ -1631,18 +1641,22 @@ function delayedStartup(isLoadingBlank, 
   placesContext.addEventListener("popupshowing", updateEditUIVisibility, false);
   placesContext.addEventListener("popuphiding", updateEditUIVisibility, false);
 #endif
 
   gBrowser.mPanelContainer.addEventListener("InstallBrowserTheme", LightWeightThemeWebInstaller, false, true);
   gBrowser.mPanelContainer.addEventListener("PreviewBrowserTheme", LightWeightThemeWebInstaller, false, true);
   gBrowser.mPanelContainer.addEventListener("ResetBrowserThemePreview", LightWeightThemeWebInstaller, false, true);
 
+#ifdef MOZ_E10S_COMPAT
+  // Bug 666808 - AeroPeek support for e10s
+#else
   if (Win7Features)
     Win7Features.onOpenWindow();
+#endif
 
   // called when we go into full screen, even if it is
   // initiated by a web page script
   window.addEventListener("fullscreen", onFullScreen, true);
   if (window.fullScreen)
     onFullScreen();
 
 #ifdef MOZ_SERVICES_SYNC
@@ -4152,21 +4166,25 @@ var XULBrowserWindow = {
     delete this._uriFixup;
     return this._uriFixup = Cc["@mozilla.org/docshell/urifixup;1"]
                               .getService(Ci.nsIURIFixup);
   },
 
   init: function () {
     this.throbberElement = document.getElementById("navigator-throbber");
 
+#ifdef MOZ_E10S_COMPAT
+    // Bug 666809 - SecurityUI support for e10s
+#else
     // Initialize the security button's state and tooltip text.  Remember to reset
     // _hostChanged, otherwise onSecurityChange will short circuit.
     var securityUI = gBrowser.securityUI;
     this._hostChanged = true;
     this.onSecurityChange(null, null, securityUI.state);
+#endif
   },
 
   destroy: function () {
     // XXXjag to avoid leaks :-/, see bug 60729
     delete this.throbberElement;
     delete this.stopCommand;
     delete this.reloadCommand;
     delete this.statusTextField;
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -1019,20 +1019,14 @@
       <svg:rect x="6" y="1" width="5" height="5" fill="white"/>
       <svg:circle cx="11" cy="6" r="5"/>
       <svg:rect x="0" y="0" width="12" height="1" fill="white"/>
     </svg:mask>
   </svg:svg>
 #endif
 
 </vbox>
-# <iframe id="highlighter-frame"
-#   transparent="true"
-#   type="content"
-#   src="chrome://content/base/highlighter.html"/> is dynamically appended as
-#     the last child of #tab-view-deck, only when it is needed, for minimal
-#     performance impact.
 # <iframe id="tab-view"> is dynamically appended as the 2nd child of #tab-view-deck.
 #     Introducing the iframe dynamically, as needed, was found to be better than
 #     starting with an empty iframe here in browser.xul from a Ts standpoint.
 </deck>
 
 </window>
new file mode 100644
--- /dev/null
+++ b/browser/base/content/content.js
@@ -0,0 +1,53 @@
+# -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is multi-process front-end code.
+#
+# The Initial Developer of the Original Code is
+# the Mozilla Foundation
+# Portions created by the Initial Developer are Copyright (C) 2011
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#   Felipe Gomes <felipc@gmail.com>
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either the GNU General Public License Version 2 or later (the "GPL"), or
+# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const Cu = Components.utils;
+
+// Bug 671101 - directly using webNavigation in this context
+// causes docshells to leak
+__defineGetter__("webNavigation", function() {
+  return docShell.QueryInterface(Ci.nsIWebNavigation);
+});
+
+addMessageListener("WebNavigation:LoadURI", function(message) {
+  let flags = message.json.flags || webNavigation.LOAD_FLAGS_NONE;
+
+  webNavigation.loadURI(message.json.uri, flags, null, null, null);
+});
new file mode 100644
--- /dev/null
+++ b/browser/base/content/highlighter.css
@@ -0,0 +1,36 @@
+#highlighter-container {
+  pointer-events: none;
+}
+
+#highlighter-controls {
+  position: absolute;
+  top: 0;
+  left: 0;
+}
+
+#highlighter-veil-container {
+  overflow: hidden;
+}
+
+.highlighter-veil,
+#highlighter-veil-middlebox,
+#highlighter-veil-transparentbox {
+  -moz-transition-property: width, height;
+  -moz-transition-duration: 0.1s;
+  -moz-transition-timing-function: linear;
+}
+
+#highlighter-veil-bottombox,
+#highlighter-veil-rightbox {
+  -moz-box-flex: 1;
+}
+
+#highlighter-veil-middlebox:-moz-locale-dir(rtl) {
+  -moz-box-direction: reverse;
+}
+
+#highlighter-close-button {
+  position: absolute;
+  pointer-events: auto;
+  z-index: 1;
+}
deleted file mode 100644
--- a/browser/base/content/highlighter.xhtml
+++ /dev/null
@@ -1,63 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE html>
-<!-- ***** BEGIN LICENSE BLOCK *****
-   - Version: MPL 1.1/GPL 2.0/LGPL 2.1
-   -
-   - The contents of this file are subject to the Mozilla Public License Version
-   - 1.1 (the "License"); you may not use this file except in compliance with
-   - the License. You may obtain a copy of the License at
-   - http://www.mozilla.org/MPL/
-   -
-   - Software distributed under the License is distributed on an "AS IS" basis,
-   - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-   - for the specific language governing rights and limitations under the
-   - License.
-   -
-   - The Original Code is Inspector Highlighter code.
-   -
-   - The Initial Developer of the Original Code is The Mozilla Foundation.
-   - Portions created by the Initial Developer are Copyright (C) 2011
-   - the Initial Developer. All Rights Reserved.
-   -
-   - Contributor(s):
-   -   Rob Campbell <rcampbell@mozilla.com> (Original Author)
-   -   Paul Rouget <paul@mozilla.com>
-   -
-   - Alternatively, the contents of this file may be used under the terms of
-   - either the GNU General Public License Version 2 or later (the "GPL"), or
-   - the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-   - in which case the provisions of the GPL or the LGPL are applicable instead
-   - of those above. If you wish to allow use of your version of this file only
-   - under the terms of either the GPL or the LGPL, and not to allow others to
-   - use your version of this file under the terms of the MPL, indicate your
-   - decision by deleting the provisions above and replace them with the notice
-   - and other provisions required by the LGPL or the GPL. If you do not delete
-   - the provisions above, a recipient may use your version of this file under
-   - the terms of any one of the MPL, the GPL or the LGPL.
-   -
-   - ***** END LICENSE BLOCK ***** -->
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-  <link rel="stylesheet" href="chrome://browser/skin/highlighter.css" type="text/css"/>
-</head>
-<body>
-<div id="close-button" role="button" class="clickable"/>
-
-<!--
-    To darken the page around the selected node, we use black-transparent
-    divs, organized in 3 rows, keeping the div in the middle transparent.
--->
-<div id="veil-container">
-  <div id="veil">
-    <div id="veil-topbox" class="veil"/>
-    <div id="veil-middlebox">
-      <div id="veil-leftbox" class="veil"/>
-      <div id="veil-transparentbox"/>
-      <div id="veil-rightbox" class="veil"/>
-    </div>
-    <div id="veil-bottombox" class="veil"/>
-  </div>
-</div>
-
-</body>
-</html>
--- a/browser/base/content/inspector.js
+++ b/browser/base/content/inspector.js
@@ -53,114 +53,178 @@ const INSPECTOR_INVISIBLE_ELEMENTS = {
   "meta": true,
   "script": true,
   "style": true,
   "title": true,
 };
 
 // Inspector notifications dispatched through the nsIObserverService.
 const INSPECTOR_NOTIFICATIONS = {
-  // Fires once the Inspector highlighter is initialized and ready for use.
-  HIGHLIGHTER_READY: "highlighter-ready",
-
   // Fires once the Inspector highlights an element in the page.
   HIGHLIGHTING: "inspector-highlighting",
 
   // Fires once the Inspector stops highlighting any element.
   UNHIGHLIGHTING: "inspector-unhighlighting",
 
   // Fires once the Inspector completes the initialization and opens up on
   // screen.
   OPENED: "inspector-opened",
 
   // Fires once the Inspector is closed.
   CLOSED: "inspector-closed",
 };
 
 ///////////////////////////////////////////////////////////////////////////
-//// IFrameHighlighter
+//// Highlighter
 
 /**
- * A highlighter mechanism using a transparent xul iframe.
+ * A highlighter mechanism.
+ *
+ * The highlighter is built dynamically once the Inspector is invoked:
+ * <stack id="highlighter-container">
+ *   <vbox id="highlighter-veil-container">...</vbox>
+ *   <box id="highlighter-controls>...</vbox>
+ * </stack>
  *
  * @param nsIDOMNode aBrowser
  *        The xul:browser object for the content window being highlighted.
  */
-function IFrameHighlighter(aBrowser)
+function Highlighter(aBrowser)
 {
   this._init(aBrowser);
 }
 
-IFrameHighlighter.prototype = {
+Highlighter.prototype = {
 
-  _init: function IFH__init(aBrowser)
+  _init: function Highlighter__init(aBrowser)
   {
     this.browser = aBrowser;
     let stack = this.browser.parentNode;
     this.win = this.browser.contentWindow;
     this._highlighting = false;
 
-    let div = document.createElement("div");
-    div.flex = 1;
-    div.setAttribute("style", "pointer-events: none; -moz-user-focus: ignore");
+    this.highlighterContainer = document.createElement("stack");
+    this.highlighterContainer.id = "highlighter-container";
+
+    let veilBox = document.createElement("vbox");
+    veilBox.id = "highlighter-veil-container";
+
+    let controlsBox = document.createElement("box");
+    controlsBox.id = "highlighter-controls";
+
+    // The veil will make the whole page darker except
+    // for the region of the selected box.
+    this.buildVeil(veilBox);
 
-    let iframe = document.createElement("iframe");
-    iframe.setAttribute("id", "highlighter-frame");
-    iframe.setAttribute("transparent", "true");
-    iframe.setAttribute("type", "content");
-    iframe.addEventListener("DOMTitleChanged", function(aEvent) {
-      aEvent.stopPropagation();
-    }, true);
-    iframe.flex = 1;
-    iframe.setAttribute("style", "-moz-user-focus: ignore");
+    // The controlsBox will host the different interactive
+    // elements of the highlighter (buttons, toolbars, ...).
+    this.buildControls(controlsBox);
+
+    this.highlighterContainer.appendChild(veilBox);
+    this.highlighterContainer.appendChild(controlsBox);
 
-    this.listenOnce(iframe, "load", (function iframeLoaded() {
-      this.iframeDoc = iframe.contentDocument;
+    stack.appendChild(this.highlighterContainer);
+
+    this.browser.addEventListener("resize", this, true);
+    this.browser.addEventListener("scroll", this, true);
+
+    this.handleResize();
+  },
+
 
-      this.veilTopDiv = this.iframeDoc.getElementById("veil-topbox");
-      this.veilLeftDiv = this.iframeDoc.getElementById("veil-leftbox");
-      this.veilMiddleDiv = this.iframeDoc.getElementById("veil-middlebox");
-      this.veilTransparentDiv = this.iframeDoc.getElementById("veil-transparentbox");
+  /**
+   * Build the veil:
+   *
+   * <vbox id="highlighter-veil-container">
+   *   <box id="highlighter-veil-topbox" class="highlighter-veil"/>
+   *   <hbox id="highlighter-veil-middlebox">
+   *     <box id="highlighter-veil-leftbox" class="highlighter-veil"/>
+   *     <box id="highlighter-veil-transparentbox"/>
+   *     <box id="highlighter-veil-rightbox" class="highlighter-veil"/>
+   *   </hbox>
+   *   <box id="highlighter-veil-bottombox" class="highlighter-veil"/>
+   * </vbox>
+   *
+   * @param nsIDOMNode aParent
+   */
+  buildVeil: function Highlighter_buildVeil(aParent)
+  {
 
-      let closeButton = this.iframeDoc.getElementById("close-button");
-      this.listenOnce(closeButton, "click",
-        InspectorUI.closeInspectorUI.bind(InspectorUI, false), false);
+    // We will need to resize these boxes to surround a node.
+    // See highlightRectangle().
+
+    this.veilTopBox = document.createElement("box");
+    this.veilTopBox.id = "highlighter-veil-topbox";
+    this.veilTopBox.className = "highlighter-veil";
 
-      this.browser.addEventListener("click", this, true);
-      iframe.contentWindow.addEventListener("resize", this, false);
-      this.handleResize();
-      Services.obs.notifyObservers(null,
-        INSPECTOR_NOTIFICATIONS.HIGHLIGHTER_READY, null);
-    }).bind(this), true);
+    this.veilMiddleBox = document.createElement("hbox");
+    this.veilMiddleBox.id = "highlighter-veil-middlebox";
+
+    this.veilLeftBox = document.createElement("box");
+    this.veilLeftBox.id = "highlighter-veil-leftbox";
+    this.veilLeftBox.className = "highlighter-veil";
+
+    this.veilTransparentBox = document.createElement("box");
+    this.veilTransparentBox.id = "highlighter-veil-transparentbox";
+
+    // We don't need any references to veilRightBox and veilBottomBox.
+    // These boxes are automatically resized (flex=1)
 
-    iframe.setAttribute("src", "chrome://browser/content/highlighter.xhtml");
+    let veilRightBox = document.createElement("box");
+    veilRightBox.id = "highlighter-veil-rightbox";
+    veilRightBox.className = "highlighter-veil";
+
+    let veilBottomBox = document.createElement("box");
+    veilBottomBox.id = "highlighter-veil-bottombox";
+    veilBottomBox.className = "highlighter-veil";
 
-    div.appendChild(iframe);
-    stack.appendChild(div);
-    this.iframe = iframe;
-    this.iframeContainer = div;
+    this.veilMiddleBox.appendChild(this.veilLeftBox);
+    this.veilMiddleBox.appendChild(this.veilTransparentBox);
+    this.veilMiddleBox.appendChild(veilRightBox);
+
+    aParent.appendChild(this.veilTopBox);
+    aParent.appendChild(this.veilMiddleBox);
+    aParent.appendChild(veilBottomBox);
   },
 
   /**
-   * Destroy the iframe and its nodes.
+   * Build the controls:
+   *
+   * <box id="highlighter-close-button"/>
+   *
+   * @param nsIDOMNode aParent
    */
-  destroy: function IFH_destroy()
+  buildControls: function Highlighter_buildControls(aParent)
   {
-    this.browser.removeEventListener("click", this, true);
+    let closeButton = document.createElement("box");
+    closeButton.id = "highlighter-close-button";
+    closeButton.appendChild(document.createElement("image"));
+
+    closeButton.setAttribute("onclick", "InspectorUI.closeInspectorUI(false);");
+
+    aParent.appendChild(closeButton);
+  },
+
+
+  /**
+   * Destroy the nodes.
+   */
+  destroy: function Highlighter_destroy()
+  {
+    this.browser.removeEventListener("scroll", this, true);
+    this.browser.removeEventListener("resize", this, true);
     this._highlightRect = null;
     this._highlighting = false;
-    this.veilTopDiv = null;
-    this.veilLeftDiv = null;
-    this.veilMiddleDiv = null;
-    this.veilTransparentDiv = null;
+    this.veilTopBox = null;
+    this.veilLeftBox = null;
+    this.veilMiddleBox = null;
+    this.veilTransparentBox = null;
     this.node = null;
-    this.iframeDoc = null;
-    this.browser.parentNode.removeChild(this.iframeContainer);
-    this.iframeContainer = null;
-    this.iframe = null;
+    this.highlighterContainer.parentNode.removeChild(this.highlighterContainer);
+    this.highlighterContainer = null;
     this.win = null
     this.browser = null;
   },
 
   /**
    * Is the highlighter highlighting? Public method for querying the state
    * of the highlighter.
    */
@@ -169,36 +233,30 @@ IFrameHighlighter.prototype = {
   },
 
   /**
    * Highlight this.node, unhilighting first if necessary.
    *
    * @param boolean aScroll
    *        Boolean determining whether to scroll or not.
    */
-  highlight: function IFH_highlight(aScroll)
+  highlight: function Highlighter_highlight(aScroll)
   {
     // node is not set or node is not highlightable, bail
     if (!this.node || !this.isNodeHighlightable()) {
       return;
     }
 
     let clientRect = this.node.getBoundingClientRect();
 
     // clientRect is read-only, we need to be able to change properties.
     let rect = {top: clientRect.top,
                 left: clientRect.left,
                 width: clientRect.width,
                 height: clientRect.height};
-    let oldRect = this._highlightRect;
-
-    if (oldRect && rect.top == oldRect.top && rect.left == oldRect.left &&
-        rect.width == oldRect.width && rect.height == oldRect.height) {
-      return; // same rectangle
-    }
 
     if (aScroll) {
       this.node.scrollIntoView();
     }
 
     // Go up in the tree of frames to determine the correct rectangle
     // coordinates and size.
     let frameWin = this.node.ownerDocument.defaultView;
@@ -243,74 +301,81 @@ IFrameHighlighter.prototype = {
   /**
    * Highlight the given node.
    *
    * @param nsIDOMNode aNode
    *        a DOM element to be highlighted
    * @param object aParams
    *        extra parameters object
    */
-  highlightNode: function IFH_highlightNode(aNode, aParams)
+  highlightNode: function Highlighter_highlightNode(aNode, aParams)
   {
     this.node = aNode;
     this.highlight(aParams && aParams.scroll);
   },
 
   /**
    * Highlight a rectangular region.
    *
    * @param object aRect
    *        The rectangle region to highlight.
    * @returns boolean
    *          True if the rectangle was highlighted, false otherwise.
    */
-  highlightRectangle: function IFH_highlightRectangle(aRect)
+  highlightRectangle: function Highlighter_highlightRectangle(aRect)
   {
+    let oldRect = this._highlightRect;
+
+    if (oldRect && aRect.top == oldRect.top && aRect.left == oldRect.left &&
+        aRect.width == oldRect.width && aRect.height == oldRect.height) {
+      return this._highlighting; // same rectangle
+    }
+
     if (aRect.left >= 0 && aRect.top >= 0 &&
         aRect.width > 0 && aRect.height > 0) {
       // The bottom div and the right div are flexibles (flex=1).
       // We don't need to resize them.
-      this.veilTopDiv.style.height = aRect.top + "px";
-      this.veilLeftDiv.style.width = aRect.left + "px";
-      this.veilMiddleDiv.style.height = aRect.height + "px";
-      this.veilTransparentDiv.style.width = aRect.width + "px";
+      this.veilTopBox.style.height = aRect.top + "px";
+      this.veilLeftBox.style.width = aRect.left + "px";
+      this.veilMiddleBox.style.height = aRect.height + "px";
+      this.veilTransparentBox.style.width = aRect.width + "px";
 
       this._highlighting = true;
     } else {
       this.unhighlight();
     }
 
     this._highlightRect = aRect;
 
     return this._highlighting;
   },
 
   /**
    * Clear the highlighter surface.
    */
-  unhighlight: function IFH_unhighlight()
+  unhighlight: function Highlighter_unhighlight()
   {
     this._highlighting = false;
-    this.veilMiddleDiv.style.height = 0;
-    this.veilTransparentDiv.style.width = 0;
+    this.veilMiddleBox.style.height = 0;
+    this.veilTransparentBox.style.width = 0;
     Services.obs.notifyObservers(null,
       INSPECTOR_NOTIFICATIONS.UNHIGHLIGHTING, null);
   },
 
   /**
    * Return the midpoint of a line from pointA to pointB.
    *
    * @param object aPointA
    *        An object with x and y properties.
    * @param object aPointB
    *        An object with x and y properties.
    * @returns object
    *          An object with x and y properties.
    */
-  midPoint: function IFH_midPoint(aPointA, aPointB)
+  midPoint: function Highlighter_midPoint(aPointA, aPointB)
   {
     let pointC = { };
     pointC.x = (aPointB.x - aPointA.x) / 2 + aPointA.x;
     pointC.y = (aPointB.y - aPointA.y) / 2 + aPointA.y;
     return pointC;
   },
 
   /**
@@ -347,51 +412,54 @@ IFrameHighlighter.prototype = {
   },
 
   /**
    * Is this.node highlightable?
    *
    * @returns boolean
    *          True if the node is highlightable or false otherwise.
    */
-  isNodeHighlightable: function IFH_isNodeHighlightable()
+  isNodeHighlightable: function Highlighter_isNodeHighlightable()
   {
     if (!this.node || this.node.nodeType != Node.ELEMENT_NODE) {
       return false;
     }
     let nodeName = this.node.nodeName.toLowerCase();
     return !INSPECTOR_INVISIBLE_ELEMENTS[nodeName];
   },
 
   /////////////////////////////////////////////////////////////////////////
   //// Event Handling
 
-  attachInspectListeners: function IFH_attachInspectListeners()
+  attachInspectListeners: function Highlighter_attachInspectListeners()
   {
     this.browser.addEventListener("mousemove", this, true);
+    this.browser.addEventListener("click", this, true);
     this.browser.addEventListener("dblclick", this, true);
     this.browser.addEventListener("mousedown", this, true);
     this.browser.addEventListener("mouseup", this, true);
   },
 
-  detachInspectListeners: function IFH_detachInspectListeners()
+  detachInspectListeners: function Highlighter_detachInspectListeners()
   {
     this.browser.removeEventListener("mousemove", this, true);
+    this.browser.removeEventListener("click", this, true);
     this.browser.removeEventListener("dblclick", this, true);
     this.browser.removeEventListener("mousedown", this, true);
     this.browser.removeEventListener("mouseup", this, true);
   },
 
+
   /**
    * Generic event handler.
    *
    * @param nsIDOMEvent aEvent
    *        The DOM event object.
    */
-  handleEvent: function IFH_handleEvent(aEvent)
+  handleEvent: function Highlighter_handleEvent(aEvent)
   {
     switch (aEvent.type) {
       case "click":
         this.handleClick(aEvent);
         break;
       case "mousemove":
         this.handleMouseMove(aEvent);
         break;
@@ -399,150 +467,61 @@ IFrameHighlighter.prototype = {
         this.handleResize(aEvent);
         break;
       case "dblclick":
       case "mousedown":
       case "mouseup":
         aEvent.stopPropagation();
         aEvent.preventDefault();
         break;
+      case "scroll":
+        this.highlight();
+        break;
     }
   },
 
   /**
-   * Handle clicks on the iframe.
+   * Handle clicks.
    *
    * @param nsIDOMEvent aEvent
    *        The DOM event.
    */
-  handleClick: function IFH_handleClick(aEvent)
+  handleClick: function Highlighter_handleClick(aEvent)
   {
-    // Proxy the click event to the iframe.
-    let x = aEvent.clientX;
-    let y = aEvent.clientY;
-    let frameWin = aEvent.view;
-    while (frameWin != this.win) {
-      if (frameWin.frameElement) {
-        let frameRect = frameWin.frameElement.getBoundingClientRect();
-        x += frameRect.left;
-        y += frameRect.top;
-      }
-      frameWin = frameWin.parent;
+    // Stop inspection when the user clicks on a node.
+    if (aEvent.button == 0) {
+      let win = aEvent.target.ownerDocument.defaultView;
+      InspectorUI.stopInspecting();
+      win.focus();
     }
-
-    let element = this.iframeDoc.elementFromPoint(x, y);
-    if (element && element.classList &&
-        element.classList.contains("clickable")) {
-      let newEvent = this.iframeDoc.createEvent("MouseEvents");
-      newEvent.initMouseEvent(aEvent.type, aEvent.bubbles, aEvent.cancelable,
-        this.iframeDoc.defaultView, aEvent.detail, aEvent.screenX,
-        aEvent.screenY, x, y, aEvent.ctrlKey, aEvent.altKey, aEvent.shiftKey,
-        aEvent.metaKey, aEvent.button, null);
-      element.dispatchEvent(newEvent);
-      aEvent.preventDefault();
-      aEvent.stopPropagation();
-      return;
-    }
-
-    // Stop inspection when the user clicks on a node.
-    if (InspectorUI.inspecting) {
-      if (aEvent.button == 0) {
-        let win = aEvent.target.ownerDocument.defaultView;
-        InspectorUI.stopInspecting();
-        win.focus();
-      }
-      aEvent.preventDefault();
-      aEvent.stopPropagation();
-    }
+    aEvent.preventDefault();
+    aEvent.stopPropagation();
   },
 
   /**
    * Handle mousemoves in panel when InspectorUI.inspecting is true.
    *
    * @param nsiDOMEvent aEvent
    *        The MouseEvent triggering the method.
    */
-  handleMouseMove: function IFH_handleMouseMove(aEvent)
+  handleMouseMove: function Highlighter_handleMouseMove(aEvent)
   {
-    if (!InspectorUI.inspecting) {
-      return;
-    }
-
     let element = InspectorUI.elementFromPoint(aEvent.target.ownerDocument,
       aEvent.clientX, aEvent.clientY);
     if (element && element != this.node) {
       InspectorUI.inspectNode(element);
     }
   },
 
   /**
    * Handle window resize events.
    */
-  handleResize: function IFH_handleResize()
-  {
-    let style = this.iframeContainer.style;
-    if (this.win.scrollMaxY && this.win.scrollbars.visible) {
-      style.paddingRight = this.getScrollbarWidth() + "px";
-    } else {
-      style.paddingRight = 0;
-    }
-    if (this.win.scrollMaxX && this.win.scrollbars.visible) {
-      style.paddingBottom = this.getScrollbarWidth() + "px";
-    } else {
-      style.paddingBottom = 0;
-    }
-
-    this.highlight();
-  },
-
-  /**
-   * Determine the scrollbar width in the current document.
-   *
-   * @returns number
-   *          The scrollbar width in pixels.
-   */
-  getScrollbarWidth: function IFH_getScrollbarWidth()
+  handleResize: function Highlighter_handleResize()
   {
-    if (this._scrollbarWidth) {
-      return this._scrollbarWidth;
-    }
-
-    let hbox = document.createElement("hbox");
-    hbox.setAttribute("style", "height: 0%; overflow: hidden");
-
-    let scrollbar = document.createElement("scrollbar");
-    scrollbar.setAttribute("orient", "vertical");
-    hbox.appendChild(scrollbar);
-
-    document.documentElement.appendChild(hbox);
-    this._scrollbarWidth = scrollbar.clientWidth;
-    document.documentElement.removeChild(hbox);
-
-    return this._scrollbarWidth;
-  },
-
-  /**
-   * Helper to listen for an event only once.
-   *
-   * @param nsIDOMEventTarget aTarget
-   *        The DOM event target you want to add an event listener to.
-   * @param string aName
-   *        The event name you want to listen for.
-   * @param function aCallback
-   *        The function you want to execute once for the given event.
-   * @param boolean aCapturing
-   *        Tells if you want to use capture for the event listener.
-   * @returns void
-   */
-  listenOnce: function IFH_listenOnce(aTarget, aName, aCallback, aCapturing)
-  {
-    aTarget.addEventListener(aName, function listenOnce_handler(aEvent) {
-      aTarget.removeEventListener(aName, listenOnce_handler, aCapturing);
-      aCallback.call(this, aEvent);
-    }, aCapturing);
+    this.highlight();
   },
 };
 
 ///////////////////////////////////////////////////////////////////////////
 //// InspectorUI
 
 /**
  * Main controller class for the Inspector.
@@ -780,28 +759,26 @@ var InspectorUI = {
     this.winID = this.getWindowID(this.win);
     if (!this.domplate) {
       Cu.import("resource:///modules/domplate.jsm", this);
       this.domplateUtils.setDOM(window);
     }
 
     this.openTreePanel();
 
-    this.browser.addEventListener("scroll", this, true);
     this.inspectCmd.setAttribute("checked", true);
   },
 
   /**
    * Initialize highlighter.
    */
   initializeHighlighter: function IUI_initializeHighlighter()
   {
-    Services.obs.addObserver(this.highlighterReady,
-      INSPECTOR_NOTIFICATIONS.HIGHLIGHTER_READY, false);
-    this.highlighter = new IFrameHighlighter(this.browser);
+    this.highlighter = new Highlighter(this.browser);
+    this.highlighterReady();
   },
 
   /**
    * Initialize the InspectorStore.
    */
   initializeStore: function IUI_initializeStore()
   {
     // First time opened, add the TabSelect listener
@@ -852,17 +829,16 @@ var InspectorUI = {
       }
       InspectorStore.setValue(this.winID, "inspecting", this.inspecting);
     }
 
     if (InspectorStore.isEmpty()) {
       gBrowser.tabContainer.removeEventListener("TabSelect", this, false);
     }
 
-    this.browser.removeEventListener("scroll", this, true);
     this.stopInspecting();
     if (this.highlighter) {
       this.highlighter.destroy();
       this.highlighter = null;
     }
 
     if (this.treePanelDiv) {
       this.treePanelDiv.ownerPanel = null;
@@ -948,36 +924,29 @@ var InspectorUI = {
       }
       this.ioBox.select(this.selection, true, true, aScroll);
     }
   },
 
   /////////////////////////////////////////////////////////////////////////
   //// Event Handling
 
-  notifyReady: function IUI_notifyReady()
+  highlighterReady: function IUI_highlighterReady()
   {
     // Setup the InspectorStore or restore state
     this.initializeStore();
 
     if (InspectorStore.getValue(this.winID, "inspecting")) {
       this.startInspecting();
     }
 
     this.win.focus();
     Services.obs.notifyObservers(null, INSPECTOR_NOTIFICATIONS.OPENED, null);
   },
 
-  highlighterReady: function IUI_highlighterReady()
-  {
-    Services.obs.removeObserver(InspectorUI.highlighterReady,
-      INSPECTOR_NOTIFICATIONS.HIGHLIGHTER_READY, false);
-    InspectorUI.notifyReady();
-  },
-
   /**
    * Main callback handler for events.
    *
    * @param event
    *        The event to be handled.
    */
   handleEvent: function IUI_handleEvent(event)
   {
@@ -1035,19 +1004,16 @@ var InspectorUI = {
             if (this.inspecting) {
               this.stopInspecting();
               event.preventDefault();
               event.stopPropagation();
             }
             break;
         }
         break;
-      case "scroll":
-        this.highlighter.highlight();
-        break;
     }
   },
 
   /**
    * Handle click events in the html tree panel.
    * @param aEvent
    *        The mouse event.
    */
--- a/browser/base/content/openLocation.js
+++ b/browser/base/content/openLocation.js
@@ -91,27 +91,32 @@ function doEnabling()
 {
     dialog.open.disabled = !dialog.input.value;
 }
 
 function open()
 {
   var url;
   var postData = {};
+  var mayInheritPrincipal = {value: false};
   if (browser)
-    url = browser.getShortcutOrURI(dialog.input.value, postData);
+    url = browser.getShortcutOrURI(dialog.input.value, postData, mayInheritPrincipal);
   else
     url = dialog.input.value;
 
   try {
     // Whichever target we use for the load, we allow third-party services to
     // fixup the URI
     switch (dialog.openWhereList.value) {
       case "0":
-        browser.loadURI(url, null, postData.value, true);
+        var webNav = Components.interfaces.nsIWebNavigation;
+        var flags = webNav.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
+        if (!mayInheritPrincipal.value)
+          flags |= webNav.LOAD_FLAGS_DISALLOW_INHERIT_OWNER;
+        browser.gBrowser.loadURIWithFlags(url, flags, null, null, postData.value);
         break;
       case "1":
         window.opener.delayedOpenWindow(getBrowserURL(), "all,dialog=no",
                                         url, postData.value, null, null, true);
         break;
       case "3":
         browser.delayedOpenTab(url, null, null, postData.value, true);
         break;
--- a/browser/base/content/scratchpad.js
+++ b/browser/base/content/scratchpad.js
@@ -638,16 +638,19 @@ var Scratchpad = {
       Services.prefs.clearUserPref(PREF_TABSIZE);
       tabsize = Services.prefs.getIntPref(PREF_TABSIZE);
     }
 
     let expandtab = Services.prefs.getBoolPref(PREF_EXPANDTAB);
     this._tabCharacter = expandtab ? (new Array(tabsize + 1)).join(" ") : "\t";
     this.textbox.style.MozTabSize = tabsize;
 
+    // Force LTR direction (otherwise the textbox inherits the locale direction)
+    this.textbox.style.direction = "ltr";
+
     this.insertIntro();
 
     // Make the Tab key work.
     this.textbox.addEventListener("keypress", this.onKeypress.bind(this), false);
 
     this.textbox.focus();
   },
 
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -772,22 +772,20 @@
         </body>
       </method>
 
       <method name="getWindowTitleForBrowser">
         <parameter name="aBrowser"/>
         <body>
           <![CDATA[
             var newTitle = "";
-            var docTitle;
             var docElement = this.ownerDocument.documentElement;
             var sep = docElement.getAttribute("titlemenuseparator");
 
-            if (aBrowser.docShell.contentViewer)
-              docTitle = aBrowser.contentTitle;
+            var docTitle = aBrowser.contentTitle;
 
             if (!docTitle)
               docTitle = docElement.getAttribute("titledefault");
 
             var modifier = docElement.getAttribute("titlemodifier");
             if (docTitle) {
               newTitle += docElement.getAttribute("titlepreface");
               newTitle += docTitle;
@@ -854,59 +852,69 @@
               if (this._lastRelatedTab != this.selectedTab)
                 this._lastRelatedTab.owner = null;
               this._lastRelatedTab = null;
             }
 
             var oldBrowser = this.mCurrentBrowser;
             if (oldBrowser) {
               oldBrowser.setAttribute("type", "content-targetable");
-              oldBrowser.docShell.isActive = false;
+              oldBrowser.docShellIsActive = false;
             }
 
             var updatePageReport = false;
             if (!oldBrowser ||
                 (oldBrowser.pageReport && !newBrowser.pageReport) ||
                 (!oldBrowser.pageReport && newBrowser.pageReport))
               updatePageReport = true;
 
             newBrowser.setAttribute("type", "content-primary");
-            newBrowser.docShell.isActive = true;
+            newBrowser.docShellIsActive =
+              (window.windowState != window.STATE_MINIMIZED);
             this.mCurrentBrowser = newBrowser;
             this.mCurrentTab = this.selectedTab;
             this.showTab(this.mCurrentTab);
 
             if (updatePageReport)
               this.mCurrentBrowser.updatePageReport();
 
             // Update the URL bar.
             var loc = this.mCurrentBrowser.currentURI;
 
+#ifdef MOZ_E10S_COMPAT
+            // Bug 666801 - WebProgress support for e10s and
+            // Bug 666809 - SecurityUI support for e10s
+#else
             var webProgress = this.mCurrentBrowser.webProgress;
             var securityUI = this.mCurrentBrowser.securityUI;
 
             this._callProgressListeners(null, "onLocationChange",
                                         [webProgress, null, loc], true, false);
 
             if (securityUI) {
               this._callProgressListeners(null, "onSecurityChange",
                                           [webProgress, null, securityUI.state], true, false);
             }
+#endif
 
             var listener = this.mTabListeners[this.tabContainer.selectedIndex] || null;
             if (listener && listener.mStateFlags) {
               this._callProgressListeners(null, "onUpdateCurrentBrowser",
                                           [listener.mStateFlags, listener.mStatus,
                                            listener.mMessage, listener.mTotalProgress],
                                           true, false);
             }
 
             // Don't switch the fast find or update the titlebar (bug 540248) - this tab switch is temporary
             if (!this._previewMode) {
+#ifdef MOZ_E10S_COMPAT
+              // Bug 666816 - TypeAheadFind support for e10s
+#else
               this._fastFind.setDocShell(this.mCurrentBrowser.docShell);
+#endif
 
               this.updateTitlebar();
 
               this.mCurrentTab.removeAttribute("titlechanged");
             }
 
             // If the new tab is busy, and our current state is not busy, then
             // we need to fire a start to all progress listeners.
@@ -1258,16 +1266,21 @@
             var b = document.createElementNS(
               "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",
                                              "browser");
             b.setAttribute("type", "content-targetable");
             b.setAttribute("message", "true");
             b.setAttribute("contextmenu", this.getAttribute("contentcontextmenu"));
             b.setAttribute("tooltip", this.getAttribute("contenttooltip"));
 
+            if (Services.prefs.getPrefType("browser.tabs.remote") == Services.prefs.PREF_BOOL &&
+                Services.prefs.getBoolPref("browser.tabs.remote")) {
+              b.setAttribute("remote", "true");
+            }
+
             if (window.gShowPageResizers && document.getElementById("addon-bar").collapsed &&
                 window.windowState == window.STATE_NORMAL) {
               b.setAttribute("showresizer", "true");
             }
 
             if (this.hasAttribute("autocompletepopup"))
               b.setAttribute("autocompletepopup", this.getAttribute("autocompletepopup"));
             b.setAttribute("autoscrollpopup", this._autoScrollPopup.id);
@@ -1305,17 +1318,21 @@
 
             this.tabContainer.updateVisibility();
 
             // wire up a progress listener for the new browser object.
             var tabListener = this.mTabProgressListener(t, b, blank);
             const filter = Components.classes["@mozilla.org/appshell/component/browser-status-filter;1"]
                                      .createInstance(Components.interfaces.nsIWebProgress);
             filter.addProgressListener(tabListener, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
+#ifdef MOZ_E10S_COMPAT
+            // Bug 666801 - WebProgress support for e10s
+#else
             b.webProgress.addProgressListener(filter, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
+#endif
             this.mTabListeners[position] = tabListener;
             this.mTabFilters[position] = filter;
 
             b._fastFind = this.fastFind;
             b.droppedLinkHandler = handleDroppedLink;
 
             // Dispatch a new tab notification.  We do this once we're
             // entirely done, so that things are in a consistent state
@@ -1343,17 +1360,17 @@
                 b.loadURIWithFlags(aURI, flags, aReferrerURI, aCharset, aPostData);
               } catch (ex) {
                 Cu.reportError(ex);
               }
             }
 
             // We start our browsers out as inactive, and then maintain
             // activeness in the tab switcher.
-            b.docShell.isActive = false;
+            b.docShellIsActive = false;
 
             // Check if we're opening a tab related to the current tab and
             // move it to after the current tab.
             // aReferrerURI is null or undefined if the tab is opened from
             // an external application or bookmark, i.e. somewhere other
             // than the current tab.
             if ((aRelatedToCurrent == null ? aReferrerURI : aRelatedToCurrent) &&
                 Services.prefs.getBoolPref("browser.tabs.insertRelatedAfterCurrent")) {
@@ -1562,17 +1579,21 @@
             // We dispatch it before any teardown so that event listeners can
             // inspect the tab that's about to close.
             var evt = document.createEvent("UIEvent");
             evt.initUIEvent("TabClose", true, false, window, aTabWillBeMoved ? 1 : 0);
             aTab.dispatchEvent(evt);
 
             // Remove the tab's filter and progress listener.
             const filter = this.mTabFilters[aTab._tPos];
+#ifdef MOZ_E10S_COMPAT
+            // Bug 666801 - WebProgress support for e10s
+#else 
             browser.webProgress.removeProgressListener(filter);
+#endif
             filter.removeProgressListener(this.mTabListeners[aTab._tPos]);
             this.mTabListeners[aTab._tPos].destroy();
 
             if (browser.registeredOpenURI && !aTabWillBeMoved) {
               this._placesAutocomplete.unregisterOpenPage(browser.registeredOpenURI);
               delete browser.registeredOpenURI;
             }
 
@@ -2438,25 +2459,32 @@
 
       <method name="handleEvent">
         <parameter name="aEvent"/>
         <body><![CDATA[
           switch (aEvent.type) {
             case "keypress":
               this._handleKeyEvent(aEvent);
               break;
+            case "sizemodechange":
+              if (aEvent.target == window) {
+                this.mCurrentBrowser.docShellIsActive =
+                  (window.windowState != window.STATE_MINIMIZED);
+              }
+              break;
           }
         ]]></body>
       </method>
 
       <constructor>
         <![CDATA[
           this.mCurrentBrowser = this.mPanelContainer.childNodes[0].firstChild.firstChild;
           this.mCurrentTab = this.tabContainer.firstChild;
           document.addEventListener("keypress", this, false);
+          window.addEventListener("sizemodechange", this, false);
 
           var uniqueId = "panel" + Date.now();
           this.mPanelContainer.childNodes[0].id = uniqueId;
           this.mCurrentTab.linkedPanel = uniqueId;
           this.mCurrentTab._tPos = 0;
           this.mCurrentTab._fullyOpen = true;
           this.mCurrentTab.linkedBrowser = this.mCurrentBrowser;
 
@@ -2509,16 +2537,17 @@
             }
             browser.webProgress.removeProgressListener(this.mTabFilters[i]);
             this.mTabFilters[i].removeProgressListener(this.mTabListeners[i]);
             this.mTabFilters[i] = null;
             this.mTabListeners[i].destroy();
             this.mTabListeners[i] = null;
           }
           document.removeEventListener("keypress", this, false);
+          window.removeEventListener("sizemodechange", this, false);
         ]]>
       </destructor>
 
       <!-- Deprecated stuff, implemented for backwards compatibility. -->
       <method name="enterTabbedMode">
         <body>
           Application.console.log("enterTabbedMode is an obsolete method and " +
                                   "will be removed in a future release.");
--- a/browser/base/content/tabview/groupitems.js
+++ b/browser/base/content/tabview/groupitems.js
@@ -186,16 +186,17 @@ function GroupItem(listOfEls, options) {
   };
 
   this.$title
     .blur(function() {
       self._titleFocused = false;
       self.$titleShield.show();
       if (self.getTitle())
         gTabView.firstUseExperienced = true;
+      self.save();
     })
     .focus(function() {
       self._unfreezeItemSize();
       if (!self._titleFocused) {
         (self.$title)[0].select();
         self._titleFocused = true;
       }
     })
@@ -820,19 +821,17 @@ GroupItem.prototype = Utils.extend(new I
       child.removeSubscriber(self, "close");
 
       let removed = child.close(true);
       if (removed) {
         shouldRemoveTabItems.push(child);
       } else {
         // child.removeSubscriber() must be called before child.close(), 
         // therefore we call child.addSubscriber() if the tab is not removed.
-        child.addSubscriber(self, "close", function() {
-          self.remove(child);
-        });
+        child.addSubscriber(self, "close", self._onChildClose.bind(self));
       }
     });
 
     if (shouldRemoveTabItems.length != toClose.length) {
       // remove children without the assiciated tab and show the group item
       shouldRemoveTabItems.forEach(function(child) {
         self.remove(child, { dontArrange: true });
       });
@@ -1005,29 +1004,17 @@ GroupItem.prototype = Utils.extend(new I
       this._children.splice(index, 0, item);
 
       item.setZ(this.getZ() + 1);
 
       if (!wasAlreadyInThisGroupItem) {
         item.droppable(false);
         item.groupItemData = {};
 
-        item.addSubscriber(this, "close", function() {
-          let count = self._children.length;
-          let dontArrange = self.expanded || !self.shouldStack(count);
-          let dontClose = !item.closedManually && gBrowser._numPinnedTabs > 0;
-          self.remove(item, {dontArrange: dontArrange, dontClose: dontClose});
-
-          if (dontArrange)
-            self._freezeItemSize(count);
-
-          if (self._children.length > 0 && self._activeTab)
-            UI.setActive(self);
-        });
-
+        item.addSubscriber(this, "close", this._onChildClose.bind(this));
         item.setParent(this);
 
         if (typeof item.setResizable == 'function')
           item.setResizable(false, options.immediately);
 
         if (item == UI.getActiveTab() || !this._activeTab)
           this.setActiveTab(item);
 
@@ -1046,16 +1033,35 @@ GroupItem.prototype = Utils.extend(new I
 
       UI.setReorderTabsOnHide(this);
     } catch(e) {
       Utils.log('GroupItem.add error', e);
     }
   },
 
   // ----------
+  // Function: _onChildClose
+  // Handles "close" events from the group's children.
+  //
+  // Parameters:
+  //   tabItem - The tabItem that is closed.
+  _onChildClose: function GroupItem__onChildClose(tabItem) {
+    let count = this._children.length;
+    let dontArrange = this.expanded || !this.shouldStack(count);
+    let dontClose = !tabItem.closedManually && gBrowser._numPinnedTabs > 0;
+    this.remove(tabItem, {dontArrange: dontArrange, dontClose: dontClose});
+
+    if (dontArrange)
+      this._freezeItemSize(count);
+
+    if (this._children.length > 0 && this._activeTab)
+      UI.setActive(this);
+  },
+
+  // ----------
   // Function: remove
   // Removes an item from the groupItem.
   // Parameters:
   //
   //   a - The item to remove. Can be an <Item>, a DOM element or an iQ object.
   //       The latter two must refer to the container of an <Item>.
   //   options - An optional object with settings for this call. See below.
   //
--- a/browser/base/content/tabview/tabitems.js
+++ b/browser/base/content/tabview/tabitems.js
@@ -260,18 +260,21 @@ TabItem.prototype = Utils.extend(new Ite
   // treats it as a new tab. 
   _reconnect: function TabItem__reconnect() {
     Utils.assertThrow(!this._reconnected, "shouldn't already be reconnected");
     Utils.assertThrow(this.tab, "should have a xul:tab");
 
     let tabData = null;
     let self = this;
     let imageDataCb = function(imageData) {
+      // we could have been unlinked while waiting for the thumbnail to load
+      if (!self.tab)
+        return;
+
       Utils.assertThrow(tabData, "tabData");
-      
       tabData.imageData = imageData;
 
       let currentUrl = self.tab.linkedBrowser.currentURI.spec;
       // If we have a cached image, then show it if the loaded URL matches
       // what the cache is from, OR the loaded URL is blank, which means
       // that the page hasn't loaded yet.
       if (tabData.imageData &&
           (tabData.url == currentUrl || currentUrl == 'about:blank')) {
--- a/browser/base/content/tabview/tabview.css
+++ b/browser/base/content/tabview/tabview.css
@@ -173,16 +173,30 @@ body {
 .shield {
   left: 0;
   top: 0;
   width: 100%;
   height: 100%;
   position: absolute;
 }
 
+.banner {
+  left: 0;
+  bottom: 0;
+  right: 0;
+  padding: 10px 0;
+  position: absolute;
+  z-index: 1000060;
+  background: #000;
+  color: #fff;
+  opacity: 0;
+  text-align: center;
+  font-weight: 700;
+}
+
 /* Resizable
 ----------------------------------*/
 .resizer {
   position: absolute;
 }
 
 .iq-resizable-handle {
   position: absolute;
--- a/browser/base/content/tabview/ui.js
+++ b/browser/base/content/tabview/ui.js
@@ -130,16 +130,20 @@ let UI = {
   // Variable: isDOMWindowClosing
   // Tells wether the parent window is about to close
   isDOMWindowClosing: false,
 
   // Variable: _browserKeys
   // Used to keep track of allowed browser keys.
   _browserKeys: null,
 
+  // Variable: _browserKeysWithShift
+  // Used to keep track of allowed browser keys with Shift key combination.
+  _browserKeysWithShift: null,
+
   // Variable: ignoreKeypressForSearch
   // Used to prevent keypress being handled after quitting search mode.
   ignoreKeypressForSearch: false,
 
   // Variable: _lastOpenedTab
   // Used to keep track of the last opened tab.
   _lastOpenedTab: null,
 
@@ -968,34 +972,37 @@ let UI = {
 #endif
 #ifdef XP_MACOSX
       "preferencesCmdMac", "minimizeWindow", "hideThisAppCmdMac",
 #endif
       "newNavigator", "newNavigatorTab", "undo", "cut", "copy", "paste", 
       "selectAll", "find"
     ].forEach(function(key) {
       let element = gWindow.document.getElementById("key_" + key);
-      keys[key] = element.getAttribute("key").toLocaleLowerCase().charCodeAt(0);
+      let code = element.getAttribute("key").toLocaleLowerCase().charCodeAt(0);
+      keys[code] = key;
     });
+    this._browserKeys = keys;
 
-    // for key combinations with shift key, the charCode of upper case letters 
-    // are different to the lower case ones so need to handle them differently.
+    keys = {};
+    // The lower case letters are passed to processBrowserKeys() even with shift 
+    // key when stimulating a key press using EventUtils.synthesizeKey() so need 
+    // to handle both upper and lower cases here.
     [
 #ifdef XP_UNIX
       "redo",
 #endif
       "closeWindow", "tabview", "undoCloseTab", "undoCloseWindow",
       "privatebrowsing"
     ].forEach(function(key) {
       let element = gWindow.document.getElementById("key_" + key);
-      keys[key] = element.getAttribute("key").toLocaleUpperCase().charCodeAt(0);
+      let code = element.getAttribute("key").toLocaleLowerCase().charCodeAt(0);
+      keys[code] = key;
     });
-
-    delete this._browserKeys;
-    this._browserKeys = keys;
+    this._browserKeysWithShift = keys;
   },
 
   // ----------
   // Function: _setTabViewFrameKeyHandlers
   // Sets up the key handlers for navigating between tabs within the TabView UI.
   _setTabViewFrameKeyHandlers: function UI__setTabViewFrameKeyHandlers() {
     let self = this;
 
@@ -1017,54 +1024,35 @@ let UI = {
 
 #ifdef XP_MACOSX
         if (evt.metaKey) {
 #else
         if (evt.ctrlKey) {
 #endif
           let preventDefault = true;
           if (evt.shiftKey) {
-            switch (evt.charCode) {
-              case self._browserKeys.tabview:
+            // when a user presses ctrl+shift+key, upper case letter charCode 
+            // is passed to processBrowserKeys() so converting back to lower 
+            // case charCode before doing the check
+            let lowercaseCharCode =
+              String.fromCharCode(evt.charCode).toLocaleLowerCase().charCodeAt(0);
+            if (lowercaseCharCode in self._browserKeysWithShift) {
+              let key = self._browserKeysWithShift[lowercaseCharCode];
+              if (key == "tabview")
                 self.exit();
-                break;
-#ifdef XP_UNIX
-              case self._browserKeys.redo:
-#endif
-              case self._browserKeys.closeWindow:
-              case self._browserKeys.undoCloseTab:
-              case self._browserKeys.undoCloseWindow:
-              case self._browserKeys.privatebrowsing:
+              else
                 preventDefault = false;
-                break;
             }
           } else {
-            switch (evt.charCode) {
-              case self._browserKeys.find:
+            if (evt.charCode in self._browserKeys) {
+              let key = self._browserKeys[evt.charCode];
+              if (key == "find")
                 self.enableSearch();
-                break;
-#ifdef XP_UNIX
-              case self._browserKeys.quitApplication:
-#else
-              case self._browserKeys.redo:
-#endif
-#ifdef XP_MACOSX
-              case self._browserKeys.preferencesCmdMac:
-              case self._browserKeys.minimizeWindow:
-              case self._browserKeys.hideThisAppCmdMac:
-#endif
-              case self._browserKeys.newNavigator:
-              case self._browserKeys.newNavigatorTab:
-              case self._browserKeys.undo:
-              case self._browserKeys.cut:
-              case self._browserKeys.copy:
-              case self._browserKeys.paste:
-              case self._browserKeys.selectAll:
+              else
                 preventDefault = false;
-                break;
             }
           }
           if (preventDefault) {
             evt.stopPropagation();
             evt.preventDefault();
           }
         }
       }
@@ -1563,13 +1551,42 @@ let UI = {
 
     // use the tab image if it doesn't start with http e.g. data:image/png, chrome://
     if (tab.image && !(/^https?:/.test(tab.image)))
       url = tab.image;
     else
       url = gFavIconService.getFaviconImageForPage(tab.linkedBrowser.currentURI).spec;
 
     return url;
+  },
+
+  // ----------
+  // Function: notifySessionRestoreEnabled
+  // Notify the user that session restore has been automatically enabled
+  // by showing a banner that expects no user interaction. It fades out after
+  // some seconds.
+  notifySessionRestoreEnabled: function UI_notifySessionRestoreEnabled() {
+    let brandBundle = gWindow.document.getElementById("bundle_brand");
+    let brandShortName = brandBundle.getString("brandShortName");
+    let notificationText = tabviewBundle.formatStringFromName(
+      "tabview.notification.sessionStore", [brandShortName], 1);
+
+    let banner = iQ("<div>")
+      .text(notificationText)
+      .addClass("banner")
+      .appendTo("body");
+
+    let onFadeOut = function () {
+      banner.remove();
+    };
+
+    let onFadeIn = function () {
+      setTimeout(function () {
+        banner.animate({opacity: 0}, {duration: 1500, complete: onFadeOut});
+      }, 5000);
+    };
+
+    banner.animate({opacity: 0.7}, {duration: 1500, complete: onFadeIn});
   }
 };
 
 // ----------
 UI.init();
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -215,16 +215,17 @@ endif
                  browser_scope.js \
                  browser_selectTabAtIndex.js \
                  browser_tab_dragdrop.js \
                  browser_tab_dragdrop2.js \
                  browser_tab_dragdrop2_frame1.xul \
                  browser_tabfocus.js \
                  browser_tabs_isActive.js \
                  browser_tabs_owner.js \
+                 browser_urlbarCopying.js \
                  browser_urlbarTrimURLs.js \
                  browser_urlHighlight.js \
                  browser_visibleFindSelection.js \
                  browser_visibleTabs.js \
                  browser_visibleTabs_contextMenu.js \
                  browser_visibleTabs_bookmarkAllPages.js \
                  browser_visibleTabs_bookmarkAllTabs.js \
                  browser_visibleTabs_tabPreview.js \
@@ -250,16 +251,17 @@ endif
                  browser_aboutHome.js \
                  app_bug575561.html \
                  app_subframe_bug575561.html \
                  browser_contentAreaClick.js \
                  browser_addon_bar_close_button.js \
                  browser_addon_bar_shortcut.js \
                  browser_addon_bar_aomlistener.js \
                  test_bug628179.html \
+                 browser_minimize.js \
                  $(NULL)
 
 ifneq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 _BROWSER_FILES += \
 		browser_bug462289.js \
 		$(NULL)
 else
 _BROWSER_FILES += \
--- a/browser/base/content/test/browser_allTabsPanel.js
+++ b/browser/base/content/test/browser_allTabsPanel.js
@@ -1,10 +1,16 @@
 function test() {
   waitForExplicitFinish();
+
+  Services.prefs.setBoolPref(allTabs.prefName, true);
+  registerCleanupFunction(function () {
+    Services.prefs.clearUserPref(allTabs.prefName);
+  });
+
   allTabs.init();
   nextSequence();
 }
 
 var sequences = 3;
 var chars = "ABCDEFGHI";
 var closedTabs;
 var history;
--- a/browser/base/content/test/browser_bug519216.js
+++ b/browser/base/content/test/browser_bug519216.js
@@ -36,13 +36,15 @@ var progressListener3 = {
   }
 };
 
 var expectListener4 = false;
 var progressListener4 = {
   onLocationChange: function onLocationChange() {
     ok(expectListener4, "didn't call progressListener4 for the first location change");
     gBrowser.removeProgressListener(this);
-    gBrowser.addTab();
-    gBrowser.removeCurrentTab();
-    finish();
+    executeSoon(function () {
+      gBrowser.addTab();
+      gBrowser.removeCurrentTab();
+      finish();
+    });
   }
 };
--- a/browser/base/content/test/browser_bug553455.js
+++ b/browser/base/content/test/browser_bug553455.js
@@ -45,17 +45,17 @@ function wait_for_notification_close(aCa
 function wait_for_install_dialog(aCallback) {
   info("Waiting for install dialog");
   Services.wm.addListener({
     onOpenWindow: function(aXULWindow) {
       info("Install dialog opened, waiting for focus");
       Services.wm.removeListener(this);
 
       var domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
-                                .getInterface(Ci.nsIDOMWindowInternal);
+                                .getInterface(Ci.nsIDOMWindow);
       waitForFocus(function() {
         info("Saw install dialog");
         is(domwindow.document.location.href, XPINSTALL_URL, "Should have seen the right window open");
 
         // Override the countdown timer on the accept button
         var button = domwindow.document.documentElement.getButton("accept");
         button.disabled = false;
 
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/browser_minimize.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+function waitForActive() {
+    if (!gBrowser.docShell.isActive) {
+        executeSoon(waitForActive);
+        return;
+    }
+    is(gBrowser.docShell.isActive, true, "Docshell should be active again");
+    finish();
+}
+
+function waitForInactive() {
+    if (gBrowser.docShell.isActive) {
+        executeSoon(waitForInactive);
+        return;
+    }
+    is(gBrowser.docShell.isActive, false, "Docshell should be inactive");
+    window.restore();
+    waitForActive();
+}
+
+function test() {
+    waitForExplicitFinish();
+    is(gBrowser.docShell.isActive, true, "Docshell should be active");
+    window.minimize();
+    // XXX On Linux minimize/restore seem to be very very async, but
+    // our window.windowState changes sync.... so we can't rely on the
+    // latter correctly reflecting the state of the former.  In
+    // particular, a restore() call before minimizing is done will not
+    // actually restore the window, but change the window state.  As a
+    // result, just poll waiting for our expected isActive values.
+    waitForInactive();
+}
--- a/browser/base/content/test/browser_popupNotification.js
+++ b/browser/base/content/test/browser_popupNotification.js
@@ -105,19 +105,21 @@ function runNextTest() {
     doOnPopupEvent("popuphidden", function () {
       if (!gShownState[gTestIndex]) {
         // This is expected to happen for test 9, so let's not treat it as a failure.
         info("Popup from test " + gTestIndex + " was hidden before its popupshown fired");
       }
 
       let onHidden = onHiddenArray.shift();
       info("[Test #" + gTestIndex + "] popup hidden (" + onHiddenArray.length + " hides remaining)");
-      onHidden.call(nextTest, this);
-      if (!onHiddenArray.length)
-        goNext();
+      executeSoon(function () {
+        onHidden.call(nextTest, this);
+        if (!onHiddenArray.length)
+          goNext();
+      });
     }, onHiddenArray.length);
     info("[Test #" + gTestIndex + "] added listeners; panel state: " + PopupNotifications.isPanelOpen);
   }
 
   info("[Test #" + gTestIndex + "] running test");
   nextTest.run();
 }
 
@@ -734,9 +736,9 @@ function loadURI(uri, callback) {
   gBrowser.loadURI(uri);
 }
 
 function dismissNotification(popup) {
   info("[Test #" + gTestIndex + "] dismissing notification");
   executeSoon(function () {
     EventUtils.synthesizeKey("VK_ESCAPE", {});
   });
-}
\ No newline at end of file
+}
--- a/browser/base/content/test/browser_sanitize-download-history.js
+++ b/browser/base/content/test/browser_sanitize-download-history.js
@@ -136,30 +136,30 @@ function test()
            getService(Ci.nsIDownloadManager);
   let db = dm.DBConnection;
 
   // Empty any old downloads
   db.executeSimpleSQL("DELETE FROM moz_downloads");
 
   // Close the UI if necessary
   let win = Services.ww.getWindowByName("Sanatize", null);
-  if (win && (win instanceof Ci.nsIDOMWindowInternal))
+  if (win && (win instanceof Ci.nsIDOMWindow))
     win.close();
 
   // Start the test when the sanitize window loads
   Services.ww.registerNotification(function (aSubject, aTopic, aData) {
     Services.ww.unregisterNotification(arguments.callee);
     aSubject.QueryInterface(Ci.nsIDOMEventTarget)
             .addEventListener("DOMContentLoaded", doTest, false);
   });
 
   // Let the methods that run onload finish before we test
   let doTest = function() setTimeout(function() {
     let win = Services.ww.getWindowByName("Sanitize", null)
-                .QueryInterface(Ci.nsIDOMWindowInternal);
+                .QueryInterface(Ci.nsIDOMWindow);
 
     for (let i = 0; i < tests.length; i++)
       tests[i](win);
 
     win.close();
     finish();
   }, 0);
  
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/browser_urlbarCopying.js
@@ -0,0 +1,165 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const trimPref = "browser.urlbar.trimURLs";
+
+function test() {
+
+  gBrowser.selectedTab = gBrowser.addTab();
+
+  registerCleanupFunction(function () {
+    gBrowser.removeCurrentTab();
+    Services.prefs.clearUserPref(trimPref);
+    URLBarSetURI();
+  });
+
+  Services.prefs.setBoolPref(trimPref, true);
+
+  waitForExplicitFinish();
+
+  nextTest();
+}
+
+var tests = [
+  // pageproxystate="invalid"
+  {
+    setURL: "http://example.com/",
+    expectedURL: "example.com",
+    copyExpected: "example.com"
+  },
+  {
+    copyVal: "<e>xample.com",
+    copyExpected: "e"
+  },
+
+
+  // pageproxystate="valid" from this point on (due to the load)
+  {
+    loadURL: "http://example.com/",
+    expectedURL: "example.com",
+    copyExpected: "http://example.com/"
+  },
+  {
+    copyVal: "<example.co>m",
+    copyExpected: "http://example.co"
+  },
+  {
+    copyVal: "e<x>ample.com",
+    copyExpected: "x"
+  },
+  {
+    copyVal: "<e>xample.com",
+    copyExpected: "http://e"
+  },
+
+  // Test escaping
+  {
+    loadURL: "http://example.com/()%C3%A9",
+    expectedURL: "example.com/()\xe9",
+    copyExpected: "http://example.com/%28%29%C3%A9"
+  },
+  {
+    copyVal: "<example.com/(>)\xe9",
+    copyExpected: "http://example.com/("
+  },
+  {
+    copyVal: "e<xample.com/(>)\xe9",
+    copyExpected: "xample.com/("
+  },
+
+  {
+    loadURL: "http://example.com/%C3%A9%C3%A9",
+    expectedURL: "example.com/\xe9\xe9",
+    copyExpected: "http://example.com/%C3%A9%C3%A9"
+  },
+  {
+    copyVal: "e<xample.com/\xe9>\xe9",
+    copyExpected: "xample.com/\xe9"
+  },
+  {
+    copyVal: "<example.com/\xe9>\xe9",
+    copyExpected: "http://example.com/\xe9"
+  },
+
+  // data: and javsacript: URIs shouldn't be encoded
+  {
+    loadURL: "javascript:('%C3%A9')",
+    expectedURL: "javascript:('\xe9')",
+    copyExpected: "javascript:('\xe9')"
+  },
+  {
+    copyVal: "<javascript:(>'\xe9')",
+    copyExpected: "javascript:("
+  },
+
+  {
+    loadURL: "data:text/html,(%C3%A9)",
+    expectedURL: "data:text/html,(\xe9)",
+    copyExpected: "data:text/html,(\xe9)"
+  },
+  {
+    copyVal: "<data:text/html,(>\xe9)",
+    copyExpected: "data:text/html,("
+  },
+  {
+    copyVal: "data:<text/html,(\xe9>)",
+    copyExpected: "text/html,(\xe9"
+  }
+];
+
+function nextTest() {
+  let test = tests.shift();
+  if (tests.length == 0)
+    runTest(test, finish);
+  else
+    runTest(test, nextTest);
+}
+
+function runTest(test, cb) {
+  function doCheck() {
+    if (test.setURL || test.loadURL)
+      is(gURLBar.value, test.expectedURL, "url bar value set");
+
+    testCopy(test.copyVal, test.copyExpected, cb);
+  }
+
+  if (test.loadURL) {
+    loadURL(test.loadURL, doCheck);
+  } else {
+    if (test.setURL)
+      gURLBar.value = test.setURL;
+    doCheck();
+  }
+}
+
+function testCopy(copyVal, targetValue, cb) {
+  info("Expecting copy of: " + targetValue);
+  waitForClipboard(targetValue, function () {
+    gURLBar.focus();
+    if (copyVal) {
+      let startBracket = copyVal.indexOf("<");
+      let endBracket = copyVal.indexOf(">");
+      if (startBracket == -1 || endBracket == -1 ||
+          startBracket > endBracket ||
+          copyVal.replace("<", "").replace(">", "") != gURLBar.value) {
+        ok(false, "invalid copyVal: " + copyVal);
+      }
+      gURLBar.selectionStart = startBracket;
+      gURLBar.selectionEnd = endBracket - 1;
+    } else {
+      gURLBar.select();
+    }
+
+    goDoCommand("cmd_copy");
+  }, cb, cb);
+}
+
+function loadURL(aURL, aCB) {
+  gBrowser.selectedBrowser.addEventListener("load", function () {
+    gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
+    is(gBrowser.currentURI.spec, aURL, "loaded expected URL");
+    aCB();
+  }, true);
+
+  gBrowser.loadURI(aURL);
+}
--- a/browser/base/content/test/browser_urlbarTrimURLs.js
+++ b/browser/base/content/test/browser_urlbarTrimURLs.js
@@ -1,15 +1,15 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 function testVal(originalValue, targetValue) {
   gURLBar.value = originalValue;
-  is(gURLBar.value, targetValue || originalValue, "original value: " + originalValue);
+  is(gURLBar.value, targetValue || originalValue, "url bar value set");
 }
 
 function test() {
   const prefname = "browser.urlbar.trimURLs";
 
   gBrowser.selectedTab = gBrowser.addTab();
 
   registerCleanupFunction(function () {
@@ -67,15 +67,15 @@ function test() {
     });
   }, true);
 
   gBrowser.loadURI("http://example.com/");
 }
 
 function testCopy(originalValue, targetValue, cb) {
   waitForClipboard(targetValue, function () {
-    is(gURLBar.value, originalValue);
+    is(gURLBar.value, originalValue, "url bar copy value set");
 
     gURLBar.focus();
     gURLBar.select();
     goDoCommand("cmd_copy");
   }, cb, cb);
 }
--- a/browser/base/content/test/tabview/Makefile.in
+++ b/browser/base/content/test/tabview/Makefile.in
@@ -105,17 +105,16 @@ include $(topsrcdir)/config/rules.mk
                  browser_tabview_bug624692.js \
                  browser_tabview_bug624727.js \
                  browser_tabview_bug624847.js \
                  browser_tabview_bug624931.js \
                  browser_tabview_bug624953.js \
                  browser_tabview_bug625195.js \
                  browser_tabview_bug625269.js \
                  browser_tabview_bug625424.js \
-                 browser_tabview_bug625666.js \
                  browser_tabview_bug626368.js \
                  browser_tabview_bug626525.js \
                  browser_tabview_bug626791.js \
                  browser_tabview_bug627239.js \
                  browser_tabview_bug627288.js \
                  browser_tabview_bug627736.js \
                  browser_tabview_bug628061.js \
                  browser_tabview_bug628165.js \
--- a/browser/base/content/test/tabview/browser_tabview_bug580412.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug580412.js
@@ -1,126 +1,80 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 function test() {
   waitForExplicitFinish();
-
-  window.addEventListener("tabviewshown", onTabViewWindowLoaded, false);
-  if (TabView.isVisible())
-    onTabViewWindowLoaded();
-  else
-    TabView.show();
+  showTabView(onTabViewShown);
 }
 
-function onTabViewWindowLoaded() {
-  window.removeEventListener("tabviewshown", onTabViewWindowLoaded, false);
-
-  let contentWindow = document.getElementById("tab-view").contentWindow;
+function onTabViewShown() {
+  let contentWindow = TabView.getContentWindow();
   let [originalTab] = gBrowser.visibleTabs;
 
   ok(TabView.isVisible(), "Tab View is visible");
   is(contentWindow.GroupItems.groupItems.length, 1, "There is only one group");
   let currentActiveGroup = contentWindow.GroupItems.getActiveGroupItem();
 
-  // set double click interval to negative so quick drag and drop doesn't 
-  // trigger the double click code.
-  let origDBlClickInterval = contentWindow.UI.DBLCLICK_INTERVAL;
-  contentWindow.UI.DBLCLICK_INTERVAL = -1;
-
   let endGame = function() {
-    contentWindow.UI.reset();
-    contentWindow.UI.DBLCLICK_INTERVAL = origDBlClickInterval;
-
-    let onTabViewHidden = function() {
-      window.removeEventListener("tabviewhidden", onTabViewHidden, false);
-      ok(!TabView.isVisible(), "TabView is shown");
-      finish();
-    };
-    window.addEventListener("tabviewhidden", onTabViewHidden, false);
-
     ok(TabView.isVisible(), "TabView is shown");
-
     gBrowser.selectedTab = originalTab;
-    TabView.hide();
-  }
 
-  let part1 = function() {
-    // move down 20 so we're far enough away from the top.
-    checkSnap(currentActiveGroup, 0, 20, contentWindow, function(snapped){
-      ok(!snapped,"Move away from the edge");
-
-      // Just pick it up and drop it.
-      checkSnap(currentActiveGroup, 0, 0, contentWindow, function(snapped){
-        ok(!snapped,"Just pick it up and drop it");
-
-        checkSnap(currentActiveGroup, 0, 1, contentWindow, function(snapped){
-          ok(snapped,"Drag one pixel: should snap");
-
-          checkSnap(currentActiveGroup, 0, 5, contentWindow, function(snapped){
-            ok(!snapped,"Moving five pixels: shouldn't snap");
-            endGame();
-          });
-        });
-      });
+    hideTabView(function () {
+      ok(!TabView.isVisible(), "TabView is hidden");
+      finish();
     });
   }
 
+  // we need to stop the setBounds() css animation or else the test will
+  // fail in single-mode because the group is newly created "ontabshown".
+  let $container = contentWindow.iQ(currentActiveGroup.container);
+  $container.css("-moz-transition-property", "none");
+
   currentActiveGroup.setPosition(40, 40, true);
   currentActiveGroup.arrange({animate: false});
-  part1();
+
+  // move down 20 so we're far enough away from the top.
+  checkSnap(currentActiveGroup, 0, 20, contentWindow, function(snapped){
+    is(currentActiveGroup.getBounds().top, 60, "group.top is 60px");
+    ok(!snapped,"Move away from the edge");
+
+    // Just pick it up and drop it.
+    checkSnap(currentActiveGroup, 0, 0, contentWindow, function(snapped){
+      is(currentActiveGroup.getBounds().top, 60, "group.top is 60px");
+      ok(!snapped,"Just pick it up and drop it");
+
+      checkSnap(currentActiveGroup, 0, 1, contentWindow, function(snapped){
+        is(currentActiveGroup.getBounds().top, 60, "group.top is 60px");
+        ok(snapped,"Drag one pixel: should snap");
+
+        checkSnap(currentActiveGroup, 0, 5, contentWindow, function(snapped){
+          is(currentActiveGroup.getBounds().top, 65, "group.top is 65px");
+          ok(!snapped,"Moving five pixels: shouldn't snap");
+          endGame();
+        });
+      });
+    });
+  });
 }
 
-function simulateDragDrop(tabItem, offsetX, offsetY, contentWindow) {
-  // enter drag mode
-  let dataTransfer;
-
-  EventUtils.synthesizeMouse(
-    tabItem.container, 1, 1, { type: "mousedown" }, contentWindow);
-  let event = contentWindow.document.createEvent("DragEvents");
-  event.initDragEvent(
-    "dragenter", true, true, contentWindow, 0, 0, 0, 0, 0,
-    false, false, false, false, 1, null, dataTransfer);
-  tabItem.container.dispatchEvent(event);
+function simulateDragDrop(item, offsetX, offsetY, contentWindow) {
+  let target = item.container;
 
-  // drag over
-  if (offsetX || offsetY) {
-    let Ci = Components.interfaces;
-    let utils = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor).
-                              getInterface(Ci.nsIDOMWindowUtils);
-    let rect = tabItem.getBounds();
-    for (let i = 1; i <= 5; i++) {
-      let left = rect.left + 1 + Math.round(i * offsetX / 5);
-      let top = rect.top + 1 + Math.round(i * offsetY / 5);
-      utils.sendMouseEvent("mousemove", left, top, 0, 1, 0);
-    }
-    event = contentWindow.document.createEvent("DragEvents");
-    event.initDragEvent(
-      "dragover", true, true, contentWindow, 0, 0, 0, 0, 0,
-      false, false, false, false, 0, null, dataTransfer);
-    tabItem.container.dispatchEvent(event);
-  }
-
-  // drop
-  EventUtils.synthesizeMouse(
-    tabItem.container, 0, 0, { type: "mouseup" }, contentWindow);
-  event = contentWindow.document.createEvent("DragEvents");
-  event.initDragEvent(
-    "drop", true, true, contentWindow, 0, 0, 0, 0, 0,
-    false, false, false, false, 0, null, dataTransfer);
-  tabItem.container.dispatchEvent(event);
+  EventUtils.synthesizeMouse(target, 1, 1, {type: "mousedown"}, contentWindow);
+  EventUtils.synthesizeMouse(target, 1 + offsetX, 1 + offsetY, {type: "mousemove"}, contentWindow);
+  EventUtils.synthesizeMouse(target, 1, 1, {type: "mouseup"}, contentWindow);
 }
 
 function checkSnap(item, offsetX, offsetY, contentWindow, callback) {
   let firstTop = item.getBounds().top;
   let firstLeft = item.getBounds().left;
-  let onDrop = function() {
-    let snapped = false;
-    item.container.removeEventListener('drop', onDrop, false);
-    if (item.getBounds().top != firstTop + offsetY)
-      snapped = true;
-    if (item.getBounds().left != firstLeft + offsetX)
-      snapped = true;
-    callback(snapped);
-  };
-  item.container.addEventListener('drop', onDrop, false);
+
   simulateDragDrop(item, offsetX, offsetY, contentWindow);
+
+  let snapped = false;
+  if (item.getBounds().top != firstTop + offsetY)
+    snapped = true;
+  if (item.getBounds().left != firstLeft + offsetX)
+    snapped = true;
+
+  callback(snapped);
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug587276.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug587276.js
@@ -12,17 +12,17 @@ function test() {
 function test1() {
   ok(TabView.isVisible(), "Tab View is visible");
 
   contentWindow = document.getElementById("tab-view").contentWindow;
   whenTabViewIsHidden(function() {
     ok(!TabView.isVisible(), "Tab View is not visible");
     showTabView(test2);
   });
-  EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true }, contentWindow);
+  EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true }, contentWindow);
 }
 
 function test2() {
   ok(TabView.isVisible(), "Tab View is visible");
 
   whenSearchIsEnabled(function() {
     ok(contentWindow.isSearchEnabled(), "The search is enabled")
 
@@ -53,17 +53,17 @@ function test3() {
 function test4() {
   is(gBrowser.tabs.length, 2, "There are two tabs");
 
   let onTabClose = function() {
     gBrowser.tabContainer.removeEventListener("TabClose", onTabClose, true);
     executeSoon(function() {
       is(gBrowser.tabs.length, 1, "There is one tab after removing one");
 
-      EventUtils.synthesizeKey("T", { accelKey: true, shiftKey: true }, contentWindow);
+      EventUtils.synthesizeKey("t", { accelKey: true, shiftKey: true }, contentWindow);
       is(gBrowser.tabs.length, 2, "There are two tabs after restoring one");
 
       gBrowser.tabs[0].linkedBrowser.loadURI("about:blank");
       gBrowser.selectedTab = gBrowser.tabs[0];
       test8();
     });
   };
   gBrowser.tabContainer.addEventListener("TabClose", onTabClose, true);
@@ -91,15 +91,15 @@ function test9() {
   is(ZoomManager.zoom, zoomLevel, "The zoom level remains unchanged after cmd/ctrl + - is pressed");
 
   test10();
 }
 
 function test10() {
   is(gBrowser.tabs.length, 1, "There is one tab before cmd/ctrl + shift + a is pressed");
   // it would open about:addons on a new tab if it passes through the white list.
-  EventUtils.synthesizeKey("A", { accelKey: true, shiftKey: true }, contentWindow);
+  EventUtils.synthesizeKey("a", { accelKey: true, shiftKey: true }, contentWindow);
 
   executeSoon(function() {
     is(gBrowser.tabs.length, 1, "There is still one tab after cmd/ctrl + shift + a is pressed");
     hideTabView(finish);
   })
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug595020.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595020.js
@@ -6,16 +6,18 @@ let ss = Cc["@mozilla.org/browser/sessio
 let stateStartup = {windows:[
   {tabs:[{entries:[{url:"about:home"}]}], extData:{"tabview-last-session-group-name":"title"}}
 ]};
 
 function test() {
   let assertWindowTitle = function (win, title) {
     let browser = win.gBrowser.tabs[0].linkedBrowser;
     let winTitle = win.gBrowser.getWindowTitleForBrowser(browser);
+
+    info('window title is: "' + winTitle + '"');
     is(winTitle.indexOf(title), 0, "title starts with '" + title + "'");
   };
 
   let testGroupNameChange = function (win) {
     showTabView(function () {
       let cw = win.TabView.getContentWindow();
       let groupItem = cw.GroupItems.groupItems[0];
       groupItem.setTitle("new-title");
--- a/browser/base/content/test/tabview/browser_tabview_bug595191.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595191.js
@@ -52,10 +52,10 @@ function toggleTabViewTest(contentWindow
   let onTabViewHidden = function() {
     contentWindow.removeEventListener("tabviewhidden", onTabViewHidden, false);
 
     ok(!TabView.isVisible(), "Tab View is hidden");
     finish();
   }
   contentWindow.addEventListener("tabviewhidden", onTabViewHidden, false);
   // Use keyboard shortcut to toggle back to browser view
-  EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true });
+  EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true });
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug595518.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595518.js
@@ -23,17 +23,17 @@ function onTabViewWindowLoaded() {
     
     // verify that the exit button no longer has focus
     is(contentWindow.iQ("#exit-button:focus").length, 0, 
        "The exit button doesn't have the focus");
 
     // verify that the keyboard combo works (this is the crux of bug 595518)
     // Prepare the key combo
     window.addEventListener("tabviewshown", onTabViewShown, false);
-    EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true }, contentWindow);
+    EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true }, contentWindow);
   }
   
   let onTabViewShown = function() {
     window.removeEventListener("tabviewshown", onTabViewShown, false);
     
     // test if the key combo worked
     ok(TabView.isVisible(), "Tab View is visible");
 
--- a/browser/base/content/test/tabview/browser_tabview_bug595930.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595930.js
@@ -36,17 +36,17 @@ function onTabViewWindowLoaded() {
       finish();
     };
     window.addEventListener("tabviewhidden", onTabViewHidden, false);
 
     // delay to give time for hidden group DOM element to be removed so
     // the appropriate group would get selected when the key
     // combination is pressed
     executeSoon(function() { 
-      EventUtils.synthesizeKey("E", {accelKey : true, shiftKey: true}, contentWindow);
+      EventUtils.synthesizeKey("e", {accelKey : true, shiftKey: true}, contentWindow);
     });
   });
 
   group1.addSubscriber(group1, "groupHidden", function() {
     group1.removeSubscriber(group1, "groupHidden");
 
     // close undo group
     let closeButton = group1.$undoContainer.find(".close");
--- a/browser/base/content/test/tabview/browser_tabview_bug597980.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug597980.js
@@ -73,13 +73,13 @@ function part2(win) {
 
     win.addEventListener("tabviewhidden", function () {
       win.removeEventListener("tabviewhidden", arguments.callee, false);
       is(win.gBrowser.selectedTab, newTab, "The seleted tab should be the same as before (new tab)");
        win.close();
        finish();
     }, false);
     // show tabview
-    EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true }, win);
+    EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true }, win);
     // hide tabview
-    EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true }, win);
+    EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true }, win);
   })
 }
deleted file mode 100644
--- a/browser/base/content/test/tabview/browser_tabview_bug625666.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
-  let cw;
-
-  let getTabItemAspect = function (tabItem) {
-    let bounds = cw.iQ('.thumb', tabItem.container).bounds();
-    let padding = cw.TabItems.tabItemPadding;
-    return (bounds.height + padding.y) / (bounds.width + padding.x);
-  }
-
-  let getAspectRange = function () {
-    let aspect = cw.TabItems.tabAspect;
-    let variance = aspect / 100 * 1.5;
-    return new cw.Range(aspect - variance, aspect + variance);
-  }
-
-  waitForExplicitFinish();
-
-  newWindowWithTabView(function (win) {
-    registerCleanupFunction(function () win.close());
-    cw = win.TabView.getContentWindow();
-
-    // prepare orphan tab
-    let tabItem = win.gBrowser.tabs[0]._tabViewTabItem;
-    tabItem.parent.remove(tabItem, {immediately: true});
-    tabItem.setBounds(new cw.Rect(20, 20, 200, 165), true);
-
-    let bounds = tabItem.getBounds();
-
-    // prepare group item
-    let box = new cw.Rect(20, 300, 400, 200);
-    let groupItem = new cw.GroupItem([], {bounds: box, immediately: true});
-
-    groupItem.setBounds(new cw.Rect(20, 100, 400, 200));
-    groupItem.pushAway(true);
-
-    let newBounds = tabItem.getBounds();
-    ok(newBounds.width < bounds.width, "The new width of item is smaller than the old one.");
-    ok(newBounds.height < bounds.height, "The new height of item is smaller than the old one.");
-
-    let aspectRange = getAspectRange();
-    let aspect = getTabItemAspect(tabItem);
-    ok(aspectRange.contains(aspect), "orphaned tabItem's aspect is correct");
-
-    finish();
-  });
-}
--- a/browser/base/content/test/tabview/browser_tabview_bug656778.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug656778.js
@@ -25,16 +25,26 @@ function test() {
   };
 
   let assertPreferences = function (startupPage, firstRun, enabledOnce) {
     assertIntPref(TabView.PREF_STARTUP_PAGE, startupPage);
     assertBoolPref(TabView.PREF_FIRST_RUN, firstRun);
     assertBoolPref(TabView.PREF_RESTORE_ENABLED_ONCE, enabledOnce);
   };
 
+  let assertNotificationBannerVisible = function (win) {
+    let cw = win.TabView.getContentWindow();
+    is(cw.iQ(".banner").length, 1, "notification banner is visible");
+  };
+
+  let assertNotificationBannerNotVisible = function (win) {
+    let cw = win.TabView.getContentWindow();
+    is(cw.iQ(".banner").length, 0, "notification banner is not visible");
+  };
+
   let next = function () {
     if (tests.length == 0) {
       waitForFocus(finish);
       return;
     }
 
     let test = tests.shift();
     info("running " + test.name + "...");
@@ -47,16 +57,17 @@ function test() {
   //
   // Expected result:
   // When entering Panorma session restore will be enabled and a notification
   // banner is shown.
   let test1 = function test1() {
     setPreferences(1, true, false);
 
     newWindowWithTabView(function (win) {
+      assertNotificationBannerVisible(win);
       assertPreferences(3, true, true);
 
       win.close();
       next();
     });
   };
 
   // State:
@@ -67,20 +78,22 @@ function test() {
   // Expected result:
   // When entering Panorma nothing happens. When we detect that Panorama is
   // really used (firstUseExperienced = true) we notify that session restore
   // is now enabled.
   let test2 = function test2() {
     setPreferences(1, false, false);
 
     newWindowWithTabView(function (win) {
+      assertNotificationBannerNotVisible(win);
       assertPreferences(1, false, false);
 
       win.TabView.firstUseExperienced = true;
 
+      assertNotificationBannerVisible(win);
       assertPreferences(3, true, true);
 
       win.close();
       next();
     });
   };
 
   // State:
@@ -89,16 +102,17 @@ function test() {
   //
   // Expected result:
   // When entering Panorama nothing happens because session store is already
   // enabled so there's no reason to notify.
   let test3 = function test3() {
     setPreferences(3, true, false);
 
     newWindowWithTabView(function (win) {
+      assertNotificationBannerNotVisible(win);
       assertPreferences(3, true, true);
 
       win.close();
       next();
     });
   };
 
   // State:
@@ -106,16 +120,17 @@ function test() {
   // restore has been automatically activated.
   //
   // Expected result:
   // When entering Panorama nothing happens.
   let test4 = function test4() {
     setPreferences(3, true, true);
 
     newWindowWithTabView(function (win) {
+      assertNotificationBannerNotVisible(win);
       assertPreferences(3, true, true);
 
       win.close();
       next();
     });
   };
 
   // State:
@@ -124,16 +139,17 @@ function test() {
   // disabled by the user so we won't touch that again.
   //
   // Expected result:
   // When entering Panorama nothing happens and we didn't enable session restore.
   let test5 = function test5() {
     setPreferences(1, true, true);
 
     newWindowWithTabView(function (win) {
+      assertNotificationBannerNotVisible(win);
       assertPreferences(1, true, true);
 
       win.close();
       next();
     });
   };
 
   let tests = [test1, test2, test3, test4, test5];
--- a/browser/base/content/test/tabview/browser_tabview_launch.js
+++ b/browser/base/content/test/tabview/browser_tabview_launch.js
@@ -23,17 +23,17 @@ function test() {
       deck.removeEventListener("select", onSelect, true);
 
       whenTabViewIsShown(function() {
         executeSoon(function() {
           testMethodToHideAndShowTabView(function() {
             newWin.document.getElementById("menu_tabview").doCommand();
           }, function() {
             testMethodToHideAndShowTabView(function() {
-              EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true }, newWin);
+              EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true }, newWin);
             }, finish);
           });
         });
       }, win);
     };
 
     let deck = win.document.getElementById("tab-view-deck");
     deck.addEventListener("select", onSelect, true);
--- a/browser/base/content/test/tabview/head.js
+++ b/browser/base/content/test/tabview/head.js
@@ -78,19 +78,21 @@ function afterAllTabItemsUpdated(callbac
 function newWindowWithTabView(shownCallback, loadCallback, width, height) {
   let winWidth = width || 800;
   let winHeight = height || 800;
   let win = window.openDialog(getBrowserURL(), "_blank",
                               "chrome,all,dialog=no,height=" + winHeight +
                               ",width=" + winWidth);
 
   whenWindowLoaded(win, function () {
-    if (typeof loadCallback == "function")
+    if (loadCallback)
       loadCallback(win);
+  });
 
+  whenDelayedStartupFinished(win, function () {
     showTabView(function () shownCallback(win), win);
   });
 }
 
 // ----------
 function afterAllTabsLoaded(callback, win) {
   const TAB_STATE_NEEDS_RESTORE = 1;
 
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -500,33 +500,50 @@
           }
         ]]></body>
       </method>
 
       <method name="_getSelectedValueForClipboard">
         <body><![CDATA[
           // Grab the actual input field's value, not our value, which could include moz-action:
           var inputVal = this.inputField.value;
-          var val = inputVal.substring(this.selectionStart, this.selectionEnd);
+          var selectedVal = inputVal.substring(this.selectionStart, this.selectionEnd);
+
+          // If the selection doesn't start at the beginning or URL bar is
+          // modified, nothing else to do here.
+          if (this.getAttribute("pageproxystate") != "valid" || this.selectionStart > 0)
+            return selectedVal;
+
+          let uri = gBrowser.currentURI;
 
-          // If the entire value is selected and it's a valid non-javascript,
-          // non-data URI, encode it.
-          if (val == inputVal &&
-              this.getAttribute("pageproxystate") == "valid") {
-            let uri = gBrowser.currentURI;
+          // If the entire URL is selected, just use the actual loaded URI.
+          if (inputVal == selectedVal) {
+            // ... but only if  isn't a javascript: or data: URI, since those
+            // are hard to read when encoded
+            if (!uri.schemeIs("javascript") && !uri.schemeIs("data")) {
+              // Parentheses are known to confuse third-party applications (bug 458565).
+              selectedVal = uri.spec.replace(/[()]/g, function (c) escape(c));
+            }
 
-            if (uri && !uri.schemeIs("javascript") && !uri.schemeIs("data")) {
-              val = uri.spec;
-
-              // Parentheses are known to confuse third-party applications (bug 458565).
-              val = val.replace(/[()]/g, function (c) escape(c));
-            }
+            return selectedVal;
           }
 
-          return val;
+          // Just the beginning of the URL is selected, check for a trimmed
+          // value
+          let spec = uri.spec;
+          let trimmedSpec = this.trimValue(spec);
+          if (spec != trimmedSpec) {
+            // Prepend the portion that trimValue removed from the beginning.
+            // This assumes trimValue will only truncate the URL at
+            // the beginning or end (or both).
+            let trimmedSegments = spec.split(trimmedSpec);
+            selectedVal = trimmedSegments[0] + selectedVal;
+          }
+
+          return selectedVal;
         ]]></body>
       </method>
 
       <field name="_copyCutController"><![CDATA[
         ({
           urlbar: this,
           doCommand: function(aCommand) {
             var urlbar = this.urlbar;
--- a/browser/base/jar.mn
+++ b/browser/base/jar.mn
@@ -24,18 +24,18 @@ browser.jar:
         content/browser/aboutHome-snippet1.png        (content/aboutHome-snippet1.png)
         content/browser/aboutHome-snippet2.png        (content/aboutHome-snippet2.png)
         content/browser/aboutRobots-icon.png          (content/aboutRobots-icon.png)
         content/browser/aboutRobots-widget-left.png   (content/aboutRobots-widget-left.png)
 *       content/browser/browser.css                   (content/browser.css)
 *       content/browser/browser.js                    (content/browser.js)
 *       content/browser/browser.xul                   (content/browser.xul)
 *       content/browser/browser-tabPreviews.xml       (content/browser-tabPreviews.xml)
+*       content/browser/content.js                    (content/content.js)
 *       content/browser/fullscreen-video.xhtml        (content/fullscreen-video.xhtml)
-        content/browser/highlighter.xhtml             (content/highlighter.xhtml)
 *       content/browser/inspector.html                (content/inspector.html)
 *       content/browser/scratchpad.xul                (content/scratchpad.xul)
 *       content/browser/scratchpad.js                 (content/scratchpad.js)
 *       content/browser/pageinfo/pageInfo.xul         (content/pageinfo/pageInfo.xul)
 *       content/browser/pageinfo/pageInfo.js          (content/pageinfo/pageInfo.js)
 *       content/browser/pageinfo/pageInfo.css         (content/pageinfo/pageInfo.css)
 *       content/browser/pageinfo/pageInfo.xml         (content/pageinfo/pageInfo.xml)
 *       content/browser/pageinfo/feeds.js             (content/pageinfo/feeds.js)
--- a/browser/branding/aurora/pref/firefox-branding.js
+++ b/browser/branding/aurora/pref/firefox-branding.js
@@ -4,17 +4,17 @@ pref("startup.homepage_welcome_url","");
 // The time interval between checks for a new version (in seconds)
 // nightly=8 hours, official=24 hours
 pref("app.update.interval", 28800);
 // The time interval between the downloading of mar file chunks in the
 // background (in seconds)
 pref("app.update.download.backgroundInterval", 60);
 // URL user can browse to manually if for some reason all update installation
 // attempts fail.
-pref("app.update.url.manual", "http://nightly.mozilla.org/");
+pref("app.update.url.manual", "http://www.mozilla.com/firefox/channel/");
 // A default value for the "More information about this update" link
 // supplied in the "An update is available" page of the update wizard. 
 pref("app.update.url.details", "http://www.mozilla.org/projects/%APP%/");
 
 // Release notes and vendor URLs
 pref("app.releaseNotesURL", "http://www.mozilla.org/projects/%APP%/%VERSION%/releasenotes/");
 pref("app.vendorURL", "http://www.mozilla.org/projects/%APP%/");
 
--- a/browser/components/migration/src/nsProfileMigrator.cpp
+++ b/browser/components/migration/src/nsProfileMigrator.cpp
@@ -34,17 +34,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsProfileMigrator.h"
 
 #include "nsIBrowserProfileMigrator.h"
 #include "nsIComponentManager.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsILocalFile.h"
 #include "nsIObserverService.h"
 #include "nsIProperties.h"
 #include "nsIServiceManager.h"
 #include "nsISupportsPrimitives.h"
 #include "nsISupportsArray.h"
 #include "nsIToolkitProfile.h"
 #include "nsIToolkitProfileService.h"
--- a/browser/components/places/tests/browser/browser_410196_paste_into_tags.js
+++ b/browser/components/places/tests/browser/browser_410196_paste_into_tags.js
@@ -19,22 +19,20 @@ Components.utils.import("resource://gre/
 const TEST_URL = "http://example.com/";
 const MOZURISPEC = "http://mozilla.com/";
 
 let gLibrary;
 let PlacesOrganizer;
 
 function test() {
   waitForExplicitFinish();
-  openLibrary(onLibraryReady);
+  gLibrary = openLibrary(onLibraryReady);
 }
 
-function onLibraryReady(library) {
-  gLibrary = library;
-
+function onLibraryReady() {
   ok(PlacesUtils, "PlacesUtils in scope");
   ok(PlacesUIUtils, "PlacesUIUtils in scope");
 
   PlacesOrganizer = gLibrary.PlacesOrganizer;
   ok(PlacesOrganizer, "Places organizer in scope");
 
   tests.makeHistVisit();
   tests.makeTag();
--- a/browser/components/places/tests/browser/browser_416459_cut.js
+++ b/browser/components/places/tests/browser/browser_416459_cut.js
@@ -1,23 +1,24 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 const TEST_URL = "http://example.com/";
 
 let gLibrary;
 let gItemId;
+let PlacesOrganizer;
 
 function test() {
   waitForExplicitFinish();
   gLibrary = openLibrary(onLibraryReady);
 }
 
-function onLibraryReady(library) {
+function onLibraryReady() {
   PlacesOrganizer = gLibrary.PlacesOrganizer;
 
   // Sanity checks.
   ok(PlacesUtils, "PlacesUtils in scope");
   ok(PlacesUIUtils, "PlacesUIUtils in scope");
   ok(PlacesOrganizer, "PlacesOrganizer in scope");
 
   gItemId = PlacesUtils.bookmarks.insertBookmark(
--- a/browser/components/places/tests/browser/browser_library_batch_delete.js
+++ b/browser/components/places/tests/browser/browser_library_batch_delete.js
@@ -91,26 +91,23 @@ gTests.push({
 
 function test() {
   waitForExplicitFinish();
   registerCleanupFunction(function () {
     PlacesUtils.bookmarks
                .removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
   });
 
-  openLibrary(function (library) {
-    gLibrary = library;
-    executeSoon(nextTest);
-  });
+  gLibrary = openLibrary(nextTest);
 }
 
 function nextTest() {
   if (gTests.length) {
     var test = gTests.shift();
     info("Start of test: " + test.desc);
     test.run();
   }
   else {
     // Close Library window.
     gLibrary.close();
-    executeSoon(finish);
+    finish();
   }
 }
--- a/browser/components/places/tests/browser/browser_library_left_pane_commands.js
+++ b/browser/components/places/tests/browser/browser_library_left_pane_commands.js
@@ -175,13 +175,10 @@ function nextTest() {
 
 function test() {
   waitForExplicitFinish();
   // Sanity checks.
   ok(PlacesUtils, "PlacesUtils is running in chrome context");
   ok(PlacesUIUtils, "PlacesUIUtils is running in chrome context");
 
   // Open Library.
-  openLibrary(function (library) {
-    gLibrary = library;
-    nextTest();
-  });
+  gLibrary = openLibrary(nextTest);
 }
--- a/browser/components/places/tests/browser/browser_library_middleclick.js
+++ b/browser/components/places/tests/browser/browser_library_middleclick.js
@@ -79,23 +79,27 @@ var gTabsListener = {
     if (gCurrentTest.URIs.indexOf(spec) != -1 )
       this._loadedURIs.push(spec);
 
     if (this._loadedURIs.length == gCurrentTest.URIs.length) {
       // We have correctly opened all URIs.
 
       // Reset arrays.
       this._loadedURIs.length = 0;
-      // Close all tabs.
-      while (gBrowser.tabs.length > 1)
-        gBrowser.removeCurrentTab();
+
       this._openTabsCount = 0;
 
-      // Test finished.  This will move to the next one.
-      waitForFocus(gCurrentTest.finish, gBrowser.ownerDocument.defaultView);
+      executeSoon(function () {
+        // Close all tabs.
+        while (gBrowser.tabs.length > 1)
+          gBrowser.removeCurrentTab();
+
+        // Test finished.  This will move to the next one.
+        waitForFocus(gCurrentTest.finish, gBrowser.ownerDocument.defaultView);
+      });
     }
   }
 }
 
 //------------------------------------------------------------------------------
 // Open bookmark in a new tab.
 
 gTests.push({
--- a/browser/components/preferences/sync.js
+++ b/browser/components/preferences/sync.js
@@ -109,20 +109,20 @@ let gSyncPane = {
 
   startOver: function (showDialog) {
     if (showDialog) {
       let flags = Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING +
                   Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_CANCEL + 
                   Services.prompt.BUTTON_POS_1_DEFAULT;
       let buttonChoice =
         Services.prompt.confirmEx(window,
-                                  this._stringBundle.GetStringFromName("stopUsingAccount.title"),
-                                  this._stringBundle.GetStringFromName("differentAccount.label"),
+                                  this._stringBundle.GetStringFromName("syncUnlink.title"),
+                                  this._stringBundle.GetStringFromName("syncUnlink.label"),
                                   flags,
-                                  this._stringBundle.GetStringFromName("differentAccountConfirm.label"),
+                                  this._stringBundle.GetStringFromName("syncUnlinkConfirm.label"),
                                   null, null, null, {});
 
       // If the user selects cancel, just bail
       if (buttonChoice == 1)
         return;
     }
 
     Weave.Service.startOver();
--- a/browser/components/preferences/sync.xul
+++ b/browser/components/preferences/sync.xul
@@ -96,22 +96,22 @@
             <hbox>
               <button type="menu"
                       label="&manageAccount.label;"
                       accesskey="&manageAccount.accesskey;">
                 <menupopup>
                   <menuitem label="&viewQuota.label;"
                             oncommand="gSyncPane.openQuotaDialog();"/>
                   <menuseparator/>
-                  <menuitem label="&changePassword.label;"
+                  <menuitem label="&changePassword2.label;"
                             oncommand="gSyncUtils.changePassword();"/>
                   <menuitem label="&mySyncKey.label;"
                             oncommand="gSyncUtils.resetPassphrase();"/>
                   <menuseparator/>
-                  <menuitem label="&resetSync.label;"
+                  <menuitem label="&resetSync2.label;"
                             oncommand="gSyncPane.resetSync();"/>
                 </menupopup>
               </button>
             </hbox>
 
             <hbox>
               <label id="syncAddDeviceLabel"
                      class="text-link"
@@ -167,17 +167,17 @@
                   <textbox id="syncComputerName"
                            onchange="gSyncUtils.changeName(this)"/>
                 </row>
               </rows>
             </grid>
             <hbox>
               <label class="text-link"
                      onclick="gSyncPane.startOver(true); return false;"
-                     value="&deactivateDevice.label;"/>
+                     value="&unlinkDevice.label;"/>
             </hbox>
           </groupbox>
           <hbox id="tosPP" pack="center">
             <label class="text-link"
                    onclick="event.stopPropagation();gSyncUtils.openToS();"
                    value="&prefs.tosLink.label;"/>
             <label class="text-link"
                    onclick="event.stopPropagation();gSyncUtils.openPrivacyPolicy();"
@@ -192,13 +192,13 @@
                    onclick="gSyncPane.updatePass(); return false;"
                    value="&updatePass.label;"/>
             <label class="text-link"
                    onclick="gSyncPane.resetPass(); return false;"
                    value="&resetPass.label;"/>
           </hbox>
           <label class="text-link"
                  onclick="gSyncPane.startOver(true); return false;"
-                 value="&deactivateDevice.label;"/>
+                 value="&unlinkDevice.label;"/>
         </vbox>
       </deck>
   </prefpane>
 </overlay>
--- a/browser/components/preferences/tests/browser_permissions.js
+++ b/browser/components/preferences/tests/browser_permissions.js
@@ -290,17 +290,17 @@ function getSiteItem(aHost) {
 
 function addWindowListener(aURL, aCallback) {
   Services.wm.addListener({
     onOpenWindow: function(aXULWindow) {
       info("window opened, waiting for focus");
       Services.wm.removeListener(this);
 
       var domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
-                                .getInterface(Ci.nsIDOMWindowInternal);
+                                .getInterface(Ci.nsIDOMWindow);
       waitForFocus(function() {
         is(domwindow.document.location.href, aURL, "should have seen the right window open");
         domwindow.close();
         aCallback();
       }, domwindow);
     },
     onCloseWindow: function(aXULWindow) { },
     onWindowTitleChange: function(aXULWindow, aNewTitle) { }
--- a/browser/components/sessionstore/content/aboutSessionRestore.js
+++ b/browser/components/sessionstore/content/aboutSessionRestore.js
@@ -284,16 +284,17 @@ var treeView = {
   getCellText: function(idx, column) { return gTreeData[idx].label; },
   isContainer: function(idx)         { return "open" in gTreeData[idx]; },
   getCellValue: function(idx, column){ return gTreeData[idx].checked; },
   isContainerOpen: function(idx)     { return gTreeData[idx].open; },
   isContainerEmpty: function(idx)    { return false; },
   isSeparator: function(idx)         { return false; },
   isSorted: function()               { return false; },
   isEditable: function(idx, column)  { return false; },
+  canDrop: function(idx, orientation, dt) { return false; },
   getLevel: function(idx)            { return this.isContainer(idx) ? 0 : 1; },
 
   getParentIndex: function(idx) {
     if (!this.isContainer(idx))
       for (var t = idx - 1; t >= 0 ; t--)
         if (this.isContainer(t))
           return t;
     return -1;
--- a/browser/components/sessionstore/nsISessionStartup.idl
+++ b/browser/components/sessionstore/nsISessionStartup.idl
@@ -38,21 +38,21 @@
 #include "nsISupports.idl"
 
 /**
  * nsISessionStore keeps track of the current browsing state - i.e.
  * tab history, cookies, scroll state, form data, POSTDATA and window features
  * - and allows to restore everything into one window.
  */
 
-[scriptable, uuid(e7bb7828-0e32-4995-a848-4aa35df603c7)]
+[scriptable, uuid(170c6857-7f71-46ce-bc9b-185723b1c3a8)]
 interface nsISessionStartup: nsISupports
 {
-  // Get session state as string
-  readonly attribute AString state;
+  // Get session state
+  readonly attribute jsval state;
 
   /**
    * Determine if session should be restored 
    */
   boolean doRestore();
 
   /**
    * What type of session we're restoring.
--- a/browser/components/sessionstore/src/nsSessionStartup.js
+++ b/browser/components/sessionstore/src/nsSessionStartup.js
@@ -84,17 +84,17 @@ function debug(aMsg) {
 /* :::::::: The Service ::::::::::::::: */
 
 function SessionStartup() {
 }
 
 SessionStartup.prototype = {
 
   // the state to restore at startup
-  _iniString: null,
+  _initialState: null,
   _sessionType: Ci.nsISessionStartup.NO_SESSION,
 
 /* ........ Global Event Handlers .............. */
 
   /**
    * Initialize the component
    */
   init: function sss_init() {
@@ -116,64 +116,63 @@ SessionStartup.prototype = {
     let doResumeSession = prefBranch.getBoolPref("sessionstore.resume_session_once") ||
                           prefBranch.getIntPref("startup.page") == 3;
 
     // only continue if the session file exists
     if (!sessionFile.exists())
       return;
 
     // get string containing session state
-    this._iniString = this._readStateFile(sessionFile);
-    if (!this._iniString)
+    let iniString = this._readStateFile(sessionFile);
+    if (!iniString)
       return;
 
     // parse the session state into a JS object
-    let initialState;
     try {
       // remove unneeded braces (added for compatibility with Firefox 2.0 and 3.0)
-      if (this._iniString.charAt(0) == '(')
-        this._iniString = this._iniString.slice(1, -1);
+      if (iniString.charAt(0) == '(')
+        iniString = iniString.slice(1, -1);
       try {
-        initialState = JSON.parse(this._iniString);
+        this._initialState = JSON.parse(iniString);
       }
       catch (exJSON) {
         var s = new Cu.Sandbox("about:blank");
-        initialState = Cu.evalInSandbox("(" + this._iniString + ")", s);
-        this._iniString = JSON.stringify(initialState);
+        this._initialState = Cu.evalInSandbox("(" + iniString + ")", s);
       }
     }
     catch (ex) { debug("The session file is invalid: " + ex); }
 
     let resumeFromCrash = prefBranch.getBoolPref("sessionstore.resume_from_crash");
     let lastSessionCrashed =
-      initialState && initialState.session && initialState.session.state &&
-      initialState.session.state == STATE_RUNNING_STR;
+      this._initialState && this._initialState.session &&
+      this._initialState.session.state &&
+      this._initialState.session.state == STATE_RUNNING_STR;
 
     // Report shutdown success via telemetry. Shortcoming here are
     // being-killed-by-OS-shutdown-logic, shutdown freezing after
     // session restore was written, etc.
     let Telemetry = Cc["@mozilla.org/base/telemetry;1"].getService(Ci.nsITelemetry);
     Telemetry.getHistogramById("SHUTDOWN_OK").add(!lastSessionCrashed);
 
     // set the startup type
     if (lastSessionCrashed && resumeFromCrash)
       this._sessionType = Ci.nsISessionStartup.RECOVER_SESSION;
     else if (!lastSessionCrashed && doResumeSession)
       this._sessionType = Ci.nsISessionStartup.RESUME_SESSION;
-    else if (initialState)
+    else if (this._initialState)
       this._sessionType = Ci.nsISessionStartup.DEFER_SESSION;
     else
-      this._iniString = null; // reset the state string
+      this._initialState = null; // reset the state
 
     // wait for the first browser window to open
     // Don't reset the initial window's default args (i.e. the home page(s))
     // if all stored tabs are pinned.
     if (this.doRestore() &&
-        (!initialState.windows ||
-        !initialState.windows.every(function (win)
+        (!this._initialState.windows ||
+        !this._initialState.windows.every(function (win)
            win.tabs.every(function (tab) tab.pinned))))
       Services.obs.addObserver(this, "domwindowopened", true);
 
     Services.obs.addObserver(this, "sessionstore-windows-restored", true);
   },
 
   /**
    * Handle notifications
@@ -199,18 +198,18 @@ SessionStartup.prototype = {
       var self = this;
       window.addEventListener("load", function() {
         self._onWindowOpened(window);
         window.removeEventListener("load", arguments.callee, false);
       }, false);
       break;
     case "sessionstore-windows-restored":
       Services.obs.removeObserver(this, "sessionstore-windows-restored");
-      // free _iniString after nsSessionStore is done with it
-      this._iniString = null;
+      // free _initialState after nsSessionStore is done with it
+      this._initialState = null;
       this._sessionType = Ci.nsISessionStartup.NO_SESSION;
       break;
     }
   },
 
   /**
    * Removes the default arguments from the first browser window
    * (and removes the "domwindowopened" observer afterwards).
@@ -249,17 +248,17 @@ SessionStartup.prototype = {
   },
 
 /* ........ Public API ................*/
 
   /**
    * Get the session state as a string
    */
   get state() {
-    return this._iniString;
+    return this._initialState;
   },
 
   /**
    * Determine whether there is a pending session restore.
    * @returns bool
    */
   doRestore: function sss_doRestore() {
     return this._sessionType == Ci.nsISessionStartup.RECOVER_SESSION ||
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -299,55 +299,53 @@ SessionStoreService.prototype = {
 
     // get file references
     this._sessionFile = Services.dirsvc.get("ProfD", Ci.nsILocalFile);
     this._sessionFileBackup = this._sessionFile.clone();
     this._sessionFile.append("sessionstore.js");
     this._sessionFileBackup.append("sessionstore.bak");
 
     // get string containing session state
-    var iniString;
     var ss = Cc["@mozilla.org/browser/sessionstartup;1"].
              getService(Ci.nsISessionStartup);
     try {
       if (ss.doRestore() ||
           ss.sessionType == Ci.nsISessionStartup.DEFER_SESSION)
-        iniString = ss.state;
+        this._initialState = ss.state;
     }
     catch(ex) { dump(ex + "\n"); } // no state to restore, which is ok
 
-    if (iniString) {
+    if (this._initialState) {
       try {
         // If we're doing a DEFERRED session, then we want to pull pinned tabs
         // out so they can be restored.
         if (ss.sessionType == Ci.nsISessionStartup.DEFER_SESSION) {
-          let [iniState, remainingState] = this._prepDataForDeferredRestore(iniString);
+          let [iniState, remainingState] = this._prepDataForDeferredRestore(this._initialState);
           // If we have a iniState with windows, that means that we have windows
           // with app tabs to restore.
           if (iniState.windows.length)
             this._initialState = iniState;
+          else
+            this._initialState = null;
           if (remainingState.windows.length)
             this._lastSessionState = remainingState;
         }
         else {
-          // parse the session state into JS objects
-          this._initialState = JSON.parse(iniString);
-
           let lastSessionCrashed =
             this._initialState.session && this._initialState.session.state &&
             this._initialState.session.state == STATE_RUNNING_STR;
           if (lastSessionCrashed) {
             this._recentCrashes = (this._initialState.session &&
                                    this._initialState.session.recentCrashes || 0) + 1;
             
             if (this._needsRestorePage(this._initialState, this._recentCrashes)) {
               // replace the crashed session with a restore-page-only session
               let pageData = {
                 url: "about:sessionrestore",
-                formdata: { "#sessionData": iniString }
+                formdata: { "#sessionData": JSON.stringify(this._initialState) }
               };
               this._initialState = { windows: [{ tabs: [{ entries: [pageData] }] }] };
             }
           }
 
           // Load the session start time from the previous state
           this._sessionStartTime = this._initialState.session &&
                                    this._initialState.session.startTime ||
@@ -806,17 +804,17 @@ SessionStoreService.prototype = {
         if (!this._doResumeSession()) {
 #endif
           // We want to split the window up into pinned tabs and unpinned tabs.
           // Pinned tabs should be restored. If there are any remaining tabs,
           // they should be added back to _closedWindows.
           // We'll cheat a little bit and reuse _prepDataForDeferredRestore
           // even though it wasn't built exactly for this.
           let [appTabsState, normalTabsState] =
-            this._prepDataForDeferredRestore(JSON.stringify({ windows: [closedWindowState] }));
+            this._prepDataForDeferredRestore({ windows: [closedWindowState] });
 
           // These are our pinned tabs, which we should restore
           if (appTabsState.windows.length) {
             newWindowState = appTabsState.windows[0];
             delete newWindowState.__lastSessionWindowID;
           }
 
           // In case there were no unpinned tabs, remove the window from _closedWindows
@@ -2217,18 +2215,24 @@ SessionStoreService.prototype = {
     var jscookies = {};
     var _this = this;
     // MAX_EXPIRY should be 2^63-1, but JavaScript can't handle that precision
     var MAX_EXPIRY = Math.pow(2, 62);
     aWindows.forEach(function(aWindow) {
       if (!aWindow._hosts)
         return;
       for (var [host, isPinned] in Iterator(aWindow._hosts)) {
-        var list = CookieSvc.getCookiesFromHost(host);
-        while (list.hasMoreElements()) {
+        let list;
+        try {
+          list = CookieSvc.getCookiesFromHost(host);
+        }
+        catch (ex) {
+          debug("getCookiesFromHost failed. Host: " + host);
+        }
+        while (list && list.hasMoreElements()) {
           var cookie = list.getNext().QueryInterface(Ci.nsICookie2);
           // aWindow._hosts will only have hosts with the right privacy rules,
           // so there is no need to do anything special with this call to
           // _checkPrivacyLevel.
           if (cookie.isSession && _this._checkPrivacyLevel(cookie.isSecure, isPinned)) {
             // use the cookie's host, path, and name as keys into a hash,
             // to make sure we serialize each cookie only once
             if (!(cookie.host in jscookies &&
@@ -2947,18 +2951,21 @@ SessionStoreService.prototype = {
     if (tabData.userTypedValue) {
       browser.userTypedValue = tabData.userTypedValue;
       if (tabData.userTypedClear) {
         // Make it so that we'll enter restoreDocument on page load. We will
         // fire SSTabRestored from there. We don't have any form data to restore
         // so we can just set the URL to null.
         browser.__SS_restore_data = { url: null };
         browser.__SS_restore_tab = aTab;
+        if (didStartLoad)
+          browser.stop();
         didStartLoad = true;
-        browser.loadURI(tabData.userTypedValue, null, null, true);
+        browser.loadURIWithFlags(tabData.userTypedValue,
+                                 Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP);
       }
     }
 
     // If we didn't start a load, then we won't reset this tab through the usual
     // channel (via the progress listener), so reset the tab ourselves. We will
     // also send SSTabRestored since this tab has technically been restored.
     if (!didStartLoad) {
       this._sendTabRestoredNotification(aTab);
@@ -3780,22 +3787,21 @@ SessionStoreService.prototype = {
    * defaultState will be comprised of windows with only pinned tabs, extracted
    * from state. It will contain the cookies that go along with the history
    * entries in those tabs. It will also contain window position information.
    *
    * defaultState will be restored at startup. state will be placed into
    * this._lastSessionState and will be kept in case the user explicitly wants
    * to restore the previous session (publicly exposed as restoreLastSession).
    *
-   * @param stateString
-   *        The state string, presumably from nsISessionStartup.state
+   * @param state
+   *        The state, presumably from nsISessionStartup.state
    * @returns [defaultState, state]
    */
-  _prepDataForDeferredRestore: function sss__prepDataForDeferredRestore(stateString) {
-    let state = JSON.parse(stateString);
+  _prepDataForDeferredRestore: function sss__prepDataForDeferredRestore(state) {
     let defaultState = { windows: [], selectedWindow: 1 };
 
     state.selectedWindow = state.selectedWindow || 1;
 
     // Look at each window, remove pinned tabs, adjust selectedindex,
     // remove window if necessary.
     for (let wIndex = 0; wIndex < state.windows.length;) {
       let window = state.windows[wIndex];
--- a/browser/components/wintaskbar/test/browser_taskbar_preview.js
+++ b/browser/components/wintaskbar/test/browser_taskbar_preview.js
@@ -124,16 +124,16 @@ function test() {
       thumbnailWidth = thumbnailHeight * ratio;
     else
       thumbnailHeight = thumbnailWidth / ratio;
 
     return getCanvas(thumbnailWidth, thumbnailHeight);
   }
 
   function getCanvas(width, height) {
-    let win = window.QueryInterface(Ci.nsIDOMWindowInternal);
+    let win = window.QueryInterface(Ci.nsIDOMWindow);
     let doc = win.document;
     let canvas = doc.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
     canvas.width = width;
     canvas.height = height;
     return canvas;
   }
 }
--- a/browser/fuel/src/fuelApplication.js
+++ b/browser/fuel/src/fuelApplication.js
@@ -217,17 +217,17 @@ BrowserTab.prototype = {
   /*
    * Helper event callback used to redirect events made on the XBL element
    */
   _event : function bt_event(aEvent) {
     if (aEvent.type == "load") {
       if (!(aEvent.originalTarget instanceof Ci.nsIDOMDocument))
         return;
 
-      if (aEvent.originalTarget.defaultView instanceof Ci.nsIDOMWindowInternal &&
+      if (aEvent.originalTarget.defaultView instanceof Ci.nsIDOMWindow &&
           aEvent.originalTarget.defaultView.frameElement)
         return;
     }
     this._events.dispatch(aEvent.type, this);
   },
   /*
    * Helper used to determine the index offset of the browsertab
    */
--- a/browser/fuel/test/browser_Application.js
+++ b/browser/fuel/test/browser_Application.js
@@ -29,17 +29,17 @@ WindowOpenListener.prototype = {
   },
 
   onOpenWindow: function(window) {
     if (this.window)
       return;
 
     this.window = window;
     this.domwindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
-                           .getInterface(Ci.nsIDOMWindowInternal);
+                           .getInterface(Ci.nsIDOMWindow);
     this.domwindow.addEventListener("load", this, false);
   },
 
   onCloseWindow: function(window) {
     if (this.window != window)
       return;
 
     Services.wm.removeListener(this);
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -40,16 +40,19 @@
 #ifndef MOZ_STATIC_JS
 @BINPATH@/@DLL_PREFIX@mozjs@DLL_SUFFIX@
 #endif
 @BINPATH@/@DLL_PREFIX@plc4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@plds4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@xpcom@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@nspr4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@mozalloc@DLL_SUFFIX@
+#ifdef MOZ_MEMORY_DARWIN
+@BINPATH@/@DLL_PREFIX@jemalloc@DLL_SUFFIX@
+#endif
 #ifdef XP_MACOSX
 @BINPATH@/XUL
 #else
 @BINPATH@/@DLL_PREFIX@xul@DLL_SUFFIX@
 #endif
 #ifdef XP_MACOSX
 @BINPATH@/@MOZ_CHILD_PROCESS_NAME@.app/
 @BINPATH@/@DLL_PREFIX@plugin_child_interpose@DLL_SUFFIX@
@@ -93,17 +96,16 @@
 #endif
 @BINPATH@/application.ini
 @BINPATH@/platform.ini
 #ifndef XP_OS2
 @BINPATH@/@DLL_PREFIX@mozsqlite3@DLL_SUFFIX@
 #else
 @BINPATH@/mozsqlt3@DLL_SUFFIX@
 #endif
-@BINPATH@/README.txt
 @BINPATH@/blocklist.xml
 #ifdef XP_UNIX
 @BINPATH@/run-mozilla.sh
 #ifndef XP_MACOSX
 @BINPATH@/mozilla-xremote-client
 #endif
 #endif
 #ifdef MOZ_SPLASHSCREEN
--- a/browser/installer/removed-files.in
+++ b/browser/installer/removed-files.in
@@ -224,16 +224,17 @@ extensions/testpilot@labs.mozilla.com/sk
 extensions/testpilot@labs.mozilla.com/tests/test_data_store.js
 greprefs/all.js
 greprefs/security-prefs.js
 greprefs/xpinstall.js
 install.rdf
 modules/JSON.jsm
 mozilla-runtime@BIN_SUFFIX@
 old-homepage-default.properties
+README.txt
 res/arrow.gif
 res/arrowd.gif
 res/broken-image.gif
 res/broken-image.png
 res/charsetData.properties
 res/charsetalias.properties
 res/cmessage.txt
 res/fonts/fontEncoding.properties
--- a/browser/locales/Makefile.in
+++ b/browser/locales/Makefile.in
@@ -120,37 +120,23 @@ libs::
 	    $(LOCALE_SRCDIR)/existing-profile-defaults.js > $(FINAL_TARGET)/defaults/existing-profile-defaults.js; \
 	fi
 install::
 	@if test -f "$(LOCALE_SRCDIR)/existing-profile-defaults.js"; then \
 	  $(PYTHON) $(topsrcdir)/config/Preprocessor.py $(PREF_PPFLAGS) $(DEFINES) $(ACDEFINES) $(XULPPFLAGS) \
 	    $(LOCALE_SRCDIR)/existing-profile-defaults.js > $(DESTDIR)$(mozappdir)/defaults/existing-profile-defaults.js; \
 	fi
 
-README_FILE = $(call MERGE_FILE,README.txt)
-
 PROFILE_FILES = \
 	localstore.rdf \
 	mimeTypes.rdf \
 	$(NULL)
 
 PROFILE_CHROME = userChrome-example.css userContent-example.css
 
-libs:: $(README_FILE)
-ifeq ($(OS_ARCH),WINNT)
-	$(EXIT_ON_ERROR) \
-	for file in $^; do \
-	  $(PERL) -pe 's/(?<!\r)\n/\r\n/g;' < $$file > $(FINAL_TARGET)/`basename $$file`; \
-	done
-else
-ifneq ($(OS_ARCH),OS2)
-	$(SYSINSTALL) $(IFLAGS1) $^ $(FINAL_TARGET)
-endif
-endif
-
 NO_JA_JP_MAC_AB_CD := $(if $(filter ja-JP-mac, $(AB_CD)),ja,$(AB_CD))
 
 %/defaults/profile/bookmarks.html: bookmarks.inc generic/profile/bookmarks.html.in
 	$(SYSINSTALL) -D $(dir $@)
 	$(PYTHON) $(topsrcdir)/config/Preprocessor.py \
 	  -I $< \
 	  -DAB_CD=$(NO_JA_JP_MAC_AB_CD) \
 	  $(srcdir)/generic/profile/bookmarks.html.in \
deleted file mode 100644
--- a/browser/locales/en-US/README.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-For information about installing, running and configuring Firefox 
-including a list of known issues and troubleshooting information, 
-refer to: http://getfirefox.com/releases/
-
--- a/browser/locales/en-US/chrome/browser/preferences/preferences.properties
+++ b/browser/locales/en-US/chrome/browser/preferences/preferences.properties
@@ -106,11 +106,11 @@ offlinepermissionstitle=Offline Data
 
 ####Preferences::Advanced::Network
 #LOCALIZATION NOTE: The next string is for the disk usage of the http cache.
 #   e.g., "Your cache is currently using 200 MB"
 #   %1$S = size
 #   %2$S = unit (MB, KB, etc.)
 actualCacheSize=Your cache is currently using %1$S %2$S of disk space
 
-stopUsingAccount.title=Do you want to stop using this account?
-differentAccount.label=This will reset all of your Sync account information and preferences.
-differentAccountConfirm.label=Reset All Information
+syncUnlink.title=Do you want to unlink your device?
+syncUnlink.label=This device will no longer be associated with your Sync account. All of your personal data, both on this device and in your Sync account, will remain intact.
+syncUnlinkConfirm.label=Unlink
--- a/browser/locales/en-US/chrome/browser/preferences/sync.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/sync.dtd
@@ -8,19 +8,20 @@
 <!-- Login error feedback -->
 <!ENTITY updatePass.label             "Update">
 <!ENTITY resetPass.label              "Reset">
 
 <!-- Manage Account -->
 <!ENTITY manageAccount.label          "Manage Account">
 <!ENTITY manageAccount.accesskey      "A">
 <!ENTITY viewQuota.label              "View Quota">
-<!ENTITY changePassword.label         "Change Password">
+<!ENTITY changePassword2.label         "Change Password…">
 <!ENTITY mySyncKey.label              "My Sync Key">
-<!ENTITY resetSync.label              "Reset Sync">
+<!ENTITY resetSync2.label              "Reset Sync…">
+
 <!ENTITY addDevice.label              "Add a Device">
 
 <!ENTITY syncMy.label               "Sync My">
 <!ENTITY engine.bookmarks.label     "Bookmarks">
 <!ENTITY engine.bookmarks.accesskey "m">
 <!ENTITY engine.tabs.label          "Tabs">
 <!ENTITY engine.tabs.accesskey      "T">
 <!ENTITY engine.history.label       "History">
@@ -28,13 +29,13 @@
 <!ENTITY engine.passwords.label     "Passwords">
 <!ENTITY engine.passwords.accesskey "P">
 <!ENTITY engine.prefs.label         "Preferences">
 <!ENTITY engine.prefs.accesskey     "S">
 
 <!-- Device Settings -->
 <!ENTITY syncComputerName.label       "Computer Name:">
 <!ENTITY syncComputerName.accesskey   "c">
-<!ENTITY deactivateDevice.label       "Deactivate This Device">
+<!ENTITY unlinkDevice.label           "Unlink This Device">
 
 <!-- Footer stuff -->
 <!ENTITY prefs.tosLink.label        "Terms of Service">
 <!ENTITY prefs.ppLink.label         "Privacy Policy">
--- a/browser/locales/en-US/chrome/browser/tabview.properties
+++ b/browser/locales/en-US/chrome/browser/tabview.properties
@@ -1,4 +1,5 @@
 tabview.groupItem.newTabButton=New tab
 tabview.groupItem.defaultName=Name this tab group…
 tabview.groupItem.undoCloseGroup=Undo Close Group
 tabview.search.otherWindowTabs=Tabs from other windows
+tabview.notification.sessionStore=Tabs and groups will automatically be restored the next time you start %S.
--- a/browser/makefiles.sh
+++ b/browser/makefiles.sh
@@ -93,16 +93,15 @@ if [ "$ENABLE_TESTS" ]; then
     browser/components/sessionstore/test/Makefile
     browser/components/sessionstore/test/browser/Makefile
     browser/components/shell/test/Makefile
     browser/components/feeds/test/Makefile
     browser/components/feeds/test/chrome/Makefile
     browser/components/places/tests/Makefile
     browser/components/places/tests/chrome/Makefile
     browser/components/places/tests/browser/Makefile
-    browser/components/places/tests/perf/Makefile
     browser/components/privatebrowsing/test/Makefile
     browser/components/privatebrowsing/test/browser/Makefile
     browser/components/safebrowsing/content/test/Makefile
     browser/components/wintaskbar/test/Makefile
     browser/fuel/test/Makefile
   "
 fi
--- a/browser/themes/gnomestripe/browser/browser.css
+++ b/browser/themes/gnomestripe/browser/browser.css
@@ -1930,8 +1930,32 @@ panel[dimmed="true"] {
 }
 
 .statuspanel-label:-moz-locale-dir(rtl):not([mirror]),
 .statuspanel-label:-moz-locale-dir(ltr)[mirror] {
   border-left-style: solid;
   border-top-left-radius: .3em;
   margin-left: 1em;
 }
+
+/* Highlighter */
+
+.highlighter-veil {
+  background-color: rgba(0, 0, 0, 0.5);
+}
+
+#highlighter-close-button {
+  list-style-image: url("chrome://browser/skin/KUI-close.png");
+  top: 12px;
+  right: 12px;
+  cursor: pointer;
+}
+
+#highlighter-close-button:-moz-locale-dir(rtl)  {
+  right: auto;
+  left: 12px;
+}
+
+#highlighter-veil-transparentbox {
+  box-shadow: 0 0 0 1px rgba(0,0,0,0.5);
+  outline: 1px dashed rgba(255,255,255,0.5);
+  outline-offset: -1px;
+}
deleted file mode 100644
--- a/browser/themes/gnomestripe/browser/highlighter.css
+++ /dev/null
@@ -1,104 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Mozilla Inspector Module.
- *
- * The Initial Developer of the Original Code is
- * The Mozilla Foundation.
- * Portions created by the Initial Developer are Copyright (C) 2011
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Rob Campbell <rcampbell@mozilla.com> (original author)
- *   Paul Rouget <paul@mozilla.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-body {
-  margin: 0;
-  overflow: hidden;
-}
-
-#close-button {
-  background-image: url("KUI-close.png");
-  border: none;
-  padding: 0;
-  width: 24px;
-  height: 24px;
-  position: fixed;
-  top: 12px;
-  right: 12px;
-  z-index: 1;
-  cursor: pointer;
-}
-
-.veil {
-  background-color: rgba(0, 0, 0, 0.5);
-}
-
-.veil, #veil-middlebox, #veil-transparentbox {
-  -moz-transition: 0.1s;
-  -moz-transition-timing-function: linear;
-}
-
-#veil-container {
-  position: absolute;
-  top: 0;
-  left: 0;
-  width: 100%;
-  height: 100%;
-}
-
-#veil {
-  width: 100%;
-  height: 100%;
-  display: -moz-box;
-  -moz-box-orient: vertical;
-}
-
-#veil-topbox, #veil-bottombox {
-  width: 100%;
-}
-
-#veil-bottombox {
-  -moz-box-flex: 1;
-}
-
-#veil-middlebox {
-  display: -moz-box;
-  -moz-box-orient: horizontal;
-}
-
-#veil-leftbox, #veil-rightbox {
-  height: 100%;
-}
-
-#veil-rightbox {
-  -moz-box-flex: 1;
-}
-
-#veil {
-  vertical-align: top;
-}
--- a/browser/themes/gnomestripe/browser/jar.mn
+++ b/browser/themes/gnomestripe/browser/jar.mn
@@ -12,17 +12,16 @@ browser.jar:
   skin/classic/browser/actionicon-tab.png
 * skin/classic/browser/browser.css                    (browser.css)
 * skin/classic/browser/engineManager.css              (engineManager.css)
   skin/classic/browser/fullscreen-video.css
   skin/classic/browser/inspector.css
   skin/classic/browser/Geolocation-16.png
   skin/classic/browser/Geolocation-64.png
   skin/classic/browser/Go-arrow.png
-* skin/classic/browser/highlighter.css
   skin/classic/browser/identity.png
   skin/classic/browser/Info.png
   skin/classic/browser/KUI-close.png
   skin/classic/browser/monitor.png
   skin/classic/browser/monitor_16-10.png
 * skin/classic/browser/pageInfo.css
   skin/classic/browser/pageInfo.png
   skin/classic/browser/page-livemarks.png
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -2503,8 +2503,33 @@ panel[dimmed="true"] {
 }
 
 .statuspanel-label:-moz-locale-dir(rtl):not([mirror]),
 .statuspanel-label:-moz-locale-dir(ltr)[mirror] {
   border-left-style: solid;
   border-top-left-radius: .3em;
   margin-left: 1em;
 }
+
+
+/* Highlighter */
+
+.highlighter-veil {
+  background-color: rgba(0, 0, 0, 0.5);
+}
+
+#highlighter-close-button {
+  list-style-image: url("chrome://browser/skin/KUI-close.png");
+  top: 12px;
+  right: 12px;
+  cursor: pointer;
+}
+
+#highlighter-close-button:-moz-locale-dir(rtl)  {
+  right: auto;
+  left: 12px;
+}
+
+#highlighter-veil-transparentbox {
+  box-shadow: 0 0 0 1px rgba(0,0,0,0.5);
+  outline: 1px dashed rgba(255,255,255,0.5);
+  outline-offset: -1px;
+}
deleted file mode 100644
--- a/browser/themes/pinstripe/browser/highlighter.css
+++ /dev/null
@@ -1,104 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Mozilla Inspector Module.
- *
- * The Initial Developer of the Original Code is
- * The Mozilla Foundation.
- * Portions created by the Initial Developer are Copyright (C) 2011
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Rob Campbell <rcampbell@mozilla.com> (original author)
- *   Paul Rouget <paul@mozilla.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-body {
-  margin: 0;
-  overflow: hidden;
-}
-
-#close-button {
-  background-image: url("KUI-close.png");
-  border: none;
-  padding: 0;
-  width: 24px;
-  height: 24px;
-  position: fixed;
-  top: 12px;
-  right: 12px;
-  z-index: 1;
-  cursor: pointer;
-}
-
-.veil {
-  background-color: rgba(0, 0, 0, 0.5);
-}
-
-.veil, #veil-middlebox, #veil-transparentbox {
-  -moz-transition: 0.1s;
-  -moz-transition-timing-function: linear;
-}
-
-#veil-container {
-  position: absolute;
-  top: 0;
-  left: 0;
-  width: 100%;
-  height: 100%;
-}
-
-#veil {
-  width: 100%;
-  height: 100%;
-  display: -moz-box;
-  -moz-box-orient: vertical;
-}
-
-#veil-topbox, #veil-bottombox {
-  width: 100%;
-}
-
-#veil-bottombox {
-  -moz-box-flex: 1;
-}
-
-#veil-middlebox {
-  display: -moz-box;
-  -moz-box-orient: horizontal;
-}
-
-#veil-leftbox, #veil-rightbox {
-  height: 100%;
-}
-
-#veil-rightbox {
-  -moz-box-flex: 1;
-}
-
-#veil {
-  vertical-align: top;
-}
--- a/browser/themes/pinstripe/browser/jar.mn
+++ b/browser/themes/pinstripe/browser/jar.mn
@@ -10,17 +10,16 @@ browser.jar:
 #endif
   skin/classic/browser/actionicon-tab.png
 * skin/classic/browser/browser.css                          (browser.css)
 * skin/classic/browser/engineManager.css                    (engineManager.css)
   skin/classic/browser/fullscreen-video.css
   skin/classic/browser/Geolocation-16.png
   skin/classic/browser/Geolocation-64.png
   skin/classic/browser/Go-arrow.png
-* skin/classic/browser/highlighter.css
   skin/classic/browser/home.png
   skin/classic/browser/hud-style-check-box-checked.png
   skin/classic/browser/hud-style-check-box-empty.png
   skin/classic/browser/hud-style-dropmarker-double-arrows.png
   skin/classic/browser/hud-style-expander-closed.png
   skin/classic/browser/hud-style-expander-open.png
   skin/classic/browser/hud-style-new-folder-plus-sign.png
   skin/classic/browser/hud-style-twisties.png
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -597,18 +597,18 @@ menuitem.bookmark-item {
 }
 
 #navigator-toolbox[iconsize=small] > #nav-bar {
   padding-top: 1px;
   padding-bottom: 1px;
 }
 
 #navigator-toolbox[iconsize=large][mode=icons] > #nav-bar {
-  padding-left: 2px;
-  padding-right: 2px;
+  -moz-padding-start: 0;
+  -moz-padding-end: 2px;
 }
 
 #nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-button,
 #nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-dropmarker,
 #nav-bar .toolbarbutton-1 {
   -moz-appearance: none;
   padding: 1px 5px;
   background: rgba(151,152,153,.05)
@@ -660,27 +660,28 @@ menuitem.bookmark-item {
 
 #nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-button:-moz-locale-dir(rtl),
 #nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-dropmarker:-moz-locale-dir(ltr) {
   border-top-left-radius: 0;
   border-bottom-left-radius: 0;
 }
 
 #nav-bar .toolbarbutton-1[disabled="true"] {
-  opacity: .8;
+  opacity: .4;
 }
 
 #nav-bar .toolbarbutton-1[disabled="true"] > .toolbarbutton-menubutton-button > .toolbarbutton-icon,
 #nav-bar .toolbarbutton-1[disabled="true"] > .toolbarbutton-icon {
-  opacity: .5;
+  opacity: 1;
 }
 
 #nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-button:not([disabled="true"]):not(:active):hover,
 #nav-bar .toolbarbutton-1:not([open="true"]):not(:active):hover > .toolbarbutton-menubutton-dropmarker:not([disabled="true"]),
-#nav-bar .toolbarbutton-1:not([type="menu-button"]):not([disabled="true"]):not([checked="true"]):not([open="true"]):not(:active):hover {
+#nav-bar .toolbarbutton-1:not([type="menu-button"]):not([disabled="true"]):not([checked="true"]):not([open="true"]):not(:active):hover,
+#navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button:not([disabled="true"]):not([open]):not(:active):hover > .toolbarbutton-icon {
   background-color: hsla(190,60%,70%,.5);
   border-color: hsla(190,50%,65%,.8) hsla(190,50%,50%,.8) hsla(190,50%,40%,.8);
   box-shadow: 0 0 0 1px rgba(255,255,255,.3) inset,
               0 0 0 1.5px rgba(255,255,255,.1) inset,
               0 0 3.5px hsl(190,90%,80%);
   -moz-transition: background-color .4s ease-in,
                    border-color .3s ease-in,
                    box-shadow .3s ease-in;
@@ -789,45 +790,57 @@ toolbar[mode="full"] .toolbarbutton-1 > 
 
 #nav-bar #back-button:-moz-locale-dir(rtl),
 #nav-bar #forward-button {
   border-top-left-radius: 0;
   border-bottom-left-radius: 0;
 }
 
 #navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button {
-  border-radius: 10000px;
-  padding: 0;
-  width: 30px;
-  height: 30px;
+  margin: -5px 0;
+  padding-top: 0;
+  padding-bottom: 0;
+  -moz-padding-start: 5px;
+  -moz-padding-end: 0;
   position: relative;
   z-index: 1;
-  margin-top: -2px;
-  margin-bottom: -2px;
+  border-radius: 0 10000px 10000px 0;
+  background: transparent;
+  border: none;
+  box-shadow: none;
+}
+
+#navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button:-moz-locale-dir(rtl) {
+  border-radius: 10000px 0 0 10000px;
+}
+
+#navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button > .toolbarbutton-icon {
+  border-radius: 10000px;
+  padding: 5px;
   border: none;
   background-image: -moz-linear-gradient(rgba(251,252,253,.97), rgba(246,247,248,.5) 49%, 
                                          rgba(231,232,233,.45) 51%, rgba(225,226,229,.2));
   box-shadow: 0 0 0 1px rgba(255,255,255,.3) inset,
               0 0 0 2px rgba(255,255,255,.1) inset,
               0 0 0 1px rgba(0,0,0,.15),
               0 1px 0 rgba(0,0,0,.4),
               0 1px 1px rgba(0,0,0,.3);
 }
 
-#navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button:not([disabled="true"]):not([open="true"]):not(:active):hover {
+#navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button:not([disabled="true"]):not([open="true"]):not(:active):hover > .toolbarbutton-icon {
   box-shadow: 0 0 0 1px rgba(255,255,255,.3) inset,
               0 0 0 2px rgba(255,255,255,.1) inset,
               0 0 0 1px hsla(190,50%,40%,.3),
               0 1px 0 rgba(0,0,0,.4),
               0 1px 1px rgba(0,0,0,.3),
               0 0 5px 1px hsl(190,90%,80%);
 }
 
-#navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button:not([disabled="true"]):hover:active,
-#navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button[open="true"] {
+#navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button:not([disabled="true"]):hover:active > .toolbarbutton-icon,
+#navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button[open="true"] > .toolbarbutton-icon {
   box-shadow: 0 0 6.5px rgba(0,0,0,.4) inset,
               0 0 2px rgba(0,0,0,.4) inset,
               0 0 0 1px rgba(0,0,0,.65),
               0 2px 0 rgba(255,255,255,.4);
 }
 
 #navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar[currentset*="unified-back-forward-button"],
 #navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar:not([currentset]) {
@@ -2416,8 +2429,32 @@ panel[dimmed="true"] {
 }
 
 .statuspanel-label:-moz-locale-dir(rtl):not([mirror]),
 .statuspanel-label:-moz-locale-dir(ltr)[mirror] {
   border-left-style: solid;
   border-top-left-radius: .3em;
   margin-left: 1em;
 }
+
+/* Highlighter */
+
+.highlighter-veil {
+  background-color: rgba(0, 0, 0, 0.5);
+}
+
+#highlighter-close-button {
+  list-style-image: url("chrome://browser/skin/KUI-close.png");
+  top: 12px;
+  right: 12px;
+  cursor: pointer;
+}
+
+#highlighter-close-button:-moz-locale-dir(rtl)  {
+  right: auto;
+  left: 12px;
+}
+
+#highlighter-veil-transparentbox {
+  box-shadow: 0 0 0 1px rgba(0,0,0,0.5);
+  outline: 1px dashed rgba(255,255,255,0.5);
+  outline-offset: -1px;
+}
deleted file mode 100644
--- a/browser/themes/winstripe/browser/highlighter.css
+++ /dev/null
@@ -1,105 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Mozilla Inspector Module.
- *
- * The Initial Developer of the Original Code is
- * The Mozilla Foundation.
- * Portions created by the Initial Developer are Copyright (C) 2011
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Rob Campbell <rcampbell@mozilla.com> (original author)
- *   Paul Rouget <paul@mozilla.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-body {
-  margin: 0;
-  overflow: hidden;
-}
-
-#close-button {
-  background-image: url("KUI-close.png");
-  border: none;
-  padding: 0;
-  width: 24px;
-  height: 24px;
-  position: fixed;
-  top: 12px;
-  right: 12px;
-  z-index: 1;
-  cursor: pointer;
-}
-
-.veil {
-  background-color: rgba(0, 0, 0, 0.5);
-}
-
-.veil, #veil-middlebox, #veil-transparentbox {
-  -moz-transition: 0.1s;
-  -moz-transition-timing-function: linear;
-}
-
-#veil-container {
-  position: absolute;
-  top: 0;
-  left: 0;
-  width: 100%;
-  height: 100%;
-}
-
-#veil {
-  width: 100%;
-  height: 100%;
-  display: -moz-box;
-  -moz-box-orient: vertical;
-}
-
-#veil-topbox, #veil-bottombox {
-  width: 100%;
-}
-
-#veil-bottombox {
-  -moz-box-flex: 1;
-}
-
-#veil-middlebox {
-  display: -moz-box;
-  -moz-box-orient: horizontal;
-}
-
-#veil-leftbox, #veil-rightbox {
-  height: 100%;
-}
-
-#veil-rightbox {
-  -moz-box-flex: 1;
-}
-
-#veil {
-  vertical-align: top;
-}
-
--- a/browser/themes/winstripe/browser/jar.mn
+++ b/browser/themes/winstripe/browser/jar.mn
@@ -14,17 +14,16 @@ browser.jar:
         skin/classic/browser/actionicon-tab.png
         skin/classic/browser/appmenu-icons.png
         skin/classic/browser/appmenu-dropmarker.png
 *       skin/classic/browser/browser.css                             (browser.css)
 *       skin/classic/browser/engineManager.css                       (engineManager.css)
         skin/classic/browser/fullscreen-video.css
         skin/classic/browser/Geolocation-16.png
         skin/classic/browser/Geolocation-64.png
-*       skin/classic/browser/highlighter.css
         skin/classic/browser/Info.png                                (Info.png)
         skin/classic/browser/identity.png                            (identity.png)
         skin/classic/browser/keyhole-forward-mask.svg
         skin/classic/browser/KUI-background.png
         skin/classic/browser/KUI-close.png
         skin/classic/browser/mainwindow-dropdown-arrow.png
         skin/classic/browser/pageInfo.css
         skin/classic/browser/pageInfo.png                            (pageInfo.png)
@@ -129,17 +128,16 @@ browser.jar:
         skin/classic/aero/browser/actionicon-tab.png                 (actionicon-tab.png)
         skin/classic/aero/browser/appmenu-dropmarker.png
         skin/classic/aero/browser/appmenu-icons.png
 *       skin/classic/aero/browser/browser.css                        (browser-aero.css)
 *       skin/classic/aero/browser/engineManager.css                  (engineManager.css)
         skin/classic/aero/browser/fullscreen-video.css
         skin/classic/aero/browser/Geolocation-16.png
         skin/classic/aero/browser/Geolocation-64.png
-*       skin/classic/aero/browser/highlighter.css
         skin/classic/aero/browser/Info.png                           (Info-aero.png)
         skin/classic/aero/browser/identity.png                       (identity-aero.png)
         skin/classic/aero/browser/keyhole-forward-mask.svg
         skin/classic/aero/browser/KUI-background.png
         skin/classic/aero/browser/KUI-close.png
         skin/classic/aero/browser/mainwindow-dropdown-arrow.png      (mainwindow-dropdown-arrow-aero.png)
         skin/classic/aero/browser/pageInfo.css
         skin/classic/aero/browser/pageInfo.png                       (pageInfo-aero.png)
--- a/build/autoconf/libstdcxx.py
+++ b/build/autoconf/libstdcxx.py
@@ -62,12 +62,12 @@ def find_version(e):
 
     p = subprocess.Popen(['readelf', '-V', libstdcxx], stdout=subprocess.PIPE)
     versions = [parse_readelf_line(x)
                 for x in p.stdout.readlines() if 'Name: GLIBCXX' in x]
     last_version = sorted(versions, cmp = cmp_ver)[-1]
     return encode_ver(last_version)
 
 if __name__ == '__main__':
-    cxx_env = os.environ.get('CXX', 'c++')
+    cxx_env = os.environ['CXX']
     print 'MOZ_LIBSTDCXX_TARGET_VERSION=%s' % find_version(cxx_env)
     host_cxx_env = os.environ.get('HOST_CXX', cxx_env)
     print 'MOZ_LIBSTDCXX_HOST_VERSION=%s' % find_version(host_cxx_env)
--- a/build/automation.py.in
+++ b/build/automation.py.in
@@ -758,17 +758,17 @@ user_pref("camino.use_system_proxy_setti
         logsource = stackFixerProcess.stdout
 
       (line, didTimeout) = self.readWithTimeout(logsource, timeout)
       while line != "" and not didTimeout:
         if "TEST-START" in line and "|" in line:
           self.lastTestSeen = line.split("|")[1].strip()
         if stackFixerFunction:
           line = stackFixerFunction(line)
-        self.log.info(line.rstrip())
+        self.log.info(line.rstrip().decode("UTF-8", "ignore"))
         if self.UNIXISH and not debuggerInfo and not self.haveDumpedScreen and "TEST-UNEXPECTED-FAIL" in line and "Test timed out" in line:
           self.dumpScreen(utilityPath)
 
         (line, didTimeout) = self.readWithTimeout(logsource, timeout)
         if not hitMaxTime and maxTime and datetime.now() - startTime > timedelta(seconds = maxTime):
           # Kill the application, but continue reading from stack fixer so as not to deadlock on stackFixerProcess.wait().
           hitMaxTime = True
           self.log.info("TEST-UNEXPECTED-FAIL | %s | application ran for longer than allowed maximum time of %d seconds", self.lastTestSeen, int(maxTime))
--- a/build/mobile/devicemanagerADB.py
+++ b/build/mobile/devicemanagerADB.py
@@ -34,16 +34,17 @@ class DeviceManagerADB(DeviceManager):
 
   # external function
   # returns:
   #  success: directory name
   #  failure: None
   def mkDir(self, name):
     try:
       self.checkCmd(["shell", "mkdir", name])
+      self.chmodDir(name)
       return name
     except:
       return None
 
   # make directory structure on the device
   # external function
   # returns:
   #  success: directory structure that we created
--- a/build/pgo/profileserver.py
+++ b/build/pgo/profileserver.py
@@ -86,26 +86,26 @@ if __name__ == '__main__':
           options.debuggerInteractive)
 
   httpd = EasyServer(("", PORT), SimpleHTTPServer.SimpleHTTPRequestHandler)
   t = threading.Thread(target=httpd.serve_forever)
   t.setDaemon(True) # don't hang on exit
   t.start()
   
   automation.setServerInfo("localhost", PORT)
-  automation.initializeProfile(PROFILE_DIRECTORY)
   browserEnv = automation.environment()
   browserEnv["XPCOM_DEBUG_BREAK"] = "warn"
   browserEnv["MOZ_JAR_LOG_DIR"] = MOZ_JAR_LOG_DIR
 
   url = "http://localhost:%d/index.html" % PORT
   appPath = os.path.join(SCRIPT_DIR, automation.DEFAULT_APP)
 
   for i in range(0, num_runs):
       if num_runs != 1:
           print "Starting profiling run %d of %d" % (i + 1, num_runs)
+      automation.initializeProfile(PROFILE_DIRECTORY)
       status = automation.runApp(url, browserEnv, appPath, PROFILE_DIRECTORY, {},
                                  debuggerInfo=debuggerInfo,
                                  # the profiling HTML doesn't output anything,
                                  # so let's just run this without a timeout
                                  timeout = None)
       if status != 0:
           sys.exit(status)
--- a/build/unix/elfhack/elfhack.cpp
+++ b/build/unix/elfhack/elfhack.cpp
@@ -411,16 +411,19 @@ int do_relocation_section(Elf *elf, unsi
     Elf_SymValue *sym = symtab->lookup("__cxa_pure_virtual");
 
     std::vector<Rel_Type> new_rels;
     Elf_RelHack relhack_entry;
     relhack_entry.r_offset = relhack_entry.r_info = 0;
     int entry_sz = (elf->getClass() == ELFCLASS32) ? 4 : 8;
     for (typename std::vector<Rel_Type>::iterator i = section->rels.begin();
          i != section->rels.end(); i++) {
+        // We don't need to keep R_*_NONE relocations
+        if (!ELF32_R_TYPE(i->r_info))
+            continue;
         ElfSection *section = elf->getSectionAt(i->r_offset);
         // __cxa_pure_virtual is a function used in vtables to point at pure
         // virtual methods. The __cxa_pure_virtual function usually abort()s.
         // These functions are however normally never called. In the case
         // where they would, jumping to the NULL address instead of calling
         // __cxa_pure_virtual is going to work just as well. So we can remove
         // relocations for the __cxa_pure_virtual symbol and NULL out the
         // content at the offset pointed by the relocation.
--- a/caps/include/nsSystemPrincipal.h
+++ b/caps/include/nsSystemPrincipal.h
@@ -54,17 +54,17 @@ class nsSystemPrincipal : public nsIPrin
 {
 public:
     // Our refcount is managed by mJSPrincipals.  Use this macro to avoid
     // an extra refcount member.
     NS_DECL_ISUPPORTS_INHERITED
     NS_DECL_NSIPRINCIPAL
     NS_DECL_NSISERIALIZABLE
 
-    nsresult Init();
+    nsresult Init(JSPrincipals **jsprin);
 
     nsSystemPrincipal();
 
 protected:
     virtual ~nsSystemPrincipal(void);
 
     nsJSPrincipals mJSPrincipals;
     // XXX Probably unnecessary.  See bug 143559.
--- a/caps/src/nsScriptSecurityManager.cpp
+++ b/caps/src/nsScriptSecurityManager.cpp
@@ -2707,17 +2707,17 @@ nsScriptSecurityManager::CheckConfirmDia
 
     //-- Get a prompter for the current window.
     nsCOMPtr<nsIPrompt> prompter;
     if (cx)
     {
         nsIScriptContext *scriptContext = GetScriptContext(cx);
         if (scriptContext)
         {
-            nsCOMPtr<nsIDOMWindowInternal> domWin =
+            nsCOMPtr<nsIDOMWindow> domWin =
                 do_QueryInterface(scriptContext->GetGlobalObject());
             if (domWin)
                 domWin->GetPrompter(getter_AddRefs(prompter));
         }
     }
 
     if (!prompter)
     {
@@ -3374,17 +3374,18 @@ nsresult nsScriptSecurityManager::Init()
 
     rv = bundleService->CreateBundle("chrome://global/locale/security/caps.properties", &sStrBundle);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Create our system principal singleton
     nsRefPtr<nsSystemPrincipal> system = new nsSystemPrincipal();
     NS_ENSURE_TRUE(system, NS_ERROR_OUT_OF_MEMORY);
 
-    rv = system->Init();
+    JSPrincipals *jsprin;
+    rv = system->Init(&jsprin);
     NS_ENSURE_SUCCESS(rv, rv);
 
     mSystemPrincipal = system;
 
     //-- Register security check callback in the JS engine
     //   Currently this is used to control access to function.caller
     nsCOMPtr<nsIJSRuntimeService> runtimeService =
         do_QueryInterface(sXPConnect, &rv);
@@ -3401,16 +3402,18 @@ nsresult nsScriptSecurityManager::Init()
     };
 
 #ifdef DEBUG
     JSSecurityCallbacks *oldcallbacks =
 #endif
     JS_SetRuntimeSecurityCallbacks(sRuntime, &securityCallbacks);
     NS_ASSERTION(!oldcallbacks, "Someone else set security callbacks!");
 
+    JS_SetTrustedPrincipals(sRuntime, jsprin);
+
     return NS_OK;
 }
 
 static nsScriptSecurityManager *gScriptSecMan = nsnull;
 
 jsid nsScriptSecurityManager::sEnabledID   = JSID_VOID;
 
 nsScriptSecurityManager::~nsScriptSecurityManager(void)
@@ -3424,16 +3427,17 @@ nsScriptSecurityManager::~nsScriptSecuri
     gScriptSecMan = nsnull;
 }
 
 void
 nsScriptSecurityManager::Shutdown()
 {
     if (sRuntime) {
         JS_SetRuntimeSecurityCallbacks(sRuntime, NULL);
+        JS_SetTrustedPrincipals(sRuntime, NULL);
         sRuntime = nsnull;
     }
     sEnabledID = JSID_VOID;
 
     NS_IF_RELEASE(sIOService);
     NS_IF_RELEASE(sXPConnect);
     NS_IF_RELEASE(sJSContextStack);
     NS_IF_RELEASE(sStrBundle);
--- a/caps/src/nsSystemPrincipal.cpp
+++ b/caps/src/nsSystemPrincipal.cpp
@@ -309,24 +309,28 @@ nsSystemPrincipal::nsSystemPrincipal()
 }
 
 // Don't rename the system principal!
 // The JS engine (NewCompartment) relies on this name. 
 // XXX: bug 669123 will fix this hack.
 #define SYSTEM_PRINCIPAL_SPEC "[System Principal]"
 
 nsresult
-nsSystemPrincipal::Init()
+nsSystemPrincipal::Init(JSPrincipals **jsprin)
 {
     // Use an nsCString so we only do the allocation once here and then
     // share with nsJSPrincipals
     nsCString str(SYSTEM_PRINCIPAL_SPEC);
     if (!str.EqualsLiteral(SYSTEM_PRINCIPAL_SPEC)) {
         NS_WARNING("Out of memory initializing system principal");
         return NS_ERROR_OUT_OF_MEMORY;
     }
 
-    return mJSPrincipals.Init(this, str);
+    nsresult rv = mJSPrincipals.Init(this, str);
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    *jsprin = &mJSPrincipals;
+    return NS_OK;
 }
 
 nsSystemPrincipal::~nsSystemPrincipal(void)
 {
 }
--- a/chrome/src/nsChromeRegistry.cpp
+++ b/chrome/src/nsChromeRegistry.cpp
@@ -59,17 +59,17 @@
 #include "nsCSSStyleSheet.h"
 #include "nsIConsoleService.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIDocShell.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMLocation.h"
 #include "nsIDOMWindowCollection.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIIOService.h"
 #include "nsIJARProtocolHandler.h"
 #include "nsIObserverService.h"
 #include "nsIPresShell.h"
 #include "nsIProtocolHandler.h"
 #include "nsIScriptError.h"
 #include "nsIWindowMediator.h"
 
@@ -346,17 +346,17 @@ nsChromeRegistry::ConvertChromeURL(nsIUR
   return NS_NewURI(aResult, path, nsnull, baseURI);
 }
 
 ////////////////////////////////////////////////////////////////////////
 
 // theme stuff
 
 
-static void FlushSkinBindingsForWindow(nsIDOMWindowInternal* aWindow)
+static void FlushSkinBindingsForWindow(nsIDOMWindow* aWindow)
 {
   // Get the DOM document.
   nsCOMPtr<nsIDOMDocument> domDocument;
   aWindow->GetDocument(getter_AddRefs(domDocument));
   if (!domDocument)
     return;
 
   nsCOMPtr<nsIDocument> document = do_QueryInterface(domDocument);
@@ -378,32 +378,32 @@ NS_IMETHODIMP nsChromeRegistry::RefreshS
   nsCOMPtr<nsISimpleEnumerator> windowEnumerator;
   windowMediator->GetEnumerator(nsnull, getter_AddRefs(windowEnumerator));
   PRBool more;
   windowEnumerator->HasMoreElements(&more);
   while (more) {
     nsCOMPtr<nsISupports> protoWindow;
     windowEnumerator->GetNext(getter_AddRefs(protoWindow));
     if (protoWindow) {
-      nsCOMPtr<nsIDOMWindowInternal> domWindow = do_QueryInterface(protoWindow);
+      nsCOMPtr<nsIDOMWindow> domWindow = do_QueryInterface(protoWindow);
       if (domWindow)
         FlushSkinBindingsForWindow(domWindow);
     }
     windowEnumerator->HasMoreElements(&more);
   }
 
   FlushSkinCaches();
 
   windowMediator->GetEnumerator(nsnull, getter_AddRefs(windowEnumerator));
   windowEnumerator->HasMoreElements(&more);
   while (more) {
     nsCOMPtr<nsISupports> protoWindow;
     windowEnumerator->GetNext(getter_AddRefs(protoWindow));
     if (protoWindow) {
-      nsCOMPtr<nsIDOMWindowInternal> domWindow = do_QueryInterface(protoWindow);
+      nsCOMPtr<nsIDOMWindow> domWindow = do_QueryInterface(protoWindow);
       if (domWindow)
         RefreshWindow(domWindow);
     }
     windowEnumerator->HasMoreElements(&more);
   }
    
   return NS_OK;
 }
@@ -423,29 +423,28 @@ static PRBool IsChromeURI(nsIURI* aURI)
 {
     PRBool isChrome=PR_FALSE;
     if (NS_SUCCEEDED(aURI->SchemeIs("chrome", &isChrome)) && isChrome)
         return PR_TRUE;
     return PR_FALSE;
 }
 
 // XXXbsmedberg: move this to windowmediator
-nsresult nsChromeRegistry::RefreshWindow(nsIDOMWindowInternal* aWindow)
+nsresult nsChromeRegistry::RefreshWindow(nsIDOMWindow* aWindow)
 {
   // Deal with our subframes first.
   nsCOMPtr<nsIDOMWindowCollection> frames;
   aWindow->GetFrames(getter_AddRefs(frames));
   PRUint32 length;
   frames->GetLength(&length);
   PRUint32 j;
   for (j = 0; j < length; j++) {
     nsCOMPtr<nsIDOMWindow> childWin;
     frames->Item(j, getter_AddRefs(childWin));
-    nsCOMPtr<nsIDOMWindowInternal> childInt(do_QueryInterface(childWin));
-    RefreshWindow(childInt);
+    RefreshWindow(childWin);
   }
 
   nsresult rv;
   // Get the DOM document.
   nsCOMPtr<nsIDOMDocument> domDocument;
   aWindow->GetDocument(getter_AddRefs(domDocument));
   if (!domDocument)
     return NS_OK;
@@ -563,18 +562,17 @@ nsChromeRegistry::ReloadChrome()
       // Get each dom window
       PRBool more;
       rv = windowEnumerator->HasMoreElements(&more);
       if (NS_FAILED(rv)) return rv;
       while (more) {
         nsCOMPtr<nsISupports> protoWindow;
         rv = windowEnumerator->GetNext(getter_AddRefs(protoWindow));
         if (NS_SUCCEEDED(rv)) {
-          nsCOMPtr<nsIDOMWindowInternal> domWindow =
-            do_QueryInterface(protoWindow);
+          nsCOMPtr<nsIDOMWindow> domWindow = do_QueryInterface(protoWindow);
           if (domWindow) {
             nsCOMPtr<nsIDOMLocation> location;
             domWindow->GetLocation(getter_AddRefs(location));
             if (location) {
               rv = location->Reload(PR_FALSE);
               if (NS_FAILED(rv)) return rv;
             }
           }
--- a/chrome/src/nsChromeRegistry.h
+++ b/chrome/src/nsChromeRegistry.h
@@ -58,17 +58,17 @@
 #include "nsURIHashKey.h"
 #include "nsInterfaceHashtable.h"
 #include "nsXULAppAPI.h"
 #include "nsIResProtocolHandler.h"
 #include "nsIXPConnect.h"
 
 #include "mozilla/Omnijar.h"
 
-class nsIDOMWindowInternal;
+class nsIDOMWindow;
 class nsIURL;
 
 // The chrome registry is actually split between nsChromeRegistryChrome and
 // nsChromeRegistryContent. The work/data that is common to both resides in
 // the shared nsChromeRegistry implementation, with operations that only make
 // sense for one side erroring out in the other.
 
 // for component registration
@@ -125,17 +125,17 @@ protected:
   virtual nsIURI* GetBaseURIFromPackage(const nsCString& aPackage,
                                         const nsCString& aProvider,
                                         const nsCString& aPath) = 0;
   virtual nsresult GetFlagsFromPackage(const nsCString& aPackage,
                                        PRUint32* aFlags) = 0;
 
   nsresult SelectLocaleFromPref(nsIPrefBranch* prefs);
 
-  static nsresult RefreshWindow(nsIDOMWindowInternal* aWindow);
+  static nsresult RefreshWindow(nsIDOMWindow* aWindow);
   static nsresult GetProviderAndPath(nsIURL* aChromeURL,
                                      nsACString& aProvider, nsACString& aPath);
 
 public:
   static already_AddRefed<nsChromeRegistry> GetSingleton();
 
   struct ManifestProcessingContext
   {
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -107,16 +107,17 @@ MOZ_JSDEBUGGER  = @MOZ_JSDEBUGGER@
 MOZ_IPDL_TESTS 	= @MOZ_IPDL_TESTS@
 MOZ_LEAKY	= @MOZ_LEAKY@
 MOZ_MEMORY      = @MOZ_MEMORY@
 MOZ_PROFILING   = @MOZ_PROFILING@
 MOZ_JPROF       = @MOZ_JPROF@
 MOZ_SHARK       = @MOZ_SHARK@
 MOZ_CALLGRIND   = @MOZ_CALLGRIND@
 MOZ_VTUNE       = @MOZ_VTUNE@
+MOZ_ETW         = @MOZ_ETW@
 MOZ_TRACE_JSCALLS = @MOZ_TRACE_JSCALLS@
 MOZ_TRACEVIS    = @MOZ_TRACEVIS@
 DEHYDRA_PATH    = @DEHYDRA_PATH@
 
 NS_TRACE_MALLOC = @NS_TRACE_MALLOC@
 USE_ELF_DYNSTR_GC = @USE_ELF_DYNSTR_GC@
 USE_ELF_HACK = @USE_ELF_HACK@
 STDCXX_COMPAT = @STDCXX_COMPAT@
@@ -338,16 +339,17 @@ AR_EXTRACT	= @AR_EXTRACT@
 AR_LIST		= @AR_LIST@
 AR_DELETE	= @AR_DELETE@
 AS		= @AS@
 ASFLAGS		= @ASFLAGS@
 AS_DASH_C_FLAG	= @AS_DASH_C_FLAG@
 LD		= @LD@
 RC		= @RC@
 RCFLAGS		= @RCFLAGS@
+MC		= @MC@
 WINDRES		= @WINDRES@
 IMPLIB		= @IMPLIB@
 FILTER		= @FILTER@
 BIN_FLAGS	= @BIN_FLAGS@
 MIDL		= @MIDL@
 MIDL_FLAGS	= @MIDL_FLAGS@
 _MSC_VER	= @_MSC_VER@
 
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -2015,16 +2015,17 @@ showbuild:
 	@echo "CPP                = $(CPP)"
 	@echo "LD                 = $(LD)"
 	@echo "AR                 = $(AR)"
 	@echo "IMPLIB             = $(IMPLIB)"
 	@echo "FILTER             = $(FILTER)"
 	@echo "MKSHLIB            = $(MKSHLIB)"
 	@echo "MKCSHLIB           = $(MKCSHLIB)"
 	@echo "RC                 = $(RC)"
+	@echo "MC                 = $(MC)"
 	@echo "CFLAGS             = $(CFLAGS)"
 	@echo "OS_CFLAGS          = $(OS_CFLAGS)"
 	@echo "COMPILE_CFLAGS     = $(COMPILE_CFLAGS)"
 	@echo "CXXFLAGS           = $(CXXFLAGS)"
 	@echo "OS_CXXFLAGS        = $(OS_CXXFLAGS)"
 	@echo "COMPILE_CXXFLAGS   = $(COMPILE_CXXFLAGS)"
 	@echo "COMPILE_CMFLAGS    = $(COMPILE_CMFLAGS)"
 	@echo "COMPILE_CMMFLAGS   = $(COMPILE_CMMFLAGS)"
--- a/configure.in
+++ b/configure.in
@@ -118,17 +118,17 @@ dnl ====================================
 GLIB_VERSION=1.2.0
 LIBIDL_VERSION=0.6.3
 PERL_VERSION=5.006
 PYTHON_VERSION=2.5
 CAIRO_VERSION=1.10
 PANGO_VERSION=1.14.0
 GTK2_VERSION=2.10.0
 WINDRES_VERSION=2.14.90
-W32API_VERSION=3.8
+W32API_VERSION=3.14
 GNOMEVFS_VERSION=2.0
 GNOMEUI_VERSION=2.2.0
 GCONF_VERSION=1.2.1
 GIO_VERSION=2.18
 STARTUP_NOTIFICATION_VERSION=0.8
 DBUS_VERSION=0.60
 SQLITE_VERSION=3.7.5
 LIBNOTIFY_VERSION=0.4
@@ -312,16 +312,22 @@ case "$target" in
     LD="$android_toolchain"/bin/"$android_tool_prefix"-ld
     AR="$android_toolchain"/bin/"$android_tool_prefix"-ar
     RANLIB="$android_toolchain"/bin/"$android_tool_prefix"-ranlib
     STRIP="$android_toolchain"/bin/"$android_tool_prefix"-strip
 
     if test -e "$android_ndk/sources/cxx-stl/stlport/libs/armeabi-v7a/libstlport_static.a" ; then
        STLPORT_CPPFLAGS="-I$android_ndk/sources/cxx-stl/stlport/stlport"
        STLPORT_LDFLAGS="-L$android_ndk/sources/cxx-stl/stlport/libs/armeabi-v7a/  -lstlport_static"
+    elif  test -e "$android_ndk/tmp/ndk-digit/build/install/sources/cxx-stl/stlport/libs/armeabi-v7a/libstlport_static.a" ; then
+       STLPORT_CPPFLAGS="-I$android_ndk/sources/cxx-stl/stlport/stlport"
+       STLPORT_LDFLAGS="-L$android_ndk/tmp/ndk-digit/build/install/sources/cxx-stl/stlport/libs/armeabi-v7a  -lstlport_static"
+    elif test "$target" != "arm-android-eabi"; then
+       dnl fail if we're not building with NDKr4
+       AC_MSG_ERROR([Couldn't find path to stlport in the android ndk])
     fi
 
     CPPFLAGS="-I$android_platform/usr/include $STLPORT_CPPFLAGS $CPPFLAGS"
     CFLAGS="-mandroid -I$android_platform/usr/include -fno-short-enums -fno-exceptions $CFLAGS"
     CXXFLAGS="-mandroid -I$android_platform/usr/include -fno-short-enums -fno-exceptions $CXXFLAGS"
     LIBS="$LIBS $STLPORT_LDFLAGS"
 
     dnl Add -llog by default, since we use it all over the place.
@@ -865,18 +871,17 @@ EOF
                 "$_WINDRES_MINOR_VERSION" -lt "$WINDRES_MINOR_VERSION" -o \
                 "$_WINDRES_MAJOR_VERSION" -eq "$WINDRES_MAJOR_VERSION" -a \
                 "$_WINDRES_MINOR_VERSION" -eq "$WINDRES_MINOR_VERSION" -a \
                 "$_WINDRES_RELEASE_VERSION" -lt "$WINDRES_RELEASE_VERSION"
         then
             AC_MSG_ERROR([windres version $WINDRES_VERSION or higher is required to build.])
         fi
 
-        # Server 2003 is the highest version supported
-        MOZ_WINSDK_MAXVER=0x05020000
+        MOZ_WINSDK_MAXVER=0x06010000
     fi # !GNU_CC
 
     AC_DEFINE_UNQUOTED(WINVER,0x$WINVER)
     AC_DEFINE_UNQUOTED(_WIN32_WINNT,0x$WINVER)
     # Require OS features provided by IE 5.0
     AC_DEFINE_UNQUOTED(_WIN32_IE,0x0500)
 
     # If the maximum version supported by this SDK is lower than the target
@@ -2250,23 +2255,27 @@ ia64*-hpux*)
     ;;
     i*86)
     	USE_ELF_DYNSTR_GC=1
     ;;
     mips*)
         MOZ_DEBUG_FLAGS="-g" # We want inlining
     ;;
     esac
-    ;;
-
+
+    if test -z "$MC"; then 
+        MC=mc.exe  
+    fi
+    ;;
 *-mingw*)
     DSO_CFLAGS=
     DSO_PIC_CFLAGS=
     DLL_SUFFIX=.dll
     RC=rc.exe
+    MC=mc.exe
     # certain versions of cygwin's makedepend barf on the 
     # #include <string> vs -I./dist/include/string issue so don't use it
     SYSTEM_MAKEDEPEND=
     if test -n "$GNU_CC"; then
         CC="$CC -mwindows"
         CXX="$CXX -mwindows"
         CPP="$CPP -mwindows"
         CFLAGS="$CFLAGS -mms-bitfields"
@@ -2544,16 +2553,17 @@ ia64*-hpux*)
     MOZ_DEBUG_FLAGS="-g -fno-inline"
     MOZ_OPTIMIZE_FLAGS="-O2"
     MOZ_OPTIMIZE_LDFLAGS="-s -Zlinker /EXEPACK:2 -Zlinker /PACKCODE -Zlinker /PACKDATA"
     DYNAMIC_XPCOM_LIBS='-L$(LIBXUL_DIST)/lib $(LIBXUL_DIST)/lib/xpcom.lib $(LIBXUL_DIST)/lib/xpcom_core.lib $(LIBXUL_DIST)/lib/mozalloc.lib'
     LIBXUL_LIBS='-L$(LIBXUL_DIST)/lib $(LIBXUL_DIST)/lib/xpcom.lib $(LIBXUL_DIST)/lib/xul.lib $(LIBXUL_DIST)/lib/mozalloc.lib'
     TARGET_MD_ARCH=os2
     _PLATFORM_DEFAULT_TOOLKIT="cairo-os2"
     RC=rc.exe
+    MC=mc.exe
     RCFLAGS='-n'
     MOZ_USER_DIR="Mozilla"
     ZIP="$ZIP -X"
 
     if test "$MOZTOOLS"; then
         MOZ_TOOLS_DIR=`echo $MOZTOOLS | sed -e 's|\\\\|/|g'`
     else
         AC_MSG_ERROR([MOZTOOLS is not set])
@@ -5676,16 +5686,33 @@ MOZ_ARG_ENABLE_BOOL(ipdl-tests,
 
 if test -n "$MOZ_IPDL_TESTS"; then
     AC_DEFINE(MOZ_IPDL_TESTS)
 fi
 
 AC_SUBST(MOZ_IPDL_TESTS)
 
 dnl ========================================================
+dnl = Turns off code necessary for e10s compatibility
+dnl ========================================================
+dnl This is a temporary flag to be removed in bug 662601 when
+dnl it's no longer needed
+
+MOZ_E10S_COMPAT=
+
+MOZ_ARG_ENABLE_BOOL(e10s-compat,
+[  --enable-e10s-compat     Turns off code for e10s compat],
+    MOZ_E10S_COMPAT=1,
+    MOZ_E10S_COMPAT=)
+
+if test -n "$MOZ_E10S_COMPAT"; then
+    AC_DEFINE(MOZ_E10S_COMPAT)
+fi
+
+dnl ========================================================
 dnl = Disable building dbm
 dnl ========================================================
 MOZ_ARG_DISABLE_BOOL(dbm,
 [  --disable-dbm           Disable building dbm],
     NSS_DISABLE_DBM=1,
     NSS_DISABLE_DBM=)
 
 dnl bi-directional support always on
@@ -7454,22 +7481,22 @@ else
     DLLFLAGS="$DLLFLAGS $MOZ_MEMORY_LDFLAGS"
     export DLLFLAGS
     ;;
   *)
     AC_MSG_ERROR([--enable-jemalloc not supported on ${target}])
     ;;
   esac
 
-  if test "$OS_ARCH" != "Darwin"; then
+  if test "$OS_ARCH" != "WINNT"; then
     dnl NB: this must be kept in sync with jemalloc.h
     AC_DEFINE(HAVE_JEMALLOC_VALLOC)
-    AC_DEFINE(HAVE_JEMALLOC_POSIX_MEMALIGN)
-    AC_DEFINE(HAVE_JEMALLOC_MEMALIGN)
   fi
+  AC_DEFINE(HAVE_JEMALLOC_POSIX_MEMALIGN)
+  AC_DEFINE(HAVE_JEMALLOC_MEMALIGN)
 fi # MOZ_MEMORY
 AC_SUBST(MOZ_MEMORY)
 AC_SUBST(MOZ_MEMORY_LDFLAGS)
 AC_SUBST(WIN32_OLD_STYLE_JEMALLOC)
 AC_SUBST(WIN32_CRT_LIBS)
 AC_SUBST(WIN32_CRT_SRC_DIR)
 dnl Need to set this for make because NSS doesn't have configure
 AC_SUBST(DLLFLAGS)
@@ -7526,16 +7553,36 @@ MOZ_ARG_ENABLE_BOOL(gctimer,
 [  --enable-gctimer        Enable GC timer (default=no)],
     MOZ_GCTIMER=1,
     MOZ_GCTIMER= )
 if test -n "$MOZ_GCTIMER"; then
     AC_DEFINE(MOZ_GCTIMER)
 fi
 
 dnl ========================================================
+dnl ETW - Event Tracing for Windows
+dnl ========================================================
+MOZ_ARG_ENABLE_BOOL(ETW,
+[  --enable-ETW            Enable ETW (Event Tracing for Windows) event reporting
+                          (needs Windows Vista+ SDK)],
+    MOZ_ETW=1,
+    MOZ_ETW= )
+if test -n "$MOZ_ETW"; then
+    AC_DEFINE(MOZ_ETW)
+fi
+
+if test -n "$MOZ_ETW"; then
+    if test -z "$MOZ_WINSDK_TARGETVER"; then
+        AC_MSG_ERROR([--enable-ETW is only valid on Windows])
+    elif test "$MOZ_WINSDK_TARGETVER" -lt "06000000"; then
+        AC_MSG_ERROR([--enable-ETW requires the Windows Vista SDK or newer])
+    fi
+fi
+
+dnl ========================================================
 dnl Zealous JavaScript GC
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(gczeal,
 [  --enable-gczeal         Enable zealous JavaScript GCing],
     JS_GC_ZEAL=1,
     JS_GC_ZEAL= )
 if test -n "$JS_GC_ZEAL"; then
     AC_DEFINE(JS_GC_ZEAL)
@@ -7676,17 +7723,17 @@ dnl ====================================
 STDCXX_COMPAT=
 MOZ_ARG_ENABLE_BOOL(stdcxx-compat,
 [  --enable-stdcxx-compat  Enable compatibility with older libstdc++],
     STDCXX_COMPAT=stdc++compat.cpp)
 
 AC_SUBST(STDCXX_COMPAT)
 
 if test -n "$STDCXX_COMPAT"; then
-   eval $($PYTHON $_topsrcdir/build/autoconf/libstdcxx.py)
+   eval $(CXX="$CXX" $PYTHON $_topsrcdir/build/autoconf/libstdcxx.py)
    AC_SUBST(MOZ_LIBSTDCXX_TARGET_VERSION)
    AC_SUBST(MOZ_LIBSTDCXX_HOST_VERSION)
 fi
 
 dnl ========================================================
 dnl = 
 dnl = Profiling and Instrumenting
 dnl = 
@@ -8829,16 +8876,17 @@ AC_SUBST(AR_LIST)
 AC_SUBST(AR_EXTRACT)
 AC_SUBST(AR_DELETE)
 AC_SUBST(AS)
 AC_SUBST(ASFLAGS)
 AC_SUBST(AS_DASH_C_FLAG)
 AC_SUBST(LD)
 AC_SUBST(RC)
 AC_SUBST(RCFLAGS)
+AC_SUBST(MC)
 AC_SUBST(WINDRES)
 AC_SUBST(IMPLIB)
 AC_SUBST(FILTER)
 AC_SUBST(BIN_FLAGS)
 AC_SUBST(NS_USE_NATIVE)
 AC_SUBST(MOZ_WIDGET_TOOLKIT)
 AC_SUBST(MOZ_UPDATE_XTERM)
 AC_SUBST(MINIMO)
@@ -8861,16 +8909,17 @@ AC_SUBST(WARNINGS_AS_ERRORS)
 AC_SUBST(MOZ_EXTENSIONS)
 AC_SUBST(MOZ_JSDEBUGGER)
 AC_SUBST(MOZ_LOG_REFCNT)
 AC_SUBST(MOZ_LEAKY)
 AC_SUBST(MOZ_JPROF)
 AC_SUBST(MOZ_SHARK)
 AC_SUBST(MOZ_CALLGRIND)
 AC_SUBST(MOZ_VTUNE)
+AC_SUBST(MOZ_ETW)
 AC_SUBST(MOZ_PROFILING)
 AC_SUBST(MOZ_QUANTIFY)
 AC_SUBST(LIBICONV)
 AC_SUBST(MOZ_PLACES)
 AC_SUBST(MOZ_STORAGE)
 AC_SUBST(MOZ_TOOLKIT_SEARCH)
 AC_SUBST(MOZ_FEEDS)
 AC_SUBST(NS_PRINTING)
--- a/content/base/public/Element.h
+++ b/content/base/public/Element.h
@@ -37,16 +37,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef mozilla_dom_Element_h__
 #define mozilla_dom_Element_h__
 
 #include "nsIContent.h"
 #include "nsEventStates.h"
+#include "nsDOMMemoryReporter.h"
 
 class nsEventStateManager;
 class nsGlobalWindow;
 class nsFocusManager;
 
 // Element-specific flags
 enum {
   // Set if the element has a pending style change.
@@ -92,16 +93,18 @@ class Element : public nsIContent
 public:
 #ifdef MOZILLA_INTERNAL_API
   Element(already_AddRefed<nsINodeInfo> aNodeInfo) :
     nsIContent(aNodeInfo),
     mState(NS_EVENT_STATE_MOZ_READONLY)
   {}
 #endif // MOZILLA_INTERNAL_API
 
+  NS_DECL_AND_IMPL_DOM_MEMORY_REPORTER_SIZEOF(Element, nsIContent)
+
   /**
    * Method to get the full state of this element.  See nsEventStates.h for
    * the possible bits that could be set here.
    */
   nsEventStates State() const {
     // mState is maintained by having whoever might have changed it
     // call UpdateState() or one of the other mState mutators.
     return mState;
--- a/content/base/public/nsDOMFile.h
+++ b/content/base/public/nsDOMFile.h
@@ -49,145 +49,213 @@
 #include "nsCOMArray.h"
 #include "nsCOMPtr.h"
 #include "mozilla/AutoRestore.h"
 #include "nsString.h"
 #include "nsIXMLHttpRequest.h"
 #include "prmem.h"
 #include "nsAutoPtr.h"
 
+#ifndef PR_UINT64_MAX
+#define PR_UINT64_MAX (~(PRUint64)(0))
+#endif
+
 class nsIFile;
 class nsIInputStream;
 class nsIClassInfo;
 class nsIBlobBuilder;
 
 nsresult NS_NewBlobBuilder(nsISupports* *aSupports);
-void ParseSize(PRInt64 aSize, PRInt64& aStart, PRInt64& aEnd);
 
-class nsDOMFile : public nsIDOMFile,
-                  public nsIXHRSendable,
-                  public nsIJSNativeInitializer
+class nsDOMFileBase : public nsIDOMFile,
+                      public nsIXHRSendable
 {
 public:
+
+  nsDOMFileBase(const nsAString& aName, const nsAString& aContentType,
+                PRUint64 aLength)
+    : mIsFile(true), mContentType(aContentType), mName(aName),
+      mStart(0), mLength(aLength)
+  {
+    // Ensure non-null mContentType by default
+    mContentType.SetIsVoid(PR_FALSE);
+  }
+
+  nsDOMFileBase(const nsAString& aContentType, PRUint64 aLength)
+    : mIsFile(false), mContentType(aContentType),
+      mStart(0), mLength(aLength)
+  {
+    // Ensure non-null mContentType by default
+    mContentType.SetIsVoid(PR_FALSE);
+  }
+
+  nsDOMFileBase(const nsAString& aContentType,
+                PRUint64 aStart, PRUint64 aLength)
+    : mIsFile(false), mContentType(aContentType),
+      mStart(aStart), mLength(aLength)
+  {
+    NS_ASSERTION(aLength != PR_UINT64_MAX,
+                 "Must know length when creating slice");
+    // Ensure non-null mContentType by default
+    mContentType.SetIsVoid(PR_FALSE);
+  }
+
+  virtual ~nsDOMFileBase() {}
+
+  virtual already_AddRefed<nsIDOMBlob>
+  CreateSlice(PRUint64 aStart, PRUint64 aLength,
+              const nsAString& aContentType) = 0;
+
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMBLOB
   NS_DECL_NSIDOMFILE
   NS_DECL_NSIXHRSENDABLE
 
-  nsDOMFile(nsIFile *aFile, const nsAString& aContentType,
-            nsISupports *aCacheToken = nsnull)
-    : mFile(aFile),
-      mCacheToken(aCacheToken),
-      mContentType(aContentType),
-      mIsFullFile(true)
-  {}
+protected:
+  bool IsSizeUnknown()
+  {
+    return mLength == PR_UINT64_MAX;
+  }
+
+  bool mIsFile;
+  nsString mContentType;
+  nsString mName;
 
-  nsDOMFile(nsIFile *aFile)
-    : mFile(aFile),
-      mIsFullFile(true)
-  {}
+  PRUint64 mStart;
+  PRUint64 mLength;
+};
 
-  nsDOMFile(const nsDOMFile* aOther, PRUint64 aStart, PRUint64 aLength,
-            const nsAString& aContentType)
-    : mFile(aOther->mFile),
-      mCacheToken(aOther->mCacheToken),
-      mStart(aOther->mIsFullFile ? aStart :
-                                   (aOther->mStart + aStart)),
-      mLength(aLength),
-      mContentType(aContentType),
-      mIsFullFile(false)
+class nsDOMFileFile : public nsDOMFileBase,
+                      public nsIJSNativeInitializer
+{
+public:
+  // Create as a file
+  nsDOMFileFile(nsIFile *aFile)
+    : nsDOMFileBase(EmptyString(), EmptyString(), PR_UINT64_MAX),
+      mFile(aFile), mWholeFile(true)
   {
     NS_ASSERTION(mFile, "must have file");
-    // Ensure non-null mContentType
-    mContentType.SetIsVoid(PR_FALSE);
+    // Lazily get the content type and size
+    mContentType.SetIsVoid(PR_TRUE);
+    mFile->GetLeafName(mName);
   }
 
-  virtual ~nsDOMFile() {}
+  // Create as a blob
+  nsDOMFileFile(nsIFile *aFile, const nsAString& aContentType,
+                nsISupports *aCacheToken = nsnull)
+    : nsDOMFileBase(aContentType, PR_UINT64_MAX),
+      mFile(aFile), mWholeFile(true),
+      mCacheToken(aCacheToken)
+  {
+    NS_ASSERTION(mFile, "must have file");
+  }
+
+  // Create as a file to be later initialized
+  nsDOMFileFile()
+    : nsDOMFileBase(EmptyString(), EmptyString(), PR_UINT64_MAX),
+      mWholeFile(true)
+  {
+    // Lazily get the content type and size
+    mContentType.SetIsVoid(PR_TRUE);
+    mName.SetIsVoid(PR_TRUE);
+  }
+
+  NS_DECL_ISUPPORTS_INHERITED
 
   // nsIJSNativeInitializer
   NS_IMETHOD Initialize(nsISupports* aOwner,
                         JSContext* aCx,
                         JSObject* aObj,
                         PRUint32 aArgc,
                         jsval* aArgv);
 
+  // Overrides
+  NS_IMETHOD GetSize(PRUint64* aSize);
+  NS_IMETHOD GetType(nsAString& aType);
+  NS_IMETHOD GetMozFullPathInternal(nsAString& aFullPath);
+  NS_IMETHOD GetInternalStream(nsIInputStream**);
+
   // DOMClassInfo constructor (for File("foo"))
   static nsresult
   NewFile(nsISupports* *aNewObject);
 
 protected:
-  nsCOMPtr<nsIFile> mFile;
-  nsCOMPtr<nsISupports> mCacheToken;
+  // Create slice
+  nsDOMFileFile(const nsDOMFileFile* aOther, PRUint64 aStart, PRUint64 aLength,
+                const nsAString& aContentType)
+    : nsDOMFileBase(aContentType, aOther->mStart + aStart, aLength),
+      mFile(aOther->mFile), mWholeFile(false),
+      mCacheToken(aOther->mCacheToken)
+  {
+    NS_ASSERTION(mFile, "must have file");
+  }
+  virtual already_AddRefed<nsIDOMBlob>
+  CreateSlice(PRUint64 aStart, PRUint64 aLength,
+              const nsAString& aContentType);
 
-  // start and length in 
-  PRUint64 mStart;
-  PRUint64 mLength;
-
-  nsString mContentType;
-  
-  bool mIsFullFile;
+  nsCOMPtr<nsIFile> mFile;
+  bool mWholeFile;
+  nsCOMPtr<nsISupports> mCacheToken;
 };
 
-class nsDOMMemoryFile : public nsDOMFile
+class nsDOMMemoryFile : public nsDOMFileBase
 {
 public:
+  // Create as file
   nsDOMMemoryFile(void *aMemoryBuffer,
                   PRUint64 aLength,
                   const nsAString& aName,
                   const nsAString& aContentType)
-    : nsDOMFile(nsnull, aContentType),
-      mDataOwner(new DataOwner(aMemoryBuffer)),
-      mName(aName)
+    : nsDOMFileBase(aName, aContentType, aLength),
+      mDataOwner(new DataOwner(aMemoryBuffer))
   {
-    mStart = 0;
-    mLength = aLength;
+    NS_ASSERTION(mDataOwner && mDataOwner->mData, "must have data");
   }
 
+  // Create as blob
+  nsDOMMemoryFile(void *aMemoryBuffer,
+                  PRUint64 aLength,
+                  const nsAString& aContentType)
+    : nsDOMFileBase(aContentType, aLength),
+      mDataOwner(new DataOwner(aMemoryBuffer))
+  {
+    NS_ASSERTION(mDataOwner && mDataOwner->mData, "must have data");
+  }
+
+  NS_IMETHOD GetInternalStream(nsIInputStream**);
+
+protected:
+  // Create slice
   nsDOMMemoryFile(const nsDOMMemoryFile* aOther, PRUint64 aStart,
                   PRUint64 aLength, const nsAString& aContentType)
-    : nsDOMFile(nsnull, aContentType),
+    : nsDOMFileBase(aContentType, aOther->mStart + aStart, aLength),
       mDataOwner(aOther->mDataOwner)
   {
     NS_ASSERTION(mDataOwner && mDataOwner->mData, "must have data");
-
-    mIsFullFile = false;
-    mStart = aOther->mStart + aStart;
-    mLength = aLength;
-
-    // Ensure non-null mContentType
-    mContentType.SetIsVoid(PR_FALSE);
   }
+  virtual already_AddRefed<nsIDOMBlob>
+  CreateSlice(PRUint64 aStart, PRUint64 aLength,
+              const nsAString& aContentType);
 
-  NS_IMETHOD GetName(nsAString&);
-  NS_IMETHOD GetSize(PRUint64*);
-  NS_IMETHOD GetInternalStream(nsIInputStream**);
-  NS_IMETHOD GetMozFullPathInternal(nsAString&);
-  NS_IMETHOD MozSlice(PRInt64 aStart, PRInt64 aEnd,
-                      const nsAString& aContentType, PRUint8 optional_argc,
-                      nsIDOMBlob **aBlob);
-
-protected:
   friend class DataOwnerAdapter; // Needs to see DataOwner
   class DataOwner {
   public:
     NS_INLINE_DECL_REFCOUNTING(DataOwner)
     DataOwner(void* aMemoryBuffer)
       : mData(aMemoryBuffer)
     {
     }
     ~DataOwner() {
       PR_Free(mData);
     }
     void* mData;
   };
 
   // Used when backed by a memory store
   nsRefPtr<DataOwner> mDataOwner;
-
-  nsString mName;
 };
 
 class nsDOMFileList : public nsIDOMFileList
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMFILELIST
 
--- a/content/base/public/nsIContent.h
+++ b/content/base/public/nsIContent.h
@@ -38,16 +38,17 @@
 #define nsIContent_h___
 
 #include "nsCOMPtr.h" // for already_AddRefed
 #include "nsStringGlue.h"
 #include "nsCaseTreatment.h"
 #include "nsChangeHint.h"
 #include "nsINode.h"
 #include "nsIDocument.h" // for IsInHTMLDocument
+#include "nsDOMMemoryReporter.h"
 
 // Forward declarations
 class nsIAtom;
 class nsIDOMEvent;
 class nsIContent;
 class nsEventListenerManager;
 class nsIURI;
 class nsRuleWalker;
@@ -71,18 +72,18 @@ enum nsLinkState {
   eLinkState_Unknown    = 0,
   eLinkState_Unvisited  = 1,
   eLinkState_Visited    = 2,
   eLinkState_NotLink    = 3
 };
 
 // IID for the nsIContent interface
 #define NS_ICONTENT_IID       \
-{ 0x860ee35b, 0xe505, 0x438f, \
- { 0xa7, 0x7b, 0x65, 0xb9, 0xf5, 0x0b, 0xe5, 0x29 } }
+{ 0x4aad2c06, 0xd6c3, 0x4f44, \
+ { 0x94, 0xf9, 0xd5, 0xac, 0xe5, 0x04, 0x67, 0xec } }
 
 /**
  * A node of content in a document's content model. This interface
  * is supported by all content objects.
  */
 class nsIContent : public nsINode {
 public:
 #ifdef MOZILLA_INTERNAL_API
@@ -95,16 +96,18 @@ public:
   {
     NS_ASSERTION(mNodeInfo,
                  "No nsINodeInfo passed to nsIContent, PREPARE TO CRASH!!!");
   }
 #endif // MOZILLA_INTERNAL_API
 
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICONTENT_IID)
 
+  NS_DECL_AND_IMPL_DOM_MEMORY_REPORTER_SIZEOF(nsIContent, nsINode);
+
   /**
    * Bind this content node to a tree.  If this method throws, the caller must
    * call UnbindFromTree() on the node.  In the typical case of a node being
    * appended to a parent, this will be called after the node has been added to
    * the parent's child list and before nsIDocumentObserver notifications for
    * the addition are dispatched.
    * @param aDocument The new document for the content node.  Must match the
    *                  current document of aParent, if aParent is not null.
@@ -941,20 +944,16 @@ public:
    */
   nsIContent* GetEditingHost();
 
   // Overloaded from nsINode
   virtual already_AddRefed<nsIURI> GetBaseURI() const;
 
   virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
 
-  PRInt64 SizeOf() const {
-    return sizeof(*this);
-  }
-
 protected:
   /**
    * Hook for implementing GetID.  This is guaranteed to only be
    * called if HasID() is true.
    */
   virtual nsIAtom* DoGetID() const = 0;
 
 private:
--- a/content/base/public/nsIDOMFile.idl
+++ b/content/base/public/nsIDOMFile.idl
@@ -42,40 +42,41 @@
 %}
 
 interface nsIDOMFileError;
 interface nsIInputStream;
 interface nsIURI;
 interface nsIPrincipal;
 interface nsIDOMBlob;
 
-[scriptable, uuid(d5237f31-443a-460b-9e42-449a135346f0)]
+[scriptable, builtinclass, uuid(d5237f31-443a-460b-9e42-449a135346f0)]
 interface nsIDOMBlob : nsISupports
 {
   readonly attribute unsigned long long size;
   readonly attribute DOMString type;
 
   [noscript] readonly attribute nsIInputStream internalStream;
   // The caller is responsible for releasing the internalUrl from the
   // moz-filedata: protocol handler
   [noscript] DOMString getInternalUrl(in nsIPrincipal principal);
 
-  [optional_argc] nsIDOMBlob mozSlice(in long long start,
+  [optional_argc] nsIDOMBlob mozSlice([optional] in long long start,
                                       [optional] in long long end,
                                       [optional] in DOMString contentType);
 };
 
-[scriptable, uuid(b096ef67-7b77-47f8-8e70-5d8ee36416bf)]
+[scriptable, builtinclass, uuid(b096ef67-7b77-47f8-8e70-5d8ee36416bf)]
 interface nsIDOMFile : nsIDOMBlob
 {
   readonly attribute DOMString name;
   readonly attribute DOMString mozFullPath;
 
   // This performs no security checks!
   [noscript] readonly attribute DOMString mozFullPathInternal;
 };
 
-[scriptable, uuid(c4a77171-039b-4f84-97f9-820fb51626af)]
+[scriptable, builtinclass, uuid(006d2cde-ec18-41d4-acc3-43682dd418e2)]
 interface nsIDOMMozBlobBuilder : nsISupports
 {
   nsIDOMBlob getBlob([optional] in DOMString contentType);
+  nsIDOMFile getFile(in DOMString name, [optional] in DOMString contentType);
   [implicit_jscontext] void append(in jsval data);
 };
--- a/content/base/public/nsIFrameLoader.idl
+++ b/content/base/public/nsIFrameLoader.idl
@@ -136,17 +136,17 @@ interface nsIContentViewManager : nsISup
                          [retval, array, size_is(aLength)] out nsIContentView aResult);
 
   /**
    * The root content view.
    */
   readonly attribute nsIContentView rootContentView;
 };
 
-[scriptable, uuid(13c512d6-fba0-402a-9244-fe7941c43965)]
+[scriptable, uuid(12905a29-4246-475a-81d4-fc389197df02)]
 interface nsIFrameLoader : nsISupports
 {
   /**
    * Get the docshell from the frame loader.
    */
   readonly attribute nsIDocShell docShell;
 
   /**
@@ -183,16 +183,22 @@ interface nsIFrameLoader : nsISupports
 
   /**
    * Activate remote frame.
    * Throws an exception with non-remote frames.
    */
   void activateRemoteFrame();
 
   /**
+   * Deactivate remote frame.
+   * Throws an exception with non-remote frames.
+   */
+  void deactivateRemoteFrame();
+
+  /**
    * @see nsIDOMWindowUtils sendMouseEvent.
    */
   void sendCrossProcessMouseEvent(in AString aType,
                                   in float aX,
                                   in float aY,
                                   in long aButton,
                                   in long aClickCount,
                                   in long aModifiers,
@@ -229,16 +235,34 @@ interface nsIFrameLoader : nsISupports
    *
    * NB: when async scrolling is enabled, it's the *user's*
    * responsibility to update the target scroll offset.  In effect,
    * the platform hands over control of scroll offset to the user.
    */
   const unsigned long RENDER_MODE_ASYNC_SCROLL   = 0x00000001;
 
   attribute unsigned long renderMode;
+
+  /**
+   * The default event mode automatically forwards the events
+   * handled in nsEventStateManager::HandleCrossProcessEvent to
+   * the child content process when these events are targeted to
+   * the remote browser element.
+   *
+   * Used primarly for input events (mouse, keyboard)
+   */
+  const unsigned long EVENT_MODE_NORMAL_DISPATCH = 0x00000000;
+
+  /**
+   * With this event mode, it's the application's responsability to 
+   * convert and forward events to the content process
+   */
+  const unsigned long EVENT_MODE_DONT_FORWARD_TO_CHILD = 0x00000001;
+
+  attribute unsigned long eventMode;
 };
 
 native alreadyAddRefed_nsFrameLoader(already_AddRefed<nsFrameLoader>);
 
 [scriptable, uuid(5879040e-83e9-40e3-b2bb-5ddf43b76e47)]
 interface nsIFrameLoaderOwner : nsISupports
 {
   /**
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -275,30 +275,34 @@ private:
 #define DOM_USER_DATA         1
 #define DOM_USER_DATA_HANDLER 2
 #ifdef MOZ_SMIL
 #define SMIL_MAPPED_ATTR_ANIMVAL 3
 #endif // MOZ_SMIL
 
 // IID for the nsINode interface
 #define NS_INODE_IID \
-{ 0x4776aa9a, 0xa886, 0x40c9, \
- { 0xae, 0x4c, 0x4d, 0x92, 0xe2, 0xf0, 0xd9, 0x61 } }
+{ 0xc7abbb40, 0x2571, 0x4d12, \
+ { 0x8f, 0x89, 0x0d, 0x4f, 0x55, 0xc0, 0x92, 0xf6 } }
 
 /**
  * An internal interface that abstracts some DOMNode-related parts that both
  * nsIContent and nsIDocument share.  An instance of this interface has a list
  * of nsIContent children and provides access to them.
  */
 class nsINode : public nsIDOMEventTarget,
                 public nsWrapperCache
 {
 public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_INODE_IID)
 
+  virtual PRInt64 SizeOf() const {
+    return sizeof(*this);
+  }
+
   friend class nsNodeUtils;
   friend class nsNodeWeakReference;
   friend class nsNodeSupportsWeakRefTearoff;
   friend class nsAttrAndChildArray;
 
 #ifdef MOZILLA_INTERNAL_API
   nsINode(already_AddRefed<nsINodeInfo> aNodeInfo)
   : mNodeInfo(aNodeInfo),
--- a/content/base/src/nsAttrAndChildArray.cpp
+++ b/content/base/src/nsAttrAndChildArray.cpp
@@ -842,8 +842,26 @@ nsAttrAndChildArray::SetChildAtPos(void*
     previous->mNextSibling = aChild;
   }
   if (aIndex != aChildCount) {
     nsIContent* next = static_cast<nsIContent*>(*(aPos + 1));
     aChild->mNextSibling = next;
     next->mPreviousSibling = aChild;
   }
 }
+
+PRInt64
+nsAttrAndChildArray::SizeOf() const
+{
+  PRInt64 size = sizeof(*this);
+
+  if (mImpl) {
+    // Don't add the size taken by *mMappedAttrs because it's shared.
+
+    // mBuffer cointains InternalAttr and nsIContent* (even if it's void**)
+    // so, we just have to compute the size of *mBuffer given that this object
+    // doesn't own the children list.
+    size += mImpl->mBufferSize * sizeof(*(mImpl->mBuffer)) + NS_IMPL_EXTRA_SIZE;
+  }
+
+  return size;
+}
+
--- a/content/base/src/nsAttrAndChildArray.h
+++ b/content/base/src/nsAttrAndChildArray.h
@@ -126,16 +126,18 @@ public:
   void Compact();
 
   bool CanFitMoreAttrs() const
   {
     return AttrSlotCount() < ATTRCHILD_ARRAY_MAX_ATTR_COUNT ||
            !AttrSlotIsTaken(ATTRCHILD_ARRAY_MAX_ATTR_COUNT - 1);
   }
 
+  PRInt64 SizeOf() const;
+
 private:
   nsAttrAndChildArray(const nsAttrAndChildArray& aOther); // Not to be implemented
   nsAttrAndChildArray& operator=(const nsAttrAndChildArray& aOther); // Not to be implemented
 
   void Clear();
 
   PRUint32 NonMappedAttrCount() const;
   PRUint32 MappedAttrCount() const;
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -61,17 +61,17 @@
 #include "nsIParser.h"
 #include "nsContentErrors.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIViewManager.h"
 #include "nsIContentViewer.h"
 #include "nsIAtom.h"
 #include "nsGkAtoms.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIPrincipal.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsNetCID.h"
 #include "nsIOfflineCacheUpdate.h"
 #include "nsIApplicationCache.h"
 #include "nsIApplicationCacheContainer.h"
 #include "nsIApplicationCacheChannel.h"
 #include "nsIScriptSecurityManager.h"
@@ -510,17 +510,17 @@ nsContentSink::ProcessHeaderData(nsIAtom
 
     // Note that a non-codebase principal (eg the system principal) will return
     // a null URI.
     nsCOMPtr<nsIURI> codebaseURI;
     rv = mDocument->NodePrincipal()->GetURI(getter_AddRefs(codebaseURI));
     NS_ENSURE_TRUE(codebaseURI, rv);
 
     nsCOMPtr<nsIPrompt> prompt;
-    nsCOMPtr<nsIDOMWindowInternal> window (do_QueryInterface(mDocument->GetScriptGlobalObject()));
+    nsCOMPtr<nsIDOMWindow> window = do_QueryInterface(mDocument->GetScriptGlobalObject());
     if (window) {
       window->GetPrompter(getter_AddRefs(prompt));
     }
 
     nsCOMPtr<nsIChannel> channel;
     if (mParser) {
       mParser->GetChannel(getter_AddRefs(channel));
     }
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -2319,16 +2319,17 @@ nsContentUtils::LoadImage(nsIURI* aURI, 
   // Make the URI immutable so people won't change it under us
   NS_TryToSetImmutable(aURI);
 
   // XXXbz using "documentURI" for the initialDocumentURI is not quite
   // right, but the best we can do here...
   return imgLoader->LoadImage(aURI,                 /* uri to load */
                               documentURI,          /* initialDocumentURI */
                               aReferrer,            /* referrer */
+                              aLoadingPrincipal,    /* loading principal */
                               loadGroup,            /* loadgroup */
                               aObserver,            /* imgIDecoderObserver */
                               aLoadingDocument,     /* uniquification key */
                               aLoadFlags,           /* load flags */
                               nsnull,               /* cache key */
                               nsnull,               /* existing request*/
                               channelPolicy,        /* CSP info */
                               aRequest);
--- a/content/base/src/nsDOMBlobBuilder.cpp
+++ b/content/base/src/nsDOMBlobBuilder.cpp
@@ -47,74 +47,75 @@
 #include "CheckedInt.h"
 
 // XXXkhuey shamelessly stolen from VideoUtils.h.  We should patch NSPR.
 #define PR_INT64_MAX (~((PRInt64)(1) << 63))
 #define PR_INT64_MIN (-PR_INT64_MAX - 1)
 
 using namespace mozilla;
 
-class nsDOMMultipartBlob : public nsDOMFile
+class nsDOMMultipartFile : public nsDOMFileBase
 {
 public:
-  nsDOMMultipartBlob(nsTArray<nsCOMPtr<nsIDOMBlob> > aBlobs,
+  // Create as a file
+  nsDOMMultipartFile(nsTArray<nsCOMPtr<nsIDOMBlob> > aBlobs,
+                     const nsAString& aName,
                      const nsAString& aContentType)
-    : nsDOMFile(nsnull, aContentType),
+    : nsDOMFileBase(aName, aContentType, PR_UINT64_MAX),
       mBlobs(aBlobs)
   {
-    mIsFullFile = false;
-    mStart = 0;
-    mLength = 0;
   }
 
+  // Create as a blob
+  nsDOMMultipartFile(nsTArray<nsCOMPtr<nsIDOMBlob> > aBlobs,
+                     const nsAString& aContentType)
+    : nsDOMFileBase(aContentType, PR_UINT64_MAX),
+      mBlobs(aBlobs)
+  {
+  }
+
+  already_AddRefed<nsIDOMBlob>
+  CreateSlice(PRUint64 aStart, PRUint64 aLength, const nsAString& aContentType);
+
   NS_IMETHOD GetSize(PRUint64*);
   NS_IMETHOD GetInternalStream(nsIInputStream**);
-  NS_IMETHOD MozSlice(PRInt64 aStart, PRInt64 aEnd,
-                      const nsAString& aContentType, PRUint8 optional_argc,
-                      nsIDOMBlob **aBlob);
 
 protected:
   nsTArray<nsCOMPtr<nsIDOMBlob> > mBlobs;
 };
 
 NS_IMETHODIMP
-nsDOMMultipartBlob::GetSize(PRUint64* aLength)
+nsDOMMultipartFile::GetSize(PRUint64* aLength)
 {
-  nsresult rv;
-  *aLength = 0;
+  if (mLength == PR_UINT64_MAX) {
+    CheckedUint64 length = 0;
+  
+    PRUint32 i;
+    PRUint32 len = mBlobs.Length();
+    for (i = 0; i < len; i++) {
+      nsIDOMBlob* blob = mBlobs.ElementAt(i).get();
+      PRUint64 l = 0;
+  
+      nsresult rv = blob->GetSize(&l);
+      NS_ENSURE_SUCCESS(rv, rv);
+  
+      length += l;
+    }
+  
+    NS_ENSURE_TRUE(length.valid(), NS_ERROR_FAILURE);
 
-  if (mLength) {
-    *aLength = mLength;
-    return NS_OK;
+    mLength = length.value();
   }
 
-  CheckedUint64 length = 0;
-
-  PRUint32 i;
-  PRUint32 len = mBlobs.Length();
-  for (i = 0; i < len; i++) {
-    nsIDOMBlob* blob = mBlobs.ElementAt(i).get();
-    PRUint64 l = 0;
-
-    rv = blob->GetSize(&l);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    length += l;
-  }
-
-  if (!length.valid())
-    return NS_ERROR_FAILURE;
-
-  mLength = length.value();
   *aLength = mLength;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMMultipartBlob::GetInternalStream(nsIInputStream** aStream)
+nsDOMMultipartFile::GetInternalStream(nsIInputStream** aStream)
 {
   nsresult rv;
   *aStream = nsnull;
 
   nsCOMPtr<nsIMultiplexInputStream> stream =
     do_CreateInstance("@mozilla.org/io/multiplex-input-stream;1");
   NS_ENSURE_TRUE(stream, NS_ERROR_FAILURE);
 
@@ -128,102 +129,81 @@ nsDOMMultipartBlob::GetInternalStream(ns
 
     rv = stream->AppendStream(scratchStream);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return CallQueryInterface(stream, aStream);
 }
 
-NS_IMETHODIMP
-nsDOMMultipartBlob::MozSlice(PRInt64 aStart, PRInt64 aEnd,
-                             const nsAString& aContentType,
-                             PRUint8 optional_argc,
-                             nsIDOMBlob **aBlob)
+already_AddRefed<nsIDOMBlob>
+nsDOMMultipartFile::CreateSlice(PRUint64 aStart, PRUint64 aLength,
+                                const nsAString& aContentType)
 {
-  nsresult rv;
-  *aBlob = nsnull;
-
-  // Truncate aStart and aEnd so that we stay within this file.
-  PRUint64 thisLength;
-  rv = GetSize(&thisLength);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  if (!optional_argc) {
-    aEnd = (PRInt64)thisLength;
-  }
-
-  // Modifies aStart and aEnd.
-  ParseSize((PRInt64)thisLength, aStart, aEnd);
-
   // If we clamped to nothing we create an empty blob
   nsTArray<nsCOMPtr<nsIDOMBlob> > blobs;
 
-  PRUint64 length = aEnd - aStart;
+  PRUint64 length = aLength;
   PRUint64 skipStart = aStart;
 
-  NS_ABORT_IF_FALSE(PRUint64(aStart) + length <= thisLength, "Er, what?");
-
   // Prune the list of blobs if we can
   PRUint32 i;
   for (i = 0; length && skipStart && i < mBlobs.Length(); i++) {
     nsIDOMBlob* blob = mBlobs[i].get();
 
     PRUint64 l;
-    rv = blob->GetSize(&l);
-    NS_ENSURE_SUCCESS(rv, rv);
+    nsresult rv = blob->GetSize(&l);
+    NS_ENSURE_SUCCESS(rv, nsnull);
 
     if (skipStart < l) {
       PRUint64 upperBound = NS_MIN<PRUint64>(l - skipStart, length);
 
       nsCOMPtr<nsIDOMBlob> firstBlob;
-      rv = mBlobs.ElementAt(i)->MozSlice(skipStart, skipStart + upperBound,
-                                         aContentType, 2,
-                                         getter_AddRefs(firstBlob));
-      NS_ENSURE_SUCCESS(rv, rv);
+      rv = blob->MozSlice(skipStart, skipStart + upperBound,
+                          aContentType, 3,
+                          getter_AddRefs(firstBlob));
+      NS_ENSURE_SUCCESS(rv, nsnull);
 
-      // Avoid wrapping a single blob inside an nsDOMMultipartBlob
+      // Avoid wrapping a single blob inside an nsDOMMultipartFile
       if (length == upperBound) {
-        firstBlob.forget(aBlob);
-        return NS_OK;
+        return firstBlob.forget();
       }
 
       blobs.AppendElement(firstBlob);
       length -= upperBound;
       i++;
       break;
     }
     skipStart -= l;
   }
 
   // Now append enough blobs until we're done
   for (; length && i < mBlobs.Length(); i++) {
     nsIDOMBlob* blob = mBlobs[i].get();
 
     PRUint64 l;
-    rv = blob->GetSize(&l);
-    NS_ENSURE_SUCCESS(rv, rv);
+    nsresult rv = blob->GetSize(&l);
+    NS_ENSURE_SUCCESS(rv, nsnull);
 
     if (length < l) {
       nsCOMPtr<nsIDOMBlob> lastBlob;
-      rv = mBlobs.ElementAt(i)->MozSlice(0, length, aContentType, 2,
-                                         getter_AddRefs(lastBlob));
-      NS_ENSURE_SUCCESS(rv, rv);
+      rv = blob->MozSlice(0, length, aContentType, 3,
+                          getter_AddRefs(lastBlob));
+      NS_ENSURE_SUCCESS(rv, nsnull);
 
       blobs.AppendElement(lastBlob);
     } else {
       blobs.AppendElement(blob);
     }
     length -= NS_MIN<PRUint64>(l, length);
   }
 
   // we can create our blob now
-  nsCOMPtr<nsIDOMBlob> blob = new nsDOMMultipartBlob(blobs, aContentType);
-  blob.forget(aBlob);
-  return NS_OK;
+  nsCOMPtr<nsIDOMBlob> blob = new nsDOMMultipartFile(blobs, aContentType);
+  return blob.forget();
 }
 
 class nsDOMBlobBuilder : public nsIDOMMozBlobBuilder
 {
 public:
   nsDOMBlobBuilder()
     : mData(nsnull), mDataLen(0), mDataBufferLen(0)
   {}
@@ -341,29 +321,53 @@ nsDOMBlobBuilder::AppendArrayBuffer(JSOb
 NS_IMETHODIMP
 nsDOMBlobBuilder::GetBlob(const nsAString& aContentType,
                           nsIDOMBlob** aBlob)
 {
   NS_ENSURE_ARG(aBlob);
 
   Flush();
 
-  nsCOMPtr<nsIDOMBlob> blob = new nsDOMMultipartBlob(mBlobs,
+  nsCOMPtr<nsIDOMBlob> blob = new nsDOMMultipartFile(mBlobs,
                                                      aContentType);
   blob.forget(aBlob);
 
   // NB: This is a willful violation of the spec.  The spec says that
   // the existing contents of the BlobBuilder should be included
   // in the next blob produced.  This seems silly and has been raised
   // on the WHATWG listserv.
   mBlobs.Clear();
 
   return NS_OK;
 }
 
+/* nsIDOMBlob getFile (in DOMString name, [optional] in DOMString contentType); */
+NS_IMETHODIMP
+nsDOMBlobBuilder::GetFile(const nsAString& aName,
+                          const nsAString& aContentType,
+                          nsIDOMFile** aFile)
+{
+  NS_ENSURE_ARG(aFile);
+
+  Flush();
+
+  nsCOMPtr<nsIDOMFile> file = new nsDOMMultipartFile(mBlobs,
+                                                     aName,
+                                                     aContentType);
+  file.forget(aFile);
+
+  // NB: This is a willful violation of the spec.  The spec says that
+  // the existing contents of the BlobBuilder should be included
+  // in the next blob produced.  This seems silly and has been raised
+  // on the WHATWG listserv.
+  mBlobs.Clear();
+
+  return NS_OK;
+}
+
 /* [implicit_jscontext] void append (in jsval data); */
 NS_IMETHODIMP
 nsDOMBlobBuilder::Append(const jsval& aData, JSContext* aCx)
 {
   // We need to figure out what our jsval is
 
   // Is it an object?
   if (JSVAL_IS_OBJECT(aData)) {
--- a/content/base/src/nsDOMFile.cpp
+++ b/content/base/src/nsDOMFile.cpp
@@ -127,129 +127,78 @@ nsresult DataOwnerAdapter::Create(DataOw
                              NS_ASSIGNMENT_DEPEND);
   NS_ENSURE_SUCCESS(rv, rv);
 
   NS_ADDREF(*_retval = new DataOwnerAdapter(aDataOwner, stream));
 
   return NS_OK;
 }
 
-// nsDOMFile implementation
+////////////////////////////////////////////////////////////////////////////
+// nsDOMFileBase implementation
 
-DOMCI_DATA(File, nsDOMFile)
-DOMCI_DATA(Blob, nsDOMFile)
+DOMCI_DATA(File, nsDOMFileBase)
+DOMCI_DATA(Blob, nsDOMFileBase)
 
-NS_INTERFACE_MAP_BEGIN(nsDOMFile)
+NS_INTERFACE_MAP_BEGIN(nsDOMFileBase)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMFile)
   NS_INTERFACE_MAP_ENTRY(nsIDOMBlob)
-  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIDOMFile, mIsFullFile)
+  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIDOMFile, mIsFile)
   NS_INTERFACE_MAP_ENTRY(nsIXHRSendable)
-  NS_INTERFACE_MAP_ENTRY(nsIJSNativeInitializer)
-  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO_CONDITIONAL(File, mIsFullFile)
-  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO_CONDITIONAL(Blob, !mIsFullFile)
+  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO_CONDITIONAL(File, mIsFile)
+  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO_CONDITIONAL(Blob, !mIsFile)
 NS_INTERFACE_MAP_END
 
-NS_IMPL_ADDREF(nsDOMFile)
-NS_IMPL_RELEASE(nsDOMFile)
-
-static nsresult
-DOMFileResult(nsresult rv)
-{
-  if (rv == NS_ERROR_FILE_NOT_FOUND) {
-    return NS_ERROR_DOM_FILE_NOT_FOUND_ERR;
-  }
+NS_IMPL_ADDREF(nsDOMFileBase)
+NS_IMPL_RELEASE(nsDOMFileBase)
 
-  if (NS_ERROR_GET_MODULE(rv) == NS_ERROR_MODULE_FILES) {
-    return NS_ERROR_DOM_FILE_NOT_READABLE_ERR;
-  }
-
-  return rv;
-}
-
-/* static */ nsresult
-nsDOMFile::NewFile(nsISupports* *aNewObject)
+NS_IMETHODIMP
+nsDOMFileBase::GetName(nsAString &aFileName)
 {
-  nsCOMPtr<nsISupports> file = do_QueryObject(new nsDOMFile(nsnull));
-  file.forget(aNewObject);
+  NS_ASSERTION(mIsFile, "Should only be called on files");
+  aFileName = mName;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMFile::GetName(nsAString &aFileName)
+nsDOMFileBase::GetMozFullPath(nsAString &aFileName)
 {
-  NS_ASSERTION(mIsFullFile, "Should only be called on files");
-  return mFile->GetLeafName(aFileName);
-}
-
-NS_IMETHODIMP
-nsDOMFile::GetMozFullPath(nsAString &aFileName)
-{
-  NS_ASSERTION(mIsFullFile, "Should only be called on files");
+  NS_ASSERTION(mIsFile, "Should only be called on files");
   if (nsContentUtils::IsCallerTrustedForCapability("UniversalFileRead")) {
     return GetMozFullPathInternal(aFileName);
   }
   aFileName.Truncate();
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMFile::GetMozFullPathInternal(nsAString &aFilename)
-{
-  NS_ASSERTION(mIsFullFile, "Should only be called on files");
-  return mFile->GetPath(aFilename);
-}
-
-NS_IMETHODIMP
-nsDOMFile::GetSize(PRUint64 *aFileSize)
+nsDOMFileBase::GetMozFullPathInternal(nsAString &aFileName)
 {
-  if (mIsFullFile) {
-    PRInt64 fileSize;
-    nsresult rv = mFile->GetFileSize(&fileSize);
-    NS_ENSURE_SUCCESS(rv, rv);
-  
-    if (fileSize < 0) {
-      return NS_ERROR_FAILURE;
-    }
-  
-    *aFileSize = fileSize;
-  }
-  else {
-    *aFileSize = mLength;
-  }
-
+  NS_ASSERTION(mIsFile, "Should only be called on files");
+  aFileName.Truncate();
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMFile::GetType(nsAString &aType)
+nsDOMFileBase::GetSize(PRUint64 *aSize)
 {
-  if (mContentType.IsEmpty() && mFile && mIsFullFile) {
-    nsresult rv;
-    nsCOMPtr<nsIMIMEService> mimeService =
-      do_GetService(NS_MIMESERVICE_CONTRACTID, &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
+  *aSize = mLength;
+  return NS_OK;
+}
 
-    nsCAutoString mimeType;
-    rv = mimeService->GetTypeFromFile(mFile, mimeType);
-    if (NS_FAILED(rv)) {
-      aType.Truncate();
-      return NS_OK;
-    }
-
-    AppendUTF8toUTF16(mimeType, mContentType);
-  }
-
+NS_IMETHODIMP
+nsDOMFileBase::GetType(nsAString &aType)
+{
   aType = mContentType;
-
   return NS_OK;
 }
 
 // Makes sure that aStart and aEnd is less then or equal to aSize and greater
 // than 0
-void
+static void
 ParseSize(PRInt64 aSize, PRInt64& aStart, PRInt64& aEnd)
 {
   CheckedInt64 newStartOffset = aStart;
   if (aStart < -aSize) {
     newStartOffset = 0;
   }
   else if (aStart < 0) {
     newStartOffset += aSize;
@@ -275,55 +224,51 @@ ParseSize(PRInt64 aSize, PRInt64& aStart
   }
   else {
     aStart = newStartOffset.value();
     aEnd = newEndOffset.value();
   }
 }
 
 NS_IMETHODIMP
-nsDOMFile::MozSlice(PRInt64 aStart, PRInt64 aEnd,
-                    const nsAString& aContentType, PRUint8 optional_argc,
-                    nsIDOMBlob **aBlob)
+nsDOMFileBase::MozSlice(PRInt64 aStart, PRInt64 aEnd,
+                        const nsAString& aContentType, PRUint8 optional_argc,
+                        nsIDOMBlob **aBlob)
 {
   *aBlob = nsnull;
 
   // Truncate aStart and aEnd so that we stay within this file.
   PRUint64 thisLength;
   nsresult rv = GetSize(&thisLength);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (!optional_argc) {
+  if (optional_argc < 2) {
     aEnd = (PRInt64)thisLength;
   }
 
   ParseSize((PRInt64)thisLength, aStart, aEnd);
   
   // Create the new file
-  NS_ADDREF(*aBlob = new nsDOMFile(this, aStart, aEnd - aStart, aContentType));
-  
-  return NS_OK;
-}
+  *aBlob = CreateSlice((PRUint64)aStart, (PRUint64)(aEnd - aStart),
+                       aContentType).get();
 
-const PRUint32 sFileStreamFlags =
-  nsIFileInputStream::CLOSE_ON_EOF |
-  nsIFileInputStream::REOPEN_ON_REWIND |
-  nsIFileInputStream::DEFER_OPEN;
-
-NS_IMETHODIMP
-nsDOMFile::GetInternalStream(nsIInputStream **aStream)
-{
-  return mIsFullFile ?
-    NS_NewLocalFileInputStream(aStream, mFile, -1, -1, sFileStreamFlags) :
-    NS_NewPartialLocalFileInputStream(aStream, mFile, mStart, mLength,
-                                      -1, -1, sFileStreamFlags);
+  return *aBlob ? NS_OK : NS_ERROR_UNEXPECTED;
 }
 
 NS_IMETHODIMP
-nsDOMFile::GetInternalUrl(nsIPrincipal* aPrincipal, nsAString& aURL)
+nsDOMFileBase::GetInternalStream(nsIInputStream **aStream)
+{
+  // Must be overridden
+  NS_NOTREACHED("Must override GetInternalStream");
+  
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+nsDOMFileBase::GetInternalUrl(nsIPrincipal* aPrincipal, nsAString& aURL)
 {
   NS_ENSURE_STATE(aPrincipal);
 
   nsresult rv;
   nsCOMPtr<nsIUUIDGenerator> uuidgen =
     do_GetService("@mozilla.org/uuid-generator;1", &rv);
   NS_ENSURE_SUCCESS(rv, rv);
   
@@ -341,19 +286,19 @@ nsDOMFile::GetInternalUrl(nsIPrincipal* 
                                               aPrincipal);
 
   CopyASCIItoUTF16(url, aURL);
   
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMFile::GetSendInfo(nsIInputStream** aBody,
-                       nsACString& aContentType,
-                       nsACString& aCharset)
+nsDOMFileBase::GetSendInfo(nsIInputStream** aBody,
+                           nsACString& aContentType,
+                           nsACString& aCharset)
 {
   nsresult rv;
 
   nsCOMPtr<nsIInputStream> stream;
   rv = this->GetInternalStream(getter_AddRefs(stream));
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsString contentType;
@@ -363,22 +308,113 @@ nsDOMFile::GetSendInfo(nsIInputStream** 
   CopyUTF16toUTF8(contentType, aContentType);
 
   aCharset.Truncate();
 
   stream.forget(aBody);
   return NS_OK;
 }
 
+////////////////////////////////////////////////////////////////////////////
+// nsDOMFileFile implementation
+
+NS_IMPL_ISUPPORTS_INHERITED1(nsDOMFileFile, nsDOMFileBase,
+                             nsIJSNativeInitializer)
+
+already_AddRefed<nsIDOMBlob>
+nsDOMFileFile::CreateSlice(PRUint64 aStart, PRUint64 aLength,
+                           const nsAString& aContentType)
+{
+  nsCOMPtr<nsIDOMBlob> t = new nsDOMFileFile(this, aStart, aLength, aContentType);
+  return t.forget();
+}
+
+/* static */ nsresult
+nsDOMFileFile::NewFile(nsISupports* *aNewObject)
+{
+  nsCOMPtr<nsISupports> file = do_QueryObject(new nsDOMFileFile());
+  file.forget(aNewObject);
+  return NS_OK;
+}
+
 NS_IMETHODIMP
-nsDOMFile::Initialize(nsISupports* aOwner,
-                      JSContext* aCx,
-                      JSObject* aObj,
-                      PRUint32 aArgc,
-                      jsval* aArgv)
+nsDOMFileFile::GetMozFullPathInternal(nsAString &aFilename)
+{
+  NS_ASSERTION(mIsFile, "Should only be called on files");
+  return mFile->GetPath(aFilename);
+}
+
+NS_IMETHODIMP
+nsDOMFileFile::GetSize(PRUint64 *aFileSize)
+{
+  if (IsSizeUnknown()) {
+    NS_ASSERTION(mWholeFile,
+                 "Should only use lazy size when using the whole file");
+    PRInt64 fileSize;
+    nsresult rv = mFile->GetFileSize(&fileSize);
+    NS_ENSURE_SUCCESS(rv, rv);
+  
+    if (fileSize < 0) {
+      return NS_ERROR_FAILURE;
+    }
+  
+    mLength = fileSize;
+  }
+
+  *aFileSize = mLength;
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDOMFileFile::GetType(nsAString &aType)
+{
+  if (mContentType.IsVoid()) {
+    NS_ASSERTION(mWholeFile,
+                 "Should only use lazy ContentType when using the whole file");
+    nsresult rv;
+    nsCOMPtr<nsIMIMEService> mimeService =
+      do_GetService(NS_MIMESERVICE_CONTRACTID, &rv);
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    nsCAutoString mimeType;
+    rv = mimeService->GetTypeFromFile(mFile, mimeType);
+    if (NS_FAILED(rv)) {
+      mimeType.Truncate();
+    }
+
+    AppendUTF8toUTF16(mimeType, mContentType);
+    mContentType.SetIsVoid(PR_FALSE);
+  }
+
+  aType = mContentType;
+
+  return NS_OK;
+}
+
+const PRUint32 sFileStreamFlags =
+  nsIFileInputStream::CLOSE_ON_EOF |
+  nsIFileInputStream::REOPEN_ON_REWIND |
+  nsIFileInputStream::DEFER_OPEN;
+
+NS_IMETHODIMP
+nsDOMFileFile::GetInternalStream(nsIInputStream **aStream)
+{
+  return mWholeFile ?
+    NS_NewLocalFileInputStream(aStream, mFile, -1, -1, sFileStreamFlags) :
+    NS_NewPartialLocalFileInputStream(aStream, mFile, mStart, mLength,
+                                      -1, -1, sFileStreamFlags);
+}
+
+NS_IMETHODIMP
+nsDOMFileFile::Initialize(nsISupports* aOwner,
+                          JSContext* aCx,
+                          JSObject* aObj,
+                          PRUint32 aArgc,
+                          jsval* aArgv)
 {
   nsresult rv;
 
   if (!nsContentUtils::IsCallerChrome()) {
     return NS_ERROR_DOM_SECURITY_ERR; // Real short trip
   }
 
   NS_ENSURE_TRUE(aArgc > 0, NS_ERROR_UNEXPECTED);
@@ -419,74 +455,49 @@ nsDOMFile::Initialize(nsISupports* aOwne
     NS_ASSERTION(file, "This should never happen");
   }
 
   PRBool exists;
   rv = file->Exists(&exists);
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(exists, NS_ERROR_FILE_NOT_FOUND);
 
-  mFile = file;
-  return NS_OK;
-}
+  PRBool isDir;
+  rv = file->IsDirectory(&isDir);
+  NS_ENSURE_SUCCESS(rv, rv);
+  NS_ENSURE_FALSE(isDir, NS_ERROR_FILE_IS_DIRECTORY);
 
-// nsDOMMemoryFile Implementation
-NS_IMETHODIMP
-nsDOMMemoryFile::GetName(nsAString &aFileName)
-{
-  NS_ASSERTION(mIsFullFile, "Should only be called on files");
-  aFileName = mName;
-  return NS_OK;
-}
+  mFile = file;
+  file->GetLeafName(mName);
 
-NS_IMETHODIMP
-nsDOMMemoryFile::GetSize(PRUint64 *aFileSize)
-{
-  *aFileSize = mLength;
   return NS_OK;
 }
 
-NS_IMETHODIMP
-nsDOMMemoryFile::MozSlice(PRInt64 aStart, PRInt64 aEnd,
-                          const nsAString& aContentType, PRUint8 optional_argc,
-                          nsIDOMBlob **aBlob)
-{
-  *aBlob = nsnull;
+////////////////////////////////////////////////////////////////////////////
+// nsDOMMemoryFile implementation
 
-  if (!optional_argc) {
-    aEnd = (PRInt64)mLength;
-  }
-
-  // Truncate aLength and aStart so that we stay within this file.
-  ParseSize((PRInt64)mLength, aStart, aEnd);
-
-  // Create the new file
-  NS_ADDREF(*aBlob = new nsDOMMemoryFile(this, aStart, aEnd - aStart,
-                                         aContentType));
-  
-  return NS_OK;
+already_AddRefed<nsIDOMBlob>
+nsDOMMemoryFile::CreateSlice(PRUint64 aStart, PRUint64 aLength,
+                             const nsAString& aContentType)
+{
+  nsCOMPtr<nsIDOMBlob> t =
+    new nsDOMMemoryFile(this, aStart, aLength, aContentType);
+  return t.forget();
 }
 
 NS_IMETHODIMP
 nsDOMMemoryFile::GetInternalStream(nsIInputStream **aStream)
 {
   if (mLength > PR_INT32_MAX)
     return NS_ERROR_FAILURE;
 
   return DataOwnerAdapter::Create(mDataOwner, mStart, mLength, aStream);
 }
 
-NS_IMETHODIMP
-nsDOMMemoryFile::GetMozFullPathInternal(nsAString &aFilename)
-{
-  NS_ASSERTION(mIsFullFile, "Should only be called on files");
-  aFilename.Truncate();
-  return NS_OK;
-}
-
+////////////////////////////////////////////////////////////////////////////
 // nsDOMFileList implementation
 
 DOMCI_DATA(FileList, nsDOMFileList)
 
 NS_INTERFACE_MAP_BEGIN(nsDOMFileList)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMFileList)
   NS_INTERFACE_MAP_ENTRY(nsIDOMFileList)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(FileList)
@@ -506,16 +517,17 @@ nsDOMFileList::GetLength(PRUint32* aLeng
 NS_IMETHODIMP
 nsDOMFileList::Item(PRUint32 aIndex, nsIDOMFile **aFile)
 {
   NS_IF_ADDREF(*aFile = GetItemAt(aIndex));
 
   return NS_OK;
 }
 
+////////////////////////////////////////////////////////////////////////////
 // nsDOMFileError implementation
 
 DOMCI_DATA(FileError, nsDOMFileError)
 
 NS_INTERFACE_MAP_BEGIN(nsDOMFileError)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMFileError)
   NS_INTERFACE_MAP_ENTRY(nsIDOMFileError)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(FileError)
@@ -526,16 +538,19 @@ NS_IMPL_RELEASE(nsDOMFileError)
 
 NS_IMETHODIMP
 nsDOMFileError::GetCode(PRUint16* aCode)
 {
   *aCode = mCode;
   return NS_OK;
 }
 
+////////////////////////////////////////////////////////////////////////////
+// nsDOMFileInternalUrlHolder implementation
+
 nsDOMFileInternalUrlHolder::nsDOMFileInternalUrlHolder(nsIDOMBlob* aFile,
                                                        nsIPrincipal* aPrincipal
                                                        MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL) {
   MOZILLA_GUARD_OBJECT_NOTIFIER_INIT;
   aFile->GetInternalUrl(aPrincipal, mUrl);
 }
  
 nsDOMFileInternalUrlHolder::~nsDOMFileInternalUrlHolder() {
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -111,17 +111,17 @@
 #include "nsIWebNavigation.h"
 #include "nsIScriptError.h"
 
 #include "nsNetUtil.h"     // for NS_MakeAbsoluteURI
 
 #include "nsIScriptSecurityManager.h"
 #include "nsIPrincipal.h"
 
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDOMElement.h"
 #include "nsFocusManager.h"
 
 // for radio group stuff
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIRadioVisitor.h"
 #include "nsIFormControl.h"
@@ -5090,31 +5090,30 @@ nsDocument::GetDefaultView(nsIDOMWindow*
 }
 
 NS_IMETHODIMP
 nsDocument::GetLocation(nsIDOMLocation **_retval)
 {
   NS_ENSURE_ARG_POINTER(_retval);
   *_retval = nsnull;
 
-  nsCOMPtr<nsIDOMWindowInternal> w(do_QueryInterface(mScriptGlobalObject));
+  nsCOMPtr<nsIDOMWindow> w = do_QueryInterface(mScriptGlobalObject);
 
   if (!w) {
     return NS_OK;
   }
 
   return w->GetLocation(_retval);
 }
 
 Element*
 nsIDocument::GetHtmlElement()
 {
   Element* rootElement = GetRootElement();
-  if (rootElement && rootElement->Tag() == nsGkAtoms::html &&
-      rootElement->IsHTML())
+  if (rootElement && rootElement->IsHTML(nsGkAtoms::html))
     return rootElement;
   return nsnull;
 }
 
 Element*
 nsIDocument::GetHtmlChildElement(nsIAtom* aTag)
 {
   Element* html = GetHtmlElement();
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -322,16 +322,17 @@ nsFrameLoader::nsFrameLoader(nsIContent 
   , mHideCalled(PR_FALSE)
   , mNetworkCreated(aNetworkCreated)
   , mDelayRemoteDialogs(PR_FALSE)
   , mRemoteBrowserShown(PR_FALSE)
   , mRemoteFrame(false)
   , mCurrentRemoteFrame(nsnull)
   , mRemoteBrowser(nsnull)
   , mRenderMode(RENDER_MODE_DEFAULT)
+  , mEventMode(EVENT_MODE_NORMAL_DISPATCH)
 {
 }
 
 nsFrameLoader*
 nsFrameLoader::Create(nsIContent* aOwner, PRBool aNetworkCreated)
 {
   NS_ENSURE_TRUE(aOwner, nsnull);
   nsIDocument* doc = aOwner->GetOwnerDoc();
@@ -532,36 +533,37 @@ nsFrameLoader::CheckURILoad(nsIURI* aURI
   }
   return CheckForRecursiveLoad(aURI);
 }
 
 NS_IMETHODIMP
 nsFrameLoader::GetDocShell(nsIDocShell **aDocShell)
 {
   *aDocShell = nsnull;
+  nsresult rv = NS_OK;
 
   // If we have an owner, make sure we have a docshell and return
   // that. If not, we're most likely in the middle of being torn down,
   // then we just return null.
   if (mOwnerContent) {
     nsresult rv = MaybeCreateDocShell();
     if (NS_FAILED(rv))
       return rv;
     if (mRemoteFrame) {
       NS_WARNING("No docshells for remote frames!");
-      return NS_ERROR_NOT_AVAILABLE;
+      return rv;
     }
     NS_ASSERTION(mDocShell,
                  "MaybeCreateDocShell succeeded, but null mDocShell");
   }
 
   *aDocShell = mDocShell;
   NS_IF_ADDREF(*aDocShell);
 
-  return NS_OK;
+  return rv;
 }
 
 void
 nsFrameLoader::Finalize()
 {
   nsCOMPtr<nsIBaseWindow> base_win(do_QueryInterface(mDocShell));
   if (base_win) {
     base_win->Destroy();
@@ -1335,46 +1337,29 @@ nsFrameLoader::SetOwnerContent(nsIConten
   if (RenderFrameParent* rfp = GetCurrentRemoteFrame()) {
     rfp->OwnerContentChanged(aContent);
   }
 }
 
 bool
 nsFrameLoader::ShouldUseRemoteProcess()
 {
-  // Check for *disabled* multi-process first: environment, prefs, attribute
-  // Then check for *enabled* multi-process pref: attribute, prefs
+  // Check for *disabled* multi-process first: environment, pref
+  // Then check for *enabled* multi-process attribute
   // Default is not-remote.
 
-  if (PR_GetEnv("MOZ_DISABLE_OOP_TABS")) {
-    return false;
-  }
-
-  PRBool remoteDisabled =
-    Preferences::GetBool("dom.ipc.tabs.disabled", PR_FALSE);
-  if (remoteDisabled) {
+  if (PR_GetEnv("MOZ_DISABLE_OOP_TABS") ||
+      Preferences::GetBool("dom.ipc.tabs.disabled", PR_FALSE)) {
     return false;
   }
 
-  static nsIAtom* const *const remoteValues[] = {
-    &nsGkAtoms::_false,
-    &nsGkAtoms::_true,
-    nsnull
-  };
-
-  switch (mOwnerContent->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::Remote,
-                                         remoteValues, eCaseMatters)) {
-  case 0:
-    return false;
-  case 1:
-    return true;
-  }
-
-  PRBool remoteEnabled = Preferences::GetBool("dom.ipc.tabs.enabled", PR_FALSE);
-  return (bool) remoteEnabled;
+  return (bool) mOwnerContent->AttrValueIs(kNameSpaceID_None,
+                                           nsGkAtoms::Remote,
+                                           nsGkAtoms::_true,
+                                           eCaseMatters);
 }
 
 nsresult
 nsFrameLoader::MaybeCreateDocShell()
 {
   if (mDocShell) {
     return NS_OK;
   }
@@ -1671,16 +1656,30 @@ nsFrameLoader::SetRenderMode(PRUint32 aR
     return NS_OK;
   }
 
   mRenderMode = aRenderMode;
   InvalidateFrame(GetPrimaryFrameOfOwningContent());
   return NS_OK;
 }
 
+NS_IMETHODIMP
+nsFrameLoader::GetEventMode(PRUint32* aEventMode)
+{
+  *aEventMode = mEventMode;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsFrameLoader::SetEventMode(PRUint32 aEventMode)
+{
+  mEventMode = aEventMode;
+  return NS_OK;
+}
+
 nsIntSize
 nsFrameLoader::GetSubDocumentSize(const nsIFrame *aIFrame)
 {
   nsSize docSizeAppUnits;
   nsPresContext* presContext = aIFrame->PresContext();
   nsCOMPtr<nsIDOMHTMLFrameElement> frameElem = 
     do_QueryInterface(aIFrame->GetContent());
   if (frameElem) {
@@ -1783,16 +1782,25 @@ nsFrameLoader::ActivateRemoteFrame() {
   if (mRemoteBrowser) {
     mRemoteBrowser->Activate();
     return NS_OK;
   }
   return NS_ERROR_UNEXPECTED;
 }
 
 NS_IMETHODIMP
+nsFrameLoader::DeactivateRemoteFrame() {
+  if (mRemoteBrowser) {
+    mRemoteBrowser->Deactivate();
+    return NS_OK;
+  }
+  return NS_ERROR_UNEXPECTED;
+}
+
+NS_IMETHODIMP
 nsFrameLoader::SendCrossProcessMouseEvent(const nsAString& aType,
                                           float aX,
                                           float aY,
                                           PRInt32 aButton,
                                           PRInt32 aClickCount,
                                           PRInt32 aModifiers,
                                           PRBool aIgnoreRootScrollFrame)
 {
--- a/content/base/src/nsFrameLoader.h
+++ b/content/base/src/nsFrameLoader.h
@@ -337,11 +337,15 @@ private:
   nsCOMPtr<nsIObserver> mChildHost;
   RenderFrameParent* mCurrentRemoteFrame;
   TabParent* mRemoteBrowser;
 
   // See nsIFrameLoader.idl.  Short story, if !(mRenderMode &
   // RENDER_MODE_ASYNC_SCROLL), all the fields below are ignored in
   // favor of what content tells.
   PRUint32 mRenderMode;
+
+  // See nsIFrameLoader.idl. EVENT_MODE_NORMAL_DISPATCH automatically
+  // forwards some input events to out-of-process content.
+  PRUint32 mEventMode;
 };
 
 #endif
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -141,16 +141,17 @@
 
 #include "mozAutoDocUpdate.h"
 
 #include "nsCSSParser.h"
 #include "nsTPtrArray.h"
 #include "prprf.h"
 
 #include "nsSVGFeatures.h"
+#include "nsDOMMemoryReporter.h"
 
 using namespace mozilla::dom;
 namespace css = mozilla::css;
 
 NS_DEFINE_IID(kThisPtrOffsetsSID, NS_THISPTROFFSETS_SID);
 
 PRInt32 nsIContent::sTabFocusModel = eTabFocus_any;
 PRBool nsIContent::sTabFocusModelAppliesToXUL = PR_FALSE;
@@ -1325,17 +1326,17 @@ nsIContent::HasIndependentSelection()
   nsIFrame* frame = GetPrimaryFrame();
   return (frame && frame->GetStateBits() & NS_FRAME_INDEPENDENT_SELECTION);
 }
 
 nsIContent*
 nsIContent::GetEditingHost()
 {
   // If this isn't editable, return NULL.
-  NS_ENSURE_TRUE(HasFlag(NODE_IS_EDITABLE), nsnull);
+  NS_ENSURE_TRUE(IsEditableInternal(), nsnull);
 
   nsIDocument* doc = GetCurrentDoc();
   NS_ENSURE_TRUE(doc, nsnull);
   // If this is in designMode, we should return <body>
   if (doc->HasFlag(NODE_IS_EDITABLE)) {
     return doc->GetBodyElement();
   }
 
@@ -5367,8 +5368,20 @@ nsNSElementTearoff::MozMatchesSelector(c
 {
   NS_PRECONDITION(aReturn, "Null out param?");
 
   nsresult rv;
   *aReturn = mContent->MozMatchesSelector(aSelector, &rv);
 
   return rv;
 }
+
+PRInt64
+nsGenericElement::SizeOf() const
+{
+  PRInt64 size = MemoryReporter::GetBasicSize<nsGenericElement, Element>(this);
+
+  size -= sizeof(mAttrsAndChildren);
+  size += mAttrsAndChildren.SizeOf();
+
+  return size;
+}
+
--- a/content/base/src/nsGenericElement.h
+++ b/content/base/src/nsGenericElement.h
@@ -235,16 +235,18 @@ class nsGenericElement : public mozilla:
 public:
   nsGenericElement(already_AddRefed<nsINodeInfo> aNodeInfo);
   virtual ~nsGenericElement();
 
   friend class nsNSElementTearoff;
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
 
+  NS_DECL_DOM_MEMORY_REPORTER_SIZEOF
+
   /**
    * Called during QueryInterface to give the binding manager a chance to
    * get an interface for this element.
    */
   nsresult PostQueryInterface(REFNSIID aIID, void** aInstancePtr);
 
   // nsINode interface methods
   virtual PRUint32 GetChildCount() const;
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -251,16 +251,17 @@ GK_ATOM(control, "control")
 #ifdef MOZ_MEDIA
 GK_ATOM(controls, "controls")
 #endif
 GK_ATOM(coords, "coords")
 GK_ATOM(copy, "copy")
 GK_ATOM(copyOf, "copy-of")
 GK_ATOM(count, "count")
 GK_ATOM(crop, "crop")
+GK_ATOM(crossOrigin, "crossOrigin")
 GK_ATOM(curpos, "curpos")
 GK_ATOM(current, "current")
 GK_ATOM(currentloop, "currentloop")
 GK_ATOM(cycler, "cycler")
 GK_ATOM(data, "data")
 GK_ATOM(datalist, "datalist")
 GK_ATOM(dataType, "data-type")
 GK_ATOM(dateTime, "date-time")
--- a/content/base/src/nsImageLoadingContent.cpp
+++ b/content/base/src/nsImageLoadingContent.cpp
@@ -714,23 +714,31 @@ nsImageLoadingContent::LoadImage(nsIURI*
   nsContentUtils::CanLoadImage(aNewURI, this, aDocument,
                                aDocument->NodePrincipal(), &cpDecision);
   if (!NS_CP_ACCEPTED(cpDecision)) {
     FireEvent(NS_LITERAL_STRING("error"));
     SetBlockedRequest(aNewURI, cpDecision);
     return NS_OK;
   }
 
+  nsLoadFlags loadFlags = aLoadFlags;
+  PRInt32 corsmode = GetCORSMode();
+  if (corsmode == nsImageLoadingContent::CORS_ANONYMOUS) {
+    loadFlags |= imgILoader::LOAD_CORS_ANONYMOUS;
+  } else if (corsmode == nsImageLoadingContent::CORS_USE_CREDENTIALS) {
+    loadFlags |= imgILoader::LOAD_CORS_USE_CREDENTIALS;
+  }
+
   // Not blocked. Do the load.
   nsCOMPtr<imgIRequest>& req = PrepareNextRequest();
   nsresult rv;
   rv = nsContentUtils::LoadImage(aNewURI, aDocument,
                                  aDocument->NodePrincipal(),
                                  aDocument->GetDocumentURI(),
-                                 this, aLoadFlags,
+                                 this, loadFlags,
                                  getter_AddRefs(req));
   if (NS_SUCCEEDED(rv)) {
     TrackImage(req);
   } else {
     // If we don't have a current URI, we might as well store this URI so people
     // know what we tried (and failed) to load.
     if (!mCurrentRequest)
       mCurrentURI = aNewURI;
@@ -1081,8 +1089,13 @@ nsImageLoadingContent::CreateStaticImage
   aDest->mStateChangerDepth = mStateChangerDepth;
   aDest->mIsImageStateForced = mIsImageStateForced;
   aDest->mLoading = mLoading;
   aDest->mBroken = mBroken;
   aDest->mUserDisabled = mUserDisabled;
   aDest->mSuppressed = mSuppressed;
 }
 
+nsImageLoadingContent::CORSMode
+nsImageLoadingContent::GetCORSMode()
+{
+  return CORS_NONE;
+}
--- a/content/base/src/nsImageLoadingContent.h
+++ b/content/base/src/nsImageLoadingContent.h
@@ -64,16 +64,35 @@ class nsImageLoadingContent : public nsI
 public:
   nsImageLoadingContent();
   virtual ~nsImageLoadingContent();
 
   NS_DECL_IMGICONTAINEROBSERVER
   NS_DECL_IMGIDECODEROBSERVER
   NS_DECL_NSIIMAGELOADINGCONTENT
 
+  enum CORSMode {
+    /**
+     * The default of not using CORS to validate cross-origin loads.
+     */
+    CORS_NONE,
+
+    /**
+     * Validate cross-site loads using CORS, but do not send any credentials
+     * (cookies, HTTP auth logins, etc) along with the request.
+     */
+    CORS_ANONYMOUS,
+
+    /**
+     * Validate cross-site loads using CORS, and send credentials such as cookies
+     * and HTTP auth logins along with the request.
+     */
+    CORS_USE_CREDENTIALS
+  };
+
 protected:
   /**
    * LoadImage is called by subclasses when the appropriate
    * attributes (eg 'src' for <img> tags) change.  The string passed
    * in is the new uri string; this consolidates the code for getting
    * the charset, constructing URI objects, and any other incidentals
    * into this superclass.   
    *
@@ -154,16 +173,22 @@ protected:
   void ClearBrokenState() { mBroken = PR_FALSE; }
 
   PRBool LoadingEnabled() { return mLoadingEnabled; }
 
   // Sets blocking state only if the desired state is different from the
   // current one. See the comment for mBlockingOnload for more information.
   void SetBlockingOnload(PRBool aBlocking);
 
+  /**
+   * Returns the CORS mode that will be used for all future image loads. The
+   * default implementation returns CORS_NONE unconditionally.
+   */
+  virtual CORSMode GetCORSMode();
+
 private:
   /**
    * Struct used to manage the image observers.
    */
   struct ImageObserver {
     ImageObserver(imgIDecoderObserver* aObserver) :
       mObserver(aObserver),
       mNext(nsnull)
--- a/content/base/src/nsNodeUtils.cpp
+++ b/content/base/src/nsNodeUtils.cpp
@@ -510,30 +510,28 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
     nodeInfo = newNodeInfo;
   }
 
   nsGenericElement *elem = aNode->IsElement() ?
                            static_cast<nsGenericElement*>(aNode) :
                            nsnull;
 
   nsCOMPtr<nsINode> clone;
-  PRBool isDeepDocumentClone = PR_FALSE;
   if (aClone) {
     rv = aNode->Clone(nodeInfo, getter_AddRefs(clone));
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (aParent) {
       // If we're cloning we need to insert the cloned children into the cloned
       // parent.
       rv = aParent->AppendChildTo(static_cast<nsIContent*>(clone.get()),
                                   PR_FALSE);
       NS_ENSURE_SUCCESS(rv, rv);
     }
     else if (aDeep && clone->IsNodeOfType(nsINode::eDOCUMENT)) {
-      isDeepDocumentClone = PR_TRUE;
       // After cloning the document itself, we want to clone the children into
       // the cloned document (somewhat like cloning and importing them into the
       // cloned document).
       nodeInfoManager = clone->mNodeInfo->NodeInfoManager();
     }
   }
   else if (nodeInfoManager) {
     nsIDocument* oldDoc = aNode->GetOwnerDoc();
--- a/content/base/src/nsScriptLoader.cpp
+++ b/content/base/src/nsScriptLoader.cpp
@@ -1309,21 +1309,22 @@ nsScriptLoader::ParsingComplete(PRBool a
   // onload and all.
   ProcessPendingRequests();
 }
 
 void
 nsScriptLoader::PreloadURI(nsIURI *aURI, const nsAString &aCharset,
                            const nsAString &aType)
 {
-  nsRefPtr<nsScriptLoadRequest> request = new nsScriptLoadRequest(nsnull, 0);
-  if (!request) {
+  // Check to see if scripts has been turned off.
+  if (!mEnabled || !mDocument->IsScriptEnabled()) {
     return;
   }
 
+  nsRefPtr<nsScriptLoadRequest> request = new nsScriptLoadRequest(nsnull, 0);
   request->mURI = aURI;
   request->mIsInline = PR_FALSE;
   request->mLoading = PR_TRUE;
   nsresult rv = StartLoad(request, aType);
   if (NS_FAILED(rv)) {
     return;
   }
 
--- a/content/base/src/nsStyledElement.cpp
+++ b/content/base/src/nsStyledElement.cpp
@@ -48,16 +48,17 @@
 #include "nsServiceManagerUtils.h"
 #include "nsIDocument.h"
 #include "mozilla/css/StyleRule.h"
 #include "nsCSSParser.h"
 #include "mozilla/css/Loader.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsXULElement.h"
 #include "nsIDOMSVGStylable.h"
+#include "nsContentUtils.h"
 
 namespace css = mozilla::css;
 
 //----------------------------------------------------------------------
 // nsIContent methods
 
 nsIAtom*
 nsStyledElementNotElementCSSInlineStyle::GetClassAttributeName() const
--- a/content/base/src/nsWebSocket.cpp
+++ b/content/base/src/nsWebSocket.cpp
@@ -1346,16 +1346,28 @@ nsWebSocket::Init(nsIPrincipal* aPrincip
 
     mWindowID = nsJSUtils::GetCurrentlyRunningCodeWindowID(cx);
   }
 
   // parses the url
   rv = ParseURL(PromiseFlatString(aURL));
   NS_ENSURE_SUCCESS(rv, rv);
 
+  // Don't allow https:// to open ws://
+  nsCOMPtr<nsIURI> originURI;
+  PRBool originHTTPS;
+  if (!mSecure && 
+      !Preferences::GetBool("network.websocket.allowInsecureFromHTTPS",
+                            PR_FALSE) &&
+      NS_SUCCEEDED(NS_NewURI(getter_AddRefs(originURI), mUTF16Origin)) &&
+      NS_SUCCEEDED(originURI->SchemeIs("https", &originHTTPS)) &&
+      originHTTPS) {
+    return NS_ERROR_DOM_SECURITY_ERR;
+  }
+
   // sets the protocol
   if (!aProtocol.IsEmpty()) {
     rv = SetProtocol(PromiseFlatString(aProtocol));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // the constructor should throw a SYNTAX_ERROR only if it fails to parse the
   // url parameter, so we don't care about the EstablishConnection result.
--- a/content/base/src/nsXMLHttpRequest.cpp
+++ b/content/base/src/nsXMLHttpRequest.cpp
@@ -1595,51 +1595,32 @@ nsXMLHttpRequest::StreamReaderFunc(nsIIn
 }
 
 void nsXMLHttpRequest::CreateResponseBlob(nsIRequest *request)
 {
   nsCOMPtr<nsIFile> file;
   nsCOMPtr<nsICachingChannel> cc(do_QueryInterface(request));
   if (cc) {
     cc->GetCacheFile(getter_AddRefs(file));
-    if (!file) {
-      // cacheAsFile returns false if caching is inhibited
-      PRBool cacheAsFile = PR_FALSE;
-      if (NS_SUCCEEDED(cc->GetCacheAsFile(&cacheAsFile)) && cacheAsFile) {
-        
-      }
-    }
   } else {
     nsCOMPtr<nsIFileChannel> fc = do_QueryInterface(request);
     if (fc) {
       fc->GetFile(getter_AddRefs(file));
     }
   }
   if (file) {
     nsCAutoString contentType;
     mChannel->GetContentType(contentType);
     nsCOMPtr<nsISupports> cacheToken;
     if (cc) {
       cc->GetCacheToken(getter_AddRefs(cacheToken));
     }
 
-    NS_ConvertASCIItoUTF16 wideContentType(contentType);
-
-    nsCOMPtr<nsIDOMBlob> blob =
-      new nsDOMFile(file, wideContentType, cacheToken);
-
-    // XXXkhuey this is a complete hack ... but we need to get 6 out the door
-    // The response blob here should not be a File object, it should only
-    // be a Blob.  Unfortunately, because nsDOMFile has grown through
-    // accretion over the years and is in dangerous need of a refactoring,
-    // slicing it is the easiest way to get there ...
-    PRUint64 size = 0;
-    blob->GetSize(&size);
-    blob->MozSlice(0, size, wideContentType, 2, getter_AddRefs(mResponseBlob));
-    
+    mResponseBlob =
+      new nsDOMFileFile(file, NS_ConvertASCIItoUTF16(contentType), cacheToken);
     mResponseBody.Truncate();
     mResponseBodyUnicode.SetIsVoid(PR_TRUE);
   }
 }
 
 /* void onDataAvailable (in nsIRequest request, in nsISupports ctxt, in nsIInputStream inStr, in unsigned long sourceOffset, in unsigned long count); */
 NS_IMETHODIMP
 nsXMLHttpRequest::OnDataAvailable(nsIRequest *request, nsISupports *ctxt, nsIInputStream *inStr, PRUint32 sourceOffset, PRUint32 count)
@@ -1901,29 +1882,19 @@ nsXMLHttpRequest::OnStopRequest(nsIReque
       mChannel->GetContentType(contentType);
       // XXX We should change mResponseBody to be a raw malloc'ed buffer
       //     to avoid copying the data.
       PRUint32 blobLen = mResponseBody.Length();
       void *blobData = PR_Malloc(blobLen);
       if (blobData) {
         memcpy(blobData, mResponseBody.BeginReading(), blobLen);
 
-        NS_ConvertASCIItoUTF16 wideContentType(contentType);
-        nsCOMPtr<nsIDOMBlob> blob =
-          new nsDOMMemoryFile(blobData, blobLen, EmptyString(),
-                              wideContentType);
-
-        // XXXkhuey this is a complete hack ... but we need to get 6 out the door
-        // The response blob here should not be a File object, it should only
-        // be a Blob.  Unfortunately, because nsDOMFile has grown through
-        // accretion over the years and is in dangerous need of a refactoring,
-        // slicing it is the easiest way to get there ...
-        blob->MozSlice(0, blobLen, wideContentType,
-                       2, getter_AddRefs(mResponseBlob));
-
+        mResponseBlob =
+          new nsDOMMemoryFile(blobData, blobLen,
+                              NS_ConvertASCIItoUTF16(contentType));
         mResponseBody.Truncate();
       }
       NS_ASSERTION(mResponseBodyUnicode.IsVoid(),
                    "mResponseBodyUnicode should be empty");
     }
   }
 
   channel->SetNotificationCallbacks(nsnull);
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -497,16 +497,17 @@ include $(topsrcdir)/config/rules.mk
 		forRemoval.resource^headers^ \
 		accesscontrol.resource \
 		accesscontrol.resource^headers^ \
 		invalid_accesscontrol.resource \
 		invalid_accesscontrol.resource^headers^ \
 		somedatas.resource \
 		somedatas.resource^headers^ \
 		delayedServerEvents.sjs \
+		test_bug664916.html \
 		test_bug666604.html \
 		$(NULL)
 
 _CHROME_FILES =	\
 		test_bug357450.js \
 		$(NULL)
 
 # This test fails on the Mac for some reason
--- a/content/base/test/chrome/test_fileconstructor.xul
+++ b/content/base/test/chrome/test_fileconstructor.xul
@@ -59,15 +59,24 @@ try {
 } catch (e) {
   ok(true, "Botched file constructor attempts throw and do not crash.");
 }
 
 try {
   var nonexistentfile = new File("i/sure/hope/this/does/not/exist/anywhere.txt");
   ok(false, "This should never be reached!");
 } catch (e) {
-  ok(true, "Attempt to construct a non-existent file should fail.")
+  ok(true, "Attempt to construct a non-existent file should fail.");
 }
 
+try {
+  var dir = Components.classes["@mozilla.org/file/directory_service;1"]
+                      .getService(Components.interfaces.nsIProperties)
+                      .get("CurWorkD", Components.interfaces.nsIFile);
+  var dirfile = new File(dir);
+  ok(false, "This should never be reached!");
+} catch (e) {
+  ok(true, "Attempt to construct a file from a directory should fail.");
+}
 ]]>
 </script>
 
 </window>
--- a/content/base/test/fileutils.js
+++ b/content/base/test/fileutils.js
@@ -215,41 +215,48 @@ function testSlice(file, size, type, con
   slice = file.mozSlice(0, 5432, "foo/bar");
   is(slice.type, "foo/bar", fileType + " sized slice foo/bar type");
   
   is(slice.mozSlice(0, 10).type, "", fileType + " slice-slice type");
   is(slice.mozSlice(0, 10).size, 10, fileType + " slice-slice size");
   is(slice.mozSlice(0, 10, "hello/world").type, "hello/world", fileType + " slice-slice hello/world type");
   is(slice.mozSlice(0, 10, "hello/world").size, 10, fileType + " slice-slice hello/world size");
 
+  // Start, end, expected size
   var indexes = [[0, size, size],
                  [0, 1234, 1234],
                  [size-500, size, 500],
                  [size-500, size+500, 500],
                  [size+500, size+1500, 0],
                  [0, 0, 0],
                  [1000, 1000, 0],
                  [size, size, 0],
+                 [undefined, undefined, size],
                  [0, undefined, size],
                  [100, undefined, size-100],
                  [-100, undefined, 100],
                  [100, -100, size-200],
                  [-size-100, undefined, size],
                  [-2*size-100, 500, 500],
                  [0, -size-100, 0],
                  [100, -size-100, 0],
                  [50, -size+100, 50],
                  [0, 33000, 33000],
                  [1000, 34000, 33000],
                 ];
   
   for (var i = 0; i < indexes.length; ++i) {
     var sliceContents;
     var testName;
-    if (indexes[i][1] == undefined) {
+    if (indexes[i][0] == undefined) {
+      slice = file.mozSlice();
+      sliceContents = contents.slice();
+      testName = fileType + " slice()";
+    }
+    else if (indexes[i][1] == undefined) {
       slice = file.mozSlice(indexes[i][0]);
       sliceContents = contents.slice(indexes[i][0]);
       testName = fileType + " slice(" + indexes[i][0] + ")";
     }
     else {
       slice = file.mozSlice(indexes[i][0], indexes[i][1]);
       sliceContents = contents.slice(indexes[i][0], indexes[i][1]);
       testName = fileType + " slice(" + indexes[i][0] + ", " + indexes[i][1] + ")";
--- a/content/base/test/test_blobbuilder.html
+++ b/content/base/test/test_blobbuilder.html
@@ -23,73 +23,109 @@ https://bugzilla.mozilla.org/show_bug.cg
 window.BlobBuilder = window.MozBlobBuilder;
 
 /** Test for Bug 648997 **/
 var blobBuilder = BlobBuilder();
 ok(blobBuilder, "BlobBuilder should exist");
 
 ok(blobBuilder.append, "BlobBuilder should have an append method");
 ok(blobBuilder.getBlob, "BlobBuilder should have a getBlob method");
+ok(blobBuilder.getFile, "BlobBuilder should have a getFile method");
 
 try {
 blobBuilder.append();
 ok(false, "NOT REACHED");
 } catch(e) {
 ok(true, "an empty argument to append should throw");
 }
 
 blobBuilder.append("squiggle");
 let blob1 = blobBuilder.getBlob();
+ok(blob1 instanceof Blob, "getBlob should produce Blobs");
+ok(!(blob1 instanceof File), "getBlob should not produce Files");
+is(blob1.type, "", "getBlob with no argument should return Blob with empty type");
+is(blob1.size, 8, "getBlob should return Blob with correct size");
+
 blobBuilder.append("ohai");
-let blob2 = blobBuilder.getBlob();
+let blob2 = blobBuilder.getFile("thefilename");
+ok(blob2 instanceof Blob, "getFile should produce Blobs");
+ok(blob2 instanceof File, "getFile should produce Files");
+is(blob2.name, "thefilename", "getFile should produces Files with correct name");
+is(blob2.type, "", "getFile with no second argument should return File with empty type");
+is(blob2.size, 4, "getFile should return Blob with correct size");
+
+blobBuilder.append("steak");
+let blob3 = blobBuilder.getBlob("content/type");
+ok(blob3 instanceof Blob, "getBlob should produce Blobs");
+ok(!(blob3 instanceof File), "getBlob should not produce Files");
+is(blob3.type, "content/type", "getBlob with no argument should return Blob with empty type");
+is(blob3.size, 5, "getBlob should return Blob with correct size");
+
+blobBuilder.append("apples");
+let blob4 = blobBuilder.getFile("the other filename", "text/plain");
+ok(blob4 instanceof Blob, "getFile should produce Blobs");
+ok(blob4 instanceof File, "getFile should produce Files");
+is(blob4.name, "the other filename", "getFile should produces Files with correct name");
+is(blob4.type, "text/plain", "getFile with second argument should return File with correct type");
+is(blob4.size, 6, "getFile should return Blob with correct size");
+
+blobBuilder.append("boletes");
+let blob5 = blobBuilder.getFile("");
+ok(blob5 instanceof Blob, "getFile should produce Blobs");
+ok(blob5 instanceof File, "getFile should produce Files");
+is(blob5.name, "", "getFile with empty name should produces Files with empty name");
+is(blob5.type, "", "getFile with no second argument should return File with correct type");
+is(blob5.size, 7, "getFile should return Blob with correct size");
+testFile(blob5, "boletes", "Test empty-named File from BlobBuilder.getFile");
+
 
 let aB = new ArrayBuffer(16);
 var int8View = new Int8Array(aB);
 for (var i = 0; i < 16; i++) {
   int8View[i] = i+65;
 }
 
 let testData = 
  [
     // Test 3 strings
     [["foo", "bar", "baz"], [{start: 0, length: 9, contents: "foobarbaz"},
                              {start: 0, length: 3, contents: "foo"},
                              {start: 3, length:6, contents:  "barbaz"},
                              {start: 6, length: 3, contents:  "baz"},
-                             {start: 6, length: 6, elength: 3, contents: "baz"},
+                             {start: 6, length: 6, contents: "baz"},
                              {start: 0, length: 9, contents:  "foobarbaz"},
-                             {start: 0, length: 11, elength: 9, contents: "foobarbaz"},
-                             {start: 10, length: 5, elength: 0, contents: ""}]],
+                             {start: 0, length: 11, contents: "foobarbaz"},
+                             {start: 10, length: 5, contents: ""}]],
     // Test string, Blob, string
     [["foo", blob1, "baz"], [{start: 0, length: 3, contents:  "foo"},
                              {start: 3, length: 8, contents:  "squiggle"},
                              {start: 2, length: 2, contents:  "os"},
                              {start: 10, length: 2, contents: "eb"}]],
     // Test blob, string, blob
     [[blob1, "foo", blob1], [{start: 0, length: 8, contents:  "squiggle"},
                              {start: 7, length: 2, contents:  "ef"},
                              {start: 10, length: 2, contents: "os"},
                              {start: 1, length: 3, contents:  "qui"},
                              {start: 12, length: 3, contents: "qui"},
-                             {start: 40, length: 20, elength: 0, contents: ""}]],
+                             {start: 40, length: 20, contents: ""}]],
     // Test blobs all the way down
     [[blob2, blob1, blob2], [{start: 0, length: 4, contents:  "ohai"},
                              {start: 4, length: 8, contents:  "squiggle"},
                              {start: 12, length: 4, contents: "ohai"},
                              {start: 1, length: 2, contents:  "ha"},
                              {start: 5, length: 4, contents:  "quig"}]],
     // Test an array buffer
     [[aB, blob1, "foo"],    [{start: 0, length: 8, contents:  "ABCDEFGH"},
                              {start: 8, length:10, contents:  "IJKLMNOPsq"},
                              {start: 17, length: 3, contents: "qui"},
                              {start: 4, length: 8, contents:  "EFGHIJKL"}]],
     // Test type coercion of a number
     [[3, aB, "foo"],        [{start: 0, length: 8, contents:  "3ABCDEFG"},
                              {start: 8, length:10, contents:  "HIJKLMNOPf"},
-                             {start: 17, length: 4, elength: 3, contents: "foo"},
+                             {start: 17, length: 4, contents: "foo"},
                              {start: 4, length: 8, contents:  "DEFGHIJK"}]]
  ];
 
 let testCounter = 0;
 
 function doTest(data) {
   testCounter++;
 
@@ -105,27 +141,26 @@ function doTest(data) {
 	  blob.expando = bb; // Do we leak?
     }
 
     blobs.forEach(doAppend);
     ok(true, "Test " + testCounter + " appended all successfully");
     let blob = bb.getBlob();
     ok(blob, "Test " + testCounter + " got blob");
     ok(blob instanceof Blob, "Test " + testCounter + " blob is a Blob");
-    //ok(!(blob instanceof File), "Test " + testCounter + " blob is not a File");
+    ok(!(blob instanceof File), "Test " + testCounter + " blob is not a File");
 
     let slice = blob.mozSlice(test.start, test.start + test.length);
     ok(slice, "Test " + testCounter + " got slice");
     ok(slice instanceof Blob, "Test " + testCounter + " slice is a Blob");
-    //ok(!(slice instanceof File), "Test " + testCounter + " slice is not a File");
-    is(slice.size,"elength" in test ? test.elength : test.length,
+    ok(!(slice instanceof File), "Test " + testCounter + " slice is not a File");
+    is(slice.size, test.contents.length,
        "Test " + testCounter + " slice is correct size");
 
-    testFile(slice, test.contents, "Test " + testCounter,
-             "elength" in test ? test.elength : test.length);
+    testFile(slice, test.contents, "Test " + testCounter);
   }
   tests.forEach(runTest);
   SpecialPowers.gc();
 }
 
 SimpleTest.waitForExplicitFinish();
 testData.forEach(doTest);
 
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug664916.html
@@ -0,0 +1,40 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=664916
+-->
+<head>
+  <title>Test for Bug 664916</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=664916">Mozilla Bug 664916</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+
+/** Test for Bug 664916 **/
+var div = document.createElement("div");
+var textNode = document.createTextNode("x")
+var tagNameGetter = div.__lookupGetter__("tagName");
+
+var tagName = "";
+try {
+  tagName = tagNameGetter.call(textNode);
+  ok(false, "Should throw when calling tagname getter on text node");
+} catch(e) {
+  ok(true, "Should throw when calling tagname getter on text node");
+}
+is(tagName, "", "Should not have changed tagName yet");
+tagName = tagNameGetter.call(div);
+is(tagName, "DIV", "Should get the right tag name");
+</script>
+</pre>
+</body>
+</html>
--- a/content/base/test/test_bug666604.html
+++ b/content/base/test/test_bug666604.html
@@ -18,16 +18,28 @@ https://bugzilla.mozilla.org/show_bug.cg
 <a href="javascript:activationListener()" id="testlink">test</a>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 666604 **/
 
 SimpleTest.waitForExplicitFinish();
 
+function hitEventLoop(times, next)
+{
+  if (times == 0) {
+     next();
+     return;
+   }
+ 
+  SimpleTest.executeSoon(function() {
+    hitEventLoop(times - 1, next);
+  });
+}
+
 var activationListener;
 
 function dispatchClick(target, ctrl) {
   var e = document.createEvent("MouseEvent");
   e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, 
                    ctrl, false, false, false, 0, null);
   target.dispatchEvent(e);
 }
@@ -66,27 +78,27 @@ function test2() {
 
 function test3() {
   activationListener =
   function() {
     ok(false, "Untrusted click+ctrl should not activate a link");
     test4();
   }
   dispatchClick(testlink, true);
-  setTimeout(test4, 1000);
+  hitEventLoop(10, test4);
 }
 
 function test4() {
   activationListener =
     function() {
       ok(false, "Untrusted return keypress+ctrl should not activate a link");
       test5();
     }
   dispatchReturn(testlink, true);
-  setTimeout(test5, 1000);
+  hitEventLoop(10, test5);
 }
 
 function test5() {
   activationListener =
     function() {
       ok(true, "click() should activate a link");
       test6();
     }
@@ -97,28 +109,46 @@ function test6() {
   activationListener =
     function() {
       ok(true, "Untrusted DOMActivate should activate a link");
       test7();
     }
   dispatchDOMActivate(testlink);
 }
 
+var oldPref;
 function test7() {
+  oldPref = SpecialPowers.getBoolPref("dom.disable_open_during_load");
+  SpecialPowers.setBoolPref("dom.disable_open_during_load", false);
   testlink.href = "javascript:opener.activationListener(); window.close();";
   testlink.target = "_blank";
   activationListener =
     function() {
       ok(true, "Click() should activate a link");
-      setTimeout(test9, 0);
+      setTimeout(test8, 0);
     }
   testlink.click();
 }
 
+function test8() {
+  SpecialPowers.setBoolPref("dom.disable_open_during_load", true);
+  testlink.href = "javascript:opener.activationListener(); window.close();";
+  testlink.target = "_blank";
+  activationListener =
+    function() {
+      ok(false, "Click() should not activate a link");
+      setTimeout(test9, 0);
+    }
+  testlink.click();  
+  hitEventLoop(10, test9);
+} 
+
+
 function test9() {
+  SpecialPowers.setBoolPref("dom.disable_open_during_load", oldPref);
   SimpleTest.finish();
 }
 
 addLoadEvent(test1);
 
 </script>
 </pre>
 </body>
--- a/content/canvas/public/nsICanvasRenderingContextInternal.h
+++ b/content/canvas/public/nsICanvasRenderingContextInternal.h
@@ -117,16 +117,21 @@ public:
   NS_IMETHOD Reset() = 0;
 
   // Return the CanvasLayer for this context, creating
   // one for the given layer manager if not available.
   virtual already_AddRefed<CanvasLayer> GetCanvasLayer(nsDisplayListBuilder* aBuilder,
                                                        CanvasLayer *aOldLayer,
                                                        LayerManager *aManager) = 0;
 
+  // Return true if the canvas should be forced to be "inactive" to ensure
+  // it can be drawn to the screen even if it's too large to be blitted by
+  // an accelerated CanvasLayer.
+  virtual PRBool ShouldForceInactiveLayer(LayerManager *aManager) { return PR_FALSE; }
+
   virtual void MarkContextClean() = 0;
 
   // Redraw the dirty rectangle of this canvas.
   NS_IMETHOD Redraw(const gfxRect &dirty) = 0;
 
   // Passes a generic nsIPropertyBag options argument, along with the
   // previous one, if any.  Optional.
   NS_IMETHOD SetContextOptions(nsIPropertyBag *aNewOptions) { return NS_OK; }
--- a/content/canvas/src/WebGLContext.cpp
+++ b/content/canvas/src/WebGLContext.cpp
@@ -35,17 +35,16 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "WebGLContext.h"
 
 #include "nsIConsoleService.h"
-#include "nsIPrefService.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIClassInfoImpl.h"
 #include "nsContentUtils.h"
 #include "nsIXPConnect.h"
 #include "nsDOMError.h"
 #include "nsIGfxInfo.h"
 
 #include "nsIPropertyBag.h"
@@ -63,20 +62,150 @@
 #include "GLContextProvider.h"
 
 #include "gfxCrashReporterUtils.h"
 
 #include "nsSVGEffects.h"
 
 #include "prenv.h"
 
+#include "mozilla/Preferences.h"
+
 using namespace mozilla;
 using namespace mozilla::gl;
 using namespace mozilla::layers;
 
+WebGLMemoryReporter* WebGLMemoryReporter::sUniqueInstance = nsnull;
+
+NS_MEMORY_REPORTER_IMPLEMENT(WebGLTextureMemoryUsed,
+                             "webgl-texture-memory",
+                             KIND_OTHER,
+                             UNITS_BYTES,
+                             WebGLMemoryReporter::GetTextureMemoryUsed,
+                             "Memory used by WebGL textures. The OpenGL implementation is free to store these textures in either video memory or main memory. This measurement is only a lower bound, actual memory usage may be higher for example if the storage is strided.")
+
+NS_MEMORY_REPORTER_IMPLEMENT(WebGLTextureCount,
+                             "webgl-texture-count",
+                             KIND_OTHER,
+                             UNITS_COUNT,
+                             WebGLMemoryReporter::GetTextureCount,
+                             "Number of WebGL textures.")
+
+NS_MEMORY_REPORTER_IMPLEMENT(WebGLBufferMemoryUsed,
+                             "webgl-buffer-memory",
+                             KIND_OTHER,
+                             UNITS_BYTES,
+                             WebGLMemoryReporter::GetBufferMemoryUsed,
+                             "Memory used by WebGL buffers. The OpenGL implementation is free to store these buffers in either video memory or main memory. This measurement is only a lower bound, actual memory usage may be higher for example if the storage is strided.")
+
+NS_MEMORY_REPORTER_IMPLEMENT(WebGLBufferCacheMemoryUsed,
+                             "webgl-buffer-cache-memory",
+                             KIND_HEAP,
+                             UNITS_BYTES,
+                             WebGLMemoryReporter::GetBufferCacheMemoryUsed,
+                             "Memory used by WebGL buffer caches. The WebGL implementation caches the contents of element array buffers only. This adds up with the webgl-buffer-memory value, but contrary to it, this one represents bytes on the heap, not managed by OpenGL.")
+
+NS_MEMORY_REPORTER_IMPLEMENT(WebGLBufferCount,
+                             "webgl-buffer-count",
+                             KIND_OTHER,
+                             UNITS_COUNT,
+                             WebGLMemoryReporter::GetBufferCount,
+                             "Number of WebGL buffers.")
+
+NS_MEMORY_REPORTER_IMPLEMENT(WebGLRenderbufferMemoryUsed,
+                             "webgl-renderbuffer-memory",
+                             KIND_OTHER,
+                             UNITS_BYTES,
+                             WebGLMemoryReporter::GetRenderbufferMemoryUsed,
+                             "Memory used by WebGL renderbuffers. The OpenGL implementation is free to store these renderbuffers in either video memory or main memory. This measurement is only a lower bound, actual memory usage may be higher for example if the storage is strided.")
+
+NS_MEMORY_REPORTER_IMPLEMENT(WebGLRenderbufferCount,
+                             "webgl-renderbuffer-count",
+                             KIND_OTHER,
+                             UNITS_COUNT,
+                             WebGLMemoryReporter::GetRenderbufferCount,
+                             "Number of WebGL renderbuffers.")
+
+NS_MEMORY_REPORTER_IMPLEMENT(WebGLShaderSourcesSize,
+                             "webgl-shader-sources-size",
+                             KIND_HEAP,
+                             UNITS_BYTES,
+                             WebGLMemoryReporter::GetShaderSourcesSize,
+                             "Combined size of WebGL shader ASCII sources, cached on the heap. This should always be at most a few kilobytes, or dozen kilobytes for very shader-intensive WebGL demos.")
+
+NS_MEMORY_REPORTER_IMPLEMENT(WebGLShaderTranslationLogsSize,
+                             "webgl-shader-translationlogs-size",
+                             KIND_HEAP,
+                             UNITS_BYTES,
+                             WebGLMemoryReporter::GetShaderTranslationLogsSize,
+                             "Combined size of WebGL shader ASCII translation logs, cached on the heap.")
+
+NS_MEMORY_REPORTER_IMPLEMENT(WebGLShaderCount,
+                             "webgl-shader-count",
+                             KIND_OTHER,
+                             UNITS_COUNT,
+                             WebGLMemoryReporter::GetShaderCount,
+                             "Number of WebGL shaders.")
+
+NS_MEMORY_REPORTER_IMPLEMENT(WebGLContextCount,
+                             "webgl-context-count",
+                             KIND_OTHER,
+                             UNITS_COUNT,
+                             WebGLMemoryReporter::GetContextCount,
+                             "Number of WebGL contexts.")
+
+WebGLMemoryReporter* WebGLMemoryReporter::UniqueInstance()
+{
+    if (!sUniqueInstance) {
+        sUniqueInstance = new WebGLMemoryReporter;
+    }
+    return sUniqueInstance;
+}
+
+WebGLMemoryReporter::WebGLMemoryReporter()
+    : mTextureMemoryUsageReporter(new NS_MEMORY_REPORTER_NAME(WebGLTextureMemoryUsed))
+    , mTextureCountReporter(new NS_MEMORY_REPORTER_NAME(WebGLTextureCount))
+    , mBufferMemoryUsageReporter(new NS_MEMORY_REPORTER_NAME(WebGLBufferMemoryUsed))
+    , mBufferCacheMemoryUsageReporter(new NS_MEMORY_REPORTER_NAME(WebGLBufferCacheMemoryUsed))
+    , mBufferCountReporter(new NS_MEMORY_REPORTER_NAME(WebGLBufferCount))
+    , mRenderbufferMemoryUsageReporter(new NS_MEMORY_REPORTER_NAME(WebGLRenderbufferMemoryUsed))
+    , mRenderbufferCountReporter(new NS_MEMORY_REPORTER_NAME(WebGLRenderbufferCount))
+    , mShaderSourcesSizeReporter(new NS_MEMORY_REPORTER_NAME(WebGLShaderSourcesSize))
+    , mShaderTranslationLogsSizeReporter(new NS_MEMORY_REPORTER_NAME(WebGLShaderTranslationLogsSize))
+    , mShaderCountReporter(new NS_MEMORY_REPORTER_NAME(WebGLShaderCount))
+    , mContextCountReporter(new NS_MEMORY_REPORTER_NAME(WebGLContextCount))
+{
+    NS_RegisterMemoryReporter(mTextureMemoryUsageReporter);
+    NS_RegisterMemoryReporter(mTextureCountReporter);
+    NS_RegisterMemoryReporter(mBufferMemoryUsageReporter);
+    NS_RegisterMemoryReporter(mBufferCacheMemoryUsageReporter);    
+    NS_RegisterMemoryReporter(mBufferCountReporter);
+    NS_RegisterMemoryReporter(mRenderbufferMemoryUsageReporter);
+    NS_RegisterMemoryReporter(mRenderbufferCountReporter);
+    NS_RegisterMemoryReporter(mShaderSourcesSizeReporter);
+    NS_RegisterMemoryReporter(mShaderTranslationLogsSizeReporter);
+    NS_RegisterMemoryReporter(mShaderCountReporter);
+    NS_RegisterMemoryReporter(mContextCountReporter);
+}
+
+WebGLMemoryReporter::~WebGLMemoryReporter()
+{
+    NS_UnregisterMemoryReporter(mTextureMemoryUsageReporter);
+    NS_UnregisterMemoryReporter(mTextureCountReporter);
+    NS_UnregisterMemoryReporter(mBufferMemoryUsageReporter);
+    NS_UnregisterMemoryReporter(mBufferCacheMemoryUsageReporter);
+    NS_UnregisterMemoryReporter(mBufferCountReporter);
+    NS_UnregisterMemoryReporter(mRenderbufferMemoryUsageReporter);
+    NS_UnregisterMemoryReporter(mRenderbufferCountReporter);
+    NS_UnregisterMemoryReporter(mShaderSourcesSizeReporter);
+    NS_UnregisterMemoryReporter(mShaderTranslationLogsSizeReporter);
+    NS_UnregisterMemoryReporter(mShaderCountReporter);
+    NS_UnregisterMemoryReporter(mContextCountReporter);
+}
+
 nsresult NS_NewCanvasRenderingContextWebGL(nsIDOMWebGLRenderingContext** aResult);
 
 nsresult
 NS_NewCanvasRenderingContextWebGL(nsIDOMWebGLRenderingContext** aResult)
 {
     nsIDOMWebGLRenderingContext* ctx = new WebGLContext();
     if (!ctx)
         return NS_ERROR_OUT_OF_MEMORY;
@@ -92,17 +221,17 @@ WebGLContext::WebGLContext()
     mWidth = mHeight = 0;
     mGeneration = 0;
     mInvalidated = PR_FALSE;
     mResetLayer = PR_TRUE;
     mVerbose = PR_FALSE;
     mOptionsFrozen = PR_FALSE;
 
     mActiveTexture = 0;
-    mSynthesizedGLError = LOCAL_GL_NO_ERROR;
+    mWebGLError = LOCAL_GL_NO_ERROR;
     mPixelStoreFlipY = PR_FALSE;
     mPixelStorePremultiplyAlpha = PR_FALSE;
     mPixelStoreColorspaceConversion = BROWSER_DEFAULT_WEBGL;
 
     mShaderValidation = PR_TRUE;
 
     mMapBuffers.Init();
     mMapTextures.Init();
@@ -159,21 +288,24 @@ WebGLContext::WebGLContext()
     mGLMaxVertexTextureImageUnits = 0;
     mGLMaxVaryingVectors = 0;
     mGLMaxFragmentUniformVectors = 0;
     mGLMaxVertexUniformVectors = 0;
     
     // See OpenGL ES 2.0.25 spec, 6.2 State Tables, table 6.13
     mPixelStorePackAlignment = 4;
     mPixelStoreUnpackAlignment = 4;
+    
+    WebGLMemoryReporter::AddWebGLContext(this);
 }
 
 WebGLContext::~WebGLContext()
 {
     DestroyResourcesAndContext();
+    WebGLMemoryReporter::RemoveWebGLContext(this);
 }
 
 static PLDHashOperator
 DeleteTextureFunction(const PRUint32& aKey, WebGLTexture *aValue, void *aData)
 {
     gl::GLContext *gl = (gl::GLContext *) aData;
     NS_ASSERTION(!aValue->Deleted(), "Texture is still in mMapTextures, but is deleted?");
     GLuint name = aValue->GLName();
@@ -408,32 +540,30 @@ WebGLContext::SetDimensions(PRInt32 widt
 
     ScopedGfxFeatureReporter reporter("WebGL");
 
     // At this point we know that the old context is not going to survive, even though we still don't
     // know if creating the new context will succeed.
     DestroyResourcesAndContext();
 
     // Get some prefs for some preferred/overriden things
-    nsCOMPtr<nsIPrefBranch> prefService = do_GetService(NS_PREFSERVICE_CONTRACTID);
-    NS_ENSURE_TRUE(prefService != nsnull, NS_ERROR_FAILURE);
+    NS_ENSURE_TRUE(Preferences::GetRootBranch(), NS_ERROR_FAILURE);
 
-    PRBool forceOSMesa = PR_FALSE;
-    PRBool preferEGL = PR_FALSE;
-    PRBool preferOpenGL = PR_FALSE;
-    PRBool forceEnabled = PR_FALSE;
-    PRBool disabled = PR_FALSE;
-    PRBool verbose = PR_FALSE;
-
-    prefService->GetBoolPref("webgl.force_osmesa", &forceOSMesa);
-    prefService->GetBoolPref("webgl.prefer-egl", &preferEGL);
-    prefService->GetBoolPref("webgl.prefer-native-gl", &preferOpenGL);
-    prefService->GetBoolPref("webgl.force-enabled", &forceEnabled);
-    prefService->GetBoolPref("webgl.disabled", &disabled);
-    prefService->GetBoolPref("webgl.verbose", &verbose);
+    PRBool forceOSMesa =
+        Preferences::GetBool("webgl.force_osmesa", PR_FALSE);
+    PRBool preferEGL =
+        Preferences::GetBool("webgl.prefer-egl", PR_FALSE);
+    PRBool preferOpenGL =
+        Preferences::GetBool("webgl.prefer-native-gl", PR_FALSE);
+    PRBool forceEnabled =
+        Preferences::GetBool("webgl.force-enabled", PR_FALSE);
+    PRBool disabled =
+        Preferences::GetBool("webgl.disabled", PR_FALSE);
+    PRBool verbose =
+        Preferences::GetBool("webgl.verbose", PR_FALSE);
 
     if (disabled)
         return NS_ERROR_FAILURE;
 
     mVerbose = verbose;
 
     // We're going to create an entirely new context.  If our
     // generation is not 0 right now (that is, if this isn't the first
--- a/content/canvas/src/WebGLContext.h
+++ b/content/canvas/src/WebGLContext.h
@@ -51,16 +51,17 @@
 #include "nsIDocShell.h"
 
 #include "nsIDOMWebGLRenderingContext.h"
 #include "nsICanvasRenderingContextInternal.h"
 #include "nsHTMLCanvasElement.h"
 #include "nsWeakReference.h"
 #include "nsIDOMHTMLElement.h"
 #include "nsIJSNativeInitializer.h"
+#include "nsIMemoryReporter.h"
 
 #include "GLContextProvider.h"
 #include "Layers.h"
 
 #include "CheckedInt.h"
 
 class nsIDocShell;
 class nsIPropertyBag;
@@ -315,16 +316,18 @@ struct WebGLContextOptions {
     bool preserveDrawingBuffer;
 };
 
 class WebGLContext :
     public nsIDOMWebGLRenderingContext,
     public nsICanvasRenderingContextInternal,
     public nsSupportsWeakReference
 {
+    friend class WebGLMemoryReporter;
+
 public:
     WebGLContext();
     virtual ~WebGLContext();
 
     NS_DECL_CYCLE_COLLECTING_ISUPPORTS
 
     NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(WebGLContext, nsIDOMWebGLRenderingContext)
 
@@ -362,16 +365,18 @@ public:
 
     nsresult ErrorInvalidEnum(const char *fmt = 0, ...);
     nsresult ErrorInvalidOperation(const char *fmt = 0, ...);
     nsresult ErrorInvalidValue(const char *fmt = 0, ...);
     nsresult ErrorInvalidEnumInfo(const char *info, PRUint32 enumvalue) {
         return ErrorInvalidEnum("%s: invalid enum value 0x%x", info, enumvalue);
     }
     nsresult ErrorOutOfMemory(const char *fmt = 0, ...);
+    
+    const char *ErrorName(GLenum error);
 
     WebGLTexture *activeBoundTextureForTarget(WebGLenum target) {
         return target == LOCAL_GL_TEXTURE_2D ? mBound2DTextures[mActiveTexture]
                                              : mBoundCubeMapTextures[mActiveTexture];
     }
 
     already_AddRefed<CanvasLayer> GetCanvasLayer(nsDisplayListBuilder* aBuilder,
                                                  CanvasLayer *aOldLayer,
@@ -387,16 +392,33 @@ public:
     // WebGL has more complex needs than GLContext as content controls GL state.
     void ForceClearFramebufferWithDefaultValues(PRUint32 mask, const nsIntRect& viewportRect);
 
     // if the preserveDrawingBuffer context option is false, we need to clear the back buffer
     // after it's been presented to the compositor. This function does that if needed.
     // See section 2.2 in the WebGL spec.
     void EnsureBackbufferClearedAsNeeded();
 
+    // checks for GL errors, clears any pending GL error, stores the current GL error in currentGLError,
+    // and copies it into mWebGLError if it doesn't already have an error set
+    void UpdateWebGLErrorAndClearGLError(GLenum *currentGLError) {
+        // get and clear GL error in ALL cases
+        *currentGLError = gl->GetAndClearError();
+        // only store in mWebGLError if is hasn't already recorded an error
+        if (!mWebGLError)
+            mWebGLError = *currentGLError;
+    }
+    
+    // checks for GL errors, clears any pending GL error,
+    // and stores the current GL error into mWebGLError if it doesn't already have an error set
+    void UpdateWebGLErrorAndClearGLError() {
+        GLenum currentGLError;
+        UpdateWebGLErrorAndClearGLError(&currentGLError);
+    }
+
 protected:
     void SetDontKnowIfNeedFakeBlack() {
         mFakeBlackStatus = DontKnowIfNeedFakeBlack;
     }
 
     PRBool NeedFakeBlack();
     void BindFakeBlackTextures();
     void UnbindFakeBlackTextures();
@@ -419,17 +441,17 @@ protected:
     WebGLContextOptions mOptions;
 
     PRPackedBool mInvalidated;
     PRPackedBool mResetLayer;
     PRPackedBool mVerbose;
     PRPackedBool mOptionsFrozen;
 
     WebGLuint mActiveTexture;
-    WebGLenum mSynthesizedGLError;
+    WebGLenum mWebGLError;
 
     // whether shader validation is supported
     PRBool mShaderValidation;
 
     // some GL constants
     PRInt32 mGLMaxVertexAttribs;
     PRInt32 mGLMaxTextureUnits;
     PRInt32 mGLMaxTextureSize;
@@ -463,16 +485,18 @@ protected:
     PRBool ValidateStencilOpEnum(WebGLenum action, const char *info);
     PRBool ValidateFaceEnum(WebGLenum face, const char *info);
     PRBool ValidateBufferUsageEnum(WebGLenum target, const char *info);
     PRBool ValidateTexFormatAndType(WebGLenum format, WebGLenum type, int jsArrayType,
                                       PRUint32 *texelSize, const char *info);
     PRBool ValidateDrawModeEnum(WebGLenum mode, const char *info);
     PRBool ValidateAttribIndex(WebGLuint index, const char *info);
     PRBool ValidateStencilParamsForDrawCall();
+    
+    static PRUint32 GetTexelSize(WebGLenum format, WebGLenum type);
 
     void Invalidate();
     void DestroyResourcesAndContext();
 
     void MakeContextCurrent() { gl->MakeCurrent(); }
 
     // helpers
     nsresult TexImage2D_base(WebGLenum target, WebGLint level, WebGLenum internalformat,
@@ -543,16 +567,34 @@ protected:
     PRBool CanGetConcreteObject(const char *info,
                                 BaseInterfaceType *aInterface,
                                 PRBool *isNull = 0,
                                 PRBool *isDeleted = 0);
 
     PRInt32 MaxTextureSizeForTarget(WebGLenum target) const {
         return target == LOCAL_GL_TEXTURE_2D ? mGLMaxTextureSize : mGLMaxCubeMapTextureSize;
     }
+    
+    /** like glBufferData but if the call may change the buffer size, checks any GL error generated
+     * by this glBufferData call and returns it */
+    GLenum CheckedBufferData(GLenum target,
+                             GLsizeiptr size,
+                             const GLvoid *data,
+                             GLenum usage);
+    /** like glTexImage2D but if the call may change the texture size, checks any GL error generated
+     * by this glTexImage2D call and returns it */
+    GLenum CheckedTexImage2D(GLenum target,
+                             GLint level,
+                             GLenum internalFormat,
+                             GLsizei width,
+                             GLsizei height,
+                             GLint border,
+                             GLenum format,
+                             GLenum type,
+                             const GLvoid *data);
 
     // the buffers bound to the current program's attribs
     nsTArray<WebGLVertexAttribData> mAttribBuffers;
 
     // the textures bound to any sampler uniforms
     nsTArray<WebGLObjectRefPtr<WebGLTexture> > mUniformTextures;
 
     // textures bound to 
@@ -654,20 +696,20 @@ protected:
 // that we need to track.
 class WebGLRectangleObject
 {
 protected:
     WebGLRectangleObject()
         : mWidth(0), mHeight(0) { }
 
 public:
-    WebGLsizei width() { return mWidth; }
+    WebGLsizei width() const { return mWidth; }
     void width(WebGLsizei value) { mWidth = value; }
 
-    WebGLsizei height() { return mHeight; }
+    WebGLsizei height() const { return mHeight; }
     void height(WebGLsizei value) { mHeight = value; }
 
     void setDimensions(WebGLsizei width, WebGLsizei height) {
         mWidth = width;
         mHeight = height;
     }
 
     void setDimensions(WebGLRectangleObject *rect) {
@@ -675,16 +717,20 @@ public:
             mWidth = rect->width();
             mHeight = rect->height();
         } else {
             mWidth = 0;
             mHeight = 0;
         }
     }
 
+    bool HasSameDimensionsAs(const WebGLRectangleObject& other) const {
+        return width() == other.width() && height() == other.height(); 
+    }
+
 protected:
     WebGLsizei mWidth;
     WebGLsizei mHeight;
 };
 
 // This class is a mixin for objects that are tied to a specific
 // context (which is to say, all of them).  They provide initialization
 // as well as comparison with the current context.
@@ -715,17 +761,17 @@ class WebGLBuffer :
 {
 public:
     NS_DECLARE_STATIC_IID_ACCESSOR(WEBGLBUFFER_PRIVATE_IID)
 
     WebGLBuffer(WebGLContext *context, WebGLuint name) :
         WebGLContextBoundObject(context),
         mName(name), mDeleted(PR_FALSE), mHasEverBeenBound(PR_FALSE),
         mByteLength(0), mTarget(LOCAL_GL_NONE), mData(nsnull)
-    { }
+    {}
 
     ~WebGLBuffer() {
         Delete();
     }
 
     void Delete() {
         if (mDeleted)
             return;
@@ -838,17 +884,16 @@ protected:
 
 NS_DEFINE_STATIC_IID_ACCESSOR(WebGLBuffer, WEBGLBUFFER_PRIVATE_IID)
 
 #define WEBGLTEXTURE_PRIVATE_IID \
     {0x4c19f189, 0x1f86, 0x4e61, {0x96, 0x21, 0x0a, 0x11, 0xda, 0x28, 0x10, 0xdd}}
 class WebGLTexture :
     public nsIWebGLTexture,
     public WebGLZeroingObject,
-    public WebGLRectangleObject,
     public WebGLContextBoundObject
 {
 public:
     NS_DECLARE_STATIC_IID_ACCESSOR(WEBGLTEXTURE_PRIVATE_IID)
 
     WebGLTexture(WebGLContext *context, WebGLuint name) :
         WebGLContextBoundObject(context),
         mDeleted(PR_FALSE), mHasEverBeenBound(PR_FALSE), mName(name),
@@ -885,18 +930,24 @@ protected:
 
     PRBool mDeleted;
     PRBool mHasEverBeenBound;
     WebGLuint mName;
 
     // we store information about the various images that are part of
     // this texture (cubemap faces, mipmap levels)
 
+public:
+
     struct ImageInfo {
         ImageInfo() : mWidth(0), mHeight(0), mFormat(0), mType(0), mIsDefined(PR_FALSE) {}
+        ImageInfo(WebGLsizei width, WebGLsizei height,
+                  WebGLenum format, WebGLenum type)
+            : mWidth(width), mHeight(height), mFormat(format), mType(type), mIsDefined(PR_TRUE) {}
+
         PRBool operator==(const ImageInfo& a) const {
             return mWidth == a.mWidth && mHeight == a.mHeight &&
                    mFormat == a.mFormat && mType == a.mType;
         }
         PRBool operator!=(const ImageInfo& a) const {
             return !(*this == a);
         }
         PRBool IsSquare() const {
@@ -904,23 +955,27 @@ protected:
         }
         PRBool IsPositive() const {
             return mWidth > 0 && mHeight > 0;
         }
         PRBool IsPowerOfTwo() const {
             return is_pot_assuming_nonnegative(mWidth) &&
                    is_pot_assuming_nonnegative(mHeight); // negative sizes should never happen (caught in texImage2D...)
         }
+        PRInt64 MemoryUsage() const {
+            if (!mIsDefined)
+                return 0;
+            PRInt64 texelSize = WebGLContext::GetTexelSize(mFormat, mType);
+            return PRInt64(mWidth) * PRInt64(mHeight) * texelSize;
+        }
         WebGLsizei mWidth, mHeight;
         WebGLenum mFormat, mType;
         PRBool mIsDefined;
     };
 
-public:
-
     ImageInfo& ImageInfoAt(size_t level, size_t face = 0) {
 #ifdef DEBUG
         if (face >= mFacesCount)
             NS_ERROR("wrong face index, must be 0 for TEXTURE_2D and at most 5 for cube maps");
 #endif
         // no need to check level as a wrong value would be caught by ElementAt().
         return mImageInfos.ElementAt(level * mFacesCount + face);
     }
@@ -934,16 +989,32 @@ public:
                face < mFacesCount &&
                ImageInfoAt(level, 0).mIsDefined;
     }
 
     static size_t FaceForTarget(WebGLenum target) {
         return target == LOCAL_GL_TEXTURE_2D ? 0 : target - LOCAL_GL_TEXTURE_CUBE_MAP_POSITIVE_X;
     }
 
+    PRInt64 MemoryUsage() const {
+        PRInt64 result = 0;
+        for(size_t face = 0; face < mFacesCount; face++) {
+            if (mHaveGeneratedMipmap) {
+                // Each mipmap level is 1/4 the size of the previous level
+                // 1 + x + x^2 + ... = 1/(1-x)
+                // for x = 1/4, we get 1/(1-1/4) = 4/3
+                result += ImageInfoAt(0, face).MemoryUsage() * 4 / 3;
+            } else {
+                for(size_t level = 0; level <= mMaxLevelWithCustomImages; level++)
+                    result += ImageInfoAt(level, face).MemoryUsage();
+            }
+        }
+        return result;
+    }
+
 protected:
 
     WebGLenum mTarget;
     WebGLenum mMinFilter, mMagFilter, mWrapS, mWrapT;
 
     size_t mFacesCount, mMaxLevelWithCustomImages;
     nsTArray<ImageInfo> mImageInfos;
 
@@ -1030,33 +1101,26 @@ public:
                 mContext->gl->fTexParameteri(mTarget, LOCAL_GL_TEXTURE_WRAP_R, LOCAL_GL_CLAMP_TO_EDGE);
         }
 
         mHasEverBeenBound = PR_TRUE;
     }
 
     void SetImageInfo(WebGLenum aTarget, WebGLint aLevel,
                       WebGLsizei aWidth, WebGLsizei aHeight,
-                      WebGLenum aFormat = 0, WebGLenum aType = 0)
+                      WebGLenum aFormat, WebGLenum aType)
     {
         if ( (aTarget == LOCAL_GL_TEXTURE_2D) != (mTarget == LOCAL_GL_TEXTURE_2D) )
             return;
 
         size_t face = FaceForTarget(aTarget);
 
         EnsureMaxLevelWithCustomImagesAtLeast(aLevel);
 
-        ImageInfo& imageInfo = ImageInfoAt(aLevel, face);
-        imageInfo.mWidth  = aWidth;
-        imageInfo.mHeight = aHeight;
-        if (aFormat)
-            imageInfo.mFormat = aFormat;
-        if (aType)
-            imageInfo.mType = aType;
-        imageInfo.mIsDefined = PR_TRUE;
+        ImageInfoAt(aLevel, face) = ImageInfo(aWidth, aHeight, aFormat, aType);
 
         if (aLevel > 0)
             SetCustomMipmap();
 
         SetDontKnowIfNeedFakeBlack();
     }
 
     void SetMinFilter(WebGLenum aMinFilter) {
@@ -1461,16 +1525,17 @@ class WebGLRenderbuffer :
 {
 public:
     NS_DECLARE_STATIC_IID_ACCESSOR(WEBGLRENDERBUFFER_PRIVATE_IID)
 
     WebGLRenderbuffer(WebGLContext *context, WebGLuint name, WebGLuint secondBufferName = 0) :
         WebGLContextBoundObject(context),
         mName(name),
         mInternalFormat(0),
+        mInternalFormatForGL(0),
         mDeleted(PR_FALSE), mHasEverBeenBound(PR_FALSE), mInitialized(PR_FALSE)
     { }
 
     void Delete() {
         if (mDeleted)
             return;
         ZeroOwners();
         mDeleted = PR_TRUE;
@@ -1480,34 +1545,62 @@ public:
     void SetHasEverBeenBound(PRBool x) { mHasEverBeenBound = x; }
     WebGLuint GLName() const { return mName; }
 
     PRBool Initialized() const { return mInitialized; }
     void SetInitialized(PRBool aInitialized) { mInitialized = aInitialized; }
 
     WebGLenum InternalFormat() const { return mInternalFormat; }
     void SetInternalFormat(WebGLenum aInternalFormat) { mInternalFormat = aInternalFormat; }
+    
+    WebGLenum InternalFormatForGL() const { return mInternalFormatForGL; }
+    void SetInternalFormatForGL(WebGLenum aInternalFormatForGL) { mInternalFormatForGL = aInternalFormatForGL; }
+    
+    PRInt64 MemoryUsage() const {
+        PRInt64 pixels = PRInt64(width()) * PRInt64(height());
+        switch (mInternalFormatForGL) {
+            case LOCAL_GL_STENCIL_INDEX8:
+                return pixels;
+            case LOCAL_GL_RGBA4:
+            case LOCAL_GL_RGB5_A1:
+            case LOCAL_GL_RGB565:
+            case LOCAL_GL_DEPTH_COMPONENT16:
+                return 2 * pixels;
+            case LOCAL_GL_RGB8:
+            case LOCAL_GL_DEPTH_COMPONENT24:
+                return 3*pixels;
+            case LOCAL_GL_RGBA8:
+            case LOCAL_GL_DEPTH24_STENCIL8:
+                return 4*pixels;
+            default:
+                break;
+        }
+        NS_ABORT();
+        return 0;
+    }
 
     NS_DECL_ISUPPORTS
     NS_DECL_NSIWEBGLRENDERBUFFER
 
 protected:
     WebGLuint mName;
     WebGLenum mInternalFormat;
+    WebGLenum mInternalFormatForGL;
 
     PRBool mDeleted;
     PRBool mHasEverBeenBound;
     PRBool mInitialized;
 
     friend class WebGLFramebuffer;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(WebGLRenderbuffer, WEBGLRENDERBUFFER_PRIVATE_IID)
 
 class WebGLFramebufferAttachment
+    : public WebGLRectangleObject
 {
     // deleting a texture or renderbuffer immediately detaches it
     WebGLObjectRefPtr<WebGLTexture> mTexturePtr;
     WebGLObjectRefPtr<WebGLRenderbuffer> mRenderbufferPtr;
     WebGLenum mAttachmentPoint;
     WebGLint mTextureLevel;
     WebGLenum mTextureCubeMapFace;
 
@@ -1533,20 +1626,27 @@ public:
                format == LOCAL_GL_RGB5_A1;
     }
 
     void SetTexture(WebGLTexture *tex, WebGLint level, WebGLenum face) {
         mTexturePtr = tex;
         mRenderbufferPtr = nsnull;
         mTextureLevel = level;
         mTextureCubeMapFace = face;
+        if (tex) {
+            const WebGLTexture::ImageInfo &imageInfo = tex->ImageInfoAt(level, face);
+            setDimensions(imageInfo.mWidth, imageInfo.mHeight);
+        } else {
+            setDimensions(0, 0);
+        }
     }
     void SetRenderbuffer(WebGLRenderbuffer *rb) {
         mTexturePtr = nsnull;
         mRenderbufferPtr = rb;
+        setDimensions(rb);
     }
     WebGLTexture *Texture() const {
         return mTexturePtr.get();
     }
     WebGLRenderbuffer *Renderbuffer() const {
         return mRenderbufferPtr.get();
     }
     WebGLint TextureLevel() const {
@@ -1586,17 +1686,16 @@ public:
     }
 };
 
 #define WEBGLFRAMEBUFFER_PRIVATE_IID \
     {0x0052a16f, 0x4bc9, 0x4a55, {0x9d, 0xa3, 0x54, 0x95, 0xaa, 0x4e, 0x80, 0xb9}}
 class WebGLFramebuffer :
     public nsIWebGLFramebuffer,
     public WebGLZeroingObject,
-    public WebGLRectangleObject,
     public WebGLContextBoundObject
 {
 public:
     NS_DECLARE_STATIC_IID_ACCESSOR(WEBGLFRAMEBUFFER_PRIVATE_IID)
 
     WebGLFramebuffer(WebGLContext *context, WebGLuint name) :
         WebGLContextBoundObject(context),
         mName(name), mDeleted(PR_FALSE), mHasEverBeenBound(PR_FALSE),
@@ -1611,16 +1710,19 @@ public:
             return;
         ZeroOwners();
         mDeleted = PR_TRUE;
     }
     PRBool Deleted() { return mDeleted; }
     PRBool HasEverBeenBound() { return mHasEverBeenBound; }
     void SetHasEverBeenBound(PRBool x) { mHasEverBeenBound = x; }
     WebGLuint GLName() { return mName; }
+    
+    WebGLsizei width() { return mColorAttachment.width(); }
+    WebGLsizei height() { return mColorAttachment.height(); }
 
     nsresult FramebufferRenderbuffer(WebGLenum target,
                                      WebGLenum attachment,
                                      WebGLenum rbtarget,
                                      nsIWebGLRenderbuffer *rbobj)
     {
         WebGLuint renderbuffername;
         PRBool isNull;
@@ -1647,21 +1749,17 @@ public:
             break;
         case LOCAL_GL_DEPTH_STENCIL_ATTACHMENT:
             mDepthStencilAttachment.SetRenderbuffer(wrb);
             break;
         default:
             // finish checking that the 'attachment' parameter is among the allowed values
             if (attachment != LOCAL_GL_COLOR_ATTACHMENT0)
                 return mContext->ErrorInvalidEnumInfo("framebufferRenderbuffer: attachment", attachment);
-            if (!isNull) {
-                // ReadPixels needs alpha and size information, but only
-                // for COLOR_ATTACHMENT0
-                setDimensions(wrb);
-            }
+
             mColorAttachment.SetRenderbuffer(wrb);
             break;
         }
 
         mContext->MakeContextCurrent();
         if (attachment == LOCAL_GL_DEPTH_STENCIL_ATTACHMENT) {
             mContext->gl->fFramebufferRenderbuffer(target, LOCAL_GL_DEPTH_ATTACHMENT, rbtarget, renderbuffername);
             mContext->gl->fFramebufferRenderbuffer(target, LOCAL_GL_STENCIL_ATTACHMENT, rbtarget, renderbuffername);
@@ -1686,42 +1784,39 @@ public:
                                                   tobj, &wtex, &texturename, &isNull))
         {
             return NS_OK;
         }
 
         if (target != LOCAL_GL_FRAMEBUFFER)
             return mContext->ErrorInvalidEnumInfo("framebufferTexture2D: target", target);
 
-        if (!isNull && textarget != LOCAL_GL_TEXTURE_2D &&
+        if (textarget != LOCAL_GL_TEXTURE_2D &&
             (textarget < LOCAL_GL_TEXTURE_CUBE_MAP_POSITIVE_X ||
-            textarget > LOCAL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z))
+             textarget > LOCAL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z))
             return mContext->ErrorInvalidEnumInfo("framebufferTexture2D: invalid texture target", textarget);
 
-        if (!isNull && level > 0)
+        if (level != 0)
             return mContext->ErrorInvalidValue("framebufferTexture2D: level must be 0");
 
-        WebGLint face = (textarget == LOCAL_GL_TEXTURE_2D) ? 0 : textarget;
+        size_t face = WebGLTexture::FaceForTarget(textarget);
         switch (attachment) {
         case LOCAL_GL_DEPTH_ATTACHMENT:
             mDepthAttachment.SetTexture(wtex, level, face);
             break;
         case LOCAL_GL_STENCIL_ATTACHMENT:
             mStencilAttachment.SetTexture(wtex, level, face);
             break;
         case LOCAL_GL_DEPTH_STENCIL_ATTACHMENT:
             mDepthStencilAttachment.SetTexture(wtex, level, face);
             break;
         default:
             if (attachment != LOCAL_GL_COLOR_ATTACHMENT0)
                 return mContext->ErrorInvalidEnumInfo("framebufferTexture2D: attachment", attachment);
 
-            // keep data for readPixels, function only uses COLOR_ATTACHMENT0
-            setDimensions(wtex);
-
             mColorAttachment.SetTexture(wtex, level, face);
             break;
         }
 
         mContext->MakeContextCurrent();
         if (attachment == LOCAL_GL_DEPTH_STENCIL_ATTACHMENT) {
             mContext->gl->fFramebufferTexture2D(target, LOCAL_GL_DEPTH_ATTACHMENT, textarget, texturename, level);
             mContext->gl->fFramebufferTexture2D(target, LOCAL_GL_STENCIL_ATTACHMENT, textarget, texturename, level);
@@ -1754,23 +1849,32 @@ public:
         if (mColorAttachment.IsIncompatibleWithAttachmentPoint() ||
             mDepthAttachment.IsIncompatibleWithAttachmentPoint() ||
             mStencilAttachment.IsIncompatibleWithAttachmentPoint() ||
             mDepthStencilAttachment.IsIncompatibleWithAttachmentPoint())
         {
             // some attachment is incompatible with its attachment point
             return PR_TRUE;
         }
-        else if (int(mDepthAttachment.IsNull()) +
-                 int(mStencilAttachment.IsNull()) +
-                 int(mDepthStencilAttachment.IsNull()) <= 1)
+        
+        if (int(mDepthAttachment.IsNull()) +
+            int(mStencilAttachment.IsNull()) +
+            int(mDepthStencilAttachment.IsNull()) <= 1)
         {
             // has at least two among Depth, Stencil, DepthStencil
             return PR_TRUE;
         }
+        
+        if (!mDepthAttachment.IsNull() && !mDepthAttachment.HasSameDimensionsAs(mColorAttachment))
+            return PR_TRUE;
+        if (!mStencilAttachment.IsNull() && !mStencilAttachment.HasSameDimensionsAs(mColorAttachment))
+            return PR_TRUE;
+        if (!mDepthStencilAttachment.IsNull() && !mDepthStencilAttachment.HasSameDimensionsAs(mColorAttachment))
+            return PR_TRUE;
+        
         else return PR_FALSE;
     }
 
     const WebGLFramebufferAttachment& ColorAttachment() const {
         return mColorAttachment;
     }
 
     const WebGLFramebufferAttachment& DepthAttachment() const {
@@ -2061,11 +2165,204 @@ WebGLContext::CanGetConcreteObject(const
                               BaseInterfaceType *aInterface,
                               PRBool *isNull,
                               PRBool *isDeleted)
 {
     ConcreteObjectType *aConcreteObject;
     return GetConcreteObject(info, aInterface, &aConcreteObject, isNull, isDeleted, PR_FALSE);
 }
 
+class WebGLMemoryReporter
+{
+    WebGLMemoryReporter();
+    ~WebGLMemoryReporter();
+    static WebGLMemoryReporter* sUniqueInstance;
+
+    // here we store plain pointers, not RefPtrs: we don't want the WebGLMemoryReporter unique instance to keep alive all
+    // WebGLContexts ever created.
+    typedef nsTArray<const WebGLContext*> ContextsArrayType;
+    ContextsArrayType mContexts;
+    
+    nsIMemoryReporter *mTextureMemoryUsageReporter;
+    nsIMemoryReporter *mTextureCountReporter;
+    nsIMemoryReporter *mBufferMemoryUsageReporter;
+    nsIMemoryReporter *mBufferCacheMemoryUsageReporter;
+    nsIMemoryReporter *mBufferCountReporter;
+    nsIMemoryReporter *mRenderbufferMemoryUsageReporter;
+    nsIMemoryReporter *mRenderbufferCountReporter;
+    nsIMemoryReporter *mShaderSourcesSizeReporter;
+    nsIMemoryReporter *mShaderTranslationLogsSizeReporter;
+    nsIMemoryReporter *mShaderCountReporter;
+    nsIMemoryReporter *mContextCountReporter;
+
+    static WebGLMemoryReporter* UniqueInstance();
+
+    static ContextsArrayType & Contexts() { return UniqueInstance()->mContexts; }
+
+  public:
+
+    static void AddWebGLContext(const WebGLContext* c) {
+        Contexts().AppendElement(c);
+    }
+
+    static void RemoveWebGLContext(const WebGLContext* c) {
+        ContextsArrayType & contexts = Contexts();
+        contexts.RemoveElement(c);
+        if (contexts.IsEmpty()) {
+            delete sUniqueInstance;
+            sUniqueInstance = nsnull;
+        }
+    }
+
+    static PLDHashOperator TextureMemoryUsageFunction(const PRUint32&, WebGLTexture *aValue, void *aData)
+    {
+        PRInt64 *result = (PRInt64*) aData;
+        *result += aValue->MemoryUsage();
+        return PL_DHASH_NEXT;
+    }
+
+    static PRInt64 GetTextureMemoryUsed() {
+        const ContextsArrayType & contexts = Contexts();
+        PRInt64 result = 0;
+        for(size_t i = 0; i < contexts.Length(); ++i) {
+            PRInt64 textureMemoryUsageForThisContext = 0;
+            contexts[i]->mMapTextures.EnumerateRead(TextureMemoryUsageFunction, &textureMemoryUsageForThisContext);
+            result += textureMemoryUsageForThisContext;
+        }
+        return result;
+    }
+    
+    static PRInt64 GetTextureCount() {
+        const ContextsArrayType & contexts = Contexts();
+        PRInt64 result = 0;
+        for(size_t i = 0; i < contexts.Length(); ++i) {
+            result += contexts[i]->mMapTextures.Count();
+        }
+        return result;
+    }
+    
+    static PLDHashOperator BufferMemoryUsageFunction(const PRUint32&, WebGLBuffer *aValue, void *aData)
+    {
+        PRInt64 *result = (PRInt64*) aData;
+        *result += aValue->ByteLength();
+        return PL_DHASH_NEXT;
+    }
+
+    static PRInt64 GetBufferMemoryUsed() {
+        const ContextsArrayType & contexts = Contexts();
+        PRInt64 result = 0;
+        for(size_t i = 0; i < contexts.Length(); ++i) {
+            PRInt64 bufferMemoryUsageForThisContext = 0;
+            contexts[i]->mMapBuffers.EnumerateRead(BufferMemoryUsageFunction, &bufferMemoryUsageForThisContext);
+            result += bufferMemoryUsageForThisContext;
+        }
+        return result;
+    }
+    
+    static PLDHashOperator BufferCacheMemoryUsageFunction(const PRUint32&, WebGLBuffer *aValue, void *aData)
+    {
+        PRInt64 *result = (PRInt64*) aData;
+        // element array buffers are cached in the WebGL implementation. Other buffers aren't.
+        if (aValue->Target() == LOCAL_GL_ELEMENT_ARRAY_BUFFER)
+          *result += aValue->ByteLength();
+        return PL_DHASH_NEXT;
+    }
+
+    static PRInt64 GetBufferCacheMemoryUsed() {
+        const ContextsArrayType & contexts = Contexts();
+        PRInt64 result = 0;
+        for(size_t i = 0; i < contexts.Length(); ++i) {
+            PRInt64 bufferCacheMemoryUsageForThisContext = 0;
+            contexts[i]->mMapBuffers.EnumerateRead(BufferCacheMemoryUsageFunction, &bufferCacheMemoryUsageForThisContext);
+            result += bufferCacheMemoryUsageForThisContext;
+        }
+        return result;
+    }
+
+    static PRInt64 GetBufferCount() {
+        const ContextsArrayType & contexts = Contexts();
+        PRInt64 result = 0;
+        for(size_t i = 0; i < contexts.Length(); ++i) {
+            result += contexts[i]->mMapBuffers.Count();
+        }
+        return result;
+    }
+    
+    static PLDHashOperator RenderbufferMemoryUsageFunction(const PRUint32&, WebGLRenderbuffer *aValue, void *aData)
+    {
+        PRInt64 *result = (PRInt64*) aData;
+        *result += aValue->MemoryUsage();
+        return PL_DHASH_NEXT;
+    }
+
+    static PRInt64 GetRenderbufferMemoryUsed() {
+        const ContextsArrayType & contexts = Contexts();
+        PRInt64 result = 0;
+        for(size_t i = 0; i < contexts.Length(); ++i) {
+            PRInt64 bufferMemoryUsageForThisContext = 0;
+            contexts[i]->mMapRenderbuffers.EnumerateRead(RenderbufferMemoryUsageFunction, &bufferMemoryUsageForThisContext);
+            result += bufferMemoryUsageForThisContext;
+        }
+        return result;
+    }
+    
+    static PRInt64 GetRenderbufferCount() {
+        const ContextsArrayType & contexts = Contexts();
+        PRInt64 result = 0;
+        for(size_t i = 0; i < contexts.Length(); ++i) {
+            result += contexts[i]->mMapRenderbuffers.Count();
+        }
+        return result;
+    }
+
+    static PLDHashOperator ShaderSourceSizeFunction(const PRUint32&, WebGLShader *aValue, void *aData)
+    {
+        PRInt64 *result = (PRInt64*) aData;
+        *result += aValue->Source().Length();
+        return PL_DHASH_NEXT;
+    }
+
+    static PLDHashOperator ShaderTranslationLogSizeFunction(const PRUint32&, WebGLShader *aValue, void *aData)
+    {
+        PRInt64 *result = (PRInt64*) aData;
+        *result += aValue->TranslationLog().Length();
+        return PL_DHASH_NEXT;
+    }
+
+    static PRInt64 GetShaderSourcesSize() {
+        const ContextsArrayType & contexts = Contexts();
+        PRInt64 result = 0;
+        for(size_t i = 0; i < contexts.Length(); ++i) {
+            PRInt64 shaderSourcesSizeForThisContext = 0;
+            contexts[i]->mMapShaders.EnumerateRead(ShaderSourceSizeFunction, &shaderSourcesSizeForThisContext);
+            result += shaderSourcesSizeForThisContext;
+        }
+        return result;
+    }
+    
+    static PRInt64 GetShaderTranslationLogsSize() {
+        const ContextsArrayType & contexts = Contexts();
+        PRInt64 result = 0;
+        for(size_t i = 0; i < contexts.Length(); ++i) {
+            PRInt64 shaderTranslationLogsSizeForThisContext = 0;
+            contexts[i]->mMapShaders.EnumerateRead(ShaderTranslationLogSizeFunction, &shaderTranslationLogsSizeForThisContext);
+            result += shaderTranslationLogsSizeForThisContext;
+        }
+        return result;
+    }
+    
+    static PRInt64 GetShaderCount() {
+        const ContextsArrayType & contexts = Contexts();
+        PRInt64 result = 0;
+        for(size_t i = 0; i < contexts.Length(); ++i) {
+            result += contexts[i]->mMapShaders.Count();
+        }
+        return result;
+    }
+
+    static PRInt64 GetContextCount() {
+        return Contexts().Length();
+    }
+};
+
 }
 
 #endif
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -36,16 +36,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "WebGLContext.h"
 
 #include "nsString.h"
+#include "nsDebug.h"
 
 #include "gfxImageSurface.h"
 #include "gfxContext.h"
 #include "gfxPlatform.h"
 //#include "nsIDOMHTMLCanvasElement.h"
 
 #include "nsContentUtils.h"
 #include "nsDOMError.h"
@@ -362,16 +363,42 @@ WebGLContext::BlendFuncSeparate(WebGLenu
     if (!ValidateBlendFuncEnumsCompatibility(srcRGB, dstRGB, "blendFuncSeparate: srcRGB and dstRGB"))
         return NS_OK;
 
     MakeContextCurrent();
     gl->fBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
     return NS_OK;
 }
 
+GLenum WebGLContext::CheckedBufferData(GLenum target,
+                                       GLsizeiptr size,
+                                       const GLvoid *data,
+                                       GLenum usage)
+{
+    WebGLBuffer *boundBuffer = NULL;
+    if (target == LOCAL_GL_ARRAY_BUFFER) {
+        boundBuffer = mBoundArrayBuffer;
+    } else if (target == LOCAL_GL_ELEMENT_ARRAY_BUFFER) {
+        boundBuffer = mBoundElementArrayBuffer;
+    }
+    NS_ABORT_IF_FALSE(boundBuffer != nsnull, "no buffer bound for this target");
+    
+    bool sizeChanges = PRUint32(size) != boundBuffer->ByteLength();
+    if (sizeChanges) {
+        UpdateWebGLErrorAndClearGLError();
+        gl->fBufferData(target, size, data, usage);
+        GLenum error = LOCAL_GL_NO_ERROR;
+        UpdateWebGLErrorAndClearGLError(&error);
+        return error;
+    } else {
+        gl->fBufferData(target, size, data, usage);
+        return LOCAL_GL_NO_ERROR;
+    }
+}
+
 NS_IMETHODIMP
 WebGLContext::BufferData(PRInt32 dummy)
 {
     // this should never be called
     LogMessageIfVerbose("BufferData");
     return NS_ERROR_FAILURE;
 }
 
@@ -401,23 +428,27 @@ WebGLContext::BufferData_size(WebGLenum 
 
     if (!ValidateBufferUsageEnum(usage, "bufferData: usage"))
         return NS_OK;
 
     if (!boundBuffer)
         return ErrorInvalidOperation("BufferData: no buffer bound!");
 
     MakeContextCurrent();
+    
+    GLenum error = CheckedBufferData(target, size, 0, usage);
+    if (error) {
+        LogMessageIfVerbose("bufferData generated error %s", ErrorName(error));
+        return NS_OK;
+    }
 
     boundBuffer->SetByteLength(size);
+    boundBuffer->InvalidateCachedMaxElements();
     if (!boundBuffer->ZeroDataIfElementArray())
         return ErrorOutOfMemory("bufferData: out of memory");
-    boundBuffer->InvalidateCachedMaxElements();
-
-    gl->fBufferData(target, size, 0, usage);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::BufferData_buf(WebGLenum target, JSObject *wb, WebGLenum usage)
 {
     WebGLBuffer *boundBuffer = NULL;
@@ -433,22 +464,29 @@ WebGLContext::BufferData_buf(WebGLenum t
     if (!ValidateBufferUsageEnum(usage, "bufferData: usage"))
         return NS_OK;
 
     if (!boundBuffer)
         return ErrorInvalidOperation("BufferData: no buffer bound!");
 
     MakeContextCurrent();
 
+    GLenum error = CheckedBufferData(target,
+                                     JS_GetArrayBufferByteLength(wb),
+                                     JS_GetArrayBufferData(wb),
+                                     usage);
+    if (error) {
+        LogMessageIfVerbose("bufferData generated error %s", ErrorName(error));
+        return NS_OK;
+    }
+
     boundBuffer->SetByteLength(JS_GetArrayBufferByteLength(wb));
+    boundBuffer->InvalidateCachedMaxElements();
     if (!boundBuffer->CopyDataIfElementArray(JS_GetArrayBufferData(wb)))
         return ErrorOutOfMemory("bufferData: out of memory");
-    boundBuffer->InvalidateCachedMaxElements();
-
-    gl->fBufferData(target, JS_GetArrayBufferByteLength(wb), JS_GetArrayBufferData(wb), usage);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::BufferData_array(WebGLenum target, js::TypedArray *wa, WebGLenum usage)
 {
     WebGLBuffer *boundBuffer = NULL;
@@ -464,22 +502,29 @@ WebGLContext::BufferData_array(WebGLenum
     if (!ValidateBufferUsageEnum(usage, "bufferData: usage"))
         return NS_OK;
 
     if (!boundBuffer)
         return ErrorInvalidOperation("BufferData: no buffer bound!");
 
     MakeContextCurrent();
 
+    GLenum error = CheckedBufferData(target,
+                                     wa->byteLength,
+                                     wa->data,
+                                     usage);
+    if (error) {
+        LogMessageIfVerbose("bufferData generated error %s", ErrorName(error));
+        return NS_OK;
+    }
+
     boundBuffer->SetByteLength(wa->byteLength);
+    boundBuffer->InvalidateCachedMaxElements();
     if (!boundBuffer->CopyDataIfElementArray(wa->data))
         return ErrorOutOfMemory("bufferData: out of memory");
-    boundBuffer->InvalidateCachedMaxElements();
-
-    gl->fBufferData(target, wa->byteLength, wa->data, usage);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::BufferSubData(PRInt32)
 {
     return NS_ERROR_FAILURE;
@@ -680,19 +725,19 @@ WebGLContext::CopyTexSubImage2D_base(Web
     WebGLsizei framebufferHeight = mBoundFramebuffer ? mBoundFramebuffer->height() : mHeight;
 
     const char *info = sub ? "copyTexSubImage2D" : "copyTexImage2D";
 
     MakeContextCurrent();
 
     if (CanvasUtils::CheckSaneSubrectSize(x, y, width, height, framebufferWidth, framebufferHeight)) {
         if (sub)
-          gl->fCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
+            gl->fCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
         else
-          gl->fCopyTexImage2D(target, level, internalformat, x, y, width, height, 0);
+            gl->fCopyTexImage2D(target, level, internalformat, x, y, width, height, 0);
     } else {
 
         // the rect doesn't fit in the framebuffer
 
         /*** first, we initialize the texture as black ***/
 
         // first, compute the size of the buffer we should allocate to initialize the texture as black
 
@@ -723,20 +768,21 @@ WebGLContext::CopyTexSubImage2D_base(Web
         // Hopefully calloc will just mmap zero pages here.
         void *tempZeroData = calloc(1, bytesNeeded);
         if (!tempZeroData)
             return ErrorOutOfMemory("%s: could not allocate %d bytes (for zero fill)", info, bytesNeeded);
 
         // now initialize the texture as black
 
         if (sub)
-          gl->fTexSubImage2D(target, level, 0, 0, width, height, internalformat, LOCAL_GL_UNSIGNED_BYTE, tempZeroData);
+            gl->fTexSubImage2D(target, level, 0, 0, width, height,