Merge from m-c in an attempt to resolve mochitest startup crash in libnecko.
authorAndreas Gal <gal@mozilla.com>
Sun, 14 Dec 2008 19:34:36 -0800
changeset 23066 0a2df946ea6e729dc6abc138c873bfcbbb23345d
parent 23063 a5c631abee1f4056232044e9b4365c9ab870ea04 (current diff)
parent 22786 3611062ed0988d1eaa82b102b0302d037582f92f (diff)
child 23067 7a24f8922f4b3064a07eaffe7ba43d7f4a0f6b7c
push id4346
push userrsayre@mozilla.com
push dateFri, 26 Dec 2008 01:26:36 +0000
treeherdermozilla-central@8eb5a5b83a93 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone1.9.2a1pre
Merge from m-c in an attempt to resolve mochitest startup crash in libnecko.
config/bin2rc.c
config/bin2rc.exe
config/build_header.pl
config/clobber_miss.pl
config/common.mk
config/nodl.pl
config/nsBuildID.h.in
config/pkg2dpth.pl
config/revdepth-nt.pl
config/revdepth.pl
config/true.bat
config/zipcfunc.pl
config/zipchrome.pl
js/src/config/revdepth-nt.pl
js/src/config/revdepth.pl
js/src/jsinterp.cpp
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -547,20 +547,16 @@ pref("browser.preferences.instantApply",
 pref("browser.preferences.animateFadeIn", true);
 #else
 pref("browser.preferences.animateFadeIn", false);
 #endif
 
 pref("browser.download.show_plugins_in_list", true);
 pref("browser.download.hide_plugins_without_extensions", true);
 
-// Setting this pref to |true| forces BiDi UI menu items and keyboard shortcuts
-// to be exposed. By default, only expose it for bidi-associated system locales.
-pref("bidi.browser.ui", false);
-
 // Backspace and Shift+Backspace behavior
 // 0 goes Back/Forward
 // 1 act like PgUp/PgDown
 // 2 and other values, nothing
 #ifdef UNIX_BUT_NOT_MAC
 pref("browser.backspace_action", 2);
 #else
 pref("browser.backspace_action", 0);
--- a/browser/base/content/utilityOverlay.js
+++ b/browser/base/content/utilityOverlay.js
@@ -347,37 +347,42 @@ function getShellService()
   try {
     shell = Components.classes["@mozilla.org/browser/shell-service;1"]
       .getService(Components.interfaces.nsIShellService);
   } catch (e) {dump("*** e = " + e + "\n");}
   return shell;
 }
 
 function isBidiEnabled() {
+  // first check the pref.
+  if (getBoolPref("browser.bidi.ui", false))
+    return true;
+
+  // if the pref isn't set, check for an RTL locale and force the pref to true
+  // if we find one.
   var rv = false;
 
   try {
     var localeService = Components.classes["@mozilla.org/intl/nslocaleservice;1"]
                                   .getService(Components.interfaces.nsILocaleService);
     var systemLocale = localeService.getSystemLocale().getCategory("NSILOCALE_CTYPE").substr(0,3);
 
     switch (systemLocale) {
       case "ar-":
       case "he-":
       case "fa-":
       case "ur-":
       case "syr":
         rv = true;
+        var pref = Components.classes["@mozilla.org/preferences-service;1"]
+                             .getService(Components.interfaces.nsIPrefBranch);
+        pref.setBoolPref("bidi.browser.ui", true);
     }
   } catch (e) {}
 
-  // check the overriding pref
-  if (!rv)
-    rv = getBoolPref("bidi.browser.ui");
-
   return rv;
 }
 
 function openAboutDialog()
 {
 #ifdef XP_MACOSX
   var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                      .getService(Components.interfaces.nsIWindowMediator);
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -292,41 +292,48 @@ PlacesController.prototype = {
    * removable item.
    * @param aIsMoveCommand
    *        True if the command for which this method is called only moves the
    *        selected items to another container, false otherwise.
    * @returns true if all nodes in the selection can be removed,
    *          false otherwise.
    */
   _hasRemovableSelection: function PC__hasRemovableSelection(aIsMoveCommand) {
-    var nodes = this._view.getSelectionNodes();
+    var ranges = this._view.getRemovableSelectionRanges();
+    if (!ranges.length)
+      return false;
+
     var root = this._view.getResultNode();
 
-    for (var i = 0; i < nodes.length; ++i) {
-      // Disallow removing the view's root node
-      if (nodes[i] == root)
-        return false;
+    for (var j = 0; j < ranges.length; j++) {
+      var nodes = ranges[j];
+      for (var i = 0; i < nodes.length; ++i) {
+        // Disallow removing the view's root node
+        if (nodes[i] == root)
+          return false;
 
-      if (PlacesUtils.nodeIsFolder(nodes[i]) &&
-          !PlacesControllerDragHelper.canMoveNode(nodes[i]))
-        return false;
+        if (PlacesUtils.nodeIsFolder(nodes[i]) &&
+            !PlacesControllerDragHelper.canMoveNode(nodes[i]))
+          return false;
 
-      // We don't call nodeIsReadOnly here, because nodeIsReadOnly means that
-      // a node has children that cannot be edited, reordered or removed. Here,
-      // we don't care if a node's children can't be reordered or edited, just
-      // that they're removable. All history results have removable children
-      // (based on the principle that any URL in the history table should be
-      // removable), but some special bookmark folders may have non-removable
-      // children, e.g. live bookmark folder children. It doesn't make sense
-      // to delete a child of a live bookmark folder, since when the folder
-      // refreshes, the child will return.
-      var parent = nodes[i].parent || root;
-      if (PlacesUtils.isReadonlyFolder(parent))
-        return false;
+        // We don't call nodeIsReadOnly here, because nodeIsReadOnly means that
+        // a node has children that cannot be edited, reordered or removed. Here,
+        // we don't care if a node's children can't be reordered or edited, just
+        // that they're removable. All history results have removable children
+        // (based on the principle that any URL in the history table should be
+        // removable), but some special bookmark folders may have non-removable
+        // children, e.g. live bookmark folder children. It doesn't make sense
+        // to delete a child of a live bookmark folder, since when the folder
+        // refreshes, the child will return.
+        var parent = nodes[i].parent || root;
+        if (PlacesUtils.isReadonlyFolder(parent))
+          return false;
+      }
     }
+
     return true;
   },
 
   /**
    * Determines whether or not nodes can be inserted relative to the selection.
    */
   _canInsert: function PC__canInsert() {
     var ip = this._view.insertionPoint;
--- a/browser/components/places/content/menu.xml
+++ b/browser/components/places/content/menu.xml
@@ -924,16 +924,23 @@
           var selectedNode = this.selectedNode;
           return selectedNode ? [selectedNode] : [];
         ]]></body>
       </method>
 
       <!-- nsIPlacesView -->
       <method name="getRemovableSelectionRanges">
         <body><![CDATA[
+          // On static content the current selectedNode would be the selection's
+          // parent node. We don't want to allow removing a node when the
+          // selection is not explicit.
+          if (document.popupNode &&
+              (document.popupNode == "menupopup" || !document.popupNode.node))
+            return [];
+
           return [this.getSelectionNodes()];
         ]]></body>
       </method>
 
       <!-- nsIPlacesView -->
       <method name="getDragableSelection">
         <body><![CDATA[
           return [this._draggedNode];
@@ -1009,29 +1016,22 @@
 
       <property name="selType" readonly="true" onget="return 'single';"/>
 
       <method name="buildContextMenu">
         <parameter name="aPopup"/>
         <body><![CDATA[
           this._ensureInitialized();
           this._contextMenuShown = true;
+          // Activate the controller
           this.focus();
-          // The above call to focus activates the controller, but it may not
-          // always fire a consumable event for commandUpdater, so we force a
-          // command update.
+          // The above call may not always fire a consumable event for
+          // commandUpdater, so we force a command update.
           window.updateCommands("focus");
-          var show = this.controller.buildContextMenu(aPopup);
-          if (show) {
-            // disable the Delete command if the selection isn't explicit
-            if (document.popupNode && document.popupNode.localName == "menupopup")
-              document.getElementById("cmd_delete").setAttribute("disabled", "true");
-            return true;
-          }
-          return false;
+          return this.controller.buildContextMenu(aPopup);
         ]]></body>
       </method>
 
       <method name="destroyContextMenu">
         <parameter name="aPopup"/>
         <body>
           <![CDATA[
             this._contextMenuShown = false;
--- a/browser/components/places/content/toolbar.xml
+++ b/browser/components/places/content/toolbar.xml
@@ -360,16 +360,23 @@
           var selectedNode = this.selectedNode;
           return selectedNode ? [selectedNode] : [];
         ]]></body>
       </method>
 
       <!-- nsIPlacesView -->
       <method name="getRemovableSelectionRanges">
         <body><![CDATA[
+          // On static content the current selectedNode would be the selection's
+          // parent node. We don't want to allow removing a node when the
+          // selection is not explicit.
+          if (document.popupNode &&
+              (document.popupNode == "menupopup" || !document.popupNode.node))
+            return [];
+
           return [this.getSelectionNodes()];
         ]]></body>
       </method>
 
       <!-- nsIPlacesView -->
       <method name="getDragableSelection">
         <body><![CDATA[
           return [this._draggedNode];
@@ -703,29 +710,22 @@
       })]]></field>
 
       <property name="selType" onget="return 'single';"/>
 
       <method name="buildContextMenu">
         <parameter name="aPopup"/>
         <body><![CDATA[
           this._contextMenuShown = true;
+          // Activate the controller
           this.focus();
-          // The above call to focus activates the controller, but it may not
-          // always fire a consumable event for commandUpdater, so we force a
-          // command update.
+          // The above call may not always fire a consumable event for
+          // commandUpdater, so we force a command update.
           window.updateCommands("focus");
-          var show = this.controller.buildContextMenu(aPopup);
-          if (show) {
-            // disable the Delete command if the selection isn't explicit
-            if (document.popupNode && document.popupNode.localName == "menupopup")
-              document.getElementById("cmd_delete").setAttribute("disabled", "true");
-            return true;
-          }
-          return false;
+          return this.controller.buildContextMenu(aPopup);
         ]]></body>
       </method>
 
       <method name="destroyContextMenu">
         <parameter name="aPopup"/>
         <body><![CDATA[
           this._contextMenuShown = false;
           if (window.content)
--- a/browser/components/places/tests/unit/test_placesTxn.js
+++ b/browser/components/places/tests/unit/test_placesTxn.js
@@ -666,9 +666,11 @@ function run_test() {
   do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_1Id), newBkmk3Id);
   do_check_eq(bmsvc.getItemType(newBkmk3_1Id), bmsvc.TYPE_BOOKMARK);
   do_check_eq(bmsvc.getBookmarkURI(newBkmk3_1Id).spec, "http://www.mozilla.org/");
   do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_2Id), newBkmk3Id);
   do_check_eq(bmsvc.getItemType(newBkmk3_2Id), bmsvc.TYPE_SEPARATOR);
   do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_3Id), newBkmk3Id);
   do_check_eq(bmsvc.getItemType(newBkmk3_3Id), bmsvc.TYPE_FOLDER);
   do_check_eq(bmsvc.getItemTitle(newBkmk3_3Id), "folder");
+
+  bmsvc.removeObserver(observer, false);
 }
--- a/config/Makefile.in
+++ b/config/Makefile.in
@@ -50,17 +50,17 @@ VISIBILITY_FLAGS =
 
 ifneq (,$(CROSS_COMPILE)$(filter-out WINNT OS2,$(OS_ARCH)))
 ifneq ($(OS_ARCH), WINCE)
 HOST_PROGRAM	= nsinstall$(HOST_BIN_SUFFIX)
 HOST_CSRCS	= nsinstall.c pathsub.c
 endif
 endif
 
-PLSRCS		= nfspwd.pl revdepth.pl
+PLSRCS		= nfspwd.pl
 
 TARGETS		= $(HOST_PROGRAM) $(PLSRCS:.pl=) $(SIMPLE_PROGRAMS)
 
 ifndef CROSS_COMPILE
 ifdef USE_ELF_DYNSTR_GC
 TARGETS		+= elf-dynstr-gc
 # Compiling the above will create dependency files.
 NEED_MDDEPDIR	= 1
deleted file mode 100644
--- a/config/bin2rc.c
+++ /dev/null
@@ -1,133 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-#include <stdio.h>
-#include <sys\stat.h>
-
-int main(int iArgc, char **ppArgv) {
-    int iRetval = 1;
-    
-    /*  First argument, the filename to convert.
-     *  Output to stdout, redirect to save.
-     */
-    char *pFileName = ppArgv[1];
-    if(pFileName) {
-        FILE *pFile = fopen(pFileName, "rb");
-        if(pFile) {
-            struct stat sInfo;
-            
-            /*  Stat the file for size.
-             */
-            if(!fstat(fileno(pFile), &sInfo)) {
-                int iChar;
-                int iX = 0;
-                int iFirsttime = 1;
-                
-                /*  Begin RCDATA
-                 */
-                printf("BEGIN\n");
-
-                /*  First string identifies created via bin2rc.
-                 *  Users of the RCDATA must check for this to
-                 *      assume the format of the remainder of
-                 *      the data.
-                 */
-                printf("\t\"bin2rc generated resource\\0\",\t// bin2rc identity string\n");
-
-                /*  Next string is optional parameter on command
-                 *      line.  If not present, an empty string.
-                 *  Users of the RCDATA must understand this is
-                 *      the optional string that can be used for
-                 *      about any purpose they desire.
-                 */
-                printf("\t\"%s\\0\",\t// optional command line string\n", ppArgv[2] ? ppArgv[2] : "");
-                
-                /*  Next string is the size of the original file.
-                 *  Users of the RCDATA must understand that this
-                 *      is the size of the file's actual contents.
-                 */
-                printf("\t\"%ld\\0\"\t// data size header\n", sInfo.st_size);
-                
-                while(EOF != (iChar = fgetc(pFile))) {
-                    /*  Comma?
-                     */
-                    if(0 == iFirsttime) {
-                        iX += printf(",");
-                    }
-                    else {
-                        iFirsttime = 0;
-                    }
-                    
-                    /*  Newline?
-                     */
-                    if(iX >= 72) {
-                        printf("\n");
-                        iX = 0;
-                    }
-                    
-                    /*  Tab?
-                     */
-                    if(0 == iX) {
-                        printf("\t");
-                        iX += 8;
-                    }
-                    
-                    /*  Octal byte.
-                     */
-                    iX += printf("\"\\%.3o\"", iChar);
-                    
-                    
-                }
-                
-                /*  End RCDATA
-                 */
-                if(0 != iX) {
-                    printf("\n");
-                }
-                printf("END\n");
-                
-                /*  All is well.
-                 */
-                iRetval = 0;
-            }
-            fclose(pFile);
-            pFile = NULL;
-        }
-    }
-    
-    return(iRetval);
-}
-
deleted file mode 100755
index 52508a588984317c0a5b6d315b8ba3d39e33f755..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
--- a/config/build_header.pl
+++ /dev/null
@@ -1,12 +0,0 @@
-open INFILE, "<$ARGV[1]";
-$build = <INFILE>;
-close INFILE;
-chop $build;
-open OUTFILE, ">$ARGV[0]" || die;
-
-print OUTFILE "/* THIS IS A GENERATED FILE!\n*\n";
-print OUTFILE "* See mozilla/config/build_header.pl */\n*\n*/";
-print OUTFILE "\n\#define NS_BUILD_ID " . $build . "\n";
-
-close OUTFILE;
-
deleted file mode 100755
--- a/config/clobber_miss.pl
+++ /dev/null
@@ -1,142 +0,0 @@
-#!perl5
-#
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of the GNU General Public License Version 2 or later (the "GPL"),
-# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-#
-# Searches the tree for unclobbered files
-#   should be relatively cross platform
-#
-
-$start_dir = $ENV{"MOZ_SRC"};
-@ignore_list = ("make.dep","manifest.mnw");
-
-$missed = 0;
-
-print "\n\nChecking for unclobbered files\n" .
-          "------------------------------\n";
-
-GoDir("ns");
-GoDir("mozilla");
-
-if( $missed ){
-    die "\nError: $missed files or directories unclobbered\n";
-}
-else {
-    print "No unclobbered files found\n";
-}
-
-sub GoDir {
-    local($dir) = @_;
-    local(%filelist,$iscvsdir);
-    local($k,$v,$d,$fn,$rev, $mod_time);
-    local($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
-                        $atime,$mtime,$ctime,$blksize,$blocks);
-
-    if(! chdir "$start_dir/$dir" ){
-        return;
-    }
-
-    while(<*.*> ){
-        if( $_ ne '.' && $_ ne '..' && $_ ne 'CVS'
-                && $_ ne 'nuke' ){
-            $filelist{$_} = 1;
-        }
-    }
-
-    if( -r "CVS/Entries" ){
-        $iscvsdir=1;
-        open(ENT, "CVS/Entries" ) || 
-                die "Cannot open CVS/Entries for reading\n";
-        while(<ENT>){
-            chop;
-            ($d,$fn,$rev,$mod_time) = split(/\//);
-
-            if( $fn ne "" ){
-                if( $d eq "D" ){
-                    $filelist{$fn} = 3;
-                }
-                else {
-                    $filelist{$fn} = 2;
-                }
-            }                                    
-        }
-        close(ENT);
-    }
-
-    while( ($k,$v) = each %filelist ){
-        if( $v == 1 && $iscvsdir && !IgnoreFile( $k ) ){
-            if( ! -d $k ){
-                print "     file: $dir/$k\n";
-                $missed++;
-            }
-            else {
-                if( ! -r "$k/CVS/Entries" ){
-                    print "directory: $dir/$k\n";
-                    $missed++;
-                }
-                else {
-                    $filelist{$k} = 3;
-                }
-
-            }
-        }
-    }
-
-    while( ($k,$v) = each %filelist ){
-        if( $v == 3 ){
-            GoDir("$dir/$k");
-        }
-    }
-
-#    while( ($k,$v) = each %filelist ){
-#        print "$k: $v\n";
-#    }
-
-}
-
-sub IgnoreFile {
-    local($fn) = @_;
-    local($i);
-
-    for $i (@ignore_list){
-        if( $fn eq $i ){
-            return 1;
-        }
-    }
-    return 0;
-}
-
deleted file mode 100644
--- a/config/common.mk
+++ /dev/null
@@ -1,157 +0,0 @@
-#
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of the GNU General Public License Version 2 or later (the "GPL"),
-# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-INCLUDED_COMMON_MK = 1
-
-######################################################################
-# Cross-platform defines used on all platforms (in theory)
-######################################################################
-
-#
-# The VERSION_NUMBER is suffixed onto the end of the DLLs we ship.
-# Since the longest of these is 5 characters without the suffix,
-# be sure to not set VERSION_NUMBER to anything longer than 3 
-# characters for Win16's sake.
-#
-# Also... If you change this value, there are several other places
-# you'll need to change (because they're not reached by this 
-# variable): 
-#	sun-java/nsjava/nsjava32.def
-#	sun-java/nsjava/nsjava16.def
-#	sun-java/classsrc/sun/audio/AudioDevice.java
-#	sun-java/classsrc/sun/awt/windows/WToolkit.java
-#
-VERSION_NUMBER		= 50
-
-# jar for core java classes:
-JAR_NAME		= java$(VERSION_NUMBER).jar
-
-# jar for navigator-specific java code:
-NAV_JAR_NAME		= nav$(VERSION_NUMBER).jar
-
-######################################################################
-# Cross-Platform Java Stuff
-######################################################################
-# java interpreter
-
-# get class files from the directory they are compiled to
-JAVA_CLASSPATH		= $(JAVAC_ZIP)$(PATH_SEPARATOR)$(JAVA_DESTPATH)
-
-JAVA_FLAGS		= -classpath $(JAVA_CLASSPATH) -ms8m
-JAVA			= $(JAVA_PROG) $(JAVA_FLAGS) 
-
-#
-# NOTE: If a new DLL is being added to this define you will have to update
-#       ns/sun-java/include/javadefs.h in order not to break win16.
-#
-JAVA_DEFINES		= -DJAR_NAME=\"$(JAR_NAME)\" -DJRTDLL=\"$(JRTDLL)\" -DMMDLL=\"$(MMDLL)\" \
-			  -DAWTDLL=\"$(AWTDLL)\" -DJITDLL=\"$(JITDLL)\" -DJPWDLL=\"$(JPWDLL)\"
-
-######################################################################
-# javac
-
-#
-# java wants '-ms8m' and kaffe wants '-ms 8m', so this needs to be
-# overridable.
-#
-JINT_FLAGS		= -ms8m
-
-# to run the compiler in the interpreter
-JAVAC_PROG		= $(JINT_FLAGS) $(PDJAVA_FLAGS) -classpath $(JAVAC_ZIP) sun.tools.javac.Main
-JAVAC			= $(JAVA_PROG) $(JAVAC_PROG) $(JAVAC_FLAGS)
-
-# std set of options passed to the compiler
-JAVAC_FLAGS		= -classpath $(JAVAC_CLASSPATH) $(JAVAC_OPTIMIZER) -d $(JAVA_DESTPATH)
-
-#
-# The canonical Java classpath is:
-# JAVA_DESTPATH, JAVA_SOURCEPATH, JAVA_LIBS
-# 
-# appropriately delimited, in that order
-#
-JAVAC_CLASSPATH		= $(JAVAC_ZIP)$(PATH_SEPARATOR)$(JAVA_DESTPATH)$(PATH_SEPARATOR)$(JAVA_SOURCEPATH)
-
-######################################################################
-# javadoc
-
-# Rules to build java .html files from java source files
-
-JAVADOC_PROG		= $(JAVA) sun.tools.javadoc.Main
-JAVADOC_FLAGS		= -classpath $(JAVAC_CLASSPATH)
-JAVADOC			= $(JAVADOC_PROG) $(JAVADOC_FLAGS)
-
-######################################################################
-# javah
-
-JAVAH_FLAGS		= -classpath $(JAVAC_ZIP)$(PATH_SEPARATOR)$(JAVA_DESTPATH)
-JAVAH			= $(JAVAH_PROG) $(JAVAH_FLAGS)
-
-######################################################################
-# jmc
-
-JMCSRCDIR		= $(DIST)/_jmc
-JMC_PROG		= $(JAVA) netscape.tools.jmc.Main
-JMC_CLASSPATH		= $(JMCSRCDIR)$(PATH_SEPARATOR)$(JAVAC_CLASSPATH)
-JMC_FLAGS		= -classpath $(JMC_CLASSPATH) -verbose
-JMC			= $(JMC_PROG) $(JMC_FLAGS)
-
-######################################################################
-# zip
-
-ZIP			= $(ZIP_PROG) $(ZIP_FLAGS)
-
-######################################################################
-# idl2java
-
-ORBTOOLS		= $(DEPTH)/modules/iiop/tools/orbtools.zip
-ORB_CLASSPATH		= $(ORBTOOLS)$(PATH_SEPARATOR)$(JAVA_CLASSPATH)
-
-IDL2JAVA_PROG		= $(JAVA_PROG)
-IDL2JAVA_FLAGS		= -classpath $(ORB_CLASSPATH) pomoco.tools.idl2java
-IDL2JAVA		= $(IDL2JAVA_PROG) $(IDL2JAVA_FLAGS)
-
-######################################################################
-# lex and yacc
-
-JAVALEX_PROG		= $(JAVA_PROG) -classpath $(ORB_CLASSPATH) sbktech.tools.jax.driver
-JAVALEX_FLAGS		=
-JAVALEX			= $(JAVALEX_PROG) $(JAVALEX_FLAGS)
-
-JAVACUP_PROG		= $(JAVA_PROG) -classpath $(ORB_CLASSPATH) java_cup.Main
-JAVACUP_FLAGS		=
-JAVACUP			= $(JAVACUP_PROG) $(JAVACUP_FLAGS)
-
deleted file mode 100644
--- a/config/nodl.pl
+++ /dev/null
@@ -1,62 +0,0 @@
-#! perl
-#
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of the GNU General Public License Version 2 or later (the "GPL"),
-# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-# 
-# Print out the nodltab.
-# Usage: nodl.pl table-name sym1 sym2 ... symN
-# 
-
-$table = $ARGV[0];
-shift(@ARGV);
-
-print "/* Automatically generated file; do not edit */\n\n";
-
-print "#include \"prtypes.h\"\n\n";
-print "#include \"prlink.h\"\n\n";
-
-foreach $symbol (@ARGV) {
-    print "extern void ",$symbol,"();\n";
-}
-print "\n";
-
-print "PRStaticLinkTable ",$table,"[] = {\n";
-foreach $symbol (@ARGV) {
-    print "  { \"",$symbol,"\", ",$symbol," },\n";
-}
-print "  { 0, 0, },\n";
-print "};\n";
deleted file mode 100644
--- a/config/nsBuildID.h.in
+++ /dev/null
@@ -1,23 +0,0 @@
-#ifndef _NSBUILDID_H_
-#define _NSBUILDID_H_
-/* Build ID file.
-*
-* If building MOZILLLA_OFFICIAL (release build) NS_BUILD_ID will be updated
-* to a current build id. This will be used to determine if we need to 
-* re-register components.
-*
-*/
-#define NS_BUILD_ID 0000000000
-
-/* GRE_BUILD_ID - GRE build version identifier
- *
- * If creating a release build (eg, MOZILLA_OFFICIAL is set), then 
- * GRE_BUILD_ID will be updated to contain <milestone>_<build id>.  
- * If building a milestone build (eg, MOZ_MILESTONE_RELEASE is set), then 
- * GRE_BUILD_ID will just contain <milestone>. 
- *
- */
-#define GRE_BUILD_ID "00000000000"
-
-#endif /* _NSBUILDID_H_ */
-
deleted file mode 100755
--- a/config/pkg2dpth.pl
+++ /dev/null
@@ -1,47 +0,0 @@
-#!perl
-#
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of the GNU General Public License Version 2 or later (the "GPL"),
-# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-#
-# Transform package paths to depths:
-#	foo/bar ==> ../..
-#
-
-# Why don't we need .. here?
-$ARGV[0] =~ s@[^/\\]+@..@g;
-
-print $ARGV[0]
deleted file mode 100644
--- a/config/revdepth-nt.pl
+++ /dev/null
@@ -1,48 +0,0 @@
-#! perl
-#
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of the GNU General Public License Version 2 or later (the "GPL"),
-# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-require "/ns/config/fastcwd.pl";
-
-$cur = &fastcwd;
-chdir($ARGV[0]);
-$newcur = &fastcwd;
-$newcurlen = length($newcur);
-
-# Skip common separating / unless $newcur is "/"
-$cur = substr($cur, $newcurlen + ($newcurlen > 1));
-print $cur;
deleted file mode 100644
--- a/config/revdepth.pl
+++ /dev/null
@@ -1,51 +0,0 @@
-#! perl
-#
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of the GNU General Public License Version 2 or later (the "GPL"),
-# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-unshift(@INC, '/usr/lib/perl');
-unshift(@INC, '/usr/local/lib/perl');
-
-require "fastcwd.pl";
-
-$cur = &fastcwd;
-chdir($ARGV[0]);
-$newcur = &fastcwd;
-$newcurlen = length($newcur);
-
-# Skip common separating / unless $newcur is "/"
-$cur = substr($cur, $newcurlen + ($newcurlen > 1));
-print $cur;
deleted file mode 100644
--- a/config/true.bat
+++ /dev/null
@@ -1,40 +0,0 @@
-@echo off
-rem ***** BEGIN LICENSE BLOCK *****
-rem Version: MPL 1.1/GPL 2.0/LGPL 2.1
-rem
-rem The contents of this file are subject to the Mozilla Public License Version
-rem 1.1 (the "License"); you may not use this file except in compliance with
-rem the License. You may obtain a copy of the License at
-rem http://www.mozilla.org/MPL/
-rem
-rem Software distributed under the License is distributed on an "AS IS" basis,
-rem WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-rem for the specific language governing rights and limitations under the
-rem License.
-rem
-rem The Original Code is mozilla.org code.
-rem
-rem The Initial Developer of the Original Code is
-rem Netscape Communications Corporation.
-rem Portions created by the Initial Developer are Copyright (C) 1998
-rem the Initial Developer. All Rights Reserved.
-rem
-rem Contributor(s):
-rem
-rem Alternatively, the contents of this file may be used under the terms of
-rem either the GNU General Public License Version 2 or later (the "GPL"), or
-rem the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-rem in which case the provisions of the GPL or the LGPL are applicable instead
-rem of those above. If you wish to allow use of your version of this file only
-rem under the terms of either the GPL or the LGPL, and not to allow others to
-rem use your version of this file under the terms of the MPL, indicate your
-rem decision by deleting the provisions above and replace them with the notice
-rem and other provisions required by the GPL or the LGPL. If you do not delete
-rem the provisions above, a recipient may use your version of this file under
-rem the terms of any one of the MPL, the GPL or the LGPL.
-rem
-rem ***** END LICENSE BLOCK ***** */
-
-@echo on
-
-@echo off
deleted file mode 100644
--- a/config/zipcfunc.pl
+++ /dev/null
@@ -1,223 +0,0 @@
-#!perl
-# 
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is Mozilla Communicator client code, released
-# March 31, 1998.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998-1999
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Sean Su <ssu@netscape.com>
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of the GNU General Public License Version 2 or later (the "GPL"),
-# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-use Cwd;
-return(1);
-
-sub ZipChrome()
-{
-  # inOsType     - Os type
-  # inUpdate     - update or noupdate
-  #                update   - enables time/date compare file update of chrome archives
-  #                noupdate - disables time/date compare file update of chrome archives.
-  #                           it will always update chrome files regardless of time/date stamp.
-  # inSourcePath - path to where the tmpchrome dir
-  # inTargetPath - path to where the bin\chrome dir
-  ($inOsType, $inUpdate, $inSourcePath, $inTargetPath) = @_;
-
-  # check Os type
-  if($inOsType =~ /win32/i)
-  {
-    $gPathDelimiter="\\";
-  }
-  elsif($inOsType =~ /mac/i)
-  {
-    $gPathDelimiter=":";
-  }
-  elsif($inOsType =~ /unix/i)
-  {
-    $gPathDelimiter="/";
-  }
-  else
-  {
-    return(2);
-  }
-
-  # Verify Update
-  if(!($inUpdate =~ /update/i) &&
-     !($inUpdate =~ /noupdate/i))
-  {
-    return(2);
-  }
-
-  if($inOsType =~ /win32/i)
-  {
-    # Convert all '/' to '\\' or else win32 will have problems
-    $inSourcePath =~ s/\//\\/g;
-    $inTargetPath =~ s/\//\\/g;
-  }
-
-  # Make sure $inSourcePath exists
-  if(!(-e "$inSourcePath"))
-  {
-    return(1);
-  }
-
-  # Make sure $inTargetPath exists
-  if(!(-e "$inTargetPath"))
-  {
-    mkdir("$inTargetPath", 0775);
-  }
-
-  # Call CreateArchive() on locales, packages, and skins
-#  CreateArchive("loc", $inSourcePath . $gPathDelimiter . "locales",  "$inTargetPath");
-#  CreateArchive("pkg", $inSourcePath . $gPathDelimiter . "packages", "$inTargetPath");
-#  CreateArchive("skn", $inSourcePath . $gPathDelimiter . "skins",    "$inTargetPath");
-  CreateArchive("jar", $inSourcePath . $gPathDelimiter, "$inTargetPath");
-  return(0);
-}
-
-sub CreateArchive()
-{
-  my($inExtension, $inSrc, $inDest) = @_;
-  my($dir);
-  my(@dirList);
-  my(@dirItem);
-  my($dirName);
-  my($saveCwdir);
-  my($mZipParam);
-
-  # Make sure $inSrc exists
-  if(!(-e "$inSrc"))
-  {
-    return(0);
-  }
-
-  # Make sure $inSrc is a directory
-  if(!(-d "$inSrc"))
-  {
-    return(0);
-  }
-
-  # Make sure $inDest exists
-  if(!(-e "$inDest"))
-  {
-    mkdir("$inDest", 0775);
-  }
-
-  # Check for extension, if none is passed, use .jar as default
-  if($inExtension eq "")
-  {
-    $inExtension = "jar";
-  }
-
-  # Save current working directory
-  $saveCwdir = cwd();
-  chdir($inSrc);
-
-  # For all the subdirectories within $inSrc, create an archive
-  # using the name of the subdirectory, but with the extension passed
-  # in as a parameter.
-  @dirList = <*>;
-  foreach $dir (@dirList)
-  {
-    if($inOsType =~ /win32/i)
-    {
-      # Convert all '/' to '\\' or else win32 will have problems
-      $dir =~ s/\//\\/g;
-    }
-
-    # Get the leaf dir name of full path
-    # Get the leaf dir name from full path
-    if($inOsType =~ /win32/i)
-    {
-      @dirItem = split(/\\/, $dir);
-    }
-    elsif($inOsType =~ /mac/i)
-    {
-      @dirItem = split(/:/, $dir);
-    }
-    elsif($inOsType =~ /unix/i)
-    {
-      @dirItem = split(/\//, $dir);
-    }
-    $dirName = $dirItem[$#dirItem];
-
-    if(-d "$dir")
-    {
-      # Zip only works for win32 and unix systems
-      if(($inOsType =~ /win32/i) || ($inOsType =~ /unix/i))
-      {
-        if($inUpdate =~ /noupdate/i)
-        {
-          print "\n";
-          if(-e "$dirName.$inExtension")
-          {
-            # Delete archive is one already exists in target location
-            print " Removing $dirName.$inExtension\n";
-            unlink "$dirName.$inExtension";
-          }
-
-          print " Creating $dirName.$inExtension\n";
-          $mZipParam = "";
-        }
-        elsif($inUpdate =~ /update/i)
-        {
-          if(!(-e "$dirName.$inExtension"))
-          {
-            print "\n";
-            print " Creating $dirName.$inExtension\n";
-            $mZipParam = "";
-          }
-          else
-          {
-            print " Updating $dirName.$inExtension\n";
-            $mZipParam = "-u";
-          }
-        }
-
-        # Create the archive in $inDest
-        chdir("$dirName");
-        if(system("zip $mZipParam -r ..$gPathDelimiter$dirName.$inExtension *") != 0)
-        {
-          print "Error: zip $mZipParam -r ..$gPathDelimiter$dirName.$inExtension *\n";
-          chdir("..");
-          return(1);
-        }
-        chdir("..");
-      }
-    }
-  }
-
-  # Restore to the current working dir
-  chdir($saveCwdir);
-  return(0);
-}
-
deleted file mode 100644
--- a/config/zipchrome.pl
+++ /dev/null
@@ -1,88 +0,0 @@
-#!perl
-# 
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is Mozilla Communicator client code, released
-# March 31, 1998.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998-1999
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Sean Su <ssu@netscape.com>
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of the GNU General Public License Version 2 or later (the "GPL"),
-# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-# Make sure there are at least four arguments
-if(($#ARGV < 2) ||
-  ((!($ARGV[0] =~ /^win32$/i)) &&
-   (!($ARGV[0] =~ /^mac$/i)) &&
-   (!($ARGV[0] =~ /^unix$/i))) ||
-  ((!($ARGV[1] =~ /^update$/i)) &&
-   (!($ARGV[1] =~ /^noupdate$/i))))
-{
-  PrintUsage();
-  exit(1);
-}
-
-require "$ENV{MOZ_SRC}/mozilla/config/zipcfunc.pl";
-
-if($#ARGV == 2)
-{
-  if(&ZipChrome($ARGV[0], $ARGV[1], $ARGV[2], $ARGV[2]) != 0)
-  {
-    die "\n Error: ZipChrome($ARGV[0], $ARGV[1], $ARGV[2], $ARGV[2])\n";
-  }
-}
-else
-{
-  if(&ZipChrome($ARGV[0], $ARGV[1], $ARGV[2], $ARGV[3]) != 0)
-  {
-    die "\n Error: ZipChrome($ARGV[0], $ARGV[1], $ARGV[2], $ARGV[3])\n";
-  }
-}
-exit(0);
-
-sub PrintUsage()
-{
-  print "usage: $0 <os> <update> <source path> [target path]
-
-       os                : win32, mac, unix
-
-       update            : update    - enables time/date compare file update of chrome archives
-                           noupdate  - disables time/date compare file update of chrome archives.
-                                       it will always update chrome files regardless of time/date stamp.
-
-       source path       : path to where the chrome dir is at
-
-       target path       : (optional) path to where the chrome jar files should be copied to
-
-              ie: $0 update $ENV{MOZ_SRC}\\mozilla\\dist\\win32_d.obj\\tmpchrome $ENV{MOZ_SRC}\\mozilla\\dist\\win32_d.obj\\bin\\chrome
-       \n";
-}
-
--- a/configure.in
+++ b/configure.in
@@ -975,17 +975,17 @@ MOZ_ZLIB_CFLAGS=
 MOZ_ZLIB_LIBS='$(call EXPAND_LIBNAME_PATH,mozz,$(DEPTH)/modules/zlib/src)'
 MOZ_BZ2_CFLAGS=
 MOZ_BZ2_LIBS='$(call EXPAND_LIBNAME_PATH,bz2,$(DEPTH)/modules/libbz2/src)'
 MOZ_PNG_CFLAGS=
 MOZ_PNG_LIBS='$(call EXPAND_LIBNAME_PATH,mozpng,$(DEPTH)/modules/libimg/png)'
 
 MOZ_JS_LIBS='-L$(LIBXUL_DIST)/bin -lmozjs'
 DYNAMIC_XPCOM_LIBS='-L$(LIBXUL_DIST)/bin -lxpcom -lxpcom_core'
-MOZ_FIX_LINK_PATHS='-Wl,-rpath-link,$(LIBXUL_DIST)/bin -Wl,-rpath-link,$(PREFIX)/lib'
+MOZ_FIX_LINK_PATHS='-Wl,-rpath-link,$(LIBXUL_DIST)/bin -Wl,-rpath-link,$(prefix)/lib'
 XPCOM_FROZEN_LDOPTS='-L$(LIBXUL_DIST)/bin -lxpcom'
 LIBXUL_LIBS='$(XPCOM_FROZEN_LDOPTS) -lxul'
 XPCOM_GLUE_LDOPTS='$(LIBXUL_DIST)/lib/$(LIB_PREFIX)xpcomglue_s.$(LIB_SUFFIX) $(XPCOM_FROZEN_LDOPTS)'
 XPCOM_STANDALONE_GLUE_LDOPTS='$(LIBXUL_DIST)/lib/$(LIB_PREFIX)xpcomglue.$(LIB_SUFFIX)'
 
 MOZ_COMPONENT_NSPR_LIBS='-L$(LIBXUL_DIST)/bin $(NSPR_LIBS)'
 MOZ_XPCOM_OBSOLETE_LIBS='-L$(LIBXUL_DIST)/lib -lxpcom_compat'
 
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -859,28 +859,30 @@ nsFrameLoader::EnsureDocShell()
   // mDocShell->SetChromeEventHandler() for the global window to get
   // the right chrome event handler.
 
   // Tell the window about the frame that hosts it.
   nsCOMPtr<nsIDOMElement> frame_element(do_QueryInterface(mOwnerContent));
   NS_ASSERTION(frame_element, "frame loader owner element not a DOM element!");
 
   nsCOMPtr<nsPIDOMWindow> win_private(do_GetInterface(mDocShell));
-  NS_ENSURE_TRUE(win_private, NS_ERROR_UNEXPECTED);
-
-  win_private->SetFrameElementInternal(frame_element);
-
   nsCOMPtr<nsIBaseWindow> base_win(do_QueryInterface(mDocShell));
-  NS_ENSURE_TRUE(base_win, NS_ERROR_UNEXPECTED);
+  if (win_private) {
+    win_private->SetFrameElementInternal(frame_element);
+  }
 
   // This is kinda whacky, this call doesn't really create anything,
   // but it must be called to make sure things are properly
-  // initialized
-
-  base_win->Create();
+  // initialized...
+  if (NS_FAILED(base_win->Create()) || !win_private) {
+    // ...but if we couldn't create the shell properly, better
+    // to make sure it gets removed.
+    Destroy();
+    return NS_ERROR_FAILURE;
+  }
 
   return NS_OK;
 }
 
 void
 nsFrameLoader::GetURL(nsString& aURI)
 {
   aURI.Truncate();
--- a/content/base/src/nsRange.cpp
+++ b/content/base/src/nsRange.cpp
@@ -1300,33 +1300,33 @@ nsresult nsRange::CutContents(nsIDOMDocu
         }
         else
         {
           // Delete or extract everything after startOffset.
 
           rv = charData->GetLength(&dataLength);
           NS_ENSURE_SUCCESS(rv, rv);
 
-          if (dataLength > (PRUint32)startOffset)
+          if (dataLength >= (PRUint32)startOffset)
           {
             nsCOMPtr<nsIDOMCharacterData> cutNode;
             rv = SplitDataNode(charData, startOffset, dataLength,
                                getter_AddRefs(cutNode), nsnull);
             NS_ENSURE_SUCCESS(rv, rv);
             nodeToResult = cutNode;
           }
 
           handled = PR_TRUE;
         }
       }
       else if (node == endContainer)
       {
         // Delete or extract everything before endOffset.
 
-        if (endOffset > 0)
+        if (endOffset >= 0)
         {
           nsCOMPtr<nsIDOMCharacterData> cutNode;
           /* The Range spec clearly states clones get cut and original nodes
              remain behind, so use PR_FALSE as the last parameter.
           */
           rv = SplitDataNode(charData, endOffset, endOffset,
                              getter_AddRefs(cutNode), nsnull, PR_FALSE);
           NS_ENSURE_SUCCESS(rv, rv);
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -181,16 +181,17 @@ include $(topsrcdir)/config/rules.mk
 		file_htmlserializer_1_noformatpre.html \
 		file_htmlserializer_1_raw.html \
 		file_htmlserializer_1_nested_body.html \
 		file_htmlserializer_1_sibling_body.html \
 		file_htmlserializer_1_sibling_body_only_body.html \
 		file_htmlserializer_1_no_body.html \
 		test_bug424359-2.html \
 		file_htmlserializer_2.html \
+		test_bug431082.html \
 		file_htmlserializer_2_basic.html \
 		file_htmlserializer_2_enthtml.html \
 		file_htmlserializer_2_entw3c.html \
 		file_htmlserializer_2_latin1.html \
 		test_bug424212.html \
 		test_bug425013.html \
 		bug426308-redirect.sjs \
 		test_bug426308.html \
@@ -258,16 +259,17 @@ include $(topsrcdir)/config/rules.mk
 		bug461735-post-redirect.js \
 		test_bug461735.html \
 		test_bug380418.html \
 		test_bug465767.html \
 		test_bug380418.html^headers^ \
 		test_elementTraversal.html \
 		test_w3element_traversal.html \
 		test_w3element_traversal.xhtml \
+		test_bug469020.html \
 		test_w3element_traversal_svg.html \
 		w3element_traversal.svg \
 		test_bug444322.html \
 		bug444322.txt \
 		bug444322.js \
 		$(NULL)
 
 # Disabled for now. Mochitest isn't reliable enough for these.
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug431082.html
@@ -0,0 +1,52 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=431082
+-->
+<head>
+  <title>Test for Bug 431082</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=431082">Mozilla Bug 431082</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+
+/** Test for Bug 431082 **/
+
+SimpleTest.waitForExplicitFinish();
+addLoadEvent(function() { ok(true, "browser should not crash."); });
+addLoadEvent(SimpleTest.finish);
+
+</script>
+</pre>
+<!--
+<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+<box  id="a" observes="b">
+  <box id="b"/>
+</box>
+
+<box  id="a"  src="javascript:"/>
+<box id="b" src="javascript://"/>
+<editor observes="a"/>
+
+<script> 
+function doe() {
+window.addEventListener('DOMAttrModified', function()
+{window.frameElement.parentNode.removeChild(window.frameElement);}, true);
+document.documentElement.appendChild(document.getElementsByTagName('box')[0]);
+}
+setTimeout(doe,0);
+</script>
+</window>
+-->
+<iframe src="data:application/vnd.mozilla.xul+xml;charset=utf-8,%3Cwindow%20xmlns%3D%22http%3A//www.mozilla.org/keymaster/gatekeeper/there.is.only.xul%22%3E%0A%3Cbox%20%20id%3D%22a%22%20observes%3D%22b%22%3E%0A%20%20%3Cbox%20id%3D%22b%22/%3E%0A%3C/box%3E%0A%0A%3Cbox%20%20id%3D%22a%22%20%20src%3D%22javascript%3A%22/%3E%0A%3Cbox%20id%3D%22b%22%20src%3D%22javascript%3A//%22/%3E%0A%3Ceditor%20observes%3D%22a%22/%3E%0A%0A%3Cscript%3E%20%0Afunction%20doe%28%29%20%7B%0Awindow.addEventListener%28%27DOMAttrModified%27%2C%20function%28%29%20%7Bwindow.frameElement.parentNode.removeChild%28window.frameElement%29%3B%7D%2C%20true%29%3B%0Adocument.documentElement.appendChild%28document.getElementsByTagName%28%27box%27%29%5B0%5D%29%3B%0A%7D%0AsetTimeout%28doe%2C0%29%3B%0A%3C/script%3E%0A%3C/window%3E" style="width:1000px;height: 300px;"></iframe>
+</body>
+</html>
+
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug469020.html
@@ -0,0 +1,129 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=469020
+-->
+<head>
+  <title>Test for Bug 469020</title>
+  <script type="application/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=469020">Mozilla Bug 469020</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 469020 **/
+
+  var range = null;
+  var anchor = null;
+
+  function doRangeAnchor(elem, start, end) {
+    range = document.createRange();
+    range.setStart(elem.firstChild, start);
+    end = end < elem.lastChild.length ? end : elem.lastChild.length
+    range.setEnd(elem.lastChild, end);
+    anchor = document.createElement('a');
+    anchor.href = "javascript: void(0);";
+    range.surroundContents(anchor);
+  }
+
+  function undoRangeAnchor() {
+    var pnode = anchor.parentNode;
+    var range2 = document.createRange();
+    range2.selectNodeContents(anchor);
+    var contents = range2.extractContents();
+    pnode.replaceChild(contents,anchor);
+  }
+
+function serializeNode(node) {
+  var s;
+  var isElem = false;
+  if (node.nodeName == "#text") {
+    if (node.nodeValue) {
+      s = node.nodeValue
+    } else {
+      s = "<#empty>"
+    }
+  } else {
+    isElem = true;
+    s = "<" + node.nodeName + ">";
+  }
+  for (var j = 0; j < node.childNodes.length; ++j) {
+    s += serializeNode(node.childNodes[j]);
+  }
+  if (isElem) {
+    s += "</" + node.nodeName + ">";
+  }
+  return s;
+}
+
+function runTest(elementID, start, end, expected1, expected2, expected3) {
+  var e = document.getElementById(elementID);
+  doRangeAnchor(e, start, end);
+  is(serializeNode(e), expected1, "Wrong range behavior!");
+  document.getElementById('log').textContent += serializeNode(e) + "\n";
+  undoRangeAnchor();
+  is(serializeNode(e), expected2, "Wrong range behavior!");
+  document.getElementById('log').textContent += serializeNode(e) + "\n";
+  doRangeAnchor(e, start, end);
+  is(serializeNode(e), expected3, "Wrong range behavior!");
+  document.getElementById('log').textContent += serializeNode(e) + "\n";
+}
+
+function runTests() {
+  runTest("test1", 0, 3,
+          "<P><#empty><A>http://www.<SPAN>mozilla.</SPAN>org</A><#empty></P>",
+          "<P><#empty>http://www.<SPAN>mozilla.</SPAN>org<#empty></P>",
+          "<P><#empty><A><#empty>http://www.<SPAN>mozilla.</SPAN>org<#empty></A><#empty></P>");
+
+  runTest("test2", 1, 3,
+          "<P>h<A>ttp://www.<SPAN>mozilla.</SPAN>org</A><#empty></P>",
+          "<P>http://www.<SPAN>mozilla.</SPAN>org<#empty></P>",
+          "<P>h<A><#empty>ttp://www.<SPAN>mozilla.</SPAN>org<#empty></A><#empty></P>");
+
+  runTest("test3", 0, 2,
+          "<P><#empty><A>http://www.<SPAN>mozilla.</SPAN>or</A>g</P>",
+          "<P><#empty>http://www.<SPAN>mozilla.</SPAN>org</P>",
+          "<P><#empty><A><#empty>http://www.<SPAN>mozilla.</SPAN>org</A><#empty></P>");
+
+  runTest("test4", 1, 2,
+          "<P>h<A>ttp://www.<SPAN>mozilla.</SPAN>or</A>g</P>",
+          "<P>http://www.<SPAN>mozilla.</SPAN>org</P>",
+          "<P>h<A><#empty>ttp://www.<SPAN>mozilla.</SPAN>org</A><#empty></P>");
+
+  runTest("test5", 11, 0,
+          "<P>http://www.<A><#empty><SPAN>mozilla.</SPAN><#empty></A>org</P>",
+          "<P>http://www.<#empty><SPAN>mozilla.</SPAN><#empty>org</P>",
+          "<P>http://www.<A><#empty><#empty><SPAN>mozilla.</SPAN><#empty><#empty></A>org</P>");
+
+  runTest("test6", 10, 1,
+          "<P>http://www<A>.<SPAN>mozilla.</SPAN>o</A>rg</P>",
+          "<P>http://www.<SPAN>mozilla.</SPAN>org</P>",
+          "<P>http://www<A><#empty>.<SPAN>mozilla.</SPAN>or</A>g</P>");
+
+  SimpleTest.finish();
+}
+
+SimpleTest.waitForExplicitFinish();
+addLoadEvent(runTests);
+
+
+
+</script>
+</pre>
+<p id="test1">http://www.<span>mozilla.</span>org</p>
+<p id="test2">http://www.<span>mozilla.</span>org</p>
+<p id="test3">http://www.<span>mozilla.</span>org</p>
+<p id="test4">http://www.<span>mozilla.</span>org</p>
+<p id="test5">http://www.<span>mozilla.</span>org</p>
+<p id="test6">http://www.<span>mozilla.</span>org</p>
+<pre id="log">
+</pre>
+</body>
+</html>
--- a/content/html/content/crashtests/453406-1.html
+++ b/content/html/content/crashtests/453406-1.html
@@ -16,21 +16,19 @@ function boom()
   var span = document.createElement("SPAN");
   f1.appendChild(i);
   f1.appendChild(br);
   s.appendChild(f1);
   b.appendChild(s);
   f2.appendChild(span);
   b.appendChild(f2)
   document.documentElement.appendChild(b);
-  dump('aaa');
   b.contentEditable = "true";
   document.execCommand("indent", false, null);
   b.contentEditable = "false";
-  dump('bbb');
   span.appendChild(i);
   i.parentNode.removeChild(i);
 }
 </script>
 </head>
 <body onload="boom();">
 </body>
 </html>
--- a/content/html/content/public/nsHTMLMediaElement.h
+++ b/content/html/content/public/nsHTMLMediaElement.h
@@ -209,19 +209,16 @@ protected:
   // Size of the media. Updated by the decoder on the main thread if
   // it changes. Defaults to a width and height of -1 if not set.
   nsIntSize mMediaSize;
 
   // If true then we have begun downloading the media content.
   // Set to false when completed, or not yet started.
   PRPackedBool mBegun;
 
-  // If truen then the video playback has completed.
-  PRPackedBool mEnded;
-
   // True when the decoder has loaded enough data to display the
   // first frame of the content.
   PRPackedBool mLoadedFirstFrame;
 
   // Indicates whether current playback is a result of user action
   // (ie. calling of the Play method), or automatic playback due to
   // the 'autoplay' attribute being set. A true value indicates the 
   // latter case.
--- a/content/html/content/src/nsHTMLMediaElement.cpp
+++ b/content/html/content/src/nsHTMLMediaElement.cpp
@@ -107,17 +107,17 @@ NS_IMETHODIMP nsHTMLMediaElement::GetErr
   NS_IF_ADDREF(*aError = mError);
 
   return NS_OK;
 }
 
 /* readonly attribute boolean ended; */
 NS_IMETHODIMP nsHTMLMediaElement::GetEnded(PRBool *aEnded)
 {
-  *aEnded = mEnded;
+  *aEnded = mDecoder ? mDecoder->IsEnded() : PR_FALSE;
 
   return NS_OK;
 }
 
 /* readonly attribute DOMString currentSrc; */
 NS_IMETHODIMP nsHTMLMediaElement::GetCurrentSrc(nsAString & aCurrentSrc)
 {
   nsCAutoString src;
@@ -186,17 +186,16 @@ nsresult nsHTMLMediaElement::LoadWithCha
   if (aChannel) {
     rv = InitializeDecoderForChannel(aChannel, aListener);
   } else {
     rv = PickMediaElement();
   }
   NS_ENSURE_SUCCESS(rv, rv);
 
   mBegun = PR_TRUE;
-  mEnded = PR_FALSE;
 
   DispatchAsyncProgressEvent(NS_LITERAL_STRING("loadstart"));
 
   return NS_OK;
 }
 
 /* readonly attribute unsigned short readyState; */
 NS_IMETHODIMP nsHTMLMediaElement::GetReadyState(PRUint16 *aReadyState)
@@ -338,17 +337,16 @@ NS_IMETHODIMP nsHTMLMediaElement::SetMut
 
 nsHTMLMediaElement::nsHTMLMediaElement(nsINodeInfo *aNodeInfo, PRBool aFromParser)
   : nsGenericHTMLElement(aNodeInfo),
     mNetworkState(nsIDOMHTMLMediaElement::EMPTY),
     mReadyState(nsIDOMHTMLMediaElement::DATA_UNAVAILABLE),
     mMutedVolume(0.0),
     mMediaSize(-1,-1),
     mBegun(PR_FALSE),
-    mEnded(PR_FALSE),
     mLoadedFirstFrame(PR_FALSE),
     mAutoplaying(PR_TRUE),
     mPaused(PR_TRUE),
     mMuted(PR_FALSE),
     mIsDoneAddingChildren(!aFromParser),
     mPlayingBeforeSeek(PR_FALSE)
 {
 }
@@ -369,18 +367,17 @@ nsHTMLMediaElement::Play(void)
 
   nsresult rv;
 
   if (mNetworkState == nsIDOMHTMLMediaElement::EMPTY) {
     rv = Load();
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  if (mEnded) {
-    mEnded = PR_FALSE;
+  if (mDecoder->IsEnded()) {
     SetCurrentTime(0);
   }
 
   // TODO: If the playback has ended, then the user agent must set 
   // currentLoop to zero and seek to the effective start.
   // TODO: The playback rate must be set to the default playback rate.
   rv = mDecoder->Play();
   NS_ENSURE_SUCCESS(rv, rv);
@@ -686,33 +683,30 @@ nsresult nsHTMLMediaElement::InitializeD
   return rv;
 }
 
 void nsHTMLMediaElement::MetadataLoaded()
 {
   mNetworkState = nsIDOMHTMLMediaElement::LOADED_METADATA;
   DispatchAsyncSimpleEvent(NS_LITERAL_STRING("durationchange"));
   DispatchAsyncSimpleEvent(NS_LITERAL_STRING("loadedmetadata"));
-  // TODO: Seek to the start time, as set in the start attribute.
-  mDecoder->Seek(0.0);
 }
 
 void nsHTMLMediaElement::FirstFrameLoaded()
 {
   mNetworkState = nsIDOMHTMLMediaElement::LOADED_FIRST_FRAME;
   ChangeReadyState(nsIDOMHTMLMediaElement::CAN_SHOW_CURRENT_FRAME);
   mLoadedFirstFrame = PR_TRUE;
   DispatchAsyncSimpleEvent(NS_LITERAL_STRING("loadedfirstframe"));
   DispatchAsyncSimpleEvent(NS_LITERAL_STRING("canshowcurrentframe"));
 }
 
 void nsHTMLMediaElement::ResourceLoaded()
 {
   mBegun = PR_FALSE;
-  mEnded = PR_FALSE;
   mNetworkState = nsIDOMHTMLMediaElement::LOADED;
   ChangeReadyState(nsIDOMHTMLMediaElement::CAN_PLAY_THROUGH);
 
   DispatchProgressEvent(NS_LITERAL_STRING("load"));
 }
 
 void nsHTMLMediaElement::NetworkError()
 {
@@ -720,18 +714,18 @@ void nsHTMLMediaElement::NetworkError()
   mBegun = PR_FALSE;
   DispatchProgressEvent(NS_LITERAL_STRING("error"));
   mNetworkState = nsIDOMHTMLMediaElement::EMPTY;
   DispatchSimpleEvent(NS_LITERAL_STRING("empty"));
 }
 
 void nsHTMLMediaElement::PlaybackEnded()
 {
+  NS_ASSERTION(mDecoder->IsEnded(), "Decoder fired ended, but not in ended state");
   mBegun = PR_FALSE;
-  mEnded = PR_TRUE;
   mPaused = PR_TRUE;
   DispatchSimpleEvent(NS_LITERAL_STRING("ended"));
 }
 
 void nsHTMLMediaElement::CanPlayThrough()
 {
   ChangeReadyState(nsIDOMHTMLMediaElement::CAN_PLAY_THROUGH);
 }
@@ -866,23 +860,25 @@ PRBool nsHTMLMediaElement::IsActivelyPla
   //   playback has not stopped due to errors, 
   //   and the element has not paused for user interaction
   return 
     !mPaused && 
     (mReadyState == nsIDOMHTMLMediaElement::CAN_PLAY || 
      mReadyState == nsIDOMHTMLMediaElement::CAN_PLAY_THROUGH) &&
     !IsPlaybackEnded();
 }
+
 PRBool nsHTMLMediaElement::IsPlaybackEnded() const
 {
   // TODO:
   //   the current playback position is equal to the effective end of the media resource, 
   //   and the currentLoop attribute is equal to playCount-1. 
   //   See bug 449157.
-  return mNetworkState >= nsIDOMHTMLMediaElement::LOADED_METADATA && mEnded;
+  return mNetworkState >= nsIDOMHTMLMediaElement::LOADED_METADATA &&
+    mDecoder ? mDecoder->IsEnded() : PR_FALSE;
 }
 
 nsIPrincipal*
 nsHTMLMediaElement::GetCurrentPrincipal()
 {
   if (!mDecoder)
     return nsnull;
 
--- a/content/media/video/public/nsMediaDecoder.h
+++ b/content/media/video/public/nsMediaDecoder.h
@@ -129,16 +129,20 @@ class nsMediaDecoder : public nsIObserve
 
   // Called if the media file encounters a network error.
   virtual void NetworkError() = 0;
 
   // Call from any thread safely. Return PR_TRUE if we are currently
   // seeking in the media resource.
   virtual PRBool IsSeeking() const = 0;
 
+  // Return PR_TRUE if the decoder has reached the end of playback.
+  // Call in the main thread only.
+  virtual PRBool IsEnded() const = 0;
+
   // Return the current number of bytes loaded from the video file.
   // This is used for progress events.
   virtual PRUint64 GetBytesLoaded() = 0;
 
   // Return the size of the video file in bytes. Return 0 if the
   // size is unknown or the stream is infinite.
   virtual PRInt64 GetTotalBytes() = 0;
 
--- a/content/media/video/public/nsOggDecoder.h
+++ b/content/media/video/public/nsOggDecoder.h
@@ -334,16 +334,20 @@ class nsOggDecoder : public nsMediaDecod
   // Called if the media file encounters a network error.
   // Call on the main thread only.
   virtual void NetworkError();
 
   // Call from any thread safely. Return PR_TRUE if we are currently
   // seeking in the media resource.
   virtual PRBool IsSeeking() const;
 
+  // Return PR_TRUE if the decoder has reached the end of playback.
+  // Call on the main thread only.
+  virtual PRBool IsEnded() const;
+
   // Get the size of the media file in bytes. Called on the main thread only.
   virtual void SetTotalBytes(PRInt64 aBytes);
 
   // Set a flag indicating whether seeking is supported
   virtual void SetSeekable(PRBool aSeekable);
 
   // Return PR_TRUE if seeking is supported.
   virtual PRBool GetSeekable();
--- a/content/media/video/public/nsWaveDecoder.h
+++ b/content/media/video/public/nsWaveDecoder.h
@@ -168,16 +168,19 @@ class nsWaveDecoder : public nsMediaDeco
   // Set the current time of the media to aTime.  This may cause mStream to
   // create a new channel to fetch data from the appropriate position in the
   // stream.
   virtual nsresult Seek(float aTime);
 
   // Report whether the decoder is currently seeking.
   virtual PRBool IsSeeking() const;
 
+  // Report whether the decoder has reached end of playback.
+  virtual PRBool IsEnded() const;
+
   // Start downloading the media at the specified URI.  The media's metadata
   // will be parsed and made available as the load progresses.
   virtual nsresult Load(nsIURI* aURI, nsIChannel* aChannel, nsIStreamListener** aStreamListener);
 
   // Called by mStream (and possibly the nsChannelToPipeListener used
   // internally by mStream) when the stream has completed loading.
   virtual void ResourceLoaded();
 
@@ -247,21 +250,29 @@ private:
   // State machine that runs on mPlaybackThread.  Methods on this object are
   // safe to call from any thread.
   nsCOMPtr<nsWaveStateMachine> mPlaybackStateMachine;
 
   // Threadsafe wrapper around channels that provides seeking based on the
   // underlying channel type.
   nsAutoPtr<nsMediaStream> mStream;
 
-  // Copy of the current time and duration when the state machine was
-  // disposed.  Used to respond to time and duration queries with sensible
-  // values after playback has ended.
+  // The media time of the last requested seek.  This has not been validated
+  // against the current media, so may be out of bounds.  Set when
+  // Seek(float) is called, and passed to the state machine when the
+  // SeekStarted event fires to tell it to update its time offset.  The
+  // state machine will validate the offset against the current media.
+  float mTimeOffset;
+
+  // Copy of the current time, duration, and ended state when the state
+  // machine was disposed.  Used to respond to time and duration queries
+  // with sensible values after the state machine is destroyed.
   float mEndedCurrentTime;
   float mEndedDuration;
+  PRPackedBool mEnded;
 
   // True if we have registered a shutdown observer.
   PRPackedBool mNotifyOnShutdown;
 
   // True if the media resource is seekable.
   PRPackedBool mSeekable;
 };
 
--- a/content/media/video/src/nsOggDecoder.cpp
+++ b/content/media/video/src/nsOggDecoder.cpp
@@ -1054,17 +1054,17 @@ nsresult nsOggDecodeStateMachine::Run()
         if (mState != DECODER_STATE_COMPLETED)
           continue;
 
         nsCOMPtr<nsIRunnable> event =
           NS_NEW_RUNNABLE_METHOD(nsOggDecoder, mDecoder, PlaybackEnded);
         NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL);
         do {
           mon.Wait();
-        } while (mState != DECODER_STATE_SHUTDOWN);
+        } while (mState == DECODER_STATE_COMPLETED);
       }
       break;
     }
   }
 
   return NS_OK;
 }
 
@@ -1282,20 +1282,16 @@ nsresult nsOggDecoder::Play()
 
 nsresult nsOggDecoder::Seek(float aTime)
 {
   nsAutoMonitor mon(mMonitor);
 
   if (aTime < 0.0)
     return NS_ERROR_FAILURE;
 
-  if (mPlayState == PLAY_STATE_LOADING && aTime == 0.0) {
-    return NS_OK;
-  }
-
   mRequestedSeekTime = aTime;
 
   // If we are already in the seeking state, then setting mRequestedSeekTime
   // above will result in the new seek occurring when the current seek
   // completes.
   if (mPlayState != PLAY_STATE_SEEKING) {
     mNextState = mPlayState;
     ChangeState(PLAY_STATE_SEEKING);
@@ -1485,22 +1481,27 @@ void nsOggDecoder::NetworkError()
 
   if (mElement)
     mElement->NetworkError();
   Stop();
 }
 
 PRBool nsOggDecoder::IsSeeking() const
 {
-  return mPlayState == PLAY_STATE_SEEKING;
+  return mPlayState == PLAY_STATE_SEEKING || mNextState == PLAY_STATE_SEEKING;
+}
+
+PRBool nsOggDecoder::IsEnded() const
+{
+  return mPlayState == PLAY_STATE_ENDED || mPlayState == PLAY_STATE_SHUTDOWN;
 }
 
 void nsOggDecoder::PlaybackEnded()
 {
-  if (mShuttingDown)
+  if (mShuttingDown || mPlayState == nsOggDecoder::PLAY_STATE_SEEKING)
     return;
 
   Stop();
   if (mElement)  {
     mElement->PlaybackEnded();
   }
 }
 
--- a/content/media/video/src/nsWaveDecoder.cpp
+++ b/content/media/video/src/nsWaveDecoder.cpp
@@ -140,22 +140,30 @@ public:
 
   // Returns the current playback position in the audio stream in seconds.
   // Threadsafe.
   float GetCurrentTime();
 
   // Returns true if the state machine is seeking.  Threadsafe.
   PRBool IsSeeking();
 
+  // Returns true if the state machine has reached the end of playback.  Threadsafe.
+  PRBool IsEnded();
+
   // Called by the decoder to indicate that the media stream has closed.
   void StreamEnded();
 
   // Main state machine loop.  Runs forever, until shutdown state is reached.
   NS_IMETHOD Run();
 
+  // Called by the decoder when the SeekStarted event runs.  This ensures
+  // the current time offset of the state machine is updated to the new seek
+  // position at the appropriate time.
+  void UpdateTimeOffset(float aTime);
+
 private:
   // Change the current state and wake the playback thread if it is waiting
   // on mMonitor.  Used by public member functions called from both threads,
   // so must hold mMonitor.  Threadsafe.
   void ChangeState(State aState);
 
   // Create and initialize audio stream using current audio parameters.
   void OpenAudioStream();
@@ -276,25 +284,28 @@ private:
   // loading to ensure a completed metadata load or seek returns to the most
   // recently requested state on completion.
   State mNextState;
 
   // Volume that the audio backend will be initialized with.
   float mInitialVolume;
 
   // Time position (in seconds) to offset current time from audio stream.
-  // Set by calling Seek(float) when seeking, and when the stream is closed
+  // Set when the seek started event runs and when the stream is closed
   // during shutdown.
   float mTimeOffset;
 
   // Set when StreamEnded has fired to indicate that we should not expect
   // any more data from mStream than what is already buffered (i.e. what
   // Available() reports).
   PRPackedBool mExpectMoreData;
 
+  // Time position (in seconds) to seek to.  Set by Seek(float).
+  float mSeekTime;
+
   // True once metadata has been parsed and validated. Users of mSampleRate,
   // mChannels, mSampleSize, mSampleFormat, mWaveLength, mWavePCMOffset must
   // check this flag before assuming the values are valid.
   PRPackedBool mMetadataValid;
 };
 
 nsWaveStateMachine::nsWaveStateMachine(nsWaveDecoder* aDecoder, nsMediaStream* aStream,
                                        PRUint32 aBufferWaitTime, float aInitialVolume)
@@ -311,16 +322,17 @@ nsWaveStateMachine::nsWaveStateMachine(n
     mWaveLength(0),
     mWavePCMOffset(0),
     mMonitor(nsnull),
     mState(STATE_LOADING_METADATA),
     mNextState(STATE_PAUSED),
     mInitialVolume(aInitialVolume),
     mTimeOffset(0.0),
     mExpectMoreData(PR_TRUE),
+    mSeekTime(0.0),
     mMetadataValid(PR_FALSE)
 {
   mMonitor = nsAutoMonitor::NewMonitor("nsWaveStateMachine");
 }
 
 nsWaveStateMachine::~nsWaveStateMachine()
 {
   nsAutoMonitor::DestroyMonitor(mMonitor);
@@ -373,30 +385,42 @@ nsWaveStateMachine::Pause()
     ChangeState(STATE_PAUSED);
   }
 }
 
 void
 nsWaveStateMachine::Seek(float aTime)
 {
   nsAutoMonitor monitor(mMonitor);
-  mNextState = mState;
-  mTimeOffset = NS_MIN(aTime, BytesToTime(mWaveLength));
-  if (mTimeOffset < 0.0) {
-    mTimeOffset = 0.0;
+  mSeekTime = aTime;
+  if (mSeekTime < 0.0) {
+    mSeekTime = 0.0;
   }
-  ChangeState(STATE_SEEKING);
+  if (mState == STATE_LOADING_METADATA) {
+    mNextState = STATE_SEEKING;
+  } else if (mState != STATE_SEEKING) {
+    mNextState = mState;
+    ChangeState(STATE_SEEKING);
+  }
 }
 
 float
 nsWaveStateMachine::GetDuration()
 {
   nsAutoMonitor monitor(mMonitor);
   if (mMetadataValid) {
-    return BytesToTime(mWaveLength);
+    PRUint32 length = mWaveLength;
+    PRInt64 contentLength = mDecoder->GetTotalBytes();
+    // If the decoder has a valid content length, and it's shorter than the
+    // expected length of the PCM data, calculate the playback duration from
+    // the content length rather than the expected PCM data length.
+    if (contentLength >= 0 && contentLength - mWavePCMOffset < length) {
+      length = contentLength - mWavePCMOffset;
+    }
+    return BytesToTime(length);
   }
   return std::numeric_limits<float>::quiet_NaN();
 }
 
 float
 nsWaveStateMachine::GetCurrentTime()
 {
   nsAutoMonitor monitor(mMonitor);
@@ -406,17 +430,24 @@ nsWaveStateMachine::GetCurrentTime()
   }
   return float(time + mTimeOffset);
 }
 
 PRBool
 nsWaveStateMachine::IsSeeking()
 {
   nsAutoMonitor monitor(mMonitor);
-  return mState == STATE_SEEKING;
+  return mState == STATE_SEEKING || mNextState == STATE_SEEKING;
+}
+
+PRBool
+nsWaveStateMachine::IsEnded()
+{
+  nsAutoMonitor monitor(mMonitor);
+  return mState == STATE_ENDED || mState == STATE_SHUTDOWN;
 }
 
 void
 nsWaveStateMachine::StreamEnded()
 {
   nsAutoMonitor monitor(mMonitor);
   mExpectMoreData = PR_FALSE;
 }
@@ -438,24 +469,28 @@ nsWaveStateMachine::Run()
         monitor.Enter();
 
         if (mState == STATE_LOADING_METADATA) {
           nsCOMPtr<nsIRunnable> event;
           State newState;
 
           if (loaded) {
             mMetadataValid = PR_TRUE;
-            event = NS_NEW_RUNNABLE_METHOD(nsWaveDecoder, mDecoder, MetadataLoaded);
+            if (mNextState != STATE_SEEKING) {
+              event = NS_NEW_RUNNABLE_METHOD(nsWaveDecoder, mDecoder, MetadataLoaded);
+            }
             newState = mNextState;
           } else {
             event = NS_NEW_RUNNABLE_METHOD(nsWaveDecoder, mDecoder, MediaErrorDecode);
             newState = STATE_ERROR;
           }
 
-          NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL);
+          if (event) {
+            NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL);
+          }
           ChangeState(newState);
         }
       }
       break;
 
     case STATE_BUFFERING:
       if ((PR_IntervalToMilliseconds(PR_IntervalNow() - mBufferingStart) < mBufferingWait) &&
           mStream->DownloadRate() >= 0 &&
@@ -557,28 +592,35 @@ nsWaveStateMachine::Run()
         monitor.Wait(PR_MillisecondsToInterval(PRUint32(nextWakeup)));
       }
       break;
 
     case STATE_SEEKING:
       {
         CloseAudioStream();
 
+        mSeekTime = NS_MIN(mSeekTime, GetDuration());
+        float seekTime = mSeekTime;
+
         monitor.Exit();
         nsCOMPtr<nsIRunnable> startEvent =
           NS_NEW_RUNNABLE_METHOD(nsWaveDecoder, mDecoder, SeekingStarted);
         NS_DispatchToMainThread(startEvent, NS_DISPATCH_SYNC);
         monitor.Enter();
 
         if (mState == STATE_SHUTDOWN) {
           break;
         }
 
-        PRInt64 position = RoundDownToSample(TimeToBytes(mTimeOffset)) + mWavePCMOffset;
-        NS_ABORT_IF_FALSE(position >= 0 && position <= mWaveLength + mWavePCMOffset, "Invalid seek position");
+        // Calculate relative offset within PCM data.
+        PRInt64 position = RoundDownToSample(TimeToBytes(seekTime));
+        NS_ABORT_IF_FALSE(position >= 0 && position <= mWaveLength, "Invalid seek position");
+
+        // Convert to absolute offset within stream.
+        position += mWavePCMOffset;
 
         monitor.Exit();
         nsresult rv = mStream->Seek(nsISeekableStream::NS_SEEK_SET, position);
         if (NS_FAILED(rv)) {
           NS_WARNING("Seek failed");
         }
         monitor.Enter();
 
@@ -587,18 +629,27 @@ nsWaveStateMachine::Run()
         }
 
         monitor.Exit();
         nsCOMPtr<nsIRunnable> stopEvent =
           NS_NEW_RUNNABLE_METHOD(nsWaveDecoder, mDecoder, SeekingStopped);
         NS_DispatchToMainThread(stopEvent, NS_DISPATCH_SYNC);
         monitor.Enter();
 
-        if (mState != STATE_SHUTDOWN) {
-          ChangeState(mNextState);
+        if (mState == STATE_SEEKING && mSeekTime == seekTime) {
+          // Special case: if a seek was requested during metadata load,
+          // mNextState will have been clobbered.  This can only happen when
+          // we're instantiating a decoder to service a seek request after
+          // playback has ended, so we know that the clobbered mNextState
+          // was PAUSED.
+          State nextState = mNextState;
+          if (nextState == STATE_SEEKING) {
+            nextState = STATE_PAUSED;
+          }
+          ChangeState(nextState);
         }
       }
       break;
 
     case STATE_PAUSED:
       if (mAudioStream) {
         mAudioStream->Pause();
       }
@@ -645,16 +696,26 @@ nsWaveStateMachine::Run()
       return NS_OK;
     }
   }
 
   return NS_OK;
 }
 
 void
+nsWaveStateMachine::UpdateTimeOffset(float aTime)
+{
+  nsAutoMonitor monitor(mMonitor);
+  mTimeOffset = NS_MIN(aTime, GetDuration());
+  if (mTimeOffset < 0.0) {
+    mTimeOffset = 0.0;
+  }
+}
+
+void
 nsWaveStateMachine::ChangeState(State aState)
 {
   nsAutoMonitor monitor(mMonitor);
   mState = aState;
   monitor.NotifyAll();
 }
 
 void
@@ -910,18 +971,20 @@ nsWaveStateMachine::FindDataOffset()
 }
 
 NS_IMPL_THREADSAFE_ISUPPORTS1(nsWaveDecoder, nsIObserver)
 
 nsWaveDecoder::nsWaveDecoder()
   : mBytesDownloaded(0),
     mInitialVolume(1.0),
     mStream(nsnull),
+    mTimeOffset(0.0),
     mEndedCurrentTime(0.0),
     mEndedDuration(std::numeric_limits<float>::quiet_NaN()),
+    mEnded(PR_FALSE),
     mNotifyOnShutdown(PR_FALSE),
     mSeekable(PR_TRUE)
 {
   MOZ_COUNT_CTOR(nsWaveDecoder);
 }
 
 nsWaveDecoder::~nsWaveDecoder()
 {
@@ -950,20 +1013,27 @@ nsWaveDecoder::GetCurrentTime()
     return mPlaybackStateMachine->GetCurrentTime();
   }
   return mEndedCurrentTime;
 }
 
 nsresult
 nsWaveDecoder::Seek(float aTime)
 {
+  mTimeOffset = aTime;
+
+  if (!mPlaybackStateMachine) {
+    Load(mURI, nsnull, nsnull);
+  }
+
   if (mPlaybackStateMachine) {
-    mPlaybackStateMachine->Seek(aTime);
+    mPlaybackStateMachine->Seek(mTimeOffset);
     return NS_OK;
   }
+
   return NS_ERROR_FAILURE;
 }
 
 nsresult
 nsWaveDecoder::PlaybackRateChanged()
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
@@ -1033,19 +1103,23 @@ nsWaveDecoder::Stop()
     mPlaybackStateMachine->Shutdown();
   }
 
   if (mStream) {
     mStream->Cancel();
   }
 
   if (mPlaybackThread) {
+    mPlaybackThread->Shutdown();
+  }
+
+  if (mPlaybackStateMachine) {
     mEndedCurrentTime = mPlaybackStateMachine->GetCurrentTime();
     mEndedDuration = mPlaybackStateMachine->GetDuration();
-    mPlaybackThread->Shutdown();
+    mEnded = mPlaybackStateMachine->IsEnded();
   }
 
   mPlaybackThread = nsnull;
   mPlaybackStateMachine = nsnull;
   mStream = nsnull;
 
   UnregisterShutdownObserver();
 }
@@ -1151,16 +1225,25 @@ PRBool
 nsWaveDecoder::IsSeeking() const
 {
   if (mPlaybackStateMachine) {
     return mPlaybackStateMachine->IsSeeking();
   }
   return PR_FALSE;
 }
 
+PRBool
+nsWaveDecoder::IsEnded() const
+{
+  if (mPlaybackStateMachine) {
+    return mPlaybackStateMachine->IsEnded();
+  }
+  return mEnded;
+}
+
 PRUint64
 nsWaveDecoder::GetBytesLoaded()
 {
   return mBytesDownloaded;
 }
 
 PRInt64
 nsWaveDecoder::GetTotalBytes()
@@ -1250,16 +1333,20 @@ nsWaveDecoder::BufferingStopped()
 
 void
 nsWaveDecoder::SeekingStarted()
 {
   if (mShuttingDown) {
     return;
   }
 
+  if (mPlaybackStateMachine) {
+    mPlaybackStateMachine->UpdateTimeOffset(mTimeOffset);
+  }
+
   if (mElement) {
     mElement->SeekStarted();
   }
 }
 
 void
 nsWaveDecoder::SeekingStopped()
 {
--- a/content/media/video/test/Makefile.in
+++ b/content/media/video/test/Makefile.in
@@ -66,20 +66,31 @@ include $(topsrcdir)/config/rules.mk
                 test_seek8.html \
                 test_standalone.html \
                 test_timeupdate1.html \
                 test_timeupdate2.html \
                 test_timeupdate3.html \
                 test_volume.html \
                 test_wav_8bit.html \
                 test_wav_ended1.html \
+                test_wav_seek3.html \
+                test_wav_seek4.html \
+                test_wav_seek5.html \
+                test_wav_seek6.html \
+                test_wav_seek7.html \
+                test_wav_seek8.html \
                 test_wav_seek_past_end.html \
                 test_wav_seek_then_play.html \
+                test_wav_trailing.html \
+                test_wav_trunc.html \
+                test_wav_trunc_seek.html \
                 320x240.ogg \
                 bug461281.ogg \
                 seek.ogg \
                 r11025_s16_c1.wav \
+                r11025_s16_c1_trailing.wav \
+                r11025_s16_c1_trunc.wav \
                 r11025_u8_c1.wav \
 #                test_bug448534.html \
                 $(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..af53beaf255b087ce953a5f1362fc35241c3504f
GIT binary patch
literal 22095
zc%1FXp$&vU07b!nR{?ZD&Qb+}O|S^in-Cn10w^7>3e058%bTZC%95<ZGVaIOHAy~?
owoiV~|E9@S&-(9N00000000000000000000000000K8+q0e|3;RR910
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..4a8f2c0e4f9dcf51eaf3bdb8f444d3f837efb1b2
GIT binary patch
literal 10000
zc%1FXu?<CF07lV|3D`iirg()v(JH7VqSG1RjgBo8C#Si&^HfS%lJ&QY$9Z*4lIqb8
aN&oyhP4?~D-p(HY0000000000zUc;QYrxL{
--- a/content/media/video/test/test_seek1.html
+++ b/content/media/video/test/test_seek1.html
@@ -17,19 +17,20 @@
 <script class="testbody" type="text/javascript">
 var startPassed = false;
 var endPassed = false;
 var seekFlagStart = false;
 var seekFlagEnd = false;
 var readonly = true;
 var completed = false;
 
-ok(!document.getElementById('v').seeking, "seeking should default to false");
+var v = document.getElementById('v');
+ok(!v.seeking, "seeking should default to false");
 try {
-  v1.seeking = 1;
+  v.seeking = 1;
   readonly = false;
 }
 catch(e) {
   readonly = true;
 }
 ok(readonly, "seeking should be readonly");
 
 function startTest() {
--- a/content/media/video/test/test_seek8.html
+++ b/content/media/video/test/test_seek8.html
@@ -40,17 +40,17 @@ function startTest() {
     v.currentTime = Math.random;
   } catch(e) {
     thrown3 = true;
   }
 
   completed = true;
   ok(thrown1, "Setting currentTime to invalid value of NaN");
   ok(thrown2, "Setting currentTime to invalid value of -1");
-  ok(thrown2, "Setting currentTime to invalid value of a function");
+  ok(thrown3, "Setting currentTime to invalid value of a function");
   SimpleTest.finish();
   return false;
 }
 
 SimpleTest.waitForExplicitFinish();
 </script>
 </pre>
 </body>
new file mode 100644
--- /dev/null
+++ b/content/media/video/test/test_wav_seek3.html
@@ -0,0 +1,68 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Wave Media test: seek test 3</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<audio id='v'
+       onloadedmetadata='return startTest();'
+       onended='return playbackEnded();'
+       onseeking='return seekStarted();'
+       onseeked='return seekEnded();'>
+  <source type='audio/x-wav' src='r11025_s16_c1.wav'>
+</audio>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+// Test seeking works if current time is set before audio is
+// playing.
+var startPassed = false;
+var endPassed = false;
+var completed = false;
+
+function startTest() {
+  if (completed)
+    return false;
+
+  var v = document.getElementById('v');
+  v.currentTime=0.5;
+  v.play();
+  return false;
+}
+
+function seekStarted() {
+  if (completed)
+    return false;
+
+  startPassed = true;
+  return false;
+}
+
+function seekEnded() {
+  if (completed)
+    return false;
+
+  var t = document.getElementById('v').currentTime;
+  ok(t >= 0.4 && t <= 0.6, "Video currentTime should be around 0.5: " + t);
+  endPassed = true;
+  return false;
+}
+
+function playbackEnded() {
+  if (completed)
+    return false
+
+  completed = true;
+  ok(startPassed, "send seeking event");
+  ok(endPassed, "send seeked event");
+  SimpleTest.finish();
+  return false;
+}
+
+SimpleTest.waitForExplicitFinish();
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/media/video/test/test_wav_seek4.html
@@ -0,0 +1,54 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Wave Media test: seek test 4</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<audio id='v'
+       onloadedmetadata='return startTest();'
+       onseeking='return seekStarted();'
+       onseeked='return seekEnded();'>
+  <source type='audio/x-wav' src='r11025_s16_c1.wav'>
+</audio>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+// Test seeking works if current time is set but audio is not played.
+var startPassed = false;
+var completed = false;
+
+function startTest() {
+  if (completed)
+    return false;
+
+  var v = document.getElementById('v');
+  v.currentTime=0.5;
+  return false;
+}
+
+function seekStarted() {
+  if (completed)
+    return false;
+
+  startPassed = true;
+  return false;
+}
+
+function seekEnded() {
+  if (completed)
+    return false;
+
+  var t = document.getElementById('v').currentTime;
+  ok(t >= 0.4 && t<= 0.6, "Video currentTime should be around 0.5: " + t);
+  completed = true;
+  SimpleTest.finish();
+  return false;
+}
+
+SimpleTest.waitForExplicitFinish();
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/media/video/test/test_wav_seek5.html
@@ -0,0 +1,71 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Wave Media test: seek test 5</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<audio id='v'
+       onloadedmetadata='return startTest();'
+       onseeking='return seekStarted();'
+       onseeked='return seekEnded();'>
+  <source type='audio/x-wav' src='r11025_s16_c1.wav'>
+</audio>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+// Test for a seek, followed by another seek before the first is complete.
+var startPassed = false;
+var seek1Passed = false;
+var seek2Passed = false;
+var seekCount = 0;
+var completed = false;
+
+function startTest() {
+  if (completed)
+    return false;
+
+  var v = document.getElementById('v');
+  v.currentTime=0.8;
+  return false;
+}
+
+function seekStarted() {
+  if (completed)
+    return false;
+
+  startPassed = true;
+  var v = document.getElementById('v');
+  v.currentTime=0.5;
+  return false;
+}
+
+function seekEnded() {
+  if (completed)
+    return false;
+  var v = document.getElementById('v');
+  seekCount++;
+  if(seekCount == 1) {
+    if (v.currentTime >= 0.7 && v.currentTime <= 0.9)
+      seek1Passed = true;
+  }
+
+  if(seekCount == 2) {
+    if (v.currentTime >= 0.4 && v.currentTime <= 0.6)
+      seek2Passed = true;
+
+    ok(seek1Passed, "First seek");
+    ok(seek2Passed, "Second seek");
+    completed = true;
+    SimpleTest.finish();
+  }
+
+  return false;
+}
+
+SimpleTest.waitForExplicitFinish();
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/media/video/test/test_wav_seek6.html
@@ -0,0 +1,63 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Wave Media test: seek test 6</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<audio id='v'
+       onloadedmetadata='return startTest();'
+       onended='return playbackEnded();'
+       onseeking='return seekStarted();'
+       onseeked='return seekEnded();'>
+  <source type='audio/x-wav' src='r11025_s16_c1.wav'>
+</audio>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+// Test for a seek, followed by a play before the seek completes, ensure we play at the end of the seek.
+var startPassed = false;
+var completed = false;
+var seekCount = 0;
+
+function startTest() {
+  if (completed)
+    return false;
+
+  var v = document.getElementById('v');
+  v.currentTime=0.5;
+  return false;
+}
+
+function seekStarted() {
+  if (completed)
+    return false;
+  startPassed = true;
+  var v = document.getElementById('v');
+  v.play();
+  return false;
+}
+
+function seekEnded() {
+  if (completed)
+    return false;
+  var v = document.getElementById('v');
+  ok(v.currentTime>=0.4 && v.currentTime<=0.6, "First seek");
+  return false;
+}
+
+function playbackEnded() {
+  if (completed)
+    return false;
+  ok(true, "Playback ended");
+  completed = true;
+  SimpleTest.finish();
+  return false;
+}
+
+SimpleTest.waitForExplicitFinish();
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/media/video/test/test_wav_seek7.html
@@ -0,0 +1,60 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Wave Media test: seek test 7</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<audio id='v'
+       onloadedmetadata='return startTest();'
+       onseeked='return seekEnded();'>
+  <source type='audio/x-wav' src='r11025_s16_c1.wav'>
+</audio>
+<pre id="test">
+<script class="testbody" type="text/javascript;version=1.7">
+// Test for bug identified by Chris Pearce in comment 40 on
+// bug 449159.
+var v = document.getElementById('v');
+var seekCount = 0;
+var completed = false;
+var interval;
+
+function startTest() {
+  if (completed)
+    return false;
+
+  var seek = function () {
+    var i = 0;
+    for (;;) {
+      i += 0.1;
+      if (i > 1)
+        i = 0;
+      yield i;
+    }
+  }();
+
+  interval = setInterval(function() { v.currentTime=seek.next(); }, 10);
+  return false;
+}
+
+function seekEnded() {
+  if (completed)
+    return false;
+
+  seekCount++;
+  ok(true, "Seek " + seekCount);
+  if (seekCount == 3) {
+    clearInterval(interval);
+    completed = true;
+    SimpleTest.finish();
+  }
+  return false;
+}
+
+SimpleTest.waitForExplicitFinish();
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/media/video/test/test_wav_seek8.html
@@ -0,0 +1,58 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Wave Media test: seek test 8</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<audio id='v'
+       onloadedmetadata='return startTest();'>
+  <source type='audio/x-wav' src='r11025_s16_c1.wav'>
+</audio>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+// If a NaN is passed to currentTime, make sure this is caught
+// otherwise an infinite loop in the Wave backend occurs.
+var v = document.getElementById('v');
+var completed = false;
+var thrown1 = false;
+var thrown2 = false;
+var thrown3 = false;
+
+function startTest() {
+  if (completed)
+    return false;
+
+  try {
+    v.currentTime = NaN;
+  } catch(e) {
+    thrown1 = true;
+  }
+
+  try {
+    v.currentTime = -1;
+  } catch(e) {
+    thrown2 = true;
+  }
+
+  try {
+    v.currentTime = Math.random;
+  } catch(e) {
+    thrown3 = true;
+  }
+
+  completed = true;
+  ok(thrown1, "Setting currentTime to invalid value of NaN");
+  ok(thrown2, "Setting currentTime to invalid value of -1");
+  ok(thrown3, "Setting currentTime to invalid value of a function");
+  SimpleTest.finish();
+  return false;
+}
+
+SimpleTest.waitForExplicitFinish();
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/media/video/test/test_wav_trailing.html
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Wave Media test: playback ends when file has trailing non-PCM data</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<audio id='v'
+       onloadedmetadata='return startTest();'
+       onended='return playbackEnded();'>
+  <source type='audio/x-wav' src='r11025_s16_c1_trailing.wav'>
+</audio>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+// Test if the ended event works correctly.
+var v = document.getElementById('v');
+var endPassed = false;
+var completed = false;
+
+function startTest() {
+  if (completed)
+    return false;
+
+  v.play();
+  return false;
+}
+
+function playbackEnded() {
+  if (completed)
+    return false
+
+  completed = true;
+  ok(v.currentTime >= 0.9 && v.currentTime <= 1.1,
+     "Checking currentTime at end: " + v.currentTime);
+  ok(v.ended, "Checking playback has ended");
+  SimpleTest.finish();
+  return false;
+}
+
+SimpleTest.waitForExplicitFinish();
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/media/video/test/test_wav_trunc.html
@@ -0,0 +1,48 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Wave Media test: playback ends when file is truncated</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<audio id='v'
+       onloadedmetadata='return startTest();'
+       onended='return playbackEnded();'>
+  <source type='audio/x-wav' src='r11025_s16_c1_trunc.wav'>
+</audio>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+// Test if the ended event works correctly.
+var v = document.getElementById('v');
+var endPassed = false;
+var completed = false;
+
+function startTest() {
+  if (completed)
+    return false;
+
+  ok(v.duration > 0.3 && v.duration < 0.5, "Duration should be around 0.4: " + v.duration);
+
+  v.play();
+  return false;
+}
+
+function playbackEnded() {
+  if (completed)
+    return false
+
+  completed = true;
+  ok(v.currentTime >= 0.3 && v.currentTime <= 0.5,
+     "Checking currentTime at end: " + v.currentTime);
+  ok(v.ended, "Checking playback has ended");
+  SimpleTest.finish();
+  return false;
+}
+
+SimpleTest.waitForExplicitFinish();
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/media/video/test/test_wav_trunc_seek.html
@@ -0,0 +1,54 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Wave Media test: seeking in truncated file</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<audio id='v'
+       onloadedmetadata='return startTest();'
+       onseeked='return endSeek();'
+       onended='return endTest();'>
+  <source type='audio/x-wav' src='r11025_s16_c1_trunc.wav'>
+</audio>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+// Test if the ended event works correctly.
+var v = document.getElementById('v');
+var endPassed = false;
+var completed = false;
+
+function startTest() {
+  if (completed)
+    return false;
+
+  ok(v.duration > 0.3 && v.duration < 0.5, "Duration should be around 0.4: " + v.duration);
+
+  v.currentTime = 1.0;
+  return false;
+}
+
+function endTest() {
+  ok(v.ended, "Checking ended set after seeking to EOF and playing");
+  SimpleTest.finish();
+  return false;
+}
+
+function endSeek() {
+  if (completed)
+    return false
+
+  completed = true;
+  ok(v.currentTime >= 0.3 && v.currentTime <= 0.5,
+     "Checking currentTime at end: " + v.currentTime);
+  v.play();
+  return false;
+}
+
+SimpleTest.waitForExplicitFinish();
+</script>
+</pre>
+</body>
+</html>
--- a/content/xul/templates/src/nsXULContentUtils.cpp
+++ b/content/xul/templates/src/nsXULContentUtils.cpp
@@ -89,17 +89,16 @@
 #include "nsCollationCID.h"
 #include "nsILocale.h"
 #include "nsILocaleService.h"
 
 static NS_DEFINE_CID(kRDFServiceCID,        NS_RDFSERVICE_CID);
 
 //------------------------------------------------------------------------
 
-nsrefcnt nsXULContentUtils::gRefCnt;
 nsIRDFService* nsXULContentUtils::gRDF;
 nsIDateTimeFormat* nsXULContentUtils::gFormat;
 nsICollation *nsXULContentUtils::gCollation;
 
 #define XUL_RESOURCE(ident, uri) nsIRDFResource* nsXULContentUtils::ident
 #define XUL_LITERAL(ident, val) nsIRDFLiteral* nsXULContentUtils::ident
 #include "nsXULResourceList.h"
 #undef XUL_RESOURCE
@@ -107,21 +106,20 @@ nsICollation *nsXULContentUtils::gCollat
 
 //------------------------------------------------------------------------
 // Constructors n' stuff
 //
 
 nsresult
 nsXULContentUtils::Init()
 {
-    if (gRefCnt++ == 0) {
-        nsresult rv = CallGetService(kRDFServiceCID, &gRDF);
-        if (NS_FAILED(rv)) {
-            return rv;
-        }
+    nsresult rv = CallGetService(kRDFServiceCID, &gRDF);
+    if (NS_FAILED(rv)) {
+        return rv;
+    }
 
 #define XUL_RESOURCE(ident, uri)                              \
   PR_BEGIN_MACRO                                              \
    rv = gRDF->GetResource(NS_LITERAL_CSTRING(uri), &(ident)); \
    if (NS_FAILED(rv)) return rv;                              \
   PR_END_MACRO
 
 #define XUL_LITERAL(ident, val)                                   \
@@ -129,41 +127,38 @@ nsXULContentUtils::Init()
    rv = gRDF->GetLiteral(NS_LITERAL_STRING(val).get(), &(ident)); \
    if (NS_FAILED(rv)) return rv;                                  \
   PR_END_MACRO
 
 #include "nsXULResourceList.h"
 #undef XUL_RESOURCE
 #undef XUL_LITERAL
 
-        rv = CallCreateInstance(NS_DATETIMEFORMAT_CONTRACTID, &gFormat);
-        if (NS_FAILED(rv)) {
-            return rv;
-        }
+    rv = CallCreateInstance(NS_DATETIMEFORMAT_CONTRACTID, &gFormat);
+    if (NS_FAILED(rv)) {
+        return rv;
     }
 
     return NS_OK;
 }
 
 
 nsresult
 nsXULContentUtils::Finish()
 {
-    if (--gRefCnt == 0) {
-        NS_IF_RELEASE(gRDF);
+    NS_IF_RELEASE(gRDF);
 
 #define XUL_RESOURCE(ident, uri) NS_IF_RELEASE(ident)
 #define XUL_LITERAL(ident, val) NS_IF_RELEASE(ident)
 #include "nsXULResourceList.h"
 #undef XUL_RESOURCE
 #undef XUL_LITERAL
 
-        NS_IF_RELEASE(gFormat);
-        NS_IF_RELEASE(gCollation);
-    }
+    NS_IF_RELEASE(gFormat);
+    NS_IF_RELEASE(gCollation);
 
     return NS_OK;
 }
 
 nsICollation*
 nsXULContentUtils::GetCollation()
 {
     if (!gCollation) {
--- a/content/xul/templates/src/nsXULContentUtils.h
+++ b/content/xul/templates/src/nsXULContentUtils.h
@@ -59,17 +59,16 @@ class nsIRDFLiteral;
 class nsIRDFService;
 class nsINameSpaceManager;
 class nsIDateTimeFormat;
 class nsICollation;
 
 class nsXULContentUtils
 {
 protected:
-    static nsrefcnt gRefCnt;
     static nsIRDFService* gRDF;
     static nsIDateTimeFormat* gFormat;
     static nsICollation *gCollation;
 
     static PRBool gDisableXULCache;
 
     static int
     DisableXULCacheChangedCallback(const char* aPrefName, void* aClosure);
--- a/db/sqlite3/src/sqlite.def
+++ b/db/sqlite3/src/sqlite.def
@@ -70,16 +70,17 @@ EXPORTS
         sqlite3_column_name16
         sqlite3_column_text
         sqlite3_column_text16
         sqlite3_column_type
         sqlite3_column_value
         sqlite3_commit_hook
         sqlite3_complete
         sqlite3_complete16
+        sqlite3_config
         sqlite3_create_collation
         sqlite3_create_collation16
         sqlite3_create_function
         sqlite3_create_function16
         sqlite3_create_module
         sqlite3_data_count
         sqlite3_db_handle
         sqlite3_declare_vtab
@@ -94,16 +95,17 @@ EXPORTS
         sqlite3_file_control
         sqlite3_finalize
         sqlite3_free
         sqlite3_free_table
         sqlite3_get_autocommit
         sqlite3_get_auxdata
         sqlite3_get_table
         sqlite3_global_recover
+        sqlite3_initialize
         sqlite3_interrupt
         sqlite3_last_insert_rowid
         sqlite3_libversion
         sqlite3_libversion_number
         sqlite3_load_extension
         sqlite3_malloc
         sqlite3_memory_alarm
         sqlite3_memory_highwater
@@ -139,16 +141,17 @@ EXPORTS
         sqlite3_result_text
         sqlite3_result_text16
         sqlite3_result_text16be
         sqlite3_result_text16le
         sqlite3_result_value
         sqlite3_rollback_hook
         sqlite3_set_authorizer
         sqlite3_set_auxdata
+        sqlite3_shutdown
         sqlite3_sleep
         sqlite3_snprintf
         sqlite3_sql
         sqlite3_step
         sqlite3_thread_cleanup
         sqlite3_total_changes
         sqlite3_trace
         sqlite3_transfer_bindings
--- a/dom/public/idl/html/nsIDOMHTMLMediaElement.idl
+++ b/dom/public/idl/html/nsIDOMHTMLMediaElement.idl
@@ -44,16 +44,23 @@
  * <audio> and <video> elements.
  *
  * For more information on this interface, please see
  * http://www.whatwg.org/specs/web-apps/current-work/#htmlmediaelement
  *
  * @status UNDER_DEVELOPMENT
  */
 
+// undef the GetCurrentTime macro defined in WinBase.h from the MS Platform SDK
+%{C++
+#ifdef GetCurrentTime
+#undef GetCurrentTime
+#endif
+%}
+
 [scriptable, uuid(e3e2a8c1-4b56-4154-8ef2-fc4b2bb42e97)]
 interface nsIDOMHTMLMediaElement : nsIDOMHTMLElement
 {
   // error state
   readonly attribute nsIDOMHTMLMediaError error;
 
   // network state
            attribute DOMString src;
--- a/dom/public/nsIScriptContext.h
+++ b/dom/public/nsIScriptContext.h
@@ -52,19 +52,19 @@ class nsIArray;
 class nsIVariant;
 class nsIObjectInputStream;
 class nsIObjectOutputStream;
 class nsScriptObjectHolder;
 
 typedef void (*nsScriptTerminationFunc)(nsISupports* aRef);
 
 #define NS_ISCRIPTCONTEXT_IID \
-{ /* {e7b9871d-3adc-4bf7-850d-7fb9554886bf} */ \
-  0xe7b9871d, 0x3adc, 0x4bf7, \
- { 0x85, 0x0d, 0x7f, 0xb9, 0x55, 0x48, 0x86, 0xbf } }
+{ /* {09316a0e-8d05-4d26-9efd-8f907a7c79d2} */ \
+  0x09316a0e, 0x8d05, 0x4d26, \
+ { 0x9e, 0xfd, 0x8f, 0x90, 0x7a, 0x7c, 0x79, 0xd2 } }
 
 /* This MUST match JSVERSION_DEFAULT.  This version stuff if we don't
    know what language we have is a little silly... */
 #define SCRIPTVERSION_DEFAULT JSVERSION_DEFAULT
 
 /**
  * It is used by the application to initialize a runtime and run scripts.
  * A script runtime would implement this interface.
@@ -451,17 +451,14 @@ public:
    * nsScriptObjectHolder to manage the lifetimes of the held script objects.
    *
    * See also nsIScriptRuntime, which has identical methods and is useful
    * in situations when you do not have an nsIScriptContext.
    * 
    */
   virtual nsresult DropScriptObject(void *object) = 0;
   virtual nsresult HoldScriptObject(void *object) = 0;
-
-  /* Report a pending exception if there is one on the native context */
-  virtual void ReportPendingException() = 0;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsIScriptContext, NS_ISCRIPTCONTEXT_IID)
 
 #endif // nsIScriptContext_h__
 
--- a/dom/src/base/nsJSEnvironment.cpp
+++ b/dom/src/base/nsJSEnvironment.cpp
@@ -1587,17 +1587,17 @@ nsJSContext::EvaluateString(const nsAStr
                                               aLineNo,
                                               vp);
 
     if (!ok) {
       // Tell XPConnect about any pending exceptions. This is needed
       // to avoid dropping JS exceptions in case we got here through
       // nested calls through XPConnect.
 
-      JS_ReportPendingException(mContext);
+      ReportPendingException(PR_FALSE);
     }
   }
 
   // Whew!  Finally done with these manually ref-counted things.
   JSPRINCIPALS_DROP(mContext, jsprin);
 
   // If all went well, convert val to a string if one is wanted.
   if (ok) {
@@ -1851,19 +1851,17 @@ nsJSContext::CompileEventHandler(nsIAtom
                                           charName, aArgCount, aArgNames,
                                           (jschar*)PromiseFlatString(aBody).get(),
                                           aBody.Length(),
                                           aURL, aLineNo);
 
   if (!fun) {
     // Set aside the frame chain on cx while reporting, since it has
     // nothing to do with the error we just hit.
-    JSStackFrame* frame = JS_SaveFrameChain(mContext);
-    ReportPendingException();
-    JS_RestoreFrameChain(mContext, frame);
+    ReportPendingException(PR_TRUE);
     return NS_ERROR_ILLEGAL_VALUE;
   }
 
   JSObject *handler = ::JS_GetFunctionObject(fun);
   NS_ASSERTION(aHandler.getScriptTypeID()==JAVASCRIPT,
                "Expecting JS script object holder");
   return aHandler.set((void *)handler);
 }
@@ -1988,19 +1986,17 @@ nsJSContext::CallEventHandler(nsISupport
     PRBool ok = ::JS_CallFunctionValue(mContext, target,
                                        funval, argc, argv, &rval);
 
     if (!ok) {
       // Tell XPConnect about any pending exceptions. This is needed
       // to avoid dropping JS exceptions in case we got here through
       // nested calls through XPConnect.
 
-      if (JS_IsExceptionPending(mContext)) {
-        JS_ReportPendingException(mContext);
-      }
+      ReportPendingException(PR_FALSE);
 
       // Don't pass back results from failed calls.
       rval = JSVAL_VOID;
 
       // Tell the caller that the handler threw an error.
       rv = NS_ERROR_FAILURE;
     }
   }
@@ -2064,16 +2060,17 @@ nsJSContext::BindCompiledEventHandler(ns
       rv = NS_ERROR_OUT_OF_MEMORY;
   }
 
   if (NS_SUCCEEDED(rv) &&
       // Make sure the flags here match those in nsEventReceiverSH::NewResolve
       !::JS_DefineProperty(mContext, target, charName,
                            OBJECT_TO_JSVAL(funobj), nsnull, nsnull,
                            JSPROP_ENUMERATE | JSPROP_PERMANENT)) {
+    ReportPendingException(PR_TRUE);
     rv = NS_ERROR_FAILURE;
   }
 
   // XXXmarkh - ideally we should assert that the wrapped native is now
   // "long lived" - how to do that?
 
   if (NS_FAILED(stack->Pop(nsnull)) && NS_SUCCEEDED(rv)) {
     rv = NS_ERROR_FAILURE;
@@ -3610,21 +3607,26 @@ nsJSContext::DropScriptObject(void* aScr
     return NS_ERROR_FAILURE;
   }
 
   ::JS_UnlockGCThingRT(nsJSRuntime::sRuntime, aScriptObject);
   return NS_OK;
 }
 
 void
-nsJSContext::ReportPendingException()
+nsJSContext::ReportPendingException(PRBool aSetAsideFrameChain)
 {
+  JSStackFrame* frame =
+    aSetAsideFrameChain ? JS_SaveFrameChain(mContext) : nsnull;
   if (mIsInitialized && ::JS_IsExceptionPending(mContext)) {
     ::JS_ReportPendingException(mContext);
   }
+  if (aSetAsideFrameChain) {
+    JS_RestoreFrameChain(mContext, frame);
+  }
 }
 
 /**********************************************************************
  * nsJSRuntime implementation
  *********************************************************************/
 
 // QueryInterface implementation for nsJSRuntime
 NS_INTERFACE_MAP_BEGIN(nsJSRuntime)
--- a/dom/src/base/nsJSEnvironment.h
+++ b/dom/src/base/nsJSEnvironment.h
@@ -161,18 +161,16 @@ public:
 
   virtual nsresult Serialize(nsIObjectOutputStream* aStream, void *aScriptObject);
   virtual nsresult Deserialize(nsIObjectInputStream* aStream,
                                nsScriptObjectHolder &aResult);
 
   virtual nsresult DropScriptObject(void *object);
   virtual nsresult HoldScriptObject(void *object);
 
-  virtual void ReportPendingException();
-
   NS_DECL_NSIXPCSCRIPTNOTIFY
 
   NS_DECL_NSITIMERCALLBACK
 
   static void LoadStart();
   static void LoadEnd();
 
   // CC does always call cycle collector and it also updates the counters
@@ -211,16 +209,21 @@ protected:
 
   void FireGCTimer(PRBool aLoadInProgress);
 
   // given an nsISupports object (presumably an event target or some other
   // DOM object), get (or create) the JSObject wrapping it.
   nsresult JSObjectFromInterface(nsISupports *aSup, void *aScript, 
                                  JSObject **aRet);
 
+  // Report the pending exception on our mContext, if any
+  // If aSetAsideFrameChain is true, set aside the frame chain on mContext
+  // before reporting.  True should be passed if the frame chain isn't really
+  // related to our exception.
+  void ReportPendingException(PRBool aSetAsideFrameChain);
 private:
   void Unlink();
 
   JSContext *mContext;
   PRUint32 mNumEvaluations;
 
 protected:
   struct TerminationFuncHolder;
--- a/extensions/python/dom/src/nsPyContext.cpp
+++ b/extensions/python/dom/src/nsPyContext.cpp
@@ -928,14 +928,8 @@ nsPythonContext::HoldScriptObject(void *
 {
   if (object) {
     PYLEAK_STAT_INCREMENT(ScriptObject);
     CEnterLeavePython _celp;
     Py_INCREF((PyObject *)object);
   }
   return NS_OK;
 }
-
-void
-nsPythonContext::ReportPendingException()
-{
-  // Not sure there's anything to do here
-}
--- a/extensions/python/dom/src/nsPyContext.h
+++ b/extensions/python/dom/src/nsPyContext.h
@@ -208,18 +208,16 @@ public:
 
   virtual nsresult Serialize(nsIObjectOutputStream* aStream, void *aScriptObject);
   virtual nsresult Deserialize(nsIObjectInputStream* aStream,
                                nsScriptObjectHolder &aResult);
 
   virtual nsresult HoldScriptObject(void *object);
   virtual nsresult DropScriptObject(void *object);
 
-  virtual void ReportPendingException();
-
   NS_DECL_NSITIMERCALLBACK
   
   PyObject *PyObject_FromInterface(nsISupports *target,
                                    const nsIID &iid)
   {
     return ::PyObject_FromNSDOMInterface(mDelegate, target, iid);
   }
 protected:
--- a/js/src/config/Makefile.in
+++ b/js/src/config/Makefile.in
@@ -50,17 +50,17 @@ VISIBILITY_FLAGS =
 
 ifneq (,$(CROSS_COMPILE)$(filter-out WINNT OS2,$(OS_ARCH)))
 ifneq ($(OS_ARCH), WINCE)
 HOST_PROGRAM	= nsinstall$(HOST_BIN_SUFFIX)
 HOST_CSRCS	= nsinstall.c pathsub.c
 endif
 endif
 
-PLSRCS		= nfspwd.pl revdepth.pl
+PLSRCS		= nfspwd.pl
 
 TARGETS		= $(HOST_PROGRAM) $(PLSRCS:.pl=) $(SIMPLE_PROGRAMS)
 
 # IMPORTANT: Disable NSBUILDROOT for this directory only, otherwise we have
 # a recursive rule for finding nsinstall and the Perl scripts.
 ifdef NSBUILDROOT
 override NSBUILDROOT :=
 endif
deleted file mode 100644
--- a/js/src/config/revdepth-nt.pl
+++ /dev/null
@@ -1,48 +0,0 @@
-#! perl
-#
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of the GNU General Public License Version 2 or later (the "GPL"),
-# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-require "/ns/config/fastcwd.pl";
-
-$cur = &fastcwd;
-chdir($ARGV[0]);
-$newcur = &fastcwd;
-$newcurlen = length($newcur);
-
-# Skip common separating / unless $newcur is "/"
-$cur = substr($cur, $newcurlen + ($newcurlen > 1));
-print $cur;
deleted file mode 100644
--- a/js/src/config/revdepth.pl
+++ /dev/null
@@ -1,51 +0,0 @@
-#! perl
-#
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of the GNU General Public License Version 2 or later (the "GPL"),
-# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-unshift(@INC, '/usr/lib/perl');
-unshift(@INC, '/usr/local/lib/perl');
-
-require "fastcwd.pl";
-
-$cur = &fastcwd;
-chdir($ARGV[0]);
-$newcur = &fastcwd;
-$newcurlen = length($newcur);
-
-# Skip common separating / unless $newcur is "/"
-$cur = substr($cur, $newcurlen + ($newcurlen > 1));
-print $cur;
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -182,25 +182,21 @@ MOZ_ARG_ENABLE_BOOL(compile-environment,
 [  --disable-compile-environment
                            Disable compiler/library checks.],
     COMPILE_ENVIRONMENT=1,
     COMPILE_ENVIRONMENT= )
 
 dnl ========================================================
 dnl Checks for compilers.
 dnl ========================================================
-dnl Set CROSS_COMPILE in the environment when running configure
-dnl to use the cross-compile setup for now
-dnl ========================================================
 
 if test "$COMPILE_ENVIRONMENT"; then
 
-if test -n "$CROSS_COMPILE" && test "$target" != "$host"; then
+if test "$target" != "$host"; then
     echo "cross compiling from $host to $target"
-    cross_compiling=yes
 
     _SAVE_CC="$CC"
     _SAVE_CFLAGS="$CFLAGS"
     _SAVE_LDFLAGS="$LDFLAGS"
 
     AC_MSG_CHECKING([for host c compiler])
     AC_CHECK_PROGS(HOST_CC, $HOST_CC gcc cc /usr/ucb/cc cl icc, "")
     if test -z "$HOST_CC"; then
@@ -279,38 +275,25 @@ if test -n "$CROSS_COMPILE" && test "$ta
 
     AC_CHECK_PROGS(RANLIB, $RANLIB "${target_alias}-ranlib" "${target}-ranlib", :)
     AC_CHECK_PROGS(AR, $AR "${target_alias}-ar" "${target}-ar", :)
     AC_PATH_PROGS(AS, $AS "${target_alias}-as" "${target}-as", :)
     AC_CHECK_PROGS(LD, $LD "${target_alias}-ld" "${target}-ld", :)
     AC_CHECK_PROGS(STRIP, $STRIP "${target_alias}-strip" "${target}-strip", :)
     AC_CHECK_PROGS(WINDRES, $WINDRES "${target_alias}-windres" "${target}-windres", :)
     AC_DEFINE(CROSS_COMPILE)
+
+    dnl If we cross compile for ppc on Mac OS X x86, cross_compiling will
+    dnl have erroneously been set to "no", because the x86 build host is
+    dnl able to run ppc code in a translated environment, making a cross
+    dnl compiler appear native.  So we override that here.
+    cross_compiling=yes
 else
-    case "$build:$target" in
-      powerpc-apple-darwin8*:i?86-apple-darwin*)
-        dnl The Darwin cross compiler doesn't necessarily point itself at a
-        dnl root that has libraries for the proper architecture, it defaults
-        dnl to the system root.  The libraries in the system root on current
-        dnl versions of PPC OS X 10.4 aren't fat, so these target compiler
-        dnl checks will fail.  Fake a working SDK in that case.
-        _SAVE_CFLAGS=$CFLAGS
-        _SAVE_CXXFLAGS=$CXXLAGS
-        CFLAGS="-isysroot /Developer/SDKs/MacOSX10.4u.sdk $CFLAGS"
-        CXXFLAGS="-isysroot /Developer/SDKs/MacOSX10.4u.sdk $CXXFLAGS"
-        ;;
-    esac
     AC_PROG_CC
     AC_PROG_CXX
-    case "$build:$target" in
-      powerpc-apple-darwin8*:i?86-apple-darwin*)
-        CFLAGS=$_SAVE_CFLAGS
-        CXXFLAGS=$_SAVE_CXXFLAGS
-        ;;
-    esac
     AC_PROG_RANLIB
     AC_PATH_PROGS(AS, $AS as, $CC)
     AC_CHECK_PROGS(AR, ar, :)
     AC_CHECK_PROGS(LD, ld, :)
     AC_CHECK_PROGS(STRIP, strip, :)
     AC_CHECK_PROGS(WINDRES, windres, :)
     if test -z "$HOST_CC"; then
         HOST_CC="$CC"
--- a/js/src/jsfun.cpp
+++ b/js/src/jsfun.cpp
@@ -709,17 +709,17 @@ call_enumerate(JSContext *cx, JSObject *
     void *mark;
     jsuword *names;
     JSBool ok;
     JSAtom *name;
     JSObject *pobj;
     JSProperty *prop;
 
     fun = js_GetCallObjectFunction(obj);
-    n = JS_GET_LOCAL_NAME_COUNT(fun);
+    n = fun ? JS_GET_LOCAL_NAME_COUNT(fun) : 0;
     if (n == 0)
         return JS_TRUE;
 
     mark = JS_ARENA_MARK(&cx->tempPool);
 
     MUST_FLOW_THROUGH("out");
     names = js_GetLocalNameArray(cx, fun, &cx->tempPool);
     if (!names) {
--- a/js/src/jsinterp.cpp
+++ b/js/src/jsinterp.cpp
@@ -226,17 +226,18 @@ js_FillPropertyCache(JSContext *cx, JSOb
                             pobj, LOCKED_OBJ_GET_CLASS(pobj)->name,
                             JSVAL_TO_OBJECT(v),
                             JS_GetFunctionName(GET_FUNCTION_PRIVATE(cx,
                                                  JSVAL_TO_OBJECT(v))),
                             kshape);
 #endif
                         SCOPE_MAKE_UNIQUE_SHAPE(cx, scope);
                         SCOPE_SET_BRANDED(scope);
-                        kshape = scope->shape;
+                        if (OBJ_SCOPE(obj) == scope)
+                            kshape = scope->shape;
                     }
                     vword = JSVAL_OBJECT_TO_PCVAL(v);
                     break;
                 }
             }
         }
 
         /* If getting a value via a stub getter, we can cache the slot. */
--- a/js/src/nanojit/Native.h
+++ b/js/src/nanojit/Native.h
@@ -87,17 +87,21 @@ namespace nanojit {
 	#ifdef NJ_STACK_GROWTH_UP
 		#define stack_direction(n)   n
 	#else
 		#define stack_direction(n)  -n
 	#endif
 	
 	#define isSPorFP(r)		( (r)==SP || (r)==FP )
 
-	#ifdef NJ_VERBOSE
+	#if defined(_MSC_VER) && _MSC_VER < 1400
+		static void asm_output(const char *f, ...) {}
+		#define gpn(r)					regNames[(r)]
+		#define fpn(r)					regNames[(r)]
+	#elif defined(NJ_VERBOSE)
 		#define asm_output(...) do {\
 			counter_increment(native);\
 			if (verbose_enabled()) {\
 				outline[0]='\0';\
 				if (outputAddr) sprintf(outline, "  %10p  ",_nIns);\
 				else sprintf(outline, "              ");\
 				sprintf(&outline[14], ##__VA_ARGS__);\
 				Assembler::outputAlign(outline, 45);\
--- a/js/src/nanojit/nanojit.h
+++ b/js/src/nanojit/nanojit.h
@@ -162,17 +162,23 @@ namespace nanojit
 	 */
 }
 
 #ifdef AVMPLUS_VERBOSE
 #define NJ_VERBOSE 1
 #define NJ_PROFILE 1
 #endif
 
-#ifdef NJ_VERBOSE
+#if defined(_MSC_VER) && _MSC_VER < 1400
+	#include <stdio.h>
+	#define verbose_output						if (verbose_enabled()) Assembler::output
+	#define verbose_outputf						if (verbose_enabled()) Assembler::outputf
+	#define verbose_enabled()					(_verbose)
+	#define verbose_only(x)						x
+#elif defined(NJ_VERBOSE)
 	#include <stdio.h>
 	#define verbose_output						if (verbose_enabled()) Assembler::output
 	#define verbose_outputf						if (verbose_enabled()) Assembler::outputf
 	#define verbose_enabled()					(_verbose)
 	#define verbose_only(...)					__VA_ARGS__
 #else
 	#define verbose_output
 	#define verbose_outputf
--- a/layout/base/nsCSSFrameConstructor.cpp
+++ b/layout/base/nsCSSFrameConstructor.cpp
@@ -1849,16 +1849,17 @@ nsCSSFrameConstructor::nsCSSFrameConstru
   , mPresShell(aPresShell)
   , mInitialContainingBlock(nsnull)
   , mRootElementStyleFrame(nsnull)
   , mFixedContainingBlock(nsnull)
   , mDocElementContainingBlock(nsnull)
   , mGfxScrollFrame(nsnull)
   , mPageSequenceFrame(nsnull)
   , mUpdateCount(0)
+  , mFocusSuppressCount(0)
   , mQuotesDirty(PR_FALSE)
   , mCountersDirty(PR_FALSE)
   , mIsDestroyingFrameTree(PR_FALSE)
   , mRebuildAllStyleData(PR_FALSE)
   , mHasRootAbsPosContainingBlock(PR_FALSE)
   , mHoverGeneration(0)
   , mRebuildAllExtraHint(nsChangeHint(0))
 {
@@ -7669,17 +7670,17 @@ nsCSSFrameConstructor::ReconstructDocEle
         if (docElementFrame) {
           // Take the docElementFrame, and remove it from its parent.
           // XXXbz So why can't we reuse ContentRemoved?
 
           // Notify self that we will destroy the entire frame tree, this blocks
           // RemoveMappingsForFrameSubtree() which would otherwise lead to a
           // crash since we cleared the placeholder map above (bug 398982).
           PRBool wasDestroyingFrameTree = mIsDestroyingFrameTree;
-          WillDestroyFrameTree();
+          WillDestroyFrameTree(PR_FALSE);
 
           rv = state.mFrameManager->RemoveFrame(docElementFrame->GetParent(),
                     GetChildListNameFor(docElementFrame), docElementFrame);
           
           if (placeholderFrame) {
             // Remove the placeholder frame first (XXX second for now) (so
             // that it doesn't retain a dangling pointer to memory)
             rv |= state.mFrameManager->RemoveFrame(placeholderFrame->GetParent(),
@@ -10159,31 +10160,34 @@ nsCSSFrameConstructor::AttributeChanged(
   PostRestyleEvent(aContent, rshint, hint);
 
   return result;
 }
 
 void
 nsCSSFrameConstructor::BeginUpdate() {
   NS_SuppressFocusEvent();
+  ++mFocusSuppressCount;
   ++mUpdateCount;
 }
 
 void
 nsCSSFrameConstructor::EndUpdate()
 {
   if (mUpdateCount == 1) {
     // This is the end of our last update.  Before we decrement
     // mUpdateCount, recalc quotes and counters as needed.
 
     RecalcQuotesAndCounters();
     NS_ASSERTION(mUpdateCount == 1, "Odd update count");
   }
-  NS_UnsuppressFocusEvent();
-  --mUpdateCount;
+  if (mFocusSuppressCount) {
+    NS_UnsuppressFocusEvent();
+    --mFocusSuppressCount;
+  }
 }
 
 void
 nsCSSFrameConstructor::RecalcQuotesAndCounters()
 {
   if (mQuotesDirty) {
     mQuotesDirty = PR_FALSE;
     mQuoteList.RecalcAll();
@@ -10193,31 +10197,56 @@ nsCSSFrameConstructor::RecalcQuotesAndCo
     mCountersDirty = PR_FALSE;
     mCounterManager.RecalcAll();
   }
 
   NS_ASSERTION(!mQuotesDirty, "Quotes updates will be lost");
   NS_ASSERTION(!mCountersDirty, "Counter updates will be lost");  
 }
 
+class nsFocusUnsuppressEvent : public nsRunnable {
+  public:
+    NS_DECL_NSIRUNNABLE
+    nsFocusUnsuppressEvent(PRUint32 aCount) : mCount(aCount) {}
+  private:
+    PRUint32 mCount;
+  };
+
+NS_IMETHODIMP nsFocusUnsuppressEvent::Run()
+{
+  while (mCount) {
+    --mCount;
+    NS_UnsuppressFocusEvent();
+  }
+  return NS_OK;
+}
+
 void
-nsCSSFrameConstructor::WillDestroyFrameTree()
+nsCSSFrameConstructor::WillDestroyFrameTree(PRBool aDestroyingPresShell)
 {
 #if defined(DEBUG_dbaron_off)
   mCounterManager.Dump();
 #endif
 
   mIsDestroyingFrameTree = PR_TRUE;
 
   // Prevent frame tree destruction from being O(N^2)
   mQuoteList.Clear();
   mCounterManager.Clear();
 
   // Cancel all pending re-resolves
   mRestyleEvent.Revoke();
+
+  if (mFocusSuppressCount && aDestroyingPresShell) {
+    nsRefPtr<nsFocusUnsuppressEvent> ev =
+      new nsFocusUnsuppressEvent(mFocusSuppressCount);
+    if (NS_SUCCEEDED(NS_DispatchToCurrentThread(ev))) {
+      mFocusSuppressCount = 0;
+    }
+  }
 }
 
 //STATIC
 
 // XXXbz I'd really like this method to go away. Once we have inline-block and
 // I can just use that for sized broken images, that can happen, maybe.
 void nsCSSFrameConstructor::GetAlternateTextFor(nsIContent*    aContent,
                                                 nsIAtom*       aTag,  // content object's tag
--- a/layout/base/nsCSSFrameConstructor.h
+++ b/layout/base/nsCSSFrameConstructor.h
@@ -149,17 +149,17 @@ public:
                             nsIAtom*    aAttribute,
                             PRInt32     aModType,
                             PRUint32    aStateMask);
 
   void BeginUpdate();
   void EndUpdate();
   void RecalcQuotesAndCounters();
 
-  void WillDestroyFrameTree();
+  void WillDestroyFrameTree(PRBool aDestroyingPresShell);
 
   // Get an integer that increments every time there is a style change
   // as a result of a change to the :hover content state.
   PRUint32 GetHoverGeneration() const { return mHoverGeneration; }
 
   // Note: It's the caller's responsibility to make sure to wrap a
   // ProcessRestyledFrames call in a view update batch.
   // This function does not call ProcessAttachedQueue() on the binding manager.
@@ -1188,16 +1188,17 @@ private:
   // This is the containing block that contains the root element ---
   // the real "initial containing block" according to CSS 2.1.
   nsIFrame*           mDocElementContainingBlock;
   nsIFrame*           mGfxScrollFrame;
   nsIFrame*           mPageSequenceFrame;
   nsQuoteList         mQuoteList;
   nsCounterManager    mCounterManager;
   PRUint16            mUpdateCount;
+  PRUint32            mFocusSuppressCount;
   PRPackedBool        mQuotesDirty : 1;
   PRPackedBool        mCountersDirty : 1;
   PRPackedBool        mIsDestroyingFrameTree : 1;
   PRPackedBool        mRebuildAllStyleData : 1;
   // This is true if mDocElementContainingBlock supports absolute positioning
   PRPackedBool        mHasRootAbsPosContainingBlock : 1;
   PRUint32            mHoverGeneration;
   nsChangeHint        mRebuildAllExtraHint;
--- a/layout/base/nsCaret.cpp
+++ b/layout/base/nsCaret.cpp
@@ -158,16 +158,19 @@ nsresult nsCaret::Init(nsIPresShell *inP
     privateSelection->AddSelectionListener(this);
   mDomSelectionWeak = do_GetWeakReference(domSelection);
   
   // set up the blink timer
   if (mVisible)
   {
     StartBlinking();
   }
+#ifdef IBMBIDI
+  mBidiUI = nsContentUtils::GetBoolPref("bidi.browser.ui");
+#endif
 
   return NS_OK;
 }
 
 static PRBool
 DrawCJKCaret(nsIFrame* aFrame, PRInt32 aOffset)
 {
   nsIContent* content = aFrame->GetContent();
@@ -752,18 +755,17 @@ nsCaret::GetCaretFrameForNodeOffset(nsIC
   // Mamdouh : modification of the caret to work at rtl and ltr with Bidi
   //
   // Direction Style from this->GetStyleData()
   // now in (visibility->mDirection)
   // ------------------
   // NS_STYLE_DIRECTION_LTR : LTR or Default
   // NS_STYLE_DIRECTION_RTL
   // NS_STYLE_DIRECTION_INHERIT
-  nsPresContext *presContext = presShell->GetPresContext();
-  if (presContext && presContext->BidiEnabled())
+  if (mBidiUI)
   {
     // If there has been a reflow, take the caret Bidi level to be the level of the current frame
     if (aBidiLevel & BIDI_LEVEL_UNDEFINED)
       aBidiLevel = NS_GET_EMBEDDING_LEVEL(theFrame);
 
     PRInt32 start;
     PRInt32 end;
     nsIFrame* frameBefore;
@@ -1213,32 +1215,24 @@ nsresult nsCaret::UpdateCaretRects(nsIFr
 
 nsresult nsCaret::UpdateHookRect(nsPresContext* aPresContext,
                                  const Metrics& aMetrics)
 {
   mHookRect.Empty();
 
 #ifdef IBMBIDI
   // Simon -- make a hook to draw to the left or right of the caret to show keyboard language direction
-  PRBool bidiEnabled;
   PRBool isCaretRTL=PR_FALSE;
   nsIBidiKeyboard* bidiKeyboard = nsContentUtils::GetBidiKeyboard();
   if (!bidiKeyboard || NS_FAILED(bidiKeyboard->IsLangRTL(&isCaretRTL)))
     // if bidiKeyboard->IsLangRTL() failed, there is no way to tell the
     // keyboard direction, or the user has no right-to-left keyboard
     // installed, so we  never draw the hook.
     return NS_OK;
-  if (isCaretRTL)
-  {
-    bidiEnabled = PR_TRUE;
-    aPresContext->SetBidiEnabled();
-  }
-  else
-    bidiEnabled = aPresContext->BidiEnabled();
-  if (bidiEnabled)
+  if (mBidiUI)
   {
     if (isCaretRTL != mKeyboardRTL)
     {
       /* if the caret bidi level and the keyboard language direction are not in
        * synch, the keyboard language must have been changed by the
        * user, and if the caret is in a boundary condition (between left-to-right and
        * right-to-left characters) it may have to change position to
        * reflect the location in which the next character typed will
--- a/layout/base/nsCaret.h
+++ b/layout/base/nsCaret.h
@@ -287,34 +287,35 @@ protected:
     
     PRPackedBool          mVisible;           // is the caret blinking
 
     PRPackedBool          mDrawn;             // Denotes when the caret is physically drawn on the screen.
 
     PRPackedBool          mReadOnly;          // it the caret in readonly state (draws differently)      
     PRPackedBool          mShowDuringSelection; // show when text is selected
 
+    PRPackedBool          mIgnoreUserModify;
+
+#ifdef IBMBIDI
+    PRPackedBool          mKeyboardRTL;       // is the keyboard language right-to-left
+    PRPackedBool          mBidiUI;            // is bidi UI turned on
+    nsRect                mHookRect;          // directional hook on the caret
+    PRUint8               mLastBidiLevel;     // saved bidi level of the last draw request, to use when we erase
+#endif
     nsRect                mCaretRect;         // the last caret rect, in the coodinates of the last frame.
 
     nsCOMPtr<nsIContent>  mLastContent;       // store the content the caret was last requested to be drawn
                                               // in (by DrawAtPosition()/DrawCaret()),
                                               // note that this can be different than where it was
                                               // actually drawn (anon <BR> in text control)
     PRInt32               mLastContentOffset; // the offset for the last request
 
     nsFrameSelection::HINT mLastHint;        // the hint associated with the last request, see also
                                               // mLastBidiLevel below
 
-    PRPackedBool          mIgnoreUserModify;
-
-#ifdef IBMBIDI
-    nsRect                mHookRect;          // directional hook on the caret
-    PRUint8               mLastBidiLevel;     // saved bidi level of the last draw request, to use when we erase
-    PRPackedBool          mKeyboardRTL;       // is the keyboard language right-to-left
-#endif
 };
 
 nsresult
 NS_NewCaret(nsCaret** aInstancePtrResult);
 
 // handy stack-based class for temporarily disabling the caret
 
 class StCaretHider
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -1700,17 +1700,17 @@ PresShell::Destroy()
   // apparently frame destruction sometimes spins the event queue when
   // plug-ins are involved(!).
   mReflowEvent.Revoke();
 
   CancelAllPendingReflows();
   CancelPostedReflowCallbacks();
 
   // Destroy the frame manager. This will destroy the frame hierarchy
-  mFrameConstructor->WillDestroyFrameTree();
+  mFrameConstructor->WillDestroyFrameTree(PR_TRUE);
   FrameManager()->Destroy();
 
   NS_WARN_IF_FALSE(!mWeakFrames, "Weak frames alive after destroying FrameManager");
   while (mWeakFrames) {
     mWeakFrames->Clear(this);
   }
 
   // Let the style set do its cleanup.
@@ -5404,51 +5404,64 @@ PresShell::RenderSelection(nsISelection*
 }
 
 NS_IMETHODIMP
 PresShell::Paint(nsIView*             aView,
                  nsIRenderingContext* aRenderingContext,
                  const nsRegion&      aDirtyRegion)
 {
   AUTO_LAYOUT_PHASE_ENTRY_POINT(GetPresContext(), Paint);
-  nsIFrame* frame;
-  nsresult  rv = NS_OK;
-
-  if (mIsDestroying) {
-    NS_ASSERTION(PR_FALSE, "A paint message was dispatched to a destroyed PresShell");
-    return NS_OK;
-  }
-
-  NS_ASSERTION(!(nsnull == aView), "null view");
-
-  frame = static_cast<nsIFrame*>(aView->GetClientData());
+
+  NS_ASSERTION(!mIsDestroying, "painting a destroyed PresShell");
+  NS_ASSERTION(aView, "null view");
+
+  // Compute the backstop color for the view.  This color must be
+  // totally transparent if the view is within a glass or transparent
+  // widget; otherwise, we compose all the view managers' default
+  // background colors in order to get something completely opaque.
+  // Nested view managers might not have an opaque default, but the
+  // root view manager must.  See bug 467459.
+
+  PRBool needTransparency = PR_FALSE;
+  nsIViewManager *lastMgr = mViewManager;
   nscolor backgroundColor;
-  mViewManager->GetDefaultBackgroundColor(&backgroundColor);
+  lastMgr->GetDefaultBackgroundColor(&backgroundColor);
+
   for (nsIView *view = aView; view; view = view->GetParent()) {
-    if (view->HasWidget()) {
-      // Both glass and transparent windows need the transparent bg color
-      if (eTransparencyOpaque != view->GetWidget()->GetTransparencyMode()) {
-        backgroundColor = NS_RGBA(0,0,0,0);
-        break;
+    if (view->HasWidget() &&
+        view->GetWidget()->GetTransparencyMode() != eTransparencyOpaque) {
+      backgroundColor = NS_RGBA(0,0,0,0);
+      needTransparency = PR_TRUE;
+      break;
+    }
+    if (NS_GET_A(backgroundColor) < 255) {
+      nsIViewManager *thisMgr = view->GetViewManager();
+      NS_ASSERTION(thisMgr, "view without view manager");
+      if (lastMgr != thisMgr) {
+        nscolor underColor;
+        thisMgr->GetDefaultBackgroundColor(&underColor);
+        backgroundColor = NS_ComposeColors(underColor, backgroundColor);
+        lastMgr = thisMgr;
       }
     }
   }
+
+  NS_ASSERTION(needTransparency || NS_GET_A(backgroundColor) == 255,
+               "root view manager's default background isn't opaque");
   
-  if (!frame) {
-    if (NS_GET_A(backgroundColor) > 0) {
-      aRenderingContext->SetColor(backgroundColor);
-      aRenderingContext->FillRect(aDirtyRegion.GetBounds());
-    }
-    return NS_OK;
-  }
-
-  nsLayoutUtils::PaintFrame(aRenderingContext, frame, aDirtyRegion,
-                            backgroundColor);
-
-  return rv;
+  nsIFrame* frame = static_cast<nsIFrame*>(aView->GetClientData());
+  if (frame) {
+    nsLayoutUtils::PaintFrame(aRenderingContext, frame, aDirtyRegion,
+                              backgroundColor);
+  } else if (NS_GET_A(backgroundColor) > 0) {
+    aRenderingContext->SetColor(backgroundColor);
+    aRenderingContext->FillRect(aDirtyRegion.GetBounds());
+  }
+
+  return NS_OK;
 }
 
 nsIFrame*
 PresShell::GetCurrentEventFrame()
 {
   if (NS_UNLIKELY(mIsDestroying)) {
     return nsnull;
   }
--- a/layout/forms/nsListControlFrame.cpp
+++ b/layout/forms/nsListControlFrame.cpp
@@ -2474,23 +2474,26 @@ nsListControlFrame::GetIncrementalString
 
 void
 nsListControlFrame::DropDownToggleKey(nsIDOMEvent* aKeyEvent)
 {
   // Cocoa widgets do native popups, so don't try to show
   // dropdowns there.
   if (IsInDropDownMode() && !nsComboboxControlFrame::ToolkitHasNativePopup()) {
     aKeyEvent->PreventDefault();
-    nsIFrame* comboFrame;
-    CallQueryInterface(mComboboxFrame, &comboFrame);
-    nsWeakFrame weakFrame(comboFrame);
-    mComboboxFrame->ShowDropDown(!mComboboxFrame->IsDroppedDown());
-    if (!weakFrame.IsAlive())
-      return;
-    mComboboxFrame->RedisplaySelectedText();
+    if (!mComboboxFrame->IsDroppedDown()) {
+      mComboboxFrame->ShowDropDown(PR_TRUE);
+    } else {
+      nsWeakFrame weakFrame(this);
+      // mEndSelectionIndex is the last item that got selected.
+      ComboboxFinish(mEndSelectionIndex);
+      if (weakFrame.IsAlive()) {
+        FireOnChange();
+      }
+    }
   }
 }
 
 nsresult
 nsListControlFrame::KeyPress(nsIDOMEvent* aKeyEvent)
 {
   NS_ASSERTION(aKeyEvent, "keyEvent is null.");
 
--- a/layout/forms/test/Makefile.in
+++ b/layout/forms/test/Makefile.in
@@ -40,15 +40,16 @@ topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = layout/forms/test
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES =	test_bug345267.html \
+		test_bug348236.html \
 		test_bug402198.html \
 		test_bug411236.html \
 		test_bug446663.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $^ $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/layout/forms/test/test_bug348236.html
@@ -0,0 +1,131 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=348236
+-->
+<head>
+
+  <title>Test for Bug 348236</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+  <style type="text/css">
+  #eSelect {
+    position: fixed; top:0; left: 350px; font-size: 24px; width: 100px
+  }
+  #eSelect option {
+    margin: 0; padding: 0; height: 24px
+  }
+  </style>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=348236">Mozilla Bug 348236</a>
+<p id="display"></p>
+<div id="content">
+
+  <select id="eSelect" size="1" onchange="++this.onchangeCount">
+    <option selected>1</option>
+    <option>2</option>
+    <option>3</option>
+  </select>
+</div>
+<pre id="test">
+<script type="text/javascript">
+
+  /** Test for Bug 348236 **/
+
+SimpleTest.waitForExplicitFinish()
+addLoadEvent(function test() {
+
+    var
+        CI = Components.interfaces,
+        WinUtils = window
+                   .QueryInterface(CI.nsIInterfaceRequestor)
+                   .getInterface(CI.nsIDOMWindowUtils),
+        sec = netscape.security,
+        eSelect = $("eSelect"),
+        IDOMNSEvent = CI.nsIDOMNSEvent,
+        IDOMKeyEvent = CI.nsIDOMKeyEvent,
+        timeout = 0 // Choose a larger value like 500 ms if you want to see what's happening.
+
+    function keypressOnSelect(key, modifiers) {
+        sec.PrivilegeManager.enablePrivilege("UniversalXPConnect")
+        WinUtils.focus(eSelect)
+        WinUtils.sendKeyEvent("keyup", key, 0, modifiers, true)
+        WinUtils.sendKeyEvent("keypress", key, 0, modifiers, true)
+        WinUtils.sendKeyEvent("keydown", key, 0, modifiers, true)
+    }
+
+    function testKey(key, modifiers, keyString, functionToContinue) {
+        var selectGotClick
+        function clickListener() { selectGotClick = true }
+        eSelect.selectedIndex = 0
+        eSelect.onchangeCount = 0
+
+        // Drop the SELECT down.
+        keypressOnSelect(key, modifiers)
+        // This timeout and the following are necessary to let the sent events take effect.
+        setTimeout(cont1, timeout)
+        function cont1() {
+            sec.PrivilegeManager.enablePrivilege("UniversalXPConnect")
+            // Move the mouse over option 3 (90 = 3 (rows) * 24 (row height) + 18).
+            WinUtils.sendMouseEvent("mousemove", 355, 90, 0, 0, 0, true)
+            setTimeout(cont2, timeout)
+        }
+        function cont2() {
+            // Close the select.
+            keypressOnSelect(key, modifiers)
+            setTimeout(cont3, timeout)
+        }
+        function cont3() {
+            sec.PrivilegeManager.enablePrivilege("UniversalXPConnect")
+            is(eSelect.value, "3", "Select's value should be 3 after hovering over option 3 and pressing " + keyString + ".")
+            is(eSelect.onchangeCount, 1, "Onchange should have fired once.")
+
+            // Simulate click on area to the left of the select.
+            eSelect.addEventListener("click", clickListener, true)
+            selectGotClick = false
+            WinUtils.sendMouseEvent("mousedown", 320, 0, 0, 0, 0, true)
+            WinUtils.sendMouseEvent("mouseup", 320, 0, 0, 0, 0, true)
+            setTimeout(cont4, timeout)
+        }
+        function cont4() {
+            eSelect.removeEventListener("click", clickListener, true)
+            ok(!selectGotClick, "SELECT must not capture mouse events after closing it with " + keyString + ".")
+            functionToContinue()
+        }
+    }
+
+
+    // Quick sanity checks.
+    is(eSelect.value, "1", "SELECT value should be 1 after load.")
+    is(eSelect.selectedIndex, 0, "SELECT selectedIndex should be 0 after load.")
+
+    // Check if sending key events works.
+    keypressOnSelect(IDOMKeyEvent.DOM_VK_DOWN, 0)
+    is(eSelect.value, "2", "SELECT value should be 2 after pressing Down.")
+      
+    // Test ALT-Down.
+    testKey(IDOMKeyEvent.DOM_VK_DOWN, IDOMNSEvent.ALT_MASK, "ALT-Down", nextKey1)
+    function nextKey1() {
+        // Test ALT-Up.
+        testKey(IDOMKeyEvent.DOM_VK_UP, IDOMNSEvent.ALT_MASK, "ALT-Up", nextKey2)
+    }
+    function nextKey2() {
+        // Test the F4 key on OS/2 and Windows.
+        if (/OS\/2|Win32/i.test(navigator.platform))
+            testKey(IDOMKeyEvent.DOM_VK_F4, 0, "F4", finished)
+        else
+            finished()
+    }
+    function finished() {
+    // Reset value to get the expected value if we reload the page.
+        eSelect.selectedIndex = 0
+        SimpleTest.finish()
+    }
+})
+
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/svg/crashtests/458453.html
@@ -0,0 +1,24 @@
+<html class="reftest-wait">
+<head>
+<script type="text/javascript">
+
+var i = 0;
+
+function bouncy()
+{
+  var body = document.body;
+  document.documentElement.removeChild(body);
+  document.documentElement.appendChild(body);
+
+  if (++i < 30)
+    setTimeout(bouncy, 1);
+  else
+    document.documentElement.removeAttribute("class");
+}
+
+</script>
+</head>
+
+<body onload="bouncy();"><span id="a"></span><span style="filter: url(#a);"><span style="filter: url(#a);">B</span></span></body>
+
+</html>
--- a/layout/svg/crashtests/crashtests.list
+++ b/layout/svg/crashtests/crashtests.list
@@ -49,9 +49,10 @@ load 386566-1.svg
 load 387290-1.svg
 load 402408-1.svg
 load 404677-1.xhtml
 load 409565-1.xhtml
 load 409573-1.svg
 load 429774-1.svg
 load 441368-1.svg
 load 455314-1.xhtml
+load 458453.html
 load extref-test-1.xhtml
--- a/media/libsydneyaudio/src/sydney_audio_sunaudio.c
+++ b/media/libsydneyaudio/src/sydney_audio_sunaudio.c
@@ -288,21 +288,22 @@ sa_stream_write(sa_stream_t *s, const vo
     return SA_SUCCESS;
 
 
  /*
   * Append the new data to the end of our buffer list.
   */
   result = SA_SUCCESS;
   buf = new_buffer(nbytes);
-  memcpy(buf->data,data, nbytes);
 
-  if ( buf == NULL)
+  if (buf == NULL)
     return SA_ERROR_OOM;
 
+  memcpy(buf->data,data, nbytes);
+
   pthread_mutex_lock(&s->mutex);
   if (!s->bl_head)
     s->bl_head = buf;
   else
     s->bl_tail->next = buf;
 
   s->bl_tail = buf;
 
--- a/media/libsydneyaudio/src/sydney_audio_waveapi.c
+++ b/media/libsydneyaudio/src/sydney_audio_waveapi.c
@@ -40,17 +40,17 @@
 #include <windows.h>
 #include <mmreg.h>
 #include <mmsystem.h>
 #include <math.h>
 
 
 // FIX ME: block size and block should be determined based on the OggPlay offset 
 // for audio track
-#define BLOCK_SIZE  2560
+#define BLOCK_SIZE  1024
 #define BLOCK_COUNT 32
 #define DEFAULT_DEVICE_NAME "Default WAVE Device"
 #define DEFAULT_DEVICE WAVE_MAPPER
 
 #define VERBOSE_OUTPUT 1
 
 // INFO: if you get weird compile errors make sure there is no extra chars pass '\' 
 #if defined(VERBOSE_OUTPUT)
@@ -198,17 +198,17 @@ int sa_stream_write(sa_stream_t *s, cons
 /** Query how much can be written without blocking */
 int sa_stream_get_write_size(sa_stream_t *s, size_t *size) {
   unsigned int avail;
   WAVEHDR* current;
 
   ERROR_IF_NO_INIT(s);
 
   EnterCriticalSection(&(s->waveCriticalSection));
-  avail = s->waveFreeBlockCount * BLOCK_SIZE;
+  avail = (s->waveFreeBlockCount-1) * BLOCK_SIZE;
   if (s->waveFreeBlockCount != BLOCK_COUNT) {
     current = &(s->waveBlocks[s->waveCurrentBlock]);
     avail += BLOCK_SIZE - current->dwUser;
   }
   LeaveCriticalSection(&(s->waveCriticalSection));
 
   *size = avail;
 
@@ -485,53 +485,51 @@ int closeAudio(sa_stream_t * s) {
  * \return - completion status
  */
 int writeAudio(sa_stream_t *s, LPSTR data, int bytes) {    
   UINT status;
   WAVEHDR* current;	  
   int remain;
 
   current = &(s->waveBlocks[s->waveCurrentBlock]);
-  
+
   while(bytes > 0) {
+     /*
+     * wait for a block to become free
+     */
+    while (!(s->waveFreeBlockCount))
+      WaitForSingleObject(s->callbackEvent, INFINITE);
+
     /* first make sure the header we're going to use is unprepared */
     if(current->dwFlags & WHDR_PREPARED) {      
         status = waveOutUnprepareHeader(s->hWaveOut, current, sizeof(WAVEHDR));         
         HANDLE_WAVE_ERROR(status, "preparing audio headers for writing");
     }
 		  
     if(bytes < (int)(BLOCK_SIZE - current->dwUser)) {							  	    
 		  memcpy(current->lpData + current->dwUser, data, bytes);
       current->dwUser += bytes;
       break;
     }
-	
+
     /* remain is even as BLOCK_SIZE and dwUser are even too */
     remain = BLOCK_SIZE - current->dwUser;      
   	memcpy(current->lpData + current->dwUser, data, remain);
     bytes -= remain;
     data += remain;
 	  current->dwBufferLength = BLOCK_SIZE;
 	  /* write to audio device */
     waveOutPrepareHeader(s->hWaveOut, current, sizeof(WAVEHDR));
 	  status = waveOutWrite(s->hWaveOut, current, sizeof(WAVEHDR));      
     HANDLE_WAVE_ERROR(status, "writing audio to audio device");
       
     EnterCriticalSection(&(s->waveCriticalSection));
     s->waveFreeBlockCount--;
     LeaveCriticalSection(&(s->waveCriticalSection));
-    /*
-     * wait for a block to become free
-     */
-    while (!(s->waveFreeBlockCount)) {
-        //printf("All audio buffer blocks empty\n");        
-      WaitForSingleObject(s->callbackEvent, INFINITE);
-        //Sleep(10);
-    }		  
-		
+
     /*
      * point to the next block
      */
     (s->waveCurrentBlock)++;
     (s->waveCurrentBlock) %= BLOCK_COUNT;		
 
     current = &(s->waveBlocks[s->waveCurrentBlock]);
     current->dwUser = 0;
--- a/modules/libpref/src/init/all.js
+++ b/modules/libpref/src/init/all.js
@@ -376,16 +376,17 @@ pref("capability.policy.mailnews.*.lowSr
 pref("capability.policy.mailnews.*.nodeValue.get", "noAccess");
 pref("capability.policy.mailnews.*.pathname.get", "noAccess");
 pref("capability.policy.mailnews.*.protocol.get", "noAccess");
 pref("capability.policy.mailnews.*.src.get", "noAccess");
 pref("capability.policy.mailnews.*.substringData.get", "noAccess");
 pref("capability.policy.mailnews.*.text.get", "noAccess");
 pref("capability.policy.mailnews.*.textContent", "noAccess");
 pref("capability.policy.mailnews.*.title.get", "noAccess");
+pref("capability.policy.mailnews.*.wholeText", "noAccess");
 pref("capability.policy.mailnews.DOMException.toString", "noAccess");
 pref("capability.policy.mailnews.HTMLAnchorElement.toString", "noAccess");
 pref("capability.policy.mailnews.HTMLDocument.domain", "noAccess");
 pref("capability.policy.mailnews.HTMLDocument.URL", "noAccess");
 pref("capability.policy.mailnews.*.documentURI", "noAccess");
 pref("capability.policy.mailnews.Location.toString", "noAccess");
 pref("capability.policy.mailnews.Range.toString", "noAccess");
 pref("capability.policy.mailnews.Window.blur", "noAccess");
@@ -1031,16 +1032,21 @@ pref("bidi.characterset", 1);
 pref("bidi.edit.delete_immediately", false);
 
 // Bidi caret movement style:
 // 0 = logical
 // 1 = visual
 // 2 = visual, but logical during selection
 pref("bidi.edit.caret_movement_style", 2);
 
+// Setting this pref to |true| forces Bidi UI menu items and keyboard shortcuts
+// to be exposed, and enables the directional caret hook. By default, only
+// expose it for bidi-associated system locales.
+pref("bidi.browser.ui", false);
+
 // used for double-click word selection behavior. Win will override.
 pref("layout.word_select.eat_space_to_next_word", false);
 pref("layout.word_select.stop_at_punctuation", true);
 
 // controls caret style and word-delete during text selection
 // 0 = use platform default
 // 1 = caret moves and blinks as when there is no selection; word
 //     delete deselects the selection and then deletes word (Windows default)
--- a/storage/src/mozStorageConnection.cpp
+++ b/storage/src/mozStorageConnection.cpp
@@ -72,16 +72,17 @@ PRLogModuleInfo* gStorageLog = nsnull;
 
 #define PREF_TS_SYNCHRONOUS "toolkit.storage.synchronous"
 
 NS_IMPL_THREADSAFE_ISUPPORTS1(mozStorageConnection, mozIStorageConnection)
 
 mozStorageConnection::mozStorageConnection(mozIStorageService* aService) :
     mDBConn(nsnull)
 ,   mAsyncExecutionMutex(nsAutoLock::NewLock("AsyncExecutionMutex"))
+,   mAsyncExecutionThreadShuttingDown(PR_FALSE)
 ,   mTransactionMutex(nsAutoLock::NewLock("TransactionMutex"))
 ,   mTransactionInProgress(PR_FALSE)
 ,   mFunctionsMutex(nsAutoLock::NewLock("FunctionsMutex"))
 ,   mProgressHandlerMutex(nsAutoLock::NewLock("ProgressHandlerMutex"))
 ,   mProgressHandler(nsnull)
 ,   mStorageService(aService)
 {
     mFunctions.Init();
@@ -225,24 +226,28 @@ mozStorageConnection::Close()
 #ifdef PR_LOGGING
     nsCAutoString leafName(":memory");
     if (mDatabaseFile)
         (void)mDatabaseFile->GetNativeLeafName(leafName);
     PR_LOG(gStorageLog, PR_LOG_NOTICE, ("Opening connection to '%s'",
                                         leafName.get()));
 #endif
 
-    // The shutdown call runs any pending events to completion, so we want to
-    // do this before closing the connection.
+    // Flag that we are shutting down the async thread, so that
+    // getAsyncExecutionTarget knows not to expose/create the async thread.
     {
         nsAutoLock mutex(mAsyncExecutionMutex);
-        if (mAsyncExecutionThread) {
-            mAsyncExecutionThread->Shutdown();
-            mAsyncExecutionThread = nsnull;
-        }
+        mAsyncExecutionThreadShuttingDown = PR_TRUE;
+    }
+    // Shutdown the async thread if it exists.  (Because we just set the flag,
+    // we are the only code that is going to be touching this variable from here
+    // on out.)
+    if (mAsyncExecutionThread) {
+        mAsyncExecutionThread->Shutdown();
+        mAsyncExecutionThread = nsnull;
     }
 
 #ifdef DEBUG
     // Notify about any non-finalized statements.
     sqlite3_stmt *stmt = NULL;
     while (stmt = sqlite3_next_stmt(mDBConn, stmt)) {
         char *msg = PR_smprintf("SQL statement '%s' was not finalized",
                                 sqlite3_sql(stmt));
@@ -945,16 +950,21 @@ mozStorageConnection::ProgressHandler()
 /**
  ** Other bits
  **/
 
 already_AddRefed<nsIEventTarget>
 mozStorageConnection::getAsyncExecutionTarget()
 {
     nsAutoLock mutex(mAsyncExecutionMutex);
+    
+    // If we are shutting down the asynchronous thread, don't hand out any more
+    // references to the thread. 
+    if (mAsyncExecutionThreadShuttingDown)
+        return nsnull;
 
     if (!mAsyncExecutionThread) {
         nsresult rv = NS_NewThread(getter_AddRefs(mAsyncExecutionThread));
         if (NS_FAILED(rv)) {
             NS_WARNING("Failed to create async thread.");
             return nsnull;
         }
     }
--- a/storage/src/mozStorageConnection.h
+++ b/storage/src/mozStorageConnection.h
@@ -110,16 +110,23 @@ protected:
     PRLock *mAsyncExecutionMutex;
 
     /**
      * Lazily created thread for asynchronous statement execution.  Consumers
      * should use getAsyncExecutionTarget rather than directly accessing this
      * field.
      */
     nsCOMPtr<nsIThread> mAsyncExecutionThread;
+    /**
+     * Set to true by Close() prior to actually shutting down the thread.  This
+     * lets getAsyncExecutionTarget() know not to hand out any more thread
+     * references (or to create the thread in the first place).  This variable
+     * should be accessed while holding the mAsyncExecutionMutex.
+     */
+    PRBool mAsyncExecutionThreadShuttingDown;
 
     PRLock *mTransactionMutex;
     PRBool mTransactionInProgress;
 
     PRLock *mFunctionsMutex;
     nsInterfaceHashtable<nsCStringHashKey, nsISupports> mFunctions;
 
     PRLock *mProgressHandlerMutex;
--- a/storage/src/mozStorageService.cpp
+++ b/storage/src/mozStorageService.cpp
@@ -105,35 +105,56 @@ mozStorageService::XPConnect()
     (void)CallGetService(nsIXPConnect::GetCID(), &sXPConnect);
     NS_ASSERTION(sXPConnect, "Could not get XPConnect!");
   }
   return sXPConnect;
 }
 
 mozStorageService::~mozStorageService()
 {
+    // Shutdown the sqlite3 API.  Warn if shutdown did not turn out okay, but
+    // there is nothing actionable we can do in that case.
+    int rc = sqlite3_shutdown();
+    if (rc != SQLITE_OK)
+        NS_WARNING("sqlite3 did not shutdown cleanly.");
+    
     gStorageService = nsnull;
     PR_DestroyLock(mLock);
 
     NS_IF_RELEASE(sXPConnect);
     sXPConnect = nsnull;
 }
 
 nsresult
 mozStorageService::Init()
 {
     mLock = PR_NewLock();
     if (!mLock)
         return NS_ERROR_OUT_OF_MEMORY;
+    
+    // Disable memory allocation statistic collection, improving performance.
+    // This must be done prior to a call to sqlite3_initialize to have any
+    // effect.
+    int rc = sqlite3_config(SQLITE_CONFIG_MEMSTATUS, 0);
+    if (rc != SQLITE_OK)
+        return ConvertResultCode(rc);
+    
+    // Explicitly initialize sqlite3.  Although this is implicitly called by
+    // various sqlite3 functions (and the sqlite3_open calls in our case),
+    // the documentation suggests calling this directly.  So we do.
+    rc = sqlite3_initialize();
+    if (rc != SQLITE_OK)
+        return ConvertResultCode(rc);
 
     // This makes multiple connections to the same database share the same pager
     // cache.  We do not need to lock here with mLock because this function is
     // only ever called from mozStorageService::GetSingleton, which will only
     // call this function once, and will not return until this function returns.
-    int rc = sqlite3_enable_shared_cache(1);
+    // (It does not matter where this is called relative to sqlite3_initialize.)
+    rc = sqlite3_enable_shared_cache(1);
     if (rc != SQLITE_OK)
         return ConvertResultCode(rc);
 
     return NS_OK;
 }
 
 #ifndef NS_APP_STORAGE_50_FILE
 #define NS_APP_STORAGE_50_FILE "UStor"
--- a/testing/mochitest/runtests.py.in
+++ b/testing/mochitest/runtests.py.in
@@ -456,16 +456,19 @@ def maybeForceLeakThreshold(options):
   if options.leakThreshold == INFINITY:
     if options.chrome:
       # We don't leak running the --chrome tests.
       options.leakThreshold = 0
     elif options.browserChrome:
       # We still leak a nondeterministic amount running browser-chrome tests.
       # But we are close to 0 (bug), so start to prevent/detect regressions. (Bug 460548)
       options.leakThreshold = 74000
+    elif options.a11y:
+      # We don't leak running the --a11y tests.
+      options.leakThreshold = 0
     else:
       # Normal Mochitests: no leaks.
       options.leakThreshold = 0
 
 def makeTestConfig(options):
   "Creates a test configuration file for customizing test execution."
   def boolString(b):
     if b:
--- a/toolkit/components/places/src/nsNavHistory.h
+++ b/toolkit/components/places/src/nsNavHistory.h
@@ -843,17 +843,17 @@ protected:
   nsresult InitializeIdleTimer();
   static void IdleTimerCallback(nsITimer* aTimer, void* aClosure);
   nsresult OnIdle();
 
   PRInt64 mTagsFolder;
 
   PRBool mInPrivateBrowsing;
 
-  PRBool mDatabaseStatus;
+  PRUint16 mDatabaseStatus;
 };
 
 /**
  * Shared between the places components, this function binds the given URI as
  * UTF8 to the given parameter for the statement.
  */
 nsresult BindStatementURI(mozIStorageStatement* statement, PRInt32 index,
                           nsIURI* aURI);
--- a/xpcom/build/nsXPComInit.cpp
+++ b/xpcom/build/nsXPComInit.cpp
@@ -294,44 +294,47 @@ static PRBool CheckUpdateFile()
                                            NS_GET_IID(nsIFile),
                                            getter_AddRefs(compregFile));
 
     if (NS_FAILED(rv)) {
         NS_WARNING("Getting NS_XPCOM_COMPONENT_REGISTRY_FILE failed");
         return PR_FALSE;
     }
 
-    PRBool exists;
-    if (NS_FAILED(compregFile->Exists(&exists)) || !exists)
+    PRInt64 compregModTime;
+    rv = compregFile->GetLastModifiedTime(&compregModTime);
+    if (NS_FAILED(rv))
         return PR_TRUE;
-
-    PRInt64 compregModTime;
-    compregFile->GetLastModifiedTime(&compregModTime);
-
+    
     nsCOMPtr<nsIFile> file;
     rv = nsDirectoryService::gService->Get(NS_XPCOM_CURRENT_PROCESS_DIR, 
                                            NS_GET_IID(nsIFile), 
                                            getter_AddRefs(file));
 
     if (NS_FAILED(rv)) {
         NS_WARNING("Getting NS_XPCOM_CURRENT_PROCESS_DIR failed");
         return PR_FALSE;
     }
 
     file->AppendNative(nsDependentCString(".autoreg"));
-    
-    file->Exists(&exists);
-    if (!exists)
+
+    // superfluous cast
+    PRInt64 nowTime = PR_Now() / PR_USEC_PER_MSEC;
+    PRInt64 autoregModTime;
+    rv = file->GetLastModifiedTime(&autoregModTime);
+    if (NS_FAILED(rv))
         goto next;
 
-    PRInt64 autoregModTime;
-    file->GetLastModifiedTime(&autoregModTime);
-
-    if (LL_CMP(autoregModTime, >, compregModTime))
-        return PR_TRUE;
+    if (autoregModTime > compregModTime) {
+        if (autoregModTime < nowTime) {
+            return PR_TRUE;
+        } else {
+            NS_WARNING("Screwy timestamps, ignoring .autoreg");
+        }
+    }
 
 next:
     nsCOMPtr<nsIFile> greFile;
     rv = nsDirectoryService::gService->Get(NS_GRE_DIR,
                                            NS_GET_IID(nsIFile),
                                            getter_AddRefs(greFile));
 
     if (NS_FAILED(rv)) {
@@ -341,23 +344,25 @@ next:
 
     greFile->AppendNative(nsDependentCString(".autoreg"));
 
     PRBool equals;
     rv = greFile->Equals(file, &equals);
     if (NS_SUCCEEDED(rv) && equals)
         return PR_FALSE;
 
-    greFile->Exists(&exists);
-    if (!exists)
+    rv = greFile->GetLastModifiedTime(&autoregModTime);
+    if (NS_FAILED(rv))
         return PR_FALSE;
 
-    greFile->GetLastModifiedTime(&autoregModTime);
-
-    return LL_CMP(autoregModTime, >, compregModTime);
+    if (autoregModTime > nowTime) {
+        NS_WARNING("Screwy timestamps, ignoring .autoreg");
+        return PR_FALSE;
+    }
+    return autoregModTime > compregModTime; 
 }
 
 
 nsComponentManagerImpl* nsComponentManagerImpl::gComponentManager = NULL;
 PRBool gXPCOMShuttingDown = PR_FALSE;
 
 // For each class that wishes to support nsIClassInfo, add a line like this
 // NS_DECL_CLASSINFO(nsMyClass)
--- a/xpcom/reflect/xptcall/src/md/unix/Makefile.in
+++ b/xpcom/reflect/xptcall/src/md/unix/Makefile.in
@@ -95,16 +95,22 @@ endif
 endif
 #
 # OpenBSD/amd64
 #
 ifeq ($(OS_ARCH)$(OS_TEST),OpenBSDx86_64)
 CPPSRCS		:= xptcinvoke_amd64_openbsd.cpp xptcstubs_amd64_openbsd.cpp
 endif
 #
+# FreeBSD/amd64
+#
+ifeq ($(OS_ARCH)$(OS_TEST),FreeBSDx86_64)
+CPPSRCS		:= xptcinvoke_amd64_linux.cpp xptcstubs_amd64_linux.cpp
+endif
+#
 # BeOS/Intel (uses the same unixish_x86 code)
 #
 ifeq ($(OS_ARCH)$(OS_TEST),BeOSBePC)
 CPPSRCS		:= xptcinvoke_unixish_x86.cpp xptcstubs_unixish_x86.cpp
 endif
 #
 # Neutrino/Intel (uses the same unixish_x86 code)
 #