Merge m-c to b-s.
authorKyle Huey <khuey@kylehuey.com>
Wed, 24 Aug 2011 08:34:27 -0400
changeset 75809 d79e6c3c0616982736bd8044d089d7487367deb4
parent 75808 2921dbf1def9fce7fcc6abd9615c9d2e4113c34f (current diff)
parent 75799 e0acef471ab29856f4c7883dc2d1bb31afdfff77 (diff)
child 75810 d3e15e7073f92cd43479d5809b337d8ba031221d
push id3
push userfelipc@gmail.com
push dateFri, 30 Sep 2011 20:09:13 +0000
milestone9.0a1
Merge m-c to b-s.
config/autoconf.mk.in
config/config.mk
configure.in
content/svg/content/test/test_animLengthRelativeUnits.xhtml
js/src/assembler/wtf/Platform.h
js/src/config/config.mk
js/src/configure.in
--- a/accessible/src/atk/nsAccessibleWrap.cpp
+++ b/accessible/src/atk/nsAccessibleWrap.cpp
@@ -971,19 +971,21 @@ refRelationSetCB(AtkObject *aAtkObj)
       atk_relation_set_remove(relation_set, atkRelation);
 
     Relation rel(accWrap->RelationByType(relationTypes[i]));
     nsTArray<AtkObject*> targets;
     nsAccessible* tempAcc = nsnull;
     while ((tempAcc = rel.Next()))
       targets.AppendElement(nsAccessibleWrap::GetAtkObject(tempAcc));
 
-    atkRelation = atk_relation_new(targets.Elements(), targets.Length(), atkType);
-    atk_relation_set_add(relation_set, atkRelation);
-    g_object_unref(atkRelation);
+    if (targets.Length()) {
+      atkRelation = atk_relation_new(targets.Elements(), targets.Length(), atkType);
+      atk_relation_set_add(relation_set, atkRelation);
+      g_object_unref(atkRelation);
+    }
   }
 
   return relation_set;
 }
 
 // Check if aAtkObj is a valid MaiAtkObject, and return the nsAccessibleWrap
 // for it.
 nsAccessibleWrap *GetAccessibleWrap(AtkObject *aAtkObj)
--- a/browser/base/content/sanitize.js
+++ b/browser/base/content/sanitize.js
@@ -151,20 +151,19 @@ Sanitizer.prototype = {
           }
         }
         else {
           // Remove everything
           cookieMgr.removeAll();
         }
 
         // Clear plugin data.
-        let ph = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
         const phInterface = Ci.nsIPluginHost;
         const FLAG_CLEAR_ALL = phInterface.FLAG_CLEAR_ALL;
-        ph.QueryInterface(phInterface);
+        let ph = Cc["@mozilla.org/plugin/host;1"].getService(phInterface);
 
         // Determine age range in seconds. (-1 means clear all.) We don't know
         // that this.range[1] is actually now, so we compute age range based
         // on the lower bound. If this.range results in a negative age, do
         // nothing.
         let age = this.range ? (Date.now() / 1000 - this.range[0] / 1000000)
                              : -1;
         if (!this.range || age >= 0) {
@@ -190,23 +189,23 @@ Sanitizer.prototype = {
         var psvc = Components.classes["@mozilla.org/preferences-service;1"]
                              .getService(Components.interfaces.nsIPrefService);
         try {
             var branch = psvc.getBranch("geo.wifi.access_token.");
             branch.deleteBranch("");
         } catch (e) {}
 
       },
-      
+
       get canClear()
       {
         return true;
       }
     },
-    
+
     offlineApps: {
       clear: function ()
       {
         const Cc = Components.classes;
         const Ci = Components.interfaces;
         var cacheService = Cc["@mozilla.org/network/cache-service;1"].
                            getService(Ci.nsICacheService);
         try {
--- a/browser/base/content/syncAddDevice.xul
+++ b/browser/base/content/syncAddDevice.xul
@@ -115,30 +115,30 @@
            onclick="gSyncAddDevice.goToSyncKeyPage();"/>
   </wizardpage>
 
   <!-- Need a non-empty label here, otherwise we get a default label on Mac -->
   <wizardpage id="syncKeyPage"
               label=" "
               onpageshow="gSyncAddDevice.onPageShow();">
     <description>
-      &addDevice.dialog.syncKey.label;
+      &addDevice.dialog.recoveryKey.label;
     </description>
     <spacer/>
 
     <groupbox>
-      <label value="&syncKeyEntry.label;"
-             accesskey="&syncKeyEntry.accesskey;"
+      <label value="&recoveryKeyEntry.label;"
+             accesskey="&recoveryKeyEntry.accesskey;"
              control="weavePassphrase"/>
       <textbox id="weavePassphrase"
                readonly="true"/>
     </groupbox>
 
     <groupbox align="center">
-      <description>&syncKeyBackup.description;</description>
+      <description>&recoveryKeyBackup.description;</description>
       <hbox>
         <button id="printSyncKeyButton"
                 label="&button.syncKeyBackup.print.label;"
                 accesskey="&button.syncKeyBackup.print.accesskey;"
                 oncommand="gSyncUtils.passphrasePrint('weavePassphrase');"/>
         <button id="saveSyncKeyButton"
                 label="&button.syncKeyBackup.save.label;"
                 accesskey="&button.syncKeyBackup.save.accesskey;"
--- a/browser/base/content/syncGenericChange.js
+++ b/browser/base/content/syncGenericChange.js
@@ -87,40 +87,40 @@ let Change = {
       Services.strings.createBundle("chrome://browser/locale/syncGenericChange.properties");
 
     switch (this._dialogType) {
       case "UpdatePassphrase":
       case "ResetPassphrase":
         document.getElementById("textBox1Row").hidden = true;
         document.getElementById("textBox2Row").hidden = true;
         document.getElementById("passphraseLabel").value
-          = this._str("new.synckey.label");
+          = this._str("new.recoverykey.label");
         document.getElementById("passphraseSpacer").hidden = false;
 
         if (this._updatingPassphrase) {
           document.getElementById("passphraseHelpBox").hidden = false;
-          document.title = this._str("new.synckey.title");
-          introText.textContent = this._str("new.synckey2.introText");
+          document.title = this._str("new.recoverykey.title");
+          introText.textContent = this._str("new.recoverykey.introText");
           this._dialog.getButton("finish").label
-            = this._str("new.synckey.acceptButton");
+            = this._str("new.recoverykey.acceptButton");
         }
         else {
           document.getElementById("generatePassphraseButton").hidden = false;
           document.getElementById("passphraseBackupButtons").hidden = false;
           this._passphraseBox.setAttribute("readonly", "true");
           let pp = Weave.Service.passphrase;
           if (Weave.Utils.isPassphrase(pp))
              pp = Weave.Utils.hyphenatePassphrase(pp);
           this._passphraseBox.value = pp;
           this._passphraseBox.focus();
-          document.title = this._str("change.synckey2.title");
+          document.title = this._str("change.recoverykey.title");
           introText.textContent = this._str("change.synckey.introText2");
-          warningText.textContent = this._str("change.synckey2.warningText");
+          warningText.textContent = this._str("change.recoverykey.warningText");
           this._dialog.getButton("finish").label
-            = this._str("change.synckey.acceptButton");
+            = this._str("change.recoverykey.acceptButton");
           if (this._duringSetup) {
             this._dialog.getButton("finish").disabled = false;
           }
         }
         break;
       case "ChangePassword":
         document.getElementById("passphraseRow").hidden = true;
         let box1label = document.getElementById("textBox1Label");
@@ -132,17 +132,17 @@ let Change = {
           introText.textContent = this._str("new.password.introText");
           this._dialog.getButton("finish").label
             = this._str("new.password.acceptButton");
           document.getElementById("textBox2Row").hidden = true;
         }
         else {
           document.title = this._str("change.password.title");
           box2label.value = this._str("new.password.confirm");
-          introText.textContent = this._str("change.password2.introText");
+          introText.textContent = this._str("change.password3.introText");
           warningText.textContent = this._str("change.password.warningText");
           this._dialog.getButton("finish").label
             = this._str("change.password.acceptButton");
         }
         break;
     }
     document.getElementById("change-page")
             .setAttribute("label", document.title);
@@ -190,30 +190,30 @@ let Change = {
     this._dialog.getButton("finish").disabled = false;
   },
 
   doChangePassphrase: function Change_doChangePassphrase() {
     let pp = Weave.Utils.normalizePassphrase(this._passphraseBox.value);
     if (this._updatingPassphrase) {
       Weave.Service.passphrase = pp;
       if (Weave.Service.login()) {
-        this._updateStatus("change.synckey2.success", "success");
+        this._updateStatus("change.recoverykey.success", "success");
         Weave.Service.persistLogin();
       }
       else {
         this._updateStatus("new.passphrase.status.incorrect", "error");
       }
     }
     else {
-      this._updateStatus("change.synckey.label", "active");
+      this._updateStatus("change.recoverykey.label", "active");
 
       if (Weave.Service.changePassphrase(pp))
-        this._updateStatus("change.synckey2.success", "success");
+        this._updateStatus("change.recoverykey.success", "success");
       else
-        this._updateStatus("change.synckey2.error", "error");
+        this._updateStatus("change.recoverykey.error", "error");
     }
 
     return false;
   },
 
   doChangePassword: function Change_doChangePassword() {
     if (this._currentPasswordInvalid) {
       Weave.Service.password = this._firstBox.value;
--- a/browser/base/content/syncGenericChange.xul
+++ b/browser/base/content/syncGenericChange.xul
@@ -133,17 +133,17 @@
               label="&button.syncKeyBackup.save.label;"
               accesskey="&button.syncKeyBackup.save.accesskey;"
               oncommand="gSyncUtils.passphraseSave('passphraseBox');"/>
     </hbox>
 
     <vbox id="passphraseHelpBox"
           hidden="true">
       <description>
-        &existingSyncKey.description;
+        &existingRecoveryKey.description;
         <label class="text-link"
                href="https://services.mozilla.com/sync/help/manual-setup">
           &addDevice.showMeHow.label;
         </label>
       </description>
     </vbox>
 
     <spacer id="passphraseSpacer"
--- a/browser/base/content/syncSetup.xul
+++ b/browser/base/content/syncSetup.xul
@@ -191,35 +191,35 @@
               &setup.tosAgree3.label;
             </description>
           </hbox>
         </row>
       </rows>
     </grid>
   </wizardpage>
 
-  <wizardpage label="&setup.newSyncKeyPage.title.label;"
+  <wizardpage label="&setup.newRecoveryKeyPage.title.label;"
               onextra1="gSyncSetup.onSyncOptions()"
               onpageshow="gSyncSetup.onPageShow();">
     <description>
-      &setup.newSyncKeyPage.description.label;
+      &setup.newRecoveryKeyPage.description.label;
     </description>
     <spacer/>
 
     <groupbox>
-      <label value="&syncKeyEntry.label;"
-             accesskey="&syncKeyEntry.accesskey;"
+      <label value="&recoveryKeyEntry.label;"
+             accesskey="&recoveryKeyEntry.accesskey;"
              control="weavePassphrase"/>
       <textbox id="weavePassphrase"
                readonly="true"
                onfocus="this.select();"/>
     </groupbox>
 
     <groupbox align="center">
-      <description>&syncKeyBackup.description;</description>
+      <description>&recoveryKeyBackup.description;</description>
       <hbox>
         <button id="printSyncKeyButton"
                 label="&button.syncKeyBackup.print.label;"
                 accesskey="&button.syncKeyBackup.print.accesskey;"
                 oncommand="gSyncUtils.passphrasePrint('weavePassphrase');"/>
         <button id="saveSyncKeyButton"
                 label="&button.syncKeyBackup.save.label;"
                 accesskey="&button.syncKeyBackup.save.accesskey;"
@@ -346,18 +346,18 @@
               </vbox>
             </hbox>
           </row>
         </rows>
       </grid>
 
     <groupbox>
       <label id="existingPassphraseLabel"
-             value="&signIn.syncKey.label;"
-             accesskey="&signIn.syncKey.accesskey;"
+             value="&signIn.recoveryKey.label;"
+             accesskey="&signIn.recoveryKey.accesskey;"
              control="existingPassphrase"/>
       <textbox id="existingPassphrase"
                oninput="gSyncSetup.checkFields()"/>
       <hbox id="login-throbber" hidden="true">
         <image/>
         <label value="&verifying.label;"/>
       </hbox>
       <vbox align="left" id="existingPassphraseFeedbackRow" hidden="true">
@@ -365,17 +365,17 @@
           <image class="statusIcon"/>
           <label class="status" value=" "/>
         </hbox>
       </vbox>
     </groupbox>
 
     <vbox id="passphraseHelpBox">
       <description>
-        &existingSyncKey.description;
+        &existingRecoveryKey.description;
         <label class="text-link"
                href="https://services.mozilla.com/sync/help/manual-setup">
           &addDevice.showMeHow.label;
         </label>
         <spacer id="passphraseHelpSpacer"/>
         <label class="text-link"
                onclick="gSyncSetup.resetPassphrase(); return false;">
           &resetSyncKey.label;
--- a/browser/base/content/syncUtils.js
+++ b/browser/base/content/syncUtils.js
@@ -188,18 +188,18 @@ let gSyncUtils = {
   },
 
   /**
    * Save passphrase backup document to disk as HTML file.
    * 
    * @param elid : ID of the form element containing the passphrase.
    */
   passphraseSave: function(elid) {
-    let dialogTitle = this.bundle.GetStringFromName("save.synckey.title");
-    let defaultSaveName = this.bundle.GetStringFromName("save.default.label");
+    let dialogTitle = this.bundle.GetStringFromName("save.recoverykey.title");
+    let defaultSaveName = this.bundle.GetStringFromName("save.recoverykey.defaultfilename");
     this._preparePPiframe(elid, function(iframe) {
       let filepicker = Cc["@mozilla.org/filepicker;1"]
                          .createInstance(Ci.nsIFilePicker);
       filepicker.init(window, dialogTitle, Ci.nsIFilePicker.modeSave);
       filepicker.appendFilters(Ci.nsIFilePicker.filterHTML);
       filepicker.defaultString = defaultSaveName;
       let rv = filepicker.show();
       if (rv == Ci.nsIFilePicker.returnOK
@@ -238,17 +238,17 @@ let gSyncUtils = {
       valid = val1.length >= Weave.MIN_PASS_LENGTH;
     else if (val1 && val1 == Weave.Service.username)
       error = "change.password.pwSameAsUsername";
     else if (val1 && val1 == Weave.Service.account)
       error = "change.password.pwSameAsEmail";
     else if (val1 && val1 == Weave.Service.password)
       error = "change.password.pwSameAsPassword";
     else if (val1 && val1 == Weave.Service.passphrase)
-      error = "change.password.pwSameAsSyncKey";
+      error = "change.password.pwSameAsRecoveryKey";
     else if (val1 && val2) {
       if (val1 == val2 && val1.length >= Weave.MIN_PASS_LENGTH)
         valid = true;
       else if (val1.length < Weave.MIN_PASS_LENGTH)
         error = "change.password.tooShort";
       else if (val1 != val2)
         error = "change.password.mismatch";
     }
--- a/browser/base/content/test/browser_sanitizeDialog.js
+++ b/browser/base/content/test/browser_sanitizeDialog.js
@@ -51,18 +51,16 @@
  */
 
 Cc["@mozilla.org/moz/jssubscript-loader;1"].
   getService(Ci.mozIJSSubScriptLoader).
   loadSubScript("chrome://browser/content/sanitize.js");
 
 const dm = Cc["@mozilla.org/download-manager;1"].
            getService(Ci.nsIDownloadManager);
-const bhist = Cc["@mozilla.org/browser/global-history;2"].
-              getService(Ci.nsIBrowserHistory);
 const formhist = Cc["@mozilla.org/satchel/form-history;1"].
                  getService(Ci.nsIFormHistory2);
 
 // Add tests here.  Each is a function that's called by doNextTest().
 var gAllTests = [
 
   /**
    * Initializes the dialog to its default state.
@@ -578,17 +576,17 @@ WindowHelper.prototype = {
         wh.win = win;
 
         executeSoon(function () {
           // Some exceptions that reach here don't reach the test harness, but
           // ok()/is() do...
           try {
             if (wh.onunload)
               wh.onunload();
-            doNextTest();
+            waitForAsyncUpdates(doNextTest);
           }
           catch (exc) {
             win.close();
             ok(false, "Unexpected exception: " + exc + "\n" + exc.stack);
             finish();
           }
         });
       }, false);
@@ -693,35 +691,70 @@ function addFormEntryWithMinutesAgo(aMin
 /**
  * Adds a history visit to history.
  *
  * @param aMinutesAgo
  *        The visit will be visited this many minutes ago
  */
 function addHistoryWithMinutesAgo(aMinutesAgo) {
   let pURI = makeURI("http://" + aMinutesAgo + "-minutes-ago.com/");
-  bhist.addPageWithDetails(pURI,
-                           aMinutesAgo + " minutes ago",
-                           now_uSec - (aMinutesAgo * 60 * 1000 * 1000));
-  is(bhist.isVisited(pURI), true,
+  PlacesUtils.bhistory
+             .addPageWithDetails(pURI,
+                                 aMinutesAgo + " minutes ago",
+                                 now_uSec - (aMinutesAgo * 60 * 1000 * 1000));
+  is(PlacesUtils.bhistory.isVisited(pURI), true,
      "Sanity check: history visit " + pURI.spec +
      " should exist after creating it");
   return pURI;
 }
 
 /**
  * Removes all history visits, downloads, and form entries.
  */
 function blankSlate() {
-  bhist.removeAllPages();
+  PlacesUtils.bhistory.removeAllPages();
   dm.cleanUp();
   formhist.removeAllEntries();
 }
 
 /**
+ * Waits for all pending async statements on the default connection, before
+ * proceeding with aCallback.
+ *
+ * @param aCallback
+ *        Function to be called when done.
+ * @param aScope
+ *        Scope for the callback.
+ * @param aArguments
+ *        Arguments array for the callback.
+ *
+ * @note The result is achieved by asynchronously executing a query requiring
+ *       a write lock.  Since all statements on the same connection are
+ *       serialized, the end of this write operation means that all writes are
+ *       complete.  Note that WAL makes so that writers don't block readers, but
+ *       this is a problem only across different connections.
+ */
+function waitForAsyncUpdates(aCallback, aScope, aArguments)
+{
+  let scope = aScope || this;
+  let args = aArguments || [];
+  let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
+                              .DBConnection;
+  db.createAsyncStatement("BEGIN EXCLUSIVE").executeAsync();
+  db.createAsyncStatement("COMMIT").executeAsync({
+    handleResult: function() {},
+    handleError: function() {},
+    handleCompletion: function(aReason)
+    {
+      aCallback.apply(scope, args);
+    }
+  });
+}
+
+/**
  * Ensures that the given pref is the expected value.
  *
  * @param aPrefName
  *        The pref's sub-branch under the privacy branch
  * @param aExpectedVal
  *        The pref's expected value
  * @param aMsg
  *        Passed to is()
@@ -753,17 +786,17 @@ function downloadExists(aID)
 
 /**
  * Runs the next test in the gAllTests array.  If all tests have been run,
  * finishes the entire suite.
  */
 function doNextTest() {
   if (gAllTests.length <= gCurrTest) {
     blankSlate();
-    finish();
+    waitForAsyncUpdates(finish);
   }
   else {
     let ct = gCurrTest;
     gCurrTest++;
     gAllTests[ct]();
   }
 }
 
@@ -805,17 +838,17 @@ function ensureFormEntriesClearedState(a
  * @param aURIs
  *        Array of page URIs
  * @param aShouldBeCleared
  *        True if each visit to the URI should be cleared, false otherwise
  */
 function ensureHistoryClearedState(aURIs, aShouldBeCleared) {
   let niceStr = aShouldBeCleared ? "no longer" : "still";
   aURIs.forEach(function (aURI) {
-    is(bhist.isVisited(aURI), !aShouldBeCleared,
+    is(PlacesUtils.bhistory.isVisited(aURI), !aShouldBeCleared,
        "history visit " + aURI.spec + " should " + niceStr + " exist");
   });
 }
 
 /**
  * Ensures that the given pref is the expected value.
  *
  * @param aPrefName
@@ -831,10 +864,10 @@ function intPrefIs(aPrefName, aExpectedV
 
 ///////////////////////////////////////////////////////////////////////////////
 
 function test() {
   requestLongerTimeout(2);
   blankSlate();
   waitForExplicitFinish();
   // Kick off all the tests in the gAllTests array.
-  doNextTest();
+  waitForAsyncUpdates(doNextTest);
 }
--- a/browser/base/content/test/browser_sanitizeDialog_treeView.js
+++ b/browser/base/content/test/browser_sanitizeDialog_treeView.js
@@ -50,18 +50,16 @@
  */
 
 Cc["@mozilla.org/moz/jssubscript-loader;1"].
   getService(Ci.mozIJSSubScriptLoader).
   loadSubScript("chrome://browser/content/sanitize.js");
 
 const dm = Cc["@mozilla.org/download-manager;1"].
            getService(Ci.nsIDownloadManager);
-const bhist = Cc["@mozilla.org/browser/global-history;2"].
-              getService(Ci.nsIBrowserHistory);
 const formhist = Cc["@mozilla.org/satchel/form-history;1"].
                  getService(Ci.nsIFormHistory2);
 
 // Add tests here.  Each is a function that's called by doNextTest().
 var gAllTests = [
 
   /**
    * Moves the grippy around, makes sure it works OK.
@@ -497,35 +495,70 @@ function addFormEntryWithMinutesAgo(aMin
 /**
  * Adds a history visit to history.
  *
  * @param aMinutesAgo
  *        The visit will be visited this many minutes ago
  */
 function addHistoryWithMinutesAgo(aMinutesAgo) {
   let pURI = makeURI("http://" + aMinutesAgo + "-minutes-ago.com/");
-  bhist.addPageWithDetails(pURI,
-                           aMinutesAgo + " minutes ago",
-                           now_uSec - (aMinutesAgo * 60 * 1000 * 1000));
-  is(bhist.isVisited(pURI), true,
+  PlacesUtils.bhistory
+             .addPageWithDetails(pURI,
+                                 aMinutesAgo + " minutes ago",
+                                 now_uSec - (aMinutesAgo * 60 * 1000 * 1000));
+  is(PlacesUtils.bhistory.isVisited(pURI), true,
      "Sanity check: history visit " + pURI.spec +
      " should exist after creating it");
   return pURI;
 }
 
 /**
  * Removes all history visits, downloads, and form entries.
  */
 function blankSlate() {
-  bhist.removeAllPages();
+  PlacesUtils.bhistory.removeAllPages();
   dm.cleanUp();
   formhist.removeAllEntries();
 }
 
 /**
+ * Waits for all pending async statements on the default connection, before
+ * proceeding with aCallback.
+ *
+ * @param aCallback
+ *        Function to be called when done.
+ * @param aScope
+ *        Scope for the callback.
+ * @param aArguments
+ *        Arguments array for the callback.
+ *
+ * @note The result is achieved by asynchronously executing a query requiring
+ *       a write lock.  Since all statements on the same connection are
+ *       serialized, the end of this write operation means that all writes are
+ *       complete.  Note that WAL makes so that writers don't block readers, but
+ *       this is a problem only across different connections.
+ */
+function waitForAsyncUpdates(aCallback, aScope, aArguments)
+{
+  let scope = aScope || this;
+  let args = aArguments || [];
+  let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
+                              .DBConnection;
+  db.createAsyncStatement("BEGIN EXCLUSIVE").executeAsync();
+  db.createAsyncStatement("COMMIT").executeAsync({
+    handleResult: function() {},
+    handleError: function() {},
+    handleCompletion: function(aReason)
+    {
+      aCallback.apply(scope, args);
+    }
+  });
+}
+
+/**
  * Checks to see if the download with the specified ID exists.
  *
  * @param  aID
  *         The ID of the download to check
  * @return True if the download exists, false otherwise
  */
 function downloadExists(aID)
 {
@@ -543,17 +576,17 @@ function downloadExists(aID)
 
 /**
  * Runs the next test in the gAllTests array.  If all tests have been run,
  * finishes the entire suite.
  */
 function doNextTest() {
   if (gAllTests.length <= gCurrTest) {
     blankSlate();
-    finish();
+    waitForAsyncUpdates(finish);
   }
   else {
     let ct = gCurrTest;
     gCurrTest++;
     gAllTests[ct]();
   }
 }
 
@@ -595,17 +628,17 @@ function ensureFormEntriesClearedState(a
  * @param aURIs
  *        Array of page URIs
  * @param aShouldBeCleared
  *        True if each visit to the URI should be cleared, false otherwise
  */
 function ensureHistoryClearedState(aURIs, aShouldBeCleared) {
   let niceStr = aShouldBeCleared ? "no longer" : "still";
   aURIs.forEach(function (aURI) {
-    is(bhist.isVisited(aURI), !aShouldBeCleared,
+    is(PlacesUtils.bhistory.isVisited(aURI), !aShouldBeCleared,
        "history visit " + aURI.spec + " should " + niceStr + " exist");
   });
 }
 
 /**
  * Opens the sanitize dialog and runs a callback once it's finished loading.
  * 
  * @param aOnloadCallback
@@ -620,17 +653,17 @@ function openWindow(aOnloadCallback) {
     let win = aSubject.QueryInterface(Ci.nsIDOMWindow);
     win.addEventListener("load", function onload(event) {
       win.removeEventListener("load", onload, false);
       executeSoon(function () {
         // Some exceptions that reach here don't reach the test harness, but
         // ok()/is() do...
         try {
           aOnloadCallback(win);
-          doNextTest();
+          waitForAsyncUpdates(doNextTest);
         }
         catch (exc) {
           win.close();
           ok(false, "Unexpected exception: " + exc + "\n" + exc.stack);
           finish();
         }
       });
     }, false);
@@ -644,10 +677,10 @@ function openWindow(aOnloadCallback) {
 }
 
 ///////////////////////////////////////////////////////////////////////////////
 
 function test() {
   blankSlate();
   waitForExplicitFinish();
   // Kick off all the tests in the gAllTests array.
-  doNextTest();
+  waitForAsyncUpdates(doNextTest);
 }
--- a/browser/components/places/tests/browser/browser_bookmarksProperties.js
+++ b/browser/components/places/tests/browser/browser_bookmarksProperties.js
@@ -531,17 +531,17 @@ function test() {
 }
 
 function runNextTest() {
   // Cleanup from previous test.
   if (gCurrentTest) {
     gCurrentTest.cleanup();
     info("End of test: " + gCurrentTest.desc);
     gCurrentTest = null;
-    executeSoon(runNextTest);
+    waitForAsyncUpdates(runNextTest);
     return;
   }
 
   if (gTests.length > 0) {
     // Goto next tests.
     gCurrentTest = gTests.shift();
     info("Start of test: " + gCurrentTest.desc);
     gCurrentTest.setup();
--- a/browser/components/places/tests/browser/browser_library_infoBox.js
+++ b/browser/components/places/tests/browser/browser_library_infoBox.js
@@ -141,18 +141,17 @@ gTests.push({
     checkInfoBoxSelected(PO);
     ok(!infoBoxExpanderWrapper.hidden,
        "Expander button is not hidden for second bookmark item.");
     checkAddInfoFieldsNotCollapsed(PO);
     checkAddInfoFields(PO, "second bookmark item");
 
     menuNode.containerOpen = false;
 
-    bhist.removeAllPages();
-    nextTest();
+    waitForClearHistory(nextTest);
   }
 });
 
 function checkInfoBoxSelected(PO) {
   is(getAndCheckElmtById("detailsDeck").selectedIndex, 1,
      "Selected element in detailsDeck is infoBox.");
 }
 
--- a/browser/components/places/tests/browser/head.js
+++ b/browser/components/places/tests/browser/head.js
@@ -24,15 +24,56 @@ function openLibrary(callback, aLeftPane
                                   aLeftPaneRoot);
   waitForFocus(function () {
     callback(library);
   }, library);
 
   return library;
 }
 
+/**
+ * Waits for completion of a clear history operation, before
+ * proceeding with aCallback.
+ *
+ * @param aCallback
+ *        Function to be called when done.
+ */
 function waitForClearHistory(aCallback) {
   Services.obs.addObserver(function observeCH(aSubject, aTopic, aData) {
     Services.obs.removeObserver(observeCH, PlacesUtils.TOPIC_EXPIRATION_FINISHED);
     aCallback();
   }, PlacesUtils.TOPIC_EXPIRATION_FINISHED, false);
   PlacesUtils.bhistory.removeAllPages();
 }
+
+/**
+ * Waits for all pending async statements on the default connection, before
+ * proceeding with aCallback.
+ *
+ * @param aCallback
+ *        Function to be called when done.
+ * @param aScope
+ *        Scope for the callback.
+ * @param aArguments
+ *        Arguments array for the callback.
+ *
+ * @note The result is achieved by asynchronously executing a query requiring
+ *       a write lock.  Since all statements on the same connection are
+ *       serialized, the end of this write operation means that all writes are
+ *       complete.  Note that WAL makes so that writers don't block readers, but
+ *       this is a problem only across different connections.
+ */
+function waitForAsyncUpdates(aCallback, aScope, aArguments)
+{
+  let scope = aScope || this;
+  let args = aArguments || [];
+  let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
+                              .DBConnection;
+  db.createAsyncStatement("BEGIN EXCLUSIVE").executeAsync();
+  db.createAsyncStatement("COMMIT").executeAsync({
+    handleResult: function() {},
+    handleError: function() {},
+    handleCompletion: function(aReason)
+    {
+      aCallback.apply(scope, args);
+    }
+  });
+}
--- a/browser/components/privatebrowsing/src/nsPrivateBrowsingService.js
+++ b/browser/components/privatebrowsing/src/nsPrivateBrowsingService.js
@@ -614,21 +614,19 @@ PrivateBrowsingService.prototype = {
       let enumerator = cm.getCookiesFromHost(aDomain);
       while (enumerator.hasMoreElements()) {
         let cookie = enumerator.getNext().QueryInterface(Ci.nsICookie);
         cm.remove(cookie.host, cookie.name, cookie.path, false);
       }
     }
 
     // Plugin data
-    let (ph = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost)) {
-      const phInterface = Ci.nsIPluginHost;
-      const FLAG_CLEAR_ALL = phInterface.FLAG_CLEAR_ALL;
-      ph.QueryInterface(phInterface);
-
+    const phInterface = Ci.nsIPluginHost;
+    const FLAG_CLEAR_ALL = phInterface.FLAG_CLEAR_ALL;
+    let (ph = Cc["@mozilla.org/plugin/host;1"].getService(phInterface)) {
       let tags = ph.getPluginTags();
       for (let i = 0; i < tags.length; i++) {
         try {
           ph.clearSiteData(tags[i], aDomain, FLAG_CLEAR_ALL, -1);
         } catch (e) {
           // Ignore errors from the plugin
         }
       }
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placestitle.js
+++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placestitle.js
@@ -37,89 +37,73 @@
 
 // This test makes sure that the title of existing history entries does not
 // change inside the private browsing mode.
 
 function test() {
   // initialization
   let pb = Cc["@mozilla.org/privatebrowsing;1"].
            getService(Ci.nsIPrivateBrowsingService);
-  let bhist = Cc["@mozilla.org/browser/global-history;2"].
-              getService(Ci.nsIBrowserHistory);
-  let histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
-                getService(Ci.nsINavHistoryService).
-                QueryInterface(Ci.nsPIPlacesDatabase);
   let cm = Cc["@mozilla.org/cookiemanager;1"].
            getService(Ci.nsICookieManager);
   waitForExplicitFinish();
 
   const TEST_URL = "http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/title.sjs";
 
-  function cleanup() {
-    // delete all history items
-    bhist.removeAllPages();
+  function waitForCleanup(aCallback) {
     // delete all cookies
     cm.removeAll();
+    // delete all history items
+    waitForClearHistory(aCallback);
   }
-  cleanup();
 
   let observer = {
     pass: 1,
-    onBeginUpdateBatch: function() {
-    },
-    onEndUpdateBatch: function() {
-    },
-    onVisit: function(aURI, aVisitID, aTime, aSessionId, aReferringId,
-                      aTransitionType, _added) {
-    },
     onTitleChanged: function(aURI, aPageTitle) {
       if (aURI.spec != TEST_URL)
         return;
       switch (this.pass++) {
       case 1: // the first time that the page is loaded
         is(aPageTitle, "No Cookie", "The page should be loaded without any cookie for the first time");
         gBrowser.selectedTab = gBrowser.addTab(TEST_URL);
         break;
       case 2: // the second time that the page is loaded
         is(aPageTitle, "Cookie", "The page should be loaded with a cookie for the second time");
-        cleanup();
-        gBrowser.selectedTab = gBrowser.addTab(TEST_URL);
+        waitForCleanup(function () {
+          gBrowser.selectedTab = gBrowser.addTab(TEST_URL);
+        });
         break;
       case 3: // before entering the private browsing mode
         is(aPageTitle, "No Cookie", "The page should be loaded without any cookie again");
         // enter private browsing mode
         pb.privateBrowsingEnabled = true;
         gBrowser.selectedTab = gBrowser.addTab(TEST_URL);
         executeSoon(function() {
-          histsvc.removeObserver(observer);
+          PlacesUtils.history.removeObserver(observer);
           pb.privateBrowsingEnabled = false;
-          while (gBrowser.browsers.length > 1)
+          while (gBrowser.browsers.length > 1) {
             gBrowser.removeCurrentTab();
-          cleanup();
-          finish();
+          }
+          waitForCleanup(finish);
         });
         break;
       default:
         ok(false, "Unexpected pass: " + (this.pass - 1));
       }
     },
-    onBeforeDeleteURI: function(aURI) {
-    },
-    onDeleteURI: function(aURI) {
-    },
-    onClearHistory: function() {
-    },
-    onPageChanged: function(aURI, aWhat, aValue) {
-    },
-    onDeleteVisits: function() {
-    },
-    QueryInterface: function(iid) {
-      if (iid.equals(Ci.nsINavHistoryObserver) ||
-          iid.equals(Ci.nsISupports)) {
-        return this;
-      }
-      throw Cr.NS_ERROR_NO_INTERFACE;
-    }
+
+    onBeginUpdateBatch: function () {},
+    onEndUpdateBatch: function () {},
+    onVisit: function () {},
+    onBeforeDeleteURI: function () {},
+    onDeleteURI: function () {},
+    onClearHistory: function () {},
+    onPageChanged: function () {},
+    onDeleteVisits: function() {},
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
   };
-  histsvc.addObserver(observer, false);
+  PlacesUtils.history.addObserver(observer, false);
 
-  gBrowser.selectedTab = gBrowser.addTab(TEST_URL);
+  waitForCleanup(function () {
+    gBrowser.selectedTab = gBrowser.addTab(TEST_URL);
+  });
 }
--- a/browser/components/privatebrowsing/test/browser/head.js
+++ b/browser/components/privatebrowsing/test/browser/head.js
@@ -4,8 +4,22 @@ registerCleanupFunction(function() {
            getService(Ci.nsIPrivateBrowsingService);
   ok(!pb.privateBrowsingEnabled, "Private browsing should be terminated after finishing the test");
   pb.privateBrowsingEnabled = false;
   try {
     Services.prefs.clearUserPref("browser.privatebrowsing.keep_current_session");
   } catch(e) {}
 });
 
+/**
+ * Waits for completion of a clear history operation, before
+ * proceeding with aCallback.
+ *
+ * @param aCallback
+ *        Function to be called when done.
+ */
+function waitForClearHistory(aCallback) {
+  Services.obs.addObserver(function observeCH(aSubject, aTopic, aData) {
+    Services.obs.removeObserver(observeCH, PlacesUtils.TOPIC_EXPIRATION_FINISHED);
+    aCallback();
+  }, PlacesUtils.TOPIC_EXPIRATION_FINISHED, false);
+  PlacesUtils.bhistory.removeAllPages();
+}
--- a/browser/locales/en-US/chrome/browser/syncGenericChange.properties
+++ b/browser/locales/en-US/chrome/browser/syncGenericChange.properties
@@ -1,35 +1,33 @@
-# LOCALIZATION NOTE (change.password.title): This (and associated change.password/passphrase) are used when the user elects to change their password.
+#LOCALIZATION NOTE (change.password.title): This (and associated change.password/passphrase) are used when the user elects to change their password.
 change.password.title = Change your Password
 change.password.acceptButton = Change Password
 change.password.status.active = Changing your password…
 change.password.status.success = Your password has been changed.
 change.password.status.error = There was an error changing your password.
 
-change.password2.introText = Your password must be at least 8 characters long.  It cannot be the same as either your user name or your Sync Key.
+change.password3.introText = Your password must be at least 8 characters long.  It cannot be the same as either your user name or your Recovery Key.
 change.password.warningText = Note: All of your other devices will be unable to connect to your account once you change this password.
 
-change.synckey2.title = My Sync Key
-change.synckey.acceptButton = Change Sync Key
-change.synckey.label = Changing Sync Key and uploading local data, please wait…
-change.synckey2.error = There was an error while changing your Sync Key!
-change.synckey2.success = Your Sync Key was successfully changed!
+change.recoverykey.title = My Recovery Key
+change.recoverykey.acceptButton = Change Recovery Key
+change.recoverykey.label = Changing Recovery Key and uploading local data, please wait…
+change.recoverykey.error = There was an error while changing your Recovery Key!
+change.recoverykey.success = Your Recovery Key was successfully changed!
 
-change.synckey.introText = Firefox Cares About Your Privacy
 change.synckey.introText2 = To ensure your total privacy, all of your data is encrypted prior to being uploaded. The key to decrypt your data is not uploaded.
-# LOCALIZATION NOTE (change.synckey2.warningText) "Sync" should match &syncBrand.shortName.label; from syncBrand.dtd
-change.synckey2.warningText = Note: Changing this will erase all data stored on the Sync server and upload new data secured by this Sync Key. Your other devices will not sync until the new Sync Key is entered for that device.
+# LOCALIZATION NOTE (change.recoverykey.warningText) "Sync" should match &syncBrand.shortName.label; from syncBrand.dtd
+change.recoverykey.warningText = Note: Changing this will erase all data stored on the Sync server and upload new data secured by this Recovery Key. Your other devices will not sync until the new Recovery Key is entered for that device.
 
-new.synckey.label = Your Sync Key
+new.recoverykey.label = Your Recovery Key
 
 # LOCALIZATION NOTE (new.password.title): This (and associated new.password/passphrase) are used on a second computer when it detects that your password or passphrase has been changed on a different device.
 new.password.title            = Update Password
 new.password.introText        = Your password was rejected by the server, please update your password.
 new.password.label            = Enter your new password
 new.password.confirm          = Confirm your new password
 new.password.acceptButton     = Update Password
 new.password.status.incorrect = Password incorrect, please try again.
 
-new.synckey.title          = Update Sync Key
-new.synckey2.introText       = Your Sync Key was changed using another device, please enter your updated Sync Key.
-new.synckey.acceptButton     = Update Sync Key
-new.synckey.status.incorrect = Sync Key incorrect, please try again.
+new.recoverykey.title          = Update Recovery Key
+new.recoverykey.introText      = Your Recovery Key was changed using another device, please enter your updated Recovery Key.
+new.recoverykey.acceptButton     = Update Recovery Key
--- a/browser/locales/en-US/chrome/browser/syncSetup.dtd
+++ b/browser/locales/en-US/chrome/browser/syncSetup.dtd
@@ -14,18 +14,18 @@
 <!-- New Account AND Existing Account -->
 <!ENTITY server.label               "Server">
 <!ENTITY serverType.main.label      "&syncBrand.fullName.label; Server">
 <!ENTITY serverType.custom2.label   "Use a custom server…">
 <!ENTITY signIn.account2.label      "Account">
 <!ENTITY signIn.account2.accesskey  "A">
 <!ENTITY signIn.password.label      "Password">
 <!ENTITY signIn.password.accesskey  "P">
-<!ENTITY signIn.syncKey.label       "Sync Key">
-<!ENTITY signIn.syncKey.accesskey   "K">
+<!ENTITY signIn.recoveryKey.label       "Recovery Key">
+<!ENTITY signIn.recoveryKey.accesskey   "K">
 
 <!-- New Account Page 1: Basic Account Info -->
 <!ENTITY setup.newAccountDetailsPage.title.label "Account Details">
 <!ENTITY setup.emailAddress.label     "Email Address">
 <!ENTITY setup.emailAddress.accesskey "E">
 <!ENTITY setup.choosePassword.label      "Choose a Password">
 <!ENTITY setup.choosePassword.accesskey  "P">
 <!ENTITY setup.confirmPassword.label     "Confirm Password">
@@ -36,22 +36,22 @@
 <!ENTITY setup.tosAgree1.accesskey  "a">
 <!ENTITY setup.tosLink.label        "Terms of Service">
 <!ENTITY setup.tosAgree2.label      "and the">
 <!ENTITY setup.ppLink.label         "Privacy Policy">
 <!ENTITY setup.tosAgree3.label      "">
 <!ENTITY setup.tosAgree2.accesskey  "">
 
 <!-- New Account Page 2: Sync Key -->
-<!ENTITY setup.newSyncKeyPage.title.label "&brandShortName; Cares About Your Privacy">
-<!ENTITY setup.newSyncKeyPage.description.label "To ensure your total privacy, all of your data is encrypted prior to being uploaded. The Sync Key which is necessary to decrypt your data is not uploaded.">
-<!ENTITY syncKeyEntry.label        "Your Sync Key">
-<!ENTITY syncKeyEntry.accesskey    "K">
+<!ENTITY setup.newRecoveryKeyPage.title.label "&brandShortName; Cares About Your Privacy">
+<!ENTITY setup.newRecoveryKeyPage.description.label "To ensure your total privacy, all of your data is encrypted prior to being uploaded. The Recovery Key which is necessary to decrypt your data is not uploaded.">
+<!ENTITY recoveryKeyEntry.label        "Your Recovery Key">
+<!ENTITY recoveryKeyEntry.accesskey    "K">
 <!ENTITY syncGenerateNewKey.label  "Generate a new key">
-<!ENTITY syncKeyBackup.description "Your Sync Key is required to access &syncBrand.fullName.label; on other machines. Please create a backup copy. We cannot help you recover your Sync Key.">
+<!ENTITY recoveryKeyBackup.description "Your Recovery Key is required to access &syncBrand.fullName.label; on other machines. Please create a backup copy. We cannot help you recover your Recovery Key.">
 
 <!ENTITY button.syncKeyBackup.print.label     "Print…">
 <!ENTITY button.syncKeyBackup.print.accesskey "P">
 <!ENTITY button.syncKeyBackup.save.label      "Save…">
 <!ENTITY button.syncKeyBackup.save.accesskey  "S">
 
 <!-- New Account Page 3: Captcha -->
 <!ENTITY setup.captchaPage2.title.label     "Please Confirm You're Not a Robot">
@@ -60,22 +60,22 @@
 <!ENTITY addDevice.showMeHow.label          "Show me how.">
 <!ENTITY addDevice.dontHaveDevice.label     "I don't have the device with me">
 <!ENTITY addDevice.setup.description.label  "To activate, go to &syncBrand.shortName.label; Options on your other device and select &#x0022;Add a Device&#x0022;.">
 <!ENTITY addDevice.setup.enterCode.label    "Then, enter this code:">
 <!ENTITY addDevice.dialog.description.label "To activate your new device, go to &syncBrand.shortName.label; Options on the device and select &#x0022;Connect.&#x0022;">
 <!ENTITY addDevice.dialog.enterCode.label   "Enter the code that the device provides:">
 <!ENTITY addDevice.dialog.tryAgain.label    "Please try again.">
 <!ENTITY addDevice.dialog.successful.label  "The device has been successfully added. The initial synchronization can take several minutes and will finish in the background.">
-<!ENTITY addDevice.dialog.syncKey.label     "To activate your device you will need to enter your Sync Key. Please print or save this key and take it with you.">
+<!ENTITY addDevice.dialog.recoveryKey.label     "To activate your device you will need to enter your Recovery Key. Please print or save this key and take it with you.">
 <!ENTITY addDevice.dialog.connected.label   "Device Connected">
 
 <!-- Existing Account Page 2: Manual Login -->
 <!ENTITY setup.signInPage.title.label "Sign In">
-<!ENTITY existingSyncKey.description "You can get a copy of your Sync Key by going to &syncBrand.shortName.label; Options on your other device, and selecting  &#x0022;My Sync Key&#x0022; under &#x0022;Manage Account&#x0022;.">
+<!ENTITY existingRecoveryKey.description "You can get a copy of your Recovery Key by going to &syncBrand.shortName.label; Options on your other device, and selecting  &#x0022;My Recovery Key&#x0022; under &#x0022;Manage Account&#x0022;.">
 <!ENTITY verifying.label              "Verifying…">
 <!ENTITY resetPassword.label          "Reset Password">
 <!ENTITY resetSyncKey.label           "I have lost my other device.">
 
 <!-- Sync Options -->
 <!ENTITY setup.optionsPage.title      "Sync Options">
 <!ENTITY syncComputerName.label       "Computer Name:">
 <!ENTITY syncComputerName.accesskey   "c">
--- a/browser/locales/en-US/chrome/browser/syncSetup.properties
+++ b/browser/locales/en-US/chrome/browser/syncSetup.properties
@@ -24,18 +24,18 @@ bookmarksCount.label        = #1 bookmar
 # #1 is the number of days (was %S for a short while, use #1 instead, even if both work)
 historyDaysCount.label      = #1 day of history;#1 days of history
 # LOCALIZATION NOTE (passwordsCount.label):
 # Semi-colon list of plural forms. See:
 # http://developer.mozilla.org/en/docs/Localization_and_Plurals
 # #1 is the number of passwords (was %S for a short while, use #1 instead, even if both work)
 passwordsCount.label        = #1 password;#1 passwords
 
-save.synckey.title = Save Sync Key
-save.default.label = Firefox Sync Key.html
+save.recoverykey.title = Save Recovery Key
+save.recoverykey.defaultfilename = Firefox Recovery Key.html
 
 newAccount.action.label = Firefox Sync is now set up to automatically sync all of your browser data.
 newAccount.change.label = You can choose exactly what to sync by selecting Sync Options below.
 resetClient.change.label = Firefox Sync will now merge all this computer's browser data into your Sync account.
 wipeClient.change.label = Firefox Sync will now replace all of the browser data on this computer with the data in your Sync account.
 wipeRemote.change.label = Firefox Sync will now replace all of the browser data in your Sync account with the data on this computer.
 existingAccount.change.label = You can change this preference by selecting Sync Options below.
 
--- a/browser/themes/gnomestripe/browser/browser.css
+++ b/browser/themes/gnomestripe/browser/browser.css
@@ -598,28 +598,47 @@ toolbar[mode="full"] .toolbarbutton-1 > 
   list-style-image: url("moz-icon://stock/gtk-go-back-rtl?size=toolbar");
 }
 #back-button[disabled="true"]:-moz-locale-dir(rtl) {
   list-style-image: url("moz-icon://stock/gtk-go-back-rtl?size=toolbar&state=disabled");
 }
 
 #forward-button {
   list-style-image: url("moz-icon://stock/gtk-go-forward-ltr?size=toolbar");
+  -moz-transition: 250ms ease-out;
 }
-#forward-button[disabled="true"] {
-  list-style-image: url("moz-icon://stock/gtk-go-forward-ltr?size=toolbar&state=disabled");
-}
-
 #forward-button:-moz-locale-dir(rtl) {
   list-style-image: url("moz-icon://stock/gtk-go-forward-rtl?size=toolbar");
 }
-#forward-button[disabled="true"]:-moz-locale-dir(rtl) {
+
+toolbar:not([mode=icons]) #forward-button[disabled="true"] {
+  list-style-image: url("moz-icon://stock/gtk-go-forward-ltr?size=toolbar&state=disabled");
+}
+toolbar:not([mode=icons]) #forward-button[disabled="true"]:-moz-locale-dir(rtl) {
   list-style-image: url("moz-icon://stock/gtk-go-forward-rtl?size=toolbar&state=disabled");
 }
 
+toolbar[mode=icons] #forward-button[disabled="true"] {
+  -moz-transform: scale(0);
+  opacity: 0;
+  pointer-events: none;
+}
+toolbar[mode=icons] #forward-button[disabled="true"]:-moz-locale-dir(ltr) {
+  margin-left: -36px;
+}
+toolbar[mode=icons] #forward-button[disabled="true"]:-moz-locale-dir(rtl) {
+  margin-right: -36px;
+}
+toolbar[mode=icons][iconsize=small] #forward-button[disabled="true"]:-moz-locale-dir(ltr) {
+  margin-left: -28px;
+}
+toolbar[mode=icons][iconsize=small] #forward-button[disabled="true"]:-moz-locale-dir(rtl) {
+  margin-right: -28px;
+}
+
 #reload-button {
   list-style-image: url("moz-icon://stock/gtk-refresh?size=toolbar");
 }
 #reload-button[disabled="true"] {
   list-style-image: url("moz-icon://stock/gtk-refresh?size=toolbar&state=disabled");
 }
 
 #stop-button {
@@ -781,27 +800,27 @@ toolbar[iconsize="small"] #back-button[d
 }
 
 toolbar[iconsize="small"] #forward-button {
   list-style-image: url("moz-icon://stock/gtk-go-forward-ltr?size=menu");
 }
 .unified-nav-forward[_moz-menuactive] {
   list-style-image: url("moz-icon://stock/gtk-go-forward-ltr?size=menu") !important;
 }
-toolbar[iconsize="small"] #forward-button[disabled="true"] {
+toolbar[iconsize="small"]:not([mode=icons]) #forward-button[disabled="true"] {
   list-style-image: url("moz-icon://stock/gtk-go-forward-ltr?size=menu&state=disabled");
 }
 
 toolbar[iconsize="small"] #forward-button:-moz-locale-dir(rtl) {
   list-style-image: url("moz-icon://stock/gtk-go-forward-rtl?size=menu");
 }
 .unified-nav-forward[_moz-menuactive]:-moz-locale-dir(rtl) {
   list-style-image: url("moz-icon://stock/gtk-go-forward-rtl?size=menu") !important;
 }
-toolbar[iconsize="small"] #forward-button[disabled="true"]:-moz-locale-dir(rtl) {
+toolbar[iconsize="small"]:not([mode=icons]) #forward-button[disabled="true"]:-moz-locale-dir(rtl) {
   list-style-image: url("moz-icon://stock/gtk-go-forward-rtl?size=menu&state=disabled");
 }
 
 toolbar[iconsize="small"] #stop-button {
   list-style-image: url("moz-icon://stock/gtk-stop?size=menu");
 }
 toolbar[iconsize="small"] #stop-button[disabled="true"] {
   list-style-image: url("moz-icon://stock/gtk-stop?size=menu&state=disabled");
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -477,16 +477,17 @@ toolbar[mode="icons"] #forward-button:-m
   border-radius: 10000px;
 }
 
 #navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button:not(:-moz-lwtheme) {
   height: 31px;
   padding: 4px 5px 5px 3px;
   margin-bottom: -1px;
   background: url(chrome://browser/skin/keyhole-circle.png) 0 0 no-repeat;
+  border-radius: 0;
 }
 
 #navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button:-moz-window-inactive:not(:-moz-lwtheme) {
   background-position: -60px 0;
 }
 
 #navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button:not([disabled="true"]):active:hover:not(:-moz-lwtheme),
 #navigator-toolbox[iconsize="large"][mode="icons"] > #nav-bar #back-button[open="true"]:not(:-moz-lwtheme) {
index f164d498c351e2541fadcbfb9b1e7a8334a7e581..8c4cb3ba212f577a420eb96e57bef052c33021c0
GIT binary patch
literal 2581
zc$`I6c|4TcA7;2@Y)L3Yu4`nO(PV5FlQ3kjh|(fU8QGGu4>$MPw<~3hFd_*VG}*f}
zAtuJyW-KF<Ww@AOEO#Wom;CPi<9*-H=e*zNe80~*&-p$l;exHXFjyMQ#l<CTao+S2
z@O1_r`9plb+tZLb!NnyoZee=PA%t3=D`0(@a=g<^-`=-;_(dw&@rZh_hfn=b5jmN_
zoi)&yB0`4znqoC(&Hjtt!k@<f3G&W;!aSfuVmvFL<0q)!ASUS|kLA%yLCciscXfAD
zc6NISMx%1~R;(hsL+2uCySvMs4V&YEFl6=3mes`3(NSBs<SwbQ54*o<V`LR$uV^0A
z_Q~#Je(7l0P|AE(WD>^_I)0{v^qsQ>jv}FW6D}0m$aluG9Q*P>O{T74VVo$u@0ep4
zW8j4vfj~fMxU?FG)-mYE;2$2_$5oBA`r)@}u&l+GSD-jqkxqwww92LycrqJ=7jHYR
zdvB^NPurKXx-e7`pyM|lKhjXj?aR?M6RP=&c-PNinGn)r1f`J8nC+lP9NYNc-O@&(
zZ+U)1BuPS56{S+7*^BIy)Ku6dv8<ON46Ip7ZgzIIE>ce~bUYjG{t@&e_*28+1s4o8
zQItF|z?YSo33=J4!k2iGWyP}JFG?Y3{9VBB-6$+FX4XTwi%FU3$r4=O`Lj#RCEP+p
z?`!cRN5ez|1qftTM#AUz_3PumB<cnIJv!K(p<HI2b4JN)VX!=bTxt_8d{F+MNoJUc
zbuU`I_sHZ()r}<bW?Mq)wDNT4LnEP@C<Q6ux@HxGvcC6hZw_rf(3+-`q$TX3DUB{-
zpwd0djdUDdUzM(*E89NHe&q%s78vR)C@Q)Se*0&QE~S3ua9PES*1<ZPz@*Wk^a{IM
z9v)xk(&W!>%x}k;anmYAffD$f(ZkN@op&{wcX~s%rU^*~m_ErK84GP^bny*x_kHVc
z-t2jj{e$DBULPRD98J$UziR<GIXML{tg=4BTw2Fl+z5%5{he^Pc%``Oh<@W*Z5Idv
zyatqU9^<b;)qcEzE=mY`2&~!ev)o+HbAC~|ZzeQN0w|-)RNU7<sLisqSY1KERZ{U1
zR`Vh%$%)&LLZK`_RdZ@|s&tmHm-%qmN~8f@7z3e(I0V~?2naB?=Sf&G&ZKP}JRt~O
zoMQgecyTf_>PveJ_O54q4kY7|wp^@>l8X)cYU4=h=X`w~*Y3wk0Y`n8sP*v0;mV|{
z1LDOu@-@=XC=@El{g>S?4=Of=|K^2A9Bg9IGWlmaT)dD0vt1m$h;%;fHBf>8*ZNS-
z^Z_z-*Y+7b+!8=Hb22#zY*N3ejA*kevfT@GqGZF|%+)zhAQw%4G?Hh$NP2mpujAUF
ztwgtEdLsYL5RmW0rCG)$J4e@PE!BxU9skrx-0h?ac;O>S0CJI(<w*kuMRb-cD%Fdj
zav@*3yJHvN<qj?brmyc^GgSvh1R8^Hj(pX+!<r^wA5fZ99!nytmd5b<GCY7V610Jc
za&dpxT1tCLCoZ!%237ZgN5cT~%y!OWXZ>oj?jJ-qSzr<tixs*yOSBsNW0unRu)=%p
zbN=TWO+k9STu=n*BY=1~aF*=9)qae4wl4c^$QO$uQCY(<gjIf&M8|7h(Pk#^L`Nn=
z)4As=9!#e;1y^@i?=J&$&>|QaF#VzI<IF^_oAZ~Lva}6h%X%N%i*vW&U2c5z7-cj(
zqbflSrmU=-+x|DL?d+$2k^HoVz&ZDw%-LyvNwTblfeO2}%<lQB`f(VtHv1lsvvT>8
z*0e!GLqnBGoQU4)+8VZ(*QSp3UeGT8LA>MZ6`2@j{Sjc#$jYj!3zQ6HyV#et)${If
z469w7-JDmPpcX`H#e7yYPc>z{b<+|5K~>KSTKFx+ID+OD!BW+DP%hUrdY+*a=4`F8
zmvS1iFpz2(!Yo`Ht#QBD_?$vKNC|U?LO{vJQGEcco!se%m+vq63wtA&M09HeXwKKD
z+0!N(d-Ka|^KsAh0wDtjJU!f;+afWZ?zp>m;Y4P8hOyl+Y%~meSpKTD4v=uEZsygY
znmAGUpaLX@8o4~)a9&d{eB<>AUw~MKITT7f?f|WXA%Kl$VDn4+OG-+t7K9}83DxSL
zrKu-Ro*0L2996%PSpS}RdI14iqKYP*-Xm(#!&KYCg&aG5%P2dtN8b#dd&Sh=puMA`
z<0}Ohp>jQ9>OJ?Q<%1(9)QiRUWLBqTVME3sa!J8}(z>FfqYr5s2?ESt&M(f*ZFUzJ
zhEHlPlWFybTnw0DwIf9>W52W%ZI!`SL8#xld5crx-oi3iyb<*lQAiC94KsY|DR4=5
z#~r?XkxF2;H&=GgwMFinGV;cr^3M~>tz`AbFEdN~3zZfKTHeFS2r%9A40rC))<FTO
zW06lI)|2&DwpetSL}yjm<M_pq>M`j(#h2sZffZ}Qf`W@rpFTy2MG&q*=oP2|e#0>K
z{N>wco&A+$8=L*SN=4v_YgHCoMG0>w6&yqLQ>&4iKyOZe)iY6~)0>X>n@BvRqEe&9
zd!Mw=vT_!>-N(bj)AamoR6(GxYODJZ8xnhSQ*>z9Cr&knkN78r!|l0#XH&{2KKqTv
znB?BE!TzfI(c=Xw)_k||@Czr7*r(cwreJ>$%*lhkNMq4EH-*69g;E1PQ*rUcab5sb
zwKU_S>HB1E-fM~tI7O6iZ!c8(jrUOW9!7lW)6L76b^eCpZZ!+VGnU~$r>hp&sHu&0
z#EF^@^ZnP_TNWly=m&kPl;a<(={gPGSmGER^vrq*=}A(@&Pdp-I?1Z<+{Z4z<(bDr
zSy%3Np?IK(imkz^ilH$cqJ)c=ao~dXEhlb8hpu=W?o8e!;c_%GRm?;kaJGx`F21_!
z-sDoEa@d#cR``WUZSYnl^<?b+G?fbx-iVQ;&((;8>%%iy6~gTPRniSt29+00c0wj5
z?D;~oKIK(wn58a0d~;bKcU1N$Yk8t6nb`&Cz?|#<c0TB|t+2DrW~^;bO--fMiwzYJ
z%wjs*@TXM!OViwc_`u-TYk7K#2<w%9a9ZgTq>}sR(mVs}aNF2|Bj4Yf^8e>}TIlel
zo?Xv*7h(_tGo=nS_+EAGcX2csaH`(bp|;aP^8+t>RzM(7^!m!}bJU(lyREfYnf?Fq
zN@XxwWA9&f?2+$&(`*J=C)A*z=hqr<MYH6PpZ>kPl-_QYCL%d>9V-6K8>U@Y!*<w{
zxY$@+<D$rZ%w$0|ezqStQ?AAMEzpmdwRjRyq~>*~#vAYyRtmSyuKgadD_Sa7I0&6W
SGlA<Kmj%k!w95Ea^#1_v!6y;`
--- a/build/macosx/mozconfig.leopard
+++ b/build/macosx/mozconfig.leopard
@@ -5,9 +5,11 @@ fi
 if test -z "$CXX" ; then
    CXX=g++-4.2
 fi
 
 # We do 32 bit builds for leopard
 CC="$CC -arch i386"
 CXX="$CXX -arch i386"
 
+# Note, the version (10) is used by libffi's configure.
+ac_add_options --target=i386-apple-darwin10
 ac_add_options --with-macos-sdk=/Developer/SDKs/MacOSX10.5.sdk
--- a/build/macosx/universal/mozconfig.common
+++ b/build/macosx/universal/mozconfig.common
@@ -33,20 +33,20 @@
 # the terms of any one of the MPL, the GPL or the LGPL.
 #
 # ***** END LICENSE BLOCK *****
 
 mk_add_options MOZ_UNIFY_BDATE=1
 
 mk_add_options MOZ_POSTFLIGHT_ALL+=build/macosx/universal/flight.mk
 
-DARWIN_VERSION=`uname -r`
-ac_add_app_options ppc  --target=powerpc-apple-darwin$DARWIN_VERSION
-ac_add_app_options i386 --target=i386-apple-darwin$DARWIN_VERSION
-ac_add_app_options x86_64 --target=x86_64-apple-darwin$DARWIN_VERSION
+# Note, the version (10) is used by libffi's configure.
+ac_add_app_options ppc  --target=powerpc-apple-darwin10
+ac_add_app_options i386 --target=i386-apple-darwin10
+ac_add_app_options x86_64 --target=x86_64-apple-darwin10
 
 ac_add_app_options ppc --with-macos-sdk=/Developer/SDKs/MacOSX10.5.sdk
 ac_add_app_options i386 --with-macos-sdk=/Developer/SDKs/MacOSX10.5.sdk
 ac_add_app_options x86_64 --with-macos-sdk=/Developer/SDKs/MacOSX10.6.sdk
 
 # $MOZ_BUILD_APP is only defined when sourced by configure.  That's not a
 # problem, because the variables it affects only need to be set for
 # configure.
--- a/build/mobile/devicemanagerADB.py
+++ b/build/mobile/devicemanagerADB.py
@@ -1,40 +1,39 @@
 import subprocess
 from devicemanager import DeviceManager, DMError
 import re
 import os
+import sys
 
 class DeviceManagerADB(DeviceManager):
 
   def __init__(self, host = None, port = 20701, retrylimit = 5, packageName = None):
     self.host = host
     self.port = port
     self.retrylimit = retrylimit
     self.retries = 0
     self._sock = None
+    self.useRunAs = False
     if packageName == None:
       if os.getenv('USER'):
         packageName = 'org.mozilla.fennec_' + os.getenv('USER')
       else:
         packageName = 'org.mozilla.fennec_'
     self.Init(packageName)
 
   def Init(self, packageName):
     # Initialization code that may fail: Catch exceptions here to allow
     # successful initialization even if, for example, adb is not installed.
     try:
-      root = self.getDeviceRoot()
-      self.verifyPackage(packageName)
-      self.tmpDir = root + "/tmp"
-      if (not self.dirExists(self.tmpDir)):
-        self.mkDir(self.tmpDir)
+      self.verifyADB()
+      self.verifyRunAs(packageName)
     except:
+      self.useRunAs = False
       self.packageName = None
-      self.tmpDir = None
     try:
       # a test to see if we have root privs
       files = self.listFiles("/data/data")
       if (len(files) == 1):
         if (files[0].find("Permission denied") != -1):
           print "NOT running as root"
           raise Exception("not running as root")
     except:
@@ -46,17 +45,17 @@ class DeviceManagerADB(DeviceManager):
   # external function
   # returns:
   #  success: True
   #  failure: False
   def pushFile(self, localname, destname):
     try:
       if (os.name == "nt"):
         destname = destname.replace('\\', '/')
-      if (self.packageName):
+      if (self.useRunAs):
         remoteTmpFile = self.tmpDir + "/" + os.path.basename(localname)
         self.checkCmd(["push", os.path.realpath(localname), remoteTmpFile])
         self.checkCmdAs(["shell", "cp", remoteTmpFile, destname])
         self.checkCmd(["shell", "rm", remoteTmpFile])
       else:
         self.checkCmd(["push", os.path.realpath(localname), destname])
       if (self.isDir(destname)):
         destname = destname + "/" + os.path.basename(localname)
@@ -493,17 +492,17 @@ class DeviceManagerADB(DeviceManager):
     args.insert(0, "adb")
     return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
   def checkCmd(self, args):
     args.insert(0, "adb")
     return subprocess.check_call(args)
 
   def checkCmdAs(self, args):
-    if (self.packageName):
+    if (self.useRunAs):
       args.insert(1, "run-as")
       args.insert(2, self.packageName)
     return self.checkCmd(args)
 
   def chmodDir(self, remoteDir):
     if (self.isDir(remoteDir)):
       files = self.listFiles(remoteDir.strip())
       for f in files:
@@ -513,18 +512,49 @@ class DeviceManagerADB(DeviceManager):
           self.checkCmdAs(["shell", "chmod", "777", remoteDir.strip()])
           print "chmod " + remoteDir.strip()
       self.checkCmdAs(["shell", "chmod", "777", remoteDir])
       print "chmod " + remoteDir
     else:
       self.checkCmdAs(["shell", "chmod", "777", remoteDir.strip()])
       print "chmod " + remoteDir.strip()
 
-  def verifyPackage(self, packageName):
-    # If a valid package name is specified, it will be used for certain
-    # file operations, so that pushed files and directories are created
-    # by the uid associated with the package.
-    self.packageName = None
-    if (packageName):
-      data = self.runCmd(["shell", "run-as", packageName, "pwd"]).stdout.read()
-      if (not re.search('is unknown', data)):
+  def verifyADB(self):
+    # Check to see if adb itself can be executed.
+    try:
+      self.runCmd(["version"])
+    except Exception as (ex):
+      print "unable to execute ADB: ensure Android SDK is installed and adb is in your $PATH"
+    
+  def isCpAvailable(self):
+    # Some Android systems may not have a cp command installed,
+    # or it may not be executable by the user. 
+    data = self.runCmd(["shell", "cp"]).stdout.read()
+    if (re.search('Usage', data)):
+      return True
+    else:
+      print "unable to execute 'cp' on device; consider installing busybox from Android Market"
+      return False
+
+  def verifyRunAs(self, packageName):
+    # If a valid package name is available, and certain other
+    # conditions are met, devicemanagerADB can execute file operations
+    # via the "run-as" command, so that pushed files and directories 
+    # are created by the uid associated with the package, more closely
+    # echoing conditions encountered by Fennec at run time.
+    # Check to see if run-as can be used here, by verifying a 
+    # file copy via run-as.
+    self.useRunAs = False
+    devroot = self.getDeviceRoot()
+    if (packageName and self.isCpAvailable() and devroot):
+      self.tmpDir = devroot + "/tmp"
+      if (not self.dirExists(self.tmpDir)):
+        self.mkDir(self.tmpDir)
+      self.checkCmd(["shell", "run-as", packageName, "mkdir", devroot + "/sanity"])
+      self.checkCmd(["push", os.path.abspath(sys.argv[0]), self.tmpDir + "/tmpfile"])
+      self.checkCmd(["shell", "run-as", packageName, "cp", self.tmpDir + "/tmpfile", devroot + "/sanity"])
+      if (self.fileExists(devroot + "/sanity/tmpfile")):
+        print "will execute commands via run-as " + packageName
         self.packageName = packageName
-        print "package set: " + self.packageName
+        self.useRunAs = True
+      self.checkCmd(["shell", "rm", devroot + "/tmp/tmpfile"])
+      self.checkCmd(["shell", "run-as", packageName, "rm", "-r", devroot + "/sanity"])
+      
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -38,17 +38,16 @@
 
 # A netscape style .mk file for autoconf builds
 
 INCLUDED_AUTOCONF_MK = 1
 USE_AUTOCONF 	= 1
 MOZILLA_CLIENT	= 1
 target          = @target@
 ac_configure_args = @ac_configure_args@
-BUILD_MODULES	= @BUILD_MODULES@
 MOZILLA_VERSION = @MOZILLA_VERSION@
 FIREFOX_VERSION	= @FIREFOX_VERSION@
 
 MOZ_BUILD_APP = @MOZ_BUILD_APP@
 MOZ_APP_NAME	= @MOZ_APP_NAME@
 MOZ_APP_DISPLAYNAME = @MOZ_APP_DISPLAYNAME@
 MOZ_APP_BASENAME = @MOZ_APP_BASENAME@
 MOZ_APP_VENDOR = @MOZ_APP_VENDOR@
--- a/config/nsinstall_win.c
+++ b/config/nsinstall_win.c
@@ -36,16 +36,48 @@ static const char *sh_GetLastErrorMessag
 static BOOL sh_DoCopy(wchar_t *srcFileName, DWORD srcFileAttributes,
         wchar_t *dstFileName, DWORD dstFileAttributes,
         int force, int recursive);
 
 #define LONGPATH_PREFIX L"\\\\?\\"
 #define ARRAY_LEN(a) (sizeof(a) / sizeof(a[0]))
 #define STR_LEN(a) (ARRAY_LEN(a) - 1)
 
+#ifdef __MINGW32__
+
+/* MingW currently does not implement a wide version of the
+   startup routines.  Workaround is to implement something like
+   it ourselves. */
+
+#include <shellapi.h>
+
+int wmain(int argc, WCHAR **argv);
+
+int main(int argc, char **argv)
+{
+    int result;
+    wchar_t *commandLine = GetCommandLineW();
+    int argcw = 0;
+    wchar_t **_argvw = CommandLineToArgvW( commandLine, &argcw );
+    wchar_t *argvw[argcw + 1];
+    int i;
+    if (!_argvw)
+        return 127;
+    /* CommandLineToArgvW doesn't output the ending NULL so
+       we have to manually add it on */
+    for ( i = 0; i < argcw; i++ )
+        argvw[i] = _argvw[i];
+    argvw[argcw] = NULL;
+
+    result = wmain(argcw, argvw);
+    LocalFree(_argvw);
+    return result;
+}
+#endif /* __MINGW32__ */
+
 /* changes all forward slashes in token to backslashes */
 void changeForwardSlashesToBackSlashes ( wchar_t *arg )
 {
     if ( arg == NULL )
         return;
 
     while ( *arg ) {
         if ( *arg == '/' )
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -1148,18 +1148,19 @@ endif # OS/2
 	$(RM) $@
 	$(HOST_AR) $(HOST_AR_FLAGS) $(HOST_OBJS)
 	$(HOST_RANLIB) $@
 
 ifdef HAVE_DTRACE
 ifndef XP_MACOSX
 ifdef DTRACE_PROBE_OBJ
 ifndef DTRACE_LIB_DEPENDENT
-$(DTRACE_PROBE_OBJ):
-	dtrace -G -C -s $(MOZILLA_DTRACE_SRC) -o $(DTRACE_PROBE_OBJ)
+NON_DTRACE_OBJS := $(filter-out $(DTRACE_PROBE_OBJ),$(OBJS))
+$(DTRACE_PROBE_OBJ): $(NON_DTRACE_OBJS)
+	dtrace -G -C -s $(MOZILLA_DTRACE_SRC) -o $(DTRACE_PROBE_OBJ) $(NON_DTRACE_OBJS)
 endif
 endif
 endif
 endif
 
 # On Darwin (Mac OS X), dwarf2 debugging uses debug info left in .o files,
 # so instead of deleting .o files after repacking them into a dylib, we make
 # symlinks back to the originals. The symlinks are a no-op for stabs debugging,
@@ -1545,19 +1546,16 @@ ifeq ($(XPIDL_MODULE),) # we need $(XPID
 export:: FORCE
 	@echo
 	@echo "*** Error processing XPIDLSRCS:"
 	@echo "Please define MODULE or XPIDL_MODULE when defining XPIDLSRCS,"
 	@echo "so we have a module name to use when creating MODULE.xpt."
 	@echo; sleep 2; false
 endif
 
-$(IDL_DIR)::
-	$(NSINSTALL) -D $@
-
 # generate .h files from into $(XPIDL_GEN_DIR), then export to $(DIST)/include;
 # warn against overriding existing .h file. 
 $(XPIDL_GEN_DIR)/.done:
 	$(MKDIR) -p $(XPIDL_GEN_DIR)
 	@$(TOUCH) $@
 
 # don't depend on $(XPIDL_GEN_DIR), because the modification date changes
 # with any addition to the directory, regenerating all .h files -> everything.
@@ -1618,24 +1616,18 @@ export:: $(XPIDLSRCS) $(IDL_DIR)
 export:: $(patsubst %.idl,$(XPIDL_GEN_DIR)/%.h, $(XPIDLSRCS)) $(DIST)/include
 	$(INSTALL) $(IFLAGS1) $^ 
 endif # NO_DIST_INSTALL
 
 endif # XPIDLSRCS
 
 
 
-#
 # General rules for exporting idl files.
-#
-# WORK-AROUND ONLY, for mozilla/tools/module-deps/bootstrap.pl build.
-# Bug to fix idl dependency problems w/o this extra build pass is
-#   http://bugzilla.mozilla.org/show_bug.cgi?id=145777
-#
-$(IDL_DIR)::
+$(IDL_DIR):
 	$(NSINSTALL) -D $@
 
 export-idl:: $(SUBMAKEFILES) $(MAKE_DIRS)
 
 ifneq ($(XPIDLSRCS),)
 ifndef NO_DIST_INSTALL
 export-idl:: $(XPIDLSRCS) $(IDL_DIR)
 	$(INSTALL) $(IFLAGS1) $^
@@ -2092,17 +2084,16 @@ showhost:
 	@echo "HOST_EXTRA_LIBS    = $(HOST_EXTRA_LIBS)"
 	@echo "HOST_EXTRA_DEPS    = $(HOST_EXTRA_DEPS)"
 	@echo "HOST_PROGRAM       = $(HOST_PROGRAM)"
 	@echo "HOST_OBJS          = $(HOST_OBJS)"
 	@echo "HOST_PROGOBJS      = $(HOST_PROGOBJS)"
 	@echo "HOST_LIBRARY       = $(HOST_LIBRARY)"
 
 showbuildmods::
-	@echo "Build Modules	= $(BUILD_MODULES)"
 	@echo "Module dirs	= $(BUILD_MODULE_DIRS)"
 
 documentation:
 	@cd $(DEPTH)
 	$(DOXYGEN) $(DEPTH)/config/doxygen.cfg
 
 ifdef ENABLE_TESTS
 check:: $(SUBMAKEFILES) $(MAKE_DIRS)
--- a/configure.in
+++ b/configure.in
@@ -965,17 +965,16 @@ if test -n "$_WIN32_MSVC"; then
     SKIP_COMPILER_CHECKS=1
     SKIP_LIBRARY_CHECKS=1
 
     # Since we're skipping compiler and library checks, hard-code
     # some facts here.
     AC_DEFINE(HAVE_IO_H)
     AC_DEFINE(HAVE_SETBUF)
     AC_DEFINE(HAVE_ISATTY)
-    AC_DEFINE(HAVE_STDCALL)
 fi
 
 fi # COMPILE_ENVIRONMENT
 
 AC_SUBST(MIDL_FLAGS)
 AC_SUBST(_MSC_VER)
 
 AC_SUBST(GNU_AS)
@@ -2487,16 +2486,18 @@ ia64*-hpux*)
 
         if test $_MSC_VER -ge 1400; then
             LDFLAGS="$LDFLAGS -SAFESEH"
         fi
 
         if test -n "$GNU_CC"; then
             CFLAGS="$CFLAGS -mstackrealign"
             CXXFLAGS="$CXXFLAGS -mstackrealign"
+        else
+            AC_DEFINE(HAVE_STDCALL)
         fi
 
         MOZ_CHECK_HEADERS(mmintrin.h)
     	AC_DEFINE(_X86_)
 	;;
     x86_64-*)
         AC_DEFINE(_AMD64_)
         ;;
@@ -5180,17 +5181,17 @@ incorrect])
     PKG_CHECK_MODULES(_QTMOBILITY, QtSensors QtFeedback QtLocation,
                       MOZ_ENABLE_QTMOBILITY=1,
                       MOZ_ENABLE_QTMOBILITY=)
     if test "$MOZ_ENABLE_QTMOBILITY"; then
        MOZ_ENABLE_QTMOBILITY=1
        MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS $_QTMOBILITY_CFLAGS"
        MOZ_QT_LIBS="$MOZ_QT_LIBS $_QTMOBILITY_LIBS"
     else
-       AC_CHECK_LIB(QtSensors QtFeedback QtLocation, main, [
+       AC_CHECK_LIB(QtSensors, main, [
           MOZ_ENABLE_QTMOBILITY=1
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I/usr/include/qt4/QtMobility"
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I/usr/include/qt4/QtSensors"
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I/usr/include/qt4/QtFeedback"
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I/usr/include/qt4/QtLocation"
           MOZ_QT_LIBS="$MOZ_QT_LIBS -lQtSensors -lQtFeedback -lQtLocation"
        ])
     fi
--- a/content/base/public/nsIFrameMessageManager.idl
+++ b/content/base/public/nsIFrameMessageManager.idl
@@ -120,21 +120,26 @@ interface nsIInProcessContentFrameMessag
 
 [scriptable, uuid(6331bbca-2c9f-4766-b3c7-ae75554bf1ec)]
 interface nsITreeItemFrameMessageManager : nsIFrameMessageManager
 {
   readonly attribute unsigned long childCount;
   nsITreeItemFrameMessageManager getChildAt(in unsigned long aIndex);
 };
 
-[scriptable, uuid(23e6ef7b-8cc5-4e8b-9391-453440a3b858)]
+[scriptable, uuid(9e5c0526-aa4c-49f0-afbb-57f489cd9b59)]
 interface nsIChromeFrameMessageManager : nsITreeItemFrameMessageManager
 {
-  /*
+  /**
    * Load a script in the (remote) frame. aURL must be the absolute URL.
    * data: URLs are also supported. For example data:,dump("foo\n");
    * If aAllowDelayedLoad is true, script will be loaded when the
    * remote frame becomes available. Otherwise the script will be loaded
    * only if the frame is already available.
    */
   void loadFrameScript(in AString aURL, in boolean aAllowDelayedLoad);
+
+  /**
+   * Removes aURL from the list of scripts which support delayed load.
+   */
+  void removeDelayedFrameScript(in AString aURL);
 };
 
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -6120,17 +6120,17 @@ nsDocument::AdoptNode(nsIDOMNode *aAdopt
           if (node &&
               nsContentUtils::ContentIsDescendantOf(node, adoptedNode)) {
             return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
           }
         }
       } while ((doc = doc->GetParentDocument()));
 
       // Remove from parent.
-      nsINode* parent = adoptedNode->GetNodeParent();
+      nsCOMPtr<nsINode> parent = adoptedNode->GetNodeParent();
       if (parent) {
         rv = parent->RemoveChildAt(parent->IndexOf(adoptedNode), PR_TRUE);
         NS_ENSURE_SUCCESS(rv, rv);
       }
 
       break;
     }
     case nsIDOMNode::ENTITY_REFERENCE_NODE:
--- a/content/base/src/nsFrameMessageManager.cpp
+++ b/content/base/src/nsFrameMessageManager.cpp
@@ -172,16 +172,23 @@ nsFrameMessageManager::LoadFrameScript(c
       // Use PR_FALSE here, so that child managers don't cache the script, which
       // is already cached in the parent.
       mm->LoadFrameScript(aURL, PR_FALSE);
     }
   }
   return NS_OK;
 }
 
+NS_IMETHODIMP
+nsFrameMessageManager::RemoveDelayedFrameScript(const nsAString& aURL)
+{
+  mPendingScripts.RemoveElement(aURL);
+  return NS_OK;
+}
+
 static JSBool
 JSONCreator(const jschar* aBuf, uint32 aLen, void* aData)
 {
   nsAString* result = static_cast<nsAString*>(aData);
   result->Append((PRUnichar*)aBuf, (PRUint32)aLen);
   return JS_TRUE;
 }
 
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -615,17 +615,17 @@ nsINode::Normalize()
           tmpStr.Truncate();
           text->AppendTo(tmpStr);
           t->AppendTextForNormalize(tmpStr.get(), tmpStr.Length(), PR_TRUE, node);
         }
       }
     }
 
     // Remove node
-    nsINode* parent = node->GetNodeParent();
+    nsCOMPtr<nsINode> parent = node->GetNodeParent();
     NS_ASSERTION(parent || hasRemoveListeners,
                  "Should always have a parent unless "
                  "mutation events messed us up");
     if (parent) {
       parent->RemoveChildAt(parent->IndexOf(node), PR_TRUE);
     }
   }
 
@@ -3940,17 +3940,17 @@ nsINode::ReplaceOrInsertBefore(PRBool aR
   if (newContent->IsRootOfAnonymousSubtree()) {
     // This is anonymous content.  Don't allow its insertion
     // anywhere, since it might have UnbindFromTree calls coming
     // its way.
     return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
   }
 
   // Remove the new child from the old parent if one exists
-  nsINode* oldParent = newContent->GetNodeParent();
+  nsCOMPtr<nsINode> oldParent = newContent->GetNodeParent();
   if (oldParent) {
     PRInt32 removeIndex = oldParent->IndexOf(newContent);
     if (removeIndex < 0) {
       // newContent is anonymous.  We can't deal with this, so just bail
       NS_ERROR("How come our flags didn't catch this?");
       return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
     }
 
--- a/content/base/test/chrome/file_bug549682.xul
+++ b/content/base/test/chrome/file_bug549682.xul
@@ -62,16 +62,26 @@ https://bugzilla.mozilla.org/show_bug.cg
     localmm.loadFrameScript("data:,sendAsyncMessage('lasync', { data: 2345 })", false);
 
     messageManager.addMessageListener("async", asyncL);
     messageManager.addMessageListener("sync", syncL);
     global.addMessageListener("async", globalListener);
     global.addMessageListener("sync", globalListener);
     global.addMessageListener("global-sync", globalListener);
     global.loadFrameScript("data:,sendSyncMessage('global-sync', { data: 1234 });", true);
+    var toBeRemovedScript = "data:,sendAsyncMessage('toberemoved', { data: 2345 })";
+    var c = 0;
+    messageManager.addMessageListener("toberemoved", function() {
+      ++c;
+      opener.wrappedJSObject.is(c, 1, "Should be called only once!");
+    });
+    // This loads the script in the existing <browser>
+    messageManager.loadFrameScript(toBeRemovedScript, true);
+    // But it won't be loaded in the dynamically created <browser>
+    messageManager.removeDelayedFrameScript(toBeRemovedScript);
 
     var oldValue = globalListenerCallCount;
     var b = document.createElement("browser");
     b.setAttribute("type", "content");
     document.documentElement.appendChild(b);
     opener.wrappedJSObject.is(globalListenerCallCount, oldValue + 1,
                               "Wrong message count");
 
--- a/content/html/content/src/nsHTMLInputElement.cpp
+++ b/content/html/content/src/nsHTMLInputElement.cpp
@@ -2505,22 +2505,22 @@ nsHTMLInputElement::SanitizeValue(nsAStr
   NS_ASSERTION(!GET_BOOLBIT(mBitField, BF_PARSER_CREATING),
                "The element parsing should be finished!");
 
   switch (mType) {
     case NS_FORM_INPUT_TEXT:
     case NS_FORM_INPUT_SEARCH:
     case NS_FORM_INPUT_TEL:
     case NS_FORM_INPUT_PASSWORD:
-    case NS_FORM_INPUT_EMAIL:
       {
         PRUnichar crlf[] = { PRUnichar('\r'), PRUnichar('\n'), 0 };
         aValue.StripChars(crlf);
       }
       break;
+    case NS_FORM_INPUT_EMAIL:
     case NS_FORM_INPUT_URL:
       {
         PRUnichar crlf[] = { PRUnichar('\r'), PRUnichar('\n'), 0 };
         aValue.StripChars(crlf);
 
         aValue = nsContentUtils::TrimWhitespace<nsContentUtils::IsHTMLWhitespace>(aValue);
       }
       break;
--- a/content/html/content/test/forms/test_input_email.html
+++ b/content/html/content/test/forms/test_input_email.html
@@ -70,18 +70,22 @@ function testEmailAddress(aElement, aVal
 }
 
 var email = document.forms[0].elements[0];
 
 // Simple values, checking the e-mail syntax validity.
 var values = [
   [ '', true ], // The empty string shouldn't be considered as invalid.
   [ 'foo@bar.com', true ],
-  [ ' foo@bar.com', false ],
-  [ 'foo@bar.com ', false ],
+  [ ' foo@bar.com', true ],
+  [ 'foo@bar.com ', true ],
+  [ '\r\n foo@bar.com', true ],
+  [ 'foo@bar.com \n\r', true ],
+  [ '\n\n \r\rfoo@bar.com\n\n   \r\r', true ],
+  [ '\n\r \n\rfoo@bar.com\n\r   \n\r', true ],
   [ 'tulip', false ],
   // Some checks on the user part of the address.
   [ '@bar.com', false ],
   [ 'f\noo@bar.com', true ],
   [ 'f\roo@bar.com', true ],
   [ 'f\r\noo@bar.com', true ],
   // Some checks for the domain part.
   [ 'foo@bar', true ],
@@ -158,17 +162,17 @@ for each (c in legalCharacters) {
   values.push(["foo@foo.bar" + c, true]);
 }
 // Add the concatenation of all legal characters too.
 values.push(["foo@bar.com" + legalCharacters, true]);
 
 // Add domain illegal characters.
 illegalCharacters = "()<>[]:;@\\,!#$%&'*+/=?^_`{|}~ \t";
 for each (c in illegalCharacters) {
-  values.push(['foo@foo.bar' + c, false]);
+  values.push(['foo@foo.ba' + c + 'r', false]);
 }
 
 values.forEach(function([value, valid]) {
   testEmailAddress(email, value, false, valid);
 });
 
 multipleValues.forEach(function([value, valid]) {
   testEmailAddress(email, value, true, valid);
--- a/content/html/content/test/test_bug549475.html
+++ b/content/html/content/test/test_bug549475.html
@@ -42,19 +42,19 @@ var valueModeValue =
 
 function sanitizeValue(aType, aValue)
 {
   switch (aType) {
     case "text":
     case "password":
     case "search":
     case "tel":
-    case "email":
       return aValue.replace(/[\n\r]/g, "");
     case "url":
+    case "email":
       return aValue.replace(/[\n\r]/g, "").replace(/^\s+|\s+$/g, "");
     case "date":
     case "month":
     case "week":
     case "time":
     case "datetime":
     case "datetime-local":
       // TODO: write the sanitize algorithm.
--- a/content/media/test/test_replay_metadata.html
+++ b/content/media/test/test_replay_metadata.html
@@ -27,17 +27,16 @@ var manager = new MediaTestManager;
 function seekStarted(evt) {
   var v = evt.target;
   v._gotSeekStarted = true;
 }
 
 function seekEnded(evt) {
   var v = evt.target;
   v._gotSeekEnded = true;
-  v.play();
 }
 
 function loadedData(evt) {
   var v = evt.target;
   v._loadedDataCount++;
   ok(v._loadedDataCount <= 1, "No more than 1 onloadeddata event for " + v._name);
 }
 
new file mode 100644
--- /dev/null
+++ b/content/smil/crashtests/650732-1.svg
@@ -0,0 +1,46 @@
+<svg xmlns="http://www.w3.org/2000/svg" class="reftest-wait">
+  <rect fill="green" width="100" height="100">
+    <set id="a" attributeName="fill" to="blue"
+      begin="6s" end="986s"/>
+    <set id="b" attributeName="fill" to="orange"
+      begin="a.begin+69.3s;b.begin+700s" dur="700s" end="a.end"/>
+    <set id="c" attributeName="fill" to="yellow"
+      begin="0s;b.begin+700s"/>
+  </rect>
+  <script type="text/javascript">
+<![CDATA[
+const max_attempts = 100;
+var   attempts = 0;
+function attemptCrash()
+{
+  remove();
+  add();
+  if (++attempts >= max_attempts) {
+    document.documentElement.removeAttribute("class");
+  } else {
+    setTimeout(attemptCrash, 0);
+  }
+}
+function add()
+{
+  const svgns = "http://www.w3.org/2000/svg";
+  var elem = document.createElementNS(svgns, "set");
+  elem.setAttribute("id", "b");
+  elem.setAttribute("attributeName", "fill");
+  elem.setAttribute("to", "orange");
+  elem.setAttribute("begin", "a.begin+69.3s;b.begin+700s");
+  elem.setAttribute("dur", "700s");
+  elem.setAttribute("end", "a.end");
+  rect = document.getElementsByTagNameNS(svgns, "rect")[0];
+  rect.appendChild(elem);
+}
+function remove()
+{
+  var elem = document.getElementById('b');
+  elem.parentNode.removeChild(elem);
+  elem = null;
+}
+window.addEventListener("load", attemptCrash, false);
+]]>
+ </script>
+</svg>
--- a/content/smil/crashtests/crashtests.list
+++ b/content/smil/crashtests/crashtests.list
@@ -29,13 +29,14 @@ load 594653-1.svg
 load 596796-1.svg
 load 605345-1.svg
 load 606101-1.svg
 load 608549-1.svg
 load 608295-1.html
 load 611927-1.svg
 load 615002-1.svg
 load 615872-1.svg
+load 650732-1.svg
 load 665334-1.svg
 load 669225-1.svg
 load 670313-1.svg
 load 669225-2.svg
 load 678822-1.svg
--- a/content/smil/nsSMILCSSProperty.cpp
+++ b/content/smil/nsSMILCSSProperty.cpp
@@ -141,46 +141,47 @@ nsSMILCSSProperty::GetBaseValue() const
 
   // (3) Put cached override style back (if it's non-empty)
   if (overrideDecl && !cachedOverrideStyleVal.IsEmpty()) {
     overrideDecl->SetPropertyValue(mPropID, cachedOverrideStyleVal);
   }
 
   // (4) Populate our nsSMILValue from the computed style
   if (didGetComputedVal) {
+    // When we parse animation values we check if they are context-sensitive or
+    // not so that we don't cache animation values whose meaning may change.
+    // For base values however this is unnecessary since on each sample the
+    // compositor will fetch the (computed) base value and compare it against
+    // the cached (computed) value and detect changes for us.
     nsSMILCSSValueType::ValueFromString(mPropID, mElement,
-                                        computedStyleVal, baseValue);
+                                        computedStyleVal, baseValue,
+                                        nsnull);
   }
   return baseValue;
 }
 
 nsresult
 nsSMILCSSProperty::ValueFromString(const nsAString& aStr,
                                    const nsISMILAnimationElement* aSrcElement,
                                    nsSMILValue& aValue,
                                    PRBool& aPreventCachingOfSandwich) const
 {
   NS_ENSURE_TRUE(IsPropertyAnimatable(mPropID), NS_ERROR_FAILURE);
 
-  nsSMILCSSValueType::ValueFromString(mPropID, mElement, aStr, aValue);
-  if (aValue.IsNull()) {
-    return NS_ERROR_FAILURE;
+  nsSMILCSSValueType::ValueFromString(mPropID, mElement, aStr, aValue,
+      &aPreventCachingOfSandwich);
+
+  // XXX Due to bug 536660 (or at least that seems to be the most likely
+  // culprit), when we have animation setting display:none on a <use> element,
+  // if we DON'T set the property every sample, chaos ensues.
+  if (!aPreventCachingOfSandwich && mPropID == eCSSProperty_display) {
+    aPreventCachingOfSandwich = PR_TRUE;
   }
 
-  // XXXdholbert: For simplicity, just assume that all CSS values have to
-  // reparsed every sample. This prevents us from doing the "nothing's changed
-  // so don't recompose" optimization (bug 533291) for CSS properties & mapped
-  // attributes.  If it ends up being expensive to always recompose those, we
-  // can be a little smarter here.  We really only need to set
-  // aPreventCachingOfSandwich to true for "inherit" & "currentColor" (whose
-  // values could change at any time), for length-valued types (particularly
-  // those with em/ex/percent units, since their conversion ratios can change
-  // at any time), and for any value for 'font-family'.
-  aPreventCachingOfSandwich = PR_TRUE;
-  return NS_OK;
+  return aValue.IsNull() ? NS_ERROR_FAILURE : NS_OK;
 }
 
 nsresult
 nsSMILCSSProperty::SetAnimValue(const nsSMILValue& aValue)
 {
   NS_ENSURE_TRUE(IsPropertyAnimatable(mPropID), NS_ERROR_FAILURE);
 
   // Convert nsSMILValue to string
--- a/content/smil/nsSMILCSSValueType.cpp
+++ b/content/smil/nsSMILCSSValueType.cpp
@@ -366,32 +366,34 @@ GetPresContextForElement(Element* aElem)
 }
 
 // Helper function to parse a string into a nsStyleAnimation::Value
 static PRBool
 ValueFromStringHelper(nsCSSProperty aPropID,
                       Element* aTargetElement,
                       nsPresContext* aPresContext,
                       const nsAString& aString,
-                      nsStyleAnimation::Value& aStyleAnimValue)
+                      nsStyleAnimation::Value& aStyleAnimValue,
+                      PRBool* aIsContextSensitive)
 {
   // If value is negative, we'll strip off the "-" so the CSS parser won't
   // barf, and then manually make the parsed value negative.
   // (This is a partial solution to let us accept some otherwise out-of-bounds
   // CSS values. Bug 501188 will provide a more complete fix.)
   PRBool isNegative = PR_FALSE;
   PRUint32 subStringBegin = 0;
   PRInt32 absValuePos = nsSMILParserUtils::CheckForNegativeNumber(aString);
   if (absValuePos > 0) {
     isNegative = PR_TRUE;
     subStringBegin = (PRUint32)absValuePos; // Start parsing after '-' sign
   }
   nsDependentSubstring subString(aString, subStringBegin);
   if (!nsStyleAnimation::ComputeValue(aPropID, aTargetElement, subString,
-                                      PR_TRUE, aStyleAnimValue)) {
+                                      PR_TRUE, aStyleAnimValue,
+                                      aIsContextSensitive)) {
     return PR_FALSE;
   }
   if (isNegative) {
     InvertSign(aStyleAnimValue);
   }
   
   if (aPropID == eCSSProperty_font_size) {
     // Divide out text-zoom, since SVG is supposed to ignore it
@@ -404,28 +406,29 @@ ValueFromStringHelper(nsCSSProperty aPro
   return PR_TRUE;
 }
 
 // static
 void
 nsSMILCSSValueType::ValueFromString(nsCSSProperty aPropID,
                                     Element* aTargetElement,
                                     const nsAString& aString,
-                                    nsSMILValue& aValue)
+                                    nsSMILValue& aValue,
+                                    PRBool* aIsContextSensitive)
 {
   NS_ABORT_IF_FALSE(aValue.IsNull(), "Outparam should be null-typed");
   nsPresContext* presContext = GetPresContextForElement(aTargetElement);
   if (!presContext) {
     NS_WARNING("Not parsing animation value; unable to get PresContext");
     return;
   }
 
   nsStyleAnimation::Value parsedValue;
   if (ValueFromStringHelper(aPropID, aTargetElement, presContext,
-                            aString, parsedValue)) {
+                            aString, parsedValue, aIsContextSensitive)) {
     sSingleton.Init(aValue);
     aValue.mU.mPtr = new ValueWrapper(aPropID, parsedValue, presContext);
   }
 }
 
 // static
 PRBool
 nsSMILCSSValueType::ValueToString(const nsSMILValue& aValue,
--- a/content/smil/nsSMILCSSValueType.h
+++ b/content/smil/nsSMILCSSValueType.h
@@ -95,23 +95,30 @@ public:
    * Otherwise, this method leaves aValue.mType == this class's singleton.
    *
    * @param       aPropID         The property for which we're parsing a value.
    * @param       aTargetElement  The target element to whom the property/value
    *                              setting applies.
    * @param       aString         The string to be parsed as a CSS value.
    * @param [out] aValue          The nsSMILValue to be populated. Should
    *                              initially be null-typed.
+   * @param [out] aIsContextSensitive Set to PR_TRUE if |aString| may produce
+   *                                  a different |aValue| depending on other
+   *                                  CSS properties on |aTargetElement|
+   *                                  or its ancestors (e.g. 'inherit).
+   *                                  PR_FALSE otherwise. May be nsnull.
+   *                                  Not set if the method fails.
    * @pre  aValue.IsNull()
    * @post aValue.IsNull() || aValue.mType == nsSMILCSSValueType::sSingleton
    */
   static void ValueFromString(nsCSSProperty aPropID,
                               Element* aTargetElement,
                               const nsAString& aString,
-                              nsSMILValue& aValue);
+                              nsSMILValue& aValue,
+                              PRBool* aIsContextSensitive);
 
   /**
    * Creates a string representation of the given nsSMILValue.
    *
    * Note: aValue is expected to be of this type (that is, it's expected to
    * have been initialized by nsSMILCSSValueType::sSingleton).  If aValue is a
    * freshly-initialized value, this method will succeed, though the resulting
    * string will be empty.
--- a/content/smil/nsSMILMappedAttribute.cpp
+++ b/content/smil/nsSMILMappedAttribute.cpp
@@ -62,38 +62,36 @@ ReleaseStringBufferPropertyValue(void*  
 nsresult
 nsSMILMappedAttribute::ValueFromString(const nsAString& aStr,
                                        const nsISMILAnimationElement* aSrcElement,
                                        nsSMILValue& aValue,
                                        PRBool& aPreventCachingOfSandwich) const
 {
   NS_ENSURE_TRUE(IsPropertyAnimatable(mPropID), NS_ERROR_FAILURE);
 
-  nsSMILCSSValueType::ValueFromString(mPropID, mElement, aStr, aValue);
-  if (aValue.IsNull()) {
-    return NS_ERROR_FAILURE;
-  }
-
-  // XXXdholbert: For simplicity, just assume that all CSS values have to
-  // reparsed every sample. See note in nsSMILCSSProperty::ValueFromString.
-  aPreventCachingOfSandwich = PR_TRUE;
-  return NS_OK;
+  nsSMILCSSValueType::ValueFromString(mPropID, mElement, aStr, aValue,
+                                      &aPreventCachingOfSandwich);
+  return aValue.IsNull() ? NS_ERROR_FAILURE : NS_OK;
 }
 
 nsSMILValue
 nsSMILMappedAttribute::GetBaseValue() const
 {
   nsAutoString baseStringValue;
   nsRefPtr<nsIAtom> attrName = GetAttrNameAtom();
   PRBool success = mElement->GetAttr(kNameSpaceID_None, attrName,
                                      baseStringValue);
   nsSMILValue baseValue;
   if (success) {
+    // For base values, we don't need to worry whether the value returned is
+    // context-sensitive or not since the compositor will take care of comparing
+    // the returned (computed) base value and its cached value and determining
+    // if an update is required or not.
     nsSMILCSSValueType::ValueFromString(mPropID, mElement,
-                                        baseStringValue, baseValue);
+                                        baseStringValue, baseValue, nsnull);
   } else {
     // Attribute is unset -- use computed value.
     // FIRST: Temporarily clear animated value, to make sure it doesn't pollute
     // the computed value. (We want base value, _without_ animations applied.)
     void* buf = mElement->UnsetProperty(SMIL_MAPPED_ATTR_ANIMVAL,
                                         attrName, nsnull);
     FlushChangesToTargetAttr();
 
--- a/content/smil/test/test_smilChangeAfterFrozen.xhtml
+++ b/content/smil/test/test_smilChangeAfterFrozen.xhtml
@@ -3,118 +3,153 @@
   <title>Test for SMIL when things change after an animation is frozen</title>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <script type="text/javascript" src="smilTestUtils.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=533291">Mozilla Bug 533291</a>
 <p id="display"></p>
-<div id="content" style="display: none">
+<!-- Bug 628848: The following should be display: none but we currently don't
+     handle percentage lengths properly when the whole fragment is display: none
+     -->
+<div id="content" style="visibility: hidden">
 <svg id="svg" xmlns="http://www.w3.org/2000/svg" width="120px" height="120px"
      onload="this.pauseAnimations()">
   <g id="circleParent">
     <circle cx="0" cy="20" r="15" fill="blue" id="circle"/>
   </g>
 </svg>
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 <![CDATA[
-/** Test for SMIL fill modes **/
+/** Test for SMIL values that are context-sensitive **/
+
+/* See bugs 533291 and 562815.
+   
+   The format of each test is basically:
+   1) create some animated and frozen state
+   2) test the animated values
+   3) change the context
+   4) test that context-sensitive animation values have changed
+
+   Ideally, after changing the context (3), the animated state would instantly
+   update. However, this is not currently the case for many situations.
+
+     For CSS properties we have bug 545282 - In animations involving 'inherit'
+     / 'currentColor', changes to inherited value / 'color' don't show up in
+     animated value immediately
+
+     For SVG lengths we have bug 508206 - Relative units used in
+     animation don't update immediately
+
+     (There are a few of todo_is's in the following tests so that if those bugs
+     are ever resolved we'll know to update this test case accordingly.)
+
+   So in between (3) and (4) we force a sample. This is currently done by
+   calling SVGSVGElement.setCurrentTime with the same current time which has the
+   side effect of forcing a sample.
+
+   What we *are* testing is that we're not too zealous with caching animation
+   values whilst in the frozen state. Normally we'd say, "Hey, we're frozen,
+   let's just use the same animation result as last time" but for some
+   context-sensitive animation values that doesn't work.
+*/
 
 /* Global Variables */
 const SVGNS = "http://www.w3.org/2000/svg";
+
+// Animation parameters -- not used for <set> animation
 const ANIM_DUR = "4s";
 const TIME_ANIM_END = "4";
 const TIME_AFTER_ANIM_END = "5";
 
-// SETTIMEOUT_INTERVAL: This value just needs to be at least as large as
-// nsSMILAnimationController::kTimerInterval, so we can queue up a callback
-// for this far in the future and be assured that an animation sample will
-// have happened before the callback fires (because we presumably already
-// have an animation sample in the setTimeout queue, with a lower timeout
-// value than this).
-// NOTE: We only need to use timeouts here because of Bug 545282.
-const SETTIMEOUT_INTERVAL = 60;
-
-const gTestArray =
-  [ testBaseValueChange,
-    testCurrentColorChange,
-    testCurrentColorChangeUsingStyle,
-    testInheritChange,
-    testInheritChangeUsingStyle
-   ];
-
-// Index of current test in gTestArray
-var gNextTestIndex = 0;
-
 const gSvg = document.getElementById("svg");
 const gCircle = document.getElementById("circle");
 const gCircleParent = document.getElementById("circleParent");
 
-
 SimpleTest.waitForExplicitFinish();
 
 // MAIN FUNCTION
 // -------------
 
-function main() {
+function main()
+{
   ok(gSvg.animationsPaused(), "should be paused by <svg> load handler");
   is(gSvg.getCurrentTime(), 0, "should be paused at 0 in <svg> load handler");
 
-  if (gNextTestIndex != 0) {
-    ok(false, "expecting to start at first test in array.");
+  const tests =
+    [ testBaseValueChange,
+      testCurrentColorChange,
+      testCurrentColorChangeUsingStyle,
+      testCurrentColorChangeOnFallback,
+      testInheritChange,
+      testInheritChangeUsingStyle,
+      testEmUnitChangeOnProp,
+      testEmUnitChangeOnPropBase,
+      testEmUnitChangeOnLength,
+      testPercentUnitChangeOnProp,
+      testPercentUnitChangeOnLength,
+      testRelativeFontSize,
+      testRelativeFontWeight,
+      testRelativeFont,
+      testCalcFontSize,
+      testDashArray,
+      testClip
+     ];
+
+  while (tests.length) {
+    tests.shift()();
   }
-  // Kick off first test.  (It will kick off the one after it, and so on.)
-  runNextTest();
+  SimpleTest.finish();
 }
 
 // HELPER FUNCTIONS
 // ----------------
-function createAnimFromTo(attrName, fromVal, toVal) {
-  var anim = document.createElementNS(SVGNS,"animate");
+function createAnimSetTo(attrName, toVal)
+{
+  var anim = document.createElementNS(SVGNS,"set");
   anim.setAttribute("attributeName", attrName);
-  anim.setAttribute("dur", ANIM_DUR);
-  anim.setAttribute("begin", "0s");
-  anim.setAttribute("from", fromVal);
   anim.setAttribute("to", toVal);
-  anim.setAttribute("fill", "freeze");
   return gCircle.appendChild(anim);
 }
-function createAnimBy(attrName, byVal) {
+
+function createAnimBy(attrName, byVal)
+{
   var anim = document.createElementNS(SVGNS,"animate");
   anim.setAttribute("attributeName", attrName);
   anim.setAttribute("dur", ANIM_DUR);
   anim.setAttribute("begin","0s");
   anim.setAttribute("by", byVal);
   anim.setAttribute("fill", "freeze");
   return gCircle.appendChild(anim);
 }
 
+function createAnimFromTo(attrName, fromVal, toVal)
+{
+  var anim = document.createElementNS(SVGNS,"animate");
+  anim.setAttribute("attributeName", attrName);
+  anim.setAttribute("dur", ANIM_DUR);
+  anim.setAttribute("begin","0s");
+  anim.setAttribute("from", fromVal);
+  anim.setAttribute("to", toVal);
+  anim.setAttribute("fill", "freeze");
+  return gCircle.appendChild(anim);
+}
+
 // Common setup code for each test function: seek to 0, and make sure
 // the previous test cleaned up its animations.
 function setupTest() {
   gSvg.setCurrentTime(0);
   if (gCircle.firstChild) {
     ok(false, "Previous test didn't clean up after itself.");
   }
 }
 
-function runNextTest() {
-  if (gNextTestIndex == gTestArray.length) {
-    // No tests left! we're done.
-    SimpleTest.finish();
-    return;
-  }
-
-  // Call next test (and increment next-test index)
-  gTestArray[gNextTestIndex++]();
-}
-
 // THE TESTS
 // ---------
 
 function testBaseValueChange()
 {
   setupTest();
   var anim = createAnimBy("cx", "50");
   gSvg.setCurrentTime(TIME_ANIM_END);
@@ -125,116 +160,410 @@ function testBaseValueChange()
   is(gCircle.cx.animVal.value, 50,
      "Checking animated cx after anim ends");
 
   gCircle.setAttribute("cx", 20);
   is(gCircle.cx.animVal.value, 70,
      "Checking animated cx after anim ends & after changing base val");
 
   anim.parentNode.removeChild(anim); // clean up
-  runNextTest();
 }
 
 function testCurrentColorChange()
 {
   gCircle.setAttribute("color", "red"); // At first: currentColor=red
-  var anim = createAnimFromTo("fill", "yellow", "currentColor");
+  var anim = createAnimSetTo("fill", "currentColor");
 
-  gSvg.setCurrentTime(TIME_AFTER_ANIM_END);
+  gSvg.setCurrentTime(0); // trigger synchronous sample
   is(SMILUtil.getComputedStyleSimple(gCircle, "fill"), "rgb(255, 0, 0)",
-     "Checking animated fill=currentColor after anim ends");
+     "Checking animated fill=currentColor after animating");
 
   gCircle.setAttribute("color", "lime"); // Change: currentColor=lime
-  setTimeout(testCurrentColorChange_final, SETTIMEOUT_INTERVAL);
-}
-
-function testCurrentColorChange_final()
-{
+  // Bug 545282: We should really detect this change and update immediately but
+  // currently we don't until we get sampled again
+  todo_is(SMILUtil.getComputedStyleSimple(gCircle, "fill"), "rgb(0, 255, 0)",
+     "Checking animated fill=currentColor after updating context but before " +
+     "sampling");
+  gSvg.setCurrentTime(0);
   is(SMILUtil.getComputedStyleSimple(gCircle, "fill"), "rgb(0, 255, 0)",
-     "Checking animated fill=currentColor after anim ends and 'color' changes");
+     "Checking animated fill=currentColor after updating context");
 
   // Clean up
   gCircle.removeAttribute("color");
-  gCircle.firstChild.parentNode.removeChild(gCircle.firstChild);
-
-  // Kick off next test
-  runNextTest();
+  gCircle.removeChild(gCircle.firstChild);
 }
 
 function testCurrentColorChangeUsingStyle()
 {
   setupTest();
   gCircle.setAttribute("style", "color: red"); // At first: currentColor=red
-  var anim = createAnimFromTo("fill", "yellow", "currentColor");
+  var anim = createAnimSetTo("fill", "currentColor");
 
-  gSvg.setCurrentTime(TIME_AFTER_ANIM_END);
+  gSvg.setCurrentTime(0);
   is(SMILUtil.getComputedStyleSimple(gCircle, "fill"), "rgb(255, 0, 0)",
-     "Checking animated fill=currentColor after anim ends (using style attr)");
+     "Checking animated fill=currentColor after animating (using style attr)");
 
   gCircle.setAttribute("style", "color: lime"); // Change: currentColor=lime
-  setTimeout(testCurrentColorChangeUsingStyle_final, SETTIMEOUT_INTERVAL);
-}
-
-function testCurrentColorChangeUsingStyle_final()
-{
+  gSvg.setCurrentTime(0);
   is(SMILUtil.getComputedStyleSimple(gCircle, "fill"), "rgb(0, 255, 0)",
-     "Checking animated fill=currentColor after anim ends and 'color' changes "
+     "Checking animated fill=currentColor after updating context "
      + "(using style attr)");
 
   // Clean up
   gCircle.removeAttribute("style");
-  gCircle.firstChild.parentNode.removeChild(gCircle.firstChild);
-  runNextTest();
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function getFallbackColor(pServerStr)
+{
+  return pServerStr.substr(pServerStr.indexOf(" ")+1);
+}
+
+function testCurrentColorChangeOnFallback()
+{
+  setupTest();
+  gCircle.setAttribute("color", "red"); // At first: currentColor=red
+  var anim = createAnimSetTo("fill", "url(#missingGrad) currentColor");
+
+  gSvg.setCurrentTime(0);
+  var fallback =
+    getFallbackColor(SMILUtil.getComputedStyleSimple(gCircle, "fill"));
+  is(fallback, "rgb(255, 0, 0)",
+     "Checking animated fallback fill=currentColor after animating");
+
+  gCircle.setAttribute("color", "lime"); // Change: currentColor=lime
+  gSvg.setCurrentTime(0);
+  fallback = getFallbackColor(SMILUtil.getComputedStyleSimple(gCircle, "fill"));
+  is(fallback, "rgb(0, 255, 0)",
+     "Checking animated fallback fill=currentColor after updating context");
+
+  gCircle.removeAttribute("style");
+  gCircle.removeChild(gCircle.firstChild);
 }
 
 function testInheritChange()
 {
   setupTest();
   gCircleParent.setAttribute("fill", "red"); // At first: inherit=red
-  var anim = createAnimFromTo("fill", "yellow", "inherit");
+  var anim = createAnimSetTo("fill", "inherit");
 
-  gSvg.setCurrentTime(TIME_AFTER_ANIM_END);
+  gSvg.setCurrentTime(0);
   is(SMILUtil.getComputedStyleSimple(gCircle, "fill"), "rgb(255, 0, 0)",
-     "Checking animated fill=inherit after anim ends");
+     "Checking animated fill=inherit after animating");
 
   gCircleParent.setAttribute("fill", "lime"); // Change: inherit=lime
-  setTimeout(testInheritChange_final, SETTIMEOUT_INTERVAL);
-}
-
-function testInheritChange_final() {
+  gSvg.setCurrentTime(0);
   is(SMILUtil.getComputedStyleSimple(gCircle, "fill"), "rgb(0, 255, 0)",
-     "Checking animated fill=inherit after anim ends and parent val changes");
+     "Checking animated fill=inherit after updating context");
 
   gCircleParent.removeAttribute("fill");
-  gCircle.firstChild.parentNode.removeChild(gCircle.firstChild);
-  runNextTest();
+  gCircle.removeChild(gCircle.firstChild);
 }
 
 function testInheritChangeUsingStyle()
 {
   setupTest();
   gCircleParent.setAttribute("style", "fill: red"); // At first: inherit=red
-  var anim = createAnimFromTo("fill", "yellow", "inherit");
+  var anim = createAnimSetTo("fill", "inherit");
 
-  gSvg.setCurrentTime(TIME_AFTER_ANIM_END);
+  gSvg.setCurrentTime(0);
   is(SMILUtil.getComputedStyleSimple(gCircle, "fill"), "rgb(255, 0, 0)",
-     "Checking animated fill=inherit after anim ends (using style attr)");
+     "Checking animated fill=inherit after animating (using style attr)");
 
   gCircleParent.setAttribute("style", "fill: lime"); // Change: inherit=lime
-  setTimeout(testInheritChangeUsingStyle_final, SETTIMEOUT_INTERVAL);
-}
-
-function testInheritChangeUsingStyle_final() {
+  gSvg.setCurrentTime(0);
   is(SMILUtil.getComputedStyleSimple(gCircle, "fill"), "rgb(0, 255, 0)",
-     "Checking animated fill=inherit after anim ends and parent val changes "
+     "Checking animated fill=inherit after updating context "
      + "(using style attr)");
 
   gCircleParent.removeAttribute("style");
-  gCircle.firstChild.parentNode.removeChild(gCircle.firstChild);
-  runNextTest();
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function testEmUnitChangeOnProp()
+{
+  setupTest();
+  gCircleParent.setAttribute("font-size", "10px"); // At first: font-size: 10px
+  var anim = createAnimSetTo("font-size", "2em");
+
+  gSvg.setCurrentTime(0);
+  is(SMILUtil.getComputedStyleSimple(gCircle, "font-size"), "20px",
+     "Checking animated font-size=2em after animating ends");
+
+  gCircleParent.setAttribute("font-size", "20px"); // Change: font-size: 20px
+  gSvg.setCurrentTime(0);
+  is(SMILUtil.getComputedStyleSimple(gCircle, "font-size"), "40px",
+     "Checking animated font-size=2em after updating context");
+
+  gCircleParent.removeAttribute("font-size");
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function testEmUnitChangeOnPropBase()
+{
+  // Test the case where the base value for our animation sandwich is
+  // context-sensitive.
+  // Currently, this is taken care of by the compositor which keeps a cached
+  // base value and compares it with the current base value. This test then just
+  // serves as a regression test in case the compositor's behaviour changes.
+  setupTest();
+  gSvg.setAttribute("font-size", "10px"); // At first: font-size: 10px
+  gCircleParent.setAttribute("font-size", "1em"); // Base: 10px
+  var anim = createAnimBy("font-size", "10px");
+
+  gSvg.setCurrentTime(TIME_AFTER_ANIM_END);
+  is(SMILUtil.getComputedStyleSimple(gCircle, "font-size"), "20px",
+     "Checking animated font-size=20px after anim ends");
+
+  gSvg.setAttribute("font-size", "20px"); // Change: font-size: 20px
+  gSvg.setCurrentTime(TIME_AFTER_ANIM_END);
+  is(SMILUtil.getComputedStyleSimple(gCircle, "font-size"), "30px",
+     "Checking animated font-size=30px after updating context");
+
+  gCircleParent.removeAttribute("font-size");
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function testEmUnitChangeOnLength()
+{
+  setupTest();
+  gCircleParent.setAttribute("font-size", "10px"); // At first: font-size: 10px
+  var anim = createAnimSetTo("cx", "2em");
+
+  gSvg.setCurrentTime(0);
+  is(gCircle.cx.animVal.value, 20,
+     "Checking animated length=2em after animating");
+
+  gCircleParent.setAttribute("font-size", "20px"); // Change: font-size: 20px
+  // Bug 508206: We should really detect this change and update immediately but
+  // currently we don't until we get sampled again
+  todo_is(gCircle.cx.animVal.value, 40,
+     "Checking animated length=2em after updating context but before sampling");
+
+  gSvg.setCurrentTime(0);
+  is(gCircle.cx.animVal.value, 40,
+     "Checking animated length=2em after updating context and after " +
+     "resampling");
+
+  gCircleParent.removeAttribute("font-size");
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function testPercentUnitChangeOnProp()
+{
+  setupTest();
+  gCircleParent.setAttribute("font-size", "10px"); // At first: font-size: 10px
+  var anim = createAnimSetTo("font-size", "150%");
+
+  gSvg.setCurrentTime(0);
+  is(SMILUtil.getComputedStyleSimple(gCircle, "font-size"), "15px",
+     "Checking animated font-size=150% after animating");
+
+  gCircleParent.setAttribute("font-size", "20px"); // Change: font-size: 20px
+  gSvg.setCurrentTime(0);
+  is(SMILUtil.getComputedStyleSimple(gCircle, "font-size"), "30px",
+     "Checking animated font-size=150% after updating context");
+
+  gCircleParent.removeAttribute("font-size");
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function testPercentUnitChangeOnLength()
+{
+  setupTest();
+  var oldHeight = gSvg.getAttribute("height");
+  gSvg.setAttribute("height", "100px"); // At first: viewport height: 100px
+  var anim = createAnimSetTo("cy", "100%");
+
+  gSvg.setCurrentTime(0); // Force synchronous sample so animation takes effect
+  // Due to bug 627594 (SVGLength.value for percent value lengths doesn't
+  // reflect updated viewport until reflow) the following will fail.
+  // Check that it does indeed fail so that when that bug is fixed this test
+  // can be updated.
+  todo_is(gCircle.cy.animVal.value, 100,
+     "Checking animated length=100% after animating but before reflow");
+  gSvg.forceRedraw();
+  // Even after doing a reflow though we'll still fail due to bug 508206
+  // (Relative units used in animation don't update immediately)
+  todo_is(gCircle.cy.animVal.value, 100,
+     "Checking animated length=100% after animating but before resampling");
+  gSvg.setCurrentTime(0);
+  // Now we should be up to date
+  is(gCircle.cy.animVal.value, 100,
+     "Checking animated length=100% after animating");
+
+  gSvg.setAttribute("height", "50px"); // Change: height: 50px
+  gSvg.forceRedraw(); // Bug 627594
+  gSvg.setCurrentTime(0); // Bug 508206
+  is(gCircle.cy.animVal.value, 50,
+     "Checking animated length=100% after updating context");
+
+  gSvg.setAttribute("height", oldHeight);
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function testRelativeFontSize()
+{
+  setupTest();
+  gCircleParent.setAttribute("font-size", "10px"); // At first: font-size: 10px
+  var anim = createAnimSetTo("font-size", "larger");
+
+  gSvg.setCurrentTime(0);
+  var fsize = parseInt(SMILUtil.getComputedStyleSimple(gCircle, "font-size"));
+  // CSS 2 suggests a scaling factor of 1.2 so we should be looking at something
+  // around about 12 or so
+  ok(fsize > 10 && fsize < 20,
+    "Checking animated font-size > 10px after animating");
+
+  gCircleParent.setAttribute("font-size", "20px"); // Change: font-size: 20px
+  gSvg.setCurrentTime(0);
+  fsize = parseInt(SMILUtil.getComputedStyleSimple(gCircle, "font-size"));
+  ok(fsize > 20, "Checking animated font-size > 20px after updating context");
+
+  gCircleParent.removeAttribute("font-size");
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function testRelativeFontWeight()
+{
+  setupTest();
+  gCircleParent.setAttribute("font-weight", "100"); // At first: font-weight 100
+  var anim = createAnimSetTo("font-weight", "bolder");
+  // CSS 2: 'bolder': Specifies the next weight that is assigned to a font
+  // that is darker than the inherited one. If there is no such weight, it
+  // simply results in the next darker numerical value (and the font remains
+  // unchanged), unless the inherited value was '900', in which case the
+  // resulting weight is also '900'.
+
+  gSvg.setCurrentTime(0);
+  var weight =
+    parseInt(SMILUtil.getComputedStyleSimple(gCircle, "font-weight"));
+  ok(weight > 100, "Checking animated font-weight > 100 after animating");
+
+  gCircleParent.setAttribute("font-weight", "800"); // Change: font-weight 800
+  gSvg.setCurrentTime(0);
+  weight = parseInt(SMILUtil.getComputedStyleSimple(gCircle, "font-weight"));
+  is(weight, 900,
+     "Checking animated font-weight = 900 after updating context");
+
+  gCircleParent.removeAttribute("font-weight");
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function testRelativeFont()
+{
+  // Test a relative font-size as part of a 'font' spec since the code path
+  // is different in this case
+  // It turns out that, due to the way we store shorthand font properties, we
+  // don't need to worry about marking such values as context-sensitive since we
+  // seem to store them in their relative form. If, however, we change the way
+  // we store shorthand font properties in the future, this will serve as
+  // a useful regression test.
+  setupTest();
+  gCircleParent.setAttribute("font-size", "10px"); // At first: font-size: 10px
+  // We must be sure to set every part of the shorthand property to some
+  // non-context sensitive value because we want to test that even if only the
+  // font-size is relative we will update it appropriately.
+  var anim =
+    createAnimSetTo("font", "normal normal bold larger/normal sans-serif");
+
+  gSvg.setCurrentTime(0);
+  var fsize = parseInt(SMILUtil.getComputedStyleSimple(gCircle, "font-size"));
+  ok(fsize > 10 && fsize < 20,
+    "Checking size of shorthand 'font' > 10px after animating");
+
+  gCircleParent.setAttribute("font-size", "20px"); // Change: font-size: 20px
+  gSvg.setCurrentTime(0);
+  fsize  = parseInt(SMILUtil.getComputedStyleSimple(gCircle, "font-size"));
+  ok(fsize > 20,
+     "Checking size of shorthand 'font' > 20px after updating context");
+
+  gCircleParent.removeAttribute("font-size");
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function testCalcFontSize()
+{
+  setupTest();
+  gCircleParent.setAttribute("font-size", "10px"); // At first: font-size: 10px
+  var anim = createAnimSetTo("font-size", "-moz-calc(110% + 0.1em)");
+
+  gSvg.setCurrentTime(0);
+  var fsize = parseInt(SMILUtil.getComputedStyleSimple(gCircle, "font-size"));
+  // Font size should be 1.1 * 10px + 0.1 * 10px = 12
+  is(fsize, 12, "Checking animated calc font-size == 12px after animating");
+
+  gCircleParent.setAttribute("font-size", "20px"); // Change: font-size: 20px
+  gSvg.setCurrentTime(0);
+  fsize = parseInt(SMILUtil.getComputedStyleSimple(gCircle, "font-size"));
+  is(fsize, 24, "Checking animated calc font-size == 24px after updating " +
+                "context");
+
+  gCircleParent.removeAttribute("font-size");
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function testDashArray()
+{
+  // stroke dasharrays don't currently convert units--but if someone ever fixes
+  // that, hopefully this test will fail and remind us not to cache percentage
+  // values in that case
+  setupTest();
+  var oldHeight = gSvg.getAttribute("height");
+  var oldWidth  = gSvg.getAttribute("width");
+  gSvg.setAttribute("height", "100px"); // At first: viewport: 100x100px
+  gSvg.setAttribute("width",  "100px");
+  var anim = createAnimFromTo("stroke-dasharray", "0 5", "0 50%");
+
+  gSvg.setCurrentTime(TIME_AFTER_ANIM_END);
+
+  // Now we should be up to date
+  is(SMILUtil.getComputedStyleSimple(gCircle, "stroke-dasharray"), "0, 50%",
+     "Checking animated stroke-dasharray after animating");
+
+  gSvg.setAttribute("height", "50px"); // Change viewport: 50x50px
+  gSvg.setAttribute("width",  "50px");
+  gSvg.setCurrentTime(TIME_AFTER_ANIM_END);
+  is(SMILUtil.getComputedStyleSimple(gCircle, "stroke-dasharray"), "0, 50%",
+     "Checking animated stroke-dasharray after updating context");
+
+  gSvg.setAttribute("height", oldHeight);
+  gSvg.setAttribute("width",  oldWidth);
+  gCircle.removeChild(gCircle.firstChild);
+}
+
+function testClip()
+{
+  setupTest();
+  gCircleParent.setAttribute("font-size", "20px"); // At first: font-size: 20px
+
+  // The clip property only applies to elements that establish a new
+  // viewport so we need to create a nested svg and add animation to that
+  var nestedSVG = document.createElementNS(SVGNS, "svg");
+  nestedSVG.setAttribute("clip", "rect(0px 0px 0px 0px)");
+  gCircleParent.appendChild(nestedSVG);
+
+  var anim = createAnimSetTo("clip", "rect(1em 1em 1em 1em)");
+  // createAnimSetTo will make the animation a child of gCircle so we need to
+  // move it so it targets nestedSVG instead
+  nestedSVG.appendChild(anim);
+
+  gSvg.setCurrentTime(TIME_AFTER_ANIM_END);
+  is(SMILUtil.getComputedStyleSimple(nestedSVG, "clip"),
+     "rect(20px, 20px, 20px, 20px)",
+     "Checking animated clip rect after animating");
+
+  gCircleParent.setAttribute("font-size", "10px"); // Change: font-size: 10px
+  gSvg.setCurrentTime(TIME_AFTER_ANIM_END);
+  is(SMILUtil.getComputedStyleSimple(nestedSVG, "clip"),
+     "rect(10px, 10px, 10px, 10px)",
+     "Checking animated clip rect after updating context");
+
+  gCircleParent.removeAttribute("font-size");
+  gCircleParent.removeChild(nestedSVG);
 }
 
 window.addEventListener("load", main, false);
 ]]>
 </script>
 </pre>
 </body>
 </html>
--- a/content/svg/content/test/Makefile.in
+++ b/content/svg/content/test/Makefile.in
@@ -52,17 +52,16 @@ include $(topsrcdir)/config/rules.mk
 		test_a_href_01.xhtml \
 		test_a_href_02.xhtml \
 		a_href_destination.svg \
 		a_href_helper_01.svg \
 		a_href_helper_02_03.svg \
 		a_href_helper_04.svg \
 		test_animLengthObjectIdentity.xhtml \
 		test_animLengthReadonly.xhtml \
-		test_animLengthRelativeUnits.xhtml \
 		test_animLengthUnits.xhtml \
 		test_bbox.xhtml \
 		test_bbox-with-invalid-viewBox.xhtml \
 		bbox-helper.svg \
 		bounds-helper.svg \
 		test_dataTypes.html \
 		dataTypes-helper.svg \
 		getCTM-helper.svg \
deleted file mode 100644
--- a/content/svg/content/test/test_animLengthRelativeUnits.xhtml
+++ /dev/null
@@ -1,80 +0,0 @@
-<html xmlns="http://www.w3.org/1999/xhtml">
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=508206
--->
-<head>
-  <title>Test for liveness of relative units in animation</title>
-  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=508206">Mozilla Bug 508206</a>
-<p id="display"></p>
-<!-- XXX The following should be display: none but that's broken by bug 413975
-     where we don't handle percentage lengths when the whole fragment is
-     display: none properly. -->
-<div id="content" style="visibility: hidden">
-<svg id="svg" xmlns="http://www.w3.org/2000/svg" width="100px" height="100px"
-     onload="this.pauseAnimations()">
-  <g font-size="10px">
-    <circle cx="0" cy="0" r="15" fill="blue" id="circle">
-      <animate attributeName="cx" from="0" to="10em" dur="10s" begin="0s"
-        fill="freeze" id="animate"/>
-      <animate attributeName="cy" from="0" to="100%" dur="10s" begin="0s"
-        fill="freeze"/>
-    </circle>
-  </g>
-</svg>
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-<![CDATA[
-/** Test liveness of relative units of animated lengths **/
-
-/* Global Variables */
-const svgns="http://www.w3.org/2000/svg";
-var svg = document.getElementById("svg");
-var circle = document.getElementById('circle');
-
-SimpleTest.waitForExplicitFinish();
-
-function main() {
-  ok(svg.animationsPaused(), "should be paused by <svg> load handler");
-  is(svg.getCurrentTime(), 0, "should be paused at 0 in <svg> load handler");
-
-  // Sample mid-way through the animation
-  svg.setCurrentTime(5);
-
-  // (1) Check values mid-way
-  is(circle.cx.animVal.value, 50,
-    "(1) Unexpected animVal for cx before changing base length");
-  is(circle.cy.animVal.value, 50,
-    "(1) Unexpected animVal for cy before changing base length");
-
-  // (2) Change the frame of reference and check values are updated immediately
-
-  // Change font-size
-  circle.parentNode.setAttribute('font-size', '5px');
-  todo_is(circle.cx.animVal.value, 25,
-    "(2) Unexpected animVal for cx after changing parent font-size");
-
-  // Change the viewport size
-  svg.setAttribute('height', '50px');
-  todo_is(circle.cy.animVal.value, 25,
-    "(2) Unexpected animVal for cy after changing containing viewport size");
-
-  SimpleTest.finish();
-}
-
-var animate = document.getElementById('animate');
-if (animate && animate.targetElement) {
-  window.addEventListener("load", main, false);
-} else {
-  ok(true); // Skip tests but don't report 'todo' either
-  SimpleTest.finish();
-}
-]]>
-</script>
-</pre>
-</body>
-</html>
--- a/content/xbl/src/nsXBLDocumentInfo.cpp
+++ b/content/xbl/src/nsXBLDocumentInfo.cpp
@@ -424,41 +424,41 @@ static PRBool IsChromeURI(nsIURI* aURI)
   PRBool isChrome = PR_FALSE;
   if (NS_SUCCEEDED(aURI->SchemeIs("chrome", &isChrome)))
       return isChrome;
   return PR_FALSE;
 }
 
 /* Implementation file */
 
-static PRIntn
+static PRBool
 TraverseProtos(nsHashKey *aKey, void *aData, void* aClosure)
 {
   nsCycleCollectionTraversalCallback *cb = 
     static_cast<nsCycleCollectionTraversalCallback*>(aClosure);
   nsXBLPrototypeBinding *proto = static_cast<nsXBLPrototypeBinding*>(aData);
   proto->Traverse(*cb);
   return kHashEnumerateNext;
 }
 
-static PRIntn
+static PRBool
 UnlinkProtoJSObjects(nsHashKey *aKey, void *aData, void* aClosure)
 {
   nsXBLPrototypeBinding *proto = static_cast<nsXBLPrototypeBinding*>(aData);
   proto->UnlinkJSObjects();
   return kHashEnumerateNext;
 }
 
 struct ProtoTracer
 {
   TraceCallback mCallback;
   void *mClosure;
 };
 
-static PRIntn
+static PRBool
 TraceProtos(nsHashKey *aKey, void *aData, void* aClosure)
 {
   ProtoTracer* closure = static_cast<ProtoTracer*>(aClosure);
   nsXBLPrototypeBinding *proto = static_cast<nsXBLPrototypeBinding*>(aData);
   proto->Trace(closure->mCallback, closure->mClosure);
   return kHashEnumerateNext;
 }
 
--- a/content/xbl/src/nsXBLPrototypeBinding.cpp
+++ b/content/xbl/src/nsXBLPrototypeBinding.cpp
@@ -323,17 +323,17 @@ PRBool nsXBLPrototypeBinding::CompareBin
   PRBool equal = PR_FALSE;
   mBindingURI->Equals(aURI, &equal);
   if (!equal && mAlternateBindingURI) {
     mAlternateBindingURI->Equals(aURI, &equal);
   }
   return equal;
 }
 
-static PRIntn
+static PRBool
 TraverseInsertionPoint(nsHashKey* aKey, void* aData, void* aClosure)
 {
   nsCycleCollectionTraversalCallback &cb = 
     *static_cast<nsCycleCollectionTraversalCallback*>(aClosure);
   nsXBLInsertionPointEntry* entry =
     static_cast<nsXBLInsertionPointEntry*>(aData);
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NATIVE_PTR(entry,
                                                nsXBLInsertionPointEntry,
@@ -1208,17 +1208,17 @@ nsXBLPrototypeBinding::ConstructInsertio
                                                DeleteInsertionPointEntry,
                                                nsnull, 4);
   if (!mInsertionPointTable)
     return;
 
   PRInt32 i;
   for (i = 0; i < count; i++) {
     nsIContent* child = childrenElements[i];
-    nsIContent* parent = child->GetParent(); 
+    nsCOMPtr<nsIContent> parent = child->GetParent(); 
 
     // Create an XBL insertion point entry.
     nsXBLInsertionPointEntry* xblIns = nsXBLInsertionPointEntry::Create(parent);
 
     nsAutoString includes;
     child->GetAttr(kNameSpaceID_None, nsGkAtoms::includes, includes);
     if (includes.IsEmpty()) {
       nsISupportsKey key(nsGkAtoms::children);
--- a/content/xul/document/src/nsXULDocument.cpp
+++ b/content/xul/document/src/nsXULDocument.cpp
@@ -4042,17 +4042,18 @@ nsXULDocument::OverlayForwardReference::
         nsAutoString value;
         aOverlayNode->GetAttr(nameSpaceID, attr, value);
 
         // Element in the overlay has the 'removeelement' attribute set
         // so remove it from the actual document.
         if (attr == nsGkAtoms::removeelement &&
             value.EqualsLiteral("true")) {
 
-            rv = RemoveElement(aTargetNode->GetParent(), aTargetNode);
+            nsCOMPtr<nsIContent> parent = aTargetNode->GetParent();
+            rv = RemoveElement(parent, aTargetNode);
             if (NS_FAILED(rv)) return rv;
 
             return NS_OK;
         }
 
         rv = aTargetNode->SetAttr(nameSpaceID, attr, prefix, value, aNotify);
         if (!NS_FAILED(rv) && !aNotify)
             rv = mDocument->BroadcastAttributeChangeFromOverlay(aTargetNode,
--- a/content/xul/templates/src/nsXULContentBuilder.cpp
+++ b/content/xul/templates/src/nsXULContentBuilder.cpp
@@ -1319,17 +1319,17 @@ nsXULContentBuilder::RemoveGeneratedCont
     nsAutoTArray<nsIContent*, 8> ungenerated;
     if (ungenerated.AppendElement(aElement) == nsnull)
         return NS_ERROR_OUT_OF_MEMORY;
 
     PRUint32 count;
     while (0 != (count = ungenerated.Length())) {
         // Pull the next "ungenerated" element off the queue.
         PRUint32 last = count - 1;
-        nsIContent* element = ungenerated[last];
+        nsCOMPtr<nsIContent> element = ungenerated[last];
         ungenerated.RemoveElementAt(last);
 
         PRUint32 i = element->GetChildCount();
 
         while (i-- > 0) {
             nsCOMPtr<nsIContent> child = element->GetChildAt(i);
 
             // Optimize for the <template> element, because we *know*
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -718,21 +718,21 @@ nsDocShell::nsDocShell():
     nsDocLoader(),
     mDefaultScrollbarPref(Scrollbar_Auto, Scrollbar_Auto),
     mTreeOwner(nsnull),
     mChromeEventHandler(nsnull),
     mCharsetReloadState(eCharsetReloadInit),
     mChildOffset(0),
     mBusyFlags(BUSY_FLAGS_NONE),
     mAppType(nsIDocShell::APP_TYPE_UNKNOWN),
+    mLoadType(0),
     mMarginWidth(-1),
     mMarginHeight(-1),
     mItemType(typeContent),
     mPreviousTransIndex(-1),
-    mLoadType(0),
     mLoadedTransIndex(-1),
     mCreated(PR_FALSE),
     mAllowSubframes(PR_TRUE),
     mAllowPlugins(PR_TRUE),
     mAllowJavascript(PR_TRUE),
     mAllowMetaRedirects(PR_TRUE),
     mAllowImages(PR_TRUE),
     mAllowDNSPrefetch(PR_TRUE),
@@ -8447,23 +8447,23 @@ nsDocShell::InternalLoad(nsIURI * aURI,
             // Save the current URI; we need it if we fire a hashchange later.
             nsCOMPtr<nsIURI> oldURI = mCurrentURI;
 
             // Save the position of the scrollers.
             nscoord cx = 0, cy = 0;
             GetCurScrollPos(ScrollOrientation_X, &cx);
             GetCurScrollPos(ScrollOrientation_Y, &cy);
 
-            // We scroll whenever we're not doing a history load.  Note that
-            // sometimes we might scroll even if we don't fire a hashchange
-            // event!  See bug 653741.
-            if (!aSHEntry) {
-                rv = ScrollToAnchor(curHash, newHash, aLoadType);
-                NS_ENSURE_SUCCESS(rv, rv);
-            }
+            // ScrollToAnchor doesn't necessarily cause us to scroll the window;
+            // the function decides whether a scroll is appropriate based on the
+            // arguments it receives.  But even if we don't end up scrolling,
+            // ScrollToAnchor performs other important tasks, such as informing
+            // the presShell that we have a new hash.  See bug 680257.
+            rv = ScrollToAnchor(curHash, newHash, aLoadType);
+            NS_ENSURE_SUCCESS(rv, rv);
 
             mLoadType = aLoadType;
             mURIResultedInDocument = PR_TRUE;
 
             /* we need to assign mLSHE to aSHEntry right here, so that on History loads,
              * SetCurrentURI() called from OnNewURI() will send proper
              * onLocationChange() notifications to the browser to update
              * back/forward buttons.
--- a/docshell/test/Makefile.in
+++ b/docshell/test/Makefile.in
@@ -115,16 +115,18 @@ include $(topsrcdir)/config/rules.mk
 		bug570341_recordevents.html \
 		test_bug668513.html \
 		bug668513_redirect.html \
 		bug668513_redirect.html^headers^ \
 		test_bug669671.html \
 		file_bug669671.sjs \
 		test_bug675587.html \
 		test_bfcache_plus_hash.html \
+		test_bug680257.html \
+		file_bug680257.html \
 		$(NULL)
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),cocoa)
 _TEST_FILES += \
 		test_bug511449.html \
 		file_bug511449.html \
 		$(NULL)
 endif
new file mode 100644
--- /dev/null
+++ b/docshell/test/file_bug680257.html
@@ -0,0 +1,16 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <style type='text/css'>
+    a        { color: black; }
+    a:target { color: red; }
+  </style>
+</head>
+
+<body onload='(opener || parent).popupLoaded()'>
+
+<a id='a' href='#a'>link</a>
+<a id='b' href='#b'>link2</a>
+
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/docshell/test/test_bug680257.html
@@ -0,0 +1,59 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=680257
+-->
+<head>
+  <title>Test for Bug 680257</title>
+  <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=680257">Mozilla Bug 680257</a>
+
+<script type="application/javascript;version=1.7">
+
+SimpleTest.waitForExplicitFinish();
+
+var popup = window.open('file_bug680257.html');
+
+// The popup will call into popupLoaded() once it loads.
+function popupLoaded() {
+  // runTests() needs to be called from outside popupLoaded's onload handler.
+  // Otherwise, the navigations we do in runTests won't create new SHEntries.
+  SimpleTest.executeSoon(runTests);
+}
+
+function runTests() {
+  checkPopupLinkStyle(false, 'Initial');
+
+  popup.location.hash = 'a';
+  checkPopupLinkStyle(true, 'After setting hash');
+
+  popup.history.back();
+  checkPopupLinkStyle(false, 'After going back');
+
+  popup.history.forward();
+  checkPopupLinkStyle(true, 'After going forward');
+
+  popup.close();
+  SimpleTest.finish();
+}
+
+function checkPopupLinkStyle(isTarget, desc) {
+  var link = popup.document.getElementById('a');
+  var style = popup.getComputedStyle(link);
+  var color = style.getPropertyValue('color');
+
+  // Color is red if isTarget, black otherwise.
+  if (isTarget) {
+    is(color, 'rgb(255, 0, 0)', desc);
+  }
+  else {
+    is(color, 'rgb(0, 0, 0)', desc);
+  }
+}
+
+</script>
+</body>
+</html>
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -8215,29 +8215,31 @@ nsGlobalWindow::GetLocalStorage(nsIDOMSt
 //*****************************************************************************
 // nsGlobalWindow::nsIDOMStorageIndexedDB
 //*****************************************************************************
 
 NS_IMETHODIMP
 nsGlobalWindow::GetMozIndexedDB(nsIIDBFactory** _retval)
 {
   if (!mIndexedDB) {
-    nsCOMPtr<mozIThirdPartyUtil> thirdPartyUtil =
-      do_GetService(THIRDPARTYUTIL_CONTRACTID);
-    NS_ENSURE_TRUE(thirdPartyUtil, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
-
-    PRBool isThirdParty;
-    nsresult rv = thirdPartyUtil->IsThirdPartyWindow(this, nsnull,
-                                                     &isThirdParty);
-    NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
-
-    if (isThirdParty) {
-      NS_WARNING("IndexedDB is not permitted in a third-party window.");
-      *_retval = nsnull;
-      return NS_OK;
+    if (!IsChromeWindow()) {
+      nsCOMPtr<mozIThirdPartyUtil> thirdPartyUtil =
+        do_GetService(THIRDPARTYUTIL_CONTRACTID);
+      NS_ENSURE_TRUE(thirdPartyUtil, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+
+      PRBool isThirdParty;
+      nsresult rv = thirdPartyUtil->IsThirdPartyWindow(this, nsnull,
+                                                       &isThirdParty);
+      NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+
+      if (isThirdParty) {
+        NS_WARNING("IndexedDB is not permitted in a third-party window.");
+        *_retval = nsnull;
+        return NS_OK;
+      }
     }
 
     mIndexedDB = indexedDB::IDBFactory::Create(this);
     NS_ENSURE_TRUE(mIndexedDB, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
   }
 
   nsCOMPtr<nsIIDBFactory> request(mIndexedDB);
   request.forget(_retval);
--- a/dom/interfaces/css/nsIDOMCSS2Properties.idl
+++ b/dom/interfaces/css/nsIDOMCSS2Properties.idl
@@ -46,17 +46,17 @@
  * The nsIDOMCSS2Properties interface is a datatype for additional
  * reflection of data already provided in nsIDOMCSSStyleDeclaration in
  * the Document Object Model.
  *
  * For more information on this interface please see
  * http://www.w3.org/TR/DOM-Level-2-Style
  */
 
-[builtinclass, scriptable, uuid(10f43750-b379-11e0-aff2-0800200c9a66)]
+[builtinclass, scriptable, uuid(286466f1-4246-4574-afdb-2f8a03ad7cc8)]
 interface nsIDOMCSS2Properties : nsISupports
 {
            attribute DOMString        background;
                                         // raises(DOMException) on setting
 
            attribute DOMString        backgroundAttachment;
                                         // raises(DOMException) on setting
 
@@ -652,16 +652,19 @@ interface nsIDOMCSS2Properties : nsISupp
                                         // raises(DOMException) on setting
 
            attribute DOMString        MozStackSizing;
                                         // raises(DOMException) on setting
 
            attribute DOMString        MozBorderImage;
                                         // raises(DOMException) on setting
 
+           attribute DOMString        MozColumns;
+                                        // raises(DOMException) on setting
+
            attribute DOMString        MozColumnRule;
                                         // raises(DOMException) on setting
 
            attribute DOMString        MozColumnRuleWidth;
                                         // raises(DOMException) on setting
 
            attribute DOMString        MozColumnRuleStyle;
                                         // raises(DOMException) on setting
--- a/dom/interfaces/events/nsIDOMMessageEvent.idl
+++ b/dom/interfaces/events/nsIDOMMessageEvent.idl
@@ -40,17 +40,17 @@
 
 /**
  * The nsIDOMMessageEvent interface is used for server-sent events and for
  * cross-domain messaging.
  *
  * For more information on this interface, please see
  * http://www.whatwg.org/specs/web-apps/current-work/#messageevent
  */
-[scriptable, uuid(dc8ec5c6-ebf2-4f95-be99-cd13e3c0d0c6)]
+[scriptable, uuid(9ac4fa26-4d19-4f4e-807e-b30cd0dbe56a)]
 interface nsIDOMMessageEvent : nsIDOMEvent
 {
   /**
    * Custom string data associated with this event.
    */
   [implicit_jscontext]
   readonly attribute jsval data;
   
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -1872,27 +1872,22 @@ nsPluginInstanceOwner::HandleEvent(nsIDO
     return KeyPress(aEvent);
   }
 
   nsCOMPtr<nsIDOMDragEvent> dragEvent(do_QueryInterface(aEvent));
   if (dragEvent && mInstance) {
     nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aEvent));
     if (privateEvent) {
       nsEvent* ievent = privateEvent->GetInternalNSEvent();
-      if (ievent && NS_IS_TRUSTED_EVENT(ievent) &&
-          (ievent->message == NS_DRAGDROP_ENTER || ievent->message == NS_DRAGDROP_OVER)) {
-        // set the allowed effect to none here. The plugin should set it if necessary
-        nsCOMPtr<nsIDOMDataTransfer> dataTransfer;
-        dragEvent->GetDataTransfer(getter_AddRefs(dataTransfer));
-        if (dataTransfer)
-          dataTransfer->SetEffectAllowed(NS_LITERAL_STRING("none"));
+      if ((ievent && NS_IS_TRUSTED_EVENT(ievent)) &&
+           ievent->message != NS_DRAGDROP_ENTER && ievent->message != NS_DRAGDROP_OVER) {
+        aEvent->PreventDefault();
       }
 
       // Let the plugin handle drag events.
-      aEvent->PreventDefault();
       aEvent->StopPropagation();
     }
   }
   return NS_OK;
 }
 
 #ifdef MOZ_X11
 static unsigned int XInputEventState(const nsInputEvent& anEvent)
--- a/dom/system/unix/QTMLocationProvider.cpp
+++ b/dom/system/unix/QTMLocationProvider.cpp
@@ -32,17 +32,17 @@
  * 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 ***** */
 
 #include "QTMLocationProvider.h"
 #include "nsGeoPosition.h"
-#include <QFeedbackEffect>
+
 using namespace QtMobility;
 
 using namespace mozilla;
 
 NS_IMPL_ISUPPORTS1(QTMLocationProvider, nsIGeolocationProvider)
 
 QTMLocationProvider::QTMLocationProvider()
 {
--- a/editor/composer/src/nsEditorSpellCheck.cpp
+++ b/editor/composer/src/nsEditorSpellCheck.cpp
@@ -48,18 +48,23 @@
 #include "nsITextServicesDocument.h"
 #include "nsISpellChecker.h"
 #include "nsISelection.h"
 #include "nsIDOMRange.h"
 #include "nsIEditor.h"
 #include "nsIHTMLEditor.h"
 
 #include "nsIComponentManager.h"
+#include "nsIContentPrefService.h"
+#include "nsIObserverService.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIChromeRegistry.h"
+#include "nsIPrivateBrowsingService.h"
+#include "nsIContentURIGrouper.h"
+#include "nsNetCID.h"
 #include "nsString.h"
 #include "nsReadableUtils.h"
 #include "nsITextServicesFilter.h"
 #include "nsUnicharUtils.h"
 #include "mozilla/Services.h"
 #include "mozilla/Preferences.h"
 
 using namespace mozilla;
@@ -75,34 +80,245 @@ class UpdateDictionnaryHolder {
     }
     ~UpdateDictionnaryHolder() {
       if (mSpellCheck) {
         mSpellCheck->EndUpdateDictionary();
       }
     }
 };
 
+#define CPS_PREF_NAME NS_LITERAL_STRING("spellcheck.lang")
+
+class LastDictionary : public nsIObserver, public nsSupportsWeakReference {
+public:
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSIOBSERVER
+
+  LastDictionary();
+
+  /**
+   * Store current dictionary for editor document url. Use content pref
+   * service. Or, if in private mode, store this information in memory.
+   */
+  NS_IMETHOD StoreCurrentDictionary(nsIEditor* aEditor, const nsAString& aDictionary);
+
+  /**
+   * Get last stored current dictionary for editor document url.
+   */
+  NS_IMETHOD FetchLastDictionary(nsIEditor* aEditor, nsAString& aDictionary);
+
+  /**
+   * Forget last current dictionary stored for editor document url.
+   */
+  NS_IMETHOD ClearCurrentDictionary(nsIEditor* aEditor);
+
+  /**
+   * get uri of editor's document.
+   *
+   */
+  static nsresult GetDocumentURI(nsIEditor* aEditor, nsIURI * *aURI);
+
+  PRBool mInPrivateBrowsing;
+
+  // During private browsing, dictionaries are stored in memory
+  nsDataHashtable<nsStringHashKey, nsString> mMemoryStorage;
+};
+
+NS_IMPL_ISUPPORTS2(LastDictionary, nsIObserver, nsISupportsWeakReference)
+
+LastDictionary::LastDictionary():
+  mInPrivateBrowsing(PR_FALSE)
+{  
+  nsCOMPtr<nsIPrivateBrowsingService> pbService =
+    do_GetService(NS_PRIVATE_BROWSING_SERVICE_CONTRACTID);
+  if (pbService) {
+    pbService->GetPrivateBrowsingEnabled(&mInPrivateBrowsing);
+    mMemoryStorage.Init();
+  }
+}
+
+// static
+nsresult
+LastDictionary::GetDocumentURI(nsIEditor* aEditor, nsIURI * *aURI)
+{
+  NS_ENSURE_ARG_POINTER(aEditor);
+  NS_ENSURE_ARG_POINTER(aURI);
+
+  nsCOMPtr<nsIDOMDocument> domDoc;
+  aEditor->GetDocument(getter_AddRefs(domDoc));
+  NS_ENSURE_TRUE(domDoc, NS_ERROR_FAILURE);
+
+  nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
+  NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE);
+
+  nsCOMPtr<nsIURI> docUri = doc->GetDocumentURI();
+  NS_ENSURE_TRUE(docUri, NS_ERROR_FAILURE);
+
+  *aURI = docUri;
+  NS_ADDREF(*aURI);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+LastDictionary::FetchLastDictionary(nsIEditor* aEditor, nsAString& aDictionary)
+{
+  NS_ENSURE_ARG_POINTER(aEditor);
+
+  nsresult rv;
+
+  nsCOMPtr<nsIURI> docUri;
+  rv = GetDocumentURI(aEditor, getter_AddRefs(docUri));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  if (mInPrivateBrowsing) {
+    nsCOMPtr<nsIContentURIGrouper> hostnameGrouperService =
+      do_GetService(NS_HOSTNAME_GROUPER_SERVICE_CONTRACTID);
+    NS_ENSURE_TRUE(hostnameGrouperService, NS_ERROR_NOT_AVAILABLE);
+    nsString group;
+    hostnameGrouperService->Group(docUri, group);
+    nsAutoString lastDict;
+    if (mMemoryStorage.Get(group, &lastDict)) {
+      aDictionary.Assign(lastDict);
+    } else {
+      aDictionary.Truncate();
+    }
+    return NS_OK;
+  }
+
+  nsCOMPtr<nsIContentPrefService> contentPrefService =
+    do_GetService(NS_CONTENT_PREF_SERVICE_CONTRACTID);
+  NS_ENSURE_TRUE(contentPrefService, NS_ERROR_NOT_AVAILABLE);
+
+  nsCOMPtr<nsIWritableVariant> uri = do_CreateInstance(NS_VARIANT_CONTRACTID);
+  NS_ENSURE_TRUE(uri, NS_ERROR_OUT_OF_MEMORY);
+  uri->SetAsISupports(docUri);
+
+  PRBool hasPref;
+  if (NS_SUCCEEDED(contentPrefService->HasPref(uri, CPS_PREF_NAME, &hasPref)) && hasPref) {
+    nsCOMPtr<nsIVariant> pref;
+    contentPrefService->GetPref(uri, CPS_PREF_NAME, nsnull, getter_AddRefs(pref));
+    pref->GetAsAString(aDictionary);
+  } else {
+    aDictionary.Truncate();
+  }
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+LastDictionary::StoreCurrentDictionary(nsIEditor* aEditor, const nsAString& aDictionary)
+{
+  NS_ENSURE_ARG_POINTER(aEditor);
+
+  nsresult rv;
+
+  nsCOMPtr<nsIURI> docUri;
+  rv = GetDocumentURI(aEditor, getter_AddRefs(docUri));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+ if (mInPrivateBrowsing) {
+    nsCOMPtr<nsIContentURIGrouper> hostnameGrouperService =
+      do_GetService(NS_HOSTNAME_GROUPER_SERVICE_CONTRACTID);
+    NS_ENSURE_TRUE(hostnameGrouperService, NS_ERROR_NOT_AVAILABLE);
+    nsString group;
+    hostnameGrouperService->Group(docUri, group);
+
+    if (mMemoryStorage.Put(group, nsString(aDictionary))) {
+      return NS_OK;
+    } else {
+      return NS_ERROR_FAILURE;
+    }
+  }
+
+  nsCOMPtr<nsIWritableVariant> uri = do_CreateInstance(NS_VARIANT_CONTRACTID);
+  NS_ENSURE_TRUE(uri, NS_ERROR_OUT_OF_MEMORY);
+  uri->SetAsISupports(docUri);
+
+  nsCOMPtr<nsIWritableVariant> prefValue = do_CreateInstance(NS_VARIANT_CONTRACTID);
+  NS_ENSURE_TRUE(prefValue, NS_ERROR_OUT_OF_MEMORY);
+  prefValue->SetAsAString(aDictionary);
+
+  nsCOMPtr<nsIContentPrefService> contentPrefService =
+    do_GetService(NS_CONTENT_PREF_SERVICE_CONTRACTID);
+  NS_ENSURE_TRUE(contentPrefService, NS_ERROR_NOT_INITIALIZED);
+
+  return contentPrefService->SetPref(uri, CPS_PREF_NAME, prefValue);
+}
+
+NS_IMETHODIMP
+LastDictionary::ClearCurrentDictionary(nsIEditor* aEditor)
+{
+  NS_ENSURE_ARG_POINTER(aEditor);
+
+  nsresult rv;
+
+  nsCOMPtr<nsIURI> docUri;
+  rv = GetDocumentURI(aEditor, getter_AddRefs(docUri));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  nsCOMPtr<nsIContentURIGrouper> hostnameGrouperService =
+      do_GetService(NS_HOSTNAME_GROUPER_SERVICE_CONTRACTID);
+  NS_ENSURE_TRUE(hostnameGrouperService, NS_ERROR_NOT_AVAILABLE);
+
+  nsString group;
+  hostnameGrouperService->Group(docUri, group);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  if (mMemoryStorage.IsInitialized()) {
+    mMemoryStorage.Remove(group);
+  }
+
+  nsCOMPtr<nsIWritableVariant> uri = do_CreateInstance(NS_VARIANT_CONTRACTID);
+  NS_ENSURE_TRUE(uri, NS_ERROR_OUT_OF_MEMORY);
+  uri->SetAsISupports(docUri);
+
+  nsCOMPtr<nsIContentPrefService> contentPrefService =
+    do_GetService(NS_CONTENT_PREF_SERVICE_CONTRACTID);
+  NS_ENSURE_TRUE(contentPrefService, NS_ERROR_NOT_INITIALIZED);
+
+  return contentPrefService->RemovePref(uri, CPS_PREF_NAME);
+}
+
+NS_IMETHODIMP
+LastDictionary::Observe(nsISupports *aSubject, char const *aTopic, PRUnichar const *aData)
+{
+  if (strcmp(aTopic, NS_PRIVATE_BROWSING_SWITCH_TOPIC) == 0) {
+    if (NS_LITERAL_STRING(NS_PRIVATE_BROWSING_ENTER).Equals(aData)) {
+      mInPrivateBrowsing = PR_TRUE;
+    } else if (NS_LITERAL_STRING(NS_PRIVATE_BROWSING_LEAVE).Equals(aData)) {
+      mInPrivateBrowsing = PR_FALSE;
+      if (mMemoryStorage.IsInitialized()) {
+        mMemoryStorage.Clear();
+      }
+    }
+  } 
+  return NS_OK;
+}
+
+LastDictionary* nsEditorSpellCheck::gDictionaryStore = nsnull;
+
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsEditorSpellCheck)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsEditorSpellCheck)
 
 NS_INTERFACE_MAP_BEGIN(nsEditorSpellCheck)
   NS_INTERFACE_MAP_ENTRY(nsIEditorSpellCheck)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIEditorSpellCheck)
   NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(nsEditorSpellCheck)
 NS_INTERFACE_MAP_END
 
-NS_IMPL_CYCLE_COLLECTION_2(nsEditorSpellCheck,
+NS_IMPL_CYCLE_COLLECTION_3(nsEditorSpellCheck,
+                           mEditor,
                            mSpellChecker,
                            mTxtSrvFilter)
 
 nsEditorSpellCheck::nsEditorSpellCheck()
   : mSuggestedWordIndex(0)
   , mDictionaryIndex(0)
+  , mEditor(nsnull)
   , mUpdateDictionaryRunning(PR_FALSE)
-  , mDictWasSetManually(PR_FALSE)
 {
 }
 
 nsEditorSpellCheck::~nsEditorSpellCheck()
 {
   // Make sure we blow the spellchecker away, just in
   // case it hasn't been destroyed already.
   mSpellChecker = nsnull;
@@ -130,18 +346,34 @@ nsEditorSpellCheck::CanSpellCheck(PRBool
 
   *_retval = (dictList.Length() > 0);
   return NS_OK;
 }
 
 NS_IMETHODIMP    
 nsEditorSpellCheck::InitSpellChecker(nsIEditor* aEditor, PRBool aEnableSelectionChecking)
 {
+  NS_ENSURE_TRUE(aEditor, NS_ERROR_NULL_POINTER);
+  mEditor = aEditor;
+
   nsresult rv;
 
+  if (!gDictionaryStore) {
+    gDictionaryStore = new LastDictionary();
+    if (gDictionaryStore) {
+      NS_ADDREF(gDictionaryStore);
+      nsCOMPtr<nsIObserverService> observerService =
+        mozilla::services::GetObserverService();
+      if (observerService) {
+        observerService->AddObserver(gDictionaryStore, NS_PRIVATE_BROWSING_SWITCH_TOPIC, PR_TRUE);
+      }
+    }
+  }
+
+
   // We can spell check with any editor type
   nsCOMPtr<nsITextServicesDocument>tsDoc =
      do_CreateInstance("@mozilla.org/textservices/textservicesdocument;1", &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   NS_ENSURE_TRUE(tsDoc, NS_ERROR_NULL_POINTER);
 
   tsDoc->SetFilter(mTxtSrvFilter);
@@ -203,17 +435,17 @@ nsEditorSpellCheck::InitSpellChecker(nsI
 
   NS_ENSURE_TRUE(mSpellChecker, NS_ERROR_NULL_POINTER);
 
   rv = mSpellChecker->SetDocument(tsDoc, PR_TRUE);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // do not fail if UpdateCurrentDictionary fails because this method may
   // succeed later.
-  UpdateCurrentDictionary(aEditor);
+  UpdateCurrentDictionary();
   return NS_OK;
 }
 
 NS_IMETHODIMP    
 nsEditorSpellCheck::GetNextMisspelledWord(PRUnichar **aNextMisspelledWord)
 {
   NS_ENSURE_TRUE(mSpellChecker, NS_ERROR_NOT_INITIALIZED);
 
@@ -386,17 +618,39 @@ nsEditorSpellCheck::GetCurrentDictionary
 }
 
 NS_IMETHODIMP    
 nsEditorSpellCheck::SetCurrentDictionary(const nsAString& aDictionary)
 {
   NS_ENSURE_TRUE(mSpellChecker, NS_ERROR_NOT_INITIALIZED);
 
   if (!mUpdateDictionaryRunning) {
-    mDictWasSetManually = PR_TRUE;
+
+    nsDefaultStringComparator comparator;
+    nsAutoString langCode;
+    PRInt32 dashIdx = aDictionary.FindChar('-');
+    if (dashIdx != -1) {
+      langCode.Assign(Substring(aDictionary, 0, dashIdx));
+    } else {
+      langCode.Assign(aDictionary);
+    }
+
+    if (mPreferredLang.IsEmpty() || !nsStyleUtil::DashMatchCompare(mPreferredLang, langCode, comparator)) {
+      // When user sets dictionary manually, we store this value associated
+      // with editor url.
+      gDictionaryStore->StoreCurrentDictionary(mEditor, aDictionary);
+    } else {
+      // If user sets a dictionary matching (even partially), lang defined by
+      // document, we consider content pref has been canceled, and we clear it.
+      gDictionaryStore->ClearCurrentDictionary(mEditor);
+    }
+
+    // Also store it in as a preference. It will be used as a default value
+    // when everything else fails.
+    Preferences::SetString("spellchecker.dictionary", aDictionary);
   }
   return mSpellChecker->SetCurrentDictionary(aDictionary);
 }
 
 NS_IMETHODIMP    
 nsEditorSpellCheck::UninitSpellChecker()
 {
   NS_ENSURE_TRUE(mSpellChecker, NS_ERROR_NOT_INITIALIZED);
@@ -404,31 +658,16 @@ nsEditorSpellCheck::UninitSpellChecker()
   // Cleanup - kill the spell checker
   DeleteSuggestedWordList();
   mDictionaryList.Clear();
   mDictionaryIndex = 0;
   mSpellChecker = 0;
   return NS_OK;
 }
 
-// Save the last set dictionary to the user's preferences.
-NS_IMETHODIMP
-nsEditorSpellCheck::SaveDefaultDictionary()
-{
-  if (!mDictWasSetManually) {
-    return NS_OK;
-  }
-
-  nsAutoString dictName;
-  nsresult rv = GetCurrentDictionary(dictName);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return Preferences::SetString("spellchecker.dictionary", dictName);
-}
-
 
 /* void setFilter (in nsITextServicesFilter filter); */
 NS_IMETHODIMP 
 nsEditorSpellCheck::SetFilter(nsITextServicesFilter *filter)
 {
   mTxtSrvFilter = filter;
   return NS_OK;
 }
@@ -437,55 +676,61 @@ nsresult
 nsEditorSpellCheck::DeleteSuggestedWordList()
 {
   mSuggestedWordList.Clear();
   mSuggestedWordIndex = 0;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsEditorSpellCheck::UpdateCurrentDictionary(nsIEditor* aEditor)
+nsEditorSpellCheck::UpdateCurrentDictionary()
 {
-  if (mDictWasSetManually) { // user has set dictionary manually; we better not change it.
-    return NS_OK;
-  }
-
   nsresult rv;
 
   UpdateDictionnaryHolder holder(this);
 
-  // Tell the spellchecker what dictionary to use:
-  nsAutoString dictName;
-
-  // First, try to get language with html5 algorithm
-  nsAutoString editorLang;
-
+  // Get language with html5 algorithm
   nsCOMPtr<nsIContent> rootContent;
-
-  nsCOMPtr<nsIHTMLEditor> htmlEditor = do_QueryInterface(aEditor);
+  nsCOMPtr<nsIHTMLEditor> htmlEditor = do_QueryInterface(mEditor);
   if (htmlEditor) {
     rootContent = htmlEditor->GetActiveEditingHost();
   } else {
     nsCOMPtr<nsIDOMElement> rootElement;
-    rv = aEditor->GetRootElement(getter_AddRefs(rootElement));
+    rv = mEditor->GetRootElement(getter_AddRefs(rootElement));
     NS_ENSURE_SUCCESS(rv, rv);
     rootContent = do_QueryInterface(rootElement);
   }
   NS_ENSURE_TRUE(rootContent, NS_ERROR_FAILURE);
 
-  rootContent->GetLang(editorLang);
+  mPreferredLang.Truncate();
+  rootContent->GetLang(mPreferredLang);
+
+  // Tell the spellchecker what dictionary to use:
 
-  if (editorLang.IsEmpty()) {
+  // First try to get dictionary from content prefs. If we have one, do not got
+  // further. Use this exact dictionary.
+  nsAutoString dictName;
+  rv = gDictionaryStore->FetchLastDictionary(mEditor, dictName);
+  if (NS_SUCCEEDED(rv) && !dictName.IsEmpty()) {
+    if (NS_FAILED(SetCurrentDictionary(dictName))) { 
+      // may be dictionary was uninstalled ?
+      gDictionaryStore->ClearCurrentDictionary(mEditor);
+    }
+    return NS_OK;
+  }
+
+  if (mPreferredLang.IsEmpty()) {
     nsCOMPtr<nsIDocument> doc = rootContent->GetCurrentDoc();
     NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE);
-    doc->GetContentLanguage(editorLang);
+    doc->GetContentLanguage(mPreferredLang);
   }
 
-  if (!editorLang.IsEmpty()) {
-    dictName.Assign(editorLang);
+  // Then, try to use language computed from element
+  if (!mPreferredLang.IsEmpty()) {
+    dictName.Assign(mPreferredLang);
   }
 
   // otherwise, get language from preferences
   if (dictName.IsEmpty()) {
     dictName.Assign(Preferences::GetLocalizedString("spellchecker.dictionary"));
   }
 
   if (dictName.IsEmpty())
@@ -538,17 +783,17 @@ nsEditorSpellCheck::UpdateCurrentDiction
         }
       }
     }
   }
 
   // If we have not set dictionary, and the editable element doesn't have a
   // lang attribute, we try to get a dictionary. First try, en-US. If it does
   // not work, pick the first one.
-  if (editorLang.IsEmpty()) {
+  if (mPreferredLang.IsEmpty()) {
     nsAutoString currentDictionary;
     rv = GetCurrentDictionary(currentDictionary);
     if (NS_FAILED(rv) || currentDictionary.IsEmpty()) {
       rv = SetCurrentDictionary(NS_LITERAL_STRING("en-US"));
       if (NS_FAILED(rv)) {
         nsTArray<nsString> dictList;
         rv = mSpellChecker->GetDictionaryList(&dictList);
         if (NS_SUCCEEDED(rv) && dictList.Length() > 0) {
@@ -562,8 +807,13 @@ nsEditorSpellCheck::UpdateCurrentDiction
   // fail silently so that the spellchecker dialog is allowed to come
   // up. The user can manually reset the language to their choice on
   // the dialog if it is wrong.
 
   DeleteSuggestedWordList();
 
   return NS_OK;
 }
+
+void 
+nsEditorSpellCheck::ShutDown() {
+  NS_IF_RELEASE(gDictionaryStore);
+}
--- a/editor/composer/src/nsEditorSpellCheck.h
+++ b/editor/composer/src/nsEditorSpellCheck.h
@@ -38,54 +38,66 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsEditorSpellCheck_h___
 #define nsEditorSpellCheck_h___
 
 
 #include "nsIEditorSpellCheck.h"
 #include "nsISpellChecker.h"
+#include "nsIObserver.h"
+#include "nsIURI.h"
+#include "nsWeakReference.h"
 #include "nsCOMPtr.h"
 #include "nsCycleCollectionParticipant.h"
+#include "nsDataHashtable.h"
 
 #define NS_EDITORSPELLCHECK_CID                     \
 { /* {75656ad9-bd13-4c5d-939a-ec6351eea0cc} */        \
     0x75656ad9, 0xbd13, 0x4c5d,                       \
     { 0x93, 0x9a, 0xec, 0x63, 0x51, 0xee, 0xa0, 0xcc }\
 }
 
+class LastDictionary;
+
 class nsEditorSpellCheck : public nsIEditorSpellCheck
 {
 public:
   nsEditorSpellCheck();
   virtual ~nsEditorSpellCheck();
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS(nsEditorSpellCheck)
 
   /* Declare all methods in the nsIEditorSpellCheck interface */
   NS_DECL_NSIEDITORSPELLCHECK
 
+  static LastDictionary* gDictionaryStore;
+
+  static void ShutDown();
+
 protected:
   nsCOMPtr<nsISpellChecker> mSpellChecker;
 
   nsTArray<nsString>  mSuggestedWordList;
   PRInt32        mSuggestedWordIndex;
 
   // these are the words in the current personal dictionary,
   // GetPersonalDictionary must be called to load them.
   nsTArray<nsString>  mDictionaryList;
   PRInt32        mDictionaryIndex;
 
   nsresult       DeleteSuggestedWordList();
 
   nsCOMPtr<nsITextServicesFilter> mTxtSrvFilter;
+  nsCOMPtr<nsIEditor> mEditor;
+
+  nsString mPreferredLang;
 
   PRPackedBool mUpdateDictionaryRunning;
-  PRPackedBool mDictWasSetManually;
 
 public:
   void BeginUpdateDictionary() { mUpdateDictionaryRunning = PR_TRUE ;}
   void EndUpdateDictionary() { mUpdateDictionaryRunning = PR_FALSE ;}
 };
 
 #endif // nsEditorSpellCheck_h___
 
--- a/editor/composer/test/Makefile.in
+++ b/editor/composer/test/Makefile.in
@@ -44,20 +44,22 @@ relativesrcdir  = editor/composer/test
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES = \
 		test_bug348497.html \
 		test_bug384147.html \
 		test_bug389350.html \
 		test_bug519928.html \
+		bug678842_subframe.html \
 		$(NULL)
 
 _CHROME_TEST_FILES = \
 		test_bug434998.xul \
 		test_bug338427.html \
+		test_bug678842.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
 
 libs:: $(_CHROME_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/chrome/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/editor/composer/test/bug678842_subframe.html
@@ -0,0 +1,8 @@
+<!DOCTYPE html>
+<html>
+<head>
+</head>
+<body>
+<textarea id="textarea" lang="testing-XXX"></textarea>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/editor/composer/test/test_bug678842.html
@@ -0,0 +1,63 @@
+<!DOCTYPE html>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=678842
+-->
+<head>
+  <title>Test for Bug 678842</title>
+  <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+</head>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=678842">Mozilla Bug 678842</a>
+<p id="display"></p>
+<iframe id="content"></iframe>
+  
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+
+/** Test for Bug 678842 **/
+SimpleTest.waitForExplicitFinish();
+var content = document.getElementById('content');
+// load a subframe containing an editor with a defined unknown lang. At first
+// load, it will set dictionary to en-US. At second load, it will return current
+// dictionary. So, we can check, dictionary is correctly remembered between
+// loads.
+
+var firstLoad = true;
+
+var loadListener = function(evt) {
+  var doc = evt.target.contentDocument;
+  var elem = doc.getElementById('textarea');
+  var editor = elem.QueryInterface(Components.interfaces.nsIDOMNSEditableElement).editor;
+  editor.setSpellcheckUserOverride(true);
+  var inlineSpellChecker = editor.getInlineSpellChecker(true);
+  var spellchecker = inlineSpellChecker.spellChecker;
+  var currentDictonary = "";
+  try {
+    currentDictonary = spellchecker.GetCurrentDictionary();
+  } catch(e) {}
+
+  if (!currentDictonary) {
+    spellchecker.SetCurrentDictionary('en-US');
+  }
+
+  if (firstLoad) {
+    firstLoad = false;
+    is (currentDictonary, "", "unexpected lang " + currentDictonary);
+    content.src = 'http://mochi.test:8888/tests/editor/composer/test/bug678842_subframe.html?firstload=false';
+  } else {
+    is (currentDictonary, "en-US", "unexpected lang " + currentDictonary + " instead of en-US");
+    content.removeEventListener('load', loadListener, false);
+    SimpleTest.finish();
+  }
+}
+
+content.addEventListener('load', loadListener, false);
+
+content.src = 'http://mochi.test:8888/tests/editor/composer/test/bug678842_subframe.html?firstload=true';
+
+</script>
+</pre>
+</body>
+</html>
--- a/editor/idl/nsIEditorSpellCheck.idl
+++ b/editor/idl/nsIEditorSpellCheck.idl
@@ -36,17 +36,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
  
 #include "nsISupports.idl"
 
 interface nsIEditor;
 interface nsITextServicesFilter;
 
-[scriptable, uuid(3da0ce96-7d3a-48d0-80b7-2d90dab09747)]
+[scriptable, uuid(af84da62-588f-409f-847d-feecc991bd93)]
 interface nsIEditorSpellCheck : nsISupports
 {
 
  /**
    * Returns true if we can enable spellchecking. If there are no available
    * dictionaries, this will return false.
    */
   boolean       canSpellCheck();
@@ -146,24 +146,16 @@ interface nsIEditorSpellCheck : nsISuppo
   AString       GetCurrentDictionary();
 
   /**
    * @see nsISpellChecker::SetCurrentDictionary
    */
   void          SetCurrentDictionary(in AString dictionary);
 
   /**
-   * Call to save the currently selected dictionary as the default. The
-   * function UninitSpellChecker will also do this, but that function may not
-   * be called in some situations. This function allows the caller to force the
-   * default right now.
-   */
-  void          saveDefaultDictionary();
-
-  /**
    * Call this to free up the spell checking object. It will also save the
    * current selected language as the default for future use.
    *
    * If you have called CanSpellCheck but not InitSpellChecker, you can still
    * call this function to clear the cached spell check object, and no
    * preference saving will happen.
    */
   void          UninitSpellChecker();
@@ -187,11 +179,11 @@ interface nsIEditorSpellCheck : nsISuppo
    * invalid.
    */
   boolean       CheckCurrentWordNoSuggest(in wstring suggestedWord);
 
   /**
    * Update the dictionary in use to be sure it corresponds to what the editor
    * needs.
    */
-  void          UpdateCurrentDictionary(in nsIEditor editor);
+  void          UpdateCurrentDictionary();
 
 };
--- a/editor/libeditor/html/nsHTMLEditRules.cpp
+++ b/editor/libeditor/html/nsHTMLEditRules.cpp
@@ -3725,17 +3725,21 @@ nsHTMLEditRules::WillCSSIndent(nsISelect
     {
       if (IsBlockNode(curNode)) {
         RelativeChangeIndentationOfElementNode(curNode, +1);
         curQuote = nsnull;
       }
       else {
         if (!curQuote)
         {
+          // First, check that our element can contain a div.
           NS_NAMED_LITERAL_STRING(divquoteType, "div");
+          if (!mEditor->CanContainTag(curParent, divquoteType))
+            return NS_OK; // cancelled
+
           res = SplitAsNeeded(&divquoteType, address_of(curParent), &offset);
           NS_ENSURE_SUCCESS(res, res);
           res = mHTMLEditor->CreateNode(divquoteType, curParent, offset, getter_AddRefs(curQuote));
           NS_ENSURE_SUCCESS(res, res);
           RelativeChangeIndentationOfElementNode(curQuote, +1);
           // remember our new block for postprocessing
           mNewBlock = curQuote;
           // curQuote is now the correct thing to put curNode in
@@ -3952,16 +3956,20 @@ nsHTMLEditRules::WillHTMLIndent(nsISelec
           res = InDifferentTableElements(curQuote, curNode, &bInDifTblElems);
           NS_ENSURE_SUCCESS(res, res);
           if (bInDifTblElems)
             curQuote = nsnull;
         }
         
         if (!curQuote) 
         {
+          // First, check that our element can contain a blockquote.
+          if (!mEditor->CanContainTag(curParent, quoteType))
+            return NS_OK; // cancelled
+
           res = SplitAsNeeded(&quoteType, address_of(curParent), &offset);
           NS_ENSURE_SUCCESS(res, res);
           res = mHTMLEditor->CreateNode(quoteType, curParent, offset, getter_AddRefs(curQuote));
           NS_ENSURE_SUCCESS(res, res);
           // remember our new block for postprocessing
           mNewBlock = curQuote;
           // curQuote is now the correct thing to put curNode in
         }
@@ -4084,20 +4092,20 @@ nsHTMLEditRules::WillOutdent(nsISelectio
           // fall out and handle curNode
         }
       }
       
       // are we inside a blockquote?
       nsCOMPtr<nsIDOMNode> n = curNode;
       nsCOMPtr<nsIDOMNode> tmp;
       curBlockQuoteIsIndentedWithCSS = PR_FALSE;
-      // keep looking up the hierarchy as long as we don't hit the body or a table element
-      // (other than an entire table)
-      while (!nsTextEditUtils::IsBody(n) &&   
-             (nsHTMLEditUtils::IsTable(n) || !nsHTMLEditUtils::IsTableElement(n)))
+      // keep looking up the hierarchy as long as we don't hit the body or the
+      // active editing host or a table element (other than an entire table)
+      while (!nsTextEditUtils::IsBody(n) && mHTMLEditor->IsNodeInActiveEditor(n)
+          && (nsHTMLEditUtils::IsTable(n) || !nsHTMLEditUtils::IsTableElement(n)))
       {
         n->GetParentNode(getter_AddRefs(tmp));
         if (!tmp) {
           break;
         }
         n = tmp;
         if (nsHTMLEditUtils::IsBlockquote(n))
         {
@@ -4780,29 +4788,33 @@ nsHTMLEditRules::WillAlign(nsISelection 
       }
       // clear out curDiv so that we don't put nodes after this one into it
     }      
 
     // need to make a div to put things in if we haven't already,
     // or if this node doesn't go in div we used earlier.
     if (!curDiv || transitionList[i])
     {
+      // First, check that our element can contain a div.
       NS_NAMED_LITERAL_STRING(divType, "div");
+      if (!mEditor->CanContainTag(curParent, divType))
+        return NS_OK; // cancelled
+
       res = SplitAsNeeded(&divType, address_of(curParent), &offset);
       NS_ENSURE_SUCCESS(res, res);
       res = mHTMLEditor->CreateNode(divType, curParent, offset, getter_AddRefs(curDiv));
       NS_ENSURE_SUCCESS(res, res);
       // remember our new block for postprocessing
       mNewBlock = curDiv;
       // set up the alignment on the div
       nsCOMPtr<nsIDOMElement> divElem = do_QueryInterface(curDiv);
       res = AlignBlock(divElem, alignType, PR_TRUE);
-//      nsAutoString attr(NS_LITERAL_STRING("align"));
-//      res = mHTMLEditor->SetAttribute(divElem, attr, *alignType);
-//      NS_ENSURE_SUCCESS(res, res);
+      //nsAutoString attr(NS_LITERAL_STRING("align"));
+      //res = mHTMLEditor->SetAttribute(divElem, attr, *alignType);
+      //NS_ENSURE_SUCCESS(res, res);
       // curDiv is now the correct thing to put curNode in
     }
 
     // tuck the node into the end of the active div
     res = mHTMLEditor->MoveNode(curNode, curDiv, -1);
     NS_ENSURE_SUCCESS(res, res);
   }
 
@@ -5593,19 +5605,23 @@ nsHTMLEditRules::GetPromotedPoint(RulesE
         break;
 
       res = nsEditor::GetNodeLocation(node, address_of(parent), &pOffset);
       NS_ENSURE_SUCCESS(res, res);
 
       // Don't walk past the editable section. Note that we need to check
       // before walking up to a parent because we need to return the parent
       // object, so the parent itself might not be in the editable area, but
-      // it's OK.
-      if (!mHTMLEditor->IsNodeInActiveEditor(node) &&
-          !mHTMLEditor->IsNodeInActiveEditor(parent)) {
+      // it's OK if we're not performing a block-level action.
+      PRBool blockLevelAction = (actionID == nsHTMLEditor::kOpIndent)
+                             || (actionID == nsHTMLEditor::kOpOutdent)
+                             || (actionID == nsHTMLEditor::kOpAlign)
+                             || (actionID == nsHTMLEditor::kOpMakeBasicBlock);
+      if (!mHTMLEditor->IsNodeInActiveEditor(parent) &&
+          (blockLevelAction || !mHTMLEditor->IsNodeInActiveEditor(node))) {
         break;
       }
 
       node = parent;
       offset = pOffset;
       res = mHTMLEditor->GetPriorHTMLNode(node, offset, address_of(nearNode), PR_TRUE);
       NS_ENSURE_SUCCESS(res, res);
     } 
@@ -8930,18 +8946,27 @@ nsHTMLEditRules::RelativeChangeIndentati
     if (0 < f) {
       nsAutoString newValue;
       newValue.AppendFloat(f);
       newValue.Append(unitString);
       mHTMLEditor->mHTMLCSSUtils->SetCSSProperty(element, marginProperty, newValue, PR_FALSE);
     }
     else {
       mHTMLEditor->mHTMLCSSUtils->RemoveCSSProperty(element, marginProperty, value, PR_FALSE);
-      if (nsHTMLEditUtils::IsDiv(aNode)) {
-        // we deal with a DIV ; let's see if it is useless and if we can remove it
+      // remove unnecessary DIV blocks:
+      // we could skip this section but that would cause a FAIL in
+      // editor/libeditor/html/tests/browserscope/richtext.html, which expects
+      // to unapply a CSS "indent" (<div style="margin-left: 40px;">) by
+      // removing the DIV container instead of just removing the CSS property.
+      nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
+      if (nsHTMLEditUtils::IsDiv(aNode)
+          && (node != mHTMLEditor->GetActiveEditingHost())
+          && mHTMLEditor->IsNodeInActiveEditor(aNode)) {
+        // we deal with an editable DIV;
+        // let's see if it is useless and if we can remove it
         nsCOMPtr<nsIDOMNamedNodeMap> attributeList;
         res = element->GetAttributes(getter_AddRefs(attributeList));
         NS_ENSURE_SUCCESS(res, res);
         PRUint32 count;
         attributeList->GetLength(&count);
         if (!count) {
           // the DIV has no attribute at all, let's remove it
           res = mHTMLEditor->RemoveContainer(element);
--- a/editor/libeditor/html/tests/Makefile.in
+++ b/editor/libeditor/html/tests/Makefile.in
@@ -81,16 +81,17 @@ include $(topsrcdir)/config/rules.mk
 		test_bug612447.html \
 		test_bug620906.html \
 		test_bug622371.html \
 		test_bug629845.html \
 		test_bug640321.html \
 		test_bug668599.html \
 		test_bug674861.html \
 		test_bug676401.html \
+		test_bug677752.html \
 		test_CF_HTML_clipboard.html \
 		test_contenteditable_focus.html \
 		test_htmleditor_keyevent_handling.html \
 		test_select_all_without_body.html \
 		file_select_all_without_body.html \
 		test_root_element_replacement.html \
 		$(NULL)
 
--- a/editor/libeditor/html/tests/browserscope/lib/richtext2/currentStatus.js
+++ b/editor/libeditor/html/tests/browserscope/lib/richtext2/currentStatus.js
@@ -4474,21 +4474,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<blockquote>`foo[bar]baz´</blockquote>",
           "innerHTML": "<blockquote>`foo[bar]baz´</blockquote>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><blockquote>`foo[bar]baz´</blockquote></body>",
           "bodyInnerHTML": "<blockquote>`foo[bar]baz´</blockquote>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><blockquote>`foo[bar]baz´</blockquote></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 0,
-          "valresult": 2,
-          "selresult": 3,
-          "output": "EXECUTION EXCEPTION: [Exception... \"Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMHTMLDocument.execCommand]\"  nsresult: \"0x80004005 (NS_ERROR_FAILURE)\"  location: \"JS frame :: http://mochi.test:8888/tests/editor/libeditor/html/tests/browserscope/lib/richtext2/richtext2/static/js/run.js :: runSingleTest :: line 143\"  data: no]"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<blockquote>`foo[bar]baz´</blockquote>",
+          "innerHTML": "<blockquote>`foo[bar]baz´</blockquote>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><blockquote>`foo[bar]baz´</blockquote></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><blockquote>`foo[bar]baz´</blockquote></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><blockquote>`foo[bar]baz´</blockquote></div>CAN<br>ARY</body>"
         }
       },
       "FB:BQ_BR.BR-1_SM": {
         "dM": {
           "valscore": 1,
           "selscore": 1,
           "valresult": 8,
           "selresult": 5,
@@ -4505,21 +4509,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<blockquote>`fo[o´<br>`bar´<br>`b]az´</blockquote>",
           "innerHTML": "<blockquote>`fo[o´<br>`bar´<br>`b]az´</blockquote>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><blockquote>`fo[o´<br>`bar´<br>`b]az´</blockquote></body>",
           "bodyInnerHTML": "<blockquote>`fo[o´<br>`bar´<br>`b]az´</blockquote>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><blockquote>`fo[o´<br>`bar´<br>`b]az´</blockquote></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 0,
-          "valresult": 2,
-          "selresult": 3,
-          "output": "EXECUTION EXCEPTION: [Exception... \"Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMHTMLDocument.execCommand]\"  nsresult: \"0x80004005 (NS_ERROR_FAILURE)\"  location: \"JS frame :: http://mochi.test:8888/tests/editor/libeditor/html/tests/browserscope/lib/richtext2/richtext2/static/js/run.js :: runSingleTest :: line 143\"  data: no]"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<blockquote>`fo[o´<br>`bar´<br>`b]az´</blockquote>",
+          "innerHTML": "<blockquote>`fo[o´<br>`bar´<br>`b]az´</blockquote>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><blockquote>`fo[o´<br>`bar´<br>`b]az´</blockquote></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><blockquote>`fo[o´<br>`bar´<br>`b]az´</blockquote></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><blockquote>`fo[o´<br>`bar´<br>`b]az´</blockquote></div>CAN<br>ARY</body>"
         }
       },
       "BC:blue_TEXT-1_SI": {
         "dM": {
           "valscore": 0,
           "selscore": 0,
           "valresult": 6,
           "selresult": 3,
@@ -4851,21 +4859,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<blockquote>`foo[bar]baz´</blockquote>",
           "innerHTML": "<blockquote>`foo[bar]baz´</blockquote>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><blockquote>`foo[bar]baz´</blockquote></body>",
           "bodyInnerHTML": "<blockquote>`foo[bar]baz´</blockquote>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><blockquote>`foo[bar]baz´</blockquote></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 0,
-          "valresult": 2,
-          "selresult": 3,
-          "output": "EXECUTION EXCEPTION: [Exception... \"Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMHTMLDocument.execCommand]\"  nsresult: \"0x80004005 (NS_ERROR_FAILURE)\"  location: \"JS frame :: http://mochi.test:8888/tests/editor/libeditor/html/tests/browserscope/lib/richtext2/richtext2/static/js/run.js :: runSingleTest :: line 143\"  data: no]"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<blockquote>`foo[bar]baz´</blockquote>",
+          "innerHTML": "<blockquote>`foo[bar]baz´</blockquote>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><blockquote>`foo[bar]baz´</blockquote></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><blockquote>`foo[bar]baz´</blockquote></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><blockquote>`foo[bar]baz´</blockquote></div>CAN<br>ARY</body>"
         }
       },
       "JC_TEXT-1_SC": {
         "dM": {
           "valscore": 1,
           "selscore": 1,
           "valresult": 8,
           "selresult": 5,
@@ -4882,25 +4894,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<div align=\"center\">`foo^bar´</div>",
           "innerHTML": "<div align=\"center\">`foo^bar´</div>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div align=\"center\">`foo^bar´</div></body>",
           "bodyInnerHTML": "<div align=\"center\">`foo^bar´</div>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div align=\"center\">`foo^bar´</div></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 1,
-          "valresult": 7,
-          "selresult": 5,
-          "output": "<div xmlns=\"http://www.w3.org/1999/xhtml\" align=\"center\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>",
-          "innerHTML": "`foo^bar´",
-          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" align=\"center\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>",
-          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\" align=\"center\">`foo^bar´</div>CAN<br>ARY",
-          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div align=\"center\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>CAN<br>ARY</body>"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<div align=\"center\">`foo^bar´</div>",
+          "innerHTML": "<div align=\"center\">`foo^bar´</div>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><div align=\"center\">`foo^bar´</div></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><div align=\"center\">`foo^bar´</div></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><div align=\"center\">`foo^bar´</div></div>CAN<br>ARY</body>"
         }
       },
       "JF_TEXT-1_SC": {
         "dM": {
           "valscore": 1,
           "selscore": 1,
           "valresult": 8,
           "selresult": 5,
@@ -4917,25 +4929,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<div align=\"justify\">`foo^bar´</div>",
           "innerHTML": "<div align=\"justify\">`foo^bar´</div>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div align=\"justify\">`foo^bar´</div></body>",
           "bodyInnerHTML": "<div align=\"justify\">`foo^bar´</div>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div align=\"justify\">`foo^bar´</div></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 1,
-          "valresult": 7,
-          "selresult": 5,
-          "output": "<div xmlns=\"http://www.w3.org/1999/xhtml\" align=\"justify\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>",
-          "innerHTML": "`foo^bar´",
-          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" align=\"justify\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>",
-          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\" align=\"justify\">`foo^bar´</div>CAN<br>ARY",
-          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div align=\"justify\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>CAN<br>ARY</body>"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<div align=\"justify\">`foo^bar´</div>",
+          "innerHTML": "<div align=\"justify\">`foo^bar´</div>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><div align=\"justify\">`foo^bar´</div></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><div align=\"justify\">`foo^bar´</div></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><div align=\"justify\">`foo^bar´</div></div>CAN<br>ARY</body>"
         }
       },
       "JL_TEXT-1_SC": {
         "dM": {
           "valscore": 1,
           "selscore": 1,
           "valresult": 8,
           "selresult": 5,
@@ -4952,25 +4964,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<div align=\"left\">`foo^bar´</div>",
           "innerHTML": "<div align=\"left\">`foo^bar´</div>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div align=\"left\">`foo^bar´</div></body>",
           "bodyInnerHTML": "<div align=\"left\">`foo^bar´</div>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div align=\"left\">`foo^bar´</div></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 1,
-          "valresult": 7,
-          "selresult": 5,
-          "output": "<div xmlns=\"http://www.w3.org/1999/xhtml\" align=\"left\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>",
-          "innerHTML": "`foo^bar´",
-          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" align=\"left\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>",
-          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\" align=\"left\">`foo^bar´</div>CAN<br>ARY",
-          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div align=\"left\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>CAN<br>ARY</body>"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<div align=\"left\">`foo^bar´</div>",
+          "innerHTML": "<div align=\"left\">`foo^bar´</div>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><div align=\"left\">`foo^bar´</div></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><div align=\"left\">`foo^bar´</div></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><div align=\"left\">`foo^bar´</div></div>CAN<br>ARY</body>"
         }
       },
       "JR_TEXT-1_SC": {
         "dM": {
           "valscore": 1,
           "selscore": 1,
           "valresult": 8,
           "selresult": 5,
@@ -4987,25 +4999,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<div align=\"right\">`foo^bar´</div>",
           "innerHTML": "<div align=\"right\">`foo^bar´</div>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div align=\"right\">`foo^bar´</div></body>",
           "bodyInnerHTML": "<div align=\"right\">`foo^bar´</div>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div align=\"right\">`foo^bar´</div></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 1,
-          "valresult": 7,
-          "selresult": 5,
-          "output": "<div xmlns=\"http://www.w3.org/1999/xhtml\" align=\"right\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>",
-          "innerHTML": "`foo^bar´",
-          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" align=\"right\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>",
-          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\" align=\"right\">`foo^bar´</div>CAN<br>ARY",
-          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div align=\"right\" contenteditable=\"true\" id=\"editor-div\">`foo^bar´</div>CAN<br>ARY</body>"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<div align=\"right\">`foo^bar´</div>",
+          "innerHTML": "<div align=\"right\">`foo^bar´</div>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><div align=\"right\">`foo^bar´</div></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><div align=\"right\">`foo^bar´</div></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><div align=\"right\">`foo^bar´</div></div>CAN<br>ARY</body>"
         }
       },
       "H:H1_TEXT-1_SC": {
         "dM": {
           "valscore": 1,
           "selscore": 1,
           "valresult": 8,
           "selresult": 5,
@@ -5551,25 +5563,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<div style=\"margin-left: 40px;\">`foo[bar]baz´</div>",
           "innerHTML": "<div style=\"margin-left: 40px;\">`foo[bar]baz´</div>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div style=\"margin-left: 40px;\">`foo[bar]baz´</div></body>",
           "bodyInnerHTML": "<div style=\"margin-left: 40px;\">`foo[bar]baz´</div>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div style=\"margin-left: 40px;\">`foo[bar]baz´</div></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 1,
-          "valresult": 7,
-          "selresult": 5,
-          "output": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\" style=\"margin-left: 40px;\">`foo[bar]baz´</div>",
-          "innerHTML": "`foo[bar]baz´",
-          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\" style=\"margin-left: 40px;\">`foo[bar]baz´</div>",
-          "bodyInnerHTML": "CAN<br>ARY<div style=\"margin-left: 40px;\" id=\"editor-div\" contenteditable=\"true\">`foo[bar]baz´</div>CAN<br>ARY",
-          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\" style=\"margin-left: 40px;\">`foo[bar]baz´</div>CAN<br>ARY</body>"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<div style=\"margin-left: 40px;\">`foo[bar]baz´</div>",
+          "innerHTML": "<div style=\"margin-left: 40px;\">`foo[bar]baz´</div>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><div style=\"margin-left: 40px;\">`foo[bar]baz´</div></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><div style=\"margin-left: 40px;\">`foo[bar]baz´</div></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><div style=\"margin-left: 40px;\">`foo[bar]baz´</div></div>CAN<br>ARY</body>"
         }
       },
       "JC_TEXT-1_SC": {
         "dM": {
           "valscore": 1,
           "selscore": 1,
           "valresult": 8,
           "selresult": 5,
@@ -5586,25 +5598,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<div style=\"text-align: center;\">`foo^bar´</div>",
           "innerHTML": "<div style=\"text-align: center;\">`foo^bar´</div>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div style=\"text-align: center;\">`foo^bar´</div></body>",
           "bodyInnerHTML": "<div style=\"text-align: center;\">`foo^bar´</div>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div style=\"text-align: center;\">`foo^bar´</div></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 1,
-          "valresult": 7,
-          "selresult": 5,
-          "output": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\" style=\"text-align: center;\">`foo^bar´</div>",
-          "innerHTML": "`foo^bar´",
-          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\" style=\"text-align: center;\">`foo^bar´</div>",
-          "bodyInnerHTML": "CAN<br>ARY<div style=\"text-align: center;\" id=\"editor-div\" contenteditable=\"true\">`foo^bar´</div>CAN<br>ARY",
-          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\" style=\"text-align: center;\">`foo^bar´</div>CAN<br>ARY</body>"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<div style=\"text-align: center;\">`foo^bar´</div>",
+          "innerHTML": "<div style=\"text-align: center;\">`foo^bar´</div>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><div style=\"text-align: center;\">`foo^bar´</div></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><div style=\"text-align: center;\">`foo^bar´</div></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><div style=\"text-align: center;\">`foo^bar´</div></div>CAN<br>ARY</body>"
         }
       },
       "JF_TEXT-1_SC": {
         "dM": {
           "valscore": 1,
           "selscore": 1,
           "valresult": 8,
           "selresult": 5,
@@ -5621,25 +5633,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<div style=\"text-align: justify;\">`foo^bar´</div>",
           "innerHTML": "<div style=\"text-align: justify;\">`foo^bar´</div>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div style=\"text-align: justify;\">`foo^bar´</div></body>",
           "bodyInnerHTML": "<div style=\"text-align: justify;\">`foo^bar´</div>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div style=\"text-align: justify;\">`foo^bar´</div></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 1,
-          "valresult": 7,
-          "selresult": 5,
-          "output": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\" style=\"text-align: justify;\">`foo^bar´</div>",
-          "innerHTML": "`foo^bar´",
-          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\" style=\"text-align: justify;\">`foo^bar´</div>",
-          "bodyInnerHTML": "CAN<br>ARY<div style=\"text-align: justify;\" id=\"editor-div\" contenteditable=\"true\">`foo^bar´</div>CAN<br>ARY",
-          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\" style=\"text-align: justify;\">`foo^bar´</div>CAN<br>ARY</body>"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<div style=\"text-align: justify;\">`foo^bar´</div>",
+          "innerHTML": "<div style=\"text-align: justify;\">`foo^bar´</div>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><div style=\"text-align: justify;\">`foo^bar´</div></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><div style=\"text-align: justify;\">`foo^bar´</div></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><div style=\"text-align: justify;\">`foo^bar´</div></div>CAN<br>ARY</body>"
         }
       },
       "JL_TEXT-1_SC": {
         "dM": {
           "valscore": 1,
           "selscore": 1,
           "valresult": 8,
           "selresult": 5,
@@ -5656,25 +5668,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<div style=\"text-align: left;\">`foo^bar´</div>",
           "innerHTML": "<div style=\"text-align: left;\">`foo^bar´</div>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div style=\"text-align: left;\">`foo^bar´</div></body>",
           "bodyInnerHTML": "<div style=\"text-align: left;\">`foo^bar´</div>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div style=\"text-align: left;\">`foo^bar´</div></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 1,
-          "valresult": 7,
-          "selresult": 5,
-          "output": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\" style=\"text-align: left;\">`foo^bar´</div>",
-          "innerHTML": "`foo^bar´",
-          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\" style=\"text-align: left;\">`foo^bar´</div>",
-          "bodyInnerHTML": "CAN<br>ARY<div style=\"text-align: left;\" id=\"editor-div\" contenteditable=\"true\">`foo^bar´</div>CAN<br>ARY",
-          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\" style=\"text-align: left;\">`foo^bar´</div>CAN<br>ARY</body>"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<div style=\"text-align: left;\">`foo^bar´</div>",
+          "innerHTML": "<div style=\"text-align: left;\">`foo^bar´</div>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><div style=\"text-align: left;\">`foo^bar´</div></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><div style=\"text-align: left;\">`foo^bar´</div></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><div style=\"text-align: left;\">`foo^bar´</div></div>CAN<br>ARY</body>"
         }
       },
       "JR_TEXT-1_SC": {
         "dM": {
           "valscore": 1,
           "selscore": 1,
           "valresult": 8,
           "selresult": 5,
@@ -5691,25 +5703,25 @@ const TEST_RESULTS = {
           "selresult": 5,
           "output": "<div style=\"text-align: right;\">`foo^bar´</div>",
           "innerHTML": "<div style=\"text-align: right;\">`foo^bar´</div>",
           "outerHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div style=\"text-align: right;\">`foo^bar´</div></body>",
           "bodyInnerHTML": "<div style=\"text-align: right;\">`foo^bar´</div>",
           "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\"><div style=\"text-align: right;\">`foo^bar´</div></body>"
         },
         "div": {
-          "valscore": 0,
-          "selscore": 1,
-          "valresult": 7,
-          "selresult": 5,
-          "output": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\" style=\"text-align: right;\">`foo^bar´</div>",
-          "innerHTML": "`foo^bar´",
-          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\" style=\"text-align: right;\">`foo^bar´</div>",
-          "bodyInnerHTML": "CAN<br>ARY<div style=\"text-align: right;\" id=\"editor-div\" contenteditable=\"true\">`foo^bar´</div>CAN<br>ARY",
-          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\" style=\"text-align: right;\">`foo^bar´</div>CAN<br>ARY</body>"
+          "valscore": 1,
+          "selscore": 1,
+          "valresult": 8,
+          "selresult": 5,
+          "output": "<div style=\"text-align: right;\">`foo^bar´</div>",
+          "innerHTML": "<div style=\"text-align: right;\">`foo^bar´</div>",
+          "outerHTML": "<div xmlns=\"http://www.w3.org/1999/xhtml\" contenteditable=\"true\" id=\"editor-div\"><div style=\"text-align: right;\">`foo^bar´</div></div>",
+          "bodyInnerHTML": "CAN<br>ARY<div id=\"editor-div\" contenteditable=\"true\"><div style=\"text-align: right;\">`foo^bar´</div></div>CAN<br>ARY",
+          "bodyOuterHTML": "<body xmlns=\"http://www.w3.org/1999/xhtml\">CAN<br>ARY<div contenteditable=\"true\" id=\"editor-div\"><div style=\"text-align: right;\">`foo^bar´</div></div>CAN<br>ARY</body>"
         }
       }
     }
   },
   "C": {
     "Proposed": {
       "I_I-1_SL": {
         "dM": {
--- a/editor/libeditor/html/tests/test_bug414526.html
+++ b/editor/libeditor/html/tests/test_bug414526.html
@@ -37,40 +37,53 @@ function runTests()
   }
 
   function moveCaretToEndOf(aEditor)
   {
     selection.selectAllChildren(aEditor);
     selection.collapseToEnd();
   }
 
+  /* TestCase #1
+   */
   const kTestCase1 =
     "<p id=\"editor1\" contenteditable=\"true\">editor1</p>" +
     "<p id=\"editor2\" contenteditable=\"true\">editor2</p>" +
     "<div id=\"editor3\" contenteditable=\"true\"><div>editor3</div></div>" +
     "<p id=\"editor4\" contenteditable=\"true\">editor4</p>" +
     "non-editable text" +
     "<p id=\"editor5\" contenteditable=\"true\">editor5</p>";
 
-  const kTestCase1_editor3_specialcase =
+  const kTestCase1_editor3_deleteAtStart =
     "<p id=\"editor1\" contenteditable=\"true\">editor1</p>" +
     "<p id=\"editor2\" contenteditable=\"true\">editor2</p>" +
     "<div id=\"editor3\" contenteditable=\"true\"><div>ditor3</div></div>" +
     "<p id=\"editor4\" contenteditable=\"true\">editor4</p>" +
     "non-editable text" +
     "<p id=\"editor5\" contenteditable=\"true\">editor5</p>";
 
+  const kTestCase1_editor3_backspaceAtEnd =
+    "<p id=\"editor1\" contenteditable=\"true\">editor1</p>" +
+    "<p id=\"editor2\" contenteditable=\"true\">editor2</p>" +
+    "<div id=\"editor3\" contenteditable=\"true\"><div>editor</div></div>" +
+    "<p id=\"editor4\" contenteditable=\"true\">editor4</p>" +
+    "non-editable text" +
+    "<p id=\"editor5\" contenteditable=\"true\">editor5</p>";
+
   container.innerHTML = kTestCase1;
 
   var editor1 = document.getElementById("editor1");
   var editor2 = document.getElementById("editor2");
   var editor3 = document.getElementById("editor3");
   var editor4 = document.getElementById("editor4");
   var editor5 = document.getElementById("editor5");
 
+  /* TestCase #1:
+   * pressing backspace key at start should not change the content.
+   */
   editor2.focus();
   moveCaretToStartOf(editor2);
   synthesizeKey("VK_BACK_SPACE", { });
   is(container.innerHTML, kTestCase1,
      "Pressing backspace key at start of editor2 changes the content");
   reset();
 
   editor3.focus();
@@ -89,16 +102,19 @@ function runTests()
 
   editor5.focus();
   moveCaretToStartOf(editor5);
   synthesizeKey("VK_BACK_SPACE", { });
   is(container.innerHTML, kTestCase1,
      "Pressing backspace key at start of editor5 changes the content");
   reset();
 
+  /* TestCase #1:
+   * pressing delete key at end should not change the content.
+   */
   editor1.focus();
   moveCaretToEndOf(editor1);
   synthesizeKey("VK_DELETE", { });
   is(container.innerHTML, kTestCase1,
      "Pressing delete key at end of editor1 changes the content");
   reset();
 
   editor2.focus();
@@ -122,31 +138,48 @@ function runTests()
 
   editor4.focus();
   moveCaretToEndOf(editor4);
   synthesizeKey("VK_DELETE", { });
   is(container.innerHTML, kTestCase1,
      "Pressing delete key at end of editor4 changes the content");
   reset();
 
-  // Cases when the caret is not on text node.
+  /* TestCase #1: cases when the caret is not on text node.
+   *   - pressing delete key at start should remove the first character
+   *   - pressing backspace key at end should remove the first character
+   * and the adjacent blocks should not be changed.
+   */
   editor3.focus();
   moveCaretToStartOf(editor3);
   synthesizeKey("VK_DELETE", { });
-  is(container.innerHTML, kTestCase1_editor3_specialcase,
-     "Pressing delete key at end of editor3 changes the content");
+  is(container.innerHTML, kTestCase1_editor3_deleteAtStart,
+     "Pressing delete key at start of editor3 changes adjacent elements"
+     + " and/or does not remove the first character.");
   reset();
 
+  // Backspace doesn't work here yet.
+  editor3.focus();
+  moveCaretToEndOf(editor3);
+  synthesizeKey("VK_BACK_SPACE", { });
+  todo_is(container.innerHTML, kTestCase1_editor3_backspaceAtEnd,
+          "Pressing backspace key at end of editor3 changes adjacent elements"
+          + " and/or does not remove the last character.");
+  reset();
+  //  We can still check that adjacent elements are not affected.
   editor3.focus();
   moveCaretToEndOf(editor3);
   synthesizeKey("VK_BACK_SPACE", { });
   is(container.innerHTML, kTestCase1,
      "Pressing backspace key at end of editor3 changes the content");
   reset();
 
+  /* TestCase #2:
+   * two adjacent editable <span> in a table cell.
+   */
   const kTestCase2 = "<table><tbody><tr><td><span id=\"editor1\" contenteditable=\"true\">test</span>" +
     "<span id=\"editor2\" contenteditable=\"true\">test</span></td></tr></tbody></table>";
 
   container.innerHTML = kTestCase2;
   editor1 = document.getElementById("editor1");
   editor2 = document.getElementById("editor2");
 
   editor2.focus();
@@ -158,16 +191,19 @@ function runTests()
 
   editor1.focus();
   moveCaretToEndOf(editor1);
   synthesizeKey("VK_DELETE", { });
   is(container.innerHTML, kTestCase2,
      "Pressing delete key at the end of editor1 changes the content for kTestCase2");
   reset();
 
+  /* TestCase #3:
+   * editable <span> in two adjacent table cells.
+   */
   const kTestCase3 = "<table><tbody><tr><td><span id=\"editor1\" contenteditable=\"true\">test</span></td>" +
     "<td><span id=\"editor2\" contenteditable=\"true\">test</span></td></tr></tbody></table>";
 
   container.innerHTML = kTestCase3;
   editor1 = document.getElementById("editor1");
   editor2 = document.getElementById("editor2");
 
   editor2.focus();
@@ -179,16 +215,19 @@ function runTests()
 
   editor1.focus();
   moveCaretToEndOf(editor1);
   synthesizeKey("VK_DELETE", { });
   is(container.innerHTML, kTestCase3,
      "Pressing delete key at the end of editor1 changes the content for kTestCase3");
   reset();
 
+  /* TestCase #4:
+   * editable <div> in two adjacent table cells.
+   */
   const kTestCase4 = "<table><tbody><tr><td><div id=\"editor1\" contenteditable=\"true\">test</div></td>" +
     "<td><div id=\"editor2\" contenteditable=\"true\">test</div></td></tr></tbody></table>";
 
   container.innerHTML = kTestCase4;
   editor1 = document.getElementById("editor1");
   editor2 = document.getElementById("editor2");
 
   editor2.focus();
new file mode 100644
--- /dev/null
+++ b/editor/libeditor/html/tests/test_bug677752.html
@@ -0,0 +1,107 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=677752
+-->
+<head>
+  <title>Test for Bug 677752</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/EventUtils.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=677752">Mozilla Bug 677752</a>
+<p id="display"></p>
+<div id="content">
+  <section contenteditable> foo bar </section>
+  <div contenteditable> foo bar </div>
+  <p contenteditable> foo bar </p>
+</div>
+
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 677752 **/
+SimpleTest.waitForExplicitFinish();
+SimpleTest.waitForFocus(runTests);
+
+function selectEditor(aEditor) {
+  aEditor.focus();
+  var selection = window.getSelection();
+  selection.selectAllChildren(aEditor);
+  selection.collapseToStart();
+}
+
+function runTests() {
+  var editor, node, initialHTML;
+  document.execCommand('styleWithCSS', false, true);
+
+  // editable <section>
+  editor = document.querySelector("section[contenteditable]");
+  initialHTML = editor.innerHTML;
+  selectEditor(editor);
+  // editable <section>: justify
+  document.execCommand("justifyright", false, null);
+  node = editor.querySelector("*");
+  is(node.nodeName.toLowerCase(), "div", "'justifyright' should create a <div> in the editable <section>.");
+  is(node.style.textAlign,      "right", "'justifyright' should create a 'text-align: right' CSS rule.");
+  document.execCommand("undo", false, null);
+  // editable <section>: indent
+  document.execCommand("indent", false, null);
+  node = editor.querySelector("*");
+  is(node.nodeName.toLowerCase(), "div", "'indent' should create a <div> in the editable <section>.");
+  is(node.style.marginLeft,      "40px", "'indent' should create a 'margin-left: 40px' CSS rule.");
+  // editable <section>: undo with outdent
+  // this should remove the whole <div> but only removing the CSS rule would be acceptable, too
+  document.execCommand("outdent", false, null);
+  is(editor.innerHTML, initialHTML, "'outdent' should undo the 'indent' action.");
+  // editable <section>: outdent again
+  document.execCommand("outdent", false, null);
+  is(editor.innerHTML, initialHTML, "another 'outdent' should not modify the <section> element.");
+
+  // editable <div>
+  editor = document.querySelector("div[contenteditable]");
+  initialHTML = editor.innerHTML;
+  selectEditor(editor);
+  // editable <div>: justify
+  document.execCommand("justifyright", false, null);
+  node = editor.querySelector("*");
+  is(node.nodeName.toLowerCase(), "div", "'justifyright' should create a <div> in the editable <div>.");
+  is(node.style.textAlign,      "right", "'justifyright' should create a 'text-align: right' CSS rule.");
+  document.execCommand("undo", false, null);
+  // editable <div>: indent
+  document.execCommand("indent", false, null);
+  node = editor.querySelector("*");
+  is(node.nodeName.toLowerCase(), "div", "'indent' should create a <div> in the editable <div>.");
+  is(node.style.marginLeft,      "40px", "'indent' should create a 'margin-left: 40px' CSS rule.");
+  // editable <div>: undo with outdent
+  // this should remove the whole <div> but only removing the CSS rule would be acceptable, too
+  document.execCommand("outdent", false, null);
+  is(editor.innerHTML, initialHTML, "'outdent' should undo the 'indent' action.");
+  // editable <div>: outdent again
+  document.execCommand("outdent", false, null);
+  is(editor.innerHTML, initialHTML, "another 'outdent' should not modify the <div> element.");
+
+  // editable <p>
+  // all block-level commands should be ignored (<p><div/></p> is not valid)
+  editor = document.querySelector("p[contenteditable]");
+  initialHTML = editor.innerHTML;
+  selectEditor(editor);
+  // editable <p>: justify
+  document.execCommand("justifyright", false, null);
+  is(editor.innerHTML, initialHTML, "'justifyright' should have no effect on <p>.");
+  // editable <p>: indent
+  document.execCommand("indent", false, null);
+  is(editor.innerHTML, initialHTML, "'indent' should have no effect on <p>.");
+  // editable <p>: outdent
+  document.execCommand("outdent", false, null);
+  is(editor.innerHTML, initialHTML, "'outdent' should have no effect on <p>.");
+
+  // done
+  SimpleTest.finish();
+}
+
+</script>
+</pre>
+</body>
+</html>
--- a/editor/libeditor/html/tests/test_htmleditor_keyevent_handling.html
+++ b/editor/libeditor/html/tests/test_htmleditor_keyevent_handling.html
@@ -320,35 +320,31 @@ function runTests()
          aIsPlaintext ? "<ul><li id=\"target\">ul list item\t</li></ul>" :
            "<ul><ul><li id=\"target\">ul list item</li></ul></ul>",
        aDescription + "Tab on UL");
     is(fm.focusedElement, aElement,
        aDescription + "focus moved unexpectedly (Tab on UL)");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab after Tab on UL",
           true, true, !aIsTabbable && !aIsReadonly && !aIsPlaintext);
-    // XXX why do we fail to outdent on non-tabbable HTML editor?
     is(aElement.innerHTML,
-       aIsReadonly || aIsTabbable ?
+       aIsReadonly || aIsTabbable || (!aIsPlaintext) ?
          "<ul><li id=\"target\">ul list item</li></ul>" :
-         aIsPlaintext ? "<ul><li id=\"target\">ul list item\t</li></ul>" :
-           "<ul><ul><li id=\"target\">ul list item</li></ul></ul>",
+         "<ul><li id=\"target\">ul list item\t</li></ul>",
        aDescription + "Shift+Tab after Tab on UL");
     is(fm.focusedElement, aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab after Tab on UL)");
 
     resetForIndent("<ul><li id=\"target\">ul list item</li></ul>");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab on UL",
           true, true, !aIsTabbable && !aIsReadonly && !aIsPlaintext);
     is(aElement.innerHTML,
-       aIsReadonly || aIsTabbable ?
-         "<ul><li id=\"target\">ul list item</li></ul>" :
-         aIsPlaintext ? "<ul><li id=\"target\">ul list item</li></ul>" :
-           "<ul><li id=\"target\">ul list item</li></ul>",
+       aIsReadonly || aIsTabbable || aIsPlaintext ?
+         "<ul><li id=\"target\">ul list item</li></ul>" : "ul list item",
        aDescription + "Shift+Tab on UL");
     is(fm.focusedElement, aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab on UL)");
 
     // Ctrl+Tab may be consumed by tabbrowser but editor shouldn't consume this.
     resetForIndent("<ul><li id=\"target\">ul list item</li></ul>");
     synthesizeKey("VK_TAB", { ctrlKey: true });
     check(aDescription + "Ctrl+Tab on UL", true, true, false);
@@ -384,35 +380,31 @@ function runTests()
          aIsPlaintext ? "<ol><li id=\"target\">ol list item\t</li></ol>" :
            "<ol><ol><li id=\"target\">ol list item</li></ol></ol>",
        aDescription + "Tab on OL");
     is(fm.focusedElement, aElement,
        aDescription + "focus moved unexpectedly (Tab on OL)");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab after Tab on OL",
           true, true, !aIsTabbable && !aIsReadonly && !aIsPlaintext);
-    // XXX why do we fail to outdent on non-tabbable HTML editor?
     is(aElement.innerHTML,
-       aIsReadonly || aIsTabbable ?
+       aIsReadonly || aIsTabbable || (!aIsPlaintext) ?
          "<ol><li id=\"target\">ol list item</li></ol>" :
-         aIsPlaintext ? "<ol><li id=\"target\">ol list item\t</li></ol>" :
-           "<ol><ol><li id=\"target\">ol list item</li></ol></ol>",
+         "<ol><li id=\"target\">ol list item\t</li></ol>",
        aDescription + "Shift+Tab after Tab on OL");
     is(fm.focusedElement, aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab after Tab on OL)");
 
     resetForIndent("<ol><li id=\"target\">ol list item</li></ol>");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab on OL",
           true, true, !aIsTabbable && !aIsReadonly && !aIsPlaintext);
     is(aElement.innerHTML,
-       aIsReadonly || aIsTabbable ?
-         "<ol><li id=\"target\">ol list item</li></ol>" :
-         aIsPlaintext ? "<ol><li id=\"target\">ol list item</li></ol>" :
-           "<ol><li id=\"target\">ol list item</li></ol>",
+       aIsReadonly || aIsTabbable || aIsPlaintext ?
+         "<ol><li id=\"target\">ol list item</li></ol>" : "ol list item",
        aDescription + "Shfit+Tab on OL");
     is(fm.focusedElement, aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab on OL)");
 
     // Ctrl+Tab may be consumed by tabbrowser but editor shouldn't consume this.
     resetForIndent("<ol><li id=\"target\">ol list item</li></ol>");
     synthesizeKey("VK_TAB", { ctrlKey: true });
     check(aDescription + "Ctrl+Tab on OL", true, true, false);
--- a/embedding/android/GeckoSurfaceView.java
+++ b/embedding/android/GeckoSurfaceView.java
@@ -164,18 +164,40 @@ class GeckoSurfaceView
             if (c == null)
                 return;
             c.drawBitmap(bitmap, 0, 0, null);
             holder.unlockCanvasAndPost(c);
         }
     }
 
     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
+
+        // Force exactly one frame to render
+        // because the surface change is only seen after we
+        // have swapped the back buffer.
+        // The buffer size only changes after the next swap buffer.
+        // We need to make sure the Gecko's view resize when Android's 
+        // buffer resizes.
+        if (mDrawMode == DRAW_GLES_2) {
+            // When we get a surfaceChange event, we have 0 to n paint events 
+            // waiting in the Gecko event queue. We will make the first
+            // succeed and the abort the others.
+            mDrawSingleFrame = true;
+            if (!mInDrawing) { 
+                // Queue at least one paint event in case none are queued.
+                GeckoAppShell.scheduleRedraw();
+            }
+            GeckoAppShell.geckoEventSync();
+            mDrawSingleFrame = false;
+            mAbortDraw = false;
+        }
+
         if (mShowingSplashScreen)
             drawSplashScreen(holder, width, height);
+
         mSurfaceLock.lock();
 
         try {
             if (mInDrawing) {
                 Log.w(LOG_FILE_NAME, "surfaceChanged while mInDrawing is true!");
             }
 
             boolean invalidSize;
@@ -216,16 +238,22 @@ class GeckoSurfaceView
                 c.drawARGB(255, 255, 255, 255);
                 holder.unlockCanvasAndPost(c);
                 return;
             } else {
                 GeckoAppShell.scheduleRedraw();
             }
         } finally {
             mSurfaceLock.unlock();
+            if (mDrawMode == DRAW_GLES_2) {
+                // Force a frame to be drawn before the surfaceChange returns,
+                // otherwise we get artifacts.
+                GeckoAppShell.scheduleRedraw();
+                GeckoAppShell.geckoEventSync();
+            }
         }
 
         Object syncDrawObject = null;
         try {
             syncDrawObject = mSyncDraws.take();
         } catch (InterruptedException ie) {
             Log.e(LOG_FILE_NAME, "Threw exception while getting sync draw bitmap/buffer: ", ie);
         }
@@ -249,17 +277,22 @@ class GeckoSurfaceView
 
     public void surfaceDestroyed(SurfaceHolder holder) {
         Log.i(LOG_FILE_NAME, "surface destroyed");
         mSurfaceValid = false;
         mSoftwareBuffer = null;
         mSoftwareBufferCopy = null;
         mSoftwareBitmap = null;
         GeckoEvent e = new GeckoEvent(GeckoEvent.SURFACE_DESTROYED);
-        GeckoAppShell.sendEventToGecko(e);
+        if (mDrawMode == DRAW_GLES_2) {
+            // Ensure GL cleanup occurs before we return.
+            GeckoAppShell.sendEventToGeckoSync(e);
+        } else {
+            GeckoAppShell.sendEventToGecko(e);
+        }
     }
 
     public Bitmap getSoftwareDrawBitmap() {
         if (mSoftwareBitmap == null ||
             mSoftwareBitmap.getHeight() != mHeight ||
             mSoftwareBitmap.getWidth() != mWidth) {
             mSoftwareBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.RGB_565);
         }
@@ -288,23 +321,33 @@ class GeckoSurfaceView
 
     /*
      * Called on Gecko thread
      */
 
     public static final int DRAW_ERROR = 0;
     public static final int DRAW_GLES_2 = 1;
     public static final int DRAW_2D = 2;
+    // Drawing is disable when the surface buffer
+    // has changed size but we haven't yet processed the
+    // resize event.
+    public static final int DRAW_DISABLED = 3;
 
     public int beginDrawing() {
         if (mInDrawing) {
             Log.e(LOG_FILE_NAME, "Recursive beginDrawing call!");
             return DRAW_ERROR;
         }
 
+        // Once we drawn our first frame after resize we can ignore
+        // the other draw events until we handle the resize events.
+        if (mAbortDraw) {
+            return DRAW_DISABLED;
+        }
+
         /* Grab the lock, which we'll hold while we're drawing.
          * It gets released in endDrawing(), and is also used in surfaceChanged
          * to make sure that we don't change our surface details while
          * we're in the middle of drawing (and especially in the middle of
          * executing beginDrawing/endDrawing).
          *
          * We might not need to hold this lock in between
          * beginDrawing/endDrawing, and might just be able to make
@@ -325,16 +368,19 @@ class GeckoSurfaceView
     }
 
     public void endDrawing() {
         if (!mInDrawing) {
             Log.e(LOG_FILE_NAME, "endDrawing without beginDrawing!");
             return;
         }
 
+       if (mDrawSingleFrame)
+            mAbortDraw = true;
+
         try {
             if (!mSurfaceValid) {
                 Log.e(LOG_FILE_NAME, "endDrawing with false mSurfaceValid");
                 return;
             }
         } finally {
             mInDrawing = false;
 
@@ -652,16 +698,20 @@ class GeckoSurfaceView
     }
 
     // Is this surface valid for drawing into?
     boolean mSurfaceValid;
 
     // Are we actively between beginDrawing/endDrawing?
     boolean mInDrawing;
 
+    // Used to finish the current buffer before changing the surface size
+    boolean mDrawSingleFrame = false;
+    boolean mAbortDraw = false;
+
     // Are we waiting for a buffer to draw in surfaceChanged?
     boolean mSyncDraw;
 
     // True if gecko requests a buffer
     int mDrawMode;
 
     static boolean mShowingSplashScreen = true;
     static String  mSplashStatusMsg = "";
--- a/extensions/pref/system-pref/src/gconf/nsSystemPrefService.cpp
+++ b/extensions/pref/system-pref/src/gconf/nsSystemPrefService.cpp
@@ -280,17 +280,17 @@ NS_IMETHODIMP nsSystemPrefService::GetPr
 /* boolean getBoolPref (in string aPrefName); */
 NS_IMETHODIMP nsSystemPrefService::GetBoolPref(const char *aPrefName, PRBool *_retval)
 {
     return mInitialized ?
         mGConf->GetBoolPref(aPrefName, _retval) : NS_ERROR_FAILURE;
 }
 
 /* void setBoolPref (in string aPrefName, in long aValue); */
-NS_IMETHODIMP nsSystemPrefService::SetBoolPref(const char *aPrefName, PRInt32 aValue)
+NS_IMETHODIMP nsSystemPrefService::SetBoolPref(const char *aPrefName, PRBool aValue)
 {
     return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 /* string getCharPref (in string aPrefName); */
 NS_IMETHODIMP nsSystemPrefService::GetCharPref(const char *aPrefName, char **_retval)
 {
     return mInitialized ?
--- a/extensions/spellcheck/src/mozInlineSpellChecker.cpp
+++ b/extensions/spellcheck/src/mozInlineSpellChecker.cpp
@@ -1760,18 +1760,17 @@ NS_IMETHODIMP mozInlineSpellChecker::Upd
     return NS_OK;
   }
 
   nsAutoString previousDictionary;
   if (NS_FAILED(mSpellCheck->GetCurrentDictionary(previousDictionary))) {
     previousDictionary.Truncate();
   }
 
-  nsCOMPtr<nsIEditor> editor (do_QueryReferent(mEditor));
-  nsresult rv = mSpellCheck->UpdateCurrentDictionary(editor);
+  nsresult rv = mSpellCheck->UpdateCurrentDictionary();
 
   nsAutoString currentDictionary;
   if (NS_FAILED(mSpellCheck->GetCurrentDictionary(currentDictionary))) {
     currentDictionary.Truncate();
   }
 
   if (!previousDictionary.Equals(currentDictionary)) {
       rv = SpellCheckRange(nsnull);
--- a/extensions/spellcheck/src/mozSpellChecker.cpp
+++ b/extensions/spellcheck/src/mozSpellChecker.cpp
@@ -36,20 +36,16 @@
 
 #include "mozSpellChecker.h"
 #include "nsIServiceManager.h"
 #include "mozISpellI18NManager.h"
 #include "nsIStringEnumerator.h"
 #include "nsICategoryManager.h"
 #include "nsISupportsPrimitives.h"
 
-// The number 130 more or less comes out of thin air.
-// See https://bugzilla.mozilla.org/show_bug.cgi?id=355178#c78 for a pseudo-rationale.
-#define UNREASONABLE_WORD_LENGTH 130
-
 #define DEFAULT_SPELL_CHECKER "@mozilla.org/spellchecker/engine;1"
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(mozSpellChecker)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(mozSpellChecker)
 
 NS_INTERFACE_MAP_BEGIN(mozSpellChecker)
   NS_INTERFACE_MAP_ENTRY(nsISpellChecker)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsISpellChecker)
@@ -144,22 +140,16 @@ mozSpellChecker::NextMisspelledWord(nsAS
 NS_IMETHODIMP 
 mozSpellChecker::CheckWord(const nsAString &aWord, PRBool *aIsMisspelled, nsTArray<nsString> *aSuggestions)
 {
   nsresult result;
   PRBool correct;
   if(!mSpellCheckingEngine)
     return NS_ERROR_NULL_POINTER;
 
-  // don't bother to check crazy words
-  if (aWord.Length() > UNREASONABLE_WORD_LENGTH) {
-    *aIsMisspelled = PR_TRUE;
-    return NS_OK;
-  }
-
   *aIsMisspelled = PR_FALSE;
   result = mSpellCheckingEngine->Check(PromiseFlatString(aWord).get(), &correct);
   NS_ENSURE_SUCCESS(result, result);
   if(!correct){
     if(aSuggestions){
       PRUint32 count,i;
       PRUnichar **words;
       
--- a/gfx/2d/DrawTargetD2D.cpp
+++ b/gfx/2d/DrawTargetD2D.cpp
@@ -45,29 +45,29 @@
 #include "Logging.h"
 #include "Tools.h"
 
 #ifndef M_PI
 #define M_PI 3.14159265358979323846
 #endif
 
 typedef HRESULT (WINAPI*D2D1CreateFactoryFunc)(
-    __in D2D1_FACTORY_TYPE factoryType,
-    __in REFIID iid,
-    __in_opt CONST D2D1_FACTORY_OPTIONS *pFactoryOptions,
-    __out void **factory
+    D2D1_FACTORY_TYPE factoryType,
+    REFIID iid,
+    CONST D2D1_FACTORY_OPTIONS *pFactoryOptions,
+    void **factory
 );
 
 typedef HRESULT (WINAPI*D3D10CreateEffectFromMemoryFunc)(
-  __in   void *pData,
-  __in   SIZE_T DataLength,
-  __in   UINT FXFlags,
-  __in   ID3D10Device *pDevice,
-  __in   ID3D10EffectPool *pEffectPool,
-  __out  ID3D10Effect **ppEffect
+    void *pData,
+    SIZE_T DataLength,
+    UINT FXFlags,
+    ID3D10Device *pDevice,
+    ID3D10EffectPool *pEffectPool,
+    ID3D10Effect **ppEffect
 );
 
 using namespace std;
 
 namespace mozilla {
 namespace gfx {
 
 struct Vertex {
--- a/gfx/2d/GradientStopsD2D.h
+++ b/gfx/2d/GradientStopsD2D.h
@@ -35,17 +35,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef MOZILLA_GFX_GRADIENTSTOPSD2D_H_
 #define MOZILLA_GFX_GRADIENTSTOPSD2D_H_
 
 #include "2D.h"
 
-#include <D2D1.h>
+#include <d2d1.h>
 
 namespace mozilla {
 namespace gfx {
 
 class GradientStopsD2D : public GradientStops
 {
 public:
   GradientStopsD2D(ID2D1GradientStopCollection *aStopCollection)
--- a/gfx/2d/HelpersD2D.h
+++ b/gfx/2d/HelpersD2D.h
@@ -33,17 +33,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 ***** */
 
 #ifndef MOZILLA_GFX_HELPERSD2D_H_
 #define MOZILLA_GFX_HELPERSD2D_H_
 
-#include <D2D1.h>
+#include <d2d1.h>
 #include "2D.h"
 
 namespace mozilla {
 namespace gfx {
 
 static inline D2D1_POINT_2F D2DPoint(const Point &aPoint)
 {
   return D2D1::Point2F(aPoint.x, aPoint.y);
--- a/gfx/2d/PathD2D.h
+++ b/gfx/2d/PathD2D.h
@@ -34,17 +34,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef MOZILLA_GFX_PATHD2D_H_
 #define MOZILLA_GFX_PATHD2D_H_
 
 #include "2D.h"
-#include <D2D1.h>
+#include <d2d1.h>
 
 namespace mozilla {
 namespace gfx {
 
 class PathD2D;
 
 class PathBuilderD2D : public PathBuilder
 {
--- a/gfx/layers/opengl/ThebesLayerOGL.cpp
+++ b/gfx/layers/opengl/ThebesLayerOGL.cpp
@@ -186,106 +186,50 @@ ThebesLayerBufferOGL::RenderTo(const nsI
       // entire visible region's bounds, and we should draw it all in one quad
       // to avoid unexpected aliasing.
       tmpRegion = visibleRegion.GetBounds();
       renderRegion = &tmpRegion;
     } else {
       renderRegion = &visibleRegion;
     }
 
+    mTexImage->BeginTileIteration();
+    if (mTexImageOnWhite) {
+      mTexImageOnWhite->BeginTileIteration();
+      NS_ASSERTION(mTexImageOnWhite->GetTileRect() == mTexImage->GetTileRect(), "component alpha textures should be the same size.");
+    }
     nsIntRegion region(*renderRegion);
     nsIntPoint origin = GetOriginOffset();
     region.MoveBy(-origin);           // translate into TexImage space, buffer origin might not be at texture (0,0)
 
-    // Figure out the intersecting draw region
-    nsIntSize texSize = mTexImage->GetSize();
-    nsIntRect textureRect = nsIntRect(0, 0, texSize.width, texSize.height);
-    textureRect.MoveBy(region.GetBounds().TopLeft());
-    nsIntRegion subregion;
-    subregion.And(region, textureRect);
-    if (subregion.IsEmpty())  // Region is empty, nothing to draw
-      return;
-
-    nsIntRegion screenRects;
-    nsIntRegion regionRects;
-
-    // Collect texture/screen coordinates for drawing
-    nsIntRegionRectIterator iter(subregion);
-    while (const nsIntRect* iterRect = iter.Next()) {
-        nsIntRect regionRect = *iterRect;
-        nsIntRect screenRect = regionRect;
-        screenRect.MoveBy(origin);
-
-        screenRects.Or(screenRects, screenRect);
-        regionRects.Or(regionRects, regionRect);
-    }
-
-    mTexImage->BeginTileIteration();
-    if (mTexImageOnWhite) {
-      NS_ASSERTION(mTexImage->GetTileCount() == mTexImageOnWhite->GetTileCount(),
-                   "Tile count mismatch on component alpha texture");
-      mTexImageOnWhite->BeginTileIteration();
-    }
-
-    bool usingTiles = (mTexImage->GetTileCount() > 1);
     do {
-      if (mTexImageOnWhite) {
-        NS_ASSERTION(mTexImageOnWhite->GetTileRect() == mTexImage->GetTileRect(), "component alpha textures should be the same size.");
+      nsIntRect textureRect = mTexImage->GetTileRect();
+      textureRect.MoveBy(region.GetBounds().x, region.GetBounds().y);
+      nsIntRegion subregion(region);
+      subregion.And(region, textureRect); // region this texture is visible in
+      if (subregion.IsEmpty()) {
+        continue;
       }
-
-      nsIntRect tileRect = mTexImage->GetTileRect();
-
       // Bind textures.
       TextureImage::ScopedBindTexture texBind(mTexImage, LOCAL_GL_TEXTURE0);
       TextureImage::ScopedBindTexture texOnWhiteBind(mTexImageOnWhite, LOCAL_GL_TEXTURE1);
 
-      // Draw texture. If we're using tiles, we do repeating manually, as texture
-      // repeat would cause each individual tile to repeat instead of the
-      // compound texture as a whole. This involves drawing at most 4 sections,
-      // 2 for each axis that has texture repeat.
-      for (int y = 0; y < (usingTiles ? 2 : 1); y++) {
-        for (int x = 0; x < (usingTiles ? 2 : 1); x++) {
-          nsIntRect currentTileRect(tileRect);
-          currentTileRect.MoveBy(x * texSize.width, y * texSize.height);
-
-          nsIntRegionRectIterator screenIter(screenRects);
-          nsIntRegionRectIterator regionIter(regionRects);
-
-          const nsIntRect* screenRect;
-          const nsIntRect* regionRect;
-          while ((screenRect = screenIter.Next()) &&
-                 (regionRect = regionIter.Next())) {
-              nsIntRect tileScreenRect(*screenRect);
-              nsIntRect tileRegionRect(*regionRect);
+      nsIntRegionRectIterator iter(subregion);
+      while (const nsIntRect *iterRect = iter.Next()) {
+        nsIntRect regionRect = *iterRect;  // one rectangle of this texture's region
+        // translate into the correct place for this texture sub-region
+        nsIntRect screenRect = regionRect;
+        screenRect.MoveBy(origin);
+        program->SetLayerQuadRect(screenRect);
 
-              // When we're using tiles, find the intersection between the tile
-              // rect and this region rect. Tiling is then handled by the
-              // outer for-loops and modifying the tile rect.
-              if (usingTiles) {
-                  tileScreenRect.MoveBy(-origin);
-                  tileScreenRect = tileScreenRect.Intersect(currentTileRect);
-                  tileScreenRect.MoveBy(origin);
-
-                  if (tileScreenRect.IsEmpty())
-                    continue;
-
-                  tileRegionRect = regionRect->Intersect(currentTileRect);
-                  tileRegionRect.MoveBy(-currentTileRect.TopLeft());
-              }
-
-              program->SetLayerQuadRect(tileScreenRect);
-              aManager->BindAndDrawQuadWithTextureRect(program, tileRegionRect,
-                                                       tileRect.Size(),
-                                                       mTexImage->GetWrapMode());
-          }
-        }
+        regionRect.MoveBy(-mTexImage->GetTileRect().TopLeft()); // get region of tile
+        aManager->BindAndDrawQuadWithTextureRect(program, regionRect,
+                                                 textureRect.Size(),
+                                                 mTexImage->GetWrapMode());
       }
-
-      if (mTexImageOnWhite)
-          mTexImageOnWhite->NextTile();
     } while (mTexImage->NextTile());
   }
 
   if (mTexImageOnWhite) {
     // Restore defaults
     gl()->fBlendFuncSeparate(LOCAL_GL_ONE, LOCAL_GL_ONE_MINUS_SRC_ALPHA,
                              LOCAL_GL_ONE, LOCAL_GL_ONE);
   }
@@ -842,28 +786,16 @@ ShadowBufferOGL::Upload(gfxASurface* aUp
   }
 
   nsIntRegion destRegion(aUpdated);
   // aUpdated is in screen coordinates.  Move it so that the layer's
   // top-left is 0,0
   nsIntPoint visTopLeft = mLayer->GetVisibleRegion().GetBounds().TopLeft();
   destRegion.MoveBy(-visTopLeft);
 
-  // Correct for rotation
-  destRegion.MoveBy(aRotation);
-  nsIntRect destBounds = destRegion.GetBounds();
-  destRegion.MoveBy((destBounds.x >= size.width) ? -size.width : 0,
-                    (destBounds.y >= size.height) ? -size.height : 0);
-
-  // There's code to make sure that updated regions don't cross rotation
-  // boundaries, so assert here that this is the case
-  NS_ASSERTION(((destBounds.x % size.width) + destBounds.width <= size.width) &&
-               ((destBounds.y % size.height) + destBounds.height <= size.height),
-               "Updated region lies across rotation boundaries!");
-
   // NB: this gfxContext must not escape EndUpdate() below
   mTexImage->DirectUpdate(aUpdate, destRegion);
 
   mBufferRect = aRect;
   mBufferRotation = aRotation;
 }
 
 ShadowThebesLayerOGL::ShadowThebesLayerOGL(LayerManagerOGL *aManager)
--- a/gfx/ots/src/cmap.cc
+++ b/gfx/ots/src/cmap.cc
@@ -483,17 +483,17 @@ bool Parse0514(ots::OpenTypeFile *file,
       ranges.resize(num_ranges);
 
       for (unsigned j = 0; j < num_ranges; ++j) {
         if (!subtable.ReadU24(&ranges[j].unicode_value) ||
             !subtable.ReadU8(&ranges[j].additional_count)) {
           return OTS_FAILURE();
         }
         const uint32_t check_value =
-            ranges[j].unicode_value + ranges[i].additional_count;
+            ranges[j].unicode_value + ranges[j].additional_count;
         if (ranges[j].unicode_value == 0 ||
             ranges[j].unicode_value > kUnicodeUpperLimit ||
             check_value > kUVSUpperLimit ||
             (last_unicode_value &&
              ranges[j].unicode_value <= last_unicode_value)) {
           return OTS_FAILURE();
         }
         last_unicode_value = check_value;
--- a/gfx/src/X11Util.h
+++ b/gfx/src/X11Util.h
@@ -121,27 +121,30 @@ private:
  * ScopedXErrorHandler was in place may then be caught by the other ScopedXErrorHandler. This is just a result of X being
  * asynchronous and us not doing any implicit syncing: the only method in this class what causes syncing is SyncAndGetError().
  *
  * This class is not thread-safe at all. It is assumed that only one thread is using any ScopedXErrorHandler's. Given that it's
  * not used on Mac, it should be easy to make it thread-safe by using thread-local storage with __thread.
  */
 class NS_GFX ScopedXErrorHandler
 {
+public:
     // trivial wrapper around XErrorEvent, just adding ctor initializing by zero.
     struct ErrorEvent
     {
         XErrorEvent mError;
 
         ErrorEvent()
         {
             memset(this, 0, sizeof(ErrorEvent));
         }
     };
 
+private:
+
     // this ScopedXErrorHandler's ErrorEvent object
     ErrorEvent mXError;
 
     // static pointer for use by the error handler
     static ErrorEvent* sXErrorPtr;
 
     // what to restore sXErrorPtr to on destruction
     ErrorEvent* mOldXErrorPtr;
--- a/gfx/thebes/GLContext.cpp
+++ b/gfx/thebes/GLContext.cpp
@@ -570,52 +570,51 @@ BasicTextureImage::~BasicTextureImage()
 }
 
 gfxASurface*
 BasicTextureImage::BeginUpdate(nsIntRegion& aRegion)
 {
     NS_ASSERTION(!mUpdateSurface, "BeginUpdate() without EndUpdate()?");
 
     // determine the region the client will need to repaint
-    GetUpdateRegion(aRegion);
-    mUpdateRegion = aRegion;
+    ImageFormat format =
+        (GetContentType() == gfxASurface::CONTENT_COLOR) ?
+        gfxASurface::ImageFormatRGB24 : gfxASurface::ImageFormatARGB32;
+    if (mTextureState != Valid)
+    {
+        // if the texture hasn't been initialized yet, or something important
+        // changed, we need to recreate our backing surface and force the
+        // client to paint everything
+        mUpdateRegion = nsIntRect(nsIntPoint(0, 0), mSize);
+    } else {
+        mUpdateRegion = aRegion;
+    }
+
+    aRegion = mUpdateRegion;
 
     nsIntRect rgnSize = mUpdateRegion.GetBounds();
     if (!nsIntRect(nsIntPoint(0, 0), mSize).Contains(rgnSize)) {
         NS_ERROR("update outside of image");
         return NULL;
     }
 
-    ImageFormat format =
-        (GetContentType() == gfxASurface::CONTENT_COLOR) ?
-        gfxASurface::ImageFormatRGB24 : gfxASurface::ImageFormatARGB32;
-    mUpdateSurface =
+    mUpdateSurface = 
         GetSurfaceForUpdate(gfxIntSize(rgnSize.width, rgnSize.height), format);
 
     if (!mUpdateSurface || mUpdateSurface->CairoStatus()) {
         mUpdateSurface = NULL;
         return NULL;
     }
 
     mUpdateSurface->SetDeviceOffset(gfxPoint(-rgnSize.x, -rgnSize.y));
 
     return mUpdateSurface;
 }
 
 void
-BasicTextureImage::GetUpdateRegion(nsIntRegion& aForRegion)
-{
-  // if the texture hasn't been initialized yet, or something important
-  // changed, we need to recreate our backing surface and force the
-  // client to paint everything
-  if (mTextureState != Valid)
-      aForRegion = nsIntRect(nsIntPoint(0, 0), mSize);
-}
-
-void
 BasicTextureImage::EndUpdate()
 {
     NS_ASSERTION(!!mUpdateSurface, "EndUpdate() without BeginUpdate()?");
 
     // FIXME: this is the slow boat.  Make me fast (with GLXPixmap?).
 
     // Undo the device offset that BeginUpdate set; doesn't much matter for us here,
     // but important if we ever do anything directly with the surface.
@@ -725,139 +724,89 @@ TiledTextureImage::TiledTextureImage(GLC
 
 TiledTextureImage::~TiledTextureImage()
 {
 }
 
 bool 
 TiledTextureImage::DirectUpdate(gfxASurface* aSurf, const nsIntRegion& aRegion, const nsIntPoint& aFrom /* = nsIntPoint(0, 0) */)
 {
+    nsIntRect bounds = aRegion.GetBounds();
     nsIntRegion region;
     if (mTextureState != Valid) {
-        nsIntRect bounds = nsIntRect(0, 0, mSize.width, mSize.height);
+        bounds = nsIntRect(0, 0, mSize.width, mSize.height);
         region = nsIntRegion(bounds);
     } else {
         region = aRegion;
     }
 
     PRBool result = PR_TRUE;
     for (unsigned i = 0; i < mImages.Length(); i++) {
-        int xPos = (i % mColumns) * mTileSize;
-        int yPos = (i / mColumns) * mTileSize;
+        unsigned int xPos = (i % mColumns) * mTileSize;
+        unsigned int yPos = (i / mColumns) * mTileSize;
         nsIntRegion tileRegion;
         tileRegion.And(region, nsIntRect(nsIntPoint(xPos,yPos), mImages[i]->GetSize())); // intersect with tile
         if (tileRegion.IsEmpty())
             continue;
         tileRegion.MoveBy(-xPos, -yPos); // translate into tile local space
         result &= mImages[i]->DirectUpdate(aSurf,
                                            tileRegion,
                                            aFrom + nsIntPoint(xPos, yPos));
     }
     mShaderType = mImages[0]->GetShaderProgramType();
     mIsRGBFormat = mImages[0]->IsRGB();
     mTextureState = Valid;
     return result;
 }
 
-void
-TiledTextureImage::GetUpdateRegion(nsIntRegion& aForRegion)
-{
-    if (mTextureState != Valid) {
-        // if the texture hasn't been initialized yet, or something important
-        // changed, we need to recreate our backing surface and force the
-        // client to paint everything
-        aForRegion = nsIntRect(nsIntPoint(0, 0), mSize);
-        return;
-    }
-
-    nsIntRegion newRegion;
-
-    // We need to query each texture with the region it will be drawing and
-    // set aForRegion to be the combination of all of these regions
-    for (unsigned i = 0; i < mImages.Length(); i++) {
-        int xPos = (i % mColumns) * mTileSize;
-        int yPos = (i / mColumns) * mTileSize;
-        nsIntRect imageRect = nsIntRect(nsIntRect(nsIntPoint(xPos,yPos), mImages[i]->GetSize()));
-
-        if (aForRegion.Intersects(imageRect)) {
-            // Make a copy of the region
-            nsIntRegion subRegion;
-            subRegion.And(aForRegion, imageRect);
-            // Translate it into tile-space
-            subRegion.MoveBy(-xPos, -yPos);
-            // Query region
-            mImages[i]->GetUpdateRegion(subRegion);
-            // Translate back
-            subRegion.MoveBy(xPos, yPos);
-            // Add to the accumulated region
-            newRegion.Or(newRegion, subRegion);
-        }
-    }
-
-    aForRegion = newRegion;
-}
-
 gfxASurface*
 TiledTextureImage::BeginUpdate(nsIntRegion& aRegion)
 {
     NS_ASSERTION(!mInUpdate, "nested update");
     mInUpdate = PR_TRUE;
 
-    // Note, we don't call GetUpdateRegion here as if the updated region is
-    // fully contained in a single tile, we get to avoid iterating through
-    // the tiles again (and a little copying).
     if (mTextureState != Valid)
     {
         // if the texture hasn't been initialized yet, or something important
         // changed, we need to recreate our backing surface and force the
         // client to paint everything
-        aRegion = nsIntRect(nsIntPoint(0, 0), mSize);
+        mUpdateRegion = nsIntRect(nsIntPoint(0, 0), mSize);
+    } else {
+        mUpdateRegion = aRegion;
     }
 
-    nsIntRect bounds = aRegion.GetBounds();
-
     for (unsigned i = 0; i < mImages.Length(); i++) {
-        int xPos = (i % mColumns) * mTileSize;
-        int yPos = (i / mColumns) * mTileSize;
+        unsigned int xPos = (i % mColumns) * mTileSize;
+        unsigned int yPos = (i / mColumns) * mTileSize;
         nsIntRegion imageRegion = nsIntRegion(nsIntRect(nsIntPoint(xPos,yPos), mImages[i]->GetSize()));
 
         // a single Image can handle this update request
         if (imageRegion.Contains(aRegion)) {
             // adjust for tile offset
             aRegion.MoveBy(-xPos, -yPos);
             // forward the actual call
             nsRefPtr<gfxASurface> surface = mImages[i]->BeginUpdate(aRegion);
             // caller expects container space
             aRegion.MoveBy(xPos, yPos);
-            // Correct the device offset
-            gfxPoint offset = surface->GetDeviceOffset();
-            surface->SetDeviceOffset(gfxPoint(offset.x - xPos,
-                                              offset.y - yPos));
             // we don't have a temp surface
             mUpdateSurface = nsnull;
             // remember which image to EndUpdate
             mCurrentImage = i;
             return surface.get();
         }
     }
-
-    // Get the real updated region, taking into account the capabilities of
-    // each TextureImage tile
-    GetUpdateRegion(aRegion);
-    mUpdateRegion = aRegion;
-    bounds = aRegion.GetBounds();
-
     // update covers multiple Images - create a temp surface to paint in
     gfxASurface::gfxImageFormat format =
         (GetContentType() == gfxASurface::CONTENT_COLOR) ?
         gfxASurface::ImageFormatRGB24 : gfxASurface::ImageFormatARGB32;
+
+    nsIntRect bounds = aRegion.GetBounds();
     mUpdateSurface = gfxPlatform::GetPlatform()->
         CreateOffscreenSurface(gfxIntSize(bounds.width, bounds.height), gfxASurface::ContentFromFormat(format));
     mUpdateSurface->SetDeviceOffset(gfxPoint(-bounds.x, -bounds.y));
-
     return mUpdateSurface;
 }
 
 void
 TiledTextureImage::EndUpdate()
 {
     NS_ASSERTION(mInUpdate, "EndUpdate not in update");
     if (!mUpdateSurface) { // update was to a single TextureImage
@@ -866,20 +815,19 @@ TiledTextureImage::EndUpdate()
         mTextureState = Valid;
         mShaderType = mImages[mCurrentImage]->GetShaderProgramType();
         mIsRGBFormat = mImages[mCurrentImage]->IsRGB();
         return;
     }
 
     // upload tiles from temp surface
     for (unsigned i = 0; i < mImages.Length(); i++) {
-        int xPos = (i % mColumns) * mTileSize;
-        int yPos = (i / mColumns) * mTileSize;
+        unsigned int xPos = (i % mColumns) * mTileSize;
+        unsigned int yPos = (i / mColumns) * mTileSize;
         nsIntRect imageRect = nsIntRect(nsIntPoint(xPos,yPos), mImages[i]->GetSize());
-
         nsIntRegion subregion;
         subregion.And(mUpdateRegion, imageRect);
         if (subregion.IsEmpty())
             continue;
         subregion.MoveBy(-xPos, -yPos); // Tile-local space
         // copy tile from temp surface
         gfxASurface* surf = mImages[i]->BeginUpdate(subregion);
         nsRefPtr<gfxContext> ctx = new gfxContext(surf);
@@ -889,17 +837,16 @@ TiledTextureImage::EndUpdate()
         ctx->Paint();
         mImages[i]->EndUpdate();
     }
 
     mUpdateSurface = nsnull;
     mInUpdate = PR_FALSE;
     mShaderType = mImages[0]->GetShaderProgramType();
     mIsRGBFormat = mImages[0]->IsRGB();
-    mTextureState = Valid;
 }
 
 void TiledTextureImage::BeginTileIteration()
 {
     mCurrentImage = 0;
 }
 
 PRBool TiledTextureImage::NextTile()
@@ -949,21 +896,16 @@ void TiledTextureImage::Resize(const nsI
           nsRefPtr<TextureImage> teximg =
                   mGL->TileGenFunc(size, mContentType, mUseNearestFilter);
           mImages.AppendElement(teximg.forget());
       }
     }
     mTextureState = Allocated;
 }
 
-PRUint32 TiledTextureImage::GetTileCount()
-{
-    return mImages.Length();
-}
-
 PRBool
 GLContext::ResizeOffscreenFBO(const gfxIntSize& aSize)
 {
     if (!IsOffscreenSizeAllowed(aSize))
         return PR_FALSE;
 
     MakeCurrent();
 
--- a/gfx/thebes/GLContext.h
+++ b/gfx/thebes/GLContext.h
@@ -189,25 +189,16 @@ public:
      * BeginUpdate() calls cannot be "nested", and each successful
      * BeginUpdate() must be followed by exactly one EndUpdate() (see
      * below).  Failure to do so can leave this in a possibly
      * inconsistent state.  Unsuccessful BeginUpdate()s must not be
      * followed by EndUpdate().
      */
     virtual gfxASurface* BeginUpdate(nsIntRegion& aRegion) = 0;
     /**
-     * Retrieves the region that will require updating, given a
-     * region that needs to be updated. This can be used for
-     * making decisions about updating before calling BeginUpdate().
-     *
-     * |aRegion| is an inout param.
-     */
-    virtual void GetUpdateRegion(nsIntRegion& aForRegion) {
-    };
-    /**
      * Finish the active update and synchronize with the server, if
      * necessary.
      *
      * BeginUpdate() must have been called exactly once before
      * EndUpdate().
      */
     virtual void EndUpdate() = 0;
 
@@ -222,21 +213,16 @@ public:
         return PR_FALSE;
     };
 
     virtual nsIntRect GetTileRect() {
         return nsIntRect(nsIntPoint(0,0), mSize);
     };
 
     virtual GLuint GetTextureID() = 0;
-
-    virtual PRUint32 GetTileCount() {
-        return 1;
-    };
-
     /**
      * Set this TextureImage's size, and ensure a texture has been
      * allocated.  Must not be called between BeginUpdate and EndUpdate.
      * After a resize, the contents are undefined.
      *
      * If this isn't implemented by a subclass, it will just perform
      * a dummy BeginUpdate/EndUpdate pair.
      */
@@ -357,17 +343,16 @@ public:
         , mTextureState(Created)
         , mGLContext(aContext)
         , mUpdateOffset(0, 0)
     {}
 
     virtual void BindTexture(GLenum aTextureUnit);
 
     virtual gfxASurface* BeginUpdate(nsIntRegion& aRegion);
-    virtual void GetUpdateRegion(nsIntRegion& aForRegion);
     virtual void EndUpdate();
     virtual bool DirectUpdate(gfxASurface* aSurf, const nsIntRegion& aRegion, const nsIntPoint& aFrom = nsIntPoint(0,0));
     virtual GLuint GetTextureID() { return mTexture; };
     // Returns a surface to draw into
     virtual already_AddRefed<gfxASurface>
       GetSurfaceForUpdate(const gfxIntSize& aSize, ImageFormat aFmt);
 
     // Call when drawing into the update surface is complete.
@@ -402,20 +387,18 @@ class TiledTextureImage
     : public TextureImage
 {
 public:
     TiledTextureImage(GLContext* aGL, nsIntSize aSize,
         TextureImage::ContentType, PRBool aUseNearestFilter = PR_FALSE);
     ~TiledTextureImage();
     void DumpDiv();
     virtual gfxASurface* BeginUpdate(nsIntRegion& aRegion);
-    virtual void GetUpdateRegion(nsIntRegion& aForRegion);
     virtual void EndUpdate();
     virtual void Resize(const nsIntSize& aSize);
-    virtual PRUint32 GetTileCount();
     virtual void BeginTileIteration();
     virtual PRBool NextTile();
     virtual nsIntRect GetTileRect();
     virtual GLuint GetTextureID() {
         return mImages[mCurrentImage]->GetTextureID();
     };
     virtual bool DirectUpdate(gfxASurface* aSurf, const nsIntRegion& aRegion, const nsIntPoint& aFrom = nsIntPoint(0,0));
     virtual PRBool InUpdate() const { return mInUpdate; };
@@ -564,16 +547,18 @@ public:
 #endif
         return MakeCurrentImpl(aForce);
     }
 
     virtual PRBool SetupLookupFunction() = 0;
 
     virtual void WindowDestroyed() {}
 
+    virtual void ReleaseSurface() {}
+
     void *GetUserData(void *aKey) {
         void *result = nsnull;
         mUserData.Get(aKey, &result);
         return result;
     }
 
     void SetUserData(void *aKey, void *aValue) {
         mUserData.Put(aKey, aValue);
--- a/gfx/thebes/GLContextProviderEGL.cpp
+++ b/gfx/thebes/GLContextProviderEGL.cpp
@@ -690,17 +690,19 @@ public:
         if (mGLWidget)
             return;
 
 #ifdef DEBUG
         printf_stderr("Destroying context %p surface %p on display %p\n", mContext, mSurface, EGL_DISPLAY());
 #endif
 
         sEGLLibrary.fDestroyContext(EGL_DISPLAY(), mContext);
-        sEGLLibrary.fDestroySurface(EGL_DISPLAY(), mSurface);
+        if (mSurface) {
+            sEGLLibrary.fDestroySurface(EGL_DISPLAY(), mSurface);
+        }
     }
 
     GLContextType GetContextType() {
         return ContextTypeEGL;
     }
 
     PRBool Init()
     {
@@ -778,24 +780,30 @@ public:
     }
 
     PRBool MakeCurrentImpl(PRBool aForce = PR_FALSE) {
         PRBool succeeded = PR_TRUE;
 
         // Assume that EGL has the same problem as WGL does,
         // where MakeCurrent with an already-current context is
         // still expensive.
-        if (aForce || sEGLLibrary.fGetCurrentContext() != mContext) {
+        if (!mSurface || aForce || sEGLLibrary.fGetCurrentContext() != mContext) {
             if (mGLWidget) {
 #ifdef MOZ_WIDGET_QT
                 static_cast<QGLWidget*>(mGLWidget)->makeCurrent();
 #else
                 succeeded = PR_FALSE;
 #endif
             } else {
+#ifndef MOZ_WIDGET_QT
+                if (!mSurface) {
+                    EGLConfig config = CreateConfig();
+                    mSurface = CreateSurfaceForWindow(NULL, config);
+                }
+#endif
                 succeeded = sEGLLibrary.fMakeCurrent(EGL_DISPLAY(),
                                                      mSurface, mSurface,
                                                      mContext);
             }
             NS_ASSERTION(succeeded, "Failed to make GL context current!");
         }
 
         return succeeded;
@@ -805,27 +813,38 @@ public:
     virtual PRBool
     RenewSurface() {
         /* We don't support renewing on QT because we don't create the surface ourselves */
         return PR_FALSE;
     }
 #else
     virtual PRBool
     RenewSurface() {
-        sEGLLibrary.fDestroySurface(EGL_DISPLAY(), mSurface);
-
+        ReleaseSurface();
         EGLConfig config = CreateConfig();
         mSurface = CreateSurfaceForWindow(NULL, config);
 
         return sEGLLibrary.fMakeCurrent(EGL_DISPLAY(),
                                         mSurface, mSurface,
                                         mContext);
     }
 #endif
 
+#ifndef MOZ_WIDGET_QT
+    virtual void
+    ReleaseSurface() {
+        if (mSurface) {
+            sEGLLibrary.fMakeCurrent(EGL_DISPLAY(), EGL_NO_SURFACE, EGL_NO_SURFACE,
+                                     EGL_NO_CONTEXT);
+            sEGLLibrary.fDestroySurface(EGL_DISPLAY(), mSurface);
+            mSurface = NULL;
+        }
+    }
+#endif
+
     PRBool SetupLookupFunction()
     {
         mLookupFunc = (PlatformLookupFunction)sEGLLibrary.fGetProcAddress;
         return PR_TRUE;
     }
 
     void *GetNativeData(NativeDataType aType)
     {
@@ -835,17 +854,21 @@ public:
 
         default:
             return nsnull;
         }
     }
 
     PRBool SwapBuffers()
     {
-        return sEGLLibrary.fSwapBuffers(EGL_DISPLAY(), mSurface);
+        if (mSurface) {
+            return sEGLLibrary.fSwapBuffers(EGL_DISPLAY(), mSurface);
+        } else {
+            return PR_FALSE;
+        }
     }
     // GLContext interface - returns Tiled Texture Image in our case
     virtual already_AddRefed<TextureImage>
     CreateTextureImage(const nsIntSize& aSize,
                        TextureImage::ContentType aContentType,
                        GLenum aWrapMode,
                        PRBool aUseNearestFilter=PR_FALSE);
 
@@ -1038,17 +1061,19 @@ GLContextEGL::ResizeOffscreen(const gfxI
                                                  pbsize);
         if (!surface) {
             NS_WARNING("Failed to resize pbuffer");
             return nsnull;
         }
 
         SetOffscreenSize(aNewSize, pbsize);
 
-        sEGLLibrary.fDestroySurface(EGL_DISPLAY(), mSurface);
+        if (mSurface) {
+            sEGLLibrary.fDestroySurface(EGL_DISPLAY(), mSurface);
+        }
 
         mSurface = surface;
 
         MakeCurrent(PR_TRUE);
         ClearSafely();
 
         return PR_TRUE;
     }
@@ -1202,38 +1227,37 @@ public:
         if (ctx && !ctx->IsDestroyed()) {
             ctx->MakeCurrent();
             ctx->fDeleteTextures(1, &mTexture);
             ReleaseTexImage();
             DestroyEGLSurface();
         }
     }
 
-    virtual void GetUpdateRegion(nsIntRegion& aForRegion)
-    {
-        if (mTextureState != Valid) {
-            // if the texture hasn't been initialized yet, force the
-            // client to paint everything
-            aForRegion = nsIntRect(nsIntPoint(0, 0), mSize);
-        } else if (!mBackingSurface) {
-            // We can only draw a rectangle, not subregions due to
-            // the way that our texture upload functions work.  If
-            // needed, we /could/ do multiple texture uploads if we have
-            // non-overlapping rects, but that's a tradeoff.
-            aForRegion = nsIntRegion(mUpdateRect);
-        }
-    }
-
     virtual gfxASurface* BeginUpdate(nsIntRegion& aRegion)
     {
         NS_ASSERTION(!mUpdateSurface, "BeginUpdate() without EndUpdate()?");
 
         // determine the region the client will need to repaint
-        GetUpdateRegion(aRegion);
-        mUpdateRect = aRegion.GetBounds();
+        if (mTextureState != Valid) {
+            // if the texture hasn't been initialized yet, force the
+            // client to paint everything
+            mUpdateRect = nsIntRect(nsIntPoint(0, 0), mSize);
+            //printf_stderr("v Forcing full paint\n");
+            aRegion = nsIntRegion(mUpdateRect);
+        } else {
+            mUpdateRect = aRegion.GetBounds();
+            if (!mBackingSurface) {
+                // We can only draw a rectangle, not subregions due to
+                // the way that our texture upload functions work.  If
+                // needed, we /could/ do multiple texture uploads if we have
+                // non-overlapping rects, but that's a tradeoff.
+                aRegion = nsIntRegion(mUpdateRect);
+            }
+        }
 
         //printf_stderr("BeginUpdate with updateRect [%d %d %d %d]\n", mUpdateRect.x, mUpdateRect.y, mUpdateRect.width, mUpdateRect.height);
         if (!nsIntRect(nsIntPoint(0, 0), mSize).Contains(mUpdateRect)) {
             NS_ERROR("update outside of image");
             return NULL;
         }
 
         if (mBackingSurface) {
--- a/gfx/thebes/GLContextProviderGLX.cpp
+++ b/gfx/thebes/GLContextProviderGLX.cpp
@@ -107,75 +107,80 @@ GLXLibrary::EnsureInitialized()
         mOGLLibrary = PR_LoadLibrary(libGLfilename);
         if (!mOGLLibrary) {
             NS_WARNING("Couldn't load OpenGL shared library.");
             return PR_FALSE;
         }
         reporter.SetSuccessful();
     }
 
+    if (PR_GetEnv("MOZ_GLX_DEBUG")) {
+        mDebug = PR_TRUE;
+    }
+
     LibrarySymbolLoader::SymLoadStruct symbols[] = {
         /* functions that were in GLX 1.0 */
-        { (PRFuncPtr*) &xDestroyContext, { "glXDestroyContext", NULL } },
-        { (PRFuncPtr*) &xMakeCurrent, { "glXMakeCurrent", NULL } },
-        { (PRFuncPtr*) &xSwapBuffers, { "glXSwapBuffers", NULL } },
-        { (PRFuncPtr*) &xQueryVersion, { "glXQueryVersion", NULL } },
-        { (PRFuncPtr*) &xGetCurrentContext, { "glXGetCurrentContext", NULL } },
-        { (PRFuncPtr*) &xWaitGL, { "glXWaitGL", NULL } },
+        { (PRFuncPtr*) &xDestroyContextInternal, { "glXDestroyContext", NULL } },
+        { (PRFuncPtr*) &xMakeCurrentInternal, { "glXMakeCurrent", NULL } },
+        { (PRFuncPtr*) &xSwapBuffersInternal, { "glXSwapBuffers", NULL } },
+        { (PRFuncPtr*) &xQueryVersionInternal, { "glXQueryVersion", NULL } },
+        { (PRFuncPtr*) &xGetCurrentContextInternal, { "glXGetCurrentContext", NULL } },
+        { (PRFuncPtr*) &xWaitGLInternal, { "glXWaitGL", NULL } },
+        { (PRFuncPtr*) &xWaitXInternal, { "glXWaitX", NULL } },
         /* functions introduced in GLX 1.1 */
-        { (PRFuncPtr*) &xQueryExtensionsString, { "glXQueryExtensionsString", NULL } },
-        { (PRFuncPtr*) &xGetClientString, { "glXGetClientString", NULL } },
-        { (PRFuncPtr*) &xQueryServerString, { "glXQueryServerString", NULL } },
+        { (PRFuncPtr*) &xQueryExtensionsStringInternal, { "glXQueryExtensionsString", NULL } },
+        { (PRFuncPtr*) &xGetClientStringInternal, { "glXGetClientString", NULL } },
+        { (PRFuncPtr*) &xQueryServerStringInternal, { "glXQueryServerString", NULL } },
         { NULL, { NULL } }
     };
 
     LibrarySymbolLoader::SymLoadStruct symbols13[] = {
         /* functions introduced in GLX 1.3 */
-        { (PRFuncPtr*) &xChooseFBConfig, { "glXChooseFBConfig", NULL } },
-        { (PRFuncPtr*) &xGetFBConfigAttrib, { "glXGetFBConfigAttrib", NULL } },
+        { (PRFuncPtr*) &xChooseFBConfigInternal, { "glXChooseFBConfig", NULL } },
+        { (PRFuncPtr*) &xGetFBConfigAttribInternal, { "glXGetFBConfigAttrib", NULL } },
         // WARNING: xGetFBConfigs not set in symbols13_ext
-        { (PRFuncPtr*) &xGetFBConfigs, { "glXGetFBConfigs", NULL } },
-        { (PRFuncPtr*) &xGetVisualFromFBConfig, { "glXGetVisualFromFBConfig", NULL } },
+        { (PRFuncPtr*) &xGetFBConfigsInternal, { "glXGetFBConfigs", NULL } },
+        { (PRFuncPtr*) &xGetVisualFromFBConfigInternal, { "glXGetVisualFromFBConfig", NULL } },
         // WARNING: symbols13_ext sets xCreateGLXPixmapWithConfig instead
-        { (PRFuncPtr*) &xCreatePixmap, { "glXCreatePixmap", NULL } },
-        { (PRFuncPtr*) &xDestroyPixmap, { "glXDestroyPixmap", NULL } },
-        { (PRFuncPtr*) &xCreateNewContext, { "glXCreateNewContext", NULL } },
+        { (PRFuncPtr*) &xCreatePixmapInternal, { "glXCreatePixmap", NULL } },
+        { (PRFuncPtr*) &xDestroyPixmapInternal, { "glXDestroyPixmap", NULL } },
+        { (PRFuncPtr*) &xCreateNewContextInternal, { "glXCreateNewContext", NULL } },
         { NULL, { NULL } }
     };
 
     LibrarySymbolLoader::SymLoadStruct symbols13_ext[] = {
         /* extension equivalents for functions introduced in GLX 1.3 */
         // GLX_SGIX_fbconfig extension
-        { (PRFuncPtr*) &xChooseFBConfig, { "glXChooseFBConfigSGIX", NULL } },
-        { (PRFuncPtr*) &xGetFBConfigAttrib, { "glXGetFBConfigAttribSGIX", NULL } },
+        { (PRFuncPtr*) &xChooseFBConfigInternal, { "glXChooseFBConfigSGIX", NULL } },
+        { (PRFuncPtr*) &xGetFBConfigAttribInternal, { "glXGetFBConfigAttribSGIX", NULL } },
         // WARNING: no xGetFBConfigs equivalent in extensions
-        { (PRFuncPtr*) &xGetVisualFromFBConfig, { "glXGetVisualFromFBConfig", NULL } },
+        { (PRFuncPtr*) &xGetVisualFromFBConfigInternal, { "glXGetVisualFromFBConfig", NULL } },
         // WARNING: different from symbols13:
-        { (PRFuncPtr*) &xCreateGLXPixmapWithConfig, { "glXCreateGLXPixmapWithConfigSGIX", NULL } },
-        { (PRFuncPtr*) &xDestroyPixmap, { "glXDestroyGLXPixmap", NULL } }, // not from ext
-        { (PRFuncPtr*) &xCreateNewContext, { "glXCreateContextWithConfigSGIX", NULL } },
+        { (PRFuncPtr*) &xCreateGLXPixmapWithConfigInternal, { "glXCreateGLXPixmapWithConfigSGIX", NULL } },
+        { (PRFuncPtr*) &xDestroyPixmapInternal, { "glXDestroyGLXPixmap", NULL } }, // not from ext
+        { (PRFuncPtr*) &xCreateNewContextInternal, { "glXCreateContextWithConfigSGIX", NULL } },
         { NULL, { NULL } }
     };
 
     LibrarySymbolLoader::SymLoadStruct symbols14[] = {
         /* functions introduced in GLX 1.4 */
-        { (PRFuncPtr*) &xGetProcAddress, { "glXGetProcAddress", NULL } },
+        { (PRFuncPtr*) &xGetProcAddressInternal, { "glXGetProcAddress", NULL } },
         { NULL, { NULL } }
     };
 
     LibrarySymbolLoader::SymLoadStruct symbols14_ext[] = {
         /* extension equivalents for functions introduced in GLX 1.4 */
         // GLX_ARB_get_proc_address extension
-        { (PRFuncPtr*) &xGetProcAddress, { "glXGetProcAddressARB", NULL } },
+        { (PRFuncPtr*) &xGetProcAddressInternal, { "glXGetProcAddressARB", NULL } },
         { NULL, { NULL } }
     };
 
     LibrarySymbolLoader::SymLoadStruct symbols_texturefrompixmap[] = {
-        { (PRFuncPtr*) &xBindTexImage, { "glXBindTexImageEXT", NULL } },
-        { (PRFuncPtr*) &xReleaseTexImage, { "glXReleaseTexImageEXT", NULL } },
+        { (PRFuncPtr*) &xBindTexImageInternal, { "glXBindTexImageEXT", NULL } },
+        { (PRFuncPtr*) &xReleaseTexImageInternal, { "glXReleaseTexImageEXT", NULL } },
         { NULL, { NULL } }
     };
 
     if (!LibrarySymbolLoader::LoadSymbols(mOGLLibrary, &symbols[0])) {
         NS_WARNING("Couldn't find required entry point in OpenGL shared library");
         return PR_FALSE;
     }
 
@@ -230,17 +235,17 @@ GLXLibrary::EnsureInitialized()
     }
     if (!LibrarySymbolLoader::LoadSymbols(mOGLLibrary, sym14)) {
         NS_WARNING("Couldn't find required entry point in OpenGL shared library");
         return PR_FALSE;
     }
 
     if (HasExtension(extensionsStr, "GLX_EXT_texture_from_pixmap") &&
         LibrarySymbolLoader::LoadSymbols(mOGLLibrary, symbols_texturefrompixmap, 
-                                         (LibrarySymbolLoader::PlatformLookupFunction)xGetProcAddress))
+                                         (LibrarySymbolLoader::PlatformLookupFunction)&xGetProcAddress))
     {
         mHasTextureFromPixmap = PR_TRUE;
     } else {
         NS_WARNING("Texture from pixmap disabled");
     }
 
     gIsATI = serverVendor && DoesVendorStringMatch(serverVendor, "ATI");
     gIsChromium = (serverVendor &&
@@ -321,31 +326,314 @@ void
 GLXLibrary::BindTexImage(GLXPixmap aPixmap)
 {    
     if (!mHasTextureFromPixmap) {
         return;
     }
 
     Display *display = DefaultXDisplay();
     // Make sure all X drawing to the surface has finished before binding to a texture.
-    XSync(DefaultXDisplay(), False);
+    xWaitX();
     xBindTexImage(display, aPixmap, GLX_FRONT_LEFT_EXT, NULL);
 }
 
 void
 GLXLibrary::ReleaseTexImage(GLXPixmap aPixmap)
 {
     if (!mHasTextureFromPixmap) {
         return;
     }
 
     Display *display = DefaultXDisplay();
     xReleaseTexImage(display, aPixmap, GLX_FRONT_LEFT_EXT);
 }
 
+#ifdef DEBUG
+
+static int (*sOldErrorHandler)(Display *, XErrorEvent *);
+ScopedXErrorHandler::ErrorEvent sErrorEvent;
+static int GLXErrorHandler(Display *display, XErrorEvent *ev)
+{
+    if (!sErrorEvent.mError.error_code) {
+        sErrorEvent.mError = *ev;
+    }
+    return 0;
+}
+
+void
+GLXLibrary::BeforeGLXCall()
+{
+    if (mDebug) {
+        sOldErrorHandler = XSetErrorHandler(GLXErrorHandler);
+    }
+}
+
+void
+GLXLibrary::AfterGLXCall()
+{
+    if (mDebug) {
+        XSync(DefaultXDisplay(), False);
+        if (sErrorEvent.mError.error_code) {
+            char buffer[2048];
+            XGetErrorText(DefaultXDisplay(), sErrorEvent.mError.error_code, buffer, sizeof(buffer));
+            printf_stderr("X ERROR: %s (%i) - Request: %i.%i, Serial: %i",
+                          buffer,
+                          sErrorEvent.mError.error_code,
+                          sErrorEvent.mError.request_code,
+                          sErrorEvent.mError.minor_code,
+                          sErrorEvent.mError.serial);
+            NS_ABORT();
+        }
+        XSetErrorHandler(sOldErrorHandler);
+    }
+}
+
+#define BEFORE_GLX_CALL do {                     \
+    sGLXLibrary.BeforeGLXCall();                 \
+} while (0)
+    
+#define AFTER_GLX_CALL do {                      \
+    sGLXLibrary.AfterGLXCall();                  \
+} while (0)
+
+#else
+
+#define BEFORE_GLX_CALL do { } while(0)
+#define AFTER_GLX_CALL do { } while(0)
+
+#endif
+    
+void 
+GLXLibrary::xDestroyContext(Display* display, GLXContext context)
+{
+    BEFORE_GLX_CALL;
+    xDestroyContextInternal(display, context);
+    AFTER_GLX_CALL;
+}
+
+Bool 
+GLXLibrary::xMakeCurrent(Display* display, 
+                         GLXDrawable drawable, 
+                         GLXContext context)
+{
+    BEFORE_GLX_CALL;
+    Bool result = xMakeCurrentInternal(display, drawable, context);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+GLXContext 
+GLXLibrary::xGetCurrentContext()
+{
+    BEFORE_GLX_CALL;
+    GLXContext result = xGetCurrentContextInternal();
+    AFTER_GLX_CALL;
+    return result;
+}
+
+/* static */ void* 
+GLXLibrary::xGetProcAddress(const char *procName)
+{
+    BEFORE_GLX_CALL;
+    void* result = sGLXLibrary.xGetProcAddressInternal(procName);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+GLXFBConfig*
+GLXLibrary::xChooseFBConfig(Display* display, 
+                            int screen, 
+                            const int *attrib_list, 
+                            int *nelements)
+{
+    BEFORE_GLX_CALL;
+    GLXFBConfig* result = xChooseFBConfigInternal(display, screen, attrib_list, nelements);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+GLXFBConfig* 
+GLXLibrary::xGetFBConfigs(Display* display, 
+                          int screen, 
+                          int *nelements)
+{
+    BEFORE_GLX_CALL;
+    GLXFBConfig* result = xGetFBConfigsInternal(display, screen, nelements);
+    AFTER_GLX_CALL;
+    return result;
+}
+    
+GLXContext
+GLXLibrary::xCreateNewContext(Display* display, 
+                              GLXFBConfig config, 
+                              int render_type, 
+                              GLXContext share_list, 
+                              Bool direct)
+{
+    BEFORE_GLX_CALL;
+    GLXContext result = xCreateNewContextInternal(display, config, 
+	                                              render_type,
+	                                              share_list, direct);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+XVisualInfo*
+GLXLibrary::xGetVisualFromFBConfig(Display* display, 
+                                   GLXFBConfig config)
+{
+    BEFORE_GLX_CALL;
+    XVisualInfo* result = xGetVisualFromFBConfigInternal(display, config);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+int
+GLXLibrary::xGetFBConfigAttrib(Display *display,
+                               GLXFBConfig config,
+                               int attribute,
+                               int *value)
+{
+    BEFORE_GLX_CALL;
+    int result = xGetFBConfigAttribInternal(display, config,
+                                            attribute, value);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+void
+GLXLibrary::xSwapBuffers(Display *display, GLXDrawable drawable)
+{
+    BEFORE_GLX_CALL;
+    xSwapBuffersInternal(display, drawable);
+    AFTER_GLX_CALL;
+}
+
+const char *
+GLXLibrary::xQueryExtensionsString(Display *display,
+                                   int screen)
+{
+    BEFORE_GLX_CALL;
+    const char *result = xQueryExtensionsStringInternal(display, screen);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+const char *
+GLXLibrary::xGetClientString(Display *display,
+                             int screen)
+{
+    BEFORE_GLX_CALL;
+    const char *result = xGetClientStringInternal(display, screen);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+const char *
+GLXLibrary::xQueryServerString(Display *display,
+                               int screen, int name)
+{
+    BEFORE_GLX_CALL;
+    const char *result = xQueryServerStringInternal(display, screen, name);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+GLXPixmap
+GLXLibrary::xCreatePixmap(Display *display, 
+                          GLXFBConfig config,
+                          Pixmap pixmap,
+                          const int *attrib_list)
+{
+    BEFORE_GLX_CALL;
+    GLXPixmap result = xCreatePixmapInternal(display, config,
+                                             pixmap, attrib_list);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+GLXPixmap
+GLXLibrary::xCreateGLXPixmapWithConfig(Display *display,
+                                       GLXFBConfig config,
+                                       Pixmap pixmap)
+{
+    BEFORE_GLX_CALL;
+    GLXPixmap result = xCreateGLXPixmapWithConfigInternal(display, config, pixmap);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+void
+GLXLibrary::xDestroyPixmap(Display *display, GLXPixmap pixmap)
+{
+    BEFORE_GLX_CALL;
+    xDestroyPixmapInternal(display, pixmap);
+    AFTER_GLX_CALL;
+}
+
+GLXContext
+GLXLibrary::xCreateContext(Display *display,
+                           XVisualInfo *vis,
+                           GLXContext shareList,
+                           Bool direct)
+{
+    BEFORE_GLX_CALL;
+    GLXContext result = xCreateContextInternal(display, vis, shareList, direct);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+Bool
+GLXLibrary::xQueryVersion(Display *display,
+                          int *major,
+                          int *minor)
+{
+    BEFORE_GLX_CALL;
+    Bool result = xQueryVersionInternal(display, major, minor);
+    AFTER_GLX_CALL;
+    return result;
+}
+
+void
+GLXLibrary::xBindTexImage(Display *display,
+                          GLXDrawable drawable,
+                          int buffer,
+                          const int *attrib_list)
+{
+    BEFORE_GLX_CALL;
+    xBindTexImageInternal(display, drawable, buffer, attrib_list);
+    AFTER_GLX_CALL;
+}
+
+void
+GLXLibrary::xReleaseTexImage(Display *display,
+                             GLXDrawable drawable,
+                             int buffer)
+{
+    BEFORE_GLX_CALL;
+    xReleaseTexImageInternal(display, drawable, buffer);
+    AFTER_GLX_CALL;
+}
+
+void 
+GLXLibrary::xWaitGL()
+{
+    BEFORE_GLX_CALL;
+    xWaitGLInternal();
+    AFTER_GLX_CALL;
+}
+
+void
+GLXLibrary::xWaitX()
+{
+    BEFORE_GLX_CALL;
+    xWaitXInternal();
+    AFTER_GLX_CALL;
+}
+
 GLXLibrary sGLXLibrary;
 
 class GLContextGLX : public GLContext
 {
 public:
     static already_AddRefed<GLContextGLX>
     CreateGLContext(const ContextFormat& format,
                     Display *display,
@@ -461,17 +749,17 @@ TRY_AGAIN_NO_SHARING:
             NS_ASSERTION(succeeded, "Failed to make GL context current!");
         }
 
         return succeeded;
     }
 
     PRBool SetupLookupFunction()
     {
-        mLookupFunc = (PlatformLookupFunction)sGLXLibrary.xGetProcAddress;
+        mLookupFunc = (PlatformLookupFunction)&GLXLibrary::xGetProcAddress;
         return PR_TRUE;
     }
 
     void *GetNativeData(NativeDataType aType)
     {
         switch(aType) {
         case NativeGLContext:
             return mContext;
@@ -1045,8 +1333,9 @@ GLContextProviderGLX::GetGlobalContext()
 void
 GLContextProviderGLX::Shutdown()
 {
     gGlobalContext = nsnull;
 }
 
 } /* namespace gl */
 } /* namespace mozilla */
+
--- a/gfx/thebes/GLXLibrary.h
+++ b/gfx/thebes/GLXLibrary.h
@@ -44,118 +44,185 @@ typedef realGLboolean GLboolean;
 
 namespace mozilla {
 namespace gl {
 
 class GLXLibrary
 {
 public:
     GLXLibrary() : mInitialized(PR_FALSE), mTriedInitializing(PR_FALSE),
-                   mHasTextureFromPixmap(PR_FALSE), mOGLLibrary(nsnull) {}
-
-    typedef void (GLAPIENTRY * PFNGLXDESTROYCONTEXTPROC) (Display*,
-                                                          GLXContext);
-    PFNGLXDESTROYCONTEXTPROC xDestroyContext;
-    typedef Bool (GLAPIENTRY * PFNGLXMAKECURRENTPROC) (Display*,
-                                                       GLXDrawable,
-                                                       GLXContext);
-    PFNGLXMAKECURRENTPROC xMakeCurrent;
-    typedef GLXContext (GLAPIENTRY * PFNGLXGETCURRENTCONTEXT) ();
-    PFNGLXGETCURRENTCONTEXT xGetCurrentContext;
-    typedef void* (GLAPIENTRY * PFNGLXGETPROCADDRESSPROC) (const char *);
-    PFNGLXGETPROCADDRESSPROC xGetProcAddress;
-    typedef GLXFBConfig* (GLAPIENTRY * PFNGLXCHOOSEFBCONFIG) (Display *,
-                                                              int,
-                                                              const int *,
-                                                              int *);
-    PFNGLXCHOOSEFBCONFIG xChooseFBConfig;
-    typedef GLXFBConfig* (GLAPIENTRY * PFNGLXGETFBCONFIGS) (Display *,
-                                                            int,
-                                                            int *);
-    PFNGLXGETFBCONFIGS xGetFBConfigs;
-    typedef GLXContext (GLAPIENTRY * PFNGLXCREATENEWCONTEXT) (Display *,
-                                                              GLXFBConfig,
-                                                              int,
-                                                              GLXContext,
-                                                              Bool);
-    PFNGLXCREATENEWCONTEXT xCreateNewContext;
-    typedef XVisualInfo* (GLAPIENTRY * PFNGLXGETVISUALFROMFBCONFIG) (Display *,
-                                                                     GLXFBConfig);
-    PFNGLXGETVISUALFROMFBCONFIG xGetVisualFromFBConfig;
-    typedef int (GLAPIENTRY * PFNGLXGETFBCONFIGATTRIB) (Display *, 
-                                                        GLXFBConfig,
-                                                        int,
-                                                        int *);
-    PFNGLXGETFBCONFIGATTRIB xGetFBConfigAttrib;
+                   mHasTextureFromPixmap(PR_FALSE), mDebug(PR_FALSE),
+                   mOGLLibrary(nsnull) {}
 
-    typedef void (GLAPIENTRY * PFNGLXSWAPBUFFERS) (Display *,
-                                                   GLXDrawable);
-    PFNGLXSWAPBUFFERS xSwapBuffers;
-    typedef const char * (GLAPIENTRY * PFNGLXQUERYEXTENSIONSSTRING) (Display *,
-                                                                     int);
-    PFNGLXQUERYEXTENSIONSSTRING xQueryExtensionsString;
-    typedef const char * (GLAPIENTRY * PFNGLXGETCLIENTSTRING) (Display *,
-                                                               int);
-    PFNGLXGETCLIENTSTRING xGetClientString;
-    typedef const char * (GLAPIENTRY * PFNGLXQUERYSERVERSTRING) (Display *,
-                                                                 int,
-                                                                 int);
-    PFNGLXQUERYSERVERSTRING xQueryServerString;
-
-    typedef GLXPixmap (GLAPIENTRY * PFNGLXCREATEPIXMAP) (Display *,
-                                                         GLXFBConfig,
-                                                         Pixmap,
-                                                         const int *);
-    PFNGLXCREATEPIXMAP xCreatePixmap;
-    typedef GLXPixmap (GLAPIENTRY * PFNGLXCREATEGLXPIXMAPWITHCONFIG)
-                                                        (Display *,
-                                                         GLXFBConfig,
-                                                         Pixmap);
-    PFNGLXCREATEGLXPIXMAPWITHCONFIG xCreateGLXPixmapWithConfig;
-    typedef void (GLAPIENTRY * PFNGLXDESTROYPIXMAP) (Display *,
-                                                     GLXPixmap);
-    PFNGLXDESTROYPIXMAP xDestroyPixmap;
-    typedef GLXContext (GLAPIENTRY * PFNGLXCREATECONTEXT) (Display *,
-                                                           XVisualInfo *,
-                                                           GLXContext,
-                                                           Bool);
-    PFNGLXCREATECONTEXT xCreateContext;
-    typedef Bool (GLAPIENTRY * PFNGLXQUERYVERSION) (Display *,
-                                                    int *,
-                                                    int *);
-    PFNGLXQUERYVERSION xQueryVersion;
-
-    typedef void (GLAPIENTRY * PFNGLXBINDTEXIMAGE) (Display *,
-                                                    GLXDrawable,
-                                                    int,
-                                                    const int *);
-    PFNGLXBINDTEXIMAGE xBindTexImage;
-
-    typedef void (GLAPIENTRY * PFNGLXRELEASETEXIMAGE) (Display *,
-                                                       GLXDrawable,
-                                                       int);
-    PFNGLXRELEASETEXIMAGE xReleaseTexImage;
-
-    typedef void (GLAPIENTRY * PFNGLXWAITGL) ();
-    PFNGLXWAITGL xWaitGL;
+    void xDestroyContext(Display* display, GLXContext context);
+    Bool xMakeCurrent(Display* display, 
+                      GLXDrawable drawable, 
+                      GLXContext context);
+    GLXContext xGetCurrentContext();
+    static void* xGetProcAddress(const char *procName);
+    GLXFBConfig* xChooseFBConfig(Display* display, 
+                                 int screen, 
+                                 const int *attrib_list, 
+                                 int *nelements);
+    GLXFBConfig* xGetFBConfigs(Display* display, 
+                               int screen, 
+                               int *nelements);
+    GLXContext xCreateNewContext(Display* display, 
+                                 GLXFBConfig config, 
+                                 int render_type, 
+                                 GLXContext share_list, 
+                                 Bool direct);
+    XVisualInfo* xGetVisualFromFBConfig(Display* display, 
+                                        GLXFBConfig config);
+    int xGetFBConfigAttrib(Display *display,
+                           GLXFBConfig config,
+                           int attribute,
+                           int *value);
+    void xSwapBuffers(Display *display, GLXDrawable drawable);
+    const char * xQueryExtensionsString(Display *display,
+                                        int screen);
+    const char * xGetClientString(Display *display,
+                                  int screen);
+    const char * xQueryServerString(Display *display,
+                                    int screen, int name);
+    GLXPixmap xCreatePixmap(Display *display, 
+                            GLXFBConfig config,
+                            Pixmap pixmap,
+                            const int *attrib_list);
+    GLXPixmap xCreateGLXPixmapWithConfig(Display *display,
+                                         GLXFBConfig config,
+                                         Pixmap pixmap);
+    void xDestroyPixmap(Display *display, GLXPixmap pixmap);
+    GLXContext xCreateContext(Display *display,
+                              XVisualInfo *vis,
+                              GLXContext shareList,
+                              Bool direct);
+    Bool xQueryVersion(Display *display,
+                       int *major,
+                       int *minor);
+    void xBindTexImage(Display *display,
+                       GLXDrawable drawable,
+                       int buffer,
+                       const int *attrib_list);
+    void xReleaseTexImage(Display *display,
+                          GLXDrawable drawable,
+                          int buffer);
+    void xWaitGL();
+    void xWaitX();
 
     PRBool EnsureInitialized();
 
     GLXPixmap CreatePixmap(gfxASurface* aSurface);
     void DestroyPixmap(GLXPixmap aPixmap);
     void BindTexImage(GLXPixmap aPixmap);
     void ReleaseTexImage(GLXPixmap aPixmap);
 
     PRBool HasTextureFromPixmap() { return mHasTextureFromPixmap; }
     PRBool SupportsTextureFromPixmap(gfxASurface* aSurface);
 
 private:
+    
+    typedef void (GLAPIENTRY * PFNGLXDESTROYCONTEXTPROC) (Display*,
+                                                          GLXContext);
+    PFNGLXDESTROYCONTEXTPROC xDestroyContextInternal;
+    typedef Bool (GLAPIENTRY * PFNGLXMAKECURRENTPROC) (Display*,
+                                                       GLXDrawable,
+                                                       GLXContext);
+    PFNGLXMAKECURRENTPROC xMakeCurrentInternal;
+    typedef GLXContext (GLAPIENTRY * PFNGLXGETCURRENTCONTEXT) ();
+    PFNGLXGETCURRENTCONTEXT xGetCurrentContextInternal;
+    typedef void* (GLAPIENTRY * PFNGLXGETPROCADDRESSPROC) (const char *);
+    PFNGLXGETPROCADDRESSPROC xGetProcAddressInternal;
+    typedef GLXFBConfig* (GLAPIENTRY * PFNGLXCHOOSEFBCONFIG) (Display *,
+                                                              int,
+                                                              const int *,
+                                                              int *);
+    PFNGLXCHOOSEFBCONFIG xChooseFBConfigInternal;
+    typedef GLXFBConfig* (GLAPIENTRY * PFNGLXGETFBCONFIGS) (Display *,
+                                                            int,
+                                                            int *);
+    PFNGLXGETFBCONFIGS xGetFBConfigsInternal;
+    typedef GLXContext (GLAPIENTRY * PFNGLXCREATENEWCONTEXT) (Display *,
+                                                              GLXFBConfig,
+                                                              int,
+                                                              GLXContext,
+                                                              Bool);
+    PFNGLXCREATENEWCONTEXT xCreateNewContextInternal;
+    typedef XVisualInfo* (GLAPIENTRY * PFNGLXGETVISUALFROMFBCONFIG) (Display *,
+                                                                     GLXFBConfig);
+    PFNGLXGETVISUALFROMFBCONFIG xGetVisualFromFBConfigInternal;
+    typedef int (GLAPIENTRY * PFNGLXGETFBCONFIGATTRIB) (Display *, 
+                                                        GLXFBConfig,
+                                                        int,
+                                                        int *);
+    PFNGLXGETFBCONFIGATTRIB xGetFBConfigAttribInternal;
+
+    typedef void (GLAPIENTRY * PFNGLXSWAPBUFFERS) (Display *,
+                                                   GLXDrawable);
+    PFNGLXSWAPBUFFERS xSwapBuffersInternal;
+    typedef const char * (GLAPIENTRY * PFNGLXQUERYEXTENSIONSSTRING) (Display *,
+                                                                     int);
+    PFNGLXQUERYEXTENSIONSSTRING xQueryExtensionsStringInternal;
+    typedef const char * (GLAPIENTRY * PFNGLXGETCLIENTSTRING) (Display *,
+                                                               int);
+    PFNGLXGETCLIENTSTRING xGetClientStringInternal;
+    typedef const char * (GLAPIENTRY * PFNGLXQUERYSERVERSTRING) (Display *,
+                                                                 int,
+                                                                 int);
+    PFNGLXQUERYSERVERSTRING xQueryServerStringInternal;
+
+    typedef GLXPixmap (GLAPIENTRY * PFNGLXCREATEPIXMAP) (Display *,
+                                                         GLXFBConfig,
+                                                         Pixmap,
+                                                         const int *);
+    PFNGLXCREATEPIXMAP xCreatePixmapInternal;
+    typedef GLXPixmap (GLAPIENTRY * PFNGLXCREATEGLXPIXMAPWITHCONFIG)
+                                                        (Display *,
+                                                         GLXFBConfig,
+                                                         Pixmap);
+    PFNGLXCREATEGLXPIXMAPWITHCONFIG xCreateGLXPixmapWithConfigInternal;
+    typedef void (GLAPIENTRY * PFNGLXDESTROYPIXMAP) (Display *,
+                                                     GLXPixmap);
+    PFNGLXDESTROYPIXMAP xDestroyPixmapInternal;
+    typedef GLXContext (GLAPIENTRY * PFNGLXCREATECONTEXT) (Display *,
+                                                           XVisualInfo *,
+                                                           GLXContext,
+                                                           Bool);
+    PFNGLXCREATECONTEXT xCreateContextInternal;
+    typedef Bool (GLAPIENTRY * PFNGLXQUERYVERSION) (Display *,
+                                                    int *,
+                                                    int *);
+    PFNGLXQUERYVERSION xQueryVersionInternal;
+
+    typedef void (GLAPIENTRY * PFNGLXBINDTEXIMAGE) (Display *,
+                                                    GLXDrawable,
+                                                    int,
+                                                    const int *);
+    PFNGLXBINDTEXIMAGE xBindTexImageInternal;
+
+    typedef void (GLAPIENTRY * PFNGLXRELEASETEXIMAGE) (Display *,
+                                                       GLXDrawable,
+                                                       int);
+    PFNGLXRELEASETEXIMAGE xReleaseTexImageInternal;
+
+    typedef void (GLAPIENTRY * PFNGLXWAITGL) ();
+    PFNGLXWAITGL xWaitGLInternal;
+    
+    typedef void (GLAPIENTRY * PFNGLXWAITX) ();
+    PFNGLXWAITGL xWaitXInternal;
+
+#ifdef DEBUG
+    void BeforeGLXCall();
+    void AfterGLXCall();
+#endif
+
     PRBool mInitialized;
     PRBool mTriedInitializing;
     PRBool mHasTextureFromPixmap;
+    PRBool mDebug;
     PRLibrary *mOGLLibrary;
 };
 
 // a global GLXLibrary instance
 extern GLXLibrary sGLXLibrary;
 
 } /* namespace gl */
 } /* namespace mozilla */
--- a/ipc/chromium/chromium-config.mk
+++ b/ipc/chromium/chromium-config.mk
@@ -43,17 +43,16 @@ ifdef CHROMIUM_CONFIG_INCLUDED
 endif
 
 CHROMIUM_CONFIG_INCLUDED = 1
 
 EXTRA_DEPS += $(topsrcdir)/ipc/chromium/chromium-config.mk
 
 DEFINES += \
   -DEXCLUDE_SKIA_DEPENDENCIES \
-  -DCHROMIUM_MOZILLA_BUILD \
   $(NULL)
 
 LOCAL_INCLUDES += \
   -I$(topsrcdir)/ipc/chromium/src \
   -I$(topsrcdir)/ipc/glue \
   -I$(DEPTH)/ipc/ipdl/_ipdlheaders \
   $(NULL)
 
--- a/ipc/chromium/src/base/at_exit.cc
+++ b/ipc/chromium/src/base/at_exit.cc
@@ -59,16 +59,14 @@ void AtExitManager::ProcessCallbacksNow(
   while (!g_top_manager->stack_.empty()) {
     CallbackAndParam callback_and_param = g_top_manager->stack_.top();
     g_top_manager->stack_.pop();
 
     callback_and_param.func_(callback_and_param.param_);
   }
 }
 
-#ifdef CHROMIUM_MOZILLA_BUILD
 // static
 bool AtExitManager::AlreadyRegistered() {
   return !!g_top_manager;
 }
-#endif
 
 }  // namespace base
--- a/ipc/chromium/src/base/at_exit.h
+++ b/ipc/chromium/src/base/at_exit.h
@@ -46,19 +46,17 @@ class AtExitManager {
   // Registers the specified function to be called at exit. The prototype of
   // the callback function is void func().
   static void RegisterCallback(AtExitCallbackType func, void* param);
 
   // Calls the functions registered with RegisterCallback in LIFO order. It
   // is possible to register new callbacks after calling this function.
   static void ProcessCallbacksNow();
 
-#ifdef CHROMIUM_MOZILLA_BUILD
   static bool AlreadyRegistered();
-#endif
 
  private:
   struct CallbackAndParam {
     CallbackAndParam(AtExitCallbackType func, void* param)
         : func_(func), param_(param) { }
     AtExitCallbackType func_;
     void* param_;
   };
--- a/ipc/chromium/src/base/atomicops_internals_x86_gcc.h
+++ b/ipc/chromium/src/base/atomicops_internals_x86_gcc.h
@@ -191,28 +191,26 @@ inline Atomic64 Barrier_AtomicIncrement(
   }
   return temp + increment;
 }
 
 inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
   *ptr = value;
 }
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
 inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
                                        Atomic64 old_value,
                                        Atomic64 new_value) {
   Atomic64 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
   /* XXX/cjones: no idea if this is necessary... */
   if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
     __asm__ __volatile__("lfence" : : : "memory");
   }
   return x;
 }
-#endif
 
 inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
   *ptr = value;
   MemoryBarrier();
 }
 
 inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
   ATOMICOPS_COMPILER_BARRIER();
--- a/ipc/chromium/src/base/base_switches.h
+++ b/ipc/chromium/src/base/base_switches.h
@@ -2,17 +2,17 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 // Defines all the "base" command-line switches.
 
 #ifndef BASE_BASE_SWITCHES_H_
 #define BASE_BASE_SWITCHES_H_
 
-#if defined(CHROMIUM_MOZILLA_BUILD) && defined(COMPILER_MSVC)
+#if defined(COMPILER_MSVC)
 #include <string.h>
 #endif
 
 namespace switches {
 
 extern const wchar_t kDebugOnStart[];
 extern const wchar_t kWaitForDebugger[];
 extern const wchar_t kDisableBreakpad[];
--- a/ipc/chromium/src/base/basictypes.h
+++ b/ipc/chromium/src/base/basictypes.h
@@ -1,17 +1,15 @@
 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 #ifndef BASE_BASICTYPES_H_
 #define BASE_BASICTYPES_H_
 
-#ifdef CHROMIUM_MOZILLA_BUILD
-
 // Chromium includes a prtypes.h also, but it has been modified to include
 // their build_config.h as well. We can therefore test for both to determine
 // if someone screws up the include order.
 #if defined(prtypes_h___) && !defined(BUILD_BUILD_CONFIG_H_)
 #error You_must_include_basictypes.h_before_prtypes.h!
 #endif
 
 #ifndef NO_NSPR_10_SUPPORT
@@ -36,18 +34,16 @@
 #define _INT32
 #define _UINT32
 
 #ifdef _WIN32_SAVE
 #undef _WIN32_SAVE
 #define _WIN32
 #endif
 
-#endif // CHROMIUM_MOZILLA_BUILD
-
 #include <limits.h>         // So we can set the bounds of our types
 #include <stddef.h>         // For size_t
 #include <string.h>         // for memcpy
 
 #include "base/port.h"    // Types that only need exist on certain systems
 
 #ifndef COMPILER_MSVC
 // stdint.h is part of C99 but MSVC doesn't have it.
@@ -58,17 +54,17 @@ typedef signed char         schar;
 typedef signed char         int8;
 typedef short               int16;
 // TODO(mbelshe) Remove these type guards.  These are
 //               temporary to avoid conflicts with npapi.h.
 #ifndef _INT32
 #define _INT32
 typedef int                 int32;
 #endif
-#if !(defined(CHROMIUM_MOZILLA_BUILD) && defined(PROTYPES_H))
+#ifndef PROTYPES_H
 typedef long long           int64;
 #endif
 
 // NOTE: unsigned types are DANGEROUS in loops and other arithmetical
 // places.  Use the signed types unless your variable represents a bit
 // pattern (eg a hash value) or you really need the extra bit.  Do NOT
 // use 'unsigned' to express "this value should always be positive";
 // use assertions for this.
@@ -76,17 +72,17 @@ typedef long long           int64;
 typedef unsigned char      uint8;
 typedef unsigned short     uint16;
 // TODO(mbelshe) Remove these type guards.  These are
 //               temporary to avoid conflicts with npapi.h.
 #ifndef _UINT32
 #define _UINT32
 typedef unsigned int       uint32;
 #endif
-#if !(defined(CHROMIUM_MOZILLA_BUILD) && defined(PROTYPES_H))
+#ifndef PROTYPES_H
 typedef unsigned long long uint64;
 #endif
 
 // A type to represent a Unicode code-point value. As of Unicode 4.0,
 // such values require up to 21 bits.
 // (For type-checking on pointers, make this explicitly signed,
 // and it should always be the signed version of whatever int32 is.)
 typedef signed int         char32;
@@ -99,33 +95,31 @@ const  int8  kint8min   = ((  int8) 0x80
 const  int8  kint8max   = ((  int8) 0x7F);
 const  int16 kint16min  = (( int16) 0x8000);
 const  int16 kint16max  = (( int16) 0x7FFF);
 const  int32 kint32min  = (( int32) 0x80000000);
 const  int32 kint32max  = (( int32) 0x7FFFFFFF);
 const  int64 kint64min  = (( int64) GG_LONGLONG(0x8000000000000000));
 const  int64 kint64max  = (( int64) GG_LONGLONG(0x7FFFFFFFFFFFFFFF));
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
 // Platform- and hardware-dependent printf specifiers
 #  if defined(OS_POSIX)
 #    define __STDC_FORMAT_MACROS 1
 #    include <inttypes.h>           // for 64-bit integer format macros
 #    define PRId64L "I64d"
 #    define PRIu64L "I64u"
 #    define PRIx64L "I64x"
 #  elif defined(OS_WIN)
 #    define PRId64 "I64d"
 #    define PRIu64 "I64u"
 #    define PRIx64 "I64x"
 #    define PRId64L L"I64d"
 #    define PRIu64L L"I64u"
 #    define PRIx64L L"I64x"
 #  endif
-#endif  // defined(CHROMIUM_MOZILLA_BUILD)
 
 // A macro to disallow the copy constructor and operator= functions
 // This should be used in the private: declarations for a class
 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
   TypeName(const TypeName&);               \
   void operator=(const TypeName&)
 
 // An older, deprecated, politically incorrect name for the above.
--- a/ipc/chromium/src/base/command_line.h
+++ b/ipc/chromium/src/base/command_line.h
@@ -60,21 +60,19 @@ class CommandLine {
 
   // Get the singleton CommandLine representing the current process's
   // command line.
   static const CommandLine* ForCurrentProcess() {
     DCHECK(current_process_commandline_);
     return current_process_commandline_;
   }
 
-#ifdef CHROMIUM_MOZILLA_BUILD
   static bool IsInitialized() {
     return !!current_process_commandline_;
   }
-#endif
 
   // Returns true if this command line contains the given switch.
   // (Switch names are case-insensitive.)
   bool HasSwitch(const std::wstring& switch_string) const;
 
   // Returns the value associated with the given switch.  If the
   // switch has no value or isn't present, this method returns
   // the empty string.
--- a/ipc/chromium/src/base/debug_util_posix.cc
+++ b/ipc/chromium/src/base/debug_util_posix.cc
@@ -139,30 +139,10 @@ StackTrace::StackTrace() {
 void StackTrace::PrintBacktrace() {
   fflush(stderr);
 #ifndef ANDROID
   backtrace_symbols_fd(&trace_[0], trace_.size(), STDERR_FILENO);
 #endif
 }
 
 void StackTrace::OutputToStream(std::ostream* os) {
-#ifdef CHROMIUM_MOZILLA_BUILD
   return;
-#else
-  scoped_ptr_malloc<char*> trace_symbols(
-      backtrace_symbols(&trace_[0], trace_.size()));
-
-  // If we can't retrieve the symbols, print an error and just dump the raw
-  // addresses.
-  if (trace_symbols.get() == NULL) {
-    (*os) << "Unable get symbols for backtrace (" << strerror(errno)
-          << "). Dumping raw addresses in trace:\n";
-    for (size_t i = 0; i < trace_.size(); ++i) {
-      (*os) << "\t" << trace_[i] << "\n";
-    }
-  } else {
-    (*os) << "Backtrace:\n";
-    for (size_t i = 0; i < trace_.size(); ++i) {
-      (*os) << "\t" << trace_symbols.get()[i] << "\n";
-    }
-  }
-#endif
 }
--- a/ipc/chromium/src/base/histogram.cc
+++ b/ipc/chromium/src/base/histogram.cc
@@ -16,23 +16,21 @@
 
 #include "base/logging.h"
 #include "base/pickle.h"
 #include "base/string_util.h"
 #include "base/logging.h"
 
 namespace base {
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
 #define DVLOG(x) LOG(ERROR)
 #define CHECK_GT DCHECK_GT
 #define CHECK_LT DCHECK_LT
 typedef ::Lock Lock;
 typedef ::AutoLock AutoLock;
-#endif
 
 // Static table of checksums for all possible 8 bit bytes.
 const uint32 Histogram::kCrcTable[256] = {0x0, 0x77073096L, 0xee0e612cL,
 0x990951baL, 0x76dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0xedb8832L,
 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x9b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, 0x1adad47dL,
 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL,
 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L,
--- a/ipc/chromium/src/base/histogram.h
+++ b/ipc/chromium/src/base/histogram.h
@@ -40,21 +40,16 @@
 #ifndef BASE_METRICS_HISTOGRAM_H_
 #define BASE_METRICS_HISTOGRAM_H_
 #pragma once
 
 #include <map>
 #include <string>
 #include <vector>
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
-#define BASE_API
-#else
-#include "base/base_api.h"
-#endif
 #include "testing/gtest/include/gtest/gtest_prod.h"
 #include "base/time.h"
 #include "base/lock.h"
 
 class Pickle;
 
 namespace base {
 //------------------------------------------------------------------------------
@@ -259,17 +254,17 @@ namespace base {
 
 //------------------------------------------------------------------------------
 
 class BooleanHistogram;
 class CustomHistogram;
 class Histogram;
 class LinearHistogram;
 
-class BASE_API Histogram {
+class Histogram {
  public:
   typedef int Sample;  // Used for samples (and ranges of samples).
   typedef int Count;  // Used to count samples in a bucket.
   static const Sample kSampleType_MAX = INT_MAX;
   // Initialize maximum number of buckets in histograms as 16,384.
   static const size_t kBucketCount_MAX;
 
   typedef std::vector<Count> Counts;
@@ -318,17 +313,17 @@ class BASE_API Histogram {
   struct DescriptionPair {
     Sample sample;
     const char* description;  // Null means end of a list of pairs.
   };
 
   //----------------------------------------------------------------------------
   // Statistic values, developed over the life of the histogram.
 
-  class BASE_API SampleSet {
+  class SampleSet {
    public:
     explicit SampleSet();
     ~SampleSet();
 
     // Adjust size of counts_ for use with given histogram.
     void Resize(const Histogram& histogram);
     void CheckSize(const Histogram& histogram) const;
 
@@ -577,17 +572,17 @@ class BASE_API Histogram {
 
   DISALLOW_COPY_AND_ASSIGN(Histogram);
 };
 
 //------------------------------------------------------------------------------
 
 // LinearHistogram is a more traditional histogram, with evenly spaced
 // buckets.
-class BASE_API LinearHistogram : public Histogram {
+class LinearHistogram : public Histogram {
  public:
   virtual ~LinearHistogram();
 
   /* minimum should start from 1. 0 is as minimum is invalid. 0 is an implicit
      default underflow bucket. */
   static Histogram* FactoryGet(const std::string& name,
                                Sample minimum,
                                Sample maximum,
@@ -633,34 +628,34 @@ class BASE_API LinearHistogram : public 
   BucketDescriptionMap bucket_description_;
 
   DISALLOW_COPY_AND_ASSIGN(LinearHistogram);
 };
 
 //------------------------------------------------------------------------------
 
 // BooleanHistogram is a histogram for booleans.
-class BASE_API BooleanHistogram : public LinearHistogram {
+class BooleanHistogram : public LinearHistogram {
  public:
   static Histogram* FactoryGet(const std::string& name, Flags flags);
 
   virtual ClassType histogram_type() const;
 
   virtual void AddBoolean(bool value);
 
  private:
   explicit BooleanHistogram(const std::string& name);
 
   DISALLOW_COPY_AND_ASSIGN(BooleanHistogram);
 };
 
 //------------------------------------------------------------------------------
 
 // CustomHistogram is a histogram for a set of custom integers.
-class BASE_API CustomHistogram : public Histogram {
+class CustomHistogram : public Histogram {
  public:
 
   static Histogram* FactoryGet(const std::string& name,
                                const std::vector<Sample>& custom_ranges,
                                Flags flags);
 
   // Overridden from Histogram:
   virtual ClassType histogram_type() const;
@@ -676,17 +671,17 @@ class BASE_API CustomHistogram : public 
   DISALLOW_COPY_AND_ASSIGN(CustomHistogram);
 };
 
 //------------------------------------------------------------------------------
 // StatisticsRecorder handles all histograms in the system.  It provides a
 // general place for histograms to register, and supports a global API for
 // accessing (i.e., dumping, or graphing) the data in all the histograms.
 
-class BASE_API StatisticsRecorder {
+class StatisticsRecorder {
  public:
   typedef std::vector<Histogram*> Histograms;
 
   StatisticsRecorder();
 
   ~StatisticsRecorder();
 
   // Find out if histograms can now be registered into our list.
--- a/ipc/chromium/src/base/id_map.h
+++ b/ipc/chromium/src/base/id_map.h
@@ -67,29 +67,27 @@ class IDMap {
     }
     data_.erase(i);
   }
 
   bool IsEmpty() const {
     return data_.empty();
   }
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
   void Clear() {
     data_.clear();
   }
 
   bool HasData(const T* data) const {
     // XXX would like to use <algorithm> here ...
     for (const_iterator it = begin(); it != end(); ++it)
       if (data == it->second)
         return true;
     return false;
   }
-#endif
 
   T* Lookup(int32 id) const {
     const_iterator i = data_.find(id);
     if (i == data_.end())
       return NULL;
     return i->second;
   }
 
--- a/ipc/chromium/src/base/logging.cc
+++ b/ipc/chromium/src/base/logging.cc
@@ -1,16 +1,13 @@
 // Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 #include "base/logging.h"
-
-#ifdef CHROMIUM_MOZILLA_BUILD
-
 #include "prmem.h"
 #include "prprf.h"
 #include "base/string_util.h"
 #include "nsXPCOM.h"
 
 namespace mozilla {
 
 Logger::~Logger()
@@ -101,575 +98,8 @@ operator<<(mozilla::Logger& log, const s
 }
 
 mozilla::Logger&
 operator<<(mozilla::Logger& log, void* p)
 {
   log.printf("%p", p);
   return log;
 }
-
-#else
-
-#if defined(OS_WIN)
-#include <windows.h>
-typedef HANDLE FileHandle;
-typedef HANDLE MutexHandle;
-#elif defined(OS_MACOSX)
-#include <CoreFoundation/CoreFoundation.h>
-#include <mach/mach.h>
-#include <mach/mach_time.h>
-#include <mach-o/dyld.h>
-#elif defined(OS_LINUX)
-#include <sys/syscall.h>
-#include <time.h>
-#endif
-
-#if defined(OS_POSIX)
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#define MAX_PATH PATH_MAX
-typedef FILE* FileHandle;
-typedef pthread_mutex_t* MutexHandle;
-#endif
-
-#include <ctime>
-#include <iomanip>
-#include <cstring>
-#include <algorithm>
-
-#include "base/base_switches.h"
-#include "base/command_line.h"
-#include "base/debug_util.h"
-#include "base/lock_impl.h"
-#include "base/string_piece.h"
-#include "base/string_util.h"
-#include "base/sys_string_conversions.h"
-
-namespace logging {
-
-bool g_enable_dcheck = false;
-
-const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
-  "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL" };
-
-int min_log_level = 0;
-LogLockingState lock_log_file = LOCK_LOG_FILE;
-
-// The default set here for logging_destination will only be used if
-// InitLogging is not called.  On Windows, use a file next to the exe;
-// on POSIX platforms, where it may not even be possible to locate the
-// executable on disk, use stderr.
-#if defined(OS_WIN)
-LoggingDestination logging_destination = LOG_ONLY_TO_FILE;
-#elif defined(OS_POSIX)
-LoggingDestination logging_destination = LOG_ONLY_TO_SYSTEM_DEBUG_LOG;
-#endif
-
-const int kMaxFilteredLogLevel = LOG_WARNING;
-std::string* log_filter_prefix;
-
-// For LOG_ERROR and above, always print to stderr.
-const int kAlwaysPrintErrorLevel = LOG_ERROR;
-
-// Which log file to use? This is initialized by InitLogging or
-// will be lazily initialized to the default value when it is
-// first needed.
-#if defined(OS_WIN)
-typedef wchar_t PathChar;
-typedef std::wstring PathString;
-#else
-typedef char PathChar;
-typedef std::string PathString;
-#endif
-PathString* log_file_name = NULL;
-
-// this file is lazily opened and the handle may be NULL
-FileHandle log_file = NULL;
-
-// what should be prepended to each message?
-bool log_process_id = false;
-bool log_thread_id = false;
-bool log_timestamp = true;
-bool log_tickcount = false;
-
-// An assert handler override specified by the client to be called instead of
-// the debug message dialog and process termination.
-LogAssertHandlerFunction log_assert_handler = NULL;
-// An report handler override specified by the client to be called instead of
-// the debug message dialog.
-LogReportHandlerFunction log_report_handler = NULL;
-
-// The lock is used if log file locking is false. It helps us avoid problems
-// with multiple threads writing to the log file at the same time.  Use
-// LockImpl directly instead of using Lock, because Lock makes logging calls.
-static LockImpl* log_lock = NULL;
-
-// When we don't use a lock, we are using a global mutex. We need to do this
-// because LockFileEx is not thread safe.
-#if defined(OS_WIN)
-MutexHandle log_mutex = NULL;
-#elif defined(OS_POSIX)
-pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
-#endif
-
-// Helper functions to wrap platform differences.
-
-int32 CurrentProcessId() {
-#if defined(OS_WIN)
-  return GetCurrentProcessId();
-#elif defined(OS_POSIX)
-  return getpid();
-#endif
-}
-
-int32 CurrentThreadId() {
-#if defined(OS_WIN)
-  return GetCurrentThreadId();
-#elif defined(OS_MACOSX)
-  return mach_thread_self();
-#elif defined(OS_LINUX)
-  return syscall(__NR_gettid);
-#endif
-}
-
-uint64 TickCount() {
-#if defined(OS_WIN)
-  return GetTickCount();
-#elif defined(OS_MACOSX)
-  return mach_absolute_time();
-#elif defined(OS_LINUX)
-  struct timespec ts;
-  clock_gettime(CLOCK_MONOTONIC, &ts);
-
-  uint64 absolute_micro =
-    static_cast<int64>(ts.tv_sec) * 1000000 +
-    static_cast<int64>(ts.tv_nsec) / 1000;
-
-  return absolute_micro;
-#endif
-}
-
-void CloseFile(FileHandle log) {
-#if defined(OS_WIN)
-  CloseHandle(log);
-#else
-  fclose(log);
-#endif
-}
-
-void DeleteFilePath(const PathString& log_name) {
-#if defined(OS_WIN)
-  DeleteFile(log_name.c_str());
-#else
-  unlink(log_name.c_str());
-#endif
-}
-
-// Called by logging functions to ensure that debug_file is initialized
-// and can be used for writing. Returns false if the file could not be
-// initialized. debug_file will be NULL in this case.
-bool InitializeLogFileHandle() {
-  if (log_file)
-    return true;
-
-  if (!log_file_name) {
-    // Nobody has called InitLogging to specify a debug log file, so here we
-    // initialize the log file name to a default.
-#if defined(OS_WIN)
-    // On Windows we use the same path as the exe.
-    wchar_t module_name[MAX_PATH];
-    GetModuleFileName(NULL, module_name, MAX_PATH);
-    log_file_name = new std::wstring(module_name);
-    std::wstring::size_type last_backslash =
-        log_file_name->rfind('\\', log_file_name->size());
-    if (last_backslash != std::wstring::npos)
-      log_file_name->erase(last_backslash + 1);
-    *log_file_name += L"debug.log";
-#elif defined(OS_POSIX)
-    // On other platforms we just use the current directory.
-    log_file_name = new std::string("debug.log");
-#endif
-  }
-
-  if (logging_destination == LOG_ONLY_TO_FILE ||
-      logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
-#if defined(OS_WIN)
-    log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
-                          FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
-                          OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
-    if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
-      // try the current directory
-      log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
-                            FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
-                            OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
-      if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
-        log_file = NULL;
-        return false;
-      }
-    }
-    SetFilePointer(log_file, 0, 0, FILE_END);
-#elif defined(OS_POSIX)
-    log_file = fopen(log_file_name->c_str(), "a");
-    if (log_file == NULL)
-      return false;
-#endif
-  }
-
-  return true;
-}
-
-void InitLogMutex() {
-#if defined(OS_WIN)
-  if (!log_mutex) {
-    // \ is not a legal character in mutex names so we replace \ with /
-    std::wstring safe_name(*log_file_name);
-    std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
-    std::wstring t(L"Global\\");
-    t.append(safe_name);
-    log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
-  }
-#elif defined(OS_POSIX)
-  // statically initialized
-#endif
-}
-
-void InitLogging(const PathChar* new_log_file, LoggingDestination logging_dest,
-                 LogLockingState lock_log, OldFileDeletionState delete_old) {
-  g_enable_dcheck =
-      CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableDCHECK);
-
-  if (log_file) {
-    // calling InitLogging twice or after some log call has already opened the
-    // default log file will re-initialize to the new options
-    CloseFile(log_file);
-    log_file = NULL;
-  }
-
-  lock_log_file = lock_log;
-  logging_destination = logging_dest;
-
-  // ignore file options if logging is disabled or only to system
-  if (logging_destination == LOG_NONE ||
-      logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG)
-    return;
-
-  if (!log_file_name)
-    log_file_name = new PathString();
-  *log_file_name = new_log_file;
-  if (delete_old == DELETE_OLD_LOG_FILE)
-    DeleteFilePath(*log_file_name);
-
-  if (lock_log_file == LOCK_LOG_FILE) {
-    InitLogMutex();
-  } else if (!log_lock) {
-    log_lock = new LockImpl();
-  }
-
-  InitializeLogFileHandle();
-}
-
-void SetMinLogLevel(int level) {
-  min_log_level = level;
-}
-
-int GetMinLogLevel() {
-  return min_log_level;
-}
-
-void SetLogFilterPrefix(const char* filter)  {
-  if (log_filter_prefix) {
-    delete log_filter_prefix;
-    log_filter_prefix = NULL;
-  }
-
-  if (filter)
-    log_filter_prefix = new std::string(filter);
-}
-
-void SetLogItems(bool enable_process_id, bool enable_thread_id,
-                 bool enable_timestamp, bool enable_tickcount) {
-  log_process_id = enable_process_id;
-  log_thread_id = enable_thread_id;
-  log_timestamp = enable_timestamp;
-  log_tickcount = enable_tickcount;
-}
-
-void SetLogAssertHandler(LogAssertHandlerFunction handler) {
-  log_assert_handler = handler;
-}
-
-void SetLogReportHandler(LogReportHandlerFunction handler) {
-  log_report_handler = handler;
-}
-
-// Displays a message box to the user with the error message in it. For
-// Windows programs, it's possible that the message loop is messed up on
-// a fatal error, and creating a MessageBox will cause that message loop
-// to be run. Instead, we try to spawn another process that displays its
-// command line. We look for "Debug Message.exe" in the same directory as
-// the application. If it exists, we use it, otherwise, we use a regular
-// message box.
-void DisplayDebugMessage(const std::string& str) {
-  if (str.empty())
-    return;
-
-#if defined(OS_WIN)
-  // look for the debug dialog program next to our application
-  wchar_t prog_name[MAX_PATH];
-  GetModuleFileNameW(NULL, prog_name, MAX_PATH);
-  wchar_t* backslash = wcsrchr(prog_name, '\\');
-  if (backslash)
-    backslash[1] = 0;
-  wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
-
-  std::wstring cmdline = base::SysUTF8ToWide(str);
-  if (cmdline.empty())
-    return;
-
-  STARTUPINFO startup_info;
-  memset(&startup_info, 0, sizeof(startup_info));
-  startup_info.cb = sizeof(startup_info);
-
-  PROCESS_INFORMATION process_info;
-  if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
-                     NULL, &startup_info, &process_info)) {
-    WaitForSingleObject(process_info.hProcess, INFINITE);
-    CloseHandle(process_info.hThread);
-    CloseHandle(process_info.hProcess);
-  } else {
-    // debug process broken, let's just do a message box
-    MessageBoxW(NULL, &cmdline[0], L"Fatal error",
-                MB_OK | MB_ICONHAND | MB_TOPMOST);
-  }
-#else
-  fprintf(stderr, "%s\n", str.c_str());
-#endif
-}
-
-#if defined(OS_WIN)
-LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
-}
-
-LogMessage::SaveLastError::~SaveLastError() {
-  ::SetLastError(last_error_);
-}
-#endif  // defined(OS_WIN)
-
-LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
-                       int ctr)
-    : severity_(severity) {
-  Init(file, line);
-}
-
-LogMessage::LogMessage(const char* file, int line, const CheckOpString& result)
-    : severity_(LOG_FATAL) {
-  Init(file, line);
-  stream_ << "Check failed: " << (*result.str_);
-}
-
-LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
-                       const CheckOpString& result)
-    : severity_(severity) {
-  Init(file, line);
-  stream_ << "Check failed: " << (*result.str_);
-}
-
-LogMessage::LogMessage(const char* file, int line)
-     : severity_(LOG_INFO) {
-  Init(file, line);
-}
-
-LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
-    : severity_(severity) {
-  Init(file, line);
-}
-
-// writes the common header info to the stream
-void LogMessage::Init(const char* file, int line) {
-  // log only the filename
-  const char* last_slash = strrchr(file, '\\');
-  if (last_slash)
-    file = last_slash + 1;
-
-  // TODO(darin): It might be nice if the columns were fixed width.
-
-  stream_ <<  '[';
-  if (log_process_id)
-    stream_ << CurrentProcessId() << ':';
-  if (log_thread_id)
-    stream_ << CurrentThreadId() << ':';
-  if (log_timestamp) {
-     time_t t = time(NULL);
-#if _MSC_VER >= 1400
-    struct tm local_time = {0};
-    localtime_s(&local_time, &t);
-    struct tm* tm_time = &local_time;
-#else
-    struct tm* tm_time = localtime(&t);
-#endif
-    stream_ << std::setfill('0')
-            << std::setw(2) << 1 + tm_time->tm_mon
-            << std::setw(2) << tm_time->tm_mday
-            << '/'
-            << std::setw(2) << tm_time->tm_hour
-            << std::setw(2) << tm_time->tm_min
-            << std::setw(2) << tm_time->tm_sec
-            << ':';
-  }
-  if (log_tickcount)
-    stream_ << TickCount() << ':';
-  stream_ << log_severity_names[severity_] << ":" << file <<
-             "(" << line << ")] ";
-
-  message_start_ = stream_.tellp();
-}
-
-LogMessage::~LogMessage() {
-  // TODO(brettw) modify the macros so that nothing is executed when the log
-  // level is too high.
-  if (severity_ < min_log_level)
-    return;
-
-  std::string str_newline(stream_.str());
-#if defined(OS_WIN)
-  str_newline.append("\r\n");
-#else
-  str_newline.append("\n");
-#endif
-
-  if (log_filter_prefix && severity_ <= kMaxFilteredLogLevel &&
-      str_newline.compare(message_start_, log_filter_prefix->size(),
-                          log_filter_prefix->data()) != 0) {
-    return;
-  }
-
-  if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG ||
-      logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
-#if defined(OS_WIN)
-    OutputDebugStringA(str_newline.c_str());
-    if (severity_ >= kAlwaysPrintErrorLevel)
-#endif
-    // TODO(erikkay): this interferes with the layout tests since it grabs
-    // stderr and stdout and diffs them against known data. Our info and warn
-    // logs add noise to that.  Ideally, the layout tests would set the log
-    // level to ignore anything below error.  When that happens, we should
-    // take this fprintf out of the #else so that Windows users can benefit
-    // from the output when running tests from the command-line.  In the
-    // meantime, we leave this in for Mac and Linux, but until this is fixed
-    // they won't be able to pass any layout tests that have info or warn logs.
-    // See http://b/1343647
-    fprintf(stderr, "%s", str_newline.c_str());
-  } else if (severity_ >= kAlwaysPrintErrorLevel) {
-    // When we're only outputting to a log file, above a certain log level, we
-    // should still output to stderr so that we can better detect and diagnose
-    // problems with unit tests, especially on the buildbots.
-    fprintf(stderr, "%s", str_newline.c_str());
-  }
-
-  // write to log file
-  if (logging_destination != LOG_NONE &&
-      logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG &&
-      InitializeLogFileHandle()) {
-    // We can have multiple threads and/or processes, so try to prevent them
-    // from clobbering each other's writes.
-    if (lock_log_file == LOCK_LOG_FILE) {
-      // Ensure that the mutex is initialized in case the client app did not
-      // call InitLogging. This is not thread safe. See below.
-      InitLogMutex();
-
-#if defined(OS_WIN)
-      DWORD r = ::WaitForSingleObject(log_mutex, INFINITE);
-      DCHECK(r != WAIT_ABANDONED);
-#elif defined(OS_POSIX)
-      pthread_mutex_lock(&log_mutex);
-#endif
-    } else {
-      // use the lock
-      if (!log_lock) {
-        // The client app did not call InitLogging, and so the lock has not
-        // been created. We do this on demand, but if two threads try to do
-        // this at the same time, there will be a race condition to create
-        // the lock. This is why InitLogging should be called from the main
-        // thread at the beginning of execution.
-        log_lock = new LockImpl();
-      }
-      log_lock->Lock();
-    }
-
-#if defined(OS_WIN)
-    SetFilePointer(log_file, 0, 0, SEEK_END);
-    DWORD num_written;
-    WriteFile(log_file,
-              static_cast<const void*>(str_newline.c_str()),
-              static_cast<DWORD>(str_newline.length()),
-              &num_written,
-              NULL);
-#else
-    fprintf(log_file, "%s", str_newline.c_str());
-#endif
-
-    if (lock_log_file == LOCK_LOG_FILE) {
-#if defined(OS_WIN)
-      ReleaseMutex(log_mutex);
-#elif defined(OS_POSIX)
-      pthread_mutex_unlock(&log_mutex);
-#endif
-    } else {
-      log_lock->Unlock();
-    }
-  }
-
-  if (severity_ == LOG_FATAL) {
-    // display a message or break into the debugger on a fatal error
-    if (DebugUtil::BeingDebugged()) {
-      DebugUtil::BreakDebugger();
-    } else {
-#ifndef NDEBUG
-      // Dump a stack trace on a fatal.
-      StackTrace trace;
-      stream_ << "\n";  // Newline to separate from log message.
-      trace.OutputToStream(&stream_);
-#endif
-
-      if (log_assert_handler) {
-        // make a copy of the string for the handler out of paranoia
-        log_assert_handler(std::string(stream_.str()));
-      } else {
-        // Don't use the string with the newline, get a fresh version to send to
-        // the debug message process. We also don't display assertions to the
-        // user in release mode. The enduser can't do anything with this
-        // information, and displaying message boxes when the application is
-        // hosed can cause additional problems.
-#ifndef NDEBUG
-        DisplayDebugMessage(stream_.str());
-#endif
-        // Crash the process to generate a dump.
-        DebugUtil::BreakDebugger();
-      }
-    }
-  } else if (severity_ == LOG_ERROR_REPORT) {
-    // We are here only if the user runs with --enable-dcheck in release mode.
-    if (log_report_handler) {
-      log_report_handler(std::string(stream_.str()));
-    } else {
-      DisplayDebugMessage(stream_.str());
-    }
-  }
-}
-
-void CloseLogFile() {
-  if (!log_file)
-    return;
-
-  CloseFile(log_file);
-  log_file = NULL;
-}
-
-}  // namespace logging
-
-std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
-  return out << base::SysWideToUTF8(std::wstring(wstr));
-}
-
-#endif // CHROMIUM_MOZILLA_BUILD
--- a/ipc/chromium/src/base/logging.h
+++ b/ipc/chromium/src/base/logging.h
@@ -4,19 +4,16 @@
 
 #ifndef BASE_LOGGING_H_
 #define BASE_LOGGING_H_
 
 #include <string>
 #include <cstring>
 
 #include "base/basictypes.h"
-
-#ifdef CHROMIUM_MOZILLA_BUILD
-
 #include "prlog.h"
 
 // Replace the Chromium logging code with NSPR-based logging code and
 // some C++ wrappers to emulate std::ostream
 
 #define ERROR 0
 
 namespace mozilla {
@@ -118,645 +115,9 @@ const mozilla::EmptyLog& operator <<(con
 #define DCHECK_GE(v1, v2) DCHECK((v1) >= (v2))
 #define DCHECK_GT(v1, v2) DCHECK((v1) > (v2))
 
 #ifdef assert
 #undef assert
 #endif
 #define assert DLOG_ASSERT
 
-#else
-
-#include <sstream>
-
-//
-// Optional message capabilities
-// -----------------------------
-// Assertion failed messages and fatal errors are displayed in a dialog box
-// before the application exits. However, running this UI creates a message
-// loop, which causes application messages to be processed and potentially
-// dispatched to existing application windows. Since the application is in a
-// bad state when this assertion dialog is displayed, these messages may not
-// get processed and hang the dialog, or the application might go crazy.
-//
-// Therefore, it can be beneficial to display the error dialog in a separate
-// process from the main application. When the logging system needs to display
-// a fatal error dialog box, it will look for a program called
-// "DebugMessage.exe" in the same directory as the application executable. It
-// will run this application with the message as the command line, and will
-// not include the name of the application as is traditional for easier
-// parsing.
-//
-// The code for DebugMessage.exe is only one line. In WinMain, do:
-//   MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
-//
-// If DebugMessage.exe is not found, the logging code will use a normal
-// MessageBox, potentially causing the problems discussed above.
-
-
-// Instructions
-// ------------
-//
-// Make a bunch of macros for logging.  The way to log things is to stream
-// things to LOG(<a particular severity level>).  E.g.,
-//
-//   LOG(INFO) << "Found " << num_cookies << " cookies";
-//
-// You can also do conditional logging:
-//
-//   LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
-//
-// The above will cause log messages to be output on the 1st, 11th, 21st, ...
-// times it is executed.  Note that the special COUNTER value is used to
-// identify which repetition is happening.
-//
-// The CHECK(condition) macro is active in both debug and release builds and
-// effectively performs a LOG(FATAL) which terminates the process and
-// generates a crashdump unless a debugger is attached.
-//
-// There are also "debug mode" logging macros like the ones above:
-//
-//   DLOG(INFO) << "Found cookies";
-//
-//   DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
-//
-// All "debug mode" logging is compiled away to nothing for non-debug mode
-// compiles.  LOG_IF and development flags also work well together
-// because the code can be compiled away sometimes.
-//
-// We also have
-//
-//   LOG_ASSERT(assertion);
-//   DLOG_ASSERT(assertion);
-//
-// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
-//
-// We also override the standard 'assert' to use 'DLOG_ASSERT'.
-//
-// The supported severity levels for macros that allow you to specify one
-// are (in increasing order of severity) INFO, WARNING, ERROR, ERROR_REPORT,
-// and FATAL.
-//
-// Very important: logging a message at the FATAL severity level causes
-// the program to terminate (after the message is logged).
-//
-// Note the special severity of ERROR_REPORT only available/relevant in normal
-// mode, which displays error dialog without terminating the program. There is
-// no error dialog for severity ERROR or below in normal mode.
-//
-// There is also the special severity of DFATAL, which logs FATAL in
-// debug mode, ERROR_REPORT in normal mode.
-
-namespace logging {
-
-// Where to record logging output? A flat file and/or system debug log via
-// OutputDebugString. Defaults on Windows to LOG_ONLY_TO_FILE, and on
-// POSIX to LOG_ONLY_TO_SYSTEM_DEBUG_LOG (aka stderr).
-enum LoggingDestination { LOG_NONE,
-                          LOG_ONLY_TO_FILE,
-                          LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
-                          LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG };
-
-// Indicates that the log file should be locked when being written to.
-// Often, there is no locking, which is fine for a single threaded program.
-// If logging is being done from multiple threads or there can be more than
-// one process doing the logging, the file should be locked during writes to
-// make each log outut atomic. Other writers will block.
-//
-// All processes writing to the log file must have their locking set for it to
-// work properly. Defaults to DONT_LOCK_LOG_FILE.
-enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
-
-// On startup, should we delete or append to an existing log file (if any)?
-// Defaults to APPEND_TO_OLD_LOG_FILE.
-enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
-
-// Sets the log file name and other global logging state. Calling this function
-// is recommended, and is normally done at the beginning of application init.
-// If you don't call it, all the flags will be initialized to their default
-// values, and there is a race condition that may leak a critical section
-// object if two threads try to do the first log at the same time.
-// See the definition of the enums above for descriptions and default values.
-//
-// The default log file is initialized to "debug.log" in the application
-// directory. You probably don't want this, especially since the program
-// directory may not be writable on an enduser's system.
-#if defined(OS_WIN)
-void InitLogging(const wchar_t* log_file, LoggingDestination logging_dest,
-                 LogLockingState lock_log, OldFileDeletionState delete_old);
-#elif defined(OS_POSIX)
-// TODO(avi): do we want to do a unification of character types here?
-void InitLogging(const char* log_file, LoggingDestination logging_dest,
-                 LogLockingState lock_log, OldFileDeletionState delete_old);
-#endif
-
-// Sets the log level. Anything at or above this level will be written to the
-// log file/displayed to the user (if applicable). Anything below this level
-// will be silently ignored. The log level defaults to 0 (everything is logged)
-// if this function is not called.
-void SetMinLogLevel(int level);
-
-// Gets the current log level.
-int GetMinLogLevel();
-
-// Sets the log filter prefix.  Any log message below LOG_ERROR severity that
-// doesn't start with this prefix with be silently ignored.  The filter defaults
-// to NULL (everything is logged) if this function is not called.  Messages
-// with severity of LOG_ERROR or higher will not be filtered.
-void SetLogFilterPrefix(const char* filter);
-
-// Sets the common items you want to be prepended to each log message.
-// process and thread IDs default to off, the timestamp defaults to on.
-// If this function is not called, logging defaults to writing the timestamp
-// only.
-void SetLogItems(bool enable_process_id, bool enable_thread_id,
-                 bool enable_timestamp, bool enable_tickcount);
-
-// Sets the Log Assert Handler that will be used to notify of check failures.
-// The default handler shows a dialog box and then terminate the process,
-// however clients can use this function to override with their own handling
-// (e.g. a silent one for Unit Tests)
-typedef void (*LogAssertHandlerFunction)(const std::string& str);
-void SetLogAssertHandler(LogAssertHandlerFunction handler);
-// Sets the Log Report Handler that will be used to notify of check failures
-// in non-debug mode. The default handler shows a dialog box and continues
-// the execution, however clients can use this function to override with their
-// own handling.
-typedef void (*LogReportHandlerFunction)(const std::string& str);
-void SetLogReportHandler(LogReportHandlerFunction handler);
-
-typedef int LogSeverity;
-const LogSeverity LOG_INFO = 0;
-const LogSeverity LOG_WARNING = 1;
-const LogSeverity LOG_ERROR = 2;
-const LogSeverity LOG_ERROR_REPORT = 3;
-const LogSeverity LOG_FATAL = 4;
-const LogSeverity LOG_NUM_SEVERITIES = 5;
-
-// LOG_DFATAL_LEVEL is LOG_FATAL in debug mode, ERROR_REPORT in normal mode
-#ifdef NDEBUG
-const LogSeverity LOG_DFATAL_LEVEL = LOG_ERROR_REPORT;
-#else
-const LogSeverity LOG_DFATAL_LEVEL = LOG_FATAL;
-#endif
-
-// A few definitions of macros that don't generate much code. These are used
-// by LOG() and LOG_IF, etc. Since these are used all over our code, it's
-// better to have compact code for these operations.
-#define COMPACT_GOOGLE_LOG_INFO \
-  logging::LogMessage(__FILE__, __LINE__)
-#define COMPACT_GOOGLE_LOG_WARNING \
-  logging::LogMessage(__FILE__, __LINE__, logging::LOG_WARNING)
-#define COMPACT_GOOGLE_LOG_ERROR \
-  logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR)
-#define COMPACT_GOOGLE_LOG_ERROR_REPORT \
-  logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR_REPORT)
-#define COMPACT_GOOGLE_LOG_FATAL \
-  logging::LogMessage(__FILE__, __LINE__, logging::LOG_FATAL)
-#define COMPACT_GOOGLE_LOG_DFATAL \
-  logging::LogMessage(__FILE__, __LINE__, logging::LOG_DFATAL_LEVEL)
-
-// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
-// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
-// to keep using this syntax, we define this macro to do the same thing
-// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
-// the Windows SDK does for consistency.
-#define ERROR 0
-#define COMPACT_GOOGLE_LOG_0 \
-  logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR)
-
-// We use the preprocessor's merging operator, "##", so that, e.g.,
-// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO.  There's some funny
-// subtle difference between ostream member streaming functions (e.g.,
-// ostream::operator<<(int) and ostream non-member streaming functions
-// (e.g., ::operator<<(ostream&, string&): it turns out that it's
-// impossible to stream something like a string directly to an unnamed
-// ostream. We employ a neat hack by calling the stream() member
-// function of LogMessage which seems to avoid the problem.
-
-#define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
-#define SYSLOG(severity) LOG(severity)
-
-#define LOG_IF(severity, condition) \
-  !(condition) ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
-#define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
-
-#define LOG_ASSERT(condition)  \
-  LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
-#define SYSLOG_ASSERT(condition) \
-  SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
-
-// CHECK dies with a fatal error if condition is not true.  It is *not*
-// controlled by NDEBUG, so the check will be executed regardless of
-// compilation mode.
-#define CHECK(condition) \
-  LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
-
-// A container for a string pointer which can be evaluated to a bool -
-// true iff the pointer is NULL.
-struct CheckOpString {
-  CheckOpString(std::string* str) : str_(str) { }
-  // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
-  // so there's no point in cleaning up str_.
-  operator bool() const { return str_ != NULL; }
-  std::string* str_;
-};
-
-// Build the error message string.  This is separate from the "Impl"
-// function template because it is not performance critical and so can
-// be out of line, while the "Impl" code should be inline.
-template<class t1, class t2>
-std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
-  std::ostringstream ss;
-  ss << names << " (" << v1 << " vs. " << v2 << ")";
-  std::string* msg = new std::string(ss.str());
-  return msg;
-}
-
-extern std::string* MakeCheckOpStringIntInt(int v1, int v2, const char* names);
-
-template<int, int>
-std::string* MakeCheckOpString(const int& v1,
-                               const int& v2,
-                               const char* names) {
-  return MakeCheckOpStringIntInt(v1, v2, names);
-}
-
-// Plus some debug-logging macros that get compiled to nothing for production
-//
-// DEBUG_MODE is for uses like
-//   if (DEBUG_MODE) foo.CheckThatFoo();
-// instead of
-//   #ifndef NDEBUG
-//     foo.CheckThatFoo();
-//   #endif
-
-#ifdef OFFICIAL_BUILD
-// We want to have optimized code for an official build so we remove DLOGS and
-// DCHECK from the executable.
-
-#define DLOG(severity) \
-  true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
-
-#define DLOG_IF(severity, condition) \
-  true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
-
-#define DLOG_ASSERT(condition) \
-  true ? (void) 0 : LOG_ASSERT(condition)
-
-enum { DEBUG_MODE = 0 };
-
-// This macro can be followed by a sequence of stream parameters in
-// non-debug mode. The DCHECK and friends macros use this so that
-// the expanded expression DCHECK(foo) << "asdf" is still syntactically
-// valid, even though the expression will get optimized away.
-// In order to avoid variable unused warnings for code that only uses a
-// variable in a CHECK, we make sure to use the macro arguments.
-#define NDEBUG_EAT_STREAM_PARAMETERS \
-  logging::LogMessage(__FILE__, __LINE__).stream()
-
-#define DCHECK(condition) \
-  while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_EQ(val1, val2) \
-  while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_NE(val1, val2) \
-  while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_LE(val1, val2) \
-  while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_LT(val1, val2) \
-  while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_GE(val1, val2) \
-  while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_GT(val1, val2) \
-  while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_STREQ(str1, str2) \
-  while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_STRCASEEQ(str1, str2) \
-  while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_STRNE(str1, str2) \
-  while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_STRCASENE(str1, str2) \
-  while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
-
-#else
-#ifndef NDEBUG
-// On a regular debug build, we want to have DCHECKS and DLOGS enabled.
-
-#define DLOG(severity) LOG(severity)
-#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
-#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
-
-// debug-only checking.  not executed in NDEBUG mode.
-enum { DEBUG_MODE = 1 };
-#define DCHECK(condition) \
-  LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
-
-// Helper macro for binary operators.
-// Don't use this macro directly in your code, use DCHECK_EQ et al below.
-#define DCHECK_OP(name, op, val1, val2)  \
-  if (logging::CheckOpString _result = \
-      logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
-    logging::LogMessage(__FILE__, __LINE__, _result).stream()
-
-// Helper functions for string comparisons.
-// To avoid bloat, the definitions are in logging.cc.
-#define DECLARE_DCHECK_STROP_IMPL(func, expected) \
-  std::string* Check##func##expected##Impl(const char* s1, \
-                                           const char* s2, \
-                                           const char* names);
-DECLARE_DCHECK_STROP_IMPL(strcmp, true)
-DECLARE_DCHECK_STROP_IMPL(strcmp, false)
-DECLARE_DCHECK_STROP_IMPL(_stricmp, true)
-DECLARE_DCHECK_STROP_IMPL(_stricmp, false)
-#undef DECLARE_DCHECK_STROP_IMPL
-
-// Helper macro for string comparisons.
-// Don't use this macro directly in your code, use CHECK_STREQ et al below.
-#define DCHECK_STROP(func, op, expected, s1, s2) \
-  while (CheckOpString _result = \
-      logging::Check##func##expected##Impl((s1), (s2), \
-                                           #s1 " " #op " " #s2)) \
-    LOG(FATAL) << *_result.str_
-
-// String (char*) equality/inequality checks.
-// CASE versions are case-insensitive.
-//
-// Note that "s1" and "s2" may be temporary strings which are destroyed
-// by the compiler at the end of the current "full expression"
-// (e.g. DCHECK_STREQ(Foo().c_str(), Bar().c_str())).
-
-#define DCHECK_STREQ(s1, s2) DCHECK_STROP(strcmp, ==, true, s1, s2)
-#define DCHECK_STRNE(s1, s2) DCHECK_STROP(strcmp, !=, false, s1, s2)
-#define DCHECK_STRCASEEQ(s1, s2) DCHECK_STROP(_stricmp, ==, true, s1, s2)
-#define DCHECK_STRCASENE(s1, s2) DCHECK_STROP(_stricmp, !=, false, s1, s2)
-
-#define DCHECK_INDEX(I,A) DCHECK(I < (sizeof(A)/sizeof(A[0])))
-#define DCHECK_BOUND(B,A) DCHECK(B <= (sizeof(A)/sizeof(A[0])))
-
-#else  // NDEBUG
-// On a regular release build we want to be able to enable DCHECKS through the
-// command line.
-#define DLOG(severity) \
-  true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
-
-#define DLOG_IF(severity, condition) \
-  true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
-
-#define DLOG_ASSERT(condition) \
-  true ? (void) 0 : LOG_ASSERT(condition)
-
-enum { DEBUG_MODE = 0 };
-
-// This macro can be followed by a sequence of stream parameters in
-// non-debug mode. The DCHECK and friends macros use this so that
-// the expanded expression DCHECK(foo) << "asdf" is still syntactically
-// valid, even though the expression will get optimized away.
-#define NDEBUG_EAT_STREAM_PARAMETERS \
-  logging::LogMessage(__FILE__, __LINE__).stream()
-
-// Set to true in InitLogging when we want to enable the dchecks in release.
-extern bool g_enable_dcheck;
-#define DCHECK(condition) \
-    !logging::g_enable_dcheck ? void (0) : \
-        LOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". "
-
-// Helper macro for binary operators.
-// Don't use this macro directly in your code, use DCHECK_EQ et al below.
-#define DCHECK_OP(name, op, val1, val2)  \
-  if (logging::g_enable_dcheck) \
-    if (logging::CheckOpString _result = \
-        logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
-      logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR_REPORT, \
-                          _result).stream()
-
-#define DCHECK_STREQ(str1, str2) \
-  while (false) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_STRCASEEQ(str1, str2) \
-  while (false) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_STRNE(str1, str2) \
-  while (false) NDEBUG_EAT_STREAM_PARAMETERS
-
-#define DCHECK_STRCASENE(str1, str2) \
-  while (false) NDEBUG_EAT_STREAM_PARAMETERS
-
-#endif  // NDEBUG
-
-// Helper functions for DCHECK_OP macro.
-// The (int, int) specialization works around the issue that the compiler
-// will not instantiate the template version of the function on values of
-// unnamed enum type - see comment below.
-#define DEFINE_DCHECK_OP_IMPL(name, op) \
-  template <class t1, class t2> \
-  inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
-                                        const char* names) { \
-    if (v1 op v2) return NULL; \
-    else return MakeCheckOpString(v1, v2, names); \
-  } \
-  inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
-    if (v1 op v2) return NULL; \
-    else return MakeCheckOpString(v1, v2, names); \
-  }
-DEFINE_DCHECK_OP_IMPL(EQ, ==)
-DEFINE_DCHECK_OP_IMPL(NE, !=)
-DEFINE_DCHECK_OP_IMPL(LE, <=)
-DEFINE_DCHECK_OP_IMPL(LT, < )
-DEFINE_DCHECK_OP_IMPL(GE, >=)
-DEFINE_DCHECK_OP_IMPL(GT, > )
-#undef DEFINE_DCHECK_OP_IMPL
-
-// Equality/Inequality checks - compare two values, and log a LOG_FATAL message
-// including the two values when the result is not as expected.  The values
-// must have operator<<(ostream, ...) defined.
-//
-// You may append to the error message like so:
-//   DCHECK_NE(1, 2) << ": The world must be ending!";
-//
-// We are very careful to ensure that each argument is evaluated exactly
-// once, and that anything which is legal to pass as a function argument is
-// legal here.  In particular, the arguments may be temporary expressions
-// which will end up being destroyed at the end of the apparent statement,
-// for example:
-//   DCHECK_EQ(string("abc")[1], 'b');
-//
-// WARNING: These may not compile correctly if one of the arguments is a pointer
-// and the other is NULL. To work around this, simply static_cast NULL to the
-// type of the desired pointer.
-
-#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
-#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
-#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
-#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
-#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
-#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
-
-#endif  // OFFICIAL_BUILD
-
-#define NOTREACHED() DCHECK(false)
-
-// Redefine the standard assert to use our nice log files
-#undef assert
-#define assert(x) DLOG_ASSERT(x)
-
-// This class more or less represents a particular log message.  You
-// create an instance of LogMessage and then stream stuff to it.
-// When you finish streaming to it, ~LogMessage is called and the
-// full message gets streamed to the appropriate destination.
-//
-// You shouldn't actually use LogMessage's constructor to log things,
-// though.  You should use the LOG() macro (and variants thereof)
-// above.
-class LogMessage {
- public:
-  LogMessage(const char* file, int line, LogSeverity severity, int ctr);
-
-  // Two special constructors that generate reduced amounts of code at
-  // LOG call sites for common cases.
-  //
-  // Used for LOG(INFO): Implied are:
-  // severity = LOG_INFO, ctr = 0
-  //
-  // Using this constructor instead of the more complex constructor above
-  // saves a couple of bytes per call site.
-  LogMessage(const char* file, int line);
-
-  // Used for LOG(severity) where severity != INFO.  Implied
-  // are: ctr = 0
-  //
-  // Using this constructor instead of the more complex constructor above
-  // saves a couple of bytes per call site.
-  LogMessage(const char* file, int line, LogSeverity severity);
-
-  // A special constructor used for check failures.
-  // Implied severity = LOG_FATAL
-  LogMessage(const char* file, int line, const CheckOpString& result);
-
-  // A special constructor used for check failures, with the option to
-  // specify severity.
-  LogMessage(const char* file, int line, LogSeverity severity,
-             const CheckOpString& result);
-
-  ~LogMessage();
-
-  std::ostream& stream() { return stream_; }
-
- private:
-  void Init(const char* file, int line);
-
-  LogSeverity severity_;
-  std::ostringstream stream_;
-  size_t message_start_;  // Offset of the start of the message (past prefix
-                          // info).
-#if defined(OS_WIN)
-  // Stores the current value of GetLastError in the constructor and restores
-  // it in the destructor by calling SetLastError.
-  // This is useful since the LogMessage class uses a lot of Win32 calls
-  // that will lose the value of GLE and the code that called the log function
-  // will have lost the thread error value when the log call returns.
-  class SaveLastError {
-   public:
-    SaveLastError();
-    ~SaveLastError();
-
-    unsigned long get_error() const { return last_error_; }
-
-   protected:
-    unsigned long last_error_;
-  };
-
-  SaveLastError last_error_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(LogMessage);
-};
-
-// A non-macro interface to the log facility; (useful
-// when the logging level is not a compile-time constant).
-inline void LogAtLevel(int const log_level, std::string const &msg) {
-  LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
-}
-
-// This class is used to explicitly ignore values in the conditional
-// logging macros.  This avoids compiler warnings like "value computed
-// is not used" and "statement has no effect".
-class LogMessageVoidify {
- public:
-  LogMessageVoidify() { }
-  // This has to be an operator with a precedence lower than << but
-  // higher than ?:
-  void operator&(std::ostream&) { }
-};
-
-// Closes the log file explicitly if open.
-// NOTE: Since the log file is opened as necessary by the action of logging
-//       statements, there's no guarantee that it will stay closed
-//       after this call.
-void CloseLogFile();
-
-}  // namespace logging
-
-// These functions are provided as a convenience for logging, which is where we
-// use streams (it is against Google style to use streams in other places). It
-// is designed to allow you to emit non-ASCII Unicode strings to the log file,
-// which is normally ASCII. It is relatively slow, so try not to use it for
-// common cases. Non-ASCII characters will be converted to UTF-8 by these
-// operators.
-std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
-inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
-  return out << wstr.c_str();
-}
-
-// The NOTIMPLEMENTED() macro annotates codepaths which have
-// not been implemented yet.
-//
-// The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
-//   0 -- Do nothing (stripped by compiler)
-//   1 -- Warn at compile time
-//   2 -- Fail at compile time
-//   3 -- Fail at runtime (DCHECK)
-//   4 -- [default] LOG(ERROR) at runtime
-//   5 -- LOG(ERROR) at runtime, only once per call-site
-
-#ifndef NOTIMPLEMENTED_POLICY
-// Select default policy: LOG(ERROR)
-#define NOTIMPLEMENTED_POLICY 4
-#endif
-
-#if defined(COMPILER_GCC)
-// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
-// of the current function in the NOTIMPLEMENTED message.
-#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
-#else
-#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
-#endif
-
-#if NOTIMPLEMENTED_POLICY == 0
-#define NOTIMPLEMENTED() ;
-#elif NOTIMPLEMENTED_POLICY == 1
-// TODO, figure out how to generate a warning
-#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
-#elif NOTIMPLEMENTED_POLICY == 2
-#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
-#elif NOTIMPLEMENTED_POLICY == 3
-#define NOTIMPLEMENTED() NOTREACHED()
-#elif NOTIMPLEMENTED_POLICY == 4
-#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
-#elif NOTIMPLEMENTED_POLICY == 5
-#define NOTIMPLEMENTED() do {\
-  static int count = 0;\
-  LOG_IF(ERROR, 0 == count++) << NOTIMPLEMENTED_MSG;\
-} while(0)
-#endif
-
-#endif // CHROMIUM_MOZILLA_BUILD
-
 #endif  // BASE_LOGGING_H_
--- a/ipc/chromium/src/base/message_loop.cc
+++ b/ipc/chromium/src/base/message_loop.cc
@@ -26,19 +26,17 @@
 #ifdef MOZ_WIDGET_QT
 #include "base/message_pump_qt.h"
 #endif
 #endif
 #ifdef MOZ_WIDGET_ANDROID
 #include "base/message_pump_android.h"
 #endif
 
-#ifdef CHROMIUM_MOZILLA_BUILD
 #include "MessagePump.h"
-#endif
 
 using base::Time;
 using base::TimeDelta;
 
 // A lazily created thread local storage for quick access to a thread's message
 // loop, if one exists.  This should be safe and free of static constructors.
 static base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
     base::LINKER_INITIALIZED);
@@ -93,27 +91,25 @@ MessageLoop::MessageLoop(Type type)
       exception_restoration_(false),
       state_(NULL),
 #ifdef OS_WIN
       os_modal_loop_(false),
 #endif  // OS_WIN
       next_sequence_num_(0) {
   DCHECK(!current()) << "should only have one message loop per thread";
   lazy_tls_ptr.Pointer()->Set(this);
-
-#ifdef CHROMIUM_MOZILLA_BUILD
   if (type_ == TYPE_MOZILLA_UI) {
     pump_ = new mozilla::ipc::MessagePump();
     return;
   }
   if (type_ == TYPE_MOZILLA_CHILD) {
     pump_ = new mozilla::ipc::MessagePumpForChildProcess();
     return;
   }
-#endif
+
 #if defined(OS_WIN)
   // TODO(rvargas): Get rid of the OS guards.
   if (type_ == TYPE_DEFAULT) {
     pump_ = new base::MessagePumpDefault();
   } else if (type_ == TYPE_IO) {
     pump_ = new base::MessagePumpForIO();
   } else {
     DCHECK(type_ == TYPE_UI);
@@ -204,25 +200,16 @@ void MessageLoop::RunHandler() {
 
   RunInternal();
 }
 
 //------------------------------------------------------------------------------
 
 void MessageLoop::RunInternal() {
   DCHECK(this == current());
-#if !defined(CHROMIUM_MOZILLA_BUILD)
-  StartHistogrammer();
-#if defined(OS_WIN)
-  if (state_->dispatcher) {
-    pump_win()->RunWithDispatcher(this, state_->dispatcher);
-    return;
-  }
-#endif
-#endif
   pump_->Run(this);
 }
 
 //------------------------------------------------------------------------------
 // Wrapper functions for use in above message loop framework.
 
 bool MessageLoop::ProcessNextDelayedNonNestableTask() {
   if (state_->run_depth != 1)
@@ -286,47 +273,34 @@ void MessageLoop::PostTask_Helper(
 
   // Warning: Don't try to short-circuit, and handle this thread's tasks more
   // directly, as it could starve handling of foreign threads.  Put every task
   // into this queue.
 
   scoped_refptr<base::MessagePump> pump;
   {
     AutoLock locked(incoming_queue_lock_);
-
-#ifdef CHROMIUM_MOZILLA_BUILD
     incoming_queue_.push(pending_task);
-#else
-    bool was_empty = incoming_queue_.empty();
-    incoming_queue_.push(pending_task);
-    if (!was_empty)
-      return;  // Someone else should have started the sub-pump.
-#endif
-
     pump = pump_;
   }
   // Since the incoming_queue_ may contain a task that destroys this message
   // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
   // We use a stack-based reference to the message pump so that we can call
   // ScheduleWork outside of incoming_queue_lock_.
 
   pump->ScheduleWork();
 }
 
 void MessageLoop::SetNestableTasksAllowed(bool allowed) {
   if (nestable_tasks_allowed_ != allowed) {
     nestable_tasks_allowed_ = allowed;
     if (!nestable_tasks_allowed_)
       return;
     // Start the native pump if we are not already pumping.
-#ifndef CHROMIUM_MOZILLA_BUILD
-    pump_->ScheduleWork();
-#else
     pump_->ScheduleWorkForNestedLoop();
-#endif
   }
 }
 
 void MessageLoop::ScheduleWork() {
   // Start the native pump if we are not already pumping.
   pump_->ScheduleWork();
 }
 
@@ -336,17 +310,16 @@ bool MessageLoop::NestableTasksAllowed()
 
 //------------------------------------------------------------------------------
 
 void MessageLoop::RunTask(Task* task) {
   DCHECK(nestable_tasks_allowed_);
   // Execute the task and assume the worst: It is probably not reentrant.
   nestable_tasks_allowed_ = false;
 
-  HistogramEvent(kTaskRunEvent);
   task->Run();
   delete task;
 
   nestable_tasks_allowed_ = true;
 }
 
 bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
   if (pending_task.nestable || state_->run_depth == 1) {
@@ -529,86 +502,16 @@ bool MessageLoop::PendingTask::operator<
     return true;
 
   // If the times happen to match, then we use the sequence number to decide.
   // Compare the difference to support integer roll-over.
   return (sequence_num - other.sequence_num) > 0;
 }
 
 //------------------------------------------------------------------------------
-// Method and data for histogramming events and actions taken by each instance
-// on each thread.
-
-#if !defined(CHROMIUM_MOZILLA_BUILD)
-// static
-bool MessageLoop::enable_histogrammer_ = false;
-#endif
-
-// static
-void MessageLoop::EnableHistogrammer(bool enable) {
-#if !defined(CHROMIUM_MOZILLA_BUILD)
-  enable_histogrammer_ = enable;
-#endif
-}
-
-void MessageLoop::StartHistogrammer() {
-#if !defined(CHROMIUM_MOZILLA_BUILD)
-  if (enable_histogrammer_ && !message_histogram_.get()
-      && base::StatisticsRecorder::IsActive()) {
-    DCHECK(!thread_name_.empty());
-    message_histogram_.reset(static_cast<base::LinearHistogram*>(
-                             base::LinearHistogram::FactoryGet(("MsgLoop:" + thread_name_).c_str(),
-                                                               kLeastNonZeroMessageId,
-                                                               kMaxMessageId,
-                                                               kNumberOfDistinctMessagesDisplayed,
-                                                               base::Histogram::kNoFlags)));
-    message_histogram_->SetFlags(message_histogram_->kHexRangePrintingFlag);
-    message_histogram_->SetRangeDescriptions(event_descriptions_);
-  }
-#endif
-}
-
-void MessageLoop::HistogramEvent(int event) {
-#if !defined(CHROMIUM_MOZILLA_BUILD)
-  if (message_histogram_.get())
-    message_histogram_->Add(event);
-#endif
-}
-
-// Provide a macro that takes an expression (such as a constant, or macro
-// constant) and creates a pair to initalize an array of pairs.  In this case,
-// our pair consists of the expressions value, and the "stringized" version
-// of the expression (i.e., the exrpression put in quotes).  For example, if
-// we have:
-//    #define FOO 2
-//    #define BAR 5
-// then the following:
-//    VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
-// will expand to:
-//   {7, "FOO + BAR"}
-// We use the resulting array as an argument to our histogram, which reads the
-// number as a bucket identifier, and proceeds to use the corresponding name
-// in the pair (i.e., the quoted string) when printing out a histogram.
-#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
-
-#if !defined(CHROMIUM_MOZILLA_BUILD)
-// static
-const base::LinearHistogram::DescriptionPair MessageLoop::event_descriptions_[] = {
-  // Provide some pretty print capability in our histogram for our internal
-  // messages.
-
-  // A few events we handle (kindred to messages), and used to profile actions.
-  VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
-  VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
-
-  {-1, NULL}  // The list must be null terminated, per API to histogram.
-};
-#endif
-
-//------------------------------------------------------------------------------
 // MessageLoopForUI
 
 #if defined(OS_WIN)
 
 void MessageLoopForUI::Run(Dispatcher* dispatcher) {
   AutoRunState save_state(this);
   state_->dispatcher = dispatcher;
   RunHandler();
@@ -657,19 +560,17 @@ bool MessageLoopForIO::WatchFileDescript
   return pump_libevent()->WatchFileDescriptor(
       fd,
       persistent,
       static_cast<base::MessagePumpLibevent::Mode>(mode),
       controller,
       delegate);
 }
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
 bool
 MessageLoopForIO::CatchSignal(int sig,
                               SignalEvent* sigevent,
                               SignalWatcher* delegate)
 {
   return pump_libevent()->CatchSignal(sig, sigevent, delegate);
 }
-#endif  // defined(CHROMIUM_MOZILLA_BUILD)
 
 #endif
--- a/ipc/chromium/src/base/message_loop.h
+++ b/ipc/chromium/src/base/message_loop.h
@@ -5,46 +5,40 @@
 #ifndef BASE_MESSAGE_LOOP_H_
 #define BASE_MESSAGE_LOOP_H_
 
 #include <deque>
 #include <queue>
 #include <string>
 #include <vector>
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
 #include <map>
 #include "base/lock.h"
-#else
-#include "base/histogram.h"
-#endif
 #include "base/message_pump.h"
 #include "base/observer_list.h"
 #include "base/ref_counted.h"
 #include "base/scoped_ptr.h"
 #include "base/task.h"
 #include "base/timer.h"
 
 #if defined(OS_WIN)
 // We need this to declare base::MessagePumpWin::Dispatcher, which we should
 // really just eliminate.
 #include "base/message_pump_win.h"
 #elif defined(OS_POSIX)
 #include "base/message_pump_libevent.h"
 #endif
 
-#ifdef CHROMIUM_MOZILLA_BUILD
 namespace mozilla {
 namespace ipc {
 
 class DoWorkRunnable;
 
 } /* namespace ipc */
 } /* namespace mozilla */
-#endif
 
 // A MessageLoop is used to process events for a particular thread.  There is
 // at most one MessageLoop instance per thread.
 //
 // Events include at a minimum Task instances submitted to PostTask or those
 // managed by TimerManager.  Depending on the type of message pump used by the
 // MessageLoop other events such as UI messages may be processed.  On Windows
 // APC calls (as time permits) and signals sent to a registered set of HANDLEs
@@ -68,23 +62,19 @@ class DoWorkRunnable;
 //   MessageLoop::current()->SetNestableTasksAllowed(old_state);
 //   // Process hr  (the result returned by DoDragDrop().
 //
 // Please be SURE your task is reentrant (nestable) and all global variables
 // are stable and accessible before calling SetNestableTasksAllowed(true).
 //
 class MessageLoop : public base::MessagePump::Delegate {
 
-#ifdef CHROMIUM_MOZILLA_BUILD
   friend class mozilla::ipc::DoWorkRunnable;
-#endif
 
 public:
-  static void EnableHistogrammer(bool enable_histogrammer);
-
   // A DestructionObserver is notified when the current MessageLoop is being
   // destroyed.  These obsevers are notified prior to MessageLoop::current()
   // being changed to return NULL.  This gives interested parties the chance to
   // do final cleanup that depends on the MessageLoop.
   //
   // NOTE: Any tasks posted to the MessageLoop during this notification will
   // not be run.  Instead, they will be deleted.
   //
@@ -207,21 +197,19 @@ public:
   //
   // TYPE_MOZILLA_UI
   //   This type of ML is used in Mozilla parent processes which initialize
   //   XPCOM and use the gecko event loop.
   //
   enum Type {
     TYPE_DEFAULT,
     TYPE_UI,
-    TYPE_IO
-#ifdef CHROMIUM_MOZILLA_BUILD
-    , TYPE_MOZILLA_CHILD
-    , TYPE_MOZILLA_UI
-#endif
+    TYPE_IO,
+    TYPE_MOZILLA_CHILD,
+    TYPE_MOZILLA_UI
   };
 
   // Normally, it is not necessary to instantiate a MessageLoop.  Instead, it
   // is typical to make use of the current thread's MessageLoop instance.
   explicit MessageLoop(Type type = TYPE_DEFAULT);
   ~MessageLoop();
 
   // Returns the type passed to the constructor.
@@ -376,30 +364,16 @@ public:
   void PostTask_Helper(const tracked_objects::Location& from_here, Task* task,
                        int delay_ms, bool nestable);
 
   // base::MessagePump::Delegate methods:
   virtual bool DoWork();
   virtual bool DoDelayedWork(base::Time* next_delayed_work_time);
   virtual bool DoIdleWork();
 
-  // Start recording histogram info about events and action IF it was enabled
-  // and IF the statistics recorder can accept a registration of our histogram.
-  void StartHistogrammer();
-
-  // Add occurence of event to our histogram, so that we can see what is being
-  // done in a specific MessageLoop instance (i.e., specific thread).
-  // If message_histogram_ is NULL, this is a no-op.
-  void HistogramEvent(int event);
-
-#if !defined(CHROMIUM_MOZILLA_BUILD)
-  static const base::LinearHistogram::DescriptionPair event_descriptions_[];
-  static bool enable_histogrammer_;
-#endif
-
   Type type_;
 
   // A list of tasks that need to be processed by this instance.  Note that
   // this queue is only accessed (push/pop) by our current thread.
   TaskQueue work_queue_;
 
   // Contains delayed tasks, sorted by their 'delayed_run_time' property.
   DelayedTaskQueue delayed_work_queue_;
@@ -415,20 +389,17 @@ public:
 
   // A recursion block that prevents accidentally running additonal tasks when
   // insider a (accidentally induced?) nested message pump.
   bool nestable_tasks_allowed_;
 
   bool exception_restoration_;
 
   std::string thread_name_;
-#if !defined(CHROMIUM_MOZILLA_BUILD)
-  // A profiling histogram showing the counts of various messages and events.
-  scoped_ptr<base::LinearHistogram> message_histogram_;
-#endif
+
   // A null terminated list which creates an incoming_queue of tasks that are
   // aquired under a mutex for processing on this instance's thread. These tasks
   // have not yet been sorted out into items for our work_queue_ vs items that
   // will be handled by the TimerManager.
   TaskQueue incoming_queue_;
   // Protect access to incoming_queue_.
   Lock incoming_queue_lock_;
 
@@ -458,24 +429,20 @@ class MessageLoopForUI : public MessageL
   MessageLoopForUI(Type type=TYPE_UI) : MessageLoop(type) {
   }
 
   // Returns the MessageLoopForUI of the current thread.
   static MessageLoopForUI* current() {
     MessageLoop* loop = MessageLoop::current();
     if (!loop)
       return NULL;
-#ifdef CHROMIUM_MOZILLA_BUILD
     Type type = loop->type();
     DCHECK(type == MessageLoop::TYPE_UI ||
            type == MessageLoop::TYPE_MOZILLA_UI ||
            type == MessageLoop::TYPE_MOZILLA_CHILD);
-#else
-    DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
-#endif
     return static_cast<MessageLoopForUI*>(loop);
   }
 
 #if defined(OS_WIN)
   typedef base::MessagePumpWin::Dispatcher Dispatcher;
   typedef base::MessagePumpWin::Observer Observer;
 
   // Please see MessagePumpWin for definitions of these methods.
@@ -546,23 +513,21 @@ class MessageLoopForIO : public MessageL
 
   // Please see MessagePumpLibevent for definition.
   bool WatchFileDescriptor(int fd,
                            bool persistent,
                            Mode mode,
                            FileDescriptorWatcher *controller,
                            Watcher *delegate);
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
   typedef base::MessagePumpLibevent::SignalEvent SignalEvent;
   typedef base::MessagePumpLibevent::SignalWatcher SignalWatcher;
   bool CatchSignal(int sig,
                    SignalEvent* sigevent,
                    SignalWatcher* delegate);
-#endif  // defined(CHROMIUM_MOZILLA_BUILD)
 
 #endif  // defined(OS_POSIX)
 };
 
 // Do not add any member variables to MessageLoopForIO!  This is important b/c
 // MessageLoopForIO is often allocated via MessageLoop(TYPE_IO).  Any extra
 // data that you need should be stored on the MessageLoop's pump_ instance.
 COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
--- a/ipc/chromium/src/base/message_pump.h
+++ b/ipc/chromium/src/base/message_pump.h
@@ -106,25 +106,23 @@ class MessagePump : public RefCountedThr
   virtual void Quit() = 0;
 
   // Schedule a DoWork callback to happen reasonably soon.  Does nothing if a
   // DoWork callback is already scheduled.  This method may be called from any
   // thread.  Once this call is made, DoWork should not be "starved" at least
   // until it returns a value of false.
   virtual void ScheduleWork() = 0;
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
   // This method may only called from the thread that called Run.
   //
   // Ensure that DoWork will be called if a nested loop is entered.
   // If a MessagePump can already guarantee that DoWork will be called
   // "reasonably soon", this method can be a no-op to avoid expensive
   // atomic tests and/or syscalls required for ScheduleWork().
   virtual void ScheduleWorkForNestedLoop() { ScheduleWork(); };
-#endif  // defined(CHROMIUM_MOZILLA_BUILD)
 
   // Schedule a DoDelayedWork callback to happen at the specified time,
   // cancelling any pending DoDelayedWork callback.  This method may only be
   // used on the thread that called Run.
   virtual void ScheduleDelayedWork(const Time& delayed_work_time) = 0;
 };
 
 }  // namespace base
--- a/ipc/chromium/src/base/message_pump_default.h
+++ b/ipc/chromium/src/base/message_pump_default.h
@@ -17,31 +17,25 @@ class MessagePumpDefault : public Messag
   ~MessagePumpDefault() {}
 
   // MessagePump methods:
   virtual void Run(Delegate* delegate);
   virtual void Quit();
   virtual void ScheduleWork();
   virtual void ScheduleDelayedWork(const Time& delayed_work_time);
 
-#ifdef CHROMIUM_MOZILLA_BUILD
  protected:
-#else
- private:
-#endif
   // This flag is set to false when Run should return.
   bool keep_running_;
 
   // Used to sleep until there is more work to do.
   WaitableEvent event_;
 
   // The time at which we should call DoDelayedWork.
   Time delayed_work_time_;
 
-#ifdef CHROMIUM_MOZILLA_BUILD
  private:
-#endif
   DISALLOW_COPY_AND_ASSIGN(MessagePumpDefault);
 };
 
 }  // namespace base
 
 #endif  // BASE_MESSAGE_PUMP_DEFAULT_H_
--- a/ipc/chromium/src/base/message_pump_libevent.cc
+++ b/ipc/chromium/src/base/message_pump_libevent.cc
@@ -207,17 +207,16 @@ void MessagePumpLibevent::OnLibeventNoti
     watcher->OnFileCanWriteWithoutBlocking(fd);
   }
   if (flags & EV_READ) {
     watcher->OnFileCanReadWithoutBlocking(fd);
   }
 }
 
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
 MessagePumpLibevent::SignalEvent::SignalEvent() :
   event_(NULL)
 {
 }
 
 MessagePumpLibevent::SignalEvent::~SignalEvent()
 {
   if (event_) {
@@ -288,17 +287,16 @@ void
 MessagePumpLibevent::OnLibeventSignalNotification(int sig, short flags,
                                                   void* context)
 {
   DCHECK(sig > 0);
   DCHECK(EV_SIGNAL == flags);
   DCHECK(context);
   reinterpret_cast<SignalWatcher*>(context)->OnSignal(sig);
 }
-#endif  // defined(CHROMIUM_MOZILLA_BUILD)
 
 
 // Reentrant!
 void MessagePumpLibevent::Run(Delegate* delegate) {
   DCHECK(keep_running_) << "Quit must have been called outside of Run!";
 
   bool old_in_run = in_run_;
   in_run_ = true;
--- a/ipc/chromium/src/base/message_pump_libevent.h
+++ b/ipc/chromium/src/base/message_pump_libevent.h
@@ -80,17 +80,16 @@ class MessagePumpLibevent : public Messa
   // TODO(dkegel): switch to edge-triggered readiness notification
   bool WatchFileDescriptor(int fd,
                            bool persistent,
                            Mode mode,
                            FileDescriptorWatcher *controller,
                            Watcher *delegate);
 
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
   // This is analagous to FileDescriptorWatcher above, which really is
   // just a wrapper around libevent's |struct event|.  This class acts
   // as a sort of "scoped event watcher" in that it guarantees that
   // when this class is out of scope, the signal-event it wraps is
   // removed from libevent's guts.
   //
   // XXX/cjones: this isn't my favorite API, but preserving it in
   // order to match code above
@@ -124,17 +123,16 @@ class MessagePumpLibevent : public Messa
   // Have the current thread's message loop catch the signal |sig|.
   // Multiple watchers can catch the same signal; they're all notified
   // upon its delivery.  Callers must provide a preallocated
   // SignalEvent object which can be used to manage the lifetime of
   // this event.  Returns true on success.
   bool CatchSignal(int sig,
                    SignalEvent* sigevent,
                    SignalWatcher* delegate);
-#endif  // defined(CHROMIUM_MOZILLA_BUILD)
 
 
   // MessagePump methods:
   virtual void Run(Delegate* delegate);
   virtual void Quit();
   virtual void ScheduleWork();
   virtual void ScheduleDelayedWork(const Time& delayed_work_time);
 
@@ -155,21 +153,19 @@ class MessagePumpLibevent : public Messa
   // Libevent dispatcher.  Watches all sockets registered with it, and sends
   // readiness callbacks when a socket is ready for I/O.
   event_base* event_base_;
 
   // Called by libevent to tell us a registered FD can be read/written to.
   static void OnLibeventNotification(int fd, short flags,
                                      void* context);
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
   // Called by libevent upon receiving a signal
   static void OnLibeventSignalNotification(int sig, short flags,
                                            void* context);
-#endif
 
   // Unix pipe used to implement ScheduleWork()
   // ... callback; called by libevent inside Run() when pipe is ready to read
   static void OnWakeup(int socket, short flags, void* context);
   // ... write end; ScheduleWork() writes a single byte to it
   int wakeup_pipe_in_;
   // ... read end; OnWakeup reads it and then breaks Run() out of its sleep
   int wakeup_pipe_out_;
--- a/ipc/chromium/src/base/pickle.cc
+++ b/ipc/chromium/src/base/pickle.cc
@@ -10,21 +10,17 @@
 #include <string>
 
 //------------------------------------------------------------------------------
 
 // static
 const int Pickle::kPayloadUnit = 64;
 
 // We mark a read only pickle with a special capacity_.
-#ifdef CHROMIUM_MOZILLA_BUILD
 static const uint32 kCapacityReadOnly = (uint32) -1;
-#else
-static const size_t kCapacityReadOnly = (size_t) -1;
-#endif
 
 // Payload is uint32 aligned.
 
 Pickle::Pickle()
     : header_(NULL),
       header_size_(sizeof(Header)),
       capacity_(0),
       variable_buffer_offset_(0) {
@@ -32,21 +28,17 @@ Pickle::Pickle()
   header_->payload_size = 0;
 }
 
 Pickle::Pickle(int header_size)
     : header_(NULL),
       header_size_(AlignInt(header_size, sizeof(uint32))),
       capacity_(0),
       variable_buffer_offset_(0) {
-#ifdef CHROMIUM_MOZILLA_BUILD
   DCHECK(static_cast<uint32>(header_size) >= sizeof(Header));
-#else
-  DCHECK(static_cast<size_t>(header_size) >= sizeof(Header));
-#endif
   DCHECK(header_size <= kPayloadUnit);
   Resize(kPayloadUnit);
   header_->payload_size = 0;
 }
 
 Pickle::Pickle(const char* data, int data_len)
     : header_(reinterpret_cast<Header*>(const_cast<char*>(data))),
       header_size_(data_len - header_->payload_size),
@@ -56,21 +48,17 @@ Pickle::Pickle(const char* data, int dat
   DCHECK(header_size_ == AlignInt(header_size_, sizeof(uint32)));
 }
 
 Pickle::Pickle(const Pickle& other)
     : header_(NULL),
       header_size_(other.header_size_),
       capacity_(0),
       variable_buffer_offset_(other.variable_buffer_offset_) {
-#ifdef CHROMIUM_MOZILLA_BUILD
   uint32 payload_size = header_size_ + other.header_->payload_size;
-#else
-  size_t payload_size = header_size_ + other.header_->payload_size;
-#endif
   bool resized = Resize(payload_size);
   CHECK(resized);  // Realloc failed.
   memcpy(header_, other.header_, payload_size);
 }
 
 Pickle::~Pickle() {
   if (capacity_ != kCapacityReadOnly)
     free(header_);
@@ -394,31 +382,22 @@ bool Pickle::ReadData(void** iter, const
     *iter = const_cast<char*>(payload());
 
   if (!ReadLength(iter, length))
     return false;
 
   return ReadBytes(iter, data, *length);
 }
 
-#ifdef CHROMIUM_MOZILLA_BUILD
 char* Pickle::BeginWrite(uint32 length) {
-#else
-char* Pickle::BeginWrite(size_t length) {
-#endif
   // write at a uint32-aligned offset from the beginning of the header
   uint32 offset = AlignInt(header_->payload_size, sizeof(uint32));
-
-#ifdef CHROMIUM_MOZILLA_BUILD
   uint32 new_size = offset + AlignInt(length, sizeof(uint32));
   uint32 needed_size = header_size_ + new_size;
-#else
-  size_t new_size = offset + length;
-  size_t needed_size = header_size_ + new_size;
-#endif
+
   if (needed_size > capacity_ && !Resize(std::max(capacity_ * 2, needed_size)))
     return NULL;
 
 #ifdef ARCH_CPU_64_BITS
   DCHECK_LE(length, std::numeric_limits<uint32>::max());
 #endif
 
   header_->payload_size = static_cast<uint32>(new_size);
@@ -504,46 +483,34 @@ void Pickle::TrimWriteData(int new_lengt
     return;
   }
 
   // Update the payload size and variable buffer size
   header_->payload_size -= (*cur_length - new_length);
   *cur_length = new_length;
 }
 
-#ifdef CHROMIUM_MOZILLA_BUILD
 bool Pickle::Resize(uint32 new_capacity) {
-#else
-bool Pickle::Resize(size_t new_capacity) {
-#endif
   new_capacity = AlignInt(new_capacity, kPayloadUnit);
 
   void* p = realloc(header_, new_capacity);
   if (!p)
     return false;
 
   header_ = reinterpret_cast<Header*>(p);
   capacity_ = new_capacity;
   return true;
 }
 
 // static
-#ifdef CHROMIUM_MOZILLA_BUILD
 const char* Pickle::FindNext(uint32 header_size,
-#else
-const char* Pickle::FindNext(size_t header_size,
-#endif
                              const char* start,
                              const char* end) {
   DCHECK(header_size == AlignInt(header_size, sizeof(uint32)));
-#ifdef CHROMIUM_MOZILLA_BUILD
   DCHECK(header_size <= static_cast<uint32>(kPayloadUnit));
-#else
-  DCHECK(header_size <= static_cast<size_t>(kPayloadUnit));
-#endif
 
   const Header* hdr = reinterpret_cast<const Header*>(start);
   const char* payload_base = start + header_size;
   const char* payload_end = payload_base + hdr->payload_size;
   if (payload_end < payload_base)
     return NULL;
 
   return (payload_end > end) ? NULL : payload_end;
--- a/ipc/chromium/src/base/pickle.h
+++ b/ipc/chromium/src/base/pickle.h
@@ -165,21 +165,19 @@ class Pickle {
   // requested.  For example, you may have created a buffer with 10K of data,
   // but decided to only fill 10 bytes of that data.  Use this function
   // to trim the buffer so that we don't send 9990 bytes of unused data.
   // You cannot increase the size of the variable buffer; only shrink it.
   // This function assumes that the length of the variable buffer has
   // not been changed.
   void TrimWriteData(int length);
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
   void EndRead(void* iter) const {
     DCHECK(iter == end_of_payload());
   }
-#endif
 
   // Payload follows after allocation of Header (header size is customizable).
   struct Header {
     uint32 payload_size;  // Specifies the size of the payload.
   };
 
   // Returns the header, cast to a user-specified type T.  The type T must be a
   // subclass of Header and its size must correspond to the header_size passed
@@ -202,21 +200,17 @@ class Pickle {
     if ((len < 0) || (iter < header_) || iter > end_of_payload())
       return false;
     const char* end_of_region = reinterpret_cast<const char*>(iter) + len;
     // Watch out for overflow in pointer calculation, which wraps.
     return (iter <= end_of_region) && (end_of_region <= end_of_payload());
   }
 
  protected:
-#ifdef CHROMIUM_MOZILLA_BUILD
   uint32 payload_size() const { return header_->payload_size; }
-#else
-  size_t payload_size() const { return header_->payload_size; }
-#endif
 
   char* payload() {
     return reinterpret_cast<char*>(header_) + header_size_;
   }
   const char* payload() const {
     return reinterpret_cast<const char*>(header_) + header_size_;
   }
 
@@ -224,89 +218,61 @@ class Pickle {
   // header + payload.
   char* end_of_payload() {
     return payload() + payload_size();
   }
   const char* end_of_payload() const {
     return payload() + payload_size();
   }
 
-#ifdef CHROMIUM_MOZILLA_BUILD
   uint32 capacity() const {
-#else
-  size_t capacity() const {
-#endif
     return capacity_;
   }
 
   // Resizes the buffer for use when writing the specified amount of data. The
   // location that the data should be written at is returned, or NULL if there
   // was an error. Call EndWrite with the returned offset and the given length
   // to pad out for the next write.
-#ifdef CHROMIUM_MOZILLA_BUILD
   char* BeginWrite(uint32 length);
-#else
-  char* BeginWrite(size_t length);
-#endif
 
   // Completes the write operation by padding the data with NULL bytes until it
   // is padded. Should be paired with BeginWrite, but it does not necessarily
   // have to be called after the data is written.
   void EndWrite(char* dest, int length);
 
   // Resize the capacity, note that the input value should include the size of
   // the header: new_capacity = sizeof(Header) + desired_payload_capacity.
   // A realloc() failure will cause a Resize failure... and caller should check
   // the return result for true (i.e., successful resizing).
-#ifdef CHROMIUM_MOZILLA_BUILD
   bool Resize(uint32 new_capacity);
-#else
-  bool Resize(size_t new_capacity);
-#endif
 
   // Aligns 'i' by rounding it up to the next multiple of 'alignment'
-#ifdef CHROMIUM_MOZILLA_BUILD
   static uint32 AlignInt(uint32 i, int alignment) {
-#else
-  static size_t AlignInt(size_t i, int alignment) {
-#endif
     return i + (alignment - (i % alignment)) % alignment;
   }
 
   // Moves the iterator by the given number of bytes, making sure it is aligned.
   // Pointer (iterator) is NOT aligned, but the change in the pointer
   // is guaranteed to be a multiple of sizeof(uint32).
   static void UpdateIter(void** iter, int bytes) {
     *iter = static_cast<char*>(*iter) + AlignInt(bytes, sizeof(uint32));
   }
 
   // Find the end of the pickled data that starts at range_start.  Returns NULL
   // if the entire Pickle is not found in the given data range.
-#ifdef CHROMIUM_MOZILLA_BUILD
   static const char* FindNext(uint32 header_size,
-#else
-  static const char* FindNext(size_t header_size,
-#endif
                               const char* range_start,
                               const char* range_end);
 
   // The allocation granularity of the payload.
   static const int kPayloadUnit;
 
  private:
   Header* header_;
-#ifdef CHROMIUM_MOZILLA_BUILD
   uint32 header_size_;
   uint32 capacity_;
   uint32 variable_buffer_offset_;
-#else
-  size_t header_size_;  // Supports extra data between header and payload.
-  // Allocation size of payload (or -1 if allocation is const).
-  size_t capacity_;
-  size_t variable_buffer_offset_;  // IF non-zero, then offset to a buffer.
-#endif
-
   FRIEND_TEST(PickleTest, Resize);
   FRIEND_TEST(PickleTest, FindNext);
   FRIEND_TEST(PickleTest, IteratorHasRoom);
 };
 
 #endif  // BASE_PICKLE_H__
--- a/ipc/chromium/src/base/port.h
+++ b/ipc/chromium/src/base/port.h
@@ -35,38 +35,27 @@
 namespace base {
 
 // It's possible for functions that use a va_list, such as StringPrintf, to
 // invalidate the data in it upon use.  The fix is to make a copy of the
 // structure before using it and use that copy instead.  va_copy is provided
 // for this purpose.  MSVC does not provide va_copy, so define an
 // implementation here.  It is not guaranteed that assignment is a copy, so the
 // StringUtil.VariableArgsFunc unit test tests this capability.
-#if !defined(CHROMIUM_MOZILLA_BUILD)
-inline void va_copy(va_list& a, va_list& b) {
-#if defined(COMPILER_GCC)
-  ::va_copy(a, b);
-#elif defined(COMPILER_MSVC)
-  a = b;
-#endif
-}
 
-#else
 // The C standard says that va_copy is a "macro", not a function.  Trying to 
 // use va_list as ref args to a function, as above, breaks some machines.
 #  if defined(COMPILER_GCC)
 #    define base_va_copy(_a, _b) ::va_copy(_a, _b)
 #  elif defined(COMPILER_MSVC)
 #    define base_va_copy(_a, _b) (_a = _b)
 #  else
 #    error No va_copy for your compiler
 #  endif
 
-#endif
-
 }  // namespace base
 
 // Define an OS-neutral wrapper for shared library entry points
 #if defined(OS_WIN)
 #define API_CALL __stdcall
 #elif defined(OS_LINUX) || defined(OS_MACOSX)
 #define API_CALL
 #endif
--- a/ipc/chromium/src/base/process_util_linux.cc
+++ b/ipc/chromium/src/base/process_util_linux.cc
@@ -27,30 +27,26 @@ enum ParsingState {
 };
 
 static mozilla::EnvironmentLog gProcessLog("MOZ_PROCESS_LOG");
 
 }  // namespace
 
 namespace base {
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
 bool LaunchApp(const std::vector<std::string>& argv,
                const file_handle_mapping_vector& fds_to_remap,
                bool wait, ProcessHandle* process_handle) {
   return LaunchApp(argv, fds_to_remap, environment_map(),
                    wait, process_handle);
 }
-#endif
 
 bool LaunchApp(const std::vector<std::string>& argv,
                const file_handle_mapping_vector& fds_to_remap,
-#if defined(CHROMIUM_MOZILLA_BUILD)
                const environment_map& env_vars_to_set,
-#endif
                bool wait, ProcessHandle* process_handle,
                ProcessArchitecture arch) {
   pid_t pid = fork();
   if (pid < 0)
     return false;
 
   if (pid == 0) {
     InjectiveMultimap fd_shuffle;
@@ -59,33 +55,29 @@ bool LaunchApp(const std::vector<std::st
       fd_shuffle.push_back(InjectionArc(it->first, it->second, false));
     }
 
     if (!ShuffleFileDescriptors(fd_shuffle))
       exit(127);
 
     CloseSuperfluousFds(fd_shuffle);
 
-#if defined(CHROMIUM_MOZILLA_BUILD)
     for (environment_map::const_iterator it = env_vars_to_set.begin();
          it != env_vars_to_set.end(); ++it) {
       if (setenv(it->first.c_str(), it->second.c_str(), 1/*overwrite*/))
         exit(127);
     }
-#endif
 
     scoped_array<char*> argv_cstr(new char*[argv.size() + 1]);
     for (size_t i = 0; i < argv.size(); i++)
       argv_cstr[i] = const_cast<char*>(argv[i].c_str());
     argv_cstr[argv.size()] = NULL;
     execvp(argv_cstr[0], argv_cstr.get());
-#if defined(CHROMIUM_MOZILLA_BUILD)
     // if we get here, we're in serious trouble and should complain loudly
     DLOG(ERROR) << "FAILED TO exec() CHILD PROCESS, path: " << argv_cstr[0];
-#endif
     exit(127);
   } else {
     gProcessLog.print("==> process %d launched child process %d\n",
                       GetCurrentProcId(), pid);
     if (wait)
       HANDLE_EINTR(waitpid(pid, 0, 0));
 
     if (process_handle)
--- a/ipc/chromium/src/base/process_util_win.cc
+++ b/ipc/chromium/src/base/process_util_win.cc
@@ -316,46 +316,16 @@ bool DidProcessCrash(bool* child_exited,
       exitcode == PROCESS_END_KILLED_BY_USER ||
       exitcode == PROCESS_END_PROCESS_WAS_HUNG ||
       exitcode == 0xC0000354 ||     // STATUS_DEBUGGER_INACTIVE.
       exitcode == 0xC000013A ||     // Control-C/end session.
       exitcode == 0x40010004) {     // Debugger terminated process/end session.
     return false;
   }
 
-#ifndef CHROMIUM_MOZILLA_BUILD
-  // All other exit codes indicate crashes.
-
-  // TODO(jar): Remove histogramming code when UMA stats are consistent with
-  // other crash metrics.
-  // Histogram the low order 3 nibbles for UMA
-  const int kLeastValue = 0;
-  const int kMaxValue = 0xFFF;
-  const int kBucketCount = kMaxValue - kLeastValue + 1;
-  static LinearHistogram least_significant_histogram("ExitCodes.LSNibbles",
-      kLeastValue + 1, kMaxValue, kBucketCount);
-  least_significant_histogram.SetFlags(kUmaTargetedHistogramFlag |
-                                       LinearHistogram::kHexRangePrintingFlag);
-  least_significant_histogram.Add(exitcode & 0xFFF);
-
-  // Histogram the high order 3 nibbles
-  static LinearHistogram most_significant_histogram("ExitCodes.MSNibbles",
-      kLeastValue + 1, kMaxValue, kBucketCount);
-  most_significant_histogram.SetFlags(kUmaTargetedHistogramFlag |
-                                      LinearHistogram::kHexRangePrintingFlag);
-  // Avoid passing in negative numbers by shifting data into low end of dword.
-  most_significant_histogram.Add((exitcode >> 20) & 0xFFF);
-
-  // Histogram the middle order 2 nibbles
-  static LinearHistogram mid_significant_histogram("ExitCodes.MidNibbles",
-      1, 0xFF, 0x100);
-  mid_significant_histogram.SetFlags(kUmaTargetedHistogramFlag |
-                                      LinearHistogram::kHexRangePrintingFlag);
-  mid_significant_histogram.Add((exitcode >> 12) & 0xFF);
-#endif
   return true;
 }
 
 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
   ScopedHandle closer(handle);  // Ensure that we always close the handle.
   if (::WaitForSingleObject(handle, INFINITE) != WAIT_OBJECT_0) {
     NOTREACHED();
     return false;
--- a/ipc/chromium/src/base/shared_memory.h
+++ b/ipc/chromium/src/base/shared_memory.h
@@ -62,21 +62,17 @@ class SharedMemory {
   static SharedMemoryHandle NULLHandle();
 
   // Creates or opens a shared memory segment based on a name.
   // If read_only is true, opens the memory as read-only.
   // If open_existing is true, and the shared memory already exists,
   // opens the existing shared memory and ignores the size parameter.
   // If name is the empty string, use a unique name.
   // Returns true on success, false on failure.
-#ifdef CHROMIUM_MOZILLA_BUILD
   bool Create(const std::string& name, bool read_only, bool open_existing,
-#else
-  bool Create(const std::wstring& name, bool read_only, bool open_existing,
-#endif
               size_t size);
 
   // Deletes resources associated with a shared memory segment based on name.
   // Not all platforms require this call.
   bool Delete(const std::wstring& name);
 
   // Opens a shared memory segment based on a name.
   // If read_only is true, opens for read-only access.
--- a/ipc/chromium/src/base/shared_memory_posix.cc
+++ b/ipc/chromium/src/base/shared_memory_posix.cc
@@ -65,27 +65,21 @@ bool SharedMemory::IsHandleValid(const S
   return handle.fd >= 0;
 }
 
 // static
 SharedMemoryHandle SharedMemory::NULLHandle() {
   return SharedMemoryHandle();
 }
 
-#ifdef CHROMIUM_MOZILLA_BUILD
 bool SharedMemory::Create(const std::string &cname, bool read_only,
-#else
-bool SharedMemory::Create(const std::wstring &name, bool read_only,
-#endif
                           bool open_existing, size_t size) {
   read_only_ = read_only;
 
-#ifdef CHROMIUM_MOZILLA_BUILD
   std::wstring name = UTF8ToWide(cname);
-#endif
 
   int posix_flags = 0;
   posix_flags |= read_only ? O_RDONLY : O_RDWR;
   if (!open_existing || mapped_file_ <= 0)
     posix_flags |= O_CREAT;
 
   if (!CreateOrOpen(name, posix_flags, size))
     return false;
--- a/ipc/chromium/src/base/shared_memory_win.cc
+++ b/ipc/chromium/src/base/shared_memory_win.cc
@@ -1,19 +1,17 @@
 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 #include "base/shared_memory.h"
 
 #include "base/logging.h"
 #include "base/win_util.h"
-#ifdef CHROMIUM_MOZILLA_BUILD
-#  include "base/string_util.h"
-#endif
+#include "base/string_util.h"
 
 namespace base {
 
 SharedMemory::SharedMemory()
     : mapped_file_(NULL),
       memory_(NULL),
       read_only_(false),
       max_size_(0),
@@ -53,28 +51,20 @@ bool SharedMemory::IsHandleValid(const S
   return handle != NULL;
 }
 
 // static
 SharedMemoryHandle SharedMemory::NULLHandle() {
   return NULL;
 }
 
-#ifdef CHROMIUM_MOZILLA_BUILD
 bool SharedMemory::Create(const std::string &cname, bool read_only,
-#else
-bool SharedMemory::Create(const std::wstring &name, bool read_only,
-#endif
                           bool open_existing, size_t size) {
   DCHECK(mapped_file_ == NULL);
-
-#ifdef CHROMIUM_MOZILLA_BUILD
   std::wstring name = UTF8ToWide(cname);
-#endif
-
   name_ = name;
   read_only_ = read_only;
   mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
       read_only_ ? PAGE_READONLY : PAGE_READWRITE, 0, static_cast<DWORD>(size),
       name.empty() ? NULL : name.c_str());
   if (!mapped_file_)
     return false;
 
--- a/ipc/chromium/src/base/stats_table.cc
+++ b/ipc/chromium/src/base/stats_table.cc
@@ -165,22 +165,17 @@ class StatsTablePrivate {
 };
 
 // static
 StatsTablePrivate* StatsTablePrivate::New(const std::string& name,
                                           int size,
                                           int max_threads,
                                           int max_counters) {
   scoped_ptr<StatsTablePrivate> priv(new StatsTablePrivate());
-#ifdef CHROMIUM_MOZILLA_BUILD
-  if (!priv->shared_memory_.Create(name, false, true,
-#else
-  if (!priv->shared_memory_.Create(base::SysUTF8ToWide(name), false, true,
-#endif
-                                   size))
+  if (!priv->shared_memory_.Create(name, false, true, size))
     return NULL;
   if (!priv->shared_memory_.Map(size))
     return NULL;
   void* memory = priv->shared_memory_.memory();
 
   TableHeader* header = static_cast<TableHeader*>(memory);
 
   // If the version does not match, then assume the table needs
--- a/ipc/chromium/src/base/string16.cc
+++ b/ipc/chromium/src/base/string16.cc
@@ -64,15 +64,9 @@ char16* c16memset(char16* s, char16 c, s
   }
   return s_orig;
 }
 
 }  // namespace base
 
 template class std::basic_string<char16, base::string16_char_traits>;
 
-#ifndef CHROMIUM_MOZILLA_BUILD
-std::ostream& operator<<(std::ostream& out, const string16& str) {
-  return out << UTF16ToUTF8(str);
-}
-#endif
-
 #endif  // WCHAR_T_IS_UTF32
--- a/ipc/chromium/src/base/string_util.cc
+++ b/ipc/chromium/src/base/string_util.cc
@@ -18,19 +18,16 @@
 #include <wctype.h>
 
 #include <algorithm>
 #include <vector>
 
 #include "base/basictypes.h"
 #include "base/logging.h"
 #include "base/singleton.h"
-#ifndef CHROMIUM_MOZILLA_BUILD
-#include "base/third_party/dmg_fp/dmg_fp.h"
-#endif
 
 namespace {
 
 // Force the singleton used by Empty[W]String[16] to be a unique type. This
 // prevents other code that might accidentally use Singleton<string> from
 // getting our internal one.
 struct EmptyStrings {
   EmptyStrings() {}
@@ -244,57 +241,16 @@ class HexString16ToLongTraits {
     return ret;
 #endif
   }
   static inline bool valid_func(const string_type& str) {
     return !str.empty() && !iswspace(str[0]);
   }
 };
 
-#ifndef CHROMIUM_MOZILLA_BUILD
-class StringToDoubleTraits {
- public:
-  typedef std::string string_type;
-  typedef double value_type;
-  static inline value_type convert_func(const string_type::value_type* str,
-                                        string_type::value_type** endptr) {
-    return dmg_fp::strtod(str, endptr);
-  }
-  static inline bool valid_func(const string_type& str) {
-    return !str.empty() && !isspace(str[0]);
-  }
-};
-
-class String16ToDoubleTraits {
- public:
-  typedef string16 string_type;
-  typedef double value_type;
-  static inline value_type convert_func(const string_type::value_type* str,
-                                        string_type::value_type** endptr) {
-    // Because dmg_fp::strtod does not like char16, we convert it to ASCII.
-    // In theory, this should be safe, but it's possible that 16-bit chars
-    // might get ignored by accident causing something to be parsed when it
-    // shouldn't.
-    std::string ascii_string = UTF16ToASCII(string16(str));
-    char* ascii_end = NULL;
-    value_type ret = dmg_fp::strtod(ascii_string.c_str(), &ascii_end);
-    if (ascii_string.c_str() + ascii_string.length() == ascii_end) {
-      // Put endptr at end of input string, so it's not recognized as an error.
-      *endptr =
-          const_cast<string_type::value_type*>(str) + ascii_string.length();
-    }
-
-    return ret;
-  }
-  static inline bool valid_func(const string_type& str) {
-    return !str.empty() && !iswspace(str[0]);
-  }
-};
-#endif
-
 }  // namespace
 
 
 namespace base {
 
 bool IsWprintfFormatPortable(const wchar_t* format) {
   for (const wchar_t* position = format; *position != '\0'; ++position) {
 
@@ -330,35 +286,31 @@ bool IsWprintfFormatPortable(const wchar
   }
 
   return true;
 }
 
 
 }  // namespace base
 
-#ifdef CHROMIUM_MOZILLA_BUILD
 namespace base {
-#endif
 
 const std::string& EmptyString() {
   return Singleton<EmptyStrings>::get()->s;
 }
 
 const std::wstring& EmptyWString() {
   return Singleton<EmptyStrings>::get()->ws;
 }
 
 const string16& EmptyString16() {
   return Singleton<EmptyStrings>::get()->s16;
 }
 
-#ifdef CHROMIUM_MOZILLA_BUILD
 }
-#endif
 
 const wchar_t kWhitespaceWide[] = {
   0x0009,  // <control-0009> to <control-000D>
   0x000A,
   0x000B,
   0x000C,
   0x000D,
   0x0020,  // Space
@@ -760,21 +712,17 @@ bool StartsWith(const std::wstring& str,
                 const std::wstring& search,
                 bool case_sensitive) {
   if (case_sensitive)
     return str.compare(0, search.length(), search) == 0;
   else {
     if (search.size() > str.size())
       return false;
     return std::equal(search.begin(), search.end(), str.begin(),
-#if defined(CHROMIUM_MOZILLA_BUILD)
                       chromium_CaseInsensitiveCompare<wchar_t>());
-#else
-                      CaseInsensitiveCompare<wchar_t>());
-#endif
   }
 }
 
 DataUnits GetByteDisplayUnits(int64 bytes) {
   // The byte thresholds at which we display amounts.  A byte count is displayed
   // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
   // This must match the DataUnits enum.
   static const int64 kUnitThresholds[] = {
@@ -939,21 +887,17 @@ static void StringAppendVT(StringType* d
                            const typename StringType::value_type* format,
                            va_list ap) {
   // First try with a small fixed size buffer.
   // This buffer size should be kept in sync with StringUtilTest.GrowBoundary
   // and StringUtilTest.StringPrintfBounds.
   typename StringType::value_type stack_buf[1024];
 
   va_list backup_ap;
-#if !defined(CHROMIUM_MOZILLA_BUILD)
-  base::va_copy(backup_ap, ap);
-#else
   base_va_copy(backup_ap, ap);
-#endif	// !defined(CHROMIUM_MOZILLA_BUILD)
 
 #if !defined(OS_WIN)
   errno = 0;
 #endif
   int result = vsnprintfT(stack_buf, arraysize(stack_buf), format, backup_ap);
   va_end(backup_ap);
 
   if (result >= 0 && result < static_cast<int>(arraysize(stack_buf))) {
@@ -990,21 +934,17 @@ static void StringAppendVT(StringType* d
       // return -1 for reasons other than overflow without setting errno.
       DLOG(WARNING) << "Unable to printf the requested string due to size.";
       return;
     }
 
     std::vector<typename StringType::value_type> mem_buf(mem_length);
 
     // Restore the va_list before we use it again.
-#if !defined(CHROMIUM_MOZILLA_BUILD)
-    base::va_copy(backup_ap, ap);
-#else
     base_va_copy(backup_ap, ap);
-#endif	// !defined(CHROMIUM_MOZILLA_BUILD)
 
     result = vsnprintfT(&mem_buf[0], mem_length, format, ap);
     va_end(backup_ap);
 
     if ((result >= 0) && (result < mem_length)) {
       // It fit.
       dst->append(&mem_buf[0], result);