Merge from mozilla-central.
authorDavid Anderson <danderson@mozilla.com>
Wed, 04 Apr 2012 13:40:49 -0700
changeset 109680 4a9f1b21e58c21aa04644b46655fa87876373674
parent 109679 ec53c5d4c3dd2d794c2b7a64b2377c7bd4558dbf (current diff)
parent 92791 3a0940f904553197a95534bf8ac153bc691766b4 (diff)
child 109681 4ea50300a5ed1ebe5edd58ba9d695ad868e9cec9
push id2248
push userakeybl@mozilla.com
push dateMon, 08 Oct 2012 19:23:44 +0000
treeherdermozilla-aurora@118a3b748323 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone14.0a1
Merge from mozilla-central.
accessible/src/mac/mozTextAccessible.mm
build/mobile/devicemanagerSUT.py
configure.in
content/base/src/nsScriptElement.cpp
content/base/test/Makefile.in
content/canvas/src/WebGLContext.h
content/canvas/src/WebGLContextGL.cpp
content/canvas/src/WebGLContextUtils.cpp
content/html/content/src/nsHTMLFormElement.cpp
content/html/document/src/nsHTMLDocument.cpp
content/smil/nsSMILAnimationFunction.cpp
content/smil/nsSMILTimedElement.cpp
content/svg/content/src/SVGTransformListParser.cpp
content/xml/document/src/nsXMLContentSink.cpp
content/xul/document/src/nsXULContentSink.cpp
content/xul/templates/src/nsXULTemplateBuilder.cpp
content/xul/templates/src/nsXULTemplateBuilder.h
content/xul/templates/src/nsXULTreeBuilder.cpp
dom/base/nsDOMClassInfo.cpp
dom/base/nsGlobalWindow.cpp
dom/bindings/parser/__init__.py
dom/ipc/ContentParent.cpp
dom/ipc/ContentParent.h
dom/plugins/base/nsNPAPIPlugin.cpp
dom/plugins/base/nsNPAPIPluginInstance.cpp
dom/plugins/base/nsPluginDirServiceProvider.cpp
dom/plugins/base/nsPluginHost.cpp
dom/plugins/base/nsPluginHost.h
dom/plugins/base/nsPluginSafety.h
dom/plugins/base/nsPluginTags.cpp
dom/plugins/base/nsPluginTags.h
dom/plugins/ipc/PluginModuleParent.cpp
dom/src/geolocation/nsGeolocation.cpp
dom/src/storage/nsDOMStorage.cpp
dom/system/nsDeviceSensors.cpp
editor/composer/src/nsComposerDocumentCommands.cpp
editor/libeditor/html/nsHTMLCSSUtils.cpp
editor/libeditor/html/nsHTMLDataTransfer.cpp
extensions/spellcheck/hunspell/src/mozHunspell.cpp
extensions/spellcheck/src/mozEnglishWordUtils.cpp
gfx/thebes/gfxFont.h
gfx/thebes/gfxWindowsPlatform.cpp
image/src/RasterImage.cpp
intl/uconv/src/nsTextToSubURI.cpp
js/src/configure.in
js/src/jsarray.cpp
js/src/jscntxt.h
js/src/jsexn.cpp
js/src/jsgc.cpp
js/src/jsgcmark.cpp
js/src/jstypedarray.cpp
layout/base/nsBidi.cpp
layout/base/nsPresContext.cpp
layout/generic/nsGfxScrollFrame.cpp
layout/generic/nsGfxScrollFrame.h
layout/generic/nsHTMLReflowMetrics.h
layout/printing/nsPrintEngine.cpp
mobile/android/base/AndroidManifest.xml.in
mobile/android/base/GeckoApp.java
mobile/android/base/Makefile.in
modules/libpref/public/Preferences.h
modules/libpref/src/Preferences.cpp
modules/libpref/src/init/all.js
modules/libpref/src/prefapi.cpp
netwerk/protocol/http/nsHttpAuthCache.cpp
netwerk/streamconv/converters/mozTXTToHTMLConv.cpp
toolkit/content/license.html
uriloader/exthandler/mac/nsOSHelperAppService.mm
widget/cocoa/nsDeviceContextSpecX.mm
widget/cocoa/nsPrintDialogX.mm
widget/windows/nsClipboard.cpp
widget/windows/nsFilePicker.cpp
xpcom/ds/nsHashtable.cpp
xpcom/ds/nsVariant.cpp
xpcom/idl-parser/xpidl.py
xpcom/io/nsBinaryStream.cpp
xpcom/io/nsEscape.cpp
--- a/accessible/src/mac/mozTextAccessible.mm
+++ b/accessible/src/mac/mozTextAccessible.mm
@@ -325,39 +325,40 @@ ToNSString(id aValue)
 - (NSNumber*)caretLineNumber
 {
   PRInt32 lineNumber = mGeckoTextAccessible ?
     mGeckoTextAccessible->CaretLineNumber() - 1 : -1;
 
   return (lineNumber >= 0) ? [NSNumber numberWithInt:lineNumber] : nil;
 }
 
-- (void)setText:(NSString*)newString
+- (void)setText:(NSString*)aNewString
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
 
   if (mGeckoEditableTextAccessible) {
-    mGeckoEditableTextAccessible->SetTextContents(NS_ConvertUTF8toUTF16([newString UTF8String]));
+    nsString text;
+    nsCocoaUtils::GetStringForNSString(aNewString, text);
+    mGeckoEditableTextAccessible->SetTextContents(text);
   }
 
   NS_OBJC_END_TRY_ABORT_BLOCK;
 }
 
 - (NSString*)text
 {
   if (!mGeckoTextAccessible)
     return nil;
     
   nsAutoString text;
-  nsresult rv = 
-    mGeckoTextAccessible->GetText(0, nsIAccessibleText::TEXT_OFFSET_END_OF_TEXT,
-				  text);
-  NS_ENSURE_SUCCESS(rv, nil);
+  nsresult rv = mGeckoTextAccessible->
+    GetText(0, nsIAccessibleText::TEXT_OFFSET_END_OF_TEXT, text);
+  NS_ENSURE_SUCCESS(rv, @"");
 
-  return text.IsEmpty() ? nil : nsCocoaUtils::ToNSString(text);
+  return nsCocoaUtils::ToNSString(text);
 }
 
 - (long)textLength
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
 
   return mGeckoTextAccessible ? mGeckoTextAccessible->CharacterCount() : 0;
 
@@ -387,17 +388,17 @@ ToNSString(id aValue)
 
   if (mGeckoTextAccessible) {
     PRInt32 start, end;
     start = end = 0;
     mGeckoTextAccessible->GetSelectionBounds(0, &start, &end);
     if (start != end) {
       nsAutoString selText;
       mGeckoTextAccessible->GetText(start, end, selText);
-      return selText.IsEmpty() ? nil : [NSString stringWithCharacters:selText.BeginReading() length:selText.Length()];
+      return nsCocoaUtils::ToNSString(selText);
     }
   }
   return nil;
 
   NS_OBJC_END_TRY_ABORT_BLOCK_NIL;
 }
 
 - (NSValue*)selectedTextRange
--- a/allmakefiles.sh
+++ b/allmakefiles.sh
@@ -1,45 +1,13 @@
 #! /bin/sh
 #
-# ***** 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) 1999
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either the GNU General Public License Version 2 or later (the "GPL"), or
-# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this file,
+# You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # allmakefiles.sh - List of all makefiles.
 #   Appends the list of makefiles to the variable, MAKEFILES.
 #   There is no need to rerun autoconf after adding makefiles.
 #   You only need to run configure.
 
 # Turn on exit on error
 set -o errexit
@@ -62,17 +30,16 @@ build/Makefile
 build/pgo/Makefile
 build/pgo/blueprint/Makefile
 build/pgo/js-input/Makefile
 config/Makefile
 config/autoconf.mk
 config/nspr/Makefile
 config/doxygen.cfg
 config/expandlibs_config.py
-config/tests/src-simple/Makefile
 mfbt/Makefile
 probes/Makefile
 extensions/Makefile
 "
 
 if [ ! "$LIBXUL_SDK" ]; then
   if [ "$STLPORT_SOURCES" ]; then
     add_makefiles "
@@ -135,16 +102,19 @@ if [ "$ENABLE_MARIONETTE" ]; then
     testing/marionette/components/Makefile
     testing/marionette/tests/Makefile
   "
 fi
 
 if [ "$ENABLE_TESTS" ]; then
   add_makefiles "
     build/autoconf/test/Makefile
+    config/makefiles/test/Makefile
+    config/tests/makefiles/autodeps/Makefile
+    config/tests/src-simple/Makefile
   "
   if [ ! "$LIBXUL_SDK" ]; then 
     add_makefiles "
       mozglue/tests/Makefile
     "
   fi
   if [ "$_MSC_VER" -a "$OS_TEST" != "x86_64" ]; then
     add_makefiles "
--- a/b2g/app/Makefile.in
+++ b/b2g/app/Makefile.in
@@ -122,30 +122,34 @@ clean clobber repackage::
 	rm -rf $(DIST)/$(APP_NAME).app
 
 ifdef LIBXUL_SDK
 APPFILES = Resources
 else
 APPFILES = MacOS
 endif
 
-libs repackage::
-	mkdir -p $(DIST)/$(APP_NAME).app/Contents/MacOS
+libs-preqs = \
+  $(call mkdir_deps,$(DIST)/$(APP_NAME).app/Contents/MacOS) \
+  $(call mkdir_deps,$(DIST)/$(APP_NAME).app/Contents/Resources/$(AB).lproj) \
+  $(NULL)
+
+.PHONY: repackage
+libs repackage:: $(libs-preqs)
 	rsync -a --exclude "*.in" $(srcdir)/macbuild/Contents $(DIST)/$(APP_NAME).app --exclude English.lproj
-	mkdir -p $(DIST)/$(APP_NAME).app/Contents/Resources/$(AB).lproj
 	rsync -a --exclude "*.in" $(srcdir)/macbuild/Contents/Resources/English.lproj/ $(DIST)/$(APP_NAME).app/Contents/Resources/$(AB).lproj
 	sed -e "s/%MOZ_APP_VERSION%/$(MOZ_APP_VERSION)/" -e "s/%MOZ_APP_NAME%/$(MOZ_APP_NAME)/" -e "s/%APP_VERSION%/$(APP_VERSION)/" -e "s/%APP_NAME%/$(APP_NAME)/" -e "s/%APP_BINARY%/$(APP_BINARY)/" $(srcdir)/macbuild/Contents/Info.plist.in > $(DIST)/$(APP_NAME).app/Contents/Info.plist
 	sed -e "s/%APP_VERSION%/$(APP_VERSION)/" -e "s/%APP_NAME%/$(APP_NAME)/" $(srcdir)/macbuild/Contents/Resources/English.lproj/InfoPlist.strings.in | iconv -f UTF-8 -t UTF-16 > $(DIST)/$(APP_NAME).app/Contents/Resources/$(AB).lproj/InfoPlist.strings
 	rsync -a $(DIST)/bin/ $(DIST)/$(APP_NAME).app/Contents/$(APPFILES)
 	$(RM) $(DIST)/$(APP_NAME).app/Contents/$(APPFILES)/mangle $(DIST)/$(APP_NAME).app/Contents/$(APPFILES)/shlibsign
 ifdef LIBXUL_SDK
 	cp $(LIBXUL_DIST)/bin/xulrunner$(BIN_SUFFIX) $(DIST)/$(APP_NAME).app/Contents/MacOS/$(APP_BINARY)
 	rsync -a --exclude nsinstall --copy-unsafe-links $(LIBXUL_DIST)/XUL.framework $(DIST)/$(APP_NAME).app/Contents/Frameworks
 else
-	rm -f $(DIST)/$(APP_NAME).app/Contents/MacOS/$(PROGRAM)
+	$(RM) $(DIST)/$(APP_NAME).app/Contents/MacOS/$(PROGRAM)
 	rsync -aL $(PROGRAM) $(DIST)/$(APP_NAME).app/Contents/MacOS
 endif
 	printf "APPLMOZB" > $(DIST)/$(APP_NAME).app/Contents/PkgInfo
 
 else # MOZ_WIDGET_TOOLKIT != cocoa
 
 libs::
 ifdef LIBXUL_SDK
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -407,21 +407,16 @@ pref("browser.dom.window.dump.enabled", 
 // installable apps or wifi support.
 pref("security.fileuri.strict_origin_policy", false);
 
 // Temporarily force-enable GL compositing.  This is default-disabled
 // deep within the bowels of the widgetry system.  Remove me when GL
 // compositing isn't default disabled in widget/android.
 pref("layers.acceleration.force-enabled", true);
 
-// screen.enabled and screen.brightness properties.
-pref("dom.screenEnabledProperty.enabled", true);
-pref("dom.screenBrightnessProperty.enabled", true);
-pref("dom.mozScreenWhitelist", "http://homescreen.gaiamobile.org,http://settings.gaiamobile.org");
-
 // handle links targeting new windows
 // 1=current window/tab, 2=new window, 3=new tab in most recent window
 pref("browser.link.open_newwindow", 3);
 
 // 0: no restrictions - divert everything
 // 1: don't divert window.open at all
 // 2: don't divert window.open with features
 pref("browser.link.open_newwindow.restriction", 0);
--- a/b2g/chrome/content/shell.js
+++ b/b2g/chrome/content/shell.js
@@ -280,33 +280,33 @@ var shell = {
 
 (function PowerManager() {
   // This will eventually be moved to content, so use content API as
   // much as possible here. TODO: Bug 738530
   let power = navigator.mozPower;
   let idleHandler = function idleHandler(subject, topic, time) {
     if (topic === "idle") {
       if (power.getWakeLockState("screen") != "locked-foreground") {
-        screen.mozEnabled = false;
+        navigator.mozPower.screenEnabled = false;
       }
     }
   }
   let wakeLockHandler = function wakeLockHandler(topic, state) {
     // Turn off the screen when no one needs the it or all of them are
     // invisible, otherwise turn the screen on. Note that the CPU
     // might go to sleep as soon as the screen is turned off and
     // acquiring wake lock will not bring it back (actually the code
     // is not executed at all).
     if (topic == "screen") {
       if (state != "locked-foreground") {
         if (Services.idle.idleTime > idleTimeout*1000) {
-          screen.mozEnabled = false;
+          navigator.mozPower.screenEnabled = false;
         }
       } else {
-        screen.mozEnabled = true;
+        navigator.mozPower.screenEnabled = true;
       }
     }
   }
   let idleTimeout = Services.prefs.getIntPref("power.screen.timeout");
   let request = navigator.mozSettings.getLock().get("power.screen.timeout");
   request.onsuccess = function onSuccess() {
     idleTimeout = request.result["power.screen.timeout"] || idleTimeout;
     if (idleTimeout) {
--- a/browser/components/privatebrowsing/test/browser/Makefile.in
+++ b/browser/components/privatebrowsing/test/browser/Makefile.in
@@ -51,16 +51,17 @@ include $(topsrcdir)/config/rules.mk
 		browser_privatebrowsing_commandline_toggle.js \
 		browser_privatebrowsing_crh.js \
 		browser_privatebrowsing_fastswitch.js \
 		browser_privatebrowsing_findbar.js \
 		browser_privatebrowsing_forgetthissite.js \
 		browser_privatebrowsing_geoprompt.js \
 		browser_privatebrowsing_geoprompt_page.html \
 		browser_privatebrowsing_import.js \
+		browser_privatebrowsing_lastpbcontextexited.js \
 		browser_privatebrowsing_localStorage.js \
 		browser_privatebrowsing_localStorage_page1.html \
 		browser_privatebrowsing_localStorage_page2.html \
 		browser_privatebrowsing_newwindow_stopcmd.js \
 		browser_privatebrowsing_opendir.js \
 		browser_privatebrowsing_openlocation.js \
 		browser_privatebrowsing_pageinfo.js \
 		browser_privatebrowsing_placestitle.js \
new file mode 100644
--- /dev/null
+++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_lastpbcontextexited.js
@@ -0,0 +1,66 @@
+/* ***** 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 Private Browsing Tests.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2012
+ * 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 ***** */
+
+function test() {
+  // We need to open a new window for this so that its docshell would get destroyed
+  // when clearing the PB mode flag.
+  let newWin = window.openDialog("chrome://browser/content/", "_blank", "chrome,all,dialog=no");
+  waitForExplicitFinish();
+  SimpleTest.waitForFocus(function() {
+    let notificationCount = 0;
+    let observer = {
+      observe: function(aSubject, aTopic, aData) {
+        is(aTopic, "last-pb-context-exited", "Correct topic should be dispatched");
+        ++notificationCount;
+      }
+    };
+    Services.obs.addObserver(observer, "last-pb-context-exited", false);
+    newWin.gPrivateBrowsingUI.privateWindow = true;
+    SimpleTest.is(notificationCount, 0, "last-pb-context-exited should not be fired yet");
+    newWin.gPrivateBrowsingUI.privateWindow = false;
+    newWin.close();
+    newWin = null;
+    window.QueryInterface(Ci.nsIInterfaceRequestor)
+          .getInterface(Ci.nsIDOMWindowUtils)
+          .garbageCollect(); // Make sure that the docshell is destroyed
+    SimpleTest.is(notificationCount, 1, "last-pb-context-exited should be fired once");
+    Services.obs.removeObserver(observer, "last-pb-context-exited", false);
+
+    // cleanup
+    gPrefService.clearUserPref("browser.privatebrowsing.keep_current_session");
+    finish();
+  }, newWin);
+}
--- a/build/autoconf/compiler-opts.m4
+++ b/build/autoconf/compiler-opts.m4
@@ -77,8 +77,54 @@ if test "$GNU_CC" -a "$GCC_USE_GNU_LD" -
         fi
         rm -rf conftest*])
     if test "$GC_SECTIONS_BREAKS_DEBUG_RANGES" = no; then
         DSO_LDOPTS="$DSO_LDOPTS -Wl,--gc-sections"
     fi
 fi
 
 ])
+
+dnl GCC and clang will fail if given an unknown warning option like -Wfoobar. 
+dnl But later versions won't fail if given an unknown negated warning option
+dnl like -Wno-foobar.  So when we are check for support of negated warning 
+dnl options, we actually test the positive form, but add the negated form to 
+dnl the flags variable.
+
+AC_DEFUN([MOZ_C_SUPPORTS_WARNING],
+[
+    AC_CACHE_CHECK(whether the C compiler supports $1$2, $3,
+        [
+            AC_LANG_SAVE
+            AC_LANG_C
+            _SAVE_CFLAGS="$CFLAGS"
+            CFLAGS="$CFLAGS -Werror -W$2"
+            AC_TRY_COMPILE([],
+                           [return(0);],
+                           $3="yes",
+                           $3="no")
+            CFLAGS="$_SAVE_CFLAGS"
+            AC_LANG_RESTORE
+        ])
+    if test "${$3}" = "yes"; then
+        _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} $1$2"
+    fi
+])
+
+AC_DEFUN([MOZ_CXX_SUPPORTS_WARNING],
+[
+    AC_CACHE_CHECK(whether the C++ compiler supports $1$2, $3,
+        [
+            AC_LANG_SAVE
+            AC_LANG_CPLUSPLUS
+            _SAVE_CXXFLAGS="$CXXFLAGS"
+            CXXFLAGS="$CXXFLAGS -Werror -W$2"
+            AC_TRY_COMPILE([],
+                           [return(0);],
+                           $3="yes",
+                           $3="no")
+            CXXFLAGS="$_SAVE_CXXFLAGS"
+            AC_LANG_RESTORE
+        ])
+    if test "${$3}" = "yes"; then
+        _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} $1$2"
+    fi
+])
--- a/build/mobile/devicemanagerSUT.py
+++ b/build/mobile/devicemanagerSUT.py
@@ -194,40 +194,42 @@ class DeviceManagerSUT(DeviceManager):
     shouldCloseSocket = False
     recvGuard = 1000
 
     if not self._sock:
       try:
         if self.debug >= 1:
           print "reconnecting socket"
         self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-      except:
+      except socket.error, msg:
         self._sock = None
-        raise AgentError("unable to create socket")
+        raise AgentError("unable to create socket: "+str(msg))
 
       try:
         self._sock.connect((self.host, int(self.port)))
         self._sock.recv(1024)
-      except:
+      except socket.error, msg:
         self._sock.close()
         self._sock = None
-        raise AgentError("unable to connect socket")
+        raise AgentError("unable to connect socket: "+str(msg))
 
     for cmd in cmdlist:
       if newline: cmd += '\r\n'
 
       try:
         numbytes = self._sock.send(cmd)
         if (numbytes != len(cmd)):
           raise AgentError("ERROR: our cmd was %s bytes and we only sent %s" % (len(cmd),
                                                                                 numbytes))
         if (self.debug >= 4): print "send cmd: " + str(cmd)
-      except:
+      except socket.error, msg:
         self._sock.close()
         self._sock = None
+        if self.debug >= 1:
+          print "Error sending data to socket. cmd="+str(cmd)+"; err="+str(msg)
         return False
 
       # Check if the command should close the socket
       shouldCloseSocket = self._shouldCmdCloseSocket(cmd)
 
       # Handle responses from commands
       if (self._cmdNeedsResponse(cmd)):
         found = False
@@ -237,20 +239,20 @@ class DeviceManagerSUT(DeviceManager):
         while (found == False and (loopguard < recvGuard)):
           temp = ''
           if (self.debug >= 4): print "recv'ing..."
 
           # Get our response
           try:
             temp = self._sock.recv(1024)
             if (self.debug >= 4): print "response: " + str(temp)
-          except:
+          except socket.error, msg:
             self._sock.close()
             self._sock = None
-            raise AgentError("Error receiving data from socket")
+            raise AgentError("Error receiving data from socket. cmd="+str(cmd)+"; err="+str(msg))
 
           data += temp
 
           # If something goes wrong in the agent it will send back a string that
           # starts with '##AGENT-ERROR##'
           if self.agentErrorRE.match(data):
             raise AgentError("Agent Error processing command: %s" % cmd, fatal=True)
 
--- a/build/win32/Makefile.in
+++ b/build/win32/Makefile.in
@@ -30,20 +30,20 @@
 # 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 *****
 
-DEPTH = ../..
+DEPTH     = ../..
 topsrcdir = @top_srcdir@
-srcdir = @srcdir@
-VPATH = @srcdir@
+srcdir    = @srcdir@
+VPATH     = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 NO_PROFILE_GUIDED_OPTIMIZE = 1
 
 ifdef _MSC_VER
 ifneq ($(OS_TEST),x86_64)
 TEST_DIRS += vmwarerecordinghelper
@@ -97,18 +97,21 @@ endif
 ifeq (1700,$(_MSC_VER))
 REDIST_FILES = \
   msvcp110.dll \
   msvcr110.dll \
   $(NULL)
 endif
 
 ifdef REDIST_FILES
-libs::
-	mkdir -p $(FINAL_TARGET)
+libs-preqs = \
+  $(call mkdir_deps,$(FINAL_TARGET)) \
+  $(NULL)
+
+libs:: $(libs-preqs)
 	install --preserve-timestamps $(foreach f,$(REDIST_FILES),"$(WIN32_REDIST_DIR)"/$(f)) $(FINAL_TARGET)
 endif
 
 endif # ! MOZ_DEBUG
 endif # WIN32_REDIST_DIR
 
 # run the binscope tool to make sure the binary and all libraries
 # are using all available Windows OS-level security mechanisms
--- a/client.mk
+++ b/client.mk
@@ -96,17 +96,16 @@ endif
 # try to find autoconf 2.13 - discard errors from 'which'
 # MacOS X 10.4 sends "no autoconf*" errors to stdout, discard those via grep
 AUTOCONF ?= $(shell which autoconf-2.13 autoconf2.13 autoconf213 2>/dev/null | grep -v '^no autoconf' | head -1)
 
 ifeq (,$(strip $(AUTOCONF)))
 AUTOCONF=$(error Could not find autoconf 2.13)
 endif
 
-MKDIR := mkdir
 SH := /bin/sh
 PERL ?= perl
 PYTHON ?= python
 
 CONFIG_GUESS_SCRIPT := $(wildcard $(TOPSRCDIR)/build/autoconf/config.guess)
 ifdef CONFIG_GUESS_SCRIPT
   CONFIG_GUESS = $(shell $(CONFIG_GUESS_SCRIPT))
 endif
@@ -176,16 +175,19 @@ OBJDIR_TARGETS = install export libs cle
 
 #######################################################################
 # Rules
 
 # The default rule is build
 build::
 	$(MAKE) -f $(TOPSRCDIR)/client.mk $(if $(MOZ_PGO),profiledbuild,realbuild)
 
+# Define mkdir
+include $(TOPSRCDIR)/config/makefiles/makeutils.mk
+include $(TOPSRCDIR)/config/makefiles/autotargets.mk
 
 # Print out any options loaded from mozconfig.
 all realbuild clean depend distclean export libs install realclean::
 	@if test -f .mozconfig.out; then \
 	  cat .mozconfig.out; \
 	  rm -f .mozconfig.out; \
 	else true; \
 	fi
@@ -311,21 +313,23 @@ CONFIGURE_ENV_ARGS += \
 ifeq ($(TOPSRCDIR),$(OBJDIR))
   CONFIGURE = ./configure
 else
   CONFIGURE = $(TOPSRCDIR)/configure
 endif
 
 configure-files: $(CONFIGURES)
 
-configure:: configure-files
-ifdef MOZ_BUILD_PROJECTS
-	@if test ! -d $(MOZ_OBJDIR); then $(MKDIR) $(MOZ_OBJDIR); else true; fi
-endif
-	@if test ! -d $(OBJDIR); then $(MKDIR) $(OBJDIR); else true; fi
+configure-preqs = \
+  configure-files \
+  $(call mkdir_deps,$(OBJDIR)) \
+  $(if $(MOZ_BUILD_PROJECTS),$(call mkdir_deps,$(MOZ_OBJDIR))) \
+  $(NULL)
+
+configure:: $(configure-preqs)
 	@echo cd $(OBJDIR);
 	@echo $(CONFIGURE) $(CONFIGURE_ARGS)
 	@cd $(OBJDIR) && $(BUILD_PROJECT_ARG) $(CONFIGURE_ENV_ARGS) $(CONFIGURE) $(CONFIGURE_ARGS) \
 	  || ( echo "*** Fix above errors and then restart with\
                \"$(MAKE) -f client.mk build\"" && exit 1 )
 	@touch $(OBJDIR)/Makefile
 
 ifneq (,$(MAKEFILE))
--- a/client.py
+++ b/client.py
@@ -2,49 +2,71 @@
 
 NSPR_DIRS = (('nsprpub', 'mozilla/nsprpub'),)
 NSS_DIRS  = (('dbm', 'mozilla/dbm'),
              ('security/nss', 'mozilla/security/nss'),
              ('security/coreconf', 'mozilla/security/coreconf'),
              ('security/dbm', 'mozilla/security/dbm'))
 NSSCKBI_DIRS = (('security/nss/lib/ckfw/builtins', 'mozilla/security/nss/lib/ckfw/builtins'),)
 LIBFFI_DIRS = (('js/ctypes/libffi', 'libffi'),)
+WEBIDLPARSER_DIR = 'dom/bindings/parser'
+WEBIDLPARSER_REPO = 'https://hg.mozilla.org/users/khuey_mozilla.com/webidl-parser'
+WEBIDLPARSER_EXCLUSIONS = ['.hgignore', '.gitignore', '.hg', 'ply']
 
 CVSROOT_MOZILLA = ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot'
 CVSROOT_LIBFFI = ':pserver:anoncvs@sources.redhat.com:/cvs/libffi'
 
 import os
 import sys
 import datetime
 import shutil
+import glob
 from optparse import OptionParser
 from subprocess import check_call
 
 topsrcdir = os.path.dirname(__file__)
 if topsrcdir == '':
     topsrcdir = '.'
 
 def check_call_noisy(cmd, *args, **kwargs):
     print "Executing command:", cmd
     check_call(cmd, *args, **kwargs)
 
 def do_hg_pull(dir, repository, hg):
     fulldir = os.path.join(topsrcdir, dir)
     # clone if the dir doesn't exist, pull if it does
     if not os.path.exists(fulldir):
-        fulldir = os.path.join(topsrcdir, dir)
         check_call_noisy([hg, 'clone', repository, fulldir])
     else:
         cmd = [hg, 'pull', '-u', '-R', fulldir]
         if repository is not None:
             cmd.append(repository)
         check_call_noisy(cmd)
     check_call([hg, 'parent', '-R', fulldir,
                 '--template=Updated to revision {node}.\n'])
 
+def do_hg_replace(dir, repository, tag, exclusions, hg):
+    """
+        Replace the contents of dir with the contents of repository, except for
+        files matching exclusions.
+    """
+    fulldir = os.path.join(topsrcdir, dir)
+    if os.path.exists(fulldir):
+        shutil.rmtree(fulldir)
+
+    assert not os.path.exists(fulldir)
+    check_call_noisy([hg, 'clone', '-u', tag, repository, fulldir])
+
+    for thing in exclusions:
+        for excluded in glob.iglob(os.path.join(fulldir, thing)):
+            if os.path.isdir(excluded):
+                shutil.rmtree(excluded)
+            else:
+                os.remove(excluded)
+
 def do_cvs_export(modules, tag, cvsroot, cvs):
     """Check out a CVS directory without CVS metadata, using "export"
     modules is a list of directories to check out and the corresponding
     cvs module, e.g. (('nsprpub', 'mozilla/nsprpub'))
     """
     for module_tuple in modules:
         module = module_tuple[0]
         cvs_module = module_tuple[1]
@@ -55,25 +77,27 @@ def do_cvs_export(modules, tag, cvsroot,
 
         (parent, leaf) = os.path.split(module)
         print "CVS export begin: " + datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
         check_call_noisy([cvs, '-d', cvsroot,
                           'export', '-r', tag, '-d', leaf, cvs_module],
                          cwd=os.path.join(topsrcdir, parent))
         print "CVS export end: " + datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
 
-o = OptionParser(usage="client.py [options] update_nspr tagname | update_nss tagname | update_libffi tagname")
+o = OptionParser(usage="client.py [options] update_nspr tagname | update_nss tagname | update_libffi tagname | update_webidlparser tagname")
 o.add_option("--skip-mozilla", dest="skip_mozilla",
              action="store_true", default=False,
              help="Obsolete")
 
 o.add_option("--cvs", dest="cvs", default=os.environ.get('CVS', 'cvs'),
              help="The location of the cvs binary")
 o.add_option("--cvsroot", dest="cvsroot",
              help="The CVSROOT (default for mozilla checkouts: %s)" % CVSROOT_MOZILLA)
+o.add_option("--hg", dest="hg", default=os.environ.get('HG', 'hg'),
+             help="The location of the hg binary")
 
 try:
     options, args = o.parse_args()
     action = args[0]
 except IndexError:
     o.print_help()
     sys.exit(2)
 
@@ -99,11 +123,14 @@ elif action in ('update_nssckbi'):
         options.cvsroot = os.environ.get('CVSROOT', CVSROOT_MOZILLA)
     do_cvs_export(NSSCKBI_DIRS, tag, options.cvsroot, options.cvs)
     print >>file("security/nss/TAG-INFO-CKBI", "w"), tag
 elif action in ('update_libffi'):
     tag, = args[1:]
     if not options.cvsroot:
         options.cvsroot = CVSROOT_LIBFFI
     do_cvs_export(LIBFFI_DIRS, tag, options.cvsroot, options.cvs)
+elif action in ('update_webidlparser'):
+    tag, = args[1:]
+    do_hg_replace(WEBIDLPARSER_DIR, WEBIDLPARSER_REPO, tag, WEBIDLPARSER_EXCLUSIONS, options.hg)
 else:
     o.print_help()
     sys.exit(2)
--- a/config/Makefile.in
+++ b/config/Makefile.in
@@ -1,8 +1,9 @@
+# -*- Makefile -*-
 #
 # ***** 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/
@@ -112,18 +113,21 @@ endif
 export::
 ifdef MOZ_BUILD_DATE
 	printf "%s" $(MOZ_BUILD_DATE) > buildid
 else
 	$(PYTHON) $(topsrcdir)/toolkit/xre/make-platformini.py --print-buildid > buildid
 endif
 
 ifdef WRAP_SYSTEM_INCLUDES
-export::
-	if test ! -d system_wrappers; then mkdir system_wrappers; fi
+export-preqs = \
+  $(call mkdir_deps,system_wrappers) \
+  $(NULL)
+
+export:: $(export-preqs)
 	$(PYTHON) $(topsrcdir)/config/Preprocessor.py $(DEFINES) $(ACDEFINES) \
 		-DMOZ_TREE_CAIRO=$(MOZ_TREE_CAIRO) \
 		-DMOZ_TREE_PIXMAN=$(MOZ_TREE_PIXMAN) \
 		-DMOZ_NATIVE_HUNSPELL=$(MOZ_NATIVE_HUNSPELL) \
 		-DMOZ_NATIVE_BZ2=$(MOZ_NATIVE_BZ2) \
 		-DMOZ_NATIVE_ZLIB=$(MOZ_NATIVE_ZLIB) \
 		-DMOZ_NATIVE_PNG=$(MOZ_NATIVE_PNG) \
 		-DMOZ_NATIVE_JPEG=$(MOZ_NATIVE_JPEG) \
@@ -185,23 +189,32 @@ PYUNITS := \
   unit-nsinstall.py \
   unit-printprereleasesuffix.py \
   unit-JarMaker.py \
   unit-buildlist.py \
   unit-expandlibs.py \
   unit-writemozinfo.py \
   $(NULL)
 
-check:: check-python-modules check-jar-mn
+check-preqs = \
+  check-python-modules \
+  check-jar-mn \
+  check-makefiles \
+  $(NULL)
+
+check:: $(check-preqs)
 
 check-python-modules::
 	@$(EXIT_ON_ERROR) \
 	for test in $(PYUNITS); do \
 	  $(PYTHON) $(srcdir)/tests/$$test ; \
 	done
 
 check-jar-mn::
 	$(MAKE) -C tests/src-simple check-jar
 	$(MAKE) -C tests/src-simple check-flat
 	$(MAKE) -C tests/src-simple check-flat USE_EXTENSION_MANIFEST=1
 ifneq (,$(filter-out WINNT OS2,$(OS_ARCH)))
 	$(MAKE) -C tests/src-simple check-symlink
 endif
+
+check-makefiles:
+	$(MAKE) -C tests/makefiles/autodeps check
--- a/config/config.mk
+++ b/config/config.mk
@@ -41,17 +41,17 @@
 #
 # Determines the platform and builds the macros needed to load the
 # appropriate platform-specific .mk file, then defines all (most?)
 # of the generic macros.
 #
 
 # Define an include-at-most-once flag
 ifdef INCLUDED_CONFIG_MK
-$(error Don't include config.mk twice!)
+$(error Do not include config.mk twice!)
 endif
 INCLUDED_CONFIG_MK = 1
 
 EXIT_ON_ERROR = set -e; # Shell loops continue past errors without this.
 
 ifndef topsrcdir
 topsrcdir	= $(DEPTH)
 endif
new file mode 100644
--- /dev/null
+++ b/config/makefiles/autotargets.mk
@@ -0,0 +1,45 @@
+# -*- makefile -*-
+# vim:set ts=8 sw=8 sts=8 noet:
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this file,
+# You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+###########################################################################
+#      AUTO_DEPS - A list of deps/targets drived from other macros.
+#         *_DEPS - Make dependencies derived from a given macro.
+###########################################################################
+
+MKDIR ?= mkdir -p
+TOUCH ?= touch
+
+###########################################################################
+# Threadsafe directory creation
+# GENERATED_DIRS - Automated creation of these directories.
+###########################################################################
+mkdir_deps =$(foreach dir,$(getargv),$(dir)/.mkdir.done)
+
+ifneq (,$(GENERATED_DIRS))
+  tmpauto :=$(call mkdir_deps,GENERATED_DIRS)
+  GENERATED_DIRS_DEPS +=$(tmpauto)
+  GARBAGE_DIRS        +=$(tmpauto)
+endif
+
+%/.mkdir.done:
+	$(subst $(SPACE)-p,$(null),$(MKDIR)) -p $(dir $@)
+	@$(TOUCH) $@
+
+#################################################################
+# One ring/dep to rule them all:
+#   config/rules.mk::all target is available by default
+#   Add $(AUTO_DEPS) as an explicit target dependency when needed.
+#################################################################
+
+AUTO_DEPS +=$(GENERATED_DIRS_DEPS)
+
+
+# Complain loudly if deps have not loaded so getargv != $(NULL)
+ifndef getargv
+  $(error config/makefiles/makeutil.mk has not been included)
+endif
new file mode 100644
--- /dev/null
+++ b/config/makefiles/makeutils.mk
@@ -0,0 +1,36 @@
+# -*- makefile -*-
+# vim:set ts=8 sw=8 sts=8 noet:
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this file,
+# You can obtain one at http://mozilla.org/MPL/2.0/.
+
+# Usage: $(call banner,foo bar tans)
+banner =\
+$(info )\
+$(info ***************************************************************************)\
+$(info ** BANNER: $(1) $(2) $(3) $(4) $(5) $(6) $(7) $(8) $(9))\
+$(info ***************************************************************************)\
+
+## Identify function argument types
+istype =$(if $(value ${1}),list,scalar)
+isval  =$(if $(filter-out list,$(call istype,${1})),true)
+isvar  =$(if $(filter-out scalar,$(call istype,${1})),true)
+
+# Access up to 9 arguments passed, option needed to emulate $*
+# Inline for function expansion, do not use $(call )
+argv  =$(strip
+argv +=$(if $(1), $(1))$(if $(2), $(2))$(if $(3), $(3))$(if $(4), $(4))
+argv +=$(if $(5), $(5))$(if $(6), $(6))$(if $(7), $(7))$(if $(8), $(8))
+argv +=$(if $(9), $(9))
+argv +=$(if $(10), $(error makeutils.mk::argv can only handle 9 arguments))
+argv +=)
+
+###########################################################################
+## Access function args as a simple list, inline within user functions.
+## Usage: $(info ** $(call banner,$(getargv)))
+##    $(call banner,scalar)
+##    $(call banner,list0 list1 list2)
+##    $(call banner,ref) ; ref=foo bar tans
+## getarglist() would be a more accurate name but is longer to type
+getargv = $(if $(call isvar,$(1)),$($(1)),$(argv))
new file mode 100644
--- /dev/null
+++ b/config/makefiles/test/Makefile.in
@@ -0,0 +1,95 @@
+# -*- makefile -*-
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this file,
+# You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DEPTH     = ../../..
+topsrcdir = @top_srcdir@
+srcdir    = @srcdir@
+VPATH     = @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+include $(topsrcdir)/config/makefiles/makeutils.mk
+
+##------------------_##
+##---]  TARGETS  [---##
+##------------------_##
+all::
+
+###########################################################################
+## This test target should really depend on a timestamp to only perform
+## work when makeutils.mk is modified.  That answer would require using a
+## 2nd makefile imposing more shell overhead.  Separate makefiles would be
+## very handy for testing when pwd==$src/ but for now avoid the overhead.
+##
+## Test logic will be interpreted at compile time, 'fast' and 'required' so
+## the test will always be run when testing is enabled.
+###########################################################################
+check::
+	@true
+
+## Logic processed at compile time so be selective about when to test
+ifneq ($(NULL),$(findstring check,$(MAKECMDGOALS)))
+
+$(info ===========================================================================)
+$(info Running test: $(MAKECMDGOALS): pwd=$(CURDIR))
+$(info ===========================================================================)
+
+## Silent errors are oh so much fun
+ifndef istype
+  $(error makeutils.mk was not included)
+endif
+
+# arg_scalar = [scalar|literal]
+arg_list = foo bar
+arg_ref  = arg_list
+
+## Identify type of function argument(s)
+########################################
+ifneq (scalar,$(call istype,arg_scalar))
+  $(error istype(arg_scalar)=scalar, found [$(call istype,arg_scalar)])
+endif
+ifneq (list,$(call istype,arg_list))
+  $(error istype(arg_list)=list, found [$(call istype,arg_list)])
+endif
+ifneq (list,$(call istype,arg_ref))
+  $(error istype(arg_ref)=list, found [$(call istype,arg_ref)])
+endif
+
+## Type == scalar or a list of values
+#####################################
+ifneq (true,$(call isval,scalar))
+  $(error isval(scalar)=true, found [$(call isval,scalar)])
+endif
+ifneq ($(NULL),$(call isval,arg_list))
+  $(error isval(arg_list)=null, found [$(call isval,arg_list)])
+endif
+
+## type == reference: macro=>macro => $($(1))
+#############################################
+ifneq ($(NULL),$(call isvar,scalar))
+  $(error isvar(scalar)=$(NULL), found [$(call isvar,scalar)])
+endif
+ifneq (true,$(call isvar,arg_list))
+  $(error isvar(arg_list)=true, found [$(call isvar,arg_list)])
+endif
+ifneq (true,$(call isvar,arg_ref))
+  $(error isvar(arg_ref)=true, found [$(call isvar,arg_ref)])
+endif
+
+# Verify getargv expansion
+##########################
+ifneq (scalar,$(call getargv,scalar))
+  $(error getargv(scalar)=scalar, found [$(call getargv,scalar)])
+endif
+ifneq ($(arg_list),$(call getargv,arg_list))
+  $(error getargv(arg_list)=list, found [$(call getargv,arg_list)])
+endif
+ifneq (arg_list,$(call getargv,arg_ref))
+  $(error getargv(arg_ref)=list, found [$(call getargv,arg_ref)])
+endif
+
+endif # check in MAKECMDGOALS
+
+
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -1,50 +1,15 @@
 # -*- makefile -*-
 # vim:set ts=8 sw=8 sts=8 noet:
 #
-# ***** 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.
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this file,
+# You can obtain one at http://mozilla.org/MPL/2.0/.
 #
-# Contributor(s):
-#  Chase Phillips <chase@mozilla.org>
-#  Benjamin Smedberg <benjamin@smedbergs.us>
-#  Jeff Walden <jwalden+code@mit.edu>
-#  Joey Armstrong <joey@mozilla.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 *****
 
 ifndef topsrcdir
 $(error topsrcdir was not set))
 endif
 
 ifndef MOZILLA_DIR
 MOZILLA_DIR = $(topsrcdir)
 endif
@@ -52,16 +17,19 @@ endif
 ifndef INCLUDED_CONFIG_MK
 include $(topsrcdir)/config/config.mk
 endif
 
 ifndef INCLUDED_VERSION_MK
 include $(topsrcdir)/config/version.mk
 endif
 
+include $(topsrcdir)/config/makefiles/makeutils.mk
+include $(topsrcdir)/config/makefiles/autotargets.mk
+
 ifdef SDK_XPIDLSRCS
 XPIDLSRCS += $(SDK_XPIDLSRCS)
 endif
 ifdef SDK_HEADERS
 EXPORTS += $(SDK_HEADERS)
 endif
 
 REPORT_BUILD = @echo $(notdir $<)
@@ -507,18 +475,18 @@ endif
 ifndef HOST_PROGOBJS
 HOST_PROGOBJS		= $(HOST_OBJS)
 endif
 
 # MAKE_DIRS: List of directories to build while looping over directories.
 # A Makefile that needs $(MDDEPDIR) created but doesn't set any of these
 # variables we know to check can just set NEED_MDDEPDIR explicitly.
 ifneq (,$(OBJS)$(XPIDLSRCS)$(SIMPLE_PROGRAMS)$(NEED_MDDEPDIR))
-MAKE_DIRS		+= $(CURDIR)/$(MDDEPDIR)
-GARBAGE_DIRS		+= $(MDDEPDIR)
+MAKE_DIRS       += $(CURDIR)/$(MDDEPDIR)
+GARBAGE_DIRS    += $(CURDIR)/$(MDDEPDIR)
 endif
 
 #
 # Tags: emacs (etags), vi (ctags)
 # TAG_PROGRAM := ctags -L -
 #
 TAG_PROGRAM		= xargs etags -a
 
@@ -1456,42 +1424,41 @@ export:: FORCE
 	@echo "*** Error processing XPIDLSRCS:"
 	@echo "Please define MODULE or XPIDL_MODULE when defining XPIDLSRCS,"
 	@echo "so we have a module name to use when creating MODULE.xpt."
 	@echo; sleep 2; false
 endif
 
 # generate .h files from into $(XPIDL_GEN_DIR), then export to $(DIST)/include;
 # warn against overriding existing .h file.
-$(XPIDL_GEN_DIR)/.done:
-	$(MKDIR) -p $(XPIDL_GEN_DIR)
-	@$(TOUCH) $@
-
-# don't depend on $(XPIDL_GEN_DIR), because the modification date changes
-# with any addition to the directory, regenerating all .h files -> everything.
 
 XPIDL_DEPS = \
   $(topsrcdir)/xpcom/idl-parser/header.py \
   $(topsrcdir)/xpcom/idl-parser/typelib.py \
   $(topsrcdir)/xpcom/idl-parser/xpidl.py \
   $(NULL)
 
-$(XPIDL_GEN_DIR)/%.h: %.idl $(XPIDL_DEPS) $(XPIDL_GEN_DIR)/.done
+xpidl-preqs = \
+  $(call mkdir_deps,$(XPIDL_GEN_DIR)) \
+  $(call mkdir_deps,$(MDDEPDIR)) \
+  $(NULL)
+
+$(XPIDL_GEN_DIR)/%.h: %.idl $(XPIDL_DEPS) $(xpidl-preqs)
 	$(REPORT_BUILD)
 	$(PYTHON_PATH) \
 	  -I$(topsrcdir)/other-licenses/ply \
 	  -I$(topsrcdir)/xpcom/idl-parser \
 	  $(topsrcdir)/xpcom/idl-parser/header.py --cachedir=$(DEPTH)/xpcom/idl-parser $(XPIDL_FLAGS) $(_VPATH_SRCS) -d $(MDDEPDIR)/$(@F).pp -o $@
 	@if test -n "$(findstring $*.h, $(EXPORTS))"; \
 	  then echo "*** WARNING: file $*.h generated from $*.idl overrides $(srcdir)/$*.h"; else true; fi
 
 ifndef NO_GEN_XPT
 # generate intermediate .xpt files into $(XPIDL_GEN_DIR), then link
 # into $(XPIDL_MODULE).xpt and export it to $(FINAL_TARGET)/components.
-$(XPIDL_GEN_DIR)/%.xpt: %.idl $(XPIDL_DEPS) $(XPIDL_GEN_DIR)/.done
+$(XPIDL_GEN_DIR)/%.xpt: %.idl $(XPIDL_DEPS) $(xpidl-preqs)
 	$(REPORT_BUILD)
 	$(PYTHON_PATH) \
 	  -I$(topsrcdir)/other-licenses/ply \
 	  -I$(topsrcdir)/xpcom/idl-parser \
 	  -I$(topsrcdir)/xpcom/typelib/xpt/tools \
 	  $(topsrcdir)/xpcom/idl-parser/typelib.py --cachedir=$(DEPTH)/xpcom/idl-parser $(XPIDL_FLAGS) $(_VPATH_SRCS) -d $(MDDEPDIR)/$(@F).pp -o $@
 
 # no need to link together if XPIDLSRCS contains only XPIDL_MODULE
@@ -2023,13 +1990,23 @@ FREEZE_VARIABLES = \
   EXTRA_PP_COMPONENTS \
   $(NULL)
 
 $(foreach var,$(FREEZE_VARIABLES),$(eval $(var)_FROZEN := '$($(var))'))
 
 CHECK_FROZEN_VARIABLES = $(foreach var,$(FREEZE_VARIABLES), \
   $(if $(subst $($(var)_FROZEN),,'$($(var))'),$(error Makefile variable '$(var)' changed value after including rules.mk. Was $($(var)_FROZEN), now $($(var)).)))
 
-libs export libs::
+libs export::
 	$(CHECK_FROZEN_VARIABLES)
 
 default all::
 	if test -d $(DIST)/bin ; then touch $(DIST)/bin/.purgecaches ; fi
+
+
+#############################################################################
+# Derived targets and dependencies
+
+include $(topsrcdir)/config/makefiles/autotargets.mk
+ifneq ($(NULL),$(AUTO_DEPS))
+  default all libs tools export:: $(AUTO_DEPS)
+endif
+
new file mode 100644
--- /dev/null
+++ b/config/rules.mk.orig
@@ -0,0 +1,2035 @@
+# -*- makefile -*-
+# vim:set ts=8 sw=8 sts=8 noet:
+#
+# ***** 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):
+#  Chase Phillips <chase@mozilla.org>
+#  Benjamin Smedberg <benjamin@smedbergs.us>
+#  Jeff Walden <jwalden+code@mit.edu>
+#  Joey Armstrong <joey@mozilla.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 *****
+
+ifndef topsrcdir
+$(error topsrcdir was not set))
+endif
+
+ifndef MOZILLA_DIR
+MOZILLA_DIR = $(topsrcdir)
+endif
+
+ifndef INCLUDED_CONFIG_MK
+include $(topsrcdir)/config/config.mk
+endif
+
+ifndef INCLUDED_VERSION_MK
+include $(topsrcdir)/config/version.mk
+endif
+
+ifdef SDK_XPIDLSRCS
+XPIDLSRCS += $(SDK_XPIDLSRCS)
+endif
+ifdef SDK_HEADERS
+EXPORTS += $(SDK_HEADERS)
+endif
+
+REPORT_BUILD = @echo $(notdir $<)
+
+ifeq ($(OS_ARCH),OS2)
+EXEC			=
+else
+EXEC			= exec
+endif
+
+# Don't copy xulrunner files at install time, when using system xulrunner
+ifdef SYSTEM_LIBXUL
+  SKIP_COPY_XULRUNNER=1
+endif
+
+# ELOG prints out failed command when building silently (gmake -s).
+ifneq (,$(findstring s, $(filter-out --%, $(MAKEFLAGS))))
+  ELOG := $(EXEC) sh $(BUILD_TOOLS)/print-failed-commands.sh
+else
+  ELOG :=
+endif
+
+_VPATH_SRCS = $(abspath $<)
+
+# Add $(DIST)/lib to VPATH so that -lfoo dependencies are followed
+VPATH += $(DIST)/lib
+ifdef LIBXUL_SDK
+VPATH += $(LIBXUL_SDK)/lib
+endif
+
+ifdef EXTRA_DSO_LIBS
+EXTRA_DSO_LIBS	:= $(call EXPAND_MOZLIBNAME,$(EXTRA_DSO_LIBS))
+endif
+
+################################################################################
+# Testing frameworks support
+################################################################################
+
+testxpcobjdir = $(DEPTH)/_tests/xpcshell
+
+ifdef ENABLE_TESTS
+
+# Add test directories to the regular directories list. TEST_DIRS should
+# arguably have the same status as TOOL_DIRS and other *_DIRS variables. It is
+# coded this way until Makefiles stop using the "ifdef ENABLE_TESTS; DIRS +="
+# convention.
+#
+# The current developer workflow expects tests to be updated when processing
+# the default target. If we ever change this implementation, the behavior
+# should be preserved or the change should be widely communicated. A
+# consequence of not processing test dir targets during the default target is
+# that changes to tests may not be updated and code could assume to pass
+# locally against non-current test code.
+DIRS += $(TEST_DIRS)
+
+ifdef XPCSHELL_TESTS
+ifndef relativesrcdir
+$(error Must define relativesrcdir when defining XPCSHELL_TESTS.)
+endif
+
+define _INSTALL_TESTS
+$(DIR_INSTALL) $(wildcard $(srcdir)/$(dir)/*) $(testxpcobjdir)/$(relativesrcdir)/$(dir)
+
+endef # do not remove the blank line!
+
+SOLO_FILE ?= $(error Specify a test filename in SOLO_FILE when using check-interactive or check-one)
+
+libs::
+	$(foreach dir,$(XPCSHELL_TESTS),$(_INSTALL_TESTS))
+ifndef NO_XPCSHELL_MANIFEST_CHECK
+	$(PYTHON) $(MOZILLA_DIR)/build/xpccheck.py \
+	  $(topsrcdir) \
+	  $(topsrcdir)/testing/xpcshell/xpcshell.ini \
+	  $(addprefix $(MOZILLA_DIR)/$(relativesrcdir)/,$(XPCSHELL_TESTS))
+endif
+
+testxpcsrcdir = $(topsrcdir)/testing/xpcshell
+
+# Execute all tests in the $(XPCSHELL_TESTS) directories.
+# See also testsuite-targets.mk 'xpcshell-tests' target for global execution.
+xpcshell-tests:
+	$(PYTHON) -u $(topsrcdir)/config/pythonpath.py \
+	  -I$(topsrcdir)/build \
+	  $(testxpcsrcdir)/runxpcshelltests.py \
+	  --symbols-path=$(DIST)/crashreporter-symbols \
+	  --build-info-json=$(DEPTH)/mozinfo.json \
+	  --tests-root-dir=$(testxpcobjdir) \
+	  --xunit-file=$(testxpcobjdir)/$(relativesrcdir)/results.xml \
+	  --xunit-suite-name=xpcshell \
+	  $(EXTRA_TEST_ARGS) \
+	  $(LIBXUL_DIST)/bin/xpcshell \
+	  $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
+
+xpcshell-tests-remote: DM_TRANS?=adb
+xpcshell-tests-remote:
+	$(PYTHON) -u $(topsrcdir)/config/pythonpath.py \
+	  -I$(topsrcdir)/build \
+	  -I$(topsrcdir)/build/mobile \
+	  $(topsrcdir)/testing/xpcshell/remotexpcshelltests.py \
+	  --symbols-path=$(DIST)/crashreporter-symbols \
+	  --build-info-json=$(DEPTH)/mozinfo.json \
+	  $(EXTRA_TEST_ARGS) \
+	  --dm_trans=$(DM_TRANS) \
+	  --deviceIP=${TEST_DEVICE} \
+	  --objdir=$(DEPTH) \
+	  $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
+
+# Execute a single test, specified in $(SOLO_FILE), but don't automatically
+# start the test. Instead, present the xpcshell prompt so the user can
+# attach a debugger and then start the test.
+check-interactive:
+	$(PYTHON) -u $(topsrcdir)/config/pythonpath.py \
+	  -I$(topsrcdir)/build \
+	  $(testxpcsrcdir)/runxpcshelltests.py \
+	  --symbols-path=$(DIST)/crashreporter-symbols \
+	  --build-info-json=$(DEPTH)/mozinfo.json \
+	  --test-path=$(SOLO_FILE) \
+	  --profile-name=$(MOZ_APP_NAME) \
+	  --interactive \
+	  $(LIBXUL_DIST)/bin/xpcshell \
+	  $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
+
+# Execute a single test, specified in $(SOLO_FILE)
+check-one:
+	$(PYTHON) -u $(topsrcdir)/config/pythonpath.py \
+	  -I$(topsrcdir)/build \
+	  $(testxpcsrcdir)/runxpcshelltests.py \
+	  --symbols-path=$(DIST)/crashreporter-symbols \
+	  --build-info-json=$(DEPTH)/mozinfo.json \
+	  --test-path=$(SOLO_FILE) \
+	  --profile-name=$(MOZ_APP_NAME) \
+	  --verbose \
+	  $(EXTRA_TEST_ARGS) \
+	  $(LIBXUL_DIST)/bin/xpcshell \
+	  $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
+
+check-one-remote: DM_TRANS?=adb
+check-one-remote:
+	$(PYTHON) -u $(topsrcdir)/config/pythonpath.py \
+	  -I$(topsrcdir)/build \
+	  -I$(topsrcdir)/build/mobile \
+	  $(testxpcsrcdir)/remotexpcshelltests.py \
+	  --symbols-path=$(DIST)/crashreporter-symbols \
+	  --build-info-json=$(DEPTH)/mozinfo.json \
+	  --test-path=$(SOLO_FILE) \
+	  --profile-name=$(MOZ_APP_NAME) \
+	  --verbose \
+	  $(EXTRA_TEST_ARGS) \
+	  --dm_trans=$(DM_TRANS) \
+	  --deviceIP=${TEST_DEVICE} \
+	  --objdir=$(DEPTH) \
+          --noSetup \
+	  $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
+endif # XPCSHELL_TESTS
+
+ifdef CPP_UNIT_TESTS
+
+# Compile the tests to $(DIST)/bin.  Make lots of niceties available by default
+# through TestHarness.h, by modifying the list of includes and the libs against
+# which stuff links.
+CPPSRCS += $(CPP_UNIT_TESTS)
+SIMPLE_PROGRAMS += $(CPP_UNIT_TESTS:.cpp=$(BIN_SUFFIX))
+INCLUDES += -I$(DIST)/include/testing
+LIBS += $(XPCOM_GLUE_LDOPTS) $(NSPR_LIBS) $(MOZ_JS_LIBS)
+
+# ...and run them the usual way
+check::
+	@$(EXIT_ON_ERROR) \
+	  for f in $(subst .cpp,$(BIN_SUFFIX),$(CPP_UNIT_TESTS)); do \
+	    XPCOM_DEBUG_BREAK=stack-and-abort $(RUN_TEST_PROGRAM) $(DIST)/bin/$$f; \
+	  done
+
+endif # CPP_UNIT_TESTS
+
+.PHONY: check xpcshell-tests check-interactive check-one
+
+endif # ENABLE_TESTS
+
+
+#
+# Library rules
+#
+# If FORCE_STATIC_LIB is set, build a static library.
+# Otherwise, build a shared library.
+#
+
+ifndef LIBRARY
+ifdef STATIC_LIBRARY_NAME
+REAL_LIBRARY		:= $(LIB_PREFIX)$(STATIC_LIBRARY_NAME).$(LIB_SUFFIX)
+# Only build actual library if it is installed in DIST/lib or SDK
+ifeq (,$(SDK_LIBRARY)$(DIST_INSTALL)$(NO_EXPAND_LIBS))
+LIBRARY			:= $(REAL_LIBRARY).$(LIBS_DESC_SUFFIX)
+else
+LIBRARY			:= $(REAL_LIBRARY) $(REAL_LIBRARY).$(LIBS_DESC_SUFFIX)
+endif
+endif # STATIC_LIBRARY_NAME
+endif # LIBRARY
+
+ifndef HOST_LIBRARY
+ifdef HOST_LIBRARY_NAME
+HOST_LIBRARY		:= $(LIB_PREFIX)$(HOST_LIBRARY_NAME).$(LIB_SUFFIX)
+endif
+endif
+
+ifdef LIBRARY
+ifdef FORCE_SHARED_LIB
+ifdef MKSHLIB
+
+ifdef LIB_IS_C_ONLY
+MKSHLIB			= $(MKCSHLIB)
+endif
+
+ifneq (,$(filter OS2 WINNT,$(OS_ARCH)))
+IMPORT_LIBRARY		:= $(LIB_PREFIX)$(SHARED_LIBRARY_NAME).$(IMPORT_LIB_SUFFIX)
+endif
+
+ifeq (OS2,$(OS_ARCH))
+ifdef SHORT_LIBNAME
+SHARED_LIBRARY_NAME	:= $(SHORT_LIBNAME)
+endif
+endif
+
+ifdef MAKE_FRAMEWORK
+SHARED_LIBRARY		:= $(SHARED_LIBRARY_NAME)
+else
+SHARED_LIBRARY		:= $(DLL_PREFIX)$(SHARED_LIBRARY_NAME)$(DLL_SUFFIX)
+endif
+
+ifeq ($(OS_ARCH),OS2)
+DEF_FILE		:= $(SHARED_LIBRARY:.dll=.def)
+endif
+
+EMBED_MANIFEST_AT=2
+
+endif # MKSHLIB
+endif # FORCE_SHARED_LIB
+endif # LIBRARY
+
+ifdef FORCE_STATIC_LIB
+ifndef FORCE_SHARED_LIB
+SHARED_LIBRARY		:= $(NULL)
+DEF_FILE		:= $(NULL)
+IMPORT_LIBRARY		:= $(NULL)
+endif
+endif
+
+ifdef FORCE_SHARED_LIB
+ifndef FORCE_STATIC_LIB
+LIBRARY := $(NULL)
+endif
+endif
+
+ifdef JAVA_LIBRARY_NAME
+JAVA_LIBRARY := $(JAVA_LIBRARY_NAME).jar
+endif
+
+ifeq ($(OS_ARCH),WINNT)
+ifndef GNU_CC
+
+#
+# Unless we're building SIMPLE_PROGRAMS, all C++ files share a PDB file per
+# directory. For parallel builds, this PDB file is shared and locked by
+# MSPDBSRV.EXE, starting with MSVC8 SP1. If you're using MSVC 7.1 or MSVC8
+# without SP1, don't do parallel builds.
+#
+# The final PDB for libraries and programs is created by the linker and uses
+# a different name from the single PDB file created by the compiler. See
+# bug 462740.
+#
+
+ifdef SIMPLE_PROGRAMS
+COMPILE_PDBFILE = $(basename $(@F)).pdb
+else
+COMPILE_PDBFILE = generated.pdb
+endif
+
+LINK_PDBFILE = $(basename $(@F)).pdb
+ifdef MOZ_DEBUG
+CODFILE=$(basename $(@F)).cod
+endif
+
+ifdef MOZ_MAPINFO
+ifdef SHARED_LIBRARY_NAME
+MAPFILE=$(SHARED_LIBRARY_NAME).map
+else
+MAPFILE=$(basename $(@F)).map
+endif # SHARED_LIBRARY_NAME
+endif # MOZ_MAPINFO
+
+ifdef DEFFILE
+OS_LDFLAGS += -DEF:$(call normalizepath,$(DEFFILE))
+EXTRA_DEPS += $(DEFFILE)
+endif
+
+ifdef MAPFILE
+OS_LDFLAGS += -MAP:$(MAPFILE)
+endif
+
+else #!GNU_CC
+
+ifdef DEFFILE
+OS_LDFLAGS += $(call normalizepath,$(DEFFILE))
+EXTRA_DEPS += $(DEFFILE)
+endif
+
+endif # !GNU_CC
+
+endif # WINNT
+
+ifeq ($(SOLARIS_SUNPRO_CXX),1)
+ifeq (86,$(findstring 86,$(OS_TEST)))
+OS_LDFLAGS += -M $(topsrcdir)/config/solaris_ia32.map
+endif # x86
+endif # Solaris Sun Studio C++
+
+ifeq ($(HOST_OS_ARCH),WINNT)
+HOST_PDBFILE=$(basename $(@F)).pdb
+endif
+
+# Don't build SIMPLE_PROGRAMS during the MOZ_PROFILE_GENERATE pass
+ifdef MOZ_PROFILE_GENERATE
+SIMPLE_PROGRAMS :=
+endif
+
+ifndef TARGETS
+TARGETS			= $(LIBRARY) $(SHARED_LIBRARY) $(PROGRAM) $(SIMPLE_PROGRAMS) $(HOST_LIBRARY) $(HOST_PROGRAM) $(HOST_SIMPLE_PROGRAMS) $(JAVA_LIBRARY)
+endif
+
+ifndef OBJS
+_OBJS			= \
+	$(JRI_STUB_CFILES) \
+	$(addsuffix .$(OBJ_SUFFIX), $(JMC_GEN)) \
+	$(CSRCS:.c=.$(OBJ_SUFFIX)) \
+	$(SSRCS:.S=.$(OBJ_SUFFIX)) \
+	$(patsubst %.cc,%.$(OBJ_SUFFIX),$(CPPSRCS:.cpp=.$(OBJ_SUFFIX))) \
+	$(CMSRCS:.m=.$(OBJ_SUFFIX)) \
+	$(CMMSRCS:.mm=.$(OBJ_SUFFIX)) \
+	$(ASFILES:.$(ASM_SUFFIX)=.$(OBJ_SUFFIX))
+OBJS	= $(strip $(_OBJS))
+endif
+
+ifndef HOST_OBJS
+_HOST_OBJS		= \
+        $(addprefix host_,$(HOST_CSRCS:.c=.$(OBJ_SUFFIX))) \
+	$(addprefix host_,$(patsubst %.cc,%.$(OBJ_SUFFIX),$(HOST_CPPSRCS:.cpp=.$(OBJ_SUFFIX)))) \
+	$(addprefix host_,$(HOST_CMSRCS:.m=.$(OBJ_SUFFIX))) \
+	$(addprefix host_,$(HOST_CMMSRCS:.mm=.$(OBJ_SUFFIX)))
+HOST_OBJS = $(strip $(_HOST_OBJS))
+endif
+
+LIBOBJS			:= $(addprefix \", $(OBJS))
+LIBOBJS			:= $(addsuffix \", $(LIBOBJS))
+
+ifndef MOZ_AUTO_DEPS
+ifneq (,$(OBJS)$(XPIDLSRCS)$(SIMPLE_PROGRAMS))
+MDDEPFILES		= $(addprefix $(MDDEPDIR)/,$(OBJS:.$(OBJ_SUFFIX)=.pp))
+ifndef NO_GEN_XPT
+MDDEPFILES		+= $(addprefix $(MDDEPDIR)/,$(XPIDLSRCS:.idl=.h.pp) $(XPIDLSRCS:.idl=.xpt.pp))
+endif
+endif
+endif
+
+ALL_TRASH = \
+	$(GARBAGE) $(TARGETS) $(OBJS) $(PROGOBJS) LOGS TAGS a.out \
+	$(filter-out $(ASFILES),$(OBJS:.$(OBJ_SUFFIX)=.s)) $(OBJS:.$(OBJ_SUFFIX)=.ii) \
+	$(OBJS:.$(OBJ_SUFFIX)=.i) $(OBJS:.$(OBJ_SUFFIX)=.i_o) \
+	$(HOST_PROGOBJS) $(HOST_OBJS) $(IMPORT_LIBRARY) $(DEF_FILE)\
+	$(EXE_DEF_FILE) so_locations _gen _stubs $(wildcard *.res) $(wildcard *.RES) \
+	$(wildcard *.pdb) $(CODFILE) $(MAPFILE) $(IMPORT_LIBRARY) \
+	$(SHARED_LIBRARY:$(DLL_SUFFIX)=.exp) $(wildcard *.ilk) \
+	$(PROGRAM:$(BIN_SUFFIX)=.exp) $(SIMPLE_PROGRAMS:$(BIN_SUFFIX)=.exp) \
+	$(PROGRAM:$(BIN_SUFFIX)=.lib) $(SIMPLE_PROGRAMS:$(BIN_SUFFIX)=.lib) \
+	$(SIMPLE_PROGRAMS:$(BIN_SUFFIX)=.$(OBJ_SUFFIX)) \
+	$(wildcard gts_tmp_*) $(LIBRARY:%.a=.%.timestamp)
+ALL_TRASH_DIRS = \
+	$(GARBAGE_DIRS) /no-such-file
+
+ifdef QTDIR
+GARBAGE                 += $(MOCSRCS)
+GARBAGE                 += $(RCCSRCS)
+endif
+
+ifdef SIMPLE_PROGRAMS
+GARBAGE			+= $(SIMPLE_PROGRAMS:%=%.$(OBJ_SUFFIX))
+endif
+
+ifdef HOST_SIMPLE_PROGRAMS
+GARBAGE			+= $(HOST_SIMPLE_PROGRAMS:%=%.$(OBJ_SUFFIX))
+endif
+
+#
+# the Solaris WorkShop template repository cache.  it occasionally can get
+# out of sync, so targets like clobber should kill it.
+#
+ifeq ($(SOLARIS_SUNPRO_CXX),1)
+GARBAGE_DIRS += SunWS_cache
+endif
+
+XPIDL_GEN_DIR		= _xpidlgen
+
+ifdef MOZ_UPDATE_XTERM
+# Its good not to have a newline at the end of the titlebar string because it
+# makes the make -s output easier to read.  Echo -n does not work on all
+# platforms, but we can trick sed into doing it.
+UPDATE_TITLE = sed -e "s!Y!$(1) in $(shell $(BUILD_TOOLS)/print-depth-path.sh)/$(2)!" $(MOZILLA_DIR)/config/xterm.str;
+endif
+
+define SUBMAKE # $(call SUBMAKE,target,directory)
++@$(UPDATE_TITLE)
++$(MAKE) $(if $(2),-C $(2)) $(1)
+
+endef # The extra line is important here! don't delete it
+
+ifneq (,$(strip $(DIRS)))
+LOOP_OVER_DIRS = \
+  $(foreach dir,$(DIRS),$(call SUBMAKE,$@,$(dir)))
+endif
+
+# we only use this for the makefiles target and other stuff that doesn't matter
+ifneq (,$(strip $(PARALLEL_DIRS)))
+LOOP_OVER_PARALLEL_DIRS = \
+  $(foreach dir,$(PARALLEL_DIRS),$(call SUBMAKE,$@,$(dir)))
+endif
+
+ifneq (,$(strip $(STATIC_DIRS)))
+LOOP_OVER_STATIC_DIRS = \
+  $(foreach dir,$(STATIC_DIRS),$(call SUBMAKE,$@,$(dir)))
+endif
+
+ifneq (,$(strip $(TOOL_DIRS)))
+LOOP_OVER_TOOL_DIRS = \
+  $(foreach dir,$(TOOL_DIRS),$(call SUBMAKE,$@,$(dir)))
+endif
+
+#
+# Now we can differentiate between objects used to build a library, and
+# objects used to build an executable in the same directory.
+#
+ifndef PROGOBJS
+PROGOBJS		= $(OBJS)
+endif
+
+ifndef HOST_PROGOBJS
+HOST_PROGOBJS		= $(HOST_OBJS)
+endif
+
+# MAKE_DIRS: List of directories to build while looping over directories.
+# A Makefile that needs $(MDDEPDIR) created but doesn't set any of these
+# variables we know to check can just set NEED_MDDEPDIR explicitly.
+ifneq (,$(OBJS)$(XPIDLSRCS)$(SIMPLE_PROGRAMS)$(NEED_MDDEPDIR))
+MAKE_DIRS		+= $(CURDIR)/$(MDDEPDIR)
+GARBAGE_DIRS		+= $(MDDEPDIR)
+endif
+
+#
+# Tags: emacs (etags), vi (ctags)
+# TAG_PROGRAM := ctags -L -
+#
+TAG_PROGRAM		= xargs etags -a
+
+#
+# Turn on C++ linking if we have any .cpp or .mm files
+# (moved this from config.mk so that config.mk can be included
+#  before the CPPSRCS are defined)
+#
+ifneq ($(CPPSRCS)$(CMMSRCS),)
+CPP_PROG_LINK		= 1
+endif
+ifneq ($(HOST_CPPSRCS)$(HOST_CMMSRCS),)
+HOST_CPP_PROG_LINK	= 1
+endif
+
+#
+# This will strip out symbols that the component should not be
+# exporting from the .dynsym section.
+#
+ifdef IS_COMPONENT
+EXTRA_DSO_LDOPTS += $(MOZ_COMPONENTS_VERSION_SCRIPT_LDFLAGS)
+endif # IS_COMPONENT
+
+#
+# Enforce the requirement that MODULE_NAME must be set
+# for components in static builds
+#
+ifdef IS_COMPONENT
+ifdef EXPORT_LIBRARY
+ifndef FORCE_SHARED_LIB
+ifndef MODULE_NAME
+$(error MODULE_NAME is required for components which may be used in static builds)
+endif
+endif
+endif
+endif
+
+#
+# MacOS X specific stuff
+#
+
+ifeq ($(OS_ARCH),Darwin)
+ifdef SHARED_LIBRARY
+ifdef IS_COMPONENT
+EXTRA_DSO_LDOPTS	+= -bundle
+else
+EXTRA_DSO_LDOPTS	+= -dynamiclib -install_name @executable_path/$(SHARED_LIBRARY) -compatibility_version 1 -current_version 1 -single_module
+endif
+endif
+endif
+
+#
+# On NetBSD a.out systems, use -Bsymbolic.  This fixes what would otherwise be
+# fatal symbol name clashes between components.
+#
+ifeq ($(OS_ARCH),NetBSD)
+ifeq ($(DLL_SUFFIX),.so.1.0)
+ifdef IS_COMPONENT
+EXTRA_DSO_LDOPTS += -Wl,-Bsymbolic
+endif
+endif
+endif
+
+ifeq ($(OS_ARCH),FreeBSD)
+ifdef IS_COMPONENT
+EXTRA_DSO_LDOPTS += -Wl,-Bsymbolic
+endif
+endif
+
+ifeq ($(OS_ARCH),NetBSD)
+ifneq (,$(filter arc cobalt hpcmips mipsco newsmips pmax sgimips,$(OS_TEST)))
+ifeq ($(MODULE),layout)
+OS_CFLAGS += -Wa,-xgot
+OS_CXXFLAGS += -Wa,-xgot
+endif
+endif
+endif
+
+#
+# HP-UXBeOS specific section: for COMPONENTS only, add -Bsymbolic flag
+# which uses internal symbols first
+#
+ifeq ($(OS_ARCH),HP-UX)
+ifdef IS_COMPONENT
+ifeq ($(GNU_CC)$(GNU_CXX),)
+EXTRA_DSO_LDOPTS += -Wl,-Bsymbolic
+ifneq ($(HAS_EXTRAEXPORTS),1)
+MKSHLIB  += -Wl,+eNSGetModule -Wl,+eerrno
+MKCSHLIB += +eNSGetModule +eerrno
+ifneq ($(OS_TEST),ia64)
+MKSHLIB  += -Wl,+e_shlInit
+MKCSHLIB += +e_shlInit
+endif # !ia64
+endif # !HAS_EXTRAEXPORTS
+endif # non-gnu compilers
+endif # IS_COMPONENT
+endif # HP-UX
+
+ifeq ($(OS_ARCH),AIX)
+ifdef IS_COMPONENT
+ifneq ($(HAS_EXTRAEXPORTS),1)
+MKSHLIB += -bE:$(MOZILLA_DIR)/build/unix/aix.exp -bnoexpall
+MKCSHLIB += -bE:$(MOZILLA_DIR)/build/unix/aix.exp -bnoexpall
+endif # HAS_EXTRAEXPORTS
+endif # IS_COMPONENT
+endif # AIX
+
+#
+# OSF1: add -B symbolic flag for components
+#
+ifeq ($(OS_ARCH),OSF1)
+ifdef IS_COMPONENT
+ifeq ($(GNU_CC)$(GNU_CXX),)
+EXTRA_DSO_LDOPTS += -B symbolic
+endif
+endif
+endif
+
+#
+# Linux: add -Bsymbolic flag for components
+#
+ifeq ($(OS_ARCH),Linux)
+ifdef IS_COMPONENT
+EXTRA_DSO_LDOPTS += -Wl,-Bsymbolic
+endif
+endif
+
+#
+# GNU doesn't have path length limitation
+#
+
+ifeq ($(OS_ARCH),GNU)
+OS_CPPFLAGS += -DPATH_MAX=1024 -DMAXPATHLEN=1024
+endif
+
+#
+# MINGW32
+#
+ifeq ($(OS_ARCH),WINNT)
+ifdef GNU_CC
+ifndef IS_COMPONENT
+DSO_LDOPTS += -Wl,--out-implib -Wl,$(IMPORT_LIBRARY)
+endif
+endif
+endif
+
+ifeq ($(USE_TVFS),1)
+IFLAGS1 = -rb
+IFLAGS2 = -rb
+else
+IFLAGS1 = -m 644
+IFLAGS2 = -m 755
+endif
+
+ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+OUTOPTION = -Fo# eol
+else
+OUTOPTION = -o # eol
+endif # WINNT && !GNU_CC
+
+ifneq (,$(filter ml%,$(AS)))
+ASOUTOPTION = -Fo# eol
+else
+ASOUTOPTION = -o # eol
+endif
+
+ifeq (,$(CROSS_COMPILE))
+HOST_OUTOPTION = $(OUTOPTION)
+else
+HOST_OUTOPTION = -o # eol
+endif
+################################################################################
+
+# SUBMAKEFILES: List of Makefiles for next level down.
+#   This is used to update or create the Makefiles before invoking them.
+SUBMAKEFILES += $(addsuffix /Makefile, $(DIRS) $(TOOL_DIRS) $(PARALLEL_DIRS))
+
+# The root makefile doesn't want to do a plain export/libs, because
+# of the tiers and because of libxul. Suppress the default rules in favor
+# of something else. Makefiles which use this var *must* provide a sensible
+# default rule before including rules.mk
+ifndef SUPPRESS_DEFAULT_RULES
+ifdef TIERS
+default all alldep::
+	$(foreach tier,$(TIERS),$(call SUBMAKE,tier_$(tier)))
+else
+
+default all::
+ifneq (,$(strip $(STATIC_DIRS)))
+	$(foreach dir,$(STATIC_DIRS),$(call SUBMAKE,,$(dir)))
+endif
+	$(MAKE) export
+	$(MAKE) libs
+	$(MAKE) tools
+
+# Do depend as well
+alldep::
+	$(MAKE) export
+	$(MAKE) depend
+	$(MAKE) libs
+	$(MAKE) tools
+
+endif # TIERS
+endif # SUPPRESS_DEFAULT_RULES
+
+ifeq ($(filter s,$(MAKEFLAGS)),)
+ECHO := echo
+QUIET :=
+else
+ECHO := true
+QUIET := -q
+endif
+
+MAKE_TIER_SUBMAKEFILES = +$(if $(tier_$*_dirs),$(MAKE) $(addsuffix /Makefile,$(tier_$*_dirs)))
+
+$(foreach tier,$(TIERS),tier_$(tier))::
+	@$(ECHO) "$@: $($@_staticdirs) $($@_dirs)"
+	$(foreach dir,$($@_staticdirs),$(call SUBMAKE,,$(dir)))
+	$(MAKE) export_$@
+	$(MAKE) libs_$@
+	$(MAKE) tools_$@
+
+# Do everything from scratch
+everything::
+	$(MAKE) clean
+	$(MAKE) alldep
+
+# Add dummy depend target for tinderboxes
+depend::
+
+# Target to only regenerate makefiles
+makefiles: $(SUBMAKEFILES)
+ifneq (,$(DIRS)$(TOOL_DIRS)$(PARALLEL_DIRS))
+	$(LOOP_OVER_PARALLEL_DIRS)
+	$(LOOP_OVER_DIRS)
+	$(LOOP_OVER_TOOL_DIRS)
+endif
+
+include $(topsrcdir)/config/makefiles/target_export.mk
+include $(topsrcdir)/config/makefiles/target_tools.mk
+
+#
+# Rule to create list of libraries for final link
+#
+export::
+ifdef LIBRARY_NAME
+ifdef EXPORT_LIBRARY
+ifdef IS_COMPONENT
+else # !IS_COMPONENT
+	$(PYTHON) $(MOZILLA_DIR)/config/buildlist.py $(FINAL_LINK_LIBS) $(STATIC_LIBRARY_NAME)
+endif # IS_COMPONENT
+endif # EXPORT_LIBRARY
+endif # LIBRARY_NAME
+
+ifneq (,$(filter-out %.$(LIB_SUFFIX),$(SHARED_LIBRARY_LIBS)))
+$(error SHARED_LIBRARY_LIBS must contain .$(LIB_SUFFIX) files only)
+endif
+
+# Create dependencies on static (and shared EXTRA_DSO_LIBS) libraries
+DO_EXPAND_LIBS = $(foreach f,$(1),$(if $(filter %.$(LIB_SUFFIX),$(f)),$(if $(wildcard $(f).$(LIBS_DESC_SUFFIX)),$(f).$(LIBS_DESC_SUFFIX),$(if $(wildcard $(f)),$(f)))))
+LIBS_DEPS = $(call DO_EXPAND_LIBS,$(filter %.$(LIB_SUFFIX),$(LIBS) $(if $(PROGRAM)$(SIMPLE_PROGRAMS),$(MOZ_GLUE_PROGRAM_LDFLAGS))))
+SHARED_LIBRARY_LIBS_DEPS = $(call DO_EXPAND_LIBS,$(SHARED_LIBRARY_LIBS))
+HOST_LIBS_DEPS = $(filter %.$(LIB_SUFFIX),$(HOST_LIBS))
+DSO_LDOPTS_DEPS = $(call DO_EXPAND_LIBS,$(EXTRA_DSO_LIBS) $(filter %.$(LIB_SUFFIX), $(EXTRA_DSO_LDOPTS)))
+
+# Dependencies which, if modified, should cause everything to rebuild
+GLOBAL_DEPS += Makefile Makefile.in $(DEPTH)/config/autoconf.mk $(topsrcdir)/config/config.mk
+
+##############################################
+include $(topsrcdir)/config/makefiles/target_libs.mk
+
+##############################################
+ifndef NO_PROFILE_GUIDED_OPTIMIZE
+ifdef MOZ_PROFILE_USE
+ifeq ($(OS_ARCH)_$(GNU_CC), WINNT_)
+# When building with PGO, we have to make sure to re-link
+# in the MOZ_PROFILE_USE phase if we linked in the
+# MOZ_PROFILE_GENERATE phase. We'll touch this pgo.relink
+# file in the link rule in the GENERATE phase to indicate
+# that we need a relink.
+ifdef SHARED_LIBRARY
+$(SHARED_LIBRARY): pgo.relink
+endif
+ifdef PROGRAM
+$(PROGRAM): pgo.relink
+endif
+
+# In the second pass, we need to merge the pgc files into the pgd file.
+# The compiler would do this for us automatically if they were in the right
+# place, but they're in dist/bin.
+ifneq (,$(SHARED_LIBRARY)$(PROGRAM))
+export::
+ifdef PROGRAM
+	$(PYTHON) $(topsrcdir)/build/win32/pgomerge.py \
+	  $(PROGRAM:$(BIN_SUFFIX)=) $(DIST)/bin
+endif
+ifdef SHARED_LIBRARY
+	$(PYTHON) $(topsrcdir)/build/win32/pgomerge.py \
+	  $(SHARED_LIBRARY_NAME) $(DIST)/bin
+endif
+endif # SHARED_LIBRARY || PROGRAM
+endif # WINNT_
+endif # MOZ_PROFILE_USE
+ifdef MOZ_PROFILE_GENERATE
+# Clean up profiling data during PROFILE_GENERATE phase
+export::
+ifeq ($(OS_ARCH)_$(GNU_CC), WINNT_)
+	$(foreach pgd,$(wildcard *.pgd),pgomgr -clear $(pgd);)
+else
+ifdef GNU_CC
+	-$(RM) *.gcda
+endif
+endif
+endif
+
+ifneq (,$(MOZ_PROFILE_GENERATE)$(MOZ_PROFILE_USE))
+ifdef GNU_CC
+# Force rebuilding libraries and programs in both passes because each
+# pass uses different object files.
+$(PROGRAM) $(SHARED_LIBRARY) $(LIBRARY): FORCE
+endif
+endif
+
+endif # NO_PROFILE_GUIDED_OPTIMIZE
+
+##############################################
+
+stdc++compat.$(OBJ_SUFFIX): CXXFLAGS+=-DMOZ_LIBSTDCXX_VERSION=$(MOZ_LIBSTDCXX_TARGET_VERSION)
+host_stdc++compat.$(OBJ_SUFFIX): CXXFLAGS+=-DMOZ_LIBSTDCXX_VERSION=$(MOZ_LIBSTDCXX_HOST_VERSION)
+
+checkout:
+	$(MAKE) -C $(topsrcdir) -f client.mk checkout
+
+clean clobber realclean clobber_all:: $(SUBMAKEFILES)
+	-$(RM) $(ALL_TRASH)
+	-$(RM) -r $(ALL_TRASH_DIRS)
+	$(foreach dir,$(PARALLEL_DIRS) $(DIRS) $(STATIC_DIRS) $(TOOL_DIRS),-$(call SUBMAKE,$@,$(dir)))
+
+distclean:: $(SUBMAKEFILES)
+	$(foreach dir,$(PARALLEL_DIRS) $(DIRS) $(STATIC_DIRS) $(TOOL_DIRS),-$(call SUBMAKE,$@,$(dir)))
+	-$(RM) -r $(ALL_TRASH_DIRS)
+	-$(RM) $(ALL_TRASH)  \
+	Makefile .HSancillary \
+	$(wildcard *.$(OBJ_SUFFIX)) $(wildcard *.ho) $(wildcard host_*.o*) \
+	$(wildcard *.$(LIB_SUFFIX)) $(wildcard *$(DLL_SUFFIX)) \
+	$(wildcard *.$(IMPORT_LIB_SUFFIX))
+ifeq ($(OS_ARCH),OS2)
+	-$(RM) $(PROGRAM:.exe=.map)
+endif
+
+alltags:
+	$(RM) TAGS
+	find $(topsrcdir) -name dist -prune -o \( -name '*.[hc]' -o -name '*.cp' -o -name '*.cpp' -o -name '*.idl' \) -print | $(TAG_PROGRAM)
+
+#
+# PROGRAM = Foo
+# creates OBJS, links with LIBS to create Foo
+#
+$(PROGRAM): $(PROGOBJS) $(LIBS_DEPS) $(EXTRA_DEPS) $(EXE_DEF_FILE) $(RESFILE) $(GLOBAL_DEPS)
+	@$(RM) $@.manifest
+ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+	$(EXPAND_LD) -NOLOGO -OUT:$@ -PDB:$(LINK_PDBFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
+ifdef MSMANIFEST_TOOL
+	@if test -f $@.manifest; then \
+		if test -f "$(srcdir)/$@.manifest"; then \
+			echo "Embedding manifest from $(srcdir)/$@.manifest and $@.manifest"; \
+			mt.exe -NOLOGO -MANIFEST "$(win_srcdir)/$@.manifest" $@.manifest -OUTPUTRESOURCE:$@\;1; \
+		else \
+			echo "Embedding manifest from $@.manifest"; \
+			mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
+		fi; \
+	elif test -f "$(srcdir)/$@.manifest"; then \
+		echo "Embedding manifest from $(srcdir)/$@.manifest"; \
+		mt.exe -NOLOGO -MANIFEST "$(win_srcdir)/$@.manifest" -OUTPUTRESOURCE:$@\;1; \
+	fi
+endif	# MSVC with manifest tool
+ifdef MOZ_PROFILE_GENERATE
+# touch it a few seconds into the future to work around FAT's
+# 2-second granularity
+	touch -t `date +%Y%m%d%H%M.%S -d "now+5seconds"` pgo.relink
+endif
+else # !WINNT || GNU_CC
+ifeq ($(CPP_PROG_LINK),1)
+	$(EXPAND_CCC) -o $@ $(CXXFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
+	@$(call CHECK_STDCXX,$@)
+else # ! CPP_PROG_LINK
+	$(EXPAND_CC) -o $@ $(CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
+endif # CPP_PROG_LINK
+endif # WINNT && !GNU_CC
+
+ifdef ENABLE_STRIP
+	$(STRIP) $@
+endif
+ifdef MOZ_POST_PROGRAM_COMMAND
+	$(MOZ_POST_PROGRAM_COMMAND) $@
+endif
+
+$(HOST_PROGRAM): $(HOST_PROGOBJS) $(HOST_LIBS_DEPS) $(HOST_EXTRA_DEPS) $(GLOBAL_DEPS)
+ifeq (_WINNT,$(GNU_CC)_$(HOST_OS_ARCH))
+	$(HOST_LD) -NOLOGO -OUT:$@ -PDB:$(HOST_PDBFILE) $(HOST_OBJS) $(WIN32_EXE_LDFLAGS) $(HOST_LDFLAGS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+ifdef MSMANIFEST_TOOL
+	@if test -f $@.manifest; then \
+		if test -f "$(srcdir)/$@.manifest"; then \
+			echo "Embedding manifest from $(srcdir)/$@.manifest and $@.manifest"; \
+			mt.exe -NOLOGO -MANIFEST "$(win_srcdir)/$@.manifest" $@.manifest -OUTPUTRESOURCE:$@\;1; \
+		else \
+			echo "Embedding manifest from $@.manifest"; \
+			mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
+		fi; \
+	elif test -f "$(srcdir)/$@.manifest"; then \
+		echo "Embedding manifest from $(srcdir)/$@.manifest"; \
+		mt.exe -NOLOGO -MANIFEST "$(win_srcdir)/$@.manifest" -OUTPUTRESOURCE:$@\;1; \
+	fi
+endif	# MSVC with manifest tool
+else
+ifeq ($(HOST_CPP_PROG_LINK),1)
+	$(HOST_CXX) -o $@ $(HOST_CXXFLAGS) $(HOST_LDFLAGS) $(HOST_PROGOBJS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+else
+	$(HOST_CC) -o $@ $(HOST_CFLAGS) $(HOST_LDFLAGS) $(HOST_PROGOBJS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+endif # HOST_CPP_PROG_LINK
+endif
+
+#
+# This is an attempt to support generation of multiple binaries
+# in one directory, it assumes everything to compile Foo is in
+# Foo.o (from either Foo.c or Foo.cpp).
+#
+# SIMPLE_PROGRAMS = Foo Bar
+# creates Foo.o Bar.o, links with LIBS to create Foo, Bar.
+#
+$(SIMPLE_PROGRAMS): %$(BIN_SUFFIX): %.$(OBJ_SUFFIX) $(LIBS_DEPS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+	$(EXPAND_LD) -nologo -out:$@ -pdb:$(LINK_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
+ifdef MSMANIFEST_TOOL
+	@if test -f $@.manifest; then \
+		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
+		rm -f $@.manifest; \
+	fi
+endif	# MSVC with manifest tool
+else
+ifeq ($(CPP_PROG_LINK),1)
+	$(EXPAND_CCC) $(CXXFLAGS) -o $@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS)
+	@$(call CHECK_STDCXX,$@)
+else
+	$(EXPAND_CC) $(CFLAGS) $(OUTOPTION)$@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS)
+endif # CPP_PROG_LINK
+endif # WINNT && !GNU_CC
+
+ifdef ENABLE_STRIP
+	$(STRIP) $@
+endif
+ifdef MOZ_POST_PROGRAM_COMMAND
+	$(MOZ_POST_PROGRAM_COMMAND) $@
+endif
+
+$(HOST_SIMPLE_PROGRAMS): host_%$(HOST_BIN_SUFFIX): host_%.$(OBJ_SUFFIX) $(HOST_LIBS_DEPS) $(HOST_EXTRA_DEPS) $(GLOBAL_DEPS)
+ifeq (WINNT_,$(HOST_OS_ARCH)_$(GNU_CC))
+	$(HOST_LD) -NOLOGO -OUT:$@ -PDB:$(HOST_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+else
+ifneq (,$(HOST_CPPSRCS)$(USE_HOST_CXX))
+	$(HOST_CXX) $(HOST_OUTOPTION)$@ $(HOST_CXXFLAGS) $(INCLUDES) $< $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+else
+	$(HOST_CC) $(HOST_OUTOPTION)$@ $(HOST_CFLAGS) $(INCLUDES) $< $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+endif
+endif
+
+#
+# Purify target.  Solaris/sparc only to start.
+# Purify does not recognize "egcs" or "c++" so we go with
+# "gcc" and "g++" for now.
+#
+pure:	$(PROGRAM)
+ifeq ($(CPP_PROG_LINK),1)
+	$(PURIFY) $(CCC) -o $^.pure $(CXXFLAGS) $(PROGOBJS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS)
+else
+	$(PURIFY) $(CC) -o $^.pure $(CFLAGS) $(PROGOBJS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS)
+endif
+ifndef NO_DIST_INSTALL
+	$(INSTALL) $(IFLAGS2) $^.pure $(FINAL_TARGET)
+endif
+
+quantify: $(PROGRAM)
+ifeq ($(CPP_PROG_LINK),1)
+	$(QUANTIFY) $(CCC) -o $^.quantify $(CXXFLAGS) $(PROGOBJS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS)
+else
+	$(QUANTIFY) $(CC) -o $^.quantify $(CFLAGS) $(PROGOBJS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS)
+endif
+ifndef NO_DIST_INSTALL
+	$(INSTALL) $(IFLAGS2) $^.quantify $(FINAL_TARGET)
+endif
+
+ifdef DTRACE_PROBE_OBJ
+EXTRA_DEPS += $(DTRACE_PROBE_OBJ)
+OBJS += $(DTRACE_PROBE_OBJ)
+endif
+
+$(filter %.$(LIB_SUFFIX),$(LIBRARY)): $(OBJS) $(LOBJS) $(SHARED_LIBRARY_LIBS_DEPS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+	$(RM) $(LIBRARY)
+	$(EXPAND_AR) $(AR_FLAGS) $(OBJS) $(LOBJS) $(SHARED_LIBRARY_LIBS)
+	$(RANLIB) $@
+
+$(filter-out %.$(LIB_SUFFIX),$(LIBRARY)): $(filter %.$(LIB_SUFFIX),$(LIBRARY)) $(OBJS) $(LOBJS) $(SHARED_LIBRARY_LIBS_DEPS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+# When we only build a library descriptor, blow out any existing library
+	$(if $(filter %.$(LIB_SUFFIX),$(LIBRARY)),,$(RM) $(REAL_LIBRARY) $(EXPORT_LIBRARY:%=%/$(REAL_LIBRARY)))
+	$(EXPAND_LIBS_GEN) $(OBJS) $(LOBJS) $(SHARED_LIBRARY_LIBS) > $@
+
+ifeq ($(OS_ARCH),WINNT)
+$(IMPORT_LIBRARY): $(SHARED_LIBRARY)
+endif
+
+ifeq ($(OS_ARCH),OS2)
+$(DEF_FILE): $(OBJS) $(SHARED_LIBRARY_LIBS)
+	$(RM) $@
+	echo LIBRARY $(SHARED_LIBRARY_NAME) INITINSTANCE TERMINSTANCE > $@
+	echo PROTMODE >> $@
+	echo CODE    LOADONCALL MOVEABLE DISCARDABLE >> $@
+	echo DATA    PRELOAD MOVEABLE MULTIPLE NONSHARED >> $@
+	echo EXPORTS >> $@
+
+	$(ADD_TO_DEF_FILE)
+
+$(IMPORT_LIBRARY): $(SHARED_LIBRARY)
+	$(RM) $@
+	$(IMPLIB) $@ $^
+	$(RANLIB) $@
+endif # OS/2
+
+$(HOST_LIBRARY): $(HOST_OBJS) Makefile
+	$(RM) $@
+	$(HOST_AR) $(HOST_AR_FLAGS) $(HOST_OBJS)
+	$(HOST_RANLIB) $@
+
+ifdef HAVE_DTRACE
+ifndef XP_MACOSX
+ifdef DTRACE_PROBE_OBJ
+ifndef DTRACE_LIB_DEPENDENT
+NON_DTRACE_OBJS := $(filter-out $(DTRACE_PROBE_OBJ),$(OBJS))
+$(DTRACE_PROBE_OBJ): $(NON_DTRACE_OBJS)
+	dtrace -G -C -s $(MOZILLA_DTRACE_SRC) -o $(DTRACE_PROBE_OBJ) $(NON_DTRACE_OBJS)
+endif
+endif
+endif
+endif
+
+# On Darwin (Mac OS X), dwarf2 debugging uses debug info left in .o files,
+# so instead of deleting .o files after repacking them into a dylib, we make
+# symlinks back to the originals. The symlinks are a no-op for stabs debugging,
+# so no need to conditionalize on OS version or debugging format.
+
+$(SHARED_LIBRARY): $(OBJS) $(LOBJS) $(DEF_FILE) $(RESFILE) $(SHARED_LIBRARY_LIBS_DEPS) $(LIBRARY) $(EXTRA_DEPS) $(DSO_LDOPTS_DEPS) $(GLOBAL_DEPS)
+ifndef INCREMENTAL_LINKER
+	$(RM) $@
+endif
+ifdef DTRACE_LIB_DEPENDENT
+ifndef XP_MACOSX
+	dtrace -G -C -s $(MOZILLA_DTRACE_SRC) -o  $(DTRACE_PROBE_OBJ) $(shell $(EXPAND_LIBS) $(MOZILLA_PROBE_LIBS))
+endif
+	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(DTRACE_PROBE_OBJ) $(MOZILLA_PROBE_LIBS) $(RESFILE) $(LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(MOZ_GLUE_LDFLAGS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
+	@$(RM) $(DTRACE_PROBE_OBJ)
+else # ! DTRACE_LIB_DEPENDENT
+	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(RESFILE) $(LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(MOZ_GLUE_LDFLAGS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
+endif # DTRACE_LIB_DEPENDENT
+	@$(call CHECK_STDCXX,$@)
+
+ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+ifdef MSMANIFEST_TOOL
+ifdef EMBED_MANIFEST_AT
+	@if test -f $@.manifest; then \
+		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;$(EMBED_MANIFEST_AT); \
+		rm -f $@.manifest; \
+	fi
+endif   # EMBED_MANIFEST_AT
+endif	# MSVC with manifest tool
+ifdef MOZ_PROFILE_GENERATE
+	touch -t `date +%Y%m%d%H%M.%S -d "now+5seconds"` pgo.relink
+endif
+endif	# WINNT && !GCC
+	@$(RM) foodummyfilefoo $(DELETE_AFTER_LINK)
+	chmod +x $@
+ifdef ENABLE_STRIP
+	$(STRIP) $@
+endif
+ifdef MOZ_POST_DSO_LIB_COMMAND
+	$(MOZ_POST_DSO_LIB_COMMAND) $@
+endif
+
+ifdef MOZ_AUTO_DEPS
+ifdef COMPILER_DEPEND
+ifeq ($(SOLARIS_SUNPRO_CC),1)
+_MDDEPFILE = $(MDDEPDIR)/$(@F).pp
+
+define MAKE_DEPS_AUTO_CC
+if test -d $(@D); then \
+	echo "Building deps for $< using Sun Studio cc"; \
+	$(CC) $(COMPILE_CFLAGS) -xM  $< >$(_MDDEPFILE) ; \
+fi
+endef
+define MAKE_DEPS_AUTO_CXX
+if test -d $(@D); then \
+	echo "Building deps for $< using Sun Studio CC"; \
+	$(CXX) $(COMPILE_CXXFLAGS) -xM $< >$(_MDDEPFILE) ; \
+fi
+endef
+endif # Sun Studio on Solaris
+else # COMPILER_DEPEND
+#
+# Generate dependencies on the fly
+#
+_MDDEPFILE = $(MDDEPDIR)/$(@F).pp
+
+define MAKE_DEPS_AUTO
+if test -d $(@D); then \
+	echo "Building deps for $<"; \
+	$(MKDEPEND) -o'.$(OBJ_SUFFIX)' -f- $(DEFINES) $(ACDEFINES) $(XULPPFLAGS) $(INCLUDES) $< 2>/dev/null | sed -e "s|^[^ ]*/||" > $(_MDDEPFILE) ; \
+fi
+endef
+
+MAKE_DEPS_AUTO_CC = $(MAKE_DEPS_AUTO)
+MAKE_DEPS_AUTO_CXX = $(MAKE_DEPS_AUTO)
+
+endif # COMPILER_DEPEND
+
+endif # MOZ_AUTO_DEPS
+
+# Rules for building native targets must come first because of the host_ prefix
+host_%.$(OBJ_SUFFIX): %.c $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
+	$(ELOG) $(HOST_CC) $(HOST_OUTOPTION)$@ -c $(HOST_CFLAGS) $(INCLUDES) $(NSPR_CFLAGS) $(_VPATH_SRCS)
+
+host_%.$(OBJ_SUFFIX): %.cpp $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
+	$(ELOG) $(HOST_CXX) $(HOST_OUTOPTION)$@ -c $(HOST_CXXFLAGS) $(INCLUDES) $(NSPR_CFLAGS) $(_VPATH_SRCS)
+
+host_%.$(OBJ_SUFFIX): %.cc $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
+	$(ELOG) $(HOST_CXX) $(HOST_OUTOPTION)$@ -c $(HOST_CXXFLAGS) $(INCLUDES) $(NSPR_CFLAGS) $(_VPATH_SRCS)
+
+host_%.$(OBJ_SUFFIX): %.m $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
+	$(ELOG) $(HOST_CC) $(HOST_OUTOPTION)$@ -c $(HOST_CFLAGS) $(HOST_CMFLAGS) $(INCLUDES) $(NSPR_CFLAGS) $(_VPATH_SRCS)
+
+host_%.$(OBJ_SUFFIX): %.mm $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
+	$(ELOG) $(HOST_CXX) $(HOST_OUTOPTION)$@ -c $(HOST_CXXFLAGS) $(HOST_CMMFLAGS) $(INCLUDES) $(NSPR_CFLAGS) $(_VPATH_SRCS)
+
+%:: %.c $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
+	@$(MAKE_DEPS_AUTO_CC)
+	$(ELOG) $(CC) $(CFLAGS) $(LDFLAGS) $(OUTOPTION)$@ $(_VPATH_SRCS)
+
+%.$(OBJ_SUFFIX): %.c $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
+	@$(MAKE_DEPS_AUTO_CC)
+	$(ELOG) $(CC) $(OUTOPTION)$@ -c $(COMPILE_CFLAGS) $(_VPATH_SRCS)
+
+# DEFINES and ACDEFINES are needed here to enable conditional compilation of Q_OBJECTs:
+# 'moc' only knows about #defines it gets on the command line (-D...), not in
+# included headers like mozilla-config.h
+moc_%.cpp: %.h $(GLOBAL_DEPS)
+	$(ELOG) $(MOC) $(DEFINES) $(ACDEFINES) $< $(OUTOPTION)$@
+
+moc_%.cc: %.cc $(GLOBAL_DEPS)
+	$(ELOG) $(MOC) $(DEFINES) $(ACDEFINES) $(_VPATH_SRCS:.cc=.h) $(OUTOPTION)$@
+
+qrc_%.cpp: %.qrc $(GLOBAL_DEPS)
+	$(ELOG) $(RCC) -name $* $< $(OUTOPTION)$@
+
+ifdef ASFILES
+# The AS_DASH_C_FLAG is needed cause not all assemblers (Solaris) accept
+# a '-c' flag.
+%.$(OBJ_SUFFIX): %.$(ASM_SUFFIX) $(GLOBAL_DEPS)
+	$(AS) $(ASOUTOPTION)$@ $(ASFLAGS) $(AS_DASH_C_FLAG) $(_VPATH_SRCS)
+endif
+
+%.$(OBJ_SUFFIX): %.S $(GLOBAL_DEPS)
+	$(AS) -o $@ $(ASFLAGS) -c $<
+
+%:: %.cpp $(GLOBAL_DEPS)
+	@$(MAKE_DEPS_AUTO_CXX)
+	$(CCC) $(OUTOPTION)$@ $(CXXFLAGS) $(_VPATH_SRCS) $(LDFLAGS)
+
+#
+# Please keep the next two rules in sync.
+#
+%.$(OBJ_SUFFIX): %.cc $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
+	@$(MAKE_DEPS_AUTO_CXX)
+	$(ELOG) $(CCC) $(OUTOPTION)$@ -c $(COMPILE_CXXFLAGS) $(_VPATH_SRCS)
+
+%.$(OBJ_SUFFIX): %.cpp $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
+	@$(MAKE_DEPS_AUTO_CXX)
+ifdef STRICT_CPLUSPLUS_SUFFIX
+	echo "#line 1 \"$*.cpp\"" | cat - $*.cpp > t_$*.cc
+	$(ELOG) $(CCC) -o $@ -c $(COMPILE_CXXFLAGS) t_$*.cc
+	$(RM) t_$*.cc
+else
+	$(ELOG) $(CCC) $(OUTOPTION)$@ -c $(COMPILE_CXXFLAGS) $(_VPATH_SRCS)
+endif #STRICT_CPLUSPLUS_SUFFIX
+
+$(OBJ_PREFIX)%.$(OBJ_SUFFIX): %.mm $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
+	@$(MAKE_DEPS_AUTO_CXX)
+	$(ELOG) $(CCC) -o $@ -c $(COMPILE_CXXFLAGS) $(COMPILE_CMMFLAGS) $(_VPATH_SRCS)
+
+$(OBJ_PREFIX)%.$(OBJ_SUFFIX): %.m $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
+	@$(MAKE_DEPS_AUTO_CC)
+	$(ELOG) $(CC) -o $@ -c $(COMPILE_CFLAGS) $(COMPILE_CMFLAGS) $(_VPATH_SRCS)
+
+%.s: %.cpp
+	$(CCC) -S $(COMPILE_CXXFLAGS) $(_VPATH_SRCS)
+
+%.s: %.cc
+	$(CCC) -S $(COMPILE_CXXFLAGS) $(_VPATH_SRCS)
+
+%.s: %.c
+	$(CC) -S $(COMPILE_CFLAGS) $(_VPATH_SRCS)
+
+%.i: %.cpp
+	$(CCC) -C -E $(COMPILE_CXXFLAGS) $(_VPATH_SRCS) > $*.i
+
+%.i: %.cc
+	$(CCC) -C -E $(COMPILE_CXXFLAGS) $(_VPATH_SRCS) > $*.i
+
+%.i: %.c
+	$(CC) -C -E $(COMPILE_CFLAGS) $(_VPATH_SRCS) > $*.i
+
+%.i: %.mm
+	$(CCC) -C -E $(COMPILE_CXXFLAGS) $(COMPILE_CMMFLAGS) $(_VPATH_SRCS) > $*.i
+
+%.res: %.rc
+	@echo Creating Resource file: $@
+ifeq ($(OS_ARCH),OS2)
+	$(RC) $(RCFLAGS:-D%=-d %) -i $(subst /,\,$(srcdir)) -r $< $@
+else
+ifdef GNU_CC
+	$(RC) $(RCFLAGS) $(filter-out -U%,$(DEFINES)) $(INCLUDES:-I%=--include-dir %) $(OUTOPTION)$@ $(_VPATH_SRCS)
+else
+	$(RC) $(RCFLAGS) -r $(DEFINES) $(INCLUDES) $(OUTOPTION)$@ $(_VPATH_SRCS)
+endif
+endif
+
+# need 3 separate lines for OS/2
+%:: %.pl
+	$(RM) $@
+	cp $< $@
+	chmod +x $@
+
+%:: %.sh
+	$(RM) $@
+	cp $< $@
+	chmod +x $@
+
+# Cancel these implicit rules
+#
+%: %,v
+
+%: RCS/%,v
+
+%: s.%
+
+%: SCCS/s.%
+
+###############################################################################
+# Java rules
+###############################################################################
+ifneq (,$(filter OS2 WINNT,$(OS_ARCH)))
+SEP := ;
+else
+SEP := :
+endif
+
+EMPTY :=
+SPACE := $(EMPTY) $(EMPTY)
+
+# MSYS has its own special path form, but javac expects the source and class
+# paths to be in the DOS form (i.e. e:/builds/...).  This function does the
+# appropriate conversion on Windows, but is a noop on other systems.
+ifeq ($(HOST_OS_ARCH),WINNT)
+#  We use 'pwd -W' to get DOS form of the path.  However, since the given path
+#  could be a file or a non-existent path, we cannot call 'pwd -W' directly
+#  on the path.  Instead, we extract the root path (i.e. "c:/"), call 'pwd -W'
+#  on it, then merge with the rest of the path.
+root-path = $(shell echo $(1) | sed -e "s|\(/[^/]*\)/\?\(.*\)|\1|")
+non-root-path = $(shell echo $(1) | sed -e "s|\(/[^/]*\)/\?\(.*\)|\2|")
+normalizepath = $(foreach p,$(1),$(if $(filter /%,$(1)),$(patsubst %/,%,$(shell cd $(call root-path,$(1)) && pwd -W))/$(call non-root-path,$(1)),$(1)))
+else
+normalizepath = $(1)
+endif
+
+_srcdir = $(call normalizepath,$(srcdir))
+ifdef JAVA_SOURCEPATH
+SP = $(subst $(SPACE),$(SEP),$(call normalizepath,$(strip $(JAVA_SOURCEPATH))))
+_JAVA_SOURCEPATH = ".$(SEP)$(_srcdir)$(SEP)$(SP)"
+else
+_JAVA_SOURCEPATH = ".$(SEP)$(_srcdir)"
+endif
+
+ifdef JAVA_CLASSPATH
+CP = $(subst $(SPACE),$(SEP),$(call normalizepath,$(strip $(JAVA_CLASSPATH))))
+_JAVA_CLASSPATH = ".$(SEP)$(CP)"
+else
+_JAVA_CLASSPATH = .
+endif
+
+_JAVA_DIR = _java
+$(_JAVA_DIR)::
+	$(NSINSTALL) -D $@
+
+$(_JAVA_DIR)/%.class: %.java $(GLOBAL_DEPS) $(_JAVA_DIR)
+	$(JAVAC) $(JAVAC_FLAGS) -classpath $(_JAVA_CLASSPATH) \
+			-sourcepath $(_JAVA_SOURCEPATH) -d $(_JAVA_DIR) $(_VPATH_SRCS)
+
+$(JAVA_LIBRARY): $(addprefix $(_JAVA_DIR)/,$(JAVA_SRCS:.java=.class)) $(GLOBAL_DEPS)
+	$(JAR) cf $@ -C $(_JAVA_DIR) .
+
+GARBAGE_DIRS += $(_JAVA_DIR)
+
+###############################################################################
+# Update Makefiles
+###############################################################################
+
+# Note: Passing depth to make-makefile is optional.
+#       It saves the script some work, though.
+Makefile: Makefile.in
+	@$(PERL) $(AUTOCONF_TOOLS)/make-makefile -t $(topsrcdir) -d $(DEPTH)
+
+ifdef SUBMAKEFILES
+# VPATH does not work on some machines in this case, so add $(srcdir)
+$(SUBMAKEFILES): % : $(srcdir)/%.in
+	$(PERL) $(AUTOCONF_TOOLS)/make-makefile -t $(topsrcdir) -d $(DEPTH) $@
+endif
+
+ifdef AUTOUPDATE_CONFIGURE
+$(topsrcdir)/configure: $(topsrcdir)/configure.in
+	(cd $(topsrcdir) && $(AUTOCONF)) && (cd $(DEPTH) && ./config.status --recheck)
+endif
+
+$(DEPTH)/config/autoconf.mk: $(topsrcdir)/config/autoconf.mk.in
+	cd $(DEPTH) && CONFIG_HEADERS= CONFIG_FILES=config/autoconf.mk ./config.status
+
+###############################################################################
+# Bunch of things that extend the 'export' rule (in order):
+###############################################################################
+
+################################################################################
+# Copy each element of EXPORTS to $(DIST)/include
+
+ifneq ($(XPI_NAME),)
+$(FINAL_TARGET):
+	$(NSINSTALL) -D $@
+
+export:: $(FINAL_TARGET)
+endif
+
+ifndef NO_DIST_INSTALL
+ifneq (,$(EXPORTS))
+export:: $(EXPORTS)
+	$(INSTALL) $(IFLAGS1) $^ $(DIST)/include
+endif
+endif # NO_DIST_INSTALL
+
+define EXPORT_NAMESPACE_RULE
+ifndef NO_DIST_INSTALL
+export:: $(EXPORTS_$(namespace))
+	$(INSTALL) $(IFLAGS1) $$^ $(DIST)/include/$(namespace)
+endif # NO_DIST_INSTALL
+endef
+
+$(foreach namespace,$(EXPORTS_NAMESPACES),$(eval $(EXPORT_NAMESPACE_RULE)))
+
+################################################################################
+# Copy each element of PREF_JS_EXPORTS
+
+ifdef GRE_MODULE
+PREF_DIR = greprefs
+else
+ifneq (,$(XPI_NAME)$(LIBXUL_SDK))
+PREF_DIR = defaults/preferences
+else
+PREF_DIR = defaults/pref
+endif
+endif
+
+ifneq ($(PREF_JS_EXPORTS),)
+# on win32, pref files need CRLF line endings... see bug 206029
+ifeq (WINNT,$(OS_ARCH))
+PREF_PPFLAGS = --line-endings=crlf
+endif
+
+ifndef NO_DIST_INSTALL
+$(FINAL_TARGET)/$(PREF_DIR):
+	$(NSINSTALL) -D $@
+
+libs:: $(FINAL_TARGET)/$(PREF_DIR)
+libs:: $(PREF_JS_EXPORTS)
+	$(EXIT_ON_ERROR)  \
+	for i in $^; do \
+	  dest=$(FINAL_TARGET)/$(PREF_DIR)/`basename $$i`; \
+	  $(RM) -f $$dest; \
+	  $(PYTHON) $(topsrcdir)/config/Preprocessor.py $(PREF_PPFLAGS) $(DEFINES) $(ACDEFINES) $(XULPPFLAGS) $$i > $$dest; \
+	done
+endif
+endif
+
+################################################################################
+# Copy each element of AUTOCFG_JS_EXPORTS to $(FINAL_TARGET)/defaults/autoconfig
+
+ifneq ($(AUTOCFG_JS_EXPORTS),)
+$(FINAL_TARGET)/defaults/autoconfig::
+	$(NSINSTALL) -D $@
+
+ifndef NO_DIST_INSTALL
+export:: $(AUTOCFG_JS_EXPORTS) $(FINAL_TARGET)/defaults/autoconfig
+	$(INSTALL) $(IFLAGS1) $^
+endif
+
+endif
+################################################################################
+# Export the elements of $(XPIDLSRCS)
+# generating .h and .xpt files and moving them to the appropriate places.
+
+ifneq ($(XPIDLSRCS),)
+
+export:: $(patsubst %.idl,$(XPIDL_GEN_DIR)/%.h, $(XPIDLSRCS))
+
+ifndef XPIDL_MODULE
+XPIDL_MODULE		= $(MODULE)
+endif
+
+ifeq ($(XPIDL_MODULE),) # we need $(XPIDL_MODULE) to make $(XPIDL_MODULE).xpt
+export:: FORCE
+	@echo
+	@echo "*** Error processing XPIDLSRCS:"
+	@echo "Please define MODULE or XPIDL_MODULE when defining XPIDLSRCS,"
+	@echo "so we have a module name to use when creating MODULE.xpt."
+	@echo; sleep 2; false
+endif
+
+# generate .h files from into $(XPIDL_GEN_DIR), then export to $(DIST)/include;
+# warn against overriding existing .h file.
+$(XPIDL_GEN_DIR)/.done:
+	$(MKDIR) -p $(XPIDL_GEN_DIR)
+	@$(TOUCH) $@
+
+# don't depend on $(XPIDL_GEN_DIR), because the modification date changes
+# with any addition to the directory, regenerating all .h files -> everything.
+
+XPIDL_DEPS = \
+  $(topsrcdir)/xpcom/idl-parser/header.py \
+  $(topsrcdir)/xpcom/idl-parser/typelib.py \
+  $(topsrcdir)/xpcom/idl-parser/xpidl.py \
+  $(NULL)
+
+$(XPIDL_GEN_DIR)/%.h: %.idl $(XPIDL_DEPS) $(XPIDL_GEN_DIR)/.done
+	$(REPORT_BUILD)
+	$(PYTHON_PATH) \
+	  -I$(topsrcdir)/other-licenses/ply \
+	  -I$(topsrcdir)/xpcom/idl-parser \
+	  $(topsrcdir)/xpcom/idl-parser/header.py --cachedir=$(DEPTH)/xpcom/idl-parser $(XPIDL_FLAGS) $(_VPATH_SRCS) -d $(MDDEPDIR)/$(@F).pp -o $@
+	@if test -n "$(findstring $*.h, $(EXPORTS))"; \
+	  then echo "*** WARNING: file $*.h generated from $*.idl overrides $(srcdir)/$*.h"; else true; fi
+
+ifndef NO_GEN_XPT
+# generate intermediate .xpt files into $(XPIDL_GEN_DIR), then link
+# into $(XPIDL_MODULE).xpt and export it to $(FINAL_TARGET)/components.
+$(XPIDL_GEN_DIR)/%.xpt: %.idl $(XPIDL_DEPS) $(XPIDL_GEN_DIR)/.done
+	$(REPORT_BUILD)
+	$(PYTHON_PATH) \
+	  -I$(topsrcdir)/other-licenses/ply \
+	  -I$(topsrcdir)/xpcom/idl-parser \
+	  -I$(topsrcdir)/xpcom/typelib/xpt/tools \
+	  $(topsrcdir)/xpcom/idl-parser/typelib.py --cachedir=$(DEPTH)/xpcom/idl-parser $(XPIDL_FLAGS) $(_VPATH_SRCS) -d $(MDDEPDIR)/$(@F).pp -o $@
+
+# no need to link together if XPIDLSRCS contains only XPIDL_MODULE
+ifneq ($(XPIDL_MODULE).idl,$(strip $(XPIDLSRCS)))
+$(XPIDL_GEN_DIR)/$(XPIDL_MODULE).xpt: $(patsubst %.idl,$(XPIDL_GEN_DIR)/%.xpt,$(XPIDLSRCS)) $(GLOBAL_DEPS)
+	$(XPIDL_LINK) $(XPIDL_GEN_DIR)/$(XPIDL_MODULE).xpt $(patsubst %.idl,$(XPIDL_GEN_DIR)/%.xpt,$(XPIDLSRCS))
+endif # XPIDL_MODULE.xpt != XPIDLSRCS
+
+libs:: $(XPIDL_GEN_DIR)/$(XPIDL_MODULE).xpt
+ifndef NO_DIST_INSTALL
+	$(INSTALL) $(IFLAGS1) $(XPIDL_GEN_DIR)/$(XPIDL_MODULE).xpt $(FINAL_TARGET)/components
+ifndef NO_INTERFACES_MANIFEST
+	@$(PYTHON) $(MOZILLA_DIR)/config/buildlist.py $(FINAL_TARGET)/components/interfaces.manifest "interfaces $(XPIDL_MODULE).xpt"
+	@$(PYTHON) $(MOZILLA_DIR)/config/buildlist.py $(FINAL_TARGET)/chrome.manifest "manifest components/interfaces.manifest"
+endif
+endif
+
+endif # NO_GEN_XPT
+
+GARBAGE_DIRS		+= $(XPIDL_GEN_DIR)
+
+endif # XPIDLSRCS
+
+ifneq ($(XPIDLSRCS),)
+# export .idl files to $(IDL_DIR)
+ifndef NO_DIST_INSTALL
+export:: $(XPIDLSRCS) $(IDL_DIR)
+	$(INSTALL) $(IFLAGS1) $^
+
+export:: $(patsubst %.idl,$(XPIDL_GEN_DIR)/%.h, $(XPIDLSRCS)) $(DIST)/include
+	$(INSTALL) $(IFLAGS1) $^
+endif # NO_DIST_INSTALL
+
+endif # XPIDLSRCS
+
+
+
+# General rules for exporting idl files.
+$(IDL_DIR):
+	$(NSINSTALL) -D $@
+
+export-idl:: $(SUBMAKEFILES) $(MAKE_DIRS)
+
+ifneq ($(XPIDLSRCS),)
+ifndef NO_DIST_INSTALL
+export-idl:: $(XPIDLSRCS) $(IDL_DIR)
+	$(INSTALL) $(IFLAGS1) $^
+endif
+endif
+	$(LOOP_OVER_PARALLEL_DIRS)
+	$(LOOP_OVER_DIRS)
+	$(LOOP_OVER_TOOL_DIRS)
+
+################################################################################
+# Copy each element of EXTRA_COMPONENTS to $(FINAL_TARGET)/components
+ifneq (,$(filter %.js,$(EXTRA_COMPONENTS) $(EXTRA_PP_COMPONENTS)))
+ifeq (,$(filter %.manifest,$(EXTRA_COMPONENTS) $(EXTRA_PP_COMPONENTS)))
+ifndef NO_JS_MANIFEST
+$(error .js component without matching .manifest. See https://developer.mozilla.org/en/XPCOM/XPCOM_changes_in_Gecko_2.0)
+endif
+endif
+endif
+
+ifdef EXTRA_COMPONENTS
+libs:: $(EXTRA_COMPONENTS)
+ifndef NO_DIST_INSTALL
+	$(INSTALL) $(IFLAGS1) $^ $(FINAL_TARGET)/components
+endif
+
+endif
+
+ifdef EXTRA_PP_COMPONENTS
+libs:: $(EXTRA_PP_COMPONENTS)
+ifndef NO_DIST_INSTALL
+	$(EXIT_ON_ERROR) \
+	$(NSINSTALL) -D $(FINAL_TARGET)/components; \
+	for i in $^; do \
+	  fname=`basename $$i`; \
+	  dest=$(FINAL_TARGET)/components/$${fname}; \
+	  $(RM) -f $$dest; \
+	  $(PYTHON) $(topsrcdir)/config/Preprocessor.py $(DEFINES) $(ACDEFINES) $(XULPPFLAGS) $$i > $$dest; \
+	done
+endif
+endif
+
+EXTRA_MANIFESTS = $(filter %.manifest,$(EXTRA_COMPONENTS) $(EXTRA_PP_COMPONENTS))
+ifneq (,$(EXTRA_MANIFESTS))
+libs::
+	$(PYTHON) $(MOZILLA_DIR)/config/buildlist.py $(FINAL_TARGET)/chrome.manifest $(patsubst %,"manifest components/%",$(notdir $(EXTRA_MANIFESTS)))
+endif
+
+################################################################################
+# Copy each element of EXTRA_JS_MODULES to $(FINAL_TARGET)/modules
+ifdef EXTRA_JS_MODULES
+libs:: $(EXTRA_JS_MODULES)
+ifndef NO_DIST_INSTALL
+	$(INSTALL) $(IFLAGS1) $^ $(FINAL_TARGET)/modules
+endif
+
+endif
+
+ifdef EXTRA_PP_JS_MODULES
+libs:: $(EXTRA_PP_JS_MODULES)
+ifndef NO_DIST_INSTALL
+	$(EXIT_ON_ERROR) \
+	$(NSINSTALL) -D $(FINAL_TARGET)/modules; \
+	for i in $^; do \
+	  dest=$(FINAL_TARGET)/modules/`basename $$i`; \
+	  $(RM) -f $$dest; \
+	  $(PYTHON) $(topsrcdir)/config/Preprocessor.py $(DEFINES) $(ACDEFINES) $(XULPPFLAGS) $$i > $$dest; \
+	done
+endif
+
+endif
+
+################################################################################
+# SDK
+
+ifneq (,$(SDK_LIBRARY))
+$(SDK_LIB_DIR)::
+	$(NSINSTALL) -D $@
+
+ifndef NO_DIST_INSTALL
+libs:: $(SDK_LIBRARY) $(SDK_LIB_DIR)
+	$(INSTALL) $(IFLAGS2) $^
+endif
+
+endif # SDK_LIBRARY
+
+ifneq (,$(strip $(SDK_BINARY)))
+$(SDK_BIN_DIR)::
+	$(NSINSTALL) -D $@
+
+ifndef NO_DIST_INSTALL
+libs:: $(SDK_BINARY) $(SDK_BIN_DIR)
+	$(INSTALL) $(IFLAGS2) $^
+endif
+
+endif # SDK_BINARY
+
+################################################################################
+# CHROME PACKAGING
+
+JAR_MANIFEST := $(srcdir)/jar.mn
+
+chrome::
+	$(MAKE) realchrome
+	$(LOOP_OVER_PARALLEL_DIRS)
+	$(LOOP_OVER_DIRS)
+	$(LOOP_OVER_TOOL_DIRS)
+
+$(FINAL_TARGET)/chrome:
+	$(NSINSTALL) -D $@
+
+ifneq (,$(wildcard $(JAR_MANIFEST)))
+ifndef NO_DIST_INSTALL
+libs realchrome:: $(CHROME_DEPS) $(FINAL_TARGET)/chrome
+	$(PYTHON) $(MOZILLA_DIR)/config/JarMaker.py \
+	  $(QUIET) -j $(FINAL_TARGET)/chrome \
+	  $(MAKE_JARS_FLAGS) $(XULPPFLAGS) $(DEFINES) $(ACDEFINES) \
+	  $(JAR_MANIFEST)
+endif
+endif
+
+ifneq ($(DIST_FILES),)
+$(DIST)/bin:
+	$(NSINSTALL) -D $@
+
+libs:: $(DIST)/bin
+libs:: $(DIST_FILES)
+	@$(EXIT_ON_ERROR) \
+	for f in $^; do \
+	  dest=$(FINAL_TARGET)/`basename $$f`; \
+	  $(RM) -f $$dest; \
+	  $(PYTHON) $(MOZILLA_DIR)/config/Preprocessor.py \
+	    $(XULAPP_DEFINES) $(DEFINES) $(ACDEFINES) $(XULPPFLAGS) \
+	    $$f > $$dest; \
+	done
+endif
+
+ifneq ($(DIST_CHROME_FILES),)
+libs:: $(DIST_CHROME_FILES)
+	@$(EXIT_ON_ERROR) \
+	for f in $^; do \
+	  dest=$(FINAL_TARGET)/chrome/`basename $$f`; \
+	  $(RM) -f $$dest; \
+	  $(PYTHON) $(MOZILLA_DIR)/config/Preprocessor.py \
+	    $(XULAPP_DEFINES) $(DEFINES) $(ACDEFINES) $(XULPPFLAGS) \
+	    $$f > $$dest; \
+	done
+endif
+
+ifneq ($(XPI_PKGNAME),)
+libs realchrome::
+ifdef STRIP_XPI
+ifndef MOZ_DEBUG
+	@echo "Stripping $(XPI_PKGNAME) package directory..."
+	@echo $(FINAL_TARGET)
+	@cd $(FINAL_TARGET) && find . ! -type d \
+			! -name "*.js" \
+			! -name "*.xpt" \
+			! -name "*.gif" \
+			! -name "*.jpg" \
+			! -name "*.png" \
+			! -name "*.xpm" \
+			! -name "*.txt" \
+			! -name "*.rdf" \
+			! -name "*.sh" \
+			! -name "*.properties" \
+			! -name "*.dtd" \
+			! -name "*.html" \
+			! -name "*.xul" \
+			! -name "*.css" \
+			! -name "*.xml" \
+			! -name "*.jar" \
+			! -name "*.dat" \
+			! -name "*.tbl" \
+			! -name "*.src" \
+			! -name "*.reg" \
+			$(PLATFORM_EXCLUDE_LIST) \
+			-exec $(STRIP) $(STRIP_FLAGS) {} >/dev/null 2>&1 \;
+endif
+endif
+	@echo "Packaging $(XPI_PKGNAME).xpi..."
+	cd $(FINAL_TARGET) && $(ZIP) -qr ../$(XPI_PKGNAME).xpi *
+endif
+
+ifdef INSTALL_EXTENSION_ID
+ifndef XPI_NAME
+$(error XPI_NAME must be set for INSTALL_EXTENSION_ID)
+endif
+
+libs::
+	$(RM) -r "$(DIST)/bin/extensions/$(INSTALL_EXTENSION_ID)"
+	$(NSINSTALL) -D "$(DIST)/bin/extensions/$(INSTALL_EXTENSION_ID)"
+	cd $(FINAL_TARGET) && tar $(TAR_CREATE_FLAGS) - . | (cd "../../bin/extensions/$(INSTALL_EXTENSION_ID)" && tar -xf -)
+
+endif
+
+ifneq (,$(filter flat symlink,$(MOZ_CHROME_FILE_FORMAT)))
+_JAR_REGCHROME_DISABLE_JAR=1
+else
+_JAR_REGCHROME_DISABLE_JAR=0
+endif
+
+REGCHROME = $(PERL) -I$(MOZILLA_DIR)/config $(MOZILLA_DIR)/config/add-chrome.pl \
+	$(if $(filter gtk2,$(MOZ_WIDGET_TOOLKIT)),-x) \
+	$(if $(CROSS_COMPILE),-o $(OS_ARCH)) $(FINAL_TARGET)/chrome/installed-chrome.txt \
+	$(_JAR_REGCHROME_DISABLE_JAR)
+
+REGCHROME_INSTALL = $(PERL) -I$(MOZILLA_DIR)/config $(MOZILLA_DIR)/config/add-chrome.pl \
+	$(if $(filter gtk2,$(MOZ_WIDGET_TOOLKIT)),-x) \
+	$(if $(CROSS_COMPILE),-o $(OS_ARCH)) $(DESTDIR)$(mozappdir)/chrome/installed-chrome.txt \
+	$(_JAR_REGCHROME_DISABLE_JAR)
+
+
+#############################################################################
+# Dependency system
+#############################################################################
+ifdef COMPILER_DEPEND
+depend::
+	@echo "$(MAKE): No need to run depend target.\
+			Using compiler-based depend." 1>&2
+ifeq ($(GNU_CC)$(GNU_CXX),)
+# Non-GNU compilers
+	@echo "`echo '$(MAKE):'|sed 's/./ /g'`"\
+	'(Compiler-based depend was turned on by "--enable-md".)' 1>&2
+else
+# GNU compilers
+	@space="`echo '$(MAKE): '|sed 's/./ /g'`";\
+	echo "$$space"'Since you are using a GNU compiler,\
+		it is on by default.' 1>&2; \
+	echo "$$space"'To turn it off, pass --disable-md to configure.' 1>&2
+endif
+
+else # ! COMPILER_DEPEND
+
+ifndef MOZ_AUTO_DEPS
+
+define MAKE_DEPS_NOAUTO
+	$(MKDEPEND) -w1024 -o'.$(OBJ_SUFFIX)' -f- $(DEFINES) $(ACDEFINES) $(INCLUDES) $< 2>/dev/null | sed -e "s|^[^ ]*/||" > $@
+endef
+
+$(MDDEPDIR)/%.pp: %.c
+	$(REPORT_BUILD)
+	@$(MAKE_DEPS_NOAUTO)
+
+$(MDDEPDIR)/%.pp: %.cpp
+	$(REPORT_BUILD)
+	@$(MAKE_DEPS_NOAUTO)
+
+$(MDDEPDIR)/%.pp: %.s
+	$(REPORT_BUILD)
+	@$(MAKE_DEPS_NOAUTO)
+
+ifneq (,$(OBJS)$(XPIDLSRCS)$(SIMPLE_PROGRAMS))
+depend:: $(SUBMAKEFILES) $(MAKE_DIRS) $(MDDEPFILES)
+else
+depend:: $(SUBMAKEFILES)
+endif
+	$(LOOP_OVER_PARALLEL_DIRS)
+	$(LOOP_OVER_DIRS)
+	$(LOOP_OVER_TOOL_DIRS)
+
+dependclean:: $(SUBMAKEFILES)
+	$(RM) $(MDDEPFILES)
+	$(LOOP_OVER_PARALLEL_DIRS)
+	$(LOOP_OVER_DIRS)
+	$(LOOP_OVER_TOOL_DIRS)
+
+endif # MOZ_AUTO_DEPS
+
+endif # COMPILER_DEPEND
+
+
+#############################################################################
+# MDDEPDIR is the subdirectory where all the dependency files are placed.
+#   This uses a make rule (instead of a macro) to support parallel
+#   builds (-jN). If this were done in the LOOP_OVER_DIRS macro, two
+#   processes could simultaneously try to create the same directory.
+#
+#   We use $(CURDIR) in the rule's target to ensure that we don't find
+#   a dependency directory in the source tree via VPATH (perhaps from
+#   a previous build in the source tree) and thus neglect to create a
+#   dependency directory in the object directory, where we really need
+#   it.
+
+$(CURDIR)/$(MDDEPDIR):
+	$(MKDIR) -p $@
+
+ifneq (,$(filter-out all chrome default export realchrome tools clean clobber clobber_all distclean realclean,$(MAKECMDGOALS)))
+ifneq (,$(OBJS)$(XPIDLSRCS)$(SIMPLE_PROGRAMS))
+MDDEPEND_FILES		:= $(strip $(wildcard $(MDDEPDIR)/*.pp))
+
+ifneq (,$(MDDEPEND_FILES))
+# The script mddepend.pl checks the dependencies and writes to stdout
+# one rule to force out-of-date objects. For example,
+#   foo.o boo.o: FORCE
+# The script has an advantage over including the *.pp files directly
+# because it handles the case when header files are removed from the build.
+# 'make' would complain that there is no way to build missing headers.
+ALL_PP_RESULTS = $(shell $(PERL) $(BUILD_TOOLS)/mddepend.pl - $(MDDEPEND_FILES))
+$(eval $(ALL_PP_RESULTS))
+endif
+
+endif
+endif
+#############################################################################
+
+-include $(topsrcdir)/$(MOZ_BUILD_APP)/app-rules.mk
+-include $(MY_RULES)
+
+#
+# Generate Emacs tags in a file named TAGS if ETAGS was set in $(MY_CONFIG)
+# or in $(MY_RULES)
+#
+ifdef ETAGS
+ifneq ($(CSRCS)$(CPPSRCS)$(HEADERS),)
+all:: TAGS
+TAGS:: $(CSRCS) $(CPPSRCS) $(HEADERS)
+	$(ETAGS) $(CSRCS) $(CPPSRCS) $(HEADERS)
+endif
+endif
+
+################################################################################
+# Special gmake rules.
+################################################################################
+
+
+#
+# Disallow parallel builds with MSVC < 8
+#
+ifneq (,$(filter 1200 1300 1310,$(_MSC_VER)))
+.NOTPARALLEL:
+endif
+
+#
+# Re-define the list of default suffixes, so gmake won't have to churn through
+# hundreds of built-in suffix rules for stuff we don't need.
+#
+.SUFFIXES:
+
+#
+# Fake targets.  Always run these rules, even if a file/directory with that
+# name already exists.
+#
+.PHONY: all alltags boot checkout chrome realchrome clean clobber clobber_all export install libs makefiles realclean run_apprunner tools $(DIRS) $(TOOL_DIRS) FORCE
+
+# Used as a dependency to force targets to rebuild
+FORCE:
+
+# Delete target if error occurs when building target
+.DELETE_ON_ERROR:
+
+# Properly set LIBPATTERNS for the platform
+.LIBPATTERNS = $(if $(IMPORT_LIB_SUFFIX),$(LIB_PREFIX)%.$(IMPORT_LIB_SUFFIX)) $(LIB_PREFIX)%.$(LIB_SUFFIX) $(DLL_PREFIX)%$(DLL_SUFFIX)
+
+tags: TAGS
+
+TAGS: $(SUBMAKEFILES) $(CSRCS) $(CPPSRCS) $(wildcard *.h)
+	-etags $(CSRCS) $(CPPSRCS) $(wildcard *.h)
+	$(LOOP_OVER_PARALLEL_DIRS)
+	$(LOOP_OVER_DIRS)
+
+echo-variable-%:
+	@echo "$($*)"
+
+echo-tiers:
+	@echo $(TIERS)
+
+echo-tier-dirs:
+	@$(foreach tier,$(TIERS),echo '$(tier):'; echo '  dirs: $(tier_$(tier)_dirs)'; echo '  staticdirs: $(tier_$(tier)_staticdirs)'; )
+
+echo-dirs:
+	@echo $(DIRS)
+
+echo-module:
+	@echo $(MODULE)
+
+echo-depth-path:
+	@$(topsrcdir)/build/unix/print-depth-path.sh
+
+echo-module-name:
+	@$(topsrcdir)/build/package/rpm/print-module-name.sh
+
+echo-module-filelist:
+	@$(topsrcdir)/build/package/rpm/print-module-filelist.sh
+
+showtargs:
+ifneq (,$(filter $(PROGRAM) $(HOST_PROGRAM) $(SIMPLE_PROGRAMS) $(HOST_LIBRARY) $(LIBRARY) $(SHARED_LIBRARY),$(TARGETS)))
+	@echo --------------------------------------------------------------------------------
+	@echo "PROGRAM             = $(PROGRAM)"
+	@echo "SIMPLE_PROGRAMS     = $(SIMPLE_PROGRAMS)"
+	@echo "LIBRARY             = $(LIBRARY)"
+	@echo "SHARED_LIBRARY      = $(SHARED_LIBRARY)"
+	@echo "SHARED_LIBRARY_LIBS = $(SHARED_LIBRARY_LIBS)"
+	@echo "LIBS                = $(LIBS)"
+	@echo "DEF_FILE            = $(DEF_FILE)"
+	@echo "IMPORT_LIBRARY      = $(IMPORT_LIBRARY)"
+	@echo "STATIC_LIBS         = $(STATIC_LIBS)"
+	@echo "SHARED_LIBS         = $(SHARED_LIBS)"
+	@echo "EXTRA_DSO_LIBS      = $(EXTRA_DSO_LIBS)"
+	@echo "EXTRA_DSO_LDOPTS    = $(EXTRA_DSO_LDOPTS)"
+	@echo "DEPENDENT_LIBS      = $(DEPENDENT_LIBS)"
+	@echo --------------------------------------------------------------------------------
+endif
+	$(LOOP_OVER_PARALLEL_DIRS)
+	$(LOOP_OVER_DIRS)
+
+showbuild:
+	@echo "MOZ_BUILD_ROOT     = $(MOZ_BUILD_ROOT)"
+	@echo "MOZ_WIDGET_TOOLKIT = $(MOZ_WIDGET_TOOLKIT)"
+	@echo "CC                 = $(CC)"
+	@echo "CXX                = $(CXX)"
+	@echo "CCC                = $(CCC)"
+	@echo "CPP                = $(CPP)"
+	@echo "LD                 = $(LD)"
+	@echo "AR                 = $(AR)"
+	@echo "IMPLIB             = $(IMPLIB)"
+	@echo "FILTER             = $(FILTER)"
+	@echo "MKSHLIB            = $(MKSHLIB)"
+	@echo "MKCSHLIB           = $(MKCSHLIB)"
+	@echo "RC                 = $(RC)"
+	@echo "MC                 = $(MC)"
+	@echo "CFLAGS             = $(CFLAGS)"
+	@echo "OS_CFLAGS          = $(OS_CFLAGS)"
+	@echo "COMPILE_CFLAGS     = $(COMPILE_CFLAGS)"
+	@echo "CXXFLAGS           = $(CXXFLAGS)"
+	@echo "OS_CXXFLAGS        = $(OS_CXXFLAGS)"
+	@echo "COMPILE_CXXFLAGS   = $(COMPILE_CXXFLAGS)"
+	@echo "COMPILE_CMFLAGS    = $(COMPILE_CMFLAGS)"
+	@echo "COMPILE_CMMFLAGS   = $(COMPILE_CMMFLAGS)"
+	@echo "LDFLAGS            = $(LDFLAGS)"
+	@echo "OS_LDFLAGS         = $(OS_LDFLAGS)"
+	@echo "DSO_LDOPTS         = $(DSO_LDOPTS)"
+	@echo "OS_INCLUDES        = $(OS_INCLUDES)"
+	@echo "OS_LIBS            = $(OS_LIBS)"
+	@echo "EXTRA_LIBS         = $(EXTRA_LIBS)"
+	@echo "BIN_FLAGS          = $(BIN_FLAGS)"
+	@echo "INCLUDES           = $(INCLUDES)"
+	@echo "DEFINES            = $(DEFINES)"
+	@echo "ACDEFINES          = $(ACDEFINES)"
+	@echo "BIN_SUFFIX         = $(BIN_SUFFIX)"
+	@echo "LIB_SUFFIX         = $(LIB_SUFFIX)"
+	@echo "DLL_SUFFIX         = $(DLL_SUFFIX)"
+	@echo "IMPORT_LIB_SUFFIX  = $(IMPORT_LIB_SUFFIX)"
+	@echo "INSTALL            = $(INSTALL)"
+	@echo "VPATH              = $(VPATH)"
+
+showhost:
+	@echo "HOST_CC            = $(HOST_CC)"
+	@echo "HOST_CXX           = $(HOST_CXX)"
+	@echo "HOST_CFLAGS        = $(HOST_CFLAGS)"
+	@echo "HOST_LDFLAGS       = $(HOST_LDFLAGS)"
+	@echo "HOST_LIBS          = $(HOST_LIBS)"
+	@echo "HOST_EXTRA_LIBS    = $(HOST_EXTRA_LIBS)"
+	@echo "HOST_EXTRA_DEPS    = $(HOST_EXTRA_DEPS)"
+	@echo "HOST_PROGRAM       = $(HOST_PROGRAM)"
+	@echo "HOST_OBJS          = $(HOST_OBJS)"
+	@echo "HOST_PROGOBJS      = $(HOST_PROGOBJS)"
+	@echo "HOST_LIBRARY       = $(HOST_LIBRARY)"
+
+showbuildmods::
+	@echo "Module dirs	= $(BUILD_MODULE_DIRS)"
+
+documentation:
+	@cd $(DEPTH)
+	$(DOXYGEN) $(DEPTH)/config/doxygen.cfg
+
+ifdef ENABLE_TESTS
+check:: $(SUBMAKEFILES) $(MAKE_DIRS)
+	$(LOOP_OVER_PARALLEL_DIRS)
+	$(LOOP_OVER_DIRS)
+	$(LOOP_OVER_TOOL_DIRS)
+endif
+
+
+FREEZE_VARIABLES = \
+  CSRCS \
+  CPPSRCS \
+  EXPORTS \
+  XPIDLSRCS \
+  DIRS \
+  LIBRARY \
+  MODULE \
+  SHORT_LIBNAME \
+  TIERS \
+  EXTRA_COMPONENTS \
+  EXTRA_PP_COMPONENTS \
+  $(NULL)
+
+$(foreach var,$(FREEZE_VARIABLES),$(eval $(var)_FROZEN := '$($(var))'))
+
+CHECK_FROZEN_VARIABLES = $(foreach var,$(FREEZE_VARIABLES), \
+  $(if $(subst $($(var)_FROZEN),,'$($(var))'),$(error Makefile variable '$(var)' changed value after including rules.mk. Was $($(var)_FROZEN), now $($(var)).)))
+
+libs export libs::
+	$(CHECK_FROZEN_VARIABLES)
+
+default all::
+	if test -d $(DIST)/bin ; then touch $(DIST)/bin/.purgecaches ; fi
new file mode 100644
--- /dev/null
+++ b/config/tests/makefiles/autodeps/Makefile.in
@@ -0,0 +1,41 @@
+# -*- makefile -*-
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this file,
+# You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+PYTHON ?= python
+PYTEST = $(PYTHON) -E
+
+# python -B not supported by older interpreters
+export PYTHONDONTWRITEBYTECODE=1
+
+DEPTH     = ../../../..
+topsrcdir = @top_srcdir@
+srcdir    = @srcdir@
+VPATH     = @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+include $(topsrcdir)/config/config.mk
+include $(topsrcdir)/config/rules.mk
+
+autotgt_tests = .deps/autotargets.mk.ts
+
+tgts =\
+  .deps/.mkdir.done\
+  $(autotgt_tests)
+  $(NULL)
+
+
+##------------------_##
+##---]  TARGETS  [---##
+##------------------_##
+all::
+
+check:: $(tgts)
+
+# Only run unit test when autotargets.mk is modified
+$(autotgt_tests): $(topsrcdir)/config/makefiles/autotargets.mk
+	MAKECMD=$(MAKE) $(PYTEST) $(srcdir)/check_mkdir.tpy
+	@$(TOUCH) $@
new file mode 100644
--- /dev/null
+++ b/config/tests/makefiles/autodeps/check_mkdir.tpy
@@ -0,0 +1,271 @@
+#!/usr/bin/env python
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this file,
+# You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+import os
+import sys
+import tempfile
+
+from subprocess import call
+from shutil     import rmtree
+
+import logging
+import unittest
+
+
+def banner():
+    """
+    Display interpreter and system info for the test env
+    """
+    print '*' * 75
+    cmd = os.path.basename(__file__)
+    print "%s: python version is %s" % (cmd, sys.version)
+    print '*' * 75
+
+
+def myopts(vals):
+    """
+    Storage for extra command line args passed.
+
+    Returns:
+    hash - argparse::Namespace object values
+    """
+
+    if not hasattr(myopts, 'vals'):
+        if 'argparse' in sys.modules:
+            tmp = { } # key existance enables unittest module debug
+        else:
+            tmp = { 'debug': False, 'verbose': False }
+
+        for k in dir(vals):
+            if k[0:1] == '_':
+                continue
+            tmp[k] = getattr(vals, k)
+        myopts.vals = tmp
+
+    return myopts.vals
+    
+
+def path2posix(src):
+    """
+    Normalize directory path syntax
+
+    Keyword arguments:
+    src - path to normalize
+
+    Returns:
+    scalar - a file path with drive separators and windows slashes removed
+
+    Todo:
+    move to {build,config,tools,toolkit}/python for use in a library
+    """
+
+    ## (drive, tail) = os.path.splitdrive(src)
+    ## Support path testing on all platforms
+    drive = ''
+    winpath = src.find(':')
+    if -1 != winpath and 10 > winpath:
+        (drive, tail) = src.split(':', 2)
+
+    if drive:
+        todo = [ '', drive.rstrip(':').lstrip('/').lstrip('\\') ]
+        todo.extend( tail.lstrip('/').lstrip('\\').split('\\') ) # c:\a => [a]
+    else: # os.name == 'posix'
+        todo = src.split('\\')
+
+    dst = '/'.join(todo)
+    return dst
+    
+
+def checkMkdir(work, debug=False):
+    """
+    Verify arg permutations for directory mutex creation.
+
+    Keyword arguments:
+    None
+
+    Returns:
+    Exception on error
+
+    Note:
+    Exception() rather than self.assertTrue() is used in this test
+    function to enable scatch cleanup on test exit/failure conditions.
+    Not guaranteed by python closures on early exit.
+    """
+
+    logging.debug("Testing: checkMkdir")
+
+    if False:
+        path = os.path.abspath(__file__).split(os.sep)
+    else:
+        path = path2posix(os.path.abspath(__file__)).split('/')
+        
+    root = os.path.join(os.sep, *path[:-5])
+    src = os.path.join(os.sep, *path[:-1])
+
+    rootP = path2posix(root)
+    srcP  = path2posix(src)
+    workP = path2posix(work)
+
+    # C:\foo -vs- /c/foo
+    # [0] command paths use /c/foo
+    # [1] os.path.exists() on mingw() requires C:\
+    paths = [
+        [ # function generated
+            "%s/mkdir_bycall" % (workP),
+            "%s/mkdir_bycall" % (work),
+        ],
+        [ # explicit dependency
+            "%s/mkdir_bydep"  % (workP),
+            "%s/mkdir_bydep"  % (work),
+        ],
+        [ # by GENERATED_DIRS macro
+            "%s/mkdir_bygen"  % (workP),
+            "%s/mkdir_bygen"  % (work),
+        ]
+        ]
+
+    ## Use make from the parent "make check" call when available
+    cmd = { 'make': 'make' }
+    shell0 = os.environ.get('MAKECMD')
+    if shell0:
+        shell = os.path.splitext(shell0)[0] # strip: .exe, .py
+        if -1 != shell.find('make'):
+            print "MAKE COMMAND FOUND: %s" % (shell0)
+            cmd['make'] = path2posix(shell0)
+
+    args = []
+    args.append('%s' % (cmd['make']))
+    args.append('-C %s'                % (workP))
+    args.append("-f %s/testor.tmpl"    % (srcP))
+    args.append('topsrcdir=%s'         % (rootP))
+    args.append('deps_mkdir_bycall=%s' % paths[0][0])
+    args.append('deps_mkdir_bydep=%s'  % paths[1][0])
+    args.append('deps_mkdir_bygen=%s'  % paths[2][0])
+    args.append('checkup') # target
+
+    # Call will fail on mingw with output redirected ?!?
+    if debug:
+        pass
+    if False: # if not debug:
+        args.append('>/dev/null')
+
+    cmd = '%s' % (' '.join(args))
+    logging.debug("Running: %s" % (cmd))
+    rc = call(cmd, shell=True)
+    if rc:
+        raise Exception("make failed ($?=%s): cmd=%s" % (rc, cmd))
+
+    for i in paths:
+        logging.debug("Did testing mkdir(%s) succeed?" % (i[1]))
+        if not os.path.exists(i[1]):
+            raise Exception("Test path %s does not exist" % (i[1]))
+
+
+def parseargs():
+    """
+    Support additional command line arguments for testing
+    
+    Returns:
+    hash - arguments of interested parsed from the command line
+    """
+
+    opts = None
+    try:
+        import argparse2
+        parser = argparse.ArgumentParser()
+        parser.add_argument('--debug',
+                            action="store_true",
+                            default=False,
+                            help='Enable debug mode')
+        # Cannot overload verbose, Verbose: False enables debugging
+        parser.add_argument('--verbose',
+                            action="store_true",
+                            default=False,
+                            help='Enable verbose mode')
+        parser.add_argument('unittest_args',
+                            nargs='*'
+                            # help='Slurp/pass remaining args to unittest'
+                            )
+        opts = parser.parse_args()
+
+    except ImportError:
+        pass
+
+    return opts
+
+
+class TestMakeLogic(unittest.TestCase):
+    """
+    Test suite used to validate makefile library rules and macros
+    """
+
+    def setUp(self):
+        opts = myopts(None) # NameSpace object not hash
+        self.debug   = opts['debug']
+        self.verbose = opts['verbose']
+
+        if self.debug:
+            logging.basicConfig(level=logging.DEBUG)
+
+        if self.verbose:
+            print
+            print "ENVIRONMENT DUMP:"
+            print '=' * 75
+            for k,v in os.environ.items():
+                print "env{%s} => %s" % (k, v)
+            print
+
+
+    def test_path2posix(self):
+
+        todo = {
+            '/dev/null'     : '/dev/null',
+            'A:\\a\\b\\c'   : '/A/a/b/c',
+            'B:/x/y'        : '/B/x/y',
+            'C:/x\\y/z'     : '/C/x/y/z',
+            '//FOO/bar/tans': '//FOO/bar/tans',
+            '//X\\a/b\\c/d' : '//X/a/b/c/d',
+            '\\c:mozilla\\sandbox': '/c/mozilla/sandbox',
+        }
+
+        for val,exp in todo.items():
+            found = path2posix(val)
+            tst = "posix2path(%s): %s != %s)" % (val, exp, found)
+            self.assertEqual(exp, found, "%s: invalid path detected" % (tst))
+
+
+    def test_mkdir(self):
+        """
+        Verify directory creation rules and macros
+        """
+
+        failed = True
+
+        # Exception handling is used to cleanup scratch space on error
+        try:
+            work = tempfile.mkdtemp()
+            checkMkdir(work, self.debug)
+            failed = False
+        finally:
+            if os.path.exists(work):
+                rmtree(work)
+
+        self.assertFalse(failed, "Unit test failure detected")
+
+
+if __name__ == '__main__':
+    banner()
+    opts = parseargs()
+    myopts(opts)
+
+    if opts:
+        if hasattr(opts, 'unittest_args'):
+            sys.argv[1:] = opts.unittest_args
+        else:
+            sys.argv[1:] = []
+
+    unittest.main()
new file mode 100644
--- /dev/null
+++ b/config/tests/makefiles/autodeps/testor.tmpl
@@ -0,0 +1,63 @@
+# -*- makefile -*-
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this file,
+# You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+###########################################################################
+## Intent: Standalone unit tests for makefile rules and target logic
+###########################################################################
+
+deps =$(NULL)
+tgts =$(NULL)
+
+ifdef VERBOSE
+  tgts += show
+endif
+
+# Define macros
+include $(topsrcdir)/config/makefiles/makeutils.mk
+include $(topsrcdir)/config/makefiles/autotargets.mk
+
+##########################
+## Verify threadsafe mkdir
+##########################
+ifdef deps_mkdir_bycall
+  deps += $(call mkdir_deps,deps_mkdir_bycall)
+  tgts += check_mkdir
+endif
+ifdef deps_mkdir_bydep
+  deps += $(foreach dir,$(deps_mkdir_bydep),$(dir)/.mkdir.done)
+  tgts += check_mkdir
+endif
+ifdef deps_mkdir_bygen
+  GENERATED_DIRS += $(deps_mkdir_bygen)
+  tgts += check_mkdir
+endif
+
+###########################
+## Minimal environment load
+###########################
+MKDIR ?= mkdir -p
+TOUCH ?= touch
+
+INCLUDED_CONFIG_MK = 1
+include $(topsrcdir)/config/rules.mk
+
+##-------------------##
+##---]  TARGETS  [---##
+##-------------------##
+all::
+
+# Quarks:
+#   o Use of 'all' would trigger export target processing
+checkup: $(tgts)
+
+# AUTO_DEPS - verify GENERATED_DIRS
+check_mkdir: $(deps) $(AUTO_DEPS)
+
+show:
+	@echo "tgts=[$(tgts)]"
+	@echo "deps=[$(deps)]"
+	find $(dir $(deps)) -print
--- a/configure.in
+++ b/configure.in
@@ -1702,46 +1702,55 @@ if test "$GNU_CC"; then
     fi
     WARNINGS_AS_ERRORS='-Werror -Wno-error=uninitialized'
     DSO_CFLAGS=''
     DSO_PIC_CFLAGS='-fPIC'
     ASFLAGS="$ASFLAGS -fPIC"
     _MOZ_RTTI_FLAGS_ON=-frtti
     _MOZ_RTTI_FLAGS_OFF=-fno-rtti
 
-    # Turn on GNU specific features
-    # -Wall - turn on all warnings
-    # -pedantic - make compiler warn about non-ANSI stuff, and
-    #             be a little bit stricter
+    # Turn on GNU-specific warnings:
+    # -Wall - turn on a lot of warnings
+    # -pedantic - this is turned on below
+    # -Wpointer-arith - enabled with -pedantic, but good to have even if not
     # -Wdeclaration-after-statement - MSVC doesn't like these
-    # Warnings slamm took out for now (these were giving more noise than help):
-    # -Wbad-function-cast - warns when casting a function to a new return type
-    # -Wshadow - removed because it generates more noise than help --pete
-    _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wall -W -Wno-unused -Wpointer-arith -Wdeclaration-after-statement"
+    # -Werror=return-type - catches missing returns, zero false positives
+    # -Wtype-limits - catches overflow bugs, few false positives
+    # -Wempty-body - catches bugs, e.g. "if (c); foo();", few false positives
+    #
+    _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wall -Wpointer-arith -Wdeclaration-after-statement"
+    MOZ_C_SUPPORTS_WARNING(-W, error=return-type, ac_c_has_werror_return_type)
+    MOZ_C_SUPPORTS_WARNING(-W, type-limits, ac_c_has_wtype_limits)
+    MOZ_C_SUPPORTS_WARNING(-W, empty-body, ac_c_has_wempty_body)
+    
+    # Turn off the following warnings that -Wall/-pedantic turn on:
+    # -Wno-unused - lots of violations in third-party code
+    # -Wno-overlength-strings - we exceed the minimum maximum length frequently
+    #
+    _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wno-unused"
+    MOZ_C_SUPPORTS_WARNING(-Wno-, overlength-strings, ac_c_has_wno_overlength_strings)
+
     if test -z "$INTEL_CC" -a -z "$CLANG_CC"; then
        # Don't use -Wcast-align with ICC or clang
        case "$CPU_ARCH" in
            # And don't use it on hppa, ia64, sparc, arm, since it's noisy there
            hppa | ia64 | sparc | arm)
            ;;
            *)
         _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wcast-align"
            ;;
        esac
     fi
 
     dnl Turn pedantic on but disable the warnings for long long
     _PEDANTIC=1
 
-    if test -z "$INTEL_CC"; then
-      _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -W"
-    fi
-
     _DEFINES_CFLAGS='-include $(DEPTH)/mozilla-config.h -DMOZILLA_CLIENT'
     _USE_CPP_INCLUDE_FLAG=1
+
 elif test "$SOLARIS_SUNPRO_CC"; then
     DSO_CFLAGS=''
     if test "$CPU_ARCH" = "sparc"; then
         # for Sun Studio on Solaris/SPARC
         DSO_PIC_CFLAGS='-xcode=pic32'
     else
         DSO_PIC_CFLAGS='-KPIC'
     fi
@@ -1759,18 +1768,42 @@ else
     DSO_CFLAGS=''
     DSO_PIC_CFLAGS='-KPIC'
     _DEFINES_CFLAGS='$(ACDEFINES) -D_MOZILLA_CONFIG_H_ -DMOZILLA_CLIENT'
 fi
 
 if test "$GNU_CXX"; then
     # FIXME: Let us build with strict aliasing. bug 414641.
     CXXFLAGS="$CXXFLAGS -fno-exceptions -fno-strict-aliasing"
-    # Turn on GNU specific features
-    _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wall -Wpointer-arith -Woverloaded-virtual -Wsynth -Wno-ctor-dtor-privacy -Wno-non-virtual-dtor"
+
+    # Turn on GNU-specific warnings:
+    # -Wall - turn on a lot of warnings
+    # -pedantic - this is turned on below
+    # -Wpointer-arith - enabled with -pedantic, but good to have even if not
+    # -Woverloaded-virtual - ???
+    # -Werror=return-type - catches missing returns, zero false positives
+    # -Wtype-limits - catches overflow bugs, few false positives
+    # -Wempty-body - catches bugs, e.g. "if (c); foo();", few false positives
+    #
+    _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wall -Wpointer-arith -Woverloaded-virtual"
+    MOZ_CXX_SUPPORTS_WARNING(-W, error=return-type, ac_cxx_has_werror_return_type)
+    MOZ_CXX_SUPPORTS_WARNING(-W, type-limits, ac_cxx_has_wtype_limits)
+    MOZ_CXX_SUPPORTS_WARNING(-W, empty-body, ac_cxx_has_wempty_body)
+
+    # Turn off the following warnings that -Wall/-pedantic turn on:
+    # -Wno-ctor-dtor-privacy - ???
+    # -Wno-overlength-strings - we exceed the minimum maximum length frequently 
+    # -Wno-invalid-offsetof - we use offsetof on non-POD types frequently
+    # -Wno-variadic-macros - ???
+    #
+    _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-ctor-dtor-privacy"
+    MOZ_CXX_SUPPORTS_WARNING(-Wno-, overlength-strings, ac_cxx_has_wno_overlength_strings)
+    MOZ_CXX_SUPPORTS_WARNING(-Wno-, invalid-offsetof, ac_cxx_has_wno_invalid_offsetof)
+    MOZ_CXX_SUPPORTS_WARNING(-Wno-, variadic-macros, ac_cxx_has_wno_variadic_macros)
+
     if test -z "$INTEL_CXX" -a -z "$CLANG_CXX"; then
        # Don't use -Wcast-align with ICC or clang
        case "$CPU_ARCH" in
            # And don't use it on hppa, ia64, sparc, arm, since it's noisy there
            hppa | ia64 | sparc | arm)
            ;;
            *)
         _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wcast-align"
@@ -1784,91 +1817,17 @@ if test "$GNU_CXX"; then
     # Recent clang and gcc support C++11 deleted functions without warnings if
     # compiling with -std=c++0x or -std=gnu++0x (or c++11 or gnu++11 in very new
     # versions).  We can't use -std=c++0x yet, so gcc's support must remain
     # unused.  But clang's warning can be disabled, so when compiling with clang
     # we use it to opt out of the warning, enabling (macro-encapsulated) use of
     # deleted function syntax.
     if test "$CLANG_CXX"; then
         _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-c++0x-extensions"
-    fi
-
-    AC_CACHE_CHECK(whether the compiler supports -Wno-extended-offsetof,
-                   ac_has_wno_extended_offsetof,
-        [
-            AC_LANG_SAVE
-            AC_LANG_CPLUSPLUS
-            _SAVE_CXXFLAGS="$CXXFLAGS"
-            CXXFLAGS="$CXXFLAGS -Wno-extended-offsetof"
-            AC_TRY_COMPILE([$configure_static_assert_macros
-                            #ifndef __has_warning
-                            #define __has_warning(x) 0
-                            #endif],
-                           [CONFIGURE_STATIC_ASSERT(__has_warning("-Wextended-offsetof"))],
-                           ac_has_wno_extended_offsetof="yes",
-                           ac_has_wno_extended_offsetof="no")
-            CXXFLAGS="$_SAVE_CXXFLAGS"
-            AC_LANG_RESTORE
-        ])
-    if test "$ac_has_wno_extended_offsetof" = "yes"; then
-        _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-extended-offsetof"
-    fi
-
-    AC_CACHE_CHECK(whether the compiler supports -Wno-invalid-offsetof,
-                   ac_has_wno_invalid_offsetof,
-        [
-            AC_LANG_SAVE
-            AC_LANG_CPLUSPLUS
-            _SAVE_CXXFLAGS="$CXXFLAGS"
-            CXXFLAGS="$CXXFLAGS -Wno-invalid-offsetof"
-            AC_TRY_COMPILE([],
-                           [return(0);],
-                           ac_has_wno_invalid_offsetof="yes",
-                           ac_has_wno_invalid_offsetof="no")
-            CXXFLAGS="$_SAVE_CXXFLAGS"
-            AC_LANG_RESTORE
-        ])
-    if test "$ac_has_wno_invalid_offsetof" = "yes"; then
-        _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-invalid-offsetof"
-    fi
-
-    AC_CACHE_CHECK(whether the compiler supports -Wno-variadic-macros,
-                   ac_has_wno_variadic_macros,
-        [
-            AC_LANG_SAVE
-            AC_LANG_CPLUSPLUS
-            _SAVE_CXXFLAGS="$CXXFLAGS"
-            CXXFLAGS="$CXXFLAGS -Wno-variadic-macros"
-            AC_TRY_COMPILE([],
-                           [return(0);],
-                           ac_has_wno_variadic_macros="yes",
-                           ac_has_wno_variadic_macros="no")
-            CXXFLAGS="$_SAVE_CXXFLAGS"
-            AC_LANG_RESTORE
-        ])
-    if test "$ac_has_wno_variadic_macros" = "yes"; then
-        _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-variadic-macros"
-    fi
-
-    AC_CACHE_CHECK(whether the compiler supports -Werror=return-type,
-                   ac_has_werror_return_type,
-        [
-            AC_LANG_SAVE
-            AC_LANG_CPLUSPLUS
-            _SAVE_CXXFLAGS="$CXXFLAGS"
-            CXXFLAGS="$CXXFLAGS -Werror=return-type"
-            AC_TRY_COMPILE([],
-                           [return(0);],
-                           ac_has_werror_return_type="yes",
-                           ac_has_werror_return_type="no")
-            CXXFLAGS="$_SAVE_CXXFLAGS"
-            AC_LANG_RESTORE
-        ])
-    if test "$ac_has_werror_return_type" = "yes"; then
-        _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Werror=return-type"
+        MOZ_CXX_SUPPORTS_WARNING(-Wno-, extended-offsetof, ac_cxx_has_wno_extended_offsetof)
     fi
 
 else
     _DEFINES_CXXFLAGS='-DMOZILLA_CLIENT -D_MOZILLA_CONFIG_H_ $(ACDEFINES)'
 fi
 
 dnl gcc can come with its own linker so it is better to use the pass-thru calls
 dnl MKSHLIB_FORCE_ALL is used to force the linker to include all object
--- a/content/base/src/nsDOMMutationObserver.cpp
+++ b/content/base/src/nsDOMMutationObserver.cpp
@@ -140,22 +140,45 @@ NS_IMPL_CYCLE_COLLECTING_RELEASE(nsMutat
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsMutationReceiver)
   NS_INTERFACE_MAP_ENTRY(nsISupports)
   NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
   NS_INTERFACE_MAP_ENTRY(nsMutationReceiver)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsMutationReceiver)
-  tmp->Disconnect();
+  tmp->Disconnect(false);
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsMutationReceiver)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
+void
+nsMutationReceiver::Disconnect(bool aRemoveFromObserver)
+{
+  if (mRegisterTarget) {
+    mRegisterTarget->RemoveMutationObserver(this);
+    mRegisterTarget = nsnull;
+  }
+
+  mParent = nsnull;
+  nsINode* target = mTarget;
+  mTarget = nsnull;
+  nsIDOMMozMutationObserver* observer = mObserver;
+  mObserver = nsnull;
+  RemoveClones();
+
+  if (target && observer) {
+    if (aRemoveFromObserver) {
+      static_cast<nsDOMMutationObserver*>(observer)->RemoveReceiver(this);
+    }
+    // UnbindObject may delete 'this'!
+    target->UnbindObject(observer);
+  }
+}
 
 void
 nsMutationReceiver::AttributeWillChange(nsIDocument* aDocument,
                                         mozilla::dom::Element* aElement,
                                         PRInt32 aNameSpaceID,
                                         nsIAtom* aAttribute,
                                         PRInt32 aModType)
 {
@@ -377,17 +400,17 @@ NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsDOMMutationObserver)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsDOMMutationObserver)
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDOMMutationObserver)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mScriptContext)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOwner)
   for (PRInt32 i = 0; i < tmp->mReceivers.Count(); ++i) {
-    tmp->mReceivers[i]->Disconnect();
+    tmp->mReceivers[i]->Disconnect(false);
   }
   tmp->mReceivers.Clear();
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mPendingMutations)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCallback)
   // No need to handle mTransientReceivers
   NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsDOMMutationObserver)
@@ -416,16 +439,22 @@ nsDOMMutationObserver::GetReceiverFor(ns
   }
 
   nsMutationReceiver* r = new nsMutationReceiver(aNode, this);
   mReceivers.AppendObject(r);
   return r;
 }
 
 void
+nsDOMMutationObserver::RemoveReceiver(nsMutationReceiver* aReceiver)
+{
+  mReceivers.RemoveObject(aReceiver);
+}
+
+void
 nsDOMMutationObserver::GetAllSubtreeObserversFor(nsINode* aNode,
                                                  nsTArray<nsMutationReceiver*>&
                                                    aReceivers)
 {
   nsINode* n = aNode;
   while (n) {
     if (n->MayHaveDOMMutationObserver()) {
       nsMutationReceiver* r = GetReceiverFor(n, false);
@@ -522,24 +551,32 @@ nsDOMMutationObserver::Observe(nsIDOMNod
   r->SetAttributes(d.attributes);
   r->SetCharacterData(d.characterData);
   r->SetSubtree(d.subtree);
   r->SetAttributeOldValue(d.attributeOldValue);
   r->SetCharacterDataOldValue(d.characterDataOldValue);
   r->SetAttributeFilter(filters);
   r->SetAllAttributes(allAttrs);
   r->RemoveClones();
+
+#ifdef DEBUG
+  for (PRInt32 i = 0; i < mReceivers.Count(); ++i) {
+    NS_WARN_IF_FALSE(mReceivers[i]->Target(),
+                     "All the receivers should have a target!");
+  }
+#endif
+
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMMutationObserver::Disconnect()
 {
   for (PRInt32 i = 0; i < mReceivers.Count(); ++i) {
-    mReceivers[i]->Disconnect();
+    mReceivers[i]->Disconnect(false);
   }
   mReceivers.Clear();
   mCurrentMutations.Clear();
   mPendingMutations.Clear();
   return NS_OK;
 }
 
 
@@ -832,13 +869,15 @@ nsAutoMutationBatch::Done()
       nsDOMMutationRecord* m =
         new nsDOMMutationRecord(NS_LITERAL_STRING("childList"));
       ob->mPendingMutations.AppendObject(m);
       m->mTarget = mBatchTarget;
       m->mRemovedNodes = removedList;
       m->mAddedNodes = addedList;
       m->mPreviousSibling = mPrevSibling;
       m->mNextSibling = mNextSibling;
-      ob->ScheduleForRun();
     }
+    // Always schedule the observer so that transient receivers are
+    // removed correctly.
+    ob->ScheduleForRun();
   }
   nsDOMMutationObserver::LeaveMutationHandling();
 }
--- a/content/base/src/nsDOMMutationObserver.h
+++ b/content/base/src/nsDOMMutationObserver.h
@@ -146,17 +146,18 @@ protected:
   {
     mRegisterTarget->AddMutationObserver(this);
     mRegisterTarget->SetMayHaveDOMMutationObserver();
     mRegisterTarget->OwnerDoc()->SetMayHaveDOMMutationObservers();
   }
 
   nsMutationReceiverBase(nsINode* aRegisterTarget,
                          nsMutationReceiverBase* aParent)
-  : mObserver(nsnull), mParent(aParent), mRegisterTarget(aRegisterTarget)
+  : mTarget(nsnull), mObserver(nsnull), mParent(aParent),
+    mRegisterTarget(aRegisterTarget)
   {
     NS_ASSERTION(mParent->Subtree(), "Should clone a non-subtree observer!");
     mRegisterTarget->AddMutationObserver(this);
     mRegisterTarget->SetMayHaveDOMMutationObserver();
     mRegisterTarget->OwnerDoc()->SetMayHaveDOMMutationObservers();
   }
 
   bool ObservesAttr(mozilla::dom::Element* aElement,
@@ -223,58 +224,46 @@ public:
   nsMutationReceiver(nsINode* aRegisterTarget, nsMutationReceiverBase* aParent)
   : nsMutationReceiverBase(aRegisterTarget, aParent)
   {
     NS_ASSERTION(!static_cast<nsMutationReceiver*>(aParent)->GetParent(),
                  "Shouldn't create deep observer hierarchies!");
     aParent->AddClone(this);
   }
 
-  virtual ~nsMutationReceiver() { Disconnect(); }
+  virtual ~nsMutationReceiver() { Disconnect(false); }
 
   nsMutationReceiver* GetParent()
   {
     return static_cast<nsMutationReceiver*>(mParent.get());
   }
 
   void RemoveClones()
   {
     for (PRInt32 i = 0; i < mTransientReceivers.Count(); ++i) {
       nsMutationReceiver* r =
         static_cast<nsMutationReceiver*>(mTransientReceivers[i]);
-      r->Disconnect();
+      r->DisconnectTransientReceiver();
     }
     mTransientReceivers.Clear();
   }
 
-  void DisconnectTransientReceivers()
+  void DisconnectTransientReceiver()
   {
     if (mRegisterTarget) {
       mRegisterTarget->RemoveMutationObserver(this);
       mRegisterTarget = nsnull;
     }
 
     mParent = nsnull;
+    NS_ASSERTION(!mTarget, "Should not have mTarget");
+    NS_ASSERTION(!mObserver, "Should not have mObserver");
   }
 
-  void Disconnect()
-  {
-    if (mRegisterTarget) {
-      mRegisterTarget->RemoveMutationObserver(this);
-      mRegisterTarget = nsnull;
-    }
-    if (mTarget && mObserver) {
-      mTarget->UnbindObject(mObserver);
-    }
-
-    mParent = nsnull;
-    mTarget = nsnull;
-    mObserver = nsnull;
-    RemoveClones();
-  }
+  void Disconnect(bool aRemoveFromObserver);
 
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_IMUTATION_OBSERVER_IID)
   NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS(nsMutationReceiver)
 
   virtual void AttributeWillChange(nsIDocument* aDocument,
                                    mozilla::dom::Element* aElement,
@@ -295,17 +284,18 @@ public:
   virtual void ContentRemoved(nsIDocument *aDocument,
                               nsIContent* aContainer,
                               nsIContent* aChild,
                               PRInt32 aIndexInContainer,
                               nsIContent* aPreviousSibling);
 
   virtual void NodeWillBeDestroyed(const nsINode *aNode)
   {
-    Disconnect();
+    NS_ASSERTION(!mParent, "Shouldn't have mParent here!");
+    Disconnect(true);
   }
   
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsMutationReceiver, NS_MUTATION_OBSERVER_IID)
 
 class nsDOMMutationObserver : public nsIDOMMozMutationObserver,
                               public nsIJSNativeInitializer
@@ -342,16 +332,18 @@ public:
     return sCurrentObserver;
   }
 
   static void Shutdown();
 protected:
   friend class nsMutationReceiver;
   friend class nsAutoMutationBatch;
   nsMutationReceiver* GetReceiverFor(nsINode* aNode, bool aMayCreate);
+  void RemoveReceiver(nsMutationReceiver* aReceiver);
+
   void GetAllSubtreeObserversFor(nsINode* aNode,
                                  nsTArray<nsMutationReceiver*>& aObservers);
   void ScheduleForRun();
   void RescheduleForRun();
 
   nsDOMMutationRecord* CurrentRecord(const nsAString& aType);
   bool HasCurrentRecord(const nsAString& aType);
 
--- a/content/base/src/nsScriptElement.cpp
+++ b/content/base/src/nsScriptElement.cpp
@@ -56,34 +56,21 @@ nsScriptElement::ScriptAvailable(nsresul
                                  bool aIsInline,
                                  nsIURI *aURI,
                                  PRInt32 aLineNo)
 {
   if (!aIsInline && NS_FAILED(aResult)) {
     nsCOMPtr<nsIContent> cont =
       do_QueryInterface((nsIScriptElement*) this);
 
-    nsRefPtr<nsPresContext> presContext =
-      nsContentUtils::GetContextForContent(cont);
-
-    nsEventStatus status = nsEventStatus_eIgnore;
-    nsScriptErrorEvent event(true, NS_LOAD_ERROR);
-
-    event.lineNr = aLineNo;
-
-    NS_NAMED_LITERAL_STRING(errorString, "Error loading script");
-    event.errorMsg = errorString.get();
-
-    nsCAutoString spec;
-    aURI->GetSpec(spec);
-
-    NS_ConvertUTF8toUTF16 fileName(spec);
-    event.fileName = fileName.get();
-
-    nsEventDispatcher::Dispatch(cont, presContext, &event, nsnull, &status);
+    return nsContentUtils::DispatchTrustedEvent(cont->OwnerDoc(),
+                                                cont,
+                                                NS_LITERAL_STRING("error"),
+                                                false /* bubbles */,
+                                                false /* cancelable */);
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsScriptElement::ScriptEvaluated(nsresult aResult,
                                  nsIScriptElement *aElement,
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -281,16 +281,17 @@ include $(topsrcdir)/config/rules.mk
 		file_CrossSiteXHR_cache_server.sjs \
 		test_XHRDocURI.html \
 		file_XHRDocURI.xml \
 		file_XHRDocURI.xml^headers^ \
 		file_XHRDocURI.text \
 		file_XHRDocURI.text^headers^ \
 		test_DOMException.html \
 		test_mutationobservers.html \
+		mutationobserver_dialog.html \
 		$(NULL)
 
 _TEST_FILES2 = \
 		test_bug459424.html \
 		bug461735-redirect1.sjs \
 		bug461735-redirect2.sjs \
 		bug461735-post-redirect.js \
 		test_bug513194.html \
@@ -570,16 +571,17 @@ include $(topsrcdir)/config/rules.mk
 		test_bug366944.html \
 		test_bug650386_redirect_301.html \
 		test_bug650386_redirect_302.html \
 		test_bug650386_redirect_303.html \
 		test_bug650386_redirect_307.html \
 		file_bug650386_content.sjs \
 		file_bug650386_report.sjs \
 		test_bug719533.html \
+		test_bug737087.html \
 		$(NULL)
 
 _CHROME_FILES =	\
 		test_bug357450.js \
 		$(NULL)
 
 # This test fails on the Mac for some reason
 ifneq (,$(filter gtk2 windows,$(MOZ_WIDGET_TOOLKIT)))
new file mode 100644
--- /dev/null
+++ b/content/base/test/mutationobserver_dialog.html
@@ -0,0 +1,62 @@
+<html>
+  <head>
+    <title></title>
+    <script>
+
+    var div = document.createElement("div");
+
+    var M;
+    if ("MozMutationObserver" in window) {
+      M = window.MozMutationObserver;
+    } else if ("WebKitMutationObserver" in window) {
+      M = window.WebKitMutationObserver;
+    } else {
+      M = window.MutationObserver;
+    }
+
+    var didCall1 = false;
+    var didCall2 = false;
+    function testMutationObserverInDialog() {
+      div.innerHTML = "<span>1</span><span>2</span>";
+      m = new M(function(records, observer) {
+          opener.is(records[0].type, "childList", "Should have got childList");
+          opener.is(records[0].removedNodes.length, 2, "Should have got removedNodes");
+          opener.is(records[0].addedNodes.length, 1, "Should have got addedNodes");
+          observer.disconnect();
+          m = null;
+          didCall1 = true;
+        });
+      m.observe(div, { childList: true });
+      div.innerHTML = "<span><span>foo</span></span>";
+    }
+
+    function testMutationObserverInDialog2() {
+      div.innerHTML = "<span>1</span><span>2</span>";
+      m = new M(function(records, observer) {
+          opener.is(records[0].type, "childList", "Should have got childList");
+          opener.is(records[0].removedNodes.length, 2, "Should have got removedNodes");
+          opener.is(records[0].addedNodes.length, 1, "Should have got addedNodes");
+          observer.disconnect();
+          m = null;
+          didCall2 = true;
+        });
+      m.observe(div, { childList: true });
+      div.innerHTML = "<span><span>foo</span></span>";
+    }
+
+    window.addEventListener("load", testMutationObserverInDialog);
+    window.addEventListener("load", testMutationObserverInDialog2);
+    window.addEventListener("load",
+      function() {
+        opener.ok(didCall1, "Should have called 1st mutation callback");
+        opener.ok(didCall2, "Should have called 2nd mutation callback");
+        window.close();
+      });
+    </script>
+    <style>
+    </style>
+  </head>
+  <body>
+    <input type="button" onclick="window.close()" value="close">
+  </body>
+</html>
--- a/content/base/test/test_blobconstructor.html
+++ b/content/base/test/test_blobconstructor.html
@@ -58,16 +58,32 @@ ok(true, "a null options member should t
 
 try {
 blob = Blob([], undefined);
 ok(false, "NOT REACHED");
 } catch(e) {
 ok(true, "an undefined options member should throw");
 }
 
+/** Test for dictionary initialization order **/
+(function() {
+  var o = {};
+  var p = {type: "text/plain", endings: "transparent"};
+  var called = [];
+  function add_to_called(n) {
+    called.push(n);
+    return p[n];
+  }
+  ["type", "endings"].forEach(function(n) {
+    Object.defineProperty(o, n, { get: add_to_called.bind(null, n) });
+  });
+  var b = new Blob([], o);
+  is(JSON.stringify(called), JSON.stringify(["endings", "type"]), "dictionary members should be get in lexicographical order");
+})();
+
 let blob1 = Blob(["squiggle"]);
 ok(blob1 instanceof Blob, "Blob constructor should produce Blobs");
 ok(!(blob1 instanceof File), "Blob constructor should not produce Files");
 is(blob1.type, "", "Blob constructor with no options should return Blob with empty type");
 is(blob1.size, 8, "Blob constructor should return Blob with correct size");
 
 let blob2 = Blob(["steak"], {type: "content/type"});
 ok(blob2 instanceof Blob, "Blob constructor should produce Blobs");
--- a/content/base/test/test_bug696301-1.html
+++ b/content/base/test/test_bug696301-1.html
@@ -51,24 +51,24 @@ window.onerror = function(message, uri, 
 <script>
   is(errorFired, true, "Should have error in different origin script with CORS");
   is(global, "ran", "Different origin script with CORS should have run");
 </script>
 
 <script type="application/javascript">
 errorFired = false;
 global = "";
-window.onerror = function(message, uri, line) {
-  is(message, "Error loading script", "Should have correct error message");
-  is(uri,
-     "http://example.com/tests/content/base/test/bug696301-script-2.js",
-     "Should still have correct script URI even when failing CORS");
-  is(line, 1, "Load failures seem to count as line 1");
+window.addEventListener("error", function(e) {
+  is(Object.getPrototypeOf(e), Event.prototype,
+     "Object prototype should be Event");
+  var externalScripts = document.querySelectorAll("script[src]");
+  is(e.target, externalScripts[externalScripts.length - 1],
+     "Event's target should be the right <script>");
   errorFired = true;
-}
+}, true);
 </script>
 <script src="http://example.com/tests/content/base/test/bug696301-script-2.js"
         crossorigin></script>
 <script>
   is(errorFired, true,
      "Should have error when different origin script fails CORS check");
   is(global, "", "Different origin script that fails CORS should not have run");
 </script>
--- a/content/base/test/test_bug696301-2.html
+++ b/content/base/test/test_bug696301-2.html
@@ -53,24 +53,24 @@ window.onerror = function(message, uri, 
 <script>
   is(errorFired, true, "Should have error in different origin script with CORS");
   is(global, "ran", "Different origin script with CORS should have run");
 </script>
 
 <script type="application/javascript">
 errorFired = false;
 global = "";
-window.onerror = function(message, uri, line) {
-  is(message, "Error loading script", "Should have correct error message");
-  is(uri,
-     "http://example.com/tests/content/base/test/bug696301-script-2.js",
-     "Should still have correct script URI even when failing CORS");
-  is(line, 1, "Load failures seem to count as line 1");
+window.addEventListener("error", function(e) {
+  is(Object.getPrototypeOf(e), Event.prototype,
+     "Object prototype should be Event");
+  var scripts = document.querySelectorAll("script");
+  is(e.target, scripts[scripts.length - 1],
+     "Event's target should be the right &lt;script>");
   errorFired = true;
-}
+}, true);
 </script>
 <script xlink:href="http://example.com/tests/content/base/test/bug696301-script-2.js"
         crossorigin></script>
 <script>
   is(errorFired, true,
      "Should have error when different origin script fails CORS check");
   is(global, "", "Different origin script that fails CORS should not have run");
 </script>
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug737087.html
@@ -0,0 +1,37 @@
+<!DOCTYPE HTML>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=737087
+-->
+<title>Test for Bug 737087</title>
+<script src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" href="/tests/SimpleTest/test.css"/>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=737087">Mozilla Bug 737087</a>
+<script>
+
+/** Test for Bug 737087 **/
+SimpleTest.waitForExplicitFinish();
+
+var bubbled = false;
+var capturedEvent = null;
+var inlineFiredEvent = null;
+
+addEventListener("error", function() { bubbled = true });
+addEventListener("error", function(e) {
+  capturedEvent = e;
+  is(typeof e, "object", "Error event must be object");
+  is(Object.getPrototypeOf(e), Event.prototype, "Error event must be Event");
+  is(e.bubbles, false, "e.bubbles must be false");
+  is(e.cancelable, false, "e.cancelable must be false");
+}, true);
+
+addLoadEvent(function() {
+  is(bubbled, false, "Error event must not bubble");
+  isnot(capturedEvent, null, "Error event must be captured");
+  isnot(inlineFiredEvent, null, "Inline error handler must fire");
+  is(capturedEvent, inlineFiredEvent,
+     "Same event must be handled by both handlers");
+  SimpleTest.finish();
+});
+</script>
+<script src=nonexistent
+  onerror="inlineFiredEvent = event"></script>
--- a/content/base/test/test_mutationobservers.html
+++ b/content/base/test/test_mutationobservers.html
@@ -288,16 +288,21 @@ function testChildList4() {
       is(records[2].target, t1, "target should be the textnode");
       is(records[2].oldValue, "Hello ", "oldValue was 'Hello '");
       observer.disconnect();
       then(testChildList5);
       m = null;
     });
   m.observe(df, { childList: true, characterData: true, characterDataOldValue: true, subtree: true });
   m.observe(div, { childList: true });
+  
+  // Make sure transient observers aren't leaked.
+  var leakTest = new MozMutationObserver(function(){});
+  leakTest.observe(div, { characterData: true, subtree: true });
+  
   div.insertBefore(df, s2);
   s1.firstChild.data = "bar"; // This should *not* create a record.
   t1.data = "Hello the whole "; // This should create a record.
 }
 
 function testChildList5() {
   div.textContent = null;
   var c1 = div.appendChild(document.createElement("div"));
@@ -449,16 +454,34 @@ function testSyncXHR() {
   x.open("GET", window.location, false);
   x.send();
   ok(!callbackHandled, "Shouldn't have called the mutation callback!");
   setTimeout(testSyncXHR2, 0);
 }
 
 function testSyncXHR2() {
   ok(callbackHandled, "Should have called the mutation callback!");
+  then(testModalDialog);
+}
+
+function testModalDialog() {
+  var didHandleCallback = false;
+  div.innerHTML = "<span>1</span><span>2</span>";
+  m = new M(function(records, observer) {
+      is(records[0].type, "childList", "Should have got childList");
+      is(records[0].removedNodes.length, 2, "Should have got removedNodes");
+      is(records[0].addedNodes.length, 1, "Should have got addedNodes");
+      observer.disconnect();
+      m = null;
+      didHandleCallback = true;
+    });
+  m.observe(div, { childList: true });
+  div.innerHTML = "<span><span>foo</span></span>";
+  window.showModalDialog("mutationobserver_dialog.html");
+  ok(didHandleCallback, "Should have called the callback while showing modal dialog!");
   then();
 }
 
 SimpleTest.waitForExplicitFinish();
 
 </script>
 </pre>
 <div id="log">
--- a/content/canvas/src/WebGLContext.h
+++ b/content/canvas/src/WebGLContext.h
@@ -122,19 +122,20 @@ struct WebGLTexelFormat {
 };
 
 struct WebGLTexelPremultiplicationOp {
     enum { Generic, None, Premultiply, Unmultiply };
 };
 
 int GetWebGLTexelFormat(GLenum format, GLenum type);
 
+// Zero is not an integer power of two.
 inline bool is_pot_assuming_nonnegative(WebGLsizei x)
 {
-    return (x & (x-1)) == 0;
+    return x && (x & (x-1)) == 0;
 }
 
 /* Each WebGL object class WebGLFoo wants to:
  *  - inherit WebGLRefCountedObject<WebGLFoo>
  *  - implement a Delete() method
  *  - have its destructor call DeleteOnce()
  * 
  * This base class provides two features to WebGL object types:
@@ -580,16 +581,17 @@ public:
     nsresult ErrorInvalidValue(const char *fmt = 0, ...);
     nsresult ErrorInvalidFramebufferOperation(const char *fmt = 0, ...);
     nsresult ErrorInvalidEnumInfo(const char *info, PRUint32 enumvalue) {
         return ErrorInvalidEnum("%s: invalid enum value 0x%x", info, enumvalue);
     }
     nsresult ErrorOutOfMemory(const char *fmt = 0, ...);
 
     const char *ErrorName(GLenum error);
+    bool IsTextureFormatCompressed(GLenum format);
 
     nsresult DummyFramebufferOperation(const char *info);
 
     WebGLTexture *activeBoundTextureForTarget(WebGLenum target) {
         return target == LOCAL_GL_TEXTURE_2D ? mBound2DTextures[mActiveTexture]
                                              : mBoundCubeMapTextures[mActiveTexture];
     }
 
@@ -1242,24 +1244,36 @@ protected:
 
     // we store information about the various images that are part of
     // this texture (cubemap faces, mipmap levels)
 
 public:
 
     class ImageInfo : public WebGLRectangleObject {
     public:
-        ImageInfo() : mFormat(0), mType(0), mIsDefined(false) {}
+        ImageInfo()
+            : mFormat(0)
+            , mType(0)
+            , mIsDefined(false)
+        {}
+
         ImageInfo(WebGLsizei width, WebGLsizei height,
                   WebGLenum format, WebGLenum type)
-            : WebGLRectangleObject(width, height), mFormat(format), mType(type), mIsDefined(true) {}
+            : WebGLRectangleObject(width, height)
+            , mFormat(format)
+            , mType(type)
+            , mIsDefined(true)
+        {}
 
         bool operator==(const ImageInfo& a) const {
-            return mWidth == a.mWidth && mHeight == a.mHeight &&
-                   mFormat == a.mFormat && mType == a.mType;
+            return mIsDefined == a.mIsDefined &&
+                   mWidth     == a.mWidth &&
+                   mHeight    == a.mHeight &&
+                   mFormat    == a.mFormat &&
+                   mType      == a.mType;
         }
         bool operator!=(const ImageInfo& a) const {
             return !(*this == a);
         }
         bool IsSquare() const {
             return mWidth == mHeight;
         }
         bool IsPositive() const {
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -1906,25 +1906,30 @@ WebGLContext::GenerateMipmap(WebGLenum t
         return NS_OK;
 
     if (!ValidateTextureTargetEnum(target, "generateMipmap"))
         return NS_OK;
 
     WebGLTexture *tex = activeBoundTextureForTarget(target);
 
     if (!tex)
-        return ErrorInvalidOperation("generateMipmap: no texture is bound to this target");
-
-    if (!tex->IsFirstImagePowerOfTwo()) {
-        return ErrorInvalidOperation("generateMipmap: the width or height of this texture is not a power of two");
-    }
-
-    if (!tex->AreAllLevel0ImageInfosEqual()) {
-        return ErrorInvalidOperation("generateMipmap: the six faces of this cube map have different dimensions, format, or type.");
-    }
+        return ErrorInvalidOperation("generateMipmap: No texture is bound to this target.");
+
+    if (!tex->HasImageInfoAt(0, 0))
+        return ErrorInvalidOperation("generateMipmap: Level zero of texture is not defined.");
+
+    if (!tex->IsFirstImagePowerOfTwo())
+        return ErrorInvalidOperation("generateMipmap: Level zero of texture does not have power-of-two width and height.");
+
+    GLenum format = tex->ImageInfoAt(0, 0).Format();
+    if (IsTextureFormatCompressed(format))
+        return ErrorInvalidOperation("generateMipmap: Texture data at level zero is compressed.");
+
+    if (!tex->AreAllLevel0ImageInfosEqual())
+        return ErrorInvalidOperation("generateMipmap: The six faces of this cube map have different dimensions, format, or type.");
 
     tex->SetGeneratedMipmap();
 
     MakeContextCurrent();
     gl->fGenerateMipmap(target);
     return NS_OK;
 }
 
--- a/content/canvas/src/WebGLContextUtils.cpp
+++ b/content/canvas/src/WebGLContextUtils.cpp
@@ -234,9 +234,32 @@ WebGLContext::ErrorName(GLenum error)
         case LOCAL_GL_INVALID_FRAMEBUFFER_OPERATION:
             return "INVALID_FRAMEBUFFER_OPERATION";
         case LOCAL_GL_NO_ERROR:
             return "NO_ERROR";
         default:
             NS_ABORT();
             return "[unknown WebGL error!]";
     }
-};
+}
+
+bool
+WebGLContext::IsTextureFormatCompressed(GLenum format)
+{
+    switch(format) {
+        case LOCAL_GL_RGB:
+        case LOCAL_GL_RGBA:
+        case LOCAL_GL_ALPHA:
+        case LOCAL_GL_LUMINANCE:
+        case LOCAL_GL_LUMINANCE_ALPHA:
+            return false;
+
+        case LOCAL_GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
+        case LOCAL_GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
+        case LOCAL_GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
+        case LOCAL_GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
+            return true;
+    }
+
+    NS_NOTREACHED("Invalid WebGL texture format?");
+    NS_ABORT();
+    return false;
+}
new file mode 100644
--- /dev/null
+++ b/content/html/content/crashtests/741250.xhtml
@@ -0,0 +1,9 @@
+<input form="f" id="x" xmlns="http://www.w3.org/1999/xhtml">
+<form id="f"></form>
+<script>
+window.addEventListener("load", function() {
+  var x = document.getElementById("x");
+  x.appendChild(x.cloneNode(true));
+}, false);
+</script>
+</input>
--- a/content/html/content/crashtests/crashtests.list
+++ b/content/html/content/crashtests/crashtests.list
@@ -29,8 +29,9 @@ load 614279.html
 load 614988-1.html
 load 620078-1.html
 load 620078-2.html
 load 680922-1.xul
 load 682058.xhtml
 load 682460.html
 load 673853.html
 load 738744.xhtml
+load 741250.xhtml
--- a/content/html/content/src/nsHTMLFormElement.cpp
+++ b/content/html/content/src/nsHTMLFormElement.cpp
@@ -2361,17 +2361,20 @@ nsFormControlList::AddElementToTable(nsG
       if (content == aChild) {
         return NS_OK;
       }
 
       // Found an element, create a list, add the element to the list and put
       // the list in the hash
       nsSimpleContentList *list = new nsSimpleContentList(mForm);
 
-      NS_ASSERTION(content->GetParent(), "Item in list without parent");
+      // If an element has a @form, we can assume it *might* be able to not have
+      // a parent and still be in the form.
+      NS_ASSERTION(content->HasAttr(kNameSpaceID_None, nsGkAtoms::form) ||
+                   content->GetParent(), "Item in list without parent");
 
       // Determine the ordering between the new and old element.
       bool newFirst = nsContentUtils::PositionIsBefore(aChild, content);
 
       list->AppendElement(newFirst ? aChild : content);
       list->AppendElement(newFirst ? content : aChild);
 
 
--- a/content/html/content/test/test_bug408231.html
+++ b/content/html/content/test/test_bug408231.html
@@ -85,17 +85,17 @@ https://bugzilla.mozilla.org/show_bug.cg
       ["justifyleft", "true"],
       ["justifyright", "false"],
       ["outdent", "exception"],
       //["paste", "exception"],
       ["redo", "exception"],
       ["removeformat", "exception"],
       ["selectall", "exception"],
       ["strikethrough", "false"],
-      ["styleWithCSS", "exception"],
+      ["styleWithCSS", "false"],
       ["subscript", "false"],
       ["superscript", "false"],
       ["underline", "false"],
       ["undo", "exception"],
       ["unlink", "false"],
       ["not-a-command", "exception"]
     ];
     
@@ -125,17 +125,17 @@ https://bugzilla.mozilla.org/show_bug.cg
       ["justifyleft", "left"],
       ["justifyright", "left"],
       ["outdent", ""],
       //["paste", ""],
       ["redo", ""],
       ["removeformat", ""],
       ["selectall", ""],
       ["strikethrough", ""],
-      ["styleWithCSS", "exception"],
+      ["styleWithCSS", ""],
       ["subscript", ""],
       ["superscript", ""],
       ["underline", ""],
       ["undo", ""],
       ["unlink", ""],
       ["not-a-command", "exception"],
     ];
     
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -3228,16 +3228,23 @@ nsHTMLDocument::QueryCommandState(const 
   GetMidasCommandManager(getter_AddRefs(cmdMgr));
   if (!cmdMgr)
     return NS_ERROR_FAILURE;
 
   nsIDOMWindow *window = GetWindow();
   if (!window)
     return NS_ERROR_FAILURE;
 
+  if (commandID.LowerCaseEqualsLiteral("usecss")) {
+    // Per spec, state is supported for styleWithCSS but not useCSS, so we just
+    // return false always.
+    *_retval = false;
+    return NS_OK;
+  }
+
   nsCAutoString cmdToDispatch, paramToCheck;
   bool dummy, dummy2;
   if (!ConvertToMidasInternalCommand(commandID, commandID,
                                      cmdToDispatch, paramToCheck, dummy, dummy2))
     return NS_ERROR_NOT_IMPLEMENTED;
 
   nsresult rv;
   nsCOMPtr<nsICommandParams> cmdParams = do_CreateInstance(
--- a/content/smil/nsSMILAnimationFunction.cpp
+++ b/content/smil/nsSMILAnimationFunction.cpp
@@ -666,17 +666,17 @@ nsSMILAnimationFunction::ScaleSimpleProg
     return aProgress;
 
   PRUint32 numTimes = mKeyTimes.Length();
 
   if (numTimes < 2)
     return aProgress;
 
   PRUint32 i = 0;
-  for (; i < numTimes - 2 && aProgress >= mKeyTimes[i+1]; ++i);
+  for (; i < numTimes - 2 && aProgress >= mKeyTimes[i+1]; ++i) { }
 
   if (aCalcMode == CALC_DISCRETE) {
     // discrete calcMode behaviour differs in that each keyTime defines the time
     // from when the corresponding value is set, and therefore the last value
     // needn't be 1. So check if we're in the last 'interval', that is, the
     // space between the final value and 1.0.
     if (aProgress >= mKeyTimes[i+1]) {
       NS_ABORT_IF_FALSE(i == numTimes - 2,
--- a/content/smil/nsSMILTimedElement.cpp
+++ b/content/smil/nsSMILTimedElement.cpp
@@ -1762,17 +1762,17 @@ nsSMILTimedElement::GetNextInterval(cons
 
 nsSMILInstanceTime*
 nsSMILTimedElement::GetNextGreater(const InstanceTimeList& aList,
                                    const nsSMILTimeValue& aBase,
                                    PRInt32& aPosition) const
 {
   nsSMILInstanceTime* result = nsnull;
   while ((result = GetNextGreaterOrEqual(aList, aBase, aPosition)) &&
-         result->Time() == aBase);
+         result->Time() == aBase) { }
   return result;
 }
 
 nsSMILInstanceTime*
 nsSMILTimedElement::GetNextGreaterOrEqual(const InstanceTimeList& aList,
                                           const nsSMILTimeValue& aBase,
                                           PRInt32& aPosition) const
 {
--- a/content/xslt/src/base/txExpandedNameMap.h
+++ b/content/xslt/src/base/txExpandedNameMap.h
@@ -97,28 +97,26 @@ protected:
 
         bool next()
         {
             return ++mCurrentPos < mMap.mItems.Length();
         }
 
         const txExpandedName key()
         {
-            NS_ASSERTION(mCurrentPos >= 0 &&
-                         mCurrentPos < mMap.mItems.Length(),
+            NS_ASSERTION(mCurrentPos < mMap.mItems.Length(),
                          "invalid position in txExpandedNameMap::iterator");
             return txExpandedName(mMap.mItems[mCurrentPos].mNamespaceID,
                                   mMap.mItems[mCurrentPos].mLocalName);
         }
 
     protected:
         void* itemValue()
         {
-            NS_ASSERTION(mCurrentPos >= 0 &&
-                         mCurrentPos < mMap.mItems.Length(),
+            NS_ASSERTION(mCurrentPos < mMap.mItems.Length(),
                          "invalid position in txExpandedNameMap::iterator");
             return mMap.mItems[mCurrentPos].mValue;
         }
 
     private:
         txExpandedNameMap_base& mMap;
         PRUint32 mCurrentPos;
     };
--- a/content/xul/templates/src/nsXULTemplateBuilder.cpp
+++ b/content/xul/templates/src/nsXULTemplateBuilder.cpp
@@ -213,38 +213,48 @@ nsXULTemplateBuilder::InitGlobals()
 
     if (!mMatchMap.IsInitialized() && !mMatchMap.Init())
         return NS_ERROR_OUT_OF_MEMORY;
 
     const size_t bucketsizes[] = { sizeof(nsTemplateMatch) };
     return mPool.Init("nsXULTemplateBuilder", bucketsizes, 1, 256);
 }
 
+void
+nsXULTemplateBuilder::CleanUp(bool aIsFinal)
+{
+    for (PRInt32 q = mQuerySets.Length() - 1; q >= 0; q--) {
+        nsTemplateQuerySet* qs = mQuerySets[q];
+        delete qs;
+    }
+
+    mQuerySets.Clear();
+
+    mMatchMap.Enumerate(DestroyMatchList, &mPool);
+
+    // Setting mQueryProcessor to null will close connections. This would be
+    // handled by the cycle collector, but we want to close them earlier.
+    if (aIsFinal)
+        mQueryProcessor = nsnull;
+}
 
 void
 nsXULTemplateBuilder::Uninit(bool aIsFinal)
 {
     if (mObservedDocument && aIsFinal) {
         gObserverService->RemoveObserver(this, DOM_WINDOW_DESTROYED_TOPIC);
         gObserverService->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
         mObservedDocument->RemoveObserver(this);
         mObservedDocument = nsnull;
     }
 
     if (mQueryProcessor)
         mQueryProcessor->Done();
 
-    for (PRInt32 q = mQuerySets.Length() - 1; q >= 0; q--) {
-        nsTemplateQuerySet* qs = mQuerySets[q];
-        delete qs;
-    }
-
-    mQuerySets.Clear();
-
-    mMatchMap.Enumerate(DestroyMatchList, &mPool);
+    CleanUp(aIsFinal);
 
     mRootResult = nsnull;
     mRefVariable = nsnull;
     mMemberVariable = nsnull;
 
     mQueriesCompiled = false;
 }
 
@@ -1183,16 +1193,18 @@ nsXULTemplateBuilder::ContentRemoved(nsI
             xuldoc->SetTemplateBuilderFor(mRoot, nsnull);
 
         // clear the template state when removing content so that template
         // content will be regenerated again if the content is reinserted
         nsXULElement *xulcontent = nsXULElement::FromContent(mRoot);
         if (xulcontent)
             xulcontent->ClearTemplateGenerated();
 
+        CleanUp(true);
+
         mDB = nsnull;
         mCompDB = nsnull;
         mDataSource = nsnull;
     }
 }
 
 void
 nsXULTemplateBuilder::NodeWillBeDestroyed(const nsINode* aNode)
--- a/content/xul/templates/src/nsXULTemplateBuilder.h
+++ b/content/xul/templates/src/nsXULTemplateBuilder.h
@@ -76,16 +76,18 @@ class nsIObserverService;
 /**
  * An object that translates an RDF graph into a presentation using a
  * set of rules.
  */
 class nsXULTemplateBuilder : public nsIXULTemplateBuilder,
                              public nsIObserver,
                              public nsStubDocumentObserver
 {
+    void CleanUp(bool aIsFinal);
+
 public:
     nsXULTemplateBuilder();
     virtual ~nsXULTemplateBuilder();
 
     nsresult InitGlobals();
 
     /**
      * Clear the template builder structures. The aIsFinal flag is set to true
--- a/content/xul/templates/src/nsXULTreeBuilder.cpp
+++ b/content/xul/templates/src/nsXULTreeBuilder.cpp
@@ -1914,16 +1914,19 @@ nsXULTreeBuilder::CompareResults(nsIXULT
                 }
 
                 return lindex - rindex;
             }
         }
     }
 
     PRInt32 sortorder;
+    if (!mQueryProcessor)
+        return 0;
+
     mQueryProcessor->CompareResults(aLeft, aRight, mSortVariable, mSortHints, &sortorder);
 
     if (sortorder)
         sortorder = sortorder * mSortDirection;
     return sortorder;
 }
 
 nsresult
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -143,17 +143,16 @@
 #include "nsDOMString.h"
 #include "nsIEmbeddingSiteWindow2.h"
 #include "nsThreadUtils.h"
 #include "nsEventStateManager.h"
 #include "nsIHttpProtocolHandler.h"
 #include "nsIJSContextStack.h"
 #include "nsIJSRuntimeService.h"
 #include "nsIMarkupDocumentViewer.h"
-#include "nsIPrefBranch.h"
 #include "nsIPresShell.h"
 #include "nsIPrivateDOMEvent.h"
 #include "nsIProgrammingLanguage.h"
 #include "nsIServiceManager.h"
 #include "nsIScriptGlobalObjectOwner.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIScrollableFrame.h"
 #include "nsIView.h"
@@ -7149,25 +7148,28 @@ nsGlobalWindow::ShowModalDialog(const ns
   nsCOMPtr<nsIDOMWindow> dlgWin;
   nsAutoString options(NS_LITERAL_STRING("-moz-internal-modal=1,status=1"));
 
   ConvertDialogOptions(aOptions, options);
 
   options.AppendLiteral(",scrollbars=1,centerscreen=1,resizable=0");
 
   nsCOMPtr<nsIDOMWindow> callerWin = EnterModalState();
+  PRUint32 oldMicroTaskLevel = nsContentUtils::MicroTaskLevel();
+  nsContentUtils::SetMicroTaskLevel(0);
   nsresult rv = OpenInternal(aURI, EmptyString(), options,
                              false,          // aDialog
                              true,           // aContentModal
                              true,           // aCalledNoScript
                              true,           // aDoJSFixups
                              nsnull, aArgs,     // args
                              GetPrincipal(),    // aCalleePrincipal
                              nsnull,            // aJSCallerContext
                              getter_AddRefs(dlgWin));
+  nsContentUtils::SetMicroTaskLevel(oldMicroTaskLevel);
   LeaveModalState(callerWin);
 
   NS_ENSURE_SUCCESS(rv, rv);
   
   if (dlgWin) {
     nsCOMPtr<nsIPrincipal> subjectPrincipal;
     rv = nsContentUtils::GetSecurityManager()->
       GetSubjectPrincipal(getter_AddRefs(subjectPrincipal));
--- a/dom/base/nsScreen.cpp
+++ b/dom/base/nsScreen.cpp
@@ -37,30 +37,23 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "mozilla/Hal.h"
 #include "nsScreen.h"
 #include "nsIDocShell.h"
 #include "nsPresContext.h"
 #include "nsCOMPtr.h"
 #include "nsDOMClassInfoID.h"
-#include "nsIInterfaceRequestorUtils.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsLayoutUtils.h"
-#include "nsContentUtils.h"
-#include "mozilla/Preferences.h"
 #include "nsDOMEvent.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
-/* static */ bool nsScreen::sInitialized = false;
-/* static */ bool nsScreen::sAllowScreenEnabledProperty = false;
-/* static */ bool nsScreen::sAllowScreenBrightnessProperty = false;
-
 namespace {
 
 bool
 IsChromeType(nsIDocShell *aDocShell)
 {
   nsCOMPtr<nsIDocShellTreeItem> ds = do_QueryInterface(aDocShell);
   if (!ds) {
     return false;
@@ -68,47 +61,31 @@ IsChromeType(nsIDocShell *aDocShell)
 
   PRInt32 itemType;
   ds->GetItemType(&itemType);
   return itemType == nsIDocShellTreeItem::typeChrome;
 }
 
 } // anonymous namespace
 
-/* static */ void
-nsScreen::Initialize()
-{
-  MOZ_ASSERT(!sInitialized);
-  sInitialized = true;
-  Preferences::AddBoolVarCache(&sAllowScreenEnabledProperty,
-                               "dom.screenEnabledProperty.enabled");
-  Preferences::AddBoolVarCache(&sAllowScreenBrightnessProperty,
-                               "dom.screenBrightnessProperty.enabled");
-}
-
 /* static */ already_AddRefed<nsScreen>
 nsScreen::Create(nsPIDOMWindow* aWindow)
 {
   MOZ_ASSERT(aWindow);
 
-  if (!sInitialized) {
-    Initialize();
-  }
-
   if (!aWindow->GetDocShell()) {
     return nsnull;
   }
 
   nsCOMPtr<nsIScriptGlobalObject> sgo =
     do_QueryInterface(static_cast<nsPIDOMWindow*>(aWindow));
   NS_ENSURE_TRUE(sgo, nsnull);
 
   nsRefPtr<nsScreen> screen = new nsScreen();
   screen->BindToOwner(aWindow);
-  screen->mIsChrome = IsChromeType(aWindow->GetDocShell());
 
   hal::RegisterScreenOrientationObserver(screen);
   hal::GetCurrentScreenOrientation(&(screen->mOrientation));
 
   return screen.forget();
 }
 
 nsScreen::nsScreen()
@@ -143,38 +120,16 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(Screen)
 NS_INTERFACE_MAP_END_INHERITING(nsDOMEventTargetHelper)
 
 NS_IMPL_ADDREF_INHERITED(nsScreen, nsDOMEventTargetHelper)
 NS_IMPL_RELEASE_INHERITED(nsScreen, nsDOMEventTargetHelper)
 
 NS_IMPL_EVENT_HANDLER(nsScreen, mozorientationchange)
 
-bool
-nsScreen::IsWhiteListed() {
-  if (mIsChrome) {
-    return true;
-  }
-
-  if (!GetOwner()) {
-    return false;
-  }
-
-  nsCOMPtr<nsIDocument> doc = do_GetInterface(GetOwner()->GetDocShell());
-  if (!doc) {
-    return false;
-  }
-
-  nsIPrincipal *principal = doc->NodePrincipal();
-  nsCOMPtr<nsIURI> principalURI;
-  principal->GetURI(getter_AddRefs(principalURI));
-  return nsContentUtils::URIIsChromeOrInPref(principalURI,
-                                             "dom.mozScreenWhitelist");
-}
-
 NS_IMETHODIMP
 nsScreen::GetTop(PRInt32* aTop)
 {
   nsRect rect;
   nsresult rv = GetRect(rect);
 
   *aTop = rect.y;
 
@@ -324,65 +279,16 @@ nsScreen::GetAvailRect(nsRect& aRect)
   aRect.x = nsPresContext::AppUnitsToIntCSSPixels(aRect.x);
   aRect.y = nsPresContext::AppUnitsToIntCSSPixels(aRect.y);
   aRect.height = nsPresContext::AppUnitsToIntCSSPixels(aRect.height);
   aRect.width = nsPresContext::AppUnitsToIntCSSPixels(aRect.width);
 
   return NS_OK;
 }
 
-nsresult
-nsScreen::GetMozEnabled(bool *aEnabled)
-{
-  if (!sAllowScreenEnabledProperty || !IsWhiteListed()) {
-    *aEnabled = true;
-    return NS_OK;
-  }
-
-  *aEnabled = hal::GetScreenEnabled();
-  return NS_OK;
-}
-
-nsresult
-nsScreen::SetMozEnabled(bool aEnabled)
-{
-  if (!sAllowScreenEnabledProperty || !IsWhiteListed()) {
-    return NS_OK;
-  }
-
-  // TODO bug 707589: When the screen's state changes, all visible windows
-  // should fire a visibility change event.
-  hal::SetScreenEnabled(aEnabled);
-  return NS_OK;
-}
-
-nsresult
-nsScreen::GetMozBrightness(double *aBrightness)
-{
-  if (!sAllowScreenEnabledProperty || !IsWhiteListed()) {
-    *aBrightness = 1;
-    return NS_OK;
-  }
-
-  *aBrightness = hal::GetScreenBrightness();
-  return NS_OK;
-}
-
-nsresult
-nsScreen::SetMozBrightness(double aBrightness)
-{
-  if (!sAllowScreenEnabledProperty || !IsWhiteListed()) {
-    return NS_OK;
-  }
-
-  NS_ENSURE_TRUE(0 <= aBrightness && aBrightness <= 1, NS_ERROR_INVALID_ARG);
-  hal::SetScreenBrightness(aBrightness);
-  return NS_OK;
-}
-
 void
 nsScreen::Notify(const ScreenOrientationWrapper& aOrientation)
 {
   ScreenOrientation previousOrientation = mOrientation;
   mOrientation = aOrientation.orientation;
 
   NS_ASSERTION(mOrientation != eScreenOrientation_None &&
                mOrientation != eScreenOrientation_EndGuard &&
--- a/dom/base/nsScreen.h
+++ b/dom/base/nsScreen.h
@@ -69,39 +69,29 @@ public:
 
   void Notify(const mozilla::dom::ScreenOrientationWrapper& aOrientation);
 
 protected:
   nsDeviceContext* GetDeviceContext();
   nsresult GetRect(nsRect& aRect);
   nsresult GetAvailRect(nsRect& aRect);
 
-  bool mIsChrome;
-
   mozilla::dom::ScreenOrientation mOrientation;
 
 private:
   class FullScreenEventListener : public nsIDOMEventListener
   {
   public:
     FullScreenEventListener() {};
 
     NS_DECL_ISUPPORTS
     NS_DECL_NSIDOMEVENTLISTENER
   };
 
   nsScreen();
   virtual ~nsScreen();
 
-  static bool sInitialized;
-  static bool sAllowScreenEnabledProperty;
-  static bool sAllowScreenBrightnessProperty;
-
-  static void Initialize();
-
-  bool IsWhiteListed();
-
   nsRefPtr<FullScreenEventListener> mEventListener;
 
   NS_DECL_EVENT_HANDLER(mozorientationchange)
 };
 
 #endif /* nsScreen_h___ */
--- a/dom/bindings/parser/WebIDL.py
+++ b/dom/bindings/parser/WebIDL.py
@@ -64,98 +64,110 @@ def parseInt(literal):
         base = 10
 
     value = int(string, base)
     return value * sign
 
 # Magic for creating enums
 def M_add_class_attribs(attribs):
     def foo(name, bases, dict_):
-        for v, k in attribs:
+        for v, k in enumerate(attribs):
             dict_[k] = v
+        assert 'length' not in dict_
+        dict_['length'] = len(attribs)
         return type(name, bases, dict_)
     return foo
 
 def enum(*names):
     class Foo(object):
-        __metaclass__ = M_add_class_attribs(enumerate(names))
+        __metaclass__ = M_add_class_attribs(names)
         def __setattr__(self, name, value):  # this makes it read-only
             raise NotImplementedError
     return Foo()
 
 class WebIDLError(Exception):
     def __init__(self, message, location, warning=False):
         self.message = message
         self.location = location
         self.warning = warning
 
     def __str__(self):
         return "%s: %s%s%s" % (self.warning and 'warning' or 'error',
                                self.message, ", " if self.location else "",
                                self.location)
 
 class Location(object):
-    _line = None
-
     def __init__(self, lexer, lineno, lexpos, filename):
+        self._line = None
         self._lineno = lineno
         self._lexpos = lexpos
         self._lexdata = lexer.lexdata
         self._file = filename if filename else "<unknown>"
 
     def __eq__(self, other):
         return self._lexpos == other._lexpos and \
                self._file == other._file
 
+    def filename(self):
+        return self.filename
+
     def resolve(self):
         if self._line:
             return
 
         startofline = self._lexdata.rfind('\n', 0, self._lexpos) + 1
         endofline = self._lexdata.find('\n', self._lexpos, self._lexpos + 80)
-        self._line = self._lexdata[startofline:endofline]
+        if endofline != -1:
+            self._line = self._lexdata[startofline:endofline]
+        else:
+            self._line = self._lexdata[startofline:]
         self._colno = self._lexpos - startofline
 
-    def pointerline(self):
-        def i():
-            for i in xrange(0, self._colno):
-                yield " "
-            yield "^"
-
-        return "".join(i())
-
     def get(self):
         self.resolve()
         return "%s line %s:%s" % (self._file, self._lineno, self._colno)
 
+    def _pointerline(self):
+        return " " * self._colno + "^"
+
     def __str__(self):
         self.resolve()
         return "%s line %s:%s\n%s\n%s" % (self._file, self._lineno, self._colno,
-                                          self._line, self.pointerline())
+                                          self._line, self._pointerline())
 
 class BuiltinLocation(object):
     def __init__(self, text):
         self.msg = text
 
+    def __eq__(self, other):
+        return isinstance(other, BuiltinLocation) and \
+               self.msg == other.msg
+
+    def filename(self):
+        return '<builtin>'
+
+    def resolve(self):
+        pass
+
     def get(self):
         return self.msg
 
     def __str__(self):
         return self.get()
 
 
 # Data Model
 
 class IDLObject(object):
     def __init__(self, location):
         self.location = location
         self.userData = dict()
 
     def filename(self):
-        return self.location._file
+        return self.location.filename()
 
     def isInterface(self):
         return False
 
     def isEnum(self):
         return False
 
     def isCallback(self):
@@ -193,16 +205,21 @@ class IDLScope(IDLObject):
         return self.QName()
 
     def QName(self):
         if self._name:
             return self._name.QName() + "::"
         return "::"
 
     def ensureUnique(self, identifier, object):
+        """
+            Ensure that there is at most one 'identifier' in scope ('self').
+            Note that object can be None.  This occurs if we end up here for an
+            interface type we haven't seen yet.
+        """
         assert isinstance(identifier, IDLUnresolvedIdentifier)
         assert not object or isinstance(object, IDLObjectWithIdentifier)
         assert not object or object.identifier == identifier
 
         if identifier.name in self._dict:
             if not object:
                 return
 
@@ -295,16 +312,19 @@ class IDLUnresolvedIdentifier(IDLObject)
 
         scope.ensureUnique(self, object)
 
         identifier = IDLIdentifier(self.location, scope, self.name)
         if object:
             object.identifier = identifier
         return identifier
 
+    def finish(self):
+        assert False # Should replace with a resolved identifier first.
+
 class IDLObjectWithIdentifier(IDLObject):
     def __init__(self, location, parentScope, identifier):
         IDLObject.__init__(self, location)
 
         assert isinstance(identifier, IDLUnresolvedIdentifier)
 
         self.identifier = identifier
 
@@ -363,19 +383,18 @@ class IDLExternalInterface(IDLObjectWith
 class IDLInterface(IDLObjectWithScope):
     def __init__(self, location, parentScope, name, parent, members):
         assert isinstance(parentScope, IDLScope)
         assert isinstance(name, IDLUnresolvedIdentifier)
         assert not parent or isinstance(parent, IDLParentPlaceholder)
 
         self.parent = parent
         self._callback = False
-
+        self._finished = False
         self.members = list(members) # clone the list
-        assert iter(self.members) # Assert it's iterable
 
         IDLObjectWithScope.__init__(self, location, parentScope, name)
 
     def __str__(self):
         return "Interface '%s'" % self.identifier.name
 
     def ctor(self):
         identifier = IDLUnresolvedIdentifier(self.location, "constructor",
@@ -399,116 +418,82 @@ class IDLInterface(IDLObjectWithScope):
 
         retval = originalObject.addOverload(newObject)
         # Might be a ctor, which isn't in self.members
         if newObject in self.members:
             self.members.remove(newObject)
         return retval
 
     def finish(self, scope):
-        if hasattr(self, "_finished"):
+        if self._finished:
             return
 
         self._finished = True
 
         assert not self.parent or isinstance(self.parent, IDLParentPlaceholder)
         parent = self.parent.finish(scope) if self.parent else None
         assert not parent or isinstance(parent, IDLInterface)
 
         self.parent = parent
 
         assert iter(self.members)
-        members = None
 
         if self.parent:
             self.parent.finish(scope)
             assert iter(self.parent.members)
 
             members = list(self.parent.members)
             members.extend(self.members)
         else:
             members = list(self.members)
 
-        SpecialType = enum(
-            'NamedGetter',
-            'NamedSetter',
-            'NamedCreator',
-            'NamedDeleter',
-            'IndexedGetter',
-            'IndexedSetter',
-            'IndexedCreator',
-            'IndexedDeleter'
-        )
-
-        specialMembersSeen = [False for i in range(8)]
-
         def memberNotOnParentChain(member, iface):
             assert iface
 
             if not iface.parent:
                 return True
 
             assert isinstance(iface.parent, IDLInterface)
             if member in iface.parent.members:
                 return False
             return memberNotOnParentChain(member, iface.parent)
 
+        # Ensure that there's at most one of each {named,indexed}
+        # {getter,setter,creator,deleter}.
+        specialMembersSeen = set()
         for member in members:
             if memberNotOnParentChain(member, self):
                 member.resolve(self)
-                
-            if member.tag == IDLInterfaceMember.Tags.Method:
-                if member.isGetter():
-                    if member.isNamed():
-                        if specialMembersSeen[SpecialType.NamedGetter]:
-                            raise WebIDLError("Multiple named getters on %s" % (self),
-                                              self.location)
-                        specialMembersSeen[SpecialType.NamedGetter] = True
-                    else:
-                        assert member.isIndexed()
-                        if specialMembersSeen[SpecialType.IndexedGetter]:
-                            raise WebIDLError("Multiple indexed getters on %s" % (self),
-                                              self.location)
-                        specialMembersSeen[SpecialType.IndexedGetter] = True
-                if member.isSetter():
-                    if member.isNamed():
-                        if specialMembersSeen[SpecialType.NamedSetter]:
-                            raise WebIDLError("Multiple named setters on %s" % (self),
-                                              self.location)
-                        specialMembersSeen[SpecialType.NamedSetter] = True
-                    else:
-                        assert member.isIndexed()
-                        if specialMembersSeen[SpecialType.IndexedSetter]:
-                            raise WebIDLError("Multiple indexed setters on %s" % (self),
-                                              self.location)
-                        specialMembersSeen[SpecialType.IndexedSetter] = True
-                if member.isCreator():
-                    if member.isNamed():
-                        if specialMembersSeen[SpecialType.NamedCreator]:
-                            raise WebIDLError("Multiple named creators on %s" % (self),
-                                              self.location)
-                        specialMembersSeen[SpecialType.NamedCreator] = True
-                    else:
-                        assert member.isIndexed()
-                        if specialMembersSeen[SpecialType.IndexedCreator]:
-                            raise WebIDLError("Multiple indexed creators on %s" % (self),
-                                              self.location)
-                        specialMembersSeen[SpecialType.IndexedCreator] = True
-                if member.isDeleter():
-                    if member.isNamed():
-                        if specialMembersSeen[SpecialType.NamedDeleter]:
-                            raise WebIDLError("Multiple named deleters on %s" % (self),
-                                              self.location)
-                        specialMembersSeen[SpecialType.NamedDeleter] = True
-                    else:
-                        assert member.isIndexed()
-                        if specialMembersSeen[SpecialType.IndexedDeleter]:
-                            raise WebIDLError("Multiple indexed Deleters on %s" % (self),
-                                              self.location)
-                        specialMembersSeen[SpecialType.IndexedDeleter] = True
+
+            if member.tag != IDLInterfaceMember.Tags.Method:
+                continue
+
+            if member.isGetter():
+                memberType = "getters"
+            elif member.isSetter():
+                memberType = "setters"
+            elif member.isCreator():
+                memberType = "creators"
+            elif member.isDeleter():
+                memberType = "deleters"
+            else:
+                continue
+
+            if member.isNamed():
+                memberType = "named " + memberType
+            elif member.isIndexed():
+                memberType = "indexed " + memberType
+            else:
+                continue
+
+            if memberType in specialMembersSeen:
+                raise WebIDLError("Multiple " + memberType + " on %s" % (self),
+                                   self.location)
+
+            specialMembersSeen.add(memberType)
 
         for member in self.members:
             member.finish(scope)
 
     def isInterface(self):
         return True
 
     def isExternal(self):
@@ -524,17 +509,17 @@ class IDLInterface(IDLObjectWithScope):
         depth = 0
         parent = self.parent
         while parent:
             depth = depth + 1
             parent = parent.parent
         return depth
 
     def hasConstants(self):
-        return reduce(lambda b, m: b or m.isConst(), self.members, False)
+        return any(m.isConst() for m in self.members)
 
     def hasInterfaceObject(self):
         if self.isCallback():
             return self.hasConstants()
         return not hasattr(self, "_noInterfaceObject")
 
     def hasInterfacePrototypeObject(self):
         return not self.isCallback()
@@ -562,20 +547,17 @@ class IDLInterface(IDLObjectWithScope):
 
                 args = attrlist[0] if len(attrlist) else []
 
                 retType = IDLWrapperType(self.location, self)
                 
                 identifier = IDLUnresolvedIdentifier(self.location, "constructor",
                                                      allowForbidden=True)
 
-                method = IDLMethod(self.location, identifier, retType, args,
-                                   False, False, False, False, False, False,
-                                   False, False)
-
+                method = IDLMethod(self.location, identifier, retType, args)
                 method.resolve(self)
 
             self._extendedAttrDict[identifier] = attrlist if len(attrlist) else True
 
 class IDLEnum(IDLObjectWithIdentifier):
     def __init__(self, location, parentScope, name, values):
         assert isinstance(parentScope, IDLScope)
         assert isinstance(name, IDLUnresolvedIdentifier)
@@ -758,25 +740,34 @@ class IDLNullableType(IDLType):
         return self.inner.isCallback()
 
     def isPrimitive(self):
         return self.inner.isPrimitive()
 
     def isString(self):
         return self.inner.isString()
 
+    def isFloat(self):
+        return self.inner.isFloat()
+
+    def isInteger(self):
+        return self.inner.isInteger()
+
     def isVoid(self):
         return False
 
     def isSequence(self):
         return self.inner.isSequence()
 
     def isArray(self):
         return self.inner.isArray()
 
+    def isArrayBuffer(self):
+        return self.inner.isArrayBuffer()
+
     def isDictionary(self):
         return self.inner.isDictionary()
 
     def isInterface(self):
         return self.inner.isInterface()
 
     def isEnum(self):
         return self.inner.isEnum()
@@ -792,17 +783,17 @@ class IDLNullableType(IDLType):
         return self.inner.isComplete()
 
     def complete(self, scope):
         self.inner = self.inner.complete(scope)
         self.name = self.inner.name
         return self
 
     def unroll(self):
-        return self.inner
+        return self.inner.unroll()
 
     def isDistinguishableFrom(self, other):
         if other.nullable():
             # Can't tell which type null should become
             return False
         return self.inner.isDistinguishableFrom(other)
 
 class IDLSequenceType(IDLType):
@@ -830,43 +821,45 @@ class IDLSequenceType(IDLType):
 
     def isVoid(self):
         return False
 
     def isSequence(self):
         return True
 
     def isArray(self):
-        return self.inner.isArray()
+        return False
 
     def isDictionary(self):
-        return self.inner.isDictionary()
+        return False
 
     def isInterface(self):
-        return self.inner.isInterface()
+        return False
 
     def isEnum(self):
-        return self.inner.isEnum();
+        return False
 
     def tag(self):
+        # XXXkhuey this is probably wrong.
         return self.inner.tag()
 
     def resolveType(self, parentScope):
         assert isinstance(parentScope, IDLScope)
         self.inner.resolveType(parentScope)
 
     def isComplete(self):
         return self.inner.isComplete()
 
     def complete(self, scope):
         self.inner = self.inner.complete(scope)
+        self.name = self.inner.name
         return self
 
     def unroll(self):
-        return self.inner
+        return self.inner.unroll()
 
     def isDistinguishableFrom(self, other):
         return (other.isPrimitive() or other.isString() or other.isEnum() or
                 other.isDictionary() or other.isDate() or
                 # XXXbz we should also be checking for indexed
                 # properties on interfaces
                 (other.isInterface() and not other.isCallback() and
                  not other.isArrayBuffer()))
@@ -890,57 +883,59 @@ class IDLArrayType(IDLType):
 
     def __str__(self):
         return self.inner.__str__() + "Array"
 
     def nullable(self):
         return False
 
     def isPrimitive(self):
-        return self.inner.isPrimitive()
+        return False
 
     def isString(self):
-        return self.inner.isString()
+        return False
 
     def isVoid(self):
         return False
 
     def isSequence(self):
         assert not self.inner.isSequence()
-        return self.inner.isSequence()
+        return False
 
     def isArray(self):
         return True
 
     def isDictionary(self):
         assert not self.inner.isDictionary()
-        return self.inner.isDictionary()
+        return False
 
     def isInterface(self):
-        return self.inner.isInterface()
+        return False
 
     def isEnum(self):
-        return self.inner.isEnum()
+        return False
 
     def tag(self):
+        # XXXkhuey this is probably wrong.
         return self.inner.tag()
 
     def resolveType(self, parentScope):
         assert isinstance(parentScope, IDLScope)
         self.inner.resolveType(parentScope)
 
     def isComplete(self):
         return self.inner.isComplete()
 
     def complete(self, scope):
         self.inner = self.inner.complete(scope)
+        self.name = self.inner.name
         return self
 
     def unroll(self):
-        return self.inner
+        return self.inner.unroll()
 
     def isDistinguishableFrom(self, other):
         return (other.isPrimitive() or other.isString() or other.isEnum() or
                 other.isDictionary() or other.isDate() or
                 # XXXbz we should also be checking for indexed
                 # properties on interfaces
                 (other.isInterface() and not other.isCallback() and
                  not other.isArrayBuffer()))
@@ -990,17 +985,17 @@ class IDLTypedefType(IDLType, IDLObjectW
     def resolve(self, parentScope):
         assert isinstance(parentScope, IDLScope)
         IDLObjectWithIdentifier.resolve(self, parentScope)
 
     def tag(self):
         return self.inner.tag()
 
     def unroll(self):
-        return self.inner
+        return self.inner.unroll()
 
     def isDistinguishableFrom(self, other):
         return self.inner.isDistinguishableFrom(other)
 
 class IDLWrapperType(IDLType):
     def __init__(self, location, inner):
         IDLType.__init__(self, location, inner.identifier.name)
         self.inner = inner
@@ -1036,16 +1031,20 @@ class IDLWrapperType(IDLType):
 
     def isInterface(self):
         return isinstance(self.inner, IDLInterface) or \
                isinstance(self.inner, IDLExternalInterface)
 
     def isEnum(self):
         return isinstance(self.inner, IDLEnum)
 
+    def resolveType(self, parentScope):
+        assert isinstance(parentScope, IDLScope)
+        self.inner.resolve(parentScope)
+
     def isComplete(self):
         return True
 
     def tag(self):
         if self.isInterface():
             return IDLType.Tags.interface
         elif self.isEnum():
             return IDLType.Tags.enum
@@ -1117,42 +1116,42 @@ class IDLBuiltinType(IDLType):
             Types.date: IDLType.Tags.date,
             Types.void: IDLType.Tags.void,
             Types.ArrayBuffer: IDLType.Tags.interface
         }
 
     def __init__(self, location, name, type):
         IDLType.__init__(self, location, name)
         self.builtin = True
-        self.type = type
+        self._typeTag = type
 
     def isPrimitive(self):
-        return self.type <= IDLBuiltinType.Types.double
+        return self._typeTag <= IDLBuiltinType.Types.double
 
     def isString(self):
-        return self.type == IDLBuiltinType.Types.domstring
+        return self._typeTag == IDLBuiltinType.Types.domstring
 
     def isInteger(self):
-        return self.type <= IDLBuiltinType.Types.unsigned_long_long
+        return self._typeTag <= IDLBuiltinType.Types.unsigned_long_long
 
     def isArrayBuffer(self):
-        return self.type == IDLBuiltinType.Types.ArrayBuffer
+        return self._typeTag == IDLBuiltinType.Types.ArrayBuffer
 
     def isInterface(self):
         # ArrayBuffers are interface types per the TypedArray spec,
         # but we handle them as builtins because SpiderMonkey implements
         # ArrayBuffers.
-        return self.type == IDLBuiltinType.Types.ArrayBuffer
+        return self._typeTag == IDLBuiltinType.Types.ArrayBuffer
 
     def isFloat(self):
-        return self.type == IDLBuiltinType.Types.float or \
-               self.type == IDLBuiltinType.Types.double
+        return self._typeTag == IDLBuiltinType.Types.float or \
+               self._typeTag == IDLBuiltinType.Types.double
 
     def tag(self):
-        return IDLBuiltinType.TagLookup[self.type]
+        return IDLBuiltinType.TagLookup[self._typeTag]
 
     def isDistinguishableFrom(self, other):
         if self.isPrimitive() or self.isString():
             return (other.isInterface() or other.isObject() or
                     other.isCallback() or other.isDictionary() or
                     other.isSequence() or other.isArray() or
                     other.isDate())
         if self.isAny():
@@ -1275,17 +1274,17 @@ class IDLValue(IDLObject):
         # Else, see if we can coerce to 'type'.
         if self.type.isInteger():
             if not self.type.isInteger():
                 raise WebIDLError("Cannot coerce type %s to type %s." %
                                   (self.type, type), location)
 
             # We're both integer types.  See if we fit.
 
-            (min, max) = integerTypeSizes[type.type]
+            (min, max) = integerTypeSizes[type._typeTag]
             if self.value <= max and self.value >= min:
                 # Promote
                 return IDLValue(self.location, type, self.value)
             else:
                 raise WebIDLError("Value %s is out of range for type %s." %
                                   (self.value, type), location)
         else:
             pass
@@ -1487,18 +1486,20 @@ class IDLMethod(IDLInterfaceMember, IDLS
 
     NamedOrIndexed = enum(
         'Neither',
         'Named',
         'Indexed'
     )
 
     def __init__(self, location, identifier, returnType, arguments,
-                 static, getter, setter, creator, deleter, specialType, legacycaller,
-                 stringifier):
+                 static=False, getter=False, setter=False, creator=False,
+                 deleter=False, specialType=NamedOrIndexed.Neither,
+                 legacycaller=False, stringifier=False):
+        # REVIEW: specialType is NamedOrIndexed -- wow, this is messed up.
         IDLInterfaceMember.__init__(self, location, identifier,
                                     IDLInterfaceMember.Tags.Method)
 
         self._hasOverloads = False
 
         assert isinstance(returnType, IDLType)
         self._returnType = [returnType]
 
@@ -1673,16 +1674,17 @@ class Tokenizer(object):
         "STRING",
         "WHITESPACE",
         "OTHER"
         ]
 
     def t_INTEGER(self, t):
         r'-?(0([0-7]+|[Xx][0-9A-Fa-f]+)?|[1-9][0-9]*)'
         try:
+            # Can't use int(), because that doesn't handle octal properly.
             t.value = parseInt(t.value)
         except:
             raise WebIDLError("Invalid integer literal",
                               Location(lexer=self.lexer,
                                        lineno=self.lexer.lineno,
                                        lexpos=self.lexer.lexpos,
                                        filename=self._filename))
         return t
@@ -2256,18 +2258,19 @@ class Parser(Tokenizer):
                  "indexed" if specialType == IDLMethod.NamedOrIndexed.Indexed else "",
                  "getter" if getter else "",
                  "setter" if setter else "",
                  "deleter" if deleter else "",
                  "creator" if creator else "",
                  "legacycaller" if legacycaller else ""), allowDoubleUnderscore=True)
 
         method = IDLMethod(self.getLocation(p, 2), identifier, returnType, arguments,
-                           static, getter, setter, creator, deleter, specialType,
-                           legacycaller, False)
+                           static=static, getter=getter, setter=setter, creator=creator,
+                           deleter=deleter, specialType=specialType,
+                           legacycaller=legacycaller, stringifier=False)
         p[0] = method
 
     def p_QualifiersStatic(self, p):
         """
             Qualifiers : STATIC
         """
         p[0] = [IDLMethod.Special.Static]
 
@@ -2856,17 +2859,24 @@ class Parser(Tokenizer):
         self._filename = filename
         self._productions.extend(self.parser.parse(lexer=self.lexer))
         self._filename = None
 
     def finish(self):
         for production in self._productions:
             production.finish(self.globalScope())
 
-        return set(self._productions)
+        # De-duplicate self._productions, without modifying its order.
+        seen = set()
+        result = []
+        for p in self._productions:
+            if p not in seen:
+                seen.add(p)
+                result.append(p)
+        return result
 
     def reset(self):
         return Parser()
 
     # Builtin IDL defined by WebIDL
     _builtins = """
         typedef unsigned long long DOMTimeStamp;
     """
deleted file mode 100644
--- a/dom/bindings/parser/__init__.py
+++ /dev/null
@@ -1,1 +0,0 @@
-__all__ = ['WebIDL']
--- a/dom/bindings/parser/runtests.py
+++ b/dom/bindings/parser/runtests.py
@@ -32,41 +32,81 @@
 # 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 *****
 
 import os, sys
 import glob
+import optparse
+import traceback
 import WebIDL
 
 class TestHarness(object):
+    def __init__(self, test, verbose):
+        self.test = test
+        self.verbose = verbose
+        self.printed_intro = False
+
+    def start(self):
+        if self.verbose:
+            self.maybe_print_intro()
+
+    def finish(self):
+        if self.verbose or self.printed_intro:
+            print "Finished test %s" % self.test
+
+    def maybe_print_intro(self):
+        if not self.printed_intro:
+            print "Starting test %s" % self.test
+            self.printed_intro = True
+
+    def test_pass(self, msg):
+        if self.verbose:
+            print "TEST-PASS | %s" % msg
+
+    def test_fail(self, msg):
+        self.maybe_print_intro()
+        print "TEST-UNEXPECTED-FAIL | %s" % msg
+
     def ok(self, condition, msg):
         if condition:
-            print "TEST-PASS | %s" % msg
+            self.test_pass(msg)
         else:
-            print "TEST-UNEXPECTED-FAIL | %s" % msg
+            self.test_fail(msg)
 
     def check(self, a, b, msg):
         if a == b:
-            print "TEST-PASS | %s" % msg
+            self.test_pass(msg)
         else:
-            print "TEST-UNEXPECTED-FAIL | %s" % msg
+            self.test_fail(msg)
             print "\tGot %s expected %s" % (a, b)
 
-def run_tests():
-    harness = TestHarness()
+def run_tests(tests, verbose):
+    testdir = os.path.join(os.path.dirname(__file__), 'tests')
+    if not tests:
+        tests = glob.iglob(os.path.join(testdir, "*.py"))
+    sys.path.append(testdir)
 
-    tests = glob.iglob("tests/*.py")
-    sys.path.append("./tests")
     for test in tests:
         (testpath, ext) = os.path.splitext(os.path.basename(test))
         _test = __import__(testpath, globals(), locals(), ['WebIDLTest'])
-        #try:
-        _test.WebIDLTest.__call__(WebIDL.Parser(), harness)
-        #except:
-        #    print "TEST-UNEXPECTED-FAIL | Unhandled exception in Test %s" % testpath
-        #    print sys.exc_info()[0]
-        print "Test %s Complete\n" % testpath
+
+        harness = TestHarness(test, verbose)
+        harness.start()
+        try:
+            _test.WebIDLTest.__call__(WebIDL.Parser(), harness)
+        except:
+            print "TEST-UNEXPECTED-FAIL | Unhandled exception in test %s" % testpath
+            traceback.print_exc()
+        finally:
+            harness.finish()
 
 if __name__ == '__main__':
-    run_tests()
+    usage = """%prog [OPTIONS] [TESTS]
+               Where TESTS are relative to the tests directory."""
+    parser = optparse.OptionParser(usage=usage)
+    parser.add_option('-q', '--quiet', action='store_false', dest='verbose', default=True,
+                      help="Don't print passing tests.")
+    options, tests = parser.parse_args()
+
+    run_tests(tests, verbose=options.verbose)
new file mode 100644
--- /dev/null
+++ b/dom/bindings/parser/tests/test_array_of_interface.py
@@ -0,0 +1,13 @@
+import WebIDL
+
+def WebIDLTest(parser, harness):
+    parser.parse("""
+      interface A {
+        attribute long a;
+      };
+
+      interface B {
+        attribute A[] b;
+      };
+    """);
+    parser.finish()
new file mode 100644
--- /dev/null
+++ b/dom/bindings/parser/tests/test_builtin_filename.py
@@ -0,0 +1,11 @@
+import WebIDL
+
+def WebIDLTest(parser, harness):
+    parser.parse("""
+        interface Test {
+          attribute long b;
+        };
+    """);
+
+    attr = parser.finish()[0].members[0]
+    harness.check(attr.type.filename(), '<builtin>', 'Filename on builtin type')
--- a/dom/bindings/parser/tests/test_constructor.py
+++ b/dom/bindings/parser/tests/test_constructor.py
@@ -57,19 +57,19 @@ def WebIDLTest(parser, harness):
     results = parser.finish()
     harness.check(len(results), 3, "Should be two productions")
     harness.ok(isinstance(results[0], WebIDL.IDLInterface),
                "Should be an IDLInterface")
     harness.ok(isinstance(results[1], WebIDL.IDLInterface),
                "Should be an IDLInterface")
 
     checkMethod(results[0].ctor(), "::TestConstructorNoArgs::constructor",
-                "constructor", [("TestConstructorNoArgs", [])])
+                "constructor", [("TestConstructorNoArgs (Wrapper)", [])])
     checkMethod(results[1].ctor(), "::TestConstructorWithArgs::constructor",
                 "constructor",
-                [("TestConstructorWithArgs",
+                [("TestConstructorWithArgs (Wrapper)",
                  [("::TestConstructorWithArgs::constructor::name", "name", "String", False, False)])])
     checkMethod(results[2].ctor(), "::TestConstructorOverloads::constructor",
                 "constructor",
-                [("TestConstructorOverloads",
+                [("TestConstructorOverloads (Wrapper)",
                  [("::TestConstructorOverloads::constructor::foo", "foo", "Object", False, False)]),
-                 ("TestConstructorOverloads",
+                 ("TestConstructorOverloads (Wrapper)",
                  [("::TestConstructorOverloads::constructor::bar", "bar", "Boolean", False, False)])])
new file mode 100644
--- /dev/null
+++ b/dom/bindings/parser/tests/test_deduplicate.py
@@ -0,0 +1,15 @@
+import WebIDL
+
+def WebIDLTest(parser, harness):
+    parser.parse("""
+        interface Foo;
+        interface Bar;
+        interface Foo;
+        """);
+
+    results = parser.finish()
+
+    # There should be no duplicate interfaces in the result.
+    expectedNames = sorted(['Foo', 'Bar'])
+    actualNames = sorted(map(lambda iface: iface.identifier.name, results))
+    harness.check(actualNames, expectedNames, "Parser shouldn't output duplicate names.")
--- a/dom/bindings/parser/tests/test_enum.py
+++ b/dom/bindings/parser/tests/test_enum.py
@@ -42,20 +42,20 @@ def WebIDLTest(parser, harness):
     harness.check(method.identifier.QName(), "::TestEnumInterface::doFoo",
                   "Method has correct QName")
     harness.check(method.identifier.name, "doFoo", "Method has correct name")
 
     signatures = method.signatures()
     harness.check(len(signatures), 1, "Expect one signature")
 
     (returnType, arguments) = signatures[0]
-    harness.check(str(returnType), "TestEnum", "Method type is the correct name")
+    harness.check(str(returnType), "TestEnum (Wrapper)", "Method type is the correct name")
     harness.check(len(arguments), 1, "Method has the right number of arguments")
     arg = arguments[0]
     harness.ok(isinstance(arg, WebIDL.IDLArgument), "Should be an IDLArgument")
     harness.check(str(arg.type), "Boolean", "Argument has the right type")
 
     attr = members[1]
     harness.check(attr.identifier.QName(), "::TestEnumInterface::foo",
                   "Attr has correct QName")
     harness.check(attr.identifier.name, "foo", "Attr has correct name")
 
-    harness.check(str(attr.type), "TestEnum", "Attr type is the correct name")
+    harness.check(str(attr.type), "TestEnum (Wrapper)", "Attr type is the correct name")
new file mode 100644
--- /dev/null
+++ b/dom/bindings/parser/tests/test_error_colno.py
@@ -0,0 +1,20 @@
+import WebIDL
+
+def WebIDLTest(parser, harness):
+    # Check that error messages put the '^' in the right place.
+
+    threw = False
+    input = 'interface ?'
+    try:
+        parser.parse(input)
+        results = parser.finish()
+    except WebIDL.WebIDLError as e:
+        threw = True
+        lines = str(e).split('\n')
+
+        harness.check(len(lines), 3, 'Expected number of lines in error message')
+        harness.check(lines[1], input, 'Second line shows error')
+        harness.check(lines[2], ' ' * (len(input) - 1) + '^',
+                      'Correct column pointer in error message')
+
+    harness.ok(threw, "Should have thrown.")
new file mode 100644
--- /dev/null
+++ b/dom/bindings/parser/tests/test_nullable_equivalency.py
@@ -0,0 +1,134 @@
+import WebIDL
+
+def WebIDLTest(parser, harness):
+    parser.parse("""
+        interface TestNullableEquivalency1 {
+          attribute long  a;
+          attribute long? b;
+        };
+
+        interface TestNullableEquivalency2 {
+          attribute ArrayBuffer  a;
+          attribute ArrayBuffer? b;
+        };
+
+        /* Not implemented */
+        /*dictionary TestNullableEquivalency3Dict {
+          long foo = 42;
+        };
+
+        interface TestNullableEquivalency3 {
+          attribute Test3Dict  a;
+          attribute Test3Dict? b;
+        };*/
+
+        enum TestNullableEquivalency4Enum {
+          "Foo",
+          "Bar"
+        };
+
+        interface TestNullableEquivalency4 {
+          attribute TestNullableEquivalency4Enum  a;
+          attribute TestNullableEquivalency4Enum? b;
+        };
+
+        interface TestNullableEquivalency5 {
+          attribute TestNullableEquivalency4  a;
+          attribute TestNullableEquivalency4? b;
+        };
+
+        interface TestNullableEquivalency6 {
+          attribute boolean  a;
+          attribute boolean? b;
+        };
+
+        interface TestNullableEquivalency7 {
+          attribute DOMString  a;
+          attribute DOMString? b;
+        };
+
+        /* Not implemented. */
+        /*interface TestNullableEquivalency8 {
+          attribute float  a;
+          attribute float? b;
+        };*/
+
+        interface TestNullableEquivalency8 {
+          attribute double  a;
+          attribute double? b;
+        };
+
+        interface TestNullableEquivalency9 {
+          attribute object  a;
+          attribute object? b;
+        };
+
+        interface TestNullableEquivalency10 {
+          attribute double[]  a;
+          attribute double[]? b;
+        };
+
+        interface TestNullableEquivalency11 {
+          attribute TestNullableEquivalency9[]  a;
+          attribute TestNullableEquivalency9[]? b;
+        };
+    """)
+
+    for decl in parser.finish():
+        if decl.isInterface():
+            checkEquivalent(decl, harness)
+
+def checkEquivalent(iface, harness):
+    type1 = iface.members[0].type
+    type2 = iface.members[1].type
+
+    harness.check(type1.nullable(), False, 'attr1 should not be nullable')
+    harness.check(type2.nullable(), True, 'attr2 should be nullable')
+
+    # We don't know about type1, but type2, the nullable type, definitely
+    # shouldn't be builtin.
+    harness.check(type2.builtin, False, 'attr2 should not be builtin')
+
+    # Ensure that all attributes of type2 match those in type1, except for:
+    #  - names on an ignore list,
+    #  - names beginning with '_',
+    #  - functions which throw when called with no args, and
+    #  - class-level non-callables ("static variables").
+    #
+    # Yes, this is an ugly, fragile hack.  But it finds bugs...
+    for attr in dir(type1):
+        if attr.startswith('_') or \
+           attr in ['nullable', 'builtin', 'filename', 'location',
+                    'inner', 'QName'] or \
+           (hasattr(type(type1), attr) and not callable(getattr(type1, attr))):
+            continue
+
+        a1 = getattr(type1, attr)
+
+        if callable(a1):
+            try:
+                v1 = a1()
+            except:
+                # Can't call a1 with no args, so skip this attriute.
+                continue
+
+            try:
+                a2 = getattr(type2, attr)
+            except:
+                harness.ok(False, 'Missing %s attribute on type %s in %s' % (attr, type2, iface))
+                continue
+
+            if not callable(a2):
+                harness.ok(False, "%s attribute on type %s in %s wasn't callable" % (attr, type2, iface))
+                continue
+
+            v2 = a2()
+            harness.check(v2, v1, '%s method return value' % attr)
+        else:
+            try:
+                a2 = getattr(type2, attr)
+            except:
+                harness.ok(False, 'Missing %s attribute on type %s in %s' % (attr, type2, iface))
+                continue
+
+            harness.check(a2, a1, '%s attribute should match' % attr)
--- a/dom/interfaces/base/nsIDOMScreen.idl
+++ b/dom/interfaces/base/nsIDOMScreen.idl
@@ -34,54 +34,31 @@
  * 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 "nsIDOMEventTarget.idl"
 
-[scriptable, uuid(8a66b30c-9a32-4b17-ab4e-ca8b7b588243)]
+[scriptable, uuid(9b978f58-5bfe-409d-aa3f-946ca934e51d)]
 interface nsIDOMScreen : nsIDOMEventTarget
 {
   readonly attribute long             top;
   readonly attribute long             left;
   readonly attribute long             width;
   readonly attribute long             height;
   readonly attribute long             pixelDepth;
   readonly attribute long             colorDepth;
   readonly attribute long             availWidth;
   readonly attribute long             availHeight;
   readonly attribute long             availLeft;
   readonly attribute long             availTop;
 
   /**
-   * Is the device's screen currently enabled?  This attribute controls the
-   * device's screen, so setting it to false will turn off the screen.
-   */
-  attribute boolean mozEnabled;
-
-  /**
-   * How bright is the screen's backlight, on a scale from 0 (very dim) to 1
-   * (full brightness)?  Setting this attribute modifies the screen's
-   * brightness.
-   *
-   * You can read and write this attribute even when the screen is disabled,
-   * but the backlight is off while the screen is disabled.
-   *
-   * If you write a value of X into this attribute, the attribute may not have
-   * the same value X when you later read it.  Most screens don't support as
-   * many different brightness levels as there are doubles between 0 and 1, so
-   * we may reduce the value's precision before storing it.
-   *
-   * @throw NS_ERROR_INVALID_ARG if brightness is not in the range [0, 1].
-   */
-  attribute double mozBrightness;
-
-  /**
    * Returns the current screen orientation.
    * Can be: landscape-primary, landscape-secondary,
    *         portrait-primary or portrait-secondary.
    */
   readonly attribute DOMString       mozOrientation;
 
   attribute nsIDOMEventListener      onmozorientationchange;
 
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -44,18 +44,16 @@
 #include "History.h"
 #include "mozilla/ipc/TestShellParent.h"
 #include "mozilla/net/NeckoParent.h"
 #include "mozilla/Preferences.h"
 #include "nsHashPropertyBag.h"
 #include "nsIFilePicker.h"
 #include "nsIWindowWatcher.h"
 #include "nsIDOMWindow.h"
-#include "nsIPrefBranch.h"
-#include "nsIPrefLocalizedString.h"
 #include "nsIObserverService.h"
 #include "nsContentUtils.h"
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsServiceManagerUtils.h"
 #include "nsThreadUtils.h"
 #include "nsChromeRegistryChrome.h"
 #include "nsExternalHelperAppService.h"
@@ -211,20 +209,17 @@ ContentParent::Init()
         obs->AddObserver(this, "child-memory-reporter-request", false);
         obs->AddObserver(this, "memory-pressure", false);
         obs->AddObserver(this, "child-gc-request", false);
         obs->AddObserver(this, "child-cc-request", false);
 #ifdef ACCESSIBILITY
         obs->AddObserver(this, "a11y-init-or-shutdown", false);
 #endif
     }
-    nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
-    if (prefs) {
-        prefs->AddObserver("", this, false);
-    }
+    Preferences::AddStrongObserver(this, "");
     nsCOMPtr<nsIThreadInternal>
             threadInt(do_QueryInterface(NS_GetCurrentThread()));
     if (threadInt) {
         threadInt->AddObserver(this);
     }
     if (obs) {
         obs->NotifyObservers(static_cast<nsIObserver*>(this), "ipc:content-created", nsnull);
     }
@@ -244,23 +239,18 @@ ContentParent::OnChannelConnected(int32 
     ProcessHandle handle;
     if (!base::OpenPrivilegedProcessHandle(pid, &handle)) {
         NS_WARNING("Can't open handle to child process.");
     }
     else {
         SetOtherProcess(handle);
 
 #if defined(ANDROID) || defined(LINUX)
-        EnsurePrefService();
-        nsCOMPtr<nsIPrefBranch> branch;
-        branch = do_QueryInterface(mPrefService);
-
         // Check nice preference
-        PRInt32 nice = 0;
-        branch->GetIntPref("dom.ipc.content.nice", &nice);
+        PRInt32 nice = Preferences::GetInt("dom.ipc.content.nice", 0);
 
         // Environment variable overrides preference
         char* relativeNicenessStr = getenv("MOZ_CHILD_PROCESS_RELATIVE_NICENESS");
         if (relativeNicenessStr) {
             nice = atoi(relativeNicenessStr);
         }
 
         /* make the GUI thread have higher priority on single-cpu devices */
@@ -324,21 +314,17 @@ ContentParent::ActorDestroy(ActorDestroy
 
     mMessageManager->Disconnect();
 
     // clear the child memory reporters
     InfallibleTArray<MemoryReport> empty;
     SetChildMemoryReporters(empty);
 
     // remove the global remote preferences observers
-    nsCOMPtr<nsIPrefBranch> prefs 
-            (do_GetService(NS_PREFSERVICE_CONTRACTID));
-    if (prefs) { 
-        prefs->RemoveObserver("", this);
-    }
+    Preferences::RemoveObserver(this, "");
 
     RecvRemoveGeolocationListener();
 
     nsCOMPtr<nsIThreadInternal>
         threadInt(do_QueryInterface(NS_GetCurrentThread()));
     if (threadInt)
         threadInt->RemoveObserver(this);
     if (mRunToCompletionDepth)
@@ -459,42 +445,29 @@ bool
 ContentParent::IsAlive()
 {
     return mIsAlive;
 }
 
 bool
 ContentParent::RecvReadPrefsArray(InfallibleTArray<PrefTuple> *prefs)
 {
-    EnsurePrefService();
     Preferences::MirrorPreferences(prefs);
     return true;
 }
 
 bool
 ContentParent::RecvReadFontList(InfallibleTArray<FontListEntry>* retValue)
 {
 #ifdef ANDROID
     gfxAndroidPlatform::GetPlatform()->GetFontList(retValue);
 #endif
     return true;
 }
 
-
-void
-ContentParent::EnsurePrefService()
-{
-    nsresult rv;
-    if (!mPrefService) {
-        mPrefService = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
-        NS_ASSERTION(NS_SUCCEEDED(rv), 
-                     "We lost prefService in the Chrome process !");
-    }
-}
-
 bool
 ContentParent::RecvReadPermissions(InfallibleTArray<IPC::Permission>* aPermissions)
 {
 #ifdef MOZ_PERMISSIONS
     nsCOMPtr<nsIPermissionManager> permissionManagerIface =
         do_GetService(NS_PERMISSIONMANAGER_CONTRACTID);
     nsPermissionManager* permissionManager =
         static_cast<nsPermissionManager*>(permissionManagerIface.get());
--- a/dom/ipc/ContentParent.h
+++ b/dom/ipc/ContentParent.h
@@ -43,17 +43,16 @@
 
 #include "mozilla/dom/PContentParent.h"
 #include "mozilla/dom/PMemoryReportRequestParent.h"
 #include "mozilla/ipc/GeckoChildProcessHost.h"
 
 #include "nsIObserver.h"
 #include "nsIThreadInternal.h"
 #include "nsNetUtil.h"
-#include "nsIPrefService.h"
 #include "nsIPermissionManager.h"
 #include "nsIDOMGeoPositionCallback.h"
 #include "nsIMemoryReporter.h"
 #include "nsCOMArray.h"
 
 class nsFrameMessageManager;
 namespace mozilla {
 
@@ -162,18 +161,16 @@ private:
     virtual bool DeallocPSms(PSmsParent*);
 
     virtual PStorageParent* AllocPStorage(const StorageConstructData& aData);
     virtual bool DeallocPStorage(PStorageParent* aActor);
 
     virtual bool RecvReadPrefsArray(InfallibleTArray<PrefTuple> *retValue);
     virtual bool RecvReadFontList(InfallibleTArray<FontListEntry>* retValue);
 
-    void EnsurePrefService();
-
     virtual bool RecvReadPermissions(InfallibleTArray<IPC::Permission>* aPermissions);
 
     virtual bool RecvGetIndexedDBDirectory(nsString* aDirectory);
 
     virtual bool RecvSetClipboardText(const nsString& text, const PRInt32& whichClipboard);
     virtual bool RecvGetClipboardText(const PRInt32& whichClipboard, nsString* text);
     virtual bool RecvEmptyClipboard();
     virtual bool RecvClipboardHasText(bool* hasText);
@@ -233,18 +230,16 @@ private:
 
     // This is a cache of all of the memory reporters
     // registered in the child process.  To update this, one
     // can broadcast the topic "child-memory-reporter-request" using
     // the nsIObserverService.
     nsCOMArray<nsIMemoryReporter> mMemoryReporters;
 
     bool mIsAlive;
-    nsCOMPtr<nsIPrefService> mPrefService;
-
     bool mSendPermissionUpdates;
 
     nsRefPtr<nsFrameMessageManager> mMessageManager;
 
     friend class CrashReporterParent;
 };
 
 } // namespace dom
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -50,22 +50,21 @@
 
 #include "nsPluginHost.h"
 #include "nsNPAPIPlugin.h"
 #include "nsNPAPIPluginInstance.h"
 #include "nsNPAPIPluginStreamListener.h"
 #include "nsIServiceManager.h"
 #include "nsThreadUtils.h"
 #include "nsIPrivateBrowsingService.h"
+#include "mozilla/Preferences.h"
 
 #include "nsIPluginStreamListener.h"
 #include "nsPluginsDir.h"
 #include "nsPluginSafety.h"
-#include "nsIPrefService.h"
-#include "nsIPrefBranch.h"
 #include "nsPluginLogging.h"
 
 #include "nsIJSContextStack.h"
 
 #include "nsIDOMElement.h"
 #include "nsIDOMDocument.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDocument.h"
@@ -347,17 +346,17 @@ nsNPAPIPlugin::RunPluginOOP(const nsPlug
       }
       if (versionPrefix.EqualsASCII("10.1") && GMA9XXGraphics()) {
         return false;
       }
     }
   }
 #endif
 
-  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
+  nsIPrefBranch* prefs = Preferences::GetRootBranch();
   if (!prefs) {
     return false;
   }
 
   // Get per-library whitelist/blacklist pref string
   // "dom.ipc.plugins.enabled.filename.dll" and fall back to the default value
   // of "dom.ipc.plugins.enabled"
   // The "filename.dll" part can contain shell wildcard pattern
@@ -380,18 +379,17 @@ nsNPAPIPlugin::RunPluginOOP(const nsPlug
 #else
   nsCAutoString prefGroupKey("dom.ipc.plugins.enabled.");
 #endif
 
   // Java plugins include a number of different file names,
   // so use the mime type (mIsJavaPlugin) and a special pref.
   bool javaIsEnabled;
   if (aPluginTag->mIsJavaPlugin &&
-      NS_SUCCEEDED(prefs->GetBoolPref("dom.ipc.plugins.java.enabled", &javaIsEnabled)) &&
-      !javaIsEnabled) {
+      !Preferences::GetBool("dom.ipc.plugins.java.enabled", true)) {
     return false;
   }
 
   PRUint32 prefCount;
   char** prefNames;
   nsresult rv = prefs->GetChildList(prefGroupKey.get(),
                                     &prefCount, &prefNames);
 
@@ -412,37 +410,37 @@ nsNPAPIPlugin::RunPluginOOP(const nsPlug
       else if(valid == NON_SXP) {
         // mask is not a shell pattern, compare it as normal string
         match = (strcmp(prefFile.get(), maskStart) == 0);
       }
       else {
         match = (NS_WildCardMatch(prefFile.get(), maskStart, 0) == MATCH);
       }
 
-      if (match && NS_SUCCEEDED(prefs->GetBoolPref(prefNames[currentPref],
-                                                   &oopPluginsEnabled))) {
+      if (match && NS_SUCCEEDED(Preferences::GetBool(prefNames[currentPref],
+                                                     &oopPluginsEnabled))) {
         prefSet = true;
         break;
       }
     }
     NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(prefCount, prefNames);
   }
 
   if (!prefSet) {
-    oopPluginsEnabled = false;
+    oopPluginsEnabled =
 #ifdef XP_MACOSX
 #if defined(__i386__)
-    prefs->GetBoolPref("dom.ipc.plugins.enabled.i386", &oopPluginsEnabled);
+    Preferences::GetBool("dom.ipc.plugins.enabled.i386", false);
 #elif defined(__x86_64__)
-    prefs->GetBoolPref("dom.ipc.plugins.enabled.x86_64", &oopPluginsEnabled);
+    Preferences::GetBool("dom.ipc.plugins.enabled.x86_64", false);
 #elif defined(__ppc__)
-    prefs->GetBoolPref("dom.ipc.plugins.enabled.ppc", &oopPluginsEnabled);
+    Preferences::GetBool("dom.ipc.plugins.enabled.ppc", false);
 #endif
 #else
-    prefs->GetBoolPref("dom.ipc.plugins.enabled", &oopPluginsEnabled);
+    Preferences::GetBool("dom.ipc.plugins.enabled", false);
 #endif
   }
 
   return oopPluginsEnabled;
 }
 
 inline PluginLibrary*
 GetNewPluginLibrary(nsPluginTag *aPluginTag)
@@ -2056,22 +2054,20 @@ NPError NP_CALLBACK
       return NPERR_NO_ERROR;
     }
     return NPERR_GENERIC_ERROR;
   }
 #endif
 
   case NPNVjavascriptEnabledBool: {
     *(NPBool*)result = false;
-    nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
-    if (prefs) {
-      bool js = false;;
-      res = prefs->GetBoolPref("javascript.enabled", &js);
-      if (NS_SUCCEEDED(res))
-        *(NPBool*)result = js;
+    bool js = false;
+    res = Preferences::GetBool("javascript.enabled", &js);
+    if (NS_SUCCEEDED(res)) {
+      *(NPBool*)result = js;
     }
     return NPERR_NO_ERROR;
   }
 
   case NPNVasdEnabledBool:
     *(NPBool*)result = false;
     return NPERR_NO_ERROR;
 
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -56,16 +56,18 @@
 #include "nsIScriptContext.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsJSNPRuntime.h"
 #include "nsPluginStreamListenerPeer.h"
 #include "nsSize.h"
 #include "nsNetCID.h"
 #include "nsIContent.h"
 
+#include "mozilla/Preferences.h"
+
 #ifdef MOZ_WIDGET_ANDROID
 #include "ANPBase.h"
 #include <android/log.h>
 #include "android_npapi.h"
 #include "mozilla/Mutex.h"
 #include "mozilla/CondVar.h"
 #include "AndroidBridge.h"
 #endif
@@ -100,23 +102,18 @@ nsNPAPIPluginInstance::nsNPAPIPluginInst
     mUsePluginLayersPref(true)
 #else
     mUsePluginLayersPref(false)
 #endif
 {
   mNPP.pdata = NULL;
   mNPP.ndata = this;
 
-  nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
-  if (prefs) {
-    bool useLayersPref;
-    nsresult rv = prefs->GetBoolPref("plugins.use_layers", &useLayersPref);
-    if (NS_SUCCEEDED(rv))
-      mUsePluginLayersPref = useLayersPref;
-  }
+  mUsePluginLayersPref =
+    Preferences::GetBool("plugins.use_layers", mUsePluginLayersPref);
 
   PLUGIN_LOG(PLUGIN_LOG_BASIC, ("nsNPAPIPluginInstance ctor: this=%p\n",this));
 }
 
 nsNPAPIPluginInstance::~nsNPAPIPluginInstance()
 {
   PLUGIN_LOG(PLUGIN_LOG_BASIC, ("nsNPAPIPluginInstance dtor: this=%p\n",this));
 
--- a/dom/plugins/base/nsPluginDirServiceProvider.cpp
+++ b/dom/plugins/base/nsPluginDirServiceProvider.cpp
@@ -36,26 +36,26 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsPluginDirServiceProvider.h"
 
 #include "nsCRT.h"
 #include "nsILocalFile.h"
-#include "nsIPrefBranch.h"
-#include "nsIPrefService.h"
 #include "nsDependentString.h"
-#include "nsXPIDLString.h"
 #include "prmem.h"
 #include "nsArrayEnumerator.h"
+#include "mozilla/Preferences.h"
 
 #include <windows.h>
 #include "nsIWindowsRegKey.h"
 
+using namespace mozilla;
+
 typedef struct structVer
 {
   WORD wMajor;
   WORD wMinor;
   WORD wRelease;
   WORD wBuild;
 } verBlock;
 
@@ -226,28 +226,25 @@ nsPluginDirServiceProvider::GetFile(cons
   nsCOMPtr<nsILocalFile>  localFile;
   nsresult rv = NS_ERROR_FAILURE;
 
   NS_ENSURE_ARG(charProp);
 
   *_retval = nsnull;
   *persistant = false;
 
-  nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
-  if (!prefs)
-    return NS_ERROR_FAILURE;
-
   nsCOMPtr<nsIWindowsRegKey> regKey =
     do_CreateInstance("@mozilla.org/windows-registry-key;1");
   NS_ENSURE_TRUE(regKey, NS_ERROR_FAILURE);
 
   if (nsCRT::strcmp(charProp, NS_WIN_JRE_SCAN_KEY) == 0) {
-    nsXPIDLCString strVer;
-    if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer))))
+    nsAdoptingCString strVer = Preferences::GetCString(charProp);
+    if (!strVer) {
       return NS_ERROR_FAILURE;
+    }
     verBlock minVer;
     TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);
 
     rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE,
                       NS_LITERAL_STRING("Software\\JavaSoft\\Java Runtime Environment"),
                       nsIWindowsRegKey::ACCESS_READ);
     NS_ENSURE_SUCCESS(rv, rv);
 
@@ -327,19 +324,20 @@ nsPluginDirServiceProvider::GetFile(cons
                          &currentVersionExists);
         if (!currentVersionExists) {
           newKey->WriteStringValue(NS_LITERAL_STRING("CurrentVersion"),
                                    NS_LITERAL_STRING(MOZILLA_VERSION));
         }
       }
     }
   } else if (nsCRT::strcmp(charProp, NS_WIN_QUICKTIME_SCAN_KEY) == 0) {
-    nsXPIDLCString strVer;
-    if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer))))
+    nsAdoptingCString strVer = Preferences::GetCString(charProp);
+    if (!strVer) {
       return NS_ERROR_FAILURE;
+    }
     verBlock minVer;
     TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);
 
     // Look for the Quicktime system installation plugins directory
     verBlock qtVer;
     ClearVersion(&qtVer);
 
     // First we need to check the version of Quicktime via checking
@@ -366,19 +364,20 @@ nsPluginDirServiceProvider::GetFile(cons
       rv = regKey->ReadStringValue(NS_LITERAL_STRING("InstallDir"), path);
       if (NS_SUCCEEDED(rv)) {
         path += NS_LITERAL_STRING("\\Plugins");
         rv = NS_NewLocalFile(path, true,
                              getter_AddRefs(localFile));
       }
     }
   } else if (nsCRT::strcmp(charProp, NS_WIN_WMP_SCAN_KEY) == 0) {
-    nsXPIDLCString strVer;
-    if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer))))
+    nsAdoptingCString strVer = Preferences::GetCString(charProp);
+    if (!strVer) {
       return NS_ERROR_FAILURE;
+    }
     verBlock minVer;
     TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);
 
     // Look for Windows Media Player system installation plugins directory
     verBlock wmpVer;
     ClearVersion(&wmpVer);
 
     // First we need to check the version of WMP
@@ -404,18 +403,18 @@ nsPluginDirServiceProvider::GetFile(cons
       rv = regKey->ReadStringValue(NS_LITERAL_STRING("Installation Directory"),
                                    path);
       if (NS_SUCCEEDED(rv)) {
         rv = NS_NewLocalFile(path, true,
                              getter_AddRefs(localFile));
       }
     }
   } else if (nsCRT::strcmp(charProp, NS_WIN_ACROBAT_SCAN_KEY) == 0) {
-    nsXPIDLCString strVer;
-    if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer)))) {
+    nsAdoptingCString strVer = Preferences::GetCString(charProp);
+    if (!strVer) {
       return NS_ERROR_FAILURE;
     }
 
     verBlock minVer;
     TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);
 
     // Look for Adobe Acrobat system installation plugins directory
     verBlock maxVer;
--- a/dom/plugins/base/nsPluginHost.cpp
+++ b/dom/plugins/base/nsPluginHost.cpp
@@ -75,24 +75,24 @@
 #include "nsISeekableStream.h"
 #include "nsNetUtil.h"
 #include "nsIProgressEventSink.h"
 #include "nsIDocument.h"
 #include "nsICachingChannel.h"
 #include "nsHashtable.h"
 #include "nsIProxyInfo.h"
 #include "nsPluginLogging.h"
-#include "nsIPrefBranch.h"
 #include "nsIScriptChannel.h"
 #include "nsIBlocklistService.h"
 #include "nsVersionComparator.h"
 #include "nsIPrivateBrowsingService.h"
 #include "nsIObjectLoadingContent.h"
 #include "nsIWritablePropertyBag2.h"
 #include "nsPluginStreamListenerPeer.h"
+#include "mozilla/Preferences.h"
 
 #include "nsEnumeratorUtils.h"
 #include "nsXPCOM.h"
 #include "nsXPCOMCID.h"
 #include "nsISupportsPrimitives.h"
 
 #include "nsXULAppAPI.h"
 #include "nsIXULRuntime.h"
@@ -331,49 +331,29 @@ NS_IMETHODIMP nsPluginDocReframeEvent::R
     }
   }
 
   return mDocs->Clear();
 }
 
 static bool UnloadPluginsASAP()
 {
-  nsresult rv;
-  nsCOMPtr<nsIPrefBranch> pref(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
-  if (NS_SUCCEEDED(rv)) {
-    bool unloadPluginsASAP = false;
-    rv = pref->GetBoolPref("dom.ipc.plugins.unloadASAP", &unloadPluginsASAP);
-    if (NS_SUCCEEDED(rv)) {
-      return unloadPluginsASAP;
-    }
-  }
-
-  return false;
+  return Preferences::GetBool("dom.ipc.plugins.unloadASAP", false);
 }
 
 nsPluginHost::nsPluginHost()
   // No need to initialize members to nsnull, false etc because this class
   // has a zeroing operator new.
 {
   // check to see if pref is set at startup to let plugins take over in
   // full page mode for certain image mime types that we handle internally
-  mPrefService = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  if (mPrefService) {
-    bool tmp;
-    nsresult rv = mPrefService->GetBoolPref("plugin.override_internal_types",
-                                            &tmp);
-    if (NS_SUCCEEDED(rv)) {
-      mOverrideInternalTypes = tmp;
-    }
-
-    rv = mPrefService->GetBoolPref("plugin.disable", &tmp);
-    if (NS_SUCCEEDED(rv)) {
-      mPluginsDisabled = tmp;
-    }
-  }
+  mOverrideInternalTypes =
+    Preferences::GetBool("plugin.override_internal_types", false);
+
+  mPluginsDisabled = Preferences::GetBool("plugin.disable", false);
 
   nsCOMPtr<nsIObserverService> obsService =
     mozilla::services::GetObserverService();
   if (obsService) {
     obsService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
     obsService->AddObserver(this, NS_PRIVATE_BROWSING_SWITCH_TOPIC, false);
 #ifdef MOZ_WIDGET_ANDROID
     obsService->AddObserver(this, "application-foreground", false);
@@ -423,26 +403,26 @@ nsPluginHost::GetInst()
       return nsnull;
     NS_ADDREF(sInst);
   }
 
   NS_ADDREF(sInst);
   return sInst;
 }
 
-bool nsPluginHost::IsRunningPlugin(nsPluginTag * plugin)
+bool nsPluginHost::IsRunningPlugin(nsPluginTag * aPluginTag)
 {
-  if (!plugin || !plugin->mEntryPoint) {
+  if (!aPluginTag || !aPluginTag->mPlugin) {
     return false;
   }
 
   for (PRUint32 i = 0; i < mInstances.Length(); i++) {
     nsNPAPIPluginInstance *instance = mInstances[i].get();
     if (instance &&
-        instance->GetPlugin() == plugin->mEntryPoint &&
+        instance->GetPlugin() == aPluginTag->mPlugin &&
         instance->IsRunning()) {
       return true;
     }
   }
 
   return false;
 }
 
@@ -861,18 +841,16 @@ nsresult nsPluginHost::Destroy()
     nsCOMPtr<nsIDirectoryService> dirService =
       do_GetService(kDirectoryServiceContractID);
     if (dirService)
       dirService->UnregisterProvider(mPrivateDirServiceProvider);
     mPrivateDirServiceProvider = nsnull;
   }
 #endif /* XP_WIN */
 
-  mPrefService = nsnull; // release prefs service to avoid leaks!
-
   return NS_OK;
 }
 
 void nsPluginHost::OnPluginInstanceDestroyed(nsPluginTag* aPluginTag)
 {
   bool hasInstance = false;
   for (PRUint32 i = 0; i < mInstances.Length(); i++) {
     if (TagForPlugin(mInstances[i]->GetPlugin()) == aPluginTag) {
@@ -1193,62 +1171,56 @@ nsPluginHost::FindTagForLibrary(PRLibrar
   return nsnull;
 }
 
 nsPluginTag*
 nsPluginHost::TagForPlugin(nsNPAPIPlugin* aPlugin)
 {
   nsPluginTag* pluginTag;
   for (pluginTag = mPlugins; pluginTag; pluginTag = pluginTag->mNext) {
-    if (pluginTag->mEntryPoint == aPlugin) {
+    if (pluginTag->mPlugin == aPlugin) {
       return pluginTag;
     }
   }
   // a plugin should never exist without a corresponding tag
   NS_ERROR("TagForPlugin has failed");
   return nsnull;
 }
 
 nsresult nsPluginHost::SetUpPluginInstance(const char *aMimeType,
                                            nsIURI *aURL,
                                            nsIPluginInstanceOwner *aOwner)
 {
   NS_ENSURE_ARG_POINTER(aOwner);
 
-  nsresult rv = NS_OK;
-
-  rv = TrySetUpPluginInstance(aMimeType, aURL, aOwner);
-
-  // if we fail, refresh plugin list just in case the plugin has been
-  // just added and try to instantiate plugin instance again, see bug 143178
-  if (NS_FAILED(rv)) {
-    // we should also make sure not to do this more than once per page
-    // so if there are a few embed tags with unknown plugins,
-    // we don't get unnecessary overhead
-    // let's cache document to decide whether this is the same page or not
-    nsCOMPtr<nsIDocument> document;
-    aOwner->GetDocument(getter_AddRefs(document));
-
-    nsCOMPtr<nsIDocument> currentdocument = do_QueryReferent(mCurrentDocument);
-    if (document == currentdocument)
-      return rv;
-
-    mCurrentDocument = do_GetWeakReference(document);
-
-    // ReloadPlugins will do the job smartly: nothing will be done
-    // if no changes detected, in such a case just return
-    if (NS_ERROR_PLUGINS_PLUGINSNOTCHANGED == ReloadPlugins(false))
-      return rv;
-
-    // other failure return codes may be not fatal, so we can still try
-    aOwner->SetInstance(nsnull); // avoid assert about setting it twice
-    rv = TrySetUpPluginInstance(aMimeType, aURL, aOwner);
+  nsresult rv = TrySetUpPluginInstance(aMimeType, aURL, aOwner);
+  if (NS_SUCCEEDED(rv)) {
+    return rv;
   }
 
-  return rv;
+  // If we failed to load a plugin instance we'll try again after
+  // reloading our plugin list. Only do that once per document to
+  // avoid redundant high resource usage on pages with multiple
+  // unkown instance types. We'll do that by caching the document.
+  nsCOMPtr<nsIDocument> document;
+  aOwner->GetDocument(getter_AddRefs(document));
+
+  nsCOMPtr<nsIDocument> currentdocument = do_QueryReferent(mCurrentDocument);
+  if (document == currentdocument) {
+    return rv;
+  }
+
+  mCurrentDocument = do_GetWeakReference(document);
+
+  // Don't try to set up an instance again if nothing changed.
+  if (ReloadPlugins(false) == NS_ERROR_PLUGINS_PLUGINSNOTCHANGED) {
+    return rv;
+  }
+
+  return TrySetUpPluginInstance(aMimeType, aURL, aOwner);
 }
 
 nsresult
 nsPluginHost::TrySetUpPluginInstance(const char *aMimeType,
                                      nsIURI *aURL,
                                      nsIPluginInstanceOwner *aOwner)
 {
 #ifdef PLUGIN_LOGGING
@@ -1455,21 +1427,17 @@ public:
   NS_METHOD GetDescription(nsAString& aDescription)
   {
     CopyUTF8toUTF16(mPluginTag.mDescription, aDescription);
     return NS_OK;
   }
 
   NS_METHOD GetFilename(nsAString& aFilename)
   {
-    bool bShowPath;
-    nsCOMPtr<nsIPrefBranch> prefService = do_GetService(NS_PREFSERVICE_CONTRACTID);
-    if (prefService &&
-        NS_SUCCEEDED(prefService->GetBoolPref("plugin.expose_full_path", &bShowPath)) &&
-        bShowPath) {
+    if (Preferences::GetBool("plugin.expose_full_path", false)) {
       CopyUTF8toUTF16(mPluginTag.mFullPath, aFilename);
     } else {
       CopyUTF8toUTF16(mPluginTag.mFileName, aFilename);
     }
 
     return NS_OK;
   }
 
@@ -1653,25 +1621,25 @@ static nsresult CreateNPAPIPlugin(nsPlug
   }
 
   nsresult rv;
   rv = nsNPAPIPlugin::CreatePlugin(aPluginTag, aOutNPAPIPlugin);
 
   return rv;
 }
 
-nsresult nsPluginHost::EnsurePluginLoaded(nsPluginTag* plugin)
+nsresult nsPluginHost::EnsurePluginLoaded(nsPluginTag* aPluginTag)
 {
-  nsRefPtr<nsNPAPIPlugin> entrypoint = plugin->mEntryPoint;
-  if (!entrypoint) {
-    nsresult rv = CreateNPAPIPlugin(plugin, getter_AddRefs(entrypoint));
+  nsRefPtr<nsNPAPIPlugin> plugin = aPluginTag->mPlugin;
+  if (!plugin) {
+    nsresult rv = CreateNPAPIPlugin(aPluginTag, getter_AddRefs(plugin));
     if (NS_FAILED(rv)) {
       return rv;
     }
-    plugin->mEntryPoint = entrypoint;
+    aPluginTag->mPlugin = plugin;
   }
   return NS_OK;
 }
 
 nsresult nsPluginHost::GetPlugin(const char *aMimeType, nsNPAPIPlugin** aPlugin)
 {
   nsresult rv = NS_ERROR_FAILURE;
   *aPlugin = NULL;
@@ -1694,17 +1662,17 @@ nsresult nsPluginHost::GetPlugin(const c
       printf("For %s found plugin %s\n", aMimeType, pluginTag->mFileName.get());
 #endif
 
     rv = EnsurePluginLoaded(pluginTag);
     if (NS_FAILED(rv)) {
       return rv;
     }
 
-    NS_ADDREF(*aPlugin = pluginTag->mEntryPoint);
+    NS_ADDREF(*aPlugin = pluginTag->mPlugin);
     return NS_OK;
   }
 
   PLUGIN_LOG(PLUGIN_LOG_NORMAL,
   ("nsPluginHost::GetPlugin End mime=%s, rv=%d, plugin=%p name=%s\n",
   aMimeType, rv, *aPlugin,
   (pluginTag ? pluginTag->mFileName.get() : "(not found)")));
 
@@ -1818,27 +1786,27 @@ nsPluginHost::ClearSiteData(nsIPluginTag
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   nsPluginTag* tag = static_cast<nsPluginTag*>(plugin);
 
   // We only ensure support for clearing Flash site data for now.
   // We will also attempt to clear data for any plugin that happens
   // to be loaded already.
-  if (!tag->mIsFlashPlugin && !tag->mEntryPoint) {
+  if (!tag->mIsFlashPlugin && !tag->mPlugin) {
     return NS_ERROR_FAILURE;
   }
 
   // Make sure the plugin is loaded.
   nsresult rv = EnsurePluginLoaded(tag);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
-  PluginLibrary* library = tag->mEntryPoint->GetLibrary();
+  PluginLibrary* library = tag->mPlugin->GetLibrary();
 
   // If 'domain' is the null string, clear everything.
   if (domain.IsVoid()) {
     return library->NPP_ClearSiteData(NULL, flags, maxAge);
   }
 
   // Get the list of sites from the plugin.
   InfallibleTArray<nsCString> sites;
@@ -1869,27 +1837,27 @@ nsPluginHost::SiteHasData(nsIPluginTag* 
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   nsPluginTag* tag = static_cast<nsPluginTag*>(plugin);
 
   // We only ensure support for clearing Flash site data for now.
   // We will also attempt to clear data for any plugin that happens
   // to be loaded already.
-  if (!tag->mIsFlashPlugin && !tag->mEntryPoint) {
+  if (!tag->mIsFlashPlugin && !tag->mPlugin) {
     return NS_ERROR_FAILURE;
   }
 
   // Make sure the plugin is loaded.
   nsresult rv = EnsurePluginLoaded(tag);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
-  PluginLibrary* library = tag->mEntryPoint->GetLibrary();
+  PluginLibrary* library = tag->mPlugin->GetLibrary();
 
   // Get the list of sites from the plugin.
   InfallibleTArray<nsCString> sites;
   rv = library->NPP_GetSitesWithData(sites);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // If there's no data, we're done.
   if (sites.IsEmpty()) {
@@ -2220,17 +2188,17 @@ nsresult nsPluginHost::ScanPluginsDirect
 
       if (pluginTag->IsEnabled()) {
         pluginTag->RegisterWithCategoryManager(mOverrideInternalTypes);
       }
     }
   }
 
   if (warnOutdated) {
-    mPrefService->SetBoolPref("plugins.update.notifyUser", true);
+    Preferences::SetBool("plugins.update.notifyUser", true);
   }
 
   return NS_OK;
 }
 
 nsresult nsPluginHost::ScanPluginsDirectoryList(nsISimpleEnumerator *dirEnum,
                                                 bool aCreatePluginList,
                                                 bool *aPluginsChanged)
@@ -2349,20 +2317,17 @@ nsresult nsPluginHost::FindPlugins(bool 
     LOG("getting plugins dir failed");
 #endif
   }
 
   mPluginsLoaded = true; // at this point 'some' plugins have been loaded,
                             // the rest is optional
 
 #ifdef XP_WIN
-  bool bScanPLIDs = false;
-
-  if (mPrefService)
-    mPrefService->GetBoolPref("plugin.scan.plid.all", &bScanPLIDs);
+  bool bScanPLIDs = Preferences::GetBool("plugin.scan.plid.all", false);
 
     // Now lets scan any PLID directories
   if (bScanPLIDs && mPrivateDirServiceProvider) {
     rv = mPrivateDirServiceProvider->GetPLIDDirectories(getter_AddRefs(dirList));
     if (NS_SUCCEEDED(rv)) {
       ScanPluginsDirectoryList(dirList, aCreatePluginList, &pluginschanged);
 
       if (pluginschanged)
@@ -3234,23 +3199,19 @@ nsPluginHost::StopPluginInstance(nsNPAPI
 
   Telemetry::AutoTimer<Telemetry::PLUGIN_SHUTDOWN_MS> timer;
   aInstance->Stop();
 
   // if the instance does not want to be 'cached' just remove it
   bool doCache = aInstance->ShouldCache();
   if (doCache) {
     // try to get the max cached instances from a pref or use default
-    PRUint32 cachedInstanceLimit;
-    nsresult rv = NS_ERROR_FAILURE;
-    if (mPrefService)
-      rv = mPrefService->GetIntPref(NS_PREF_MAX_NUM_CACHED_INSTANCES, (int*)&cachedInstanceLimit);
-    if (NS_FAILED(rv))
-      cachedInstanceLimit = DEFAULT_NUMBER_OF_STOPPED_INSTANCES;
-    
+    PRUint32 cachedInstanceLimit =
+      Preferences::GetUint(NS_PREF_MAX_NUM_CACHED_INSTANCES,
+                           DEFAULT_NUMBER_OF_STOPPED_INSTANCES);
     if (StoppedInstanceCount() >= cachedInstanceLimit) {
       nsNPAPIPluginInstance *oldestInstance = FindOldestStoppedInstance();
       if (oldestInstance) {
         nsPluginTag* pluginTag = TagForPlugin(oldestInstance->GetPlugin());
         oldestInstance->Destroy();
         mInstances.RemoveElement(oldestInstance);
         OnPluginInstanceDestroyed(pluginTag);
       }
@@ -3979,20 +3940,20 @@ nsPluginHost::PluginCrashed(nsNPAPIPlugi
 
       instance->Destroy();
       mInstances.RemoveElement(instance);
       OnPluginInstanceDestroyed(crashedPluginTag);
     }
   }
 
   // Only after all instances have been invalidated is it safe to null
-  // out nsPluginTag.mEntryPoint. The next time we try to create an
+  // out nsPluginTag.mPlugin. The next time we try to create an
   // instance of this plugin we reload it (launch a new plugin process).
 
-  crashedPluginTag->mEntryPoint = nsnull;
+  crashedPluginTag->mPlugin = nsnull;
 
 #ifdef XP_WIN
   CheckForDisabledWindows();
 #endif
 }
 
 nsNPAPIPluginInstance*
 nsPluginHost::FindInstance(const char *mimetype)
--- a/dom/plugins/base/nsPluginHost.h
+++ b/dom/plugins/base/nsPluginHost.h
@@ -48,17 +48,16 @@
 #include "nsNPAPIPluginInstance.h"
 #include "nsIPluginTag.h"
 #include "nsPluginsDir.h"
 #include "nsPluginDirServiceProvider.h"
 #include "nsAutoPtr.h"
 #include "nsWeakPtr.h"
 #include "nsIPrompt.h"
 #include "nsISupportsArray.h"
-#include "nsIPrefBranch.h"
 #include "nsWeakReference.h"
 #include "nsThreadUtils.h"
 #include "nsTArray.h"
 #include "nsTObserverArray.h"
 #include "nsITimer.h"
 #include "nsPluginTags.h"
 #include "nsIEffectiveTLDService.h"
 #include "nsIIDNService.h"
@@ -270,19 +269,19 @@ private:
                        bool aCreatePluginList,
                        bool *aPluginsChanged);
 
   nsresult
   ScanPluginsDirectoryList(nsISimpleEnumerator *dirEnum,
                            bool aCreatePluginList,
                            bool *aPluginsChanged);
 
-  nsresult EnsurePluginLoaded(nsPluginTag* plugin);
+  nsresult EnsurePluginLoaded(nsPluginTag* aPluginTag);
 
-  bool IsRunningPlugin(nsPluginTag * plugin);
+  bool IsRunningPlugin(nsPluginTag * aPluginTag);
 
   // Stores all plugins info into the registry
   nsresult WritePluginInfo();
 
   // Loads all cached plugins info into mCachedPlugins
   nsresult ReadPluginInfo();
 
   // Given a file path, returns the plugins info from our cache
@@ -317,17 +316,16 @@ private:
   // set by pref plugin.disable
   bool mPluginsDisabled;
 
   // Any instances in this array will have valid plugin objects via GetPlugin().
   // When removing an instance it might not die - be sure to null out it's plugin.
   nsTArray< nsRefPtr<nsNPAPIPluginInstance> > mInstances;
 
   nsCOMPtr<nsIFile> mPluginRegFile;
-  nsCOMPtr<nsIPrefBranch> mPrefService;
 #ifdef XP_WIN
   nsRefPtr<nsPluginDirServiceProvider> mPrivateDirServiceProvider;
 #endif
 
   nsCOMPtr<nsIEffectiveTLDService> mTLDService;
   nsCOMPtr<nsIIDNService> mIDNService;
 
   // Helpers for ClearSiteData and SiteHasData.
--- a/dom/plugins/base/nsPluginSafety.h
+++ b/dom/plugins/base/nsPluginSafety.h
@@ -35,36 +35,35 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsPluginSafety_h_
 #define nsPluginSafety_h_
 
 #include "npapi.h"
 #include "nsPluginHost.h"
-#include "nsIPrefBranch.h"
-#include "nsIPrefService.h"
 #include <prinrval.h>
 
 #if defined(XP_WIN)
 #define CALL_SAFETY_ON
 #endif
 
 void NS_NotifyPluginCall(PRIntervalTime);
 
 #ifdef CALL_SAFETY_ON
 
+#include "mozilla/Preferences.h"
+
 extern bool gSkipPluginSafeCalls;
 
-#define NS_INIT_PLUGIN_SAFE_CALLS                               \
-PR_BEGIN_MACRO                                                  \
-  nsresult res;                                                 \
-  nsCOMPtr<nsIPrefBranch> pref(do_GetService(NS_PREFSERVICE_CONTRACTID, &res)); \
-  if(NS_SUCCEEDED(res) && pref)                                 \
-    res = pref->GetBoolPref("plugin.dont_try_safe_calls", &gSkipPluginSafeCalls);\
+#define NS_INIT_PLUGIN_SAFE_CALLS                                  \
+PR_BEGIN_MACRO                                                     \
+  gSkipPluginSafeCalls =                                           \
+    ::mozilla::Preferences::GetBool("plugin.dont_try_safe_calls",  \
+                                    gSkipPluginSafeCalls);         \
 PR_END_MACRO
 
 #define NS_TRY_SAFE_CALL_RETURN(ret, fun, pluginInst) \
 PR_BEGIN_MACRO                                     \
   PRIntervalTime startTime = PR_IntervalNow();     \
   if(gSkipPluginSafeCalls)                         \
     ret = fun;                                     \
   else                                             \
--- a/dom/plugins/base/nsPluginTags.cpp
+++ b/dom/plugins/base/nsPluginTags.cpp
@@ -40,28 +40,28 @@
 
 #include "nsPluginTags.h"
 
 #include "prlink.h"
 #include "plstr.h"
 #include "nsIPluginInstanceOwner.h"
 #include "nsIDocument.h"
 #include "nsServiceManagerUtils.h"
-#include "nsIPrefService.h"
-#include "nsIPrefBranch.h"
 #include "nsPluginsDir.h"
 #include "nsPluginHost.h"
 #include "nsIUnicodeDecoder.h"
 #include "nsIPlatformCharset.h"
 #include "nsICharsetConverterManager.h"
 #include "nsPluginLogging.h"
 #include "nsICategoryManager.h"
 #include "nsNPAPIPlugin.h"
 #include "mozilla/TimeStamp.h"
+#include "mozilla/Preferences.h"
 
+using namespace mozilla;
 using mozilla::TimeStamp;
 
 inline char* new_str(const char* str)
 {
   if (str == nsnull)
     return nsnull;
   
   char* result = new char[strlen(str) + 1];
@@ -383,32 +383,28 @@ nsPluginTag::RegisterWithCategoryManager
               mFileName.get(), aType == ePluginUnregister ? "yes" : "no"));
   
   nsCOMPtr<nsICategoryManager> catMan = do_GetService(NS_CATEGORYMANAGER_CONTRACTID);
   if (!catMan)
     return;
   
   const char *contractId = "@mozilla.org/content/plugin/document-loader-factory;1";
   
-  nsCOMPtr<nsIPrefBranch> psvc(do_GetService(NS_PREFSERVICE_CONTRACTID));
-  if (!psvc)
-    return; // NS_ERROR_OUT_OF_MEMORY
-  
   // A preference controls whether or not the full page plugin is disabled for
   // a particular type. The string must be in the form:
   //   type1,type2,type3,type4
   // Note: need an actual interface to control this and subsequent disabling 
   // (and other plugin host settings) so applications can reliably disable 
   // plugins - without relying on implementation details such as prefs/category
   // manager entries.
-  nsXPIDLCString overrideTypes;
   nsCAutoString overrideTypesFormatted;
   if (aType != ePluginUnregister) {
-    psvc->GetCharPref("plugin.disable_full_page_plugin_for_types", getter_Copies(overrideTypes));
     overrideTypesFormatted.Assign(',');
+    nsAdoptingCString overrideTypes =
+      Preferences::GetCString("plugin.disable_full_page_plugin_for_types");
     overrideTypesFormatted += overrideTypes;
     overrideTypesFormatted.Append(',');
   }
   
   nsACString::const_iterator start, end;
   for (PRUint32 i = 0; i < mMimeTypes.Length(); i++) {
     if (aType == ePluginUnregister) {
       nsXPIDLCString value;
@@ -509,13 +505,13 @@ bool nsPluginTag::Equals(nsPluginTag *aP
 void nsPluginTag::TryUnloadPlugin(bool inShutdown)
 {
   // We never want to send NPP_Shutdown to an in-process plugin unless
   // this process is shutting down.
   if (mLibrary && !inShutdown) {
     return;
   }
 
-  if (mEntryPoint) {
-    mEntryPoint->Shutdown();
-    mEntryPoint = nsnull;
+  if (mPlugin) {
+    mPlugin->Shutdown();
+    mPlugin = nsnull;
   }
 }
--- a/dom/plugins/base/nsPluginTags.h
+++ b/dom/plugins/base/nsPluginTags.h
@@ -103,17 +103,17 @@ public:
   nsRefPtr<nsPluginTag> mNext;
   nsPluginHost *mPluginHost;
   nsCString     mName; // UTF-8
   nsCString     mDescription; // UTF-8
   nsTArray<nsCString> mMimeTypes; // UTF-8
   nsTArray<nsCString> mMimeDescriptions; // UTF-8
   nsTArray<nsCString> mExtensions; // UTF-8
   PRLibrary     *mLibrary;
-  nsRefPtr<nsNPAPIPlugin> mEntryPoint;
+  nsRefPtr<nsNPAPIPlugin> mPlugin;
   bool          mIsJavaPlugin;
   bool          mIsNPRuntimeEnabledJavaPlugin;
   bool          mIsFlashPlugin;
   nsCString     mFileName; // UTF-8
   nsCString     mFullPath; // UTF-8
   nsCString     mVersion;  // UTF-8
   PRInt64       mLastModifiedTime;
   nsCOMPtr<nsITimer> mUnloadTimer;
--- a/dom/plugins/ipc/PluginModuleParent.cpp
+++ b/dom/plugins/ipc/PluginModuleParent.cpp
@@ -36,18 +36,16 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef MOZ_WIDGET_GTK2
 #include <glib.h>
 #elif XP_MACOSX
 #include "PluginInterposeOSX.h"
 #include "PluginUtilsOSX.h"
-#include "nsIPrefService.h"
-#include "nsIPrefBranch.h"
 #endif
 #ifdef MOZ_WIDGET_QT
 #include <QtCore/QCoreApplication>
 #include <QtCore/QEventLoop>
 #endif
 
 #include "base/process_util.h"
 
@@ -1158,25 +1156,18 @@ PluginModuleParent::RecvPopCursor()
 #endif
 }
 
 bool
 PluginModuleParent::RecvGetNativeCursorsSupported(bool* supported)
 {
     PLUGIN_LOG_DEBUG(("%s", FULLFUNCTION));
 #if defined(XP_MACOSX)
-    bool nativeCursorsSupported = false;
-    nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-    if (prefs) {
-      if (NS_FAILED(prefs->GetBoolPref("dom.ipc.plugins.nativeCursorSupport",
-          &nativeCursorsSupported))) {
-        nativeCursorsSupported = false;
-      }
-    }
-    *supported = nativeCursorsSupported;
+    *supported =
+      Preferences::GetBool("dom.ipc.plugins.nativeCursorSupport", false);
     return true;
 #else
     NS_NOTREACHED(
         "PluginInstanceParent::RecvGetNativeCursorSupportLevel not implemented!");
     return false;
 #endif
 }
 
--- a/dom/power/PowerManager.cpp
+++ b/dom/power/PowerManager.cpp
@@ -30,16 +30,17 @@
  * 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 "mozilla/Hal.h"
 #include "PowerManager.h"
 #include "WakeLock.h"
 #include "nsContentUtils.h"
 #include "nsDOMClassInfoID.h"
 #include "nsIDOMWakeLockListener.h"
 #include "nsIPowerManagerService.h"
 #include "nsIPrincipal.h"
 #include "nsPIDOMWindow.h"
@@ -82,97 +83,92 @@ PowerManager::Shutdown()
     do_GetService(POWERMANAGERSERVICE_CONTRACTID);
   NS_ENSURE_STATE(pmService);
 
   // Remove ourself from the global notification list.
   pmService->RemoveWakeLockListener(this);
   return NS_OK;
 }
 
-nsresult
+bool
 PowerManager::CheckPermission()
 {
   if (nsContentUtils::IsCallerChrome()) {
-    return NS_OK;
+    return true;
   }
 
   nsCOMPtr<nsPIDOMWindow> win = do_QueryReferent(mWindow);
-  NS_ENSURE_STATE(win);
+  NS_ENSURE_TRUE(win, false);
   nsCOMPtr<nsIDocument> doc = do_QueryInterface(win->GetExtantDocument());
-  NS_ENSURE_STATE(doc);
+  NS_ENSURE_TRUE(doc, false);
 
   nsCOMPtr<nsIURI> uri;
   doc->NodePrincipal()->GetURI(getter_AddRefs(uri));
 
   if (!nsContentUtils::URIIsChromeOrInPref(uri, "dom.power.whitelist")) {
-    return NS_ERROR_DOM_SECURITY_ERR;
+    return false;
   }
 
-  return NS_OK;
+  return true;
 }
 
 NS_IMETHODIMP
 PowerManager::Reboot()
 {
-  nsresult rv = CheckPermission();
-  NS_ENSURE_SUCCESS(rv, rv);
+  NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
 
   nsCOMPtr<nsIPowerManagerService> pmService =
     do_GetService(POWERMANAGERSERVICE_CONTRACTID);
   NS_ENSURE_STATE(pmService);
 
   pmService->Reboot();
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 PowerManager::PowerOff()
 {
-  nsresult rv = CheckPermission();
-  NS_ENSURE_SUCCESS(rv, rv);
+  NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
 
   nsCOMPtr<nsIPowerManagerService> pmService =
     do_GetService(POWERMANAGERSERVICE_CONTRACTID);
   NS_ENSURE_STATE(pmService);
 
   pmService->PowerOff();
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 PowerManager::AddWakeLockListener(nsIDOMMozWakeLockListener *aListener)
 {
-  nsresult rv = CheckPermission();
-  NS_ENSURE_SUCCESS(rv, rv);
+  NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
 
   // already added? bail out.
   if (mListeners.Contains(aListener))
     return NS_OK;
 
   mListeners.AppendElement(aListener);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 PowerManager::RemoveWakeLockListener(nsIDOMMozWakeLockListener *aListener)
 {
-  nsresult rv = CheckPermission();
-  NS_ENSURE_SUCCESS(rv, rv);
+  NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
 
   mListeners.RemoveElement(aListener);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 PowerManager::GetWakeLockState(const nsAString &aTopic, nsAString &aState)
 {
-  nsresult rv = CheckPermission();
-  NS_ENSURE_SUCCESS(rv, rv);
+  NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
 
   nsCOMPtr<nsIPowerManagerService> pmService =
     do_GetService(POWERMANAGERSERVICE_CONTRACTID);
   NS_ENSURE_STATE(pmService);
 
   return pmService->GetWakeLockState(aTopic, aState);
 }
 
@@ -190,11 +186,56 @@ PowerManager::Callback(const nsAString &
   nsAutoTArray<nsCOMPtr<nsIDOMMozWakeLockListener>, 2> listeners(mListeners);
   for (PRUint32 i = 0; i < listeners.Length(); ++i) {
     listeners[i]->Callback(aTopic, aState);
   }
 
   return NS_OK;
 }
 
+NS_IMETHODIMP
+PowerManager::GetScreenEnabled(bool *aEnabled)
+{
+  if (!CheckPermission()) {
+    *aEnabled = true;
+    return NS_OK;
+  }
+
+  *aEnabled = hal::GetScreenEnabled();
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+PowerManager::SetScreenEnabled(bool aEnabled)
+{
+  NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
+
+  // TODO bug 707589: When the screen's state changes, all visible windows
+  // should fire a visibility change event.
+  hal::SetScreenEnabled(aEnabled);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+PowerManager::GetScreenBrightness(double *aBrightness)
+{
+  if (!CheckPermission()) {
+    *aBrightness = 1;
+    return NS_OK;
+  }
+
+  *aBrightness = hal::GetScreenBrightness();
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+PowerManager::SetScreenBrightness(double aBrightness)
+{
+  NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
+
+  NS_ENSURE_TRUE(0 <= aBrightness && aBrightness <= 1, NS_ERROR_INVALID_ARG);
+  hal::SetScreenBrightness(aBrightness);
+  return NS_OK;
+}
+
 } // power
 } // dom
 } // mozilla
--- a/dom/power/PowerManager.h
+++ b/dom/power/PowerManager.h
@@ -59,17 +59,17 @@ public:
 
   PowerManager() {};
   virtual ~PowerManager() {};
 
   nsresult Init(nsIDOMWindow *aWindow);
   nsresult Shutdown();
 
 private:
-  nsresult CheckPermission();
+  bool CheckPermission();
 
   nsWeakPtr mWindow;
   nsTArray<nsCOMPtr<nsIDOMMozWakeLockListener> > mListeners;
 };
 
 } // namespace power
 } // namespace dom
 } // namespace mozilla
--- a/dom/power/nsIDOMPowerManager.idl
+++ b/dom/power/nsIDOMPowerManager.idl
@@ -37,17 +37,17 @@
 
 #include "nsISupports.idl"
 
 interface nsIDOMMozWakeLockListener;
 
 /**
  * This interface implements navigator.mozPower
  */
-[scriptable, uuid(abf4b2b1-139d-4eff-998d-8f24616910ae)]
+[scriptable, uuid(4586bed1-cf78-4436-b503-88277d645b68)]
 interface nsIDOMMozPowerManager : nsISupports
 {
     void    powerOff();
     void    reboot();
 
     /**
      * The listeners are notified when a resource changes its lock state to:
      *  - unlocked
@@ -68,9 +68,32 @@ interface nsIDOMMozPowerManager : nsISup
      *    and it is visible.
      *
      *  - "locked-background" - at least one window holds the wake lock,
      *    but all of them are hidden.
      *
      * @param aTopic The resource name related to the wake lock.
      */
     DOMString getWakeLockState(in DOMString aTopic);
+
+    /**
+     * Is the device's screen currently enabled?  This attribute controls the
+     * device's screen, so setting it to false will turn off the screen.
+     */
+    attribute boolean screenEnabled;
+
+    /**
+     * How bright is the screen's backlight, on a scale from 0 (very dim) to 1
+     * (full brightness)?  Setting this attribute modifies the screen's
+     * brightness.
+     *
+     * You can read and write this attribute even when the screen is disabled,
+     * but the backlight is off while the screen is disabled.
+     *
+     * If you write a value of X into this attribute, the attribute may not have
+     * the same value X when you later read it.  Most screens don't support as
+     * many different brightness levels as there are doubles between 0 and 1, so
+     * we may reduce the value's precision before storing it.
+     *
+     * @throw NS_ERROR_INVALID_ARG if brightness is not in the range [0, 1].
+     */
+    attribute double screenBrightness;
 };
--- a/dom/src/geolocation/nsGeolocation.cpp
+++ b/dom/src/geolocation/nsGeolocation.cpp
@@ -61,18 +61,16 @@
 #include "nsComponentManagerUtils.h"
 #include "nsICategoryManager.h"
 #include "nsISupportsPrimitives.h"
 #include "nsServiceManagerUtils.h"
 #include "nsContentUtils.h"
 #include "nsIURI.h"
 #include "nsIPermissionManager.h"
 #include "nsIObserverService.h"
-#include "nsIPrefService.h"
-#include "nsIPrefBranch.h"
 #include "nsIJSContextStack.h"
 #include "nsThreadUtils.h"
 #include "mozilla/Services.h"
 #include "mozilla/unused.h"
 #include "mozilla/Preferences.h"
 
 #include <math.h>
 
--- a/dom/src/storage/nsDOMStorage.cpp
+++ b/dom/src/storage/nsDOMStorage.cpp
@@ -56,17 +56,16 @@ using mozilla::dom::StorageChild;
 #include "nsEscape.h"
 #include "nsContentUtils.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIPrincipal.h"
 #include "nsIURI.h"
 #include "nsReadableUtils.h"
 #include "nsIObserverService.h"
 #include "nsNetUtil.h"
-#include "nsIPrefBranch.h"
 #include "nsICookiePermission.h"
 #include "nsIPermission.h"
 #include "nsIPermissionManager.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsIOfflineCacheUpdate.h"
 #include "nsIJSContextStack.h"
 #include "nsIPrivateBrowsingService.h"
 #include "nsDOMString.h"
--- a/dom/system/nsDeviceSensors.cpp
+++ b/dom/system/nsDeviceSensors.cpp
@@ -43,17 +43,18 @@
 #include "nsIDOMEvent.h"
 #include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIServiceManager.h"
 #include "nsIPrivateDOMEvent.h"
 #include "nsIServiceManager.h"
-#include "nsIPrefService.h"
+
+#include "mozilla/Preferences.h"
 
 using namespace mozilla;
 using namespace hal;
 
 // also see sDefaultSensorHint in mobile/android/base/GeckoAppShell.java
 #define DEFAULT_SENSOR_POLL 100
 
 static const nsTArray<nsIDOMWindow*>::index_type NoIndex =
@@ -117,27 +118,19 @@ NS_IMETHODIMP nsDeviceSensorData::GetZ(d
   NS_ENSURE_ARG_POINTER(aZ);
   *aZ = mZ;
   return NS_OK;
 }
 
 NS_IMPL_ISUPPORTS1(nsDeviceSensors, nsIDeviceSensors)
 
 nsDeviceSensors::nsDeviceSensors()
-: mEnabled(true)
 {
   mLastDOMMotionEventTime = TimeStamp::Now();
-
-  nsCOMPtr<nsIPrefBranch> prefSrv = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  if (prefSrv) {
-    bool bvalue;
-    nsresult rv = prefSrv->GetBoolPref("device.motion.enabled", &bvalue);
-    if (NS_SUCCEEDED(rv) && bvalue == false)
-      mEnabled = false;
-  }
+  mEnabled = Preferences::GetBool("device.motion.enabled", true);
 
   for (int i = 0; i < NUM_SENSOR_TYPE; i++) {
     nsTArray<nsIDOMWindow*> *windows = new nsTArray<nsIDOMWindow*>();
     mWindowListeners.AppendElement(windows);
   }
 
   mLastDOMMotionEventTime = TimeStamp::Now();
 }
--- a/dom/system/unix/MaemoLocationProvider.cpp
+++ b/dom/system/unix/MaemoLocationProvider.cpp
@@ -36,20 +36,21 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include <stdio.h>
 #include <math.h>
 #include "nsGeoPosition.h"
 #include "MaemoLocationProvider.h"
 #include "nsIClassInfo.h"
 #include "nsDOMClassInfoID.h"
-#include "nsIPrefService.h"
-#include "nsIPrefBranch.h"
 #include "nsIServiceManager.h"
 #include "nsServiceManagerUtils.h"
+#include "mozilla/Preferences.h"
+
+using namespace mozilla;
 
 NS_IMPL_ISUPPORTS2(MaemoLocationProvider, nsIGeolocationProvider, nsITimerCallback)
 
 MaemoLocationProvider::MaemoLocationProvider() :
   mLocationChanged(0),
   mControlError(0),
   mDeviceDisconnected(0),
   mControlStopped(0),
@@ -187,41 +188,41 @@ MaemoLocationProvider::StartDevice()
                                          G_CALLBACK(DeviceDisconnected), this);
   return NS_OK;
 }
 
 NS_IMETHODIMP MaemoLocationProvider::Startup()
 {
   nsresult rv(NS_OK);
 
-  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  if (!prefs)
-    return NS_ERROR_FAILURE;
-
   rv = StartControl();
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = StartDevice();
   NS_ENSURE_SUCCESS(rv, rv);
 
-  prefs->GetBoolPref("geo.herror.ignore.big", &mIgnoreBigHErr);
+  mIgnoreBigHErr =
+    Preferences::GetBool("geo.herror.ignore.big", mIgnoreBigHErr);
 
-  if (mIgnoreBigHErr)
-    prefs->GetIntPref("geo.herror.max.value", &mMaxHErr);
+  if (mIgnoreBigHErr) {
+    mMaxHErr = Preferences::GetInt("geo.herror.max.value", mMaxHErr);
+  }
 
-  prefs->GetBoolPref("geo.verror.ignore.big", &mIgnoreBigVErr);
+  mIgnoreBigVErr =
+    Preferences::GetBool("geo.verror.ignore.big", mIgnoreBigVErr);
 
-  if (mIgnoreBigVErr)
-    prefs->GetIntPref("geo.verror.max.value", &mMaxVErr);
+  if (mIgnoreBigVErr) {
+    mMaxVErr = Preferences::GetInt("geo.verror.max.value", mMaxVErr);
+  }
 
   if (mUpdateTimer)
     return NS_OK;
 
-  PRInt32 update = 0; //0 second no timer created
-  prefs->GetIntPref("geo.default.update", &update);
+  // 0 second no timer created
+  PRInt32 update = Preferences::GetInt("geo.default.update", 0);
 
   if (!update)
     return NS_OK;
 
   mUpdateTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
 
   if (NS_FAILED(rv))
     return NS_ERROR_FAILURE;
--- a/dom/workers/test/extensions/bootstrap/Makefile.in
+++ b/dom/workers/test/extensions/bootstrap/Makefile.in
@@ -47,13 +47,14 @@ XPI_NAME = workerbootstrap
 DIST_FILES = \
   bootstrap.js \
   install.rdf \
   worker.js \
   $(NULL)
 
 TEST_EXTENSIONS_DIR = $(DEPTH)/_tests/testing/mochitest/extensions
 
+GENERATED_DIRS = $(TEST_EXTENSIONS_DIR)
+
 include $(topsrcdir)/config/rules.mk
 
 libs::
-	$(MKDIR) -p $(TEST_EXTENSIONS_DIR)
 	@(cd $(DIST)/xpi-stage && tar $(TAR_CREATE_FLAGS) - $(XPI_NAME)) | (cd $(TEST_EXTENSIONS_DIR) && tar -xf -)
--- a/dom/workers/test/extensions/traditional/Makefile.in
+++ b/dom/workers/test/extensions/traditional/Makefile.in
@@ -56,13 +56,14 @@ EXTRA_COMPONENTS = \
 
 DIST_FILES = \
   install.rdf \
   worker.js \
   $(NULL)
 
 TEST_EXTENSIONS_DIR = $(DEPTH)/_tests/testing/mochitest/extensions
 
+GENERATED_DIRS = $(TEST_EXTENSIONS_DIR)
+
 include $(topsrcdir)/config/rules.mk
 
 libs::
-	$(MKDIR) -p $(TEST_EXTENSIONS_DIR)
 	@(cd $(DIST)/xpi-stage && tar $(TAR_CREATE_FLAGS) - $(XPI_NAME)) | (cd $(TEST_EXTENSIONS_DIR) && tar -xf -)
--- a/dom/workers/test/test_errorPropagation.html
+++ b/dom/workers/test/test_errorPropagation.html
@@ -11,17 +11,17 @@
     <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
   </head>
   <body>
     <iframe id="workerFrame" src="errorPropagation_iframe.html"
             onload="workerFrameLoaded();"></iframe>
     <script type="text/javascript">
       const workerCount = 3;
 
-      const errorMessage = "expectedError";
+      const errorMessage = "Error: expectedError";
       const errorFilename = "http://mochi.test:8888/tests/dom/workers/test/" +
                             "errorPropagation_worker.js";
       const errorLineno = 48;
 
       var workerFrame;
 
       scopeErrorCount = 0;
       workerErrorCount = 0;
--- a/dom/workers/test/test_newError.html
+++ b/dom/workers/test/test_newError.html
@@ -15,17 +15,17 @@
   var worker = new Worker("newError_worker.js");
 
   worker.onmessage = function(event) {
     ok(false, "Shouldn't get a message!");
     SimpleTest.finish();
   }
 
   worker.onerror = function(event) {
-    is(event.message, "foo!", "Got wrong error message!");
+    is(event.message, "Error: foo!", "Got wrong error message!");
     event.preventDefault();
     SimpleTest.finish();
   }
 
   SimpleTest.waitForExplicitFinish();
 
 </script>
 </pre>
--- a/dom/workers/test/test_recursiveOnerror.html
+++ b/dom/workers/test/test_recursiveOnerror.html
@@ -9,18 +9,18 @@
     </script>
     <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
   </head>
   <body>
     <script type="text/javascript">
       const filename = "http://mochi.test:8888/tests/dom/workers/test/" +
                        "recursiveOnerror_worker.js";
       const errors = [
-        { message: "2", lineno: 6 },
-        { message: "1", lineno: 10 }
+        { message: "Error: 2", lineno: 6 },
+        { message: "Error: 1", lineno: 10 }
       ]
 
       var errorCount = 0;
 
       var worker = new Worker("recursiveOnerror_worker.js");
       worker.postMessage("go");
 
       worker.onerror = function(event) {
--- a/editor/composer/src/nsComposerDocumentCommands.cpp
+++ b/editor/composer/src/nsComposerDocumentCommands.cpp
@@ -58,16 +58,17 @@
 #include "nsCOMPtr.h"
 
 #include "nsComposerCommands.h"
 #include "nsICommandParams.h"
 #include "nsCRT.h"
 
 //defines
 #define STATE_ENABLED  "state_enabled"
+#define STATE_ALL "state_all"
 #define STATE_ATTRIBUTE "state_attribute"
 #define STATE_DATA "state_data"
 
 static
 nsresult
 GetPresContextFromEditor(nsIEditor *aEditor, nsPresContext **aResult)
 {
   NS_ENSURE_ARG_POINTER(aResult);
@@ -373,17 +374,17 @@ nsSetDocumentStateCommand::GetCommandSta
   if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentUseCSS"))
   {
     NS_ENSURE_ARG_POINTER(aParams);
     nsCOMPtr<nsIHTMLEditor> htmleditor = do_QueryInterface(refCon);
     NS_ENSURE_TRUE(htmleditor, NS_ERROR_INVALID_ARG);
 
     bool isCSS;
     htmleditor->GetIsCSSEnabled(&isCSS);
-    return aParams->SetBooleanValue(STATE_ATTRIBUTE, isCSS);
+    return aParams->SetBooleanValue(STATE_ALL, isCSS);
   }
 
   if (!nsCRT::strcmp(aCommandName, "cmd_insertBrOnReturn"))
   {
     NS_ENSURE_ARG_POINTER(aParams);
     nsCOMPtr<nsIHTMLEditor> htmleditor = do_QueryInterface(refCon);
     NS_ENSURE_TRUE(htmleditor, NS_ERROR_INVALID_ARG);
 
--- a/editor/composer/test/Makefile.in
+++ b/editor/composer/test/Makefile.in
@@ -45,16 +45,17 @@ include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES = \
 		test_bug348497.html \
 		test_bug384147.html \
 		test_bug389350.html \
 		test_bug519928.html \
 		bug678842_subframe.html \
+		test_bug738440.html \
 		$(NULL)
 
 _CHROME_TEST_FILES = \
 		test_bug434998.xul \
 		test_bug338427.html \
 		test_bug678842.html \
 		$(NULL)
 
new file mode 100644
--- /dev/null
+++ b/editor/composer/test/test_bug738440.html
@@ -0,0 +1,37 @@
+<!doctype html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=738440
+-->
+<title>Test for Bug 738440</title>
+<script src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" href="/tests/SimpleTest/test.css" />
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=738440">Mozilla Bug 738440</a>
+<div contenteditable></div>
+<script>
+
+/** Test for Bug 738440 **/
+document.execCommand("stylewithcss", false, "true");
+is(document.queryCommandState("stylewithcss"), true,
+   "setting stylewithcss to true should cause its state to be true");
+is(document.queryCommandState("usecss"), false,
+   "usecss state should always be false");
+
+document.execCommand("stylewithcss", false, "false");
+is(document.queryCommandState("stylewithcss"), false,
+   "setting stylewithcss to false should cause its state to be false");
+is(document.queryCommandState("usecss"), false,
+   "usecss state should always be false");
+
+document.execCommand("usecss", false, "true");
+is(document.queryCommandState("stylewithcss"), false,
+   "setting usecss to true should cause stylewithcss state to be false");
+is(document.queryCommandState("usecss"), false,
+   "usecss state should always be false");
+
+document.execCommand("usecss", false, "false");
+is(document.queryCommandState("stylewithcss"), true,
+   "setting usecss to false should cause stylewithcss state to be true");
+is(document.queryCommandState("usecss"), false,
+   "usecss state should always be false");
+
+</script>
--- a/editor/libeditor/base/crashtests/633709.xhtml
+++ b/editor/libeditor/base/crashtests/633709.xhtml
@@ -4,22 +4,32 @@
 
 <script id="s">
 <![CDATA[
 
 function boom()
 {
   document.getElementById("i").focus();
 
+  try { document.execCommand("stylewithcss", false, "true") } catch(e) { }
   try { document.execCommand("inserthtml", false, "<x>X</x>"); } catch(e) { }
   try { document.execCommand("underline", false, null); } catch(e) { }
   try { document.execCommand("justifyfull", false, null); } catch(e) { }
   try { document.execCommand("underline", false, null); } catch(e) { }
   try { document.execCommand("insertParagraph", false, null); } catch(e) { }
   try { document.execCommand("delete", false, null); } catch(e) { }
+
+  try { document.execCommand("stylewithcss", false, "false") } catch(e) { }
+  try { document.execCommand("inserthtml", false, "<x>X</x>"); } catch(e) { }
+  try { document.execCommand("underline", false, null); } catch(e) { }
+  try { document.execCommand("justifyfull", false, null); } catch(e) { }
+  try { document.execCommand("underline", false, null); } catch(e) { }
+  try { document.execCommand("insertParagraph", false, null); } catch(e) { }
+  try { document.execCommand("delete", false, null); } catch(e) { }
+
   document.documentElement.removeAttribute("class");
 }
 
 setTimeout(boom, 10);
 
 ]]>
 </script>
 
--- a/editor/libeditor/base/crashtests/crashtests.list
+++ b/editor/libeditor/base/crashtests/crashtests.list
@@ -1,12 +1,12 @@
 load 336104.html
 load 382527-1.html
 load 402172-1.html
 load 407079-1.html
 load 407256-1.html
 load 430624-1.html
 load 459613.html
 load 475132-1.xhtml
-asserts-if(!Android,1) load 633709.xhtml # Bug 695364
+asserts-if(!Android,2) load 633709.xhtml # Bug 695364 and bug 671153
 asserts-if(!Android,6) load 636074-1.html # Bug 439258, charged to the wrong test due to bug 635550
 load 713427-1.html
 load 713427-2.xhtml
--- a/editor/libeditor/html/nsHTMLCSSUtils.cpp
+++ b/editor/libeditor/html/nsHTMLCSSUtils.cpp
@@ -294,17 +294,17 @@ const nsHTMLCSSUtils::CSSEquivTable tabl
 const nsHTMLCSSUtils::CSSEquivTable hrAlignEquivTable[] = {
   { nsHTMLCSSUtils::eCSSEditableProperty_margin_left, ProcessMarginLeftValue, nsnull, nsnull, nsnull, true, false },
   { nsHTMLCSSUtils::eCSSEditableProperty_margin_right, ProcessMarginRightValue, nsnull, nsnull, nsnull, true, false },
   { nsHTMLCSSUtils::eCSSEditableProperty_NONE, 0 }
 };
 
 nsHTMLCSSUtils::nsHTMLCSSUtils(nsHTMLEditor* aEditor)
   : mHTMLEditor(aEditor)
-  , mIsCSSPrefChecked(false)
+  , mIsCSSPrefChecked(true)
 {
   // let's retrieve the value of the "CSS editing" pref
   mIsCSSPrefChecked = Preferences::GetBool("editor.use_css", mIsCSSPrefChecked);
 }
 
 nsHTMLCSSUtils::~nsHTMLCSSUtils()
 {
 }
--- a/editor/libeditor/html/nsHTMLDataTransfer.cpp
+++ b/editor/libeditor/html/nsHTMLDataTransfer.cpp
@@ -1619,16 +1619,19 @@ NS_IMETHODIMP nsHTMLEditor::PasteTransfe
                                 nsnull, 0, true);
 }
 
 // 
 // HTML PasteNoFormatting. Ignore any HTML styles and formating in paste source
 //
 NS_IMETHODIMP nsHTMLEditor::PasteNoFormatting(PRInt32 aSelectionType)
 {
+  if (!FireClipboardEvent(NS_PASTE))
+    return NS_OK;
+
   ForceCompositionEnd();
 
   // Get Clipboard Service
   nsresult rv;
   nsCOMPtr<nsIClipboard> clipboard(do_GetService("@mozilla.org/widget/clipboard;1", &rv));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Get the nsITransferable interface for getting the data from the clipboard.
--- a/editor/libeditor/html/tests/Makefile.in
+++ b/editor/libeditor/html/tests/Makefile.in
@@ -97,16 +97,17 @@ include $(topsrcdir)/config/rules.mk
 		test_CF_HTML_clipboard.html \
 		test_contenteditable_focus.html \
 		test_dom_input_event_on_htmleditor.html \
 		test_htmleditor_keyevent_handling.html \
 		test_keypress_untrusted_event.html \
 		test_select_all_without_body.html \
 		file_select_all_without_body.html \
 		test_root_element_replacement.html \
+		test_bug738366.html \
 		$(NULL)
 
 ifneq (mobile,$(MOZ_BUILD_APP))
 _TEST_FILES +=  test_spellcheck_pref.html \
 		$(NULL)
 endif
 
 _DATA_FILES = \
--- a/editor/libeditor/html/tests/test_bug290026.html
+++ b/editor/libeditor/html/tests/test_bug290026.html
@@ -20,17 +20,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 /** Test for Bug 290026 **/
 SimpleTest.waitForExplicitFinish();
 
 var editor = document.getElementById("editor");
 editor.innerHTML = '<p></p><ul><li>Item 1</li><li>Item 2</li></ul><p></p>';
 editor.focus();
 
 addLoadEvent(function() {
-
+  document.execCommand("stylewithcss", false, "true");
   var sel = window.getSelection();
   sel.removeAllRanges();
   var lis = document.getElementsByTagName("li");
   var range = document.createRange();
   range.setStart(lis[0], 0);
   range.setEnd(lis[1], lis[1].childNodes.length);
   sel.addRange(range);
   document.execCommand("indent", false, false);
--- a/editor/libeditor/html/tests/test_bug410986.html
+++ b/editor/libeditor/html/tests/test_bug410986.html
@@ -16,46 +16,53 @@ https://bugzilla.mozilla.org/show_bug.cg
   <div id="contents"><span style="color: green;">green text</span></div>
   <div id="editor" contenteditable="true"></div>
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 410986 **/
 
+var gPasteEvents = 0;
+document.getElementById("editor").addEventListener("paste", function() {
+  ++gPasteEvents;
+}, false);
+
 SimpleTest.waitForExplicitFinish();
 SimpleTest.waitForFocus(function() {
   getSelection().selectAllChildren(document.getElementById("contents"));
   SimpleTest.waitForClipboard("green text",
     function() {
       synthesizeKey("C", {accelKey: true});
     },
     function() {
       var ed = document.getElementById("editor");
       ed.focus();
       if (navigator.platform.indexOf("Mac") >= 0) {
         synthesizeKey("V", {accelKey: true, shiftKey: true, altKey: true});
       } else {
         synthesizeKey("V", {accelKey: true, shiftKey: true});
       }
       is(ed.innerHTML, "green text", "Content should be pasted in plaintext format");
+      is(gPasteEvents, 1, "One paste event must be fired");
 
       ed.innerHTML = "";
       ed.blur();
       getSelection().selectAllChildren(document.getElementById("contents"));
       SimpleTest.waitForClipboard("green text",
         function() {
           synthesizeKey("C", {accelKey: true});
         },
         function() {
           var ed = document.getElementById("editor");
           ed.focus();
           synthesizeKey("V", {accelKey: true});
           isnot(ed.innerHTML.indexOf("<span style=\"color: green;\">green text</span>"), -1,
                 "Content should be pasted in HTML format");
+          is(gPasteEvents, 2, "Two paste events must be fired");
 
           SimpleTest.finish();
         },
         function() {
           ok(false, "Failed to copy the second item to the clipboard");
           SimpleTest.finish();
         }
       );
--- a/editor/libeditor/html/tests/test_bug442186.html
+++ b/editor/libeditor/html/tests/test_bug442186.html
@@ -49,16 +49,18 @@ function justify(textNode, pos) {
   range.setEnd(textNode, pos);
   sel.addRange(range);
 
   // align
   document.execCommand("justifyright", false, null);
 }
 
 function runTests() {
+  document.execCommand("stylewithcss", false, "true");
+
   const test1 = document.getElementById("test1");
   const test2 = document.getElementById("test2");
   const test3 = document.getElementById("test3");
 
   // #test1: two <div> containers
   const line1 = test1.querySelector("div").firstChild;
   test1.focus();
   justify(line1);
new file mode 100644
--- /dev/null
+++ b/editor/libeditor/html/tests/test_bug738366.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=738366
+-->
+<title>Test for Bug 738366</title>
+<script src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" href="/tests/SimpleTest/test.css"/>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=738366">Mozilla Bug 738366</a>
+<div id="display" contenteditable>foobarbaz</div>
+<script>
+/** Test for Bug 738366 **/
+
+getSelection().collapse(document.getElementById("display").firstChild, 3);
+getSelection().extend(document.getElementById("display").firstChild, 6);
+document.execCommand("bold");
+is(document.getElementById("display").innerHTML, "foo<b>bar</b>baz",
+   "styleWithCSS must default to false");
+document.execCommand("stylewithcss", false, "true");
+document.execCommand("bold");
+document.execCommand("bold");
+is(document.getElementById("display").innerHTML,
+   'foo<span style="font-weight: bold;">bar</span>baz',
+   "styleWithCSS must be settable to true");
+</script>
--- a/editor/libeditor/html/tests/test_htmleditor_keyevent_handling.html
+++ b/editor/libeditor/html/tests/test_htmleditor_keyevent_handling.html
@@ -26,16 +26,17 @@ SimpleTest.waitForFocus(runTests, window
 var htmlEditor = document.getElementById("htmlEditor");
 
 const kIsMac = navigator.platform.indexOf("Mac") == 0;
 const kIsWin = navigator.platform.indexOf("Win") == 0;
 const kIsLinux = navigator.platform.indexOf("Linux") == 0 || navigator.platform.indexOf("SunOS") == 0 ;
 
 function runTests()
 {
+  document.execCommand("stylewithcss", false, "true");
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
   var fm = Components.classes["@mozilla.org/focus-manager;1"].
     getService(Components.interfaces.nsIFocusManager);
 
   var capturingPhase = { fired: false, prevented: false };
   var bubblingPhase = { fired: false, prevented: false };
 
--- a/gfx/2d/2D.h
+++ b/gfx/2d/2D.h
@@ -824,16 +824,21 @@ public:
    * surface.
    */
   static TemporaryRef<DataSourceSurface>
     CreateDataSourceSurfaceFromData(unsigned char *aData, int32_t aStride,
                                     const IntSize &aSize, SurfaceFormat aFormat);
 
 #ifdef WIN32
   static TemporaryRef<DrawTarget> CreateDrawTargetForD3D10Texture(ID3D10Texture2D *aTexture, SurfaceFormat aFormat);
+  static TemporaryRef<DrawTarget>
+    CreateDualDrawTargetForD3D10Textures(ID3D10Texture2D *aTextureA,
+                                         ID3D10Texture2D *aTextureB,
+                                         SurfaceFormat aFormat);
+
   static void SetDirect3D10Device(ID3D10Device1 *aDevice);
   static ID3D10Device1 *GetDirect3D10Device();
 
   static TemporaryRef<GlyphRenderingOptions>
     CreateDWriteGlyphRenderingOptions(IDWriteRenderingParams *aParams);
 
 private:
   static ID3D10Device1 *mD3D10Device;
new file mode 100644
--- /dev/null
+++ b/gfx/2d/DrawTargetDual.cpp
@@ -0,0 +1,213 @@
+/* -*- Mode: C++; tab-width: 20; 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 Corporation code.
+  *
+  * The Initial Developer of the Original Code is Mozilla Foundation.
+  * Portions created by the Initial Developer are Copyright (C) 2011
+  * the Initial Developer. All Rights Reserved.
+  *
+  * Contributor(s):
+  *   Bas Schouten <bschouten@mozilla.com>
+  *
+  * Alternatively, the contents of this file may be used under the terms of
+  * either the GNU General Public License Version 2 or later (the "GPL"), or
+  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+  * in which case the provisions of the GPL or the LGPL are applicable instead
+  * of those above. If you wish to allow use of your version of this file only
+  * under the terms of either the GPL or the LGPL, and not to allow others to
+  * use your version of this file under the terms of the MPL, indicate your
+  * decision by deleting the provisions above and replace them with the notice
+  * and other provisions required by the GPL or the LGPL. If you do not delete
+  * the provisions above, a recipient may use your version of this file under
+  * the terms of any one of the MPL, the GPL or the LGPL.
+  *
+  * ***** END LICENSE BLOCK ***** */
+     
+#include "DrawTargetDual.h"
+#include "Tools.h"
+
+namespace mozilla {
+namespace gfx {
+
+class DualSurface
+{
+public:
+  inline DualSurface(SourceSurface *aSurface)
+  {
+    if (aSurface->GetType() != SURFACE_DUAL_DT) {
+      mA = mB = aSurface;
+      return;
+    }
+
+    SourceSurfaceDual *ssDual =
+      static_cast<SourceSurfaceDual*>(aSurface);
+    mA = ssDual->mA;
+    mB = ssDual->mB;
+  }
+
+  SourceSurface *mA;
+  SourceSurface *mB;
+};
+
+/* This only needs to split patterns up for SurfacePatterns. Only in that
+ * case can we be dealing with a 'dual' source (SourceSurfaceDual) and do
+ * we need to pass separate patterns into our destination DrawTargets.
+ */
+class DualPattern
+{
+public:
+  inline DualPattern(const Pattern &aPattern)
+    : mPatternsInitialized(false)
+  {
+    if (aPattern.GetType() != PATTERN_SURFACE) {
+      mA = mB = &aPattern;
+      return;
+    }
+
+    const SurfacePattern *surfPat =
+      static_cast<const SurfacePattern*>(&aPattern);
+
+    if (surfPat->mSurface->GetType() != SURFACE_DUAL_DT) {
+      mA = mB = &aPattern;
+      return;
+    }
+
+    const SourceSurfaceDual *ssDual =
+      static_cast<const SourceSurfaceDual*>(surfPat->mSurface.get());
+    mA = new (mSurfPatA.addr()) SurfacePattern(ssDual->mA, surfPat->mExtendMode,
+                                               surfPat->mMatrix, surfPat->mFilter);
+    mB = new (mSurfPatB.addr()) SurfacePattern(ssDual->mB, surfPat->mExtendMode,
+                                               surfPat->mMatrix, surfPat->mFilter);
+    mPatternsInitialized = true;
+  }
+
+  inline ~DualPattern()
+  {
+    if (mPatternsInitialized) {
+      mA->~Pattern();
+      mB->~Pattern();
+    }
+  }
+
+  ClassStorage<SurfacePattern> mSurfPatA;
+  ClassStorage<SurfacePattern> mSurfPatB;
+
+  const Pattern *mA;
+  const Pattern *mB;
+
+  bool mPatternsInitialized;
+};
+
+void
+DrawTargetDual::DrawSurface(SourceSurface *aSurface, const Rect &aDest, const Rect &aSource,
+                            const DrawSurfaceOptions &aSurfOptions, const DrawOptions &aOptions)
+{
+  DualSurface surface(aSurface);
+  mA->DrawSurface(surface.mA, aDest, aSource, aSurfOptions, aOptions);
+  mB->DrawSurface(surface.mB, aDest, aSource, aSurfOptions, aOptions);
+}
+
+void
+DrawTargetDual::DrawSurfaceWithShadow(SourceSurface *aSurface, const Point &aDest,
+                                      const Color &aColor, const Point &aOffset,
+                                      Float aSigma, CompositionOp aOp)
+{
+  DualSurface surface(aSurface);
+  mA->DrawSurfaceWithShadow(surface.mA, aDest, aColor, aOffset, aSigma, aOp);
+  mB->DrawSurfaceWithShadow(surface.mB, aDest, aColor, aOffset, aSigma, aOp);
+}
+
+void
+DrawTargetDual::CopySurface(SourceSurface *aSurface, const IntRect &aSourceRect,
+                            const IntPoint &aDestination)
+{
+  DualSurface surface(aSurface);
+  mA->CopySurface(surface.mA, aSourceRect, aDestination);
+  mB->CopySurface(surface.mB, aSourceRect, aDestination);
+}
+
+void
+DrawTargetDual::FillRect(const Rect &aRect, const Pattern &aPattern, const DrawOptions &aOptions)
+{
+  DualPattern pattern(aPattern);
+  mA->FillRect(aRect, *pattern.mA, aOptions);
+  mB->FillRect(aRect, *pattern.mB, aOptions);
+}
+
+void
+DrawTargetDual::StrokeRect(const Rect &aRect, const Pattern &aPattern,
+                           const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions)
+{
+  DualPattern pattern(aPattern);
+  mA->StrokeRect(aRect, *pattern.mA, aStrokeOptions, aOptions);
+  mB->StrokeRect(aRect, *pattern.mB, aStrokeOptions, aOptions);
+}
+
+void
+DrawTargetDual::StrokeLine(const Point &aStart, const Point &aEnd, const Pattern &aPattern,
+                           const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions)
+{
+  DualPattern pattern(aPattern);
+  mA->StrokeLine(aStart, aEnd, *pattern.mA, aStrokeOptions, aOptions);
+  mB->StrokeLine(aStart, aEnd, *pattern.mB, aStrokeOptions, aOptions);
+}
+
+void
+DrawTargetDual::Stroke(const Path *aPath, const Pattern &aPattern,
+                       const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions)
+{
+  DualPattern pattern(aPattern);
+  mA->Stroke(aPath, *pattern.mA, aStrokeOptions, aOptions);
+  mB->Stroke(aPath, *pattern.mB, aStrokeOptions, aOptions);
+}
+
+void
+DrawTargetDual::Fill(const Path *aPath, const Pattern &aPattern, const DrawOptions &aOptions)
+{
+  DualPattern pattern(aPattern);
+  mA->Fill(aPath, *pattern.mA, aOptions);
+  mB->Fill(aPath, *pattern.mB, aOptions);
+}
+
+void
+DrawTargetDual::FillGlyphs(ScaledFont *aScaledFont, const GlyphBuffer &aBuffer,
+                           const Pattern &aPattern, const DrawOptions &aOptions,
+                           const GlyphRenderingOptions *aRenderingOptions)
+{
+  DualPattern pattern(aPattern);
+  mA->FillGlyphs(aScaledFont, aBuffer, *pattern.mA, aOptions, aRenderingOptions);
+  mB->FillGlyphs(aScaledFont, aBuffer, *pattern.mB, aOptions, aRenderingOptions);
+}
+
+void
+DrawTargetDual::Mask(const Pattern &aSource, const Pattern &aMask, const DrawOptions &aOptions)
+{
+  DualPattern source(aSource);
+  DualPattern mask(aMask);
+  mA->Mask(*source.mA, *mask.mA, aOptions);
+  mB->Mask(*source.mB, *mask.mB, aOptions);
+}
+
+TemporaryRef<DrawTarget>
+DrawTargetDual::CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const
+{
+  RefPtr<DrawTarget> dtA = mA->CreateSimilarDrawTarget(aSize, aFormat);
+  RefPtr<DrawTarget> dtB = mB->CreateSimilarDrawTarget(aSize, aFormat);
+
+  return new DrawTargetDual(dtA, dtB);
+}
+
+}
+}
new file mode 100644
--- /dev/null
+++ b/gfx/2d/DrawTargetDual.h
@@ -0,0 +1,170 @@
+/* -*- Mode: C++; tab-width: 20; 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 Corporation code.
+  *
+  * The Initial Developer of the Original Code is Mozilla Foundation.
+  * Portions created by the Initial Developer are Copyright (C) 2011
+  * the Initial Developer. All Rights Reserved.
+  *
+  * Contributor(s):
+  *   Bas Schouten <bschouten@mozilla.com>
+  *
+  * Alternatively, the contents of this file may be used under the terms of
+  * either the GNU General Public License Version 2 or later (the "GPL"), or
+  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+  * in which case the provisions of the GPL or the LGPL are applicable instead
+  * of those above. If you wish to allow use of your version of this file only
+  * under the terms of either the GPL or the LGPL, and not to allow others to
+  * use your version of this file under the terms of the MPL, indicate your
+  * decision by deleting the provisions above and replace them with the notice
+  * and other provisions required by the GPL or the LGPL. If you do not delete
+  * the provisions above, a recipient may use your version of this file under
+  * the terms of any one of the MPL, the GPL or the LGPL.
+  *
+  * ***** END LICENSE BLOCK ***** */
+     
+#ifndef MOZILLA_GFX_DRAWTARGETDUAL_H_
+#define MOZILLA_GFX_DRAWTARGETDUAL_H_
+     
+#include <vector>
+#include <sstream>
+
+#include "SourceSurfaceDual.h"
+     
+#include "2D.h"
+     
+namespace mozilla {
+namespace gfx {
+     
+#define FORWARD_FUNCTION(funcName) \
+  virtual void funcName() { mA->funcName(); mB->funcName(); }
+#define FORWARD_FUNCTION1(funcName, var1Type, var1Name) \
+  virtual void funcName(var1Type var1Name) { mA->funcName(var1Name); mB->funcName(var1Name); }
+
+/* This is a special type of DrawTarget. It duplicates all drawing calls
+ * accross two drawtargets. An exception to this is when a snapshot of another
+ * dual DrawTarget is used as the source for any surface data. In this case
+ * the snapshot of the first source DrawTarget is used as a source for the call
+ * to the first destination DrawTarget (mA) and the snapshot of the second
+ * source DrawTarget is used at the source for the second destination
+ * DrawTarget (mB). This class facilitates black-background/white-background
+ * drawing for per-component alpha extraction for backends which do not support
+ * native component alpha.
+ */
+class DrawTargetDual : public DrawTarget
+{
+public:
+  DrawTargetDual(DrawTarget *aA, DrawTarget *aB)
+    : mA(aA)
+    , mB(aB)
+  { 
+    mFormat = aA->GetFormat();
+  }
+     
+  virtual BackendType GetType() const { return mA->GetType(); }
+  virtual TemporaryRef<SourceSurface> Snapshot() { return new SourceSurfaceDual(mA, mB); }
+  virtual IntSize GetSize() { return mA->GetSize(); }
+     
+  FORWARD_FUNCTION(Flush)
+  FORWARD_FUNCTION1(PushClip, const Path *, aPath)
+  FORWARD_FUNCTION1(PushClipRect, const Rect &, aRect)
+  FORWARD_FUNCTION(PopClip)
+  FORWARD_FUNCTION1(ClearRect, const Rect &, aRect)
+
+  virtual void SetTransform(const Matrix &aTransform) {
+    mTransform = aTransform;
+    mA->SetTransform(aTransform);
+    mB->SetTransform(aTransform);
+  }
+
+  virtual void DrawSurface(SourceSurface *aSurface, const Rect &aDest, const Rect & aSource,
+                           const DrawSurfaceOptions &aSurfOptions, const DrawOptions &aOptions);
+  
+  virtual void DrawSurfaceWithShadow(SourceSurface *aSurface, const Point &aDest,
+                                     const Color &aColor, const Point &aOffset,
+                                     Float aSigma, CompositionOp aOp);
+
+  virtual void CopySurface(SourceSurface *aSurface, const IntRect &aSourceRect,
+                           const IntPoint &aDestination);
+
+  virtual void FillRect(const Rect &aRect, const Pattern &aPattern, const DrawOptions &aOptions);
+
+  virtual void StrokeRect(const Rect &aRect, const Pattern &aPattern,
+                          const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions);
+
+  virtual void StrokeLine(const Point &aStart, const Point &aEnd, const Pattern &aPattern,
+                          const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions);
+
+  virtual void Stroke(const Path *aPath, const Pattern &aPattern,
+                      const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions);
+
+  virtual void Fill(const Path *aPath, const Pattern &aPattern, const DrawOptions &aOptions);
+
+  virtual void FillGlyphs(ScaledFont *aScaledFont, const GlyphBuffer &aBuffer,
+                          const Pattern &aPattern, const DrawOptions &aOptions,
+                          const GlyphRenderingOptions *aRenderingOptions);
+  
+  virtual void Mask(const Pattern &aSource, const Pattern &aMask, const DrawOptions &aOptions);
+     
+  virtual TemporaryRef<SourceSurface>
+    CreateSourceSurfaceFromData(unsigned char *aData,
+                                const IntSize &aSize,
+                                int32_t aStride,
+                                SurfaceFormat aFormat) const
+  {
+    return mA->CreateSourceSurfaceFromData(aData, aSize, aStride, aFormat);
+  }
+     
+  virtual TemporaryRef<SourceSurface> OptimizeSourceSurface(SourceSurface *aSurface) const
+  {
+    return mA->OptimizeSourceSurface(aSurface);
+  }
+     
+  virtual TemporaryRef<SourceSurface>
+    CreateSourceSurfaceFromNativeSurface(const NativeSurface &aSurface) const
+  {
+    return mA->CreateSourceSurfaceFromNativeSurface(aSurface);
+  }
+     
+  virtual TemporaryRef<DrawTarget>
+    CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const;
+     
+  virtual TemporaryRef<PathBuilder> CreatePathBuilder(FillRule aFillRule = FILL_WINDING) const
+  {
+    return mA->CreatePathBuilder(aFillRule);
+  }
+     
+  virtual TemporaryRef<GradientStops>
+    CreateGradientStops(GradientStop *aStops,
+                        uint32_t aNumStops,
+                        ExtendMode aExtendMode = EXTEND_CLAMP) const
+  {
+    return mA->CreateGradientStops(aStops, aNumStops, aExtendMode);
+  }
+     
+  virtual void *GetNativeSurface(NativeSurfaceType aType)
+  {
+    return NULL;
+  }
+     
+private:
+  RefPtr<DrawTarget> mA;
+  RefPtr<DrawTarget> mB;
+};
+     
+}
+}
+     
+#endif /* MOZILLA_GFX_DRAWTARGETDUAL_H_ */ 
\ No newline at end of file
--- a/gfx/2d/Factory.cpp
+++ b/gfx/2d/Factory.cpp
@@ -62,16 +62,17 @@
 #endif
 
 #ifdef WIN32
 #include "DrawTargetD2D.h"
 #include "ScaledFontDWrite.h"
 #include <d3d10_1.h>
 #endif
 
+#include "DrawTargetDual.h"
 
 #include "Logging.h"
 
 #ifdef PR_LOGGING
 PRLogModuleInfo *sGFX2DLog = PR_NewLogModule("gfx2d");
 #endif
 
 namespace mozilla {
@@ -227,16 +228,42 @@ Factory::CreateDrawTargetForD3D10Texture
   }
 
   gfxWarning() << "Failed to create draw target for D3D10 texture.";
 
   // Failed
   return NULL;
 }
 
+TemporaryRef<DrawTarget>
+Factory::CreateDualDrawTargetForD3D10Textures(ID3D10Texture2D *aTextureA,
+                                              ID3D10Texture2D *aTextureB,
+                                              SurfaceFormat aFormat)
+{
+  RefPtr<DrawTargetD2D> newTargetA;
+  RefPtr<DrawTargetD2D> newTargetB;
+
+  newTargetA = new DrawTargetD2D();
+  if (!newTargetA->Init(aTextureA, aFormat)) {
+    gfxWarning() << "Failed to create draw target for D3D10 texture.";
+    return NULL;
+  }
+
+  newTargetB = new DrawTargetD2D();
+  if (!newTargetB->Init(aTextureB, aFormat)) {
+    gfxWarning() << "Failed to create draw target for D3D10 texture.";
+    return NULL;
+  }
+
+  RefPtr<DrawTarget> newTarget =
+    new DrawTargetDual(newTargetA, newTargetB);
+
+  return newTarget;
+}
+
 void
 Factory::SetDirect3D10Device(ID3D10Device1 *aDevice)
 {
   mD3D10Device = aDevice;
 }
 
 ID3D10Device1*
 Factory::GetDirect3D10Device()
--- a/gfx/2d/Makefile.in
+++ b/gfx/2d/Makefile.in
@@ -68,16 +68,17 @@ EXPORTS_mozilla/gfx	= \
 CPPSRCS	= \
 	Factory.cpp \
         Matrix.cpp \
         DrawTargetCairo.cpp \
         SourceSurfaceCairo.cpp \
         PathCairo.cpp \
         Blur.cpp \
         ScaledFontBase.cpp \
+        DrawTargetDual.cpp \
         $(NULL)
 
 ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 CPPSRCS	+= \
 	   SourceSurfaceCG.cpp \
 	   DrawTargetCG.cpp \
 	   PathCG.cpp \
 	   $(NULL)
new file mode 100644
--- /dev/null
+++ b/gfx/2d/SourceSurfaceDual.h
@@ -0,0 +1,74 @@
+/* -*- Mode: C++; tab-width: 20; 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 Corporation code.
+  *
+  * The Initial Developer of the Original Code is Mozilla Foundation.
+  * Portions created by the Initial Developer are Copyright (C) 2011
+  * the Initial Developer. All Rights Reserved.
+  *
+  * Contributor(s):
+  *   Bas Schouten <bschouten@mozilla.com>
+  *
+  * Alternatively, the contents of this file may be used under the terms of
+  * either the GNU General Public License Version 2 or later (the "GPL"), or
+  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+  * in which case the provisions of the GPL or the LGPL are applicable instead
+  * of those above. If you wish to allow use of your version of this file only
+  * under the terms of either the GPL or the LGPL, and not to allow others to
+  * use your version of this file under the terms of the MPL, indicate your
+  * decision by deleting the provisions above and replace them with the notice
+  * and other provisions required by the GPL or the LGPL. If you do not delete
+  * the provisions above, a recipient may use your version of this file under
+  * the terms of any one of the MPL, the GPL or the LGPL.
+  *
+  * ***** END LICENSE BLOCK ***** */
+     
+#ifndef MOZILLA_GFX_SOURCESURFACEDUAL_H_
+#define MOZILLA_GFX_SOURCESURFACEDUAL_H_
+     
+#include "2D.h"
+     
+namespace mozilla {
+namespace gfx {
+
+class DualSurface;
+class DualPattern;
+
+class SourceSurfaceDual : public SourceSurface
+{
+public:
+  SourceSurfaceDual(DrawTarget *aDTA, DrawTarget *aDTB)
+    : mA(aDTA->Snapshot())
+    , mB(aDTB->Snapshot())
+  { }
+
+  virtual SurfaceType GetType() const { return SURFACE_DUAL_DT; }
+  virtual IntSize GetSize() const { return mA->GetSize(); }
+  virtual SurfaceFormat GetFormat() const { return mA->GetFormat(); }
+
+  /* Readback from this surface type is not supported! */
+  virtual TemporaryRef<DataSourceSurface> GetDataSurface() { return NULL; }
+private:
+  friend class DualSurface;
+  friend class DualPattern;
+
+  RefPtr<SourceSurface> mA;
+  RefPtr<SourceSurface> mB;
+};
+
+}
+}
+
+#endif /* MOZILLA_GFX_SOURCESURFACEDUAL_H_ */
--- a/gfx/2d/Tools.h
+++ b/gfx/2d/Tools.h
@@ -52,12 +52,21 @@ IsOperatorBoundByMask(CompositionOp aOp)
   case OP_DEST_ATOP:
   case OP_SOURCE:
     return false;
   default:
     return true;
   }
 }
 
+template <class T>
+struct ClassStorage
+{
+  char bytes[sizeof(T)];
+
+  const T *addr() const { return (const T *)bytes; }
+  T *addr() { return (T *)(void *)bytes; }
+};
+
 }
 }
 
 #endif /* MOZILLA_GFX_TOOLS_H_ */
--- a/gfx/2d/Types.h
+++ b/gfx/2d/Types.h
@@ -51,17 +51,18 @@ enum SurfaceType
 {
   SURFACE_DATA, /* Data surface - bitmap in memory */
   SURFACE_D2D1_BITMAP, /* Surface wrapping a ID2D1Bitmap */
   SURFACE_D2D1_DRAWTARGET, /* Surface made from a D2D draw target */
   SURFACE_CAIRO, /* Surface wrapping a cairo surface */
   SURFACE_CAIRO_IMAGE, /* Data surface wrapping a cairo image surface */
   SURFACE_COREGRAPHICS_IMAGE, /* Surface wrapping a CoreGraphics Image */
   SURFACE_COREGRAPHICS_CGCONTEXT, /* Surface wrapping a CG context */
-  SURFACE_SKIA /* Surface wrapping a Skia bitmap */
+  SURFACE_SKIA, /* Surface wrapping a Skia bitmap */
+  SURFACE_DUAL_DT /* Snapshot of a dual drawtarget */
 };
 
 enum SurfaceFormat
 {
   FORMAT_B8G8R8A8,
   FORMAT_B8G8R8X8,
   FORMAT_R5G6B5,
   FORMAT_A8
--- a/gfx/layers/d3d10/LayerManagerD3D10.fx
+++ b/gfx/layers/d3d10/LayerManagerD3D10.fx
@@ -36,16 +36,25 @@ BlendState NonPremul
   DestBlend = Inv_Src_Alpha;
   BlendOp = Add;
   SrcBlendAlpha = One;
   DestBlendAlpha = Inv_Src_Alpha;
   BlendOpAlpha = Add;
   RenderTargetWriteMask[0] = 0x0F; // All
 };
 
+BlendState NoBlendDual
+{
+  AlphaToCoverageEnable = FALSE;
+  BlendEnable[0] = FALSE;
+  BlendEnable[1] = FALSE;
+  RenderTargetWriteMask[0] = 0x0F; // All
+  RenderTargetWriteMask[1] = 0x0F; // All
+};
+
 BlendState ComponentAlphaBlend
 {
   AlphaToCoverageEnable = FALSE;
   BlendEnable[0] = TRUE;
   SrcBlend = One;
   DestBlend = Inv_Src1_Color;
   BlendOp = Add;
   SrcBlendAlpha = One;
@@ -89,16 +98,21 @@ struct VS_OUTPUT {
   float2 vTexCoords : TEXCOORD0;
 };
 
 struct PS_OUTPUT {
   float4 vSrc;
   float4 vAlpha;
 };
 
+struct PS_DUAL_OUTPUT {
+  float4 vOutput1 : SV_Target0;
+  float4 vOutput2 : SV_Target1;
+};
+
 VS_OUTPUT LayerQuadVS(const VS_INPUT aVertex)
 {
   VS_OUTPUT outp;
   outp.vPosition.z = 0;
   outp.vPosition.w = 1;
   
   // We use 4 component floats to uniquely describe a rectangle, by the structure
   // of x, y, width, height. This allows us to easily generate the 4 corners
@@ -180,16 +194,24 @@ PS_OUTPUT ComponentAlphaShader(const VS_
   return result;
 }
 
 float4 SolidColorShader(const VS_OUTPUT aVertex) : SV_Target
 {
   return fLayerColor;
 }
 
+PS_DUAL_OUTPUT AlphaExtractionPrepareShader(const VS_OUTPUT aVertex)
+{
+  PS_DUAL_OUTPUT result;
+  result.vOutput1 = float4(0, 0, 0, 1);
+  result.vOutput2 = float4(1, 1, 1, 1);
+  return result;
+}
+
 technique10 RenderRGBLayerPremul
 {
     pass P0
     {
         SetRasterizerState( LayerRast );
         SetBlendState( Premul, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
         SetVertexShader( CompileShader( vs_4_0_level_9_3, LayerQuadVS() ) );
         SetGeometryShader( NULL );
@@ -288,8 +310,20 @@ technique10 RenderSolidColorLayer
     {
         SetRasterizerState( LayerRast );
         SetBlendState( Premul, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
         SetVertexShader( CompileShader( vs_4_0_level_9_3, LayerQuadVS() ) );
         SetGeometryShader( NULL );
         SetPixelShader( CompileShader( ps_4_0_level_9_3, SolidColorShader() ) );
     }
 }
+
+technique10 PrepareAlphaExtractionTextures
+{
+    pass P0
+    {
+        SetRasterizerState( LayerRast );
+        SetBlendState( NoBlendDual, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
+        SetVertexShader( CompileShader( vs_4_0_level_9_3, LayerQuadVS() ) );
+        SetGeometryShader( NULL );
+        SetPixelShader( CompileShader( ps_4_0_level_9_3, AlphaExtractionPrepareShader() ) );
+    }
+}
--- a/gfx/layers/d3d10/LayerManagerD3D10Effect.h
+++ b/gfx/layers/d3d10/LayerManagerD3D10Effect.h
@@ -20,17 +20,17 @@ cbuffer PerOccasionalLayer
 }
 
 cbuffer PerLayerManager
 {
     float4x4 mProjection;               // Offset:    0, size:   64
 }
 
 //
-// 11 local object(s)
+// 12 local object(s)
 //
 BlendState Premul
 {
     AlphaToCoverageEnable = bool(FALSE /* 0 */);
     BlendEnable[0] = bool(TRUE /* 1 */);
     SrcBlend[0] = uint(ONE /* 2 */);
     DestBlend[0] = uint(INV_SRC_ALPHA /* 6 */);
     BlendOp[0] = uint(ADD /* 1 */);
@@ -46,16 +46,24 @@ BlendState NonPremul
     SrcBlend[0] = uint(SRC_ALPHA /* 5 */);
     DestBlend[0] = uint(INV_SRC_ALPHA /* 6 */);
     BlendOp[0] = uint(ADD /* 1 */);
     SrcBlendAlpha[0] = uint(ONE /* 2 */);
     DestBlendAlpha[0] = uint(INV_SRC_ALPHA /* 6 */);
     BlendOpAlpha[0] = uint(ADD /* 1 */);
     RenderTargetWriteMask[0] = byte(0x0f);
 };
+BlendState NoBlendDual
+{
+    AlphaToCoverageEnable = bool(FALSE /* 0 */);
+    BlendEnable[0] = bool(FALSE /* 0 */);
+    BlendEnable[1] = bool(FALSE /* 0 */);
+    RenderTargetWriteMask[0] = byte(0x0f);
+    RenderTargetWriteMask[1] = byte(0x0f);
+};
 BlendState ComponentAlphaBlend
 {
     AlphaToCoverageEnable = bool(FALSE /* 0 */);
     BlendEnable[0] = bool(TRUE /* 1 */);
     SrcBlend[0] = uint(ONE /* 2 */);
     DestBlend[0] = uint(INV_SRC1_COLOR /* 17 */);
     BlendOp[0] = uint(ADD /* 1 */);
     SrcBlendAlpha[0] = uint(ONE /* 2 */);
@@ -82,17 +90,17 @@ SamplerState LayerTextureSamplerLinear
 SamplerState LayerTextureSamplerPoint
 {
     Filter   = uint(MIN_MAG_MIP_POINT /* 0 */);
     AddressU = uint(CLAMP /* 3 */);
     AddressV = uint(CLAMP /* 3 */);
 };
 
 //
-// 9 technique(s)
+// 10 technique(s)
 //
 technique10 RenderRGBLayerPremul
 {
     pass P0
     {
         RasterizerState = LayerRast;
         AB_BlendFactor = float4(0, 0, 0, 0);
         AB_SampleMask = uint(0xffffffff);
@@ -2046,40 +2054,214 @@ technique10 RenderSolidColorLayer
             ret 
             // Approximately 2 instruction slots used
                     
         };
     }
 
 }
 
+technique10 PrepareAlphaExtractionTextures
+{
+    pass P0
+    {
+        RasterizerState = LayerRast;
+        AB_BlendFactor = float4(0, 0, 0, 0);
+        AB_SampleMask = uint(0xffffffff);
+        BlendState = NoBlendDual;
+        VertexShader = asm {
+            //
+            // Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+            //
+            //
+            // Buffer Definitions: 
+            //
+            // cbuffer PerLayer
+            // {
+            //
+            //   float4 vTextureCoords;             // Offset:    0 Size:    16
+            //   float4 vLayerQuad;                 // Offset:   16 Size:    16
+            //   float fLayerOpacity;               // Offset:   32 Size:     4 [unused]
+            //   float4x4 mLayerTransform;          // Offset:   48 Size:    64
+            //
+            // }
+            //
+            // cbuffer PerOccasionalLayer
+            // {
+            //
+            //   float4 vRenderTargetOffset;        // Offset:    0 Size:    16
+            //   float4 fLayerColor;                // Offset:   16 Size:    16 [unused]
+            //
+            // }
+            //
+            // cbuffer PerLayerManager
+            // {
+            //
+            //   float4x4 mProjection;              // Offset:    0 Size:    64
+            //
+            // }
+            //
+            //
+            // Resource Bindings:
+            //
+            // Name                                 Type  Format         Dim Slot Elements
+            // ------------------------------ ---------- ------- ----------- ---- --------
+            // PerLayer                          cbuffer      NA          NA    0        1
+            // PerOccasionalLayer                cbuffer      NA          NA    1        1
+            // PerLayerManager                   cbuffer      NA          NA    2        1
+            //
+            //
+            //
+            // Input signature:
+            //
+            // Name                 Index   Mask Register SysValue Format   Used
+            // -------------------- ----- ------ -------- -------- ------ ------
+            // POSITION                 0   xy          0     NONE  float   xy  
+            //
+            //
+            // Output signature:
+            //
+            // Name                 Index   Mask Register SysValue Format   Used
+            // -------------------- ----- ------ -------- -------- ------ ------
+            // SV_Position              0   xyzw        0      POS  float   xyzw
+            // TEXCOORD                 0   xy          1     NONE  float   xy  
+            //
+            //
+            // Constant buffer to DX9 shader constant mappings:
+            //
+            // Target Reg Buffer  Start Reg # of Regs        Data Conversion
+            // ---------- ------- --------- --------- ----------------------
+            // c1         cb0             0         2  ( FLT, FLT, FLT, FLT)
+            // c3         cb0             3         2  ( FLT, FLT, FLT, FLT)
+            // c5         cb0             6         1  ( FLT, FLT, FLT, FLT)
+            // c6         cb1             0         1  ( FLT, FLT, FLT, FLT)
+            // c7         cb2             0         4  ( FLT, FLT, FLT, FLT)
+            //
+            //
+            // Runtime generated constant mappings:
+            //
+            // Target Reg                               Constant Description
+            // ---------- --------------------------------------------------
+            // c0                              Vertex Shader position offset
+            //
+            //
+            // Level9 shader bytecode:
+            //
+                vs_2_x
+                dcl_texcoord v0
+                mad oT0.xy, v0, c1.zwzw, c1
+                mad r0.xy, v0, c2.zwzw, c2
+                mul r1, r0.y, c4
+                mad r0, c3, r0.x, r1
+                add r0, r0, c5
+                rcp r1.x, r0.w
+                mul r0.xyz, r0, r1.x
+                add r0, r0, -c6
+                mul r0.xyz, r0.w, r0
+                mul r1, r0.y, c8
+                mad r1, c7, r0.x, r1
+                mad r1, c9, r0.z, r1
+                mad r0, c10, r0.w, r1
+                mad oPos.xy, r0.w, c0, r0
+                mov oPos.zw, r0
+            
+            // approximately 15 instruction slots used
+            vs_4_0
+            dcl_constantbuffer cb0[7], immediateIndexed
+            dcl_constantbuffer cb1[1], immediateIndexed
+            dcl_constantbuffer cb2[4], immediateIndexed
+            dcl_input v0.xy
+            dcl_output_siv o0.xyzw, position
+            dcl_output o1.xy
+            dcl_temps 2
+            mad r0.xy, v0.xyxx, cb0[1].zwzz, cb0[1].xyxx
+            mul r1.xyzw, r0.yyyy, cb0[4].xyzw
+            mad r0.xyzw, cb0[3].xyzw, r0.xxxx, r1.xyzw
+            add r0.xyzw, r0.xyzw, cb0[6].xyzw
+            div r0.xyz, r0.xyzx, r0.wwww
+            add r0.xyzw, r0.xyzw, -cb1[0].xyzw
+            mul r0.xyz, r0.wwww, r0.xyzx
+            mul r1.xyzw, r0.yyyy, cb2[1].xyzw
+            mad r1.xyzw, cb2[0].xyzw, r0.xxxx, r1.xyzw
+            mad r1.xyzw, cb2[2].xyzw, r0.zzzz, r1.xyzw
+            mad o0.xyzw, cb2[3].xyzw, r0.wwww, r1.xyzw
+            mad o1.xy, v0.xyxx, cb0[0].zwzz, cb0[0].xyxx
+            ret 
+            // Approximately 13 instruction slots used
+                    
+        };
+        GeometryShader = NULL;
+        PixelShader = asm {
+            //
+            // Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+            //
+            //
+            //
+            // Input signature:
+            //
+            // Name                 Index   Mask Register SysValue Format   Used
+            // -------------------- ----- ------ -------- -------- ------ ------
+            // SV_Position              0   xyzw        0      POS  float       
+            // TEXCOORD                 0   xy          1     NONE  float       
+            //
+            //
+            // Output signature:
+            //
+            // Name                 Index   Mask Register SysValue Format   Used
+            // -------------------- ----- ------ -------- -------- ------ ------
+            // SV_Target                0   xyzw        0   TARGET  float   xyzw
+            // SV_Target                1   xyzw        1   TARGET  float   xyzw
+            //
+            //
+            // Level9 shader bytecode:
+            //
+                ps_2_x
+                def c0, 0, 0, 0, 1
+                mov oC0, c0
+                mov r0, c0.w
+                mov oC1, r0
+            
+            // approximately 3 instruction slots used
+            ps_4_0
+            dcl_output o0.xyzw
+            dcl_output o1.xyzw
+            mov o0.xyzw, l(0,0,0,1.000000)
+            mov o1.xyzw, l(1.000000,1.000000,1.000000,1.000000)
+            ret 
+            // Approximately 3 instruction slots used
+                    
+        };
+    }
+
+}
+
 #endif
 
 const BYTE g_main[] =
 {
-     68,  88,  66,  67,  17, 159, 
-     33, 161, 201, 116,  88,   5, 
-    211,  56, 199,  67, 199, 232, 
-    242,  72,   1,   0,   0,   0, 
-    215, 124,   0,   0,   1,   0, 
+     68,  88,  66,  67, 254, 183, 
+    204, 179, 168, 103,  33,  91, 
+      6,  38, 255, 118, 143,  81, 
+     10, 185,   1,   0,   0,   0, 
+    118, 136,   0,   0,   1,   0, 
       0,   0,  36,   0,   0,   0, 
-     70,  88,  49,  48, 171, 124, 
+     70,  88,  49,  48,  74, 136, 
       0,   0,   1,  16, 255, 254, 
       3,   0,   0,   0,   7,   0, 
-      0,   0,  11,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      9,   0,   0,   0, 103, 115, 
+      0,   0,  12,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+     10,   0,   0,   0,  22, 126, 
       0,   0,   0,   0,   0,   0, 
       5,   0,   0,   0,   0,   0, 
-      0,   0,   3,   0,   0,   0, 
+      0,   0,   4,   0,   0,   0, 
       1,   0,   0,   0,   2,   0, 
       0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,  18,   0, 
-      0,   0,  18,   0,   0,   0, 
+      0,   0,   0,   0,  20,   0, 
+      0,   0,  20,   0,   0,   0, 
       0,   0,   0,   0,  80, 101, 
     114,  76,  97, 121, 101, 114, 
       0, 102, 108, 111,  97, 116, 
      52,   0,  13,   0,   0,   0, 
       1,   0,   0,   0,   0,   0, 
       0,   0,  16,   0,   0,   0, 
      16,   0,   0,   0,  16,   0, 
       0,   0,  10,  33,   0,   0, 
@@ -2157,16 +2339,28 @@ const BYTE g_main[] =
       1,   0,   0,   0,   1,   0, 
       0,   0,   2,   0,   0,   0, 
       2,   0,   0,   0,   1,   0, 
       0,   0,   2,   0,   0,   0, 
       6,   0,   0,   0,   1,   0, 
       0,   0,   2,   0,   0,   0, 
       1,   0,   0,   0,   1,   0, 
       0,   0,   3,   0,   0,   0, 
+     15,   0,   0,   0,  78, 111, 
+     66, 108, 101, 110, 100,  68, 
+    117,  97, 108,   0,   1,   0, 
+      0,   0,   2,   0,   0,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   0,   2,   0,   0,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   0,   2,   0,   0,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   0,   3,   0,   0,   0, 
+     15,   0,   0,   0,   1,   0, 
+      0,   0,   3,   0,   0,   0, 
      15,   0,   0,   0,  67, 111, 
     109, 112, 111, 110, 101, 110, 
     116,  65, 108, 112, 104,  97, 
      66, 108, 101, 110, 100,   0, 
       1,   0,   0,   0,   2,   0, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   2,   0, 
       0,   0,   1,   0,   0,   0, 
@@ -2181,40 +2375,40 @@ const BYTE g_main[] =
       1,   0,   0,   0,   2,   0, 
       0,   0,   6,   0,   0,   0, 
       1,   0,   0,   0,   2,   0, 
       0,   0,   1,   0,   0,   0, 
       1,   0,   0,   0,   3,   0, 
       0,   0,  15,   0,   0,   0, 
      82,  97, 115, 116, 101, 114, 
     105, 122, 101, 114,  83, 116, 
-     97, 116, 101,   0, 142,   2, 
+     97, 116, 101,   0, 214,   2, 
       0,   0,   2,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   4,   0, 
       0,   0,  76,  97, 121, 101, 
     114,  82,  97, 115, 116,   0, 
       1,   0,   0,   0,   2,   0, 
       0,   0,   1,   0,   0,   0, 
       1,   0,   0,   0,   2,   0, 
       0,   0,   1,   0,   0,   0, 
      84, 101, 120, 116, 117, 114, 
-    101,  50,  68,   0, 220,   2, 
+    101,  50,  68,   0,  36,   3, 
       0,   0,   2,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,  12,   0, 
       0,   0, 116,  82,  71,  66, 
       0, 116,  89,   0, 116,  67, 
      98,   0, 116,  67, 114,   0, 
     116,  82,  71,  66,  87, 104, 
     105, 116, 101,   0,  83,  97, 
     109, 112, 108, 101, 114,  83, 
-    116,  97, 116, 101,   0,  28, 
+    116,  97, 116, 101,   0, 100, 
       3,   0,   0,   2,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,  21, 
       0,   0,   0,  76,  97, 121, 
     101, 114,  84, 101, 120, 116, 
     117, 114, 101,  83,  97, 109, 
     112, 108, 101, 114,  76, 105, 
@@ -2558,17 +2752,17 @@ const BYTE g_main[] =
      15,   0,   0,   0,  68,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   3,   0, 
       0,   0,   1,   0,   0,   0, 
       3,  12,   0,   0,  83,  86, 
      95,  80, 111, 115, 105, 116, 
     105, 111, 110,   0,  84,  69, 
      88,  67,  79,  79,  82,  68, 
-      0, 171, 171, 171,   8,   4, 
+      0, 171, 171, 171,  80,   4, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   2,   0, 
       0,   0,   0,   0,   0,   0, 
      84,   4,   0,   0,  68,  88, 
      66,  67, 243,   1, 145, 163, 
     244, 213, 142, 119,  56, 177, 
      66, 167, 121,  91, 183,  98, 
       1,   0,   0,   0,  84,   4, 
@@ -2747,17 +2941,17 @@ const BYTE g_main[] =
      71,  78,  44,   0,   0,   0, 
       1,   0,   0,   0,   8,   0, 
       0,   0,  32,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,  15,   0, 
       0,   0,  83,  86,  95,  84, 
      97, 114, 103, 101, 116,   0, 
-    171, 171, 136,  11,   0,   0, 
+    171, 171, 208,  11,   0,   0, 
       0,   0,   0,   0,  82, 101, 
     110, 100, 101, 114,  82,  71, 
      66,  76,  97, 121, 101, 114, 
      80, 114, 101, 109, 117, 108, 
      80, 111, 105, 110, 116,   0, 
       4,   0,   0,   0,   1,   0, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   0,   0, 
@@ -3077,17 +3271,17 @@ const BYTE g_main[] =
      15,   0,   0,   0,  68,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   3,   0, 
       0,   0,   1,   0,   0,   0, 
       3,  12,   0,   0,  83,  86, 
      95,  80, 111, 115, 105, 116, 
     105, 111, 110,   0,  84,  69, 
      88,  67,  79,  79,  82,  68, 
-      0, 171, 171, 171,  50,  16, 
+      0, 171, 171, 171, 122,  16, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   2,   0, 
       0,   0,   0,   0,   0,   0, 
      84,   4,   0,   0,  68,  88, 
      66,  67,  18,   7, 254,  25, 
     136,  32, 226,  82, 202, 102, 
      47, 221,  83,  73, 192, 155, 
       1,   0,   0,   0,  84,   4, 
@@ -3266,17 +3460,17 @@ const BYTE g_main[] =
      71,  78,  44,   0,   0,   0, 
       1,   0,   0,   0,   8,   0, 
       0,   0,  32,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,  15,   0, 
       0,   0,  83,  86,  95,  84, 
      97, 114, 103, 101, 116,   0, 
-    171, 171, 178,  23,   0,   0, 
+    171, 171, 250,  23,   0,   0, 
       0,   0,   0,   0,  82, 101, 
     110, 100, 101, 114,  82,  71, 
      66,  65,  76,  97, 121, 101, 
     114,  80, 114, 101, 109, 117, 
     108,   0,   4,   0,   0,   0, 
       1,   0,   0,   0,   0,   0, 
       0,   0,   1,   0,   0,   0, 
       0,   0,   0,   0,   1,   0, 
@@ -3596,17 +3790,17 @@ const BYTE g_main[] =
      68,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       3,   0,   0,   0,   1,   0, 
       0,   0,   3,  12,   0,   0, 
      83,  86,  95,  80, 111, 115, 
     105, 116, 105, 111, 110,   0, 
      84,  69,  88,  67,  79,  79, 
      82,  68,   0, 171, 171, 171, 
-     88,  28,   0,   0,   0,   0, 
+    160,  28,   0,   0,   0,   0, 
       0,   0,   1,   0,   0,   0, 
       2,   0,   0,   0,   0,   0, 
       0,   0,  48,   4,   0,   0, 
      68,  88,  66,  67, 158, 107, 
      18, 255, 206, 164, 235, 111, 
     119,   9, 247, 201, 106, 179, 
      84,  67,   1,   0,   0,   0, 
      48,   4,   0,   0,   6,   0, 
@@ -3778,17 +3972,17 @@ const BYTE g_main[] =
      79,  83,  71,  78,  44,   0, 
       0,   0,   1,   0,   0,   0, 
       8,   0,   0,   0,  32,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   3,   0, 
       0,   0,   0,   0,   0,   0, 
      15,   0,   0,   0,  83,  86, 
      95,  84,  97, 114, 103, 101, 
-    116,   0, 171, 171, 216,  35, 
+    116,   0, 171, 171,  32,  36, 
       0,   0,   0,   0,   0,   0, 
      82, 101, 110, 100, 101, 114, 
      82,  71,  66,  65,  76,  97, 
     121, 101, 114,  78, 111, 110, 
      80, 114, 101, 109, 117, 108, 
       0,   4,   0,   0,   0,   1, 
       0,   0,   0,   0,   0,   0, 
       0,   1,   0,   0,   0,   0, 
@@ -4108,17 +4302,17 @@ const BYTE g_main[] =
       0,  15,   0,   0,   0,  68, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   3, 
       0,   0,   0,   1,   0,   0, 
       0,   3,  12,   0,   0,  83, 
      86,  95,  80, 111, 115, 105, 
     116, 105, 111, 110,   0,  84, 
      69,  88,  67,  79,  79,  82, 
-     68,   0, 171, 171, 171,  93, 
+     68,   0, 171, 171, 171, 165, 
      40,   0,   0,   0,   0,   0, 
       0,   1,   0,   0,   0,   2, 
       0,   0,   0,   0,   0,   0, 
       0,  48,   4,   0,   0,  68, 
      88,  66,  67, 158, 107,  18, 
     255, 206, 164, 235, 111, 119, 
       9, 247, 201, 106, 179,  84, 
      67,   1,   0,   0,   0,  48, 
@@ -4291,17 +4485,17 @@ const BYTE g_main[] =
      83,  71,  78,  44,   0,   0, 
       0,   1,   0,   0,   0,   8, 
       0,   0,   0,  32,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   3,   0,   0, 
       0,   0,   0,   0,   0,  15, 
       0,   0,   0,  83,  86,  95, 
      84,  97, 114, 103, 101, 116, 
-      0, 171, 171, 221,  47,   0, 
+      0, 171, 171,  37,  48,   0, 
       0,   0,   0,   0,   0,  82, 
     101, 110, 100, 101, 114,  82, 
      71,  66,  65,  76,  97, 121, 
     101, 114,  80, 114, 101, 109, 
     117, 108,  80, 111, 105, 110, 
     116,   0,   4,   0,   0,   0, 
       1,   0,   0,   0,   0,   0, 
       0,   0,   1,   0,   0,   0, 
@@ -4622,17 +4816,17 @@ const BYTE g_main[] =
      68,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       3,   0,   0,   0,   1,   0, 
       0,   0,   3,  12,   0,   0, 
      83,  86,  95,  80, 111, 115, 
     105, 116, 105, 111, 110,   0, 
      84,  69,  88,  67,  79,  79, 
      82,  68,   0, 171, 171, 171, 
-    100,  52,   0,   0,   0,   0, 
+    172,  52,   0,   0,   0,   0, 
       0,   0,   1,   0,   0,   0, 
       2,   0,   0,   0,   0,   0, 
       0,   0,  48,   4,   0,   0, 
      68,  88,  66,  67,  61,  89, 
     104, 203, 112,  15, 192,   7, 
      21,  99, 104, 101,   1, 140, 
     240, 252,   1,   0,   0,   0, 
      48,   4,   0,   0,   6,   0, 
@@ -4804,17 +4998,17 @@ const BYTE g_main[] =
      79,  83,  71,  78,  44,   0, 
       0,   0,   1,   0,   0,   0, 
       8,   0,   0,   0,  32,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   3,   0, 
       0,   0,   0,   0,   0,   0, 
      15,   0,   0,   0,  83,  86, 
      95,  84,  97, 114, 103, 101, 
-    116,   0, 171, 171, 228,  59, 
+    116,   0, 171, 171,  44,  60, 
       0,   0,   0,   0,   0,   0, 
      82, 101, 110, 100, 101, 114, 
      82,  71,  66,  65,  76,  97, 
     121, 101, 114,  78, 111, 110, 
      80, 114, 101, 109, 117, 108, 
      80, 111, 105, 110, 116,   0, 
       4,   0,   0,   0,   1,   0, 
       0,   0,   0,   0,   0,   0, 
@@ -5135,17 +5329,17 @@ const BYTE g_main[] =
      15,   0,   0,   0,  68,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   3,   0, 
       0,   0,   1,   0,   0,   0, 
       3,  12,   0,   0,  83,  86, 
      95,  80, 111, 115, 105, 116, 
     105, 111, 110,   0,  84,  69, 
      88,  67,  79,  79,  82,  68, 
-      0, 171, 171, 171, 110,  64, 
+      0, 171, 171, 171, 182,  64, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   2,   0, 
       0,   0,   0,   0,   0,   0, 
      48,   4,   0,   0,  68,  88, 
      66,  67,  61,  89, 104, 203, 
     112,  15, 192,   7,  21,  99, 
     104, 101,   1, 140, 240, 252, 
       1,   0,   0,   0,  48,   4, 
@@ -5318,17 +5512,17 @@ const BYTE g_main[] =
      71,  78,  44,   0,   0,   0, 
       1,   0,   0,   0,   8,   0, 
       0,   0,  32,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,  15,   0, 
       0,   0,  83,  86,  95,  84, 
      97, 114, 103, 101, 116,   0, 
-    171, 171, 238,  71,   0,   0, 
+    171, 171,  54,  72,   0,   0, 
       0,   0,   0,   0,  82, 101, 
     110, 100, 101, 114,  89,  67, 
      98,  67, 114,  76,  97, 121, 
     101, 114,   0,   4,   0,   0, 
       0,   1,   0,   0,   0,   0, 
       0,   0,   0,   1,   0,   0, 
       0,   0,   0,   0,   0,   1, 
       0,   0,   0,   0,   0,   0, 
@@ -5647,17 +5841,17 @@ const BYTE g_main[] =
       0,  68,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   3,   0,   0,   0,   1, 
       0,   0,   0,   3,  12,   0, 
       0,  83,  86,  95,  80, 111, 
     115, 105, 116, 105, 111, 110, 
       0,  84,  69,  88,  67,  79, 
      79,  82,  68,   0, 171, 171, 
-    171, 107,  76,   0,   0,   0, 
+    171, 179,  76,   0,   0,   0, 
       0,   0,   0,   1,   0,   0, 
       0,   2,   0,   0,   0,   0, 
       0,   0,   0,  64,   7,   0, 
       0,  68,  88,  66,  67, 222, 
     117, 213, 158, 196,  73, 115, 
     238,  98,  73, 165, 136,  82, 
     215, 234,   7,   1,   0,   0, 
       0,  64,   7,   0,   0,   6, 
@@ -5960,17 +6154,17 @@ const BYTE g_main[] =
      83,  71,  78,  44,   0,   0, 
       0,   1,   0,   0,   0,   8, 
       0,   0,   0,  32,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   3,   0,   0, 
       0,   0,   0,   0,   0,  15, 
       0,   0,   0,  83,  86,  95, 
      84,  97, 114, 103, 101, 116, 
-      0, 171, 171, 235,  83,   0, 
+      0, 171, 171,  51,  84,   0, 
       0,   0,   0,   0,   0,  82, 
     101, 110, 100, 101, 114,  67, 
     111, 109, 112, 111, 110, 101, 
     110, 116,  65, 108, 112, 104, 
      97,  76,  97, 121, 101, 114, 
       0,   4,   0,   0,   0,   1, 
       0,   0,   0,   0,   0,   0, 
       0,   1,   0,   0,   0,   0, 
@@ -6290,17 +6484,17 @@ const BYTE g_main[] =
       0,  15,   0,   0,   0,  68, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   3, 
       0,   0,   0,   1,   0,   0, 
       0,   3,  12,   0,   0,  83, 
      86,  95,  80, 111, 115, 105, 
     116, 105, 111, 110,   0,  84, 
      69,  88,  67,  79,  79,  82, 
-     68,   0, 171, 171, 171, 129, 
+     68,   0, 171, 171, 171, 201, 
      91,   0,   0,   0,   0,   0, 
       0,   1,   0,   0,   0,   2, 
       0,   0,   0,   0,   0,   0, 
       0, 176,   5,   0,   0,  68, 
      88,  66,  67,  10, 232, 128, 
      36, 124, 206, 211, 130, 126, 
      20, 252, 175, 204,  95, 106, 
      47,   1,   0,   0,   0, 176, 
@@ -6537,17 +6731,17 @@ const BYTE g_main[] =
       0,   0,   0,   3,   0,   0, 
       0,   0,   0,   0,   0,  15, 
       0,   0,   0,  56,   0,   0, 
       0,   1,   0,   0,   0,   0, 
       0,   0,   0,   3,   0,   0, 
       0,   1,   0,   0,   0,  15, 
       0,   0,   0,  83,  86,  95, 
      84,  97, 114, 103, 101, 116, 
-      0, 171, 171,   1,  99,   0, 
+      0, 171, 171,  73,  99,   0, 
       0,   0,   0,   0,   0,  82, 
     101, 110, 100, 101, 114,  83, 
     111, 108, 105, 100,  67, 111, 
     108, 111, 114,  76,  97, 121, 
     101, 114,   0,   4,   0,   0, 
       0,   1,   0,   0,   0,   0, 
       0,   0,   0,   1,   0,   0, 
       0,   0,   0,   0,   0,   1, 
@@ -6867,17 +7061,17 @@ const BYTE g_main[] =
       0,  68,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   3,   0,   0,   0,   1, 
       0,   0,   0,   3,  12,   0, 
       0,  83,  86,  95,  80, 111, 
     115, 105, 116, 105, 111, 110, 
       0,  84,  69,  88,  67,  79, 
      79,  82,  68,   0, 171, 171, 
-    171,   3, 105,   0,   0,   0, 
+    171,  75, 105,   0,   0,   0, 
       0,   0,   0,   1,   0,   0, 
       0,   2,   0,   0,   0,   0, 
       0,   0,   0, 216,   2,   0, 
       0,  68,  88,  66,  67, 136, 
     106,  87,  29, 239,  32, 100, 
     138, 218,   2, 105,  91, 143, 
     165, 252,  49,   1,   0,   0, 
       0, 216,   2,   0,   0,   6, 
@@ -6992,394 +7186,878 @@ const BYTE g_main[] =
      83,  71,  78,  44,   0,   0, 
       0,   1,   0,   0,   0,   8, 
       0,   0,   0,  32,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   3,   0,   0, 
       0,   0,   0,   0,   0,  15, 
       0,   0,   0,  83,  86,  95, 
      84,  97, 114, 103, 101, 116, 
-      0, 171, 171, 131, 112,   0, 
-      0,   0,   0,   0,   0,   4, 
-      0,   0,   0, 112,   0,   0, 
-      0,   0,   0,   0,   0,   4, 
-      0,   0,   0, 255, 255, 255, 
-    255,   0,   0,   0,   0,  48, 
-      0,   0,   0,  20,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,  63,   0,   0, 
-      0,  20,   0,   0,   0,   0, 
-      0,   0,   0,  16,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0, 108,   0,   0,   0,  80, 
-      0,   0,   0,   0,   0,   0, 
-      0,  32,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0, 159, 
-      0,   0,   0, 131,   0,   0, 
-      0,   0,   0,   0,   0,  48, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0, 175,   0,   0, 
-      0,  32,   0,   0,   0,   0, 
-      0,   0,   0,   2,   0,   0, 
-      0, 255, 255, 255, 255,   0, 
-      0,   0,   0, 194,   0,   0, 
-      0,  20,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0, 214,   0,   0,   0,  20, 
-      0,   0,   0,   0,   0,   0, 
-      0,  16,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0, 226, 
-      0,   0,   0,  64,   0,   0, 
-      0,   0,   0,   0,   0,   1, 
-      0,   0,   0, 255, 255, 255, 
-    255,   0,   0,   0,   0, 242, 
-      0,   0,   0, 131,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,  37,   1,   0, 
-      0,   9,   1,   0,   0,   0, 
-      0,   0,   0, 255, 255, 255, 
-    255,   9,   0,   0,   0,  36, 
-      0,   0,   0,   0,   0,   0, 
-      0,   1,   0,   0,   0,  44, 
-      1,   0,   0,  37,   0,   0, 
-      0,   0,   0,   0,   0,   1, 
-      0,   0,   0,  56,   1,   0, 
-      0,  38,   0,   0,   0,   0, 
-      0,   0,   0,   1,   0,   0, 
-      0,  68,   1,   0,   0,  39, 
-      0,   0,   0,   0,   0,   0, 
-      0,   1,   0,   0,   0,  80, 
-      1,   0,   0,  40,   0,   0, 
-      0,   0,   0,   0,   0,   1, 
-      0,   0,   0,  92,   1,   0, 
-      0,  41,   0,   0,   0,   0, 
-      0,   0,   0,   1,   0,   0, 
-      0, 104,   1,   0,   0,  42, 
-      0,   0,   0,   0,   0,   0, 
-      0,   1,   0,   0,   0, 116, 
-      1,   0,   0,  43,   0,   0, 
-      0,   0,   0,   0,   0,   1, 
+      0, 171, 171, 203, 112,   0, 
+      0,   0,   0,   0,   0,  80, 
+    114, 101, 112,  97, 114, 101, 
+     65, 108, 112, 104,  97,  69, 
+    120, 116, 114,  97,  99, 116, 
+    105, 111, 110,  84, 101, 120, 
+    116, 117, 114, 101, 115,   0, 
+      4,   0,   0,   0,   1,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,   0,   0,   0,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,   0,   0,   0,   3,   0, 
+      0,   0, 255, 255, 255, 255, 
+    104,   7,   0,   0,  68,  88, 
+     66,  67, 148, 219,   9, 126, 
+     59, 247, 178, 128, 120,  37, 
+    163, 130,  38,  53, 191, 236, 
+      1,   0,   0,   0, 104,   7, 
+      0,   0,   6,   0,   0,   0, 
+     56,   0,   0,   0, 188,   1, 
+      0,   0, 228,   3,   0,   0, 
+     96,   4,   0,   0, 220,   6, 
+      0,   0,  16,   7,   0,   0, 
+     65, 111, 110,  57, 124,   1, 
+      0,   0, 124,   1,   0,   0, 
+      0,   2, 254, 255,  24,   1, 
+      0,   0, 100,   0,   0,   0, 
+      5,   0,  36,   0,   0,   0, 
+     96,   0,   0,   0,  96,   0, 
+      0,   0,  36,   0,   1,   0, 
+     96,   0,   0,   0,   0,   0, 
+      2,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0,   3,   0, 
+      2,   0,   3,   0,   0,   0, 
+      0,   0,   0,   0,   6,   0, 
+      1,   0,   5,   0,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
+      1,   0,   6,   0,   0,   0, 
+      0,   0,   2,   0,   0,   0, 
+      4,   0,   7,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,   2, 254, 255,  31,   0, 
+      0,   2,   5,   0,   0, 128, 
+      0,   0,  15, 144,   4,   0, 
+      0,   4,   0,   0,   3, 224, 
+      0,   0, 228, 144,   1,   0, 
+    238, 160,   1,   0, 228, 160, 
+      4,   0,   0,   4,   0,   0, 
+      3, 128,   0,   0, 228, 144, 
+      2,   0, 238, 160,   2,   0, 
+    228, 160,   5,   0,   0,   3, 
+      1,   0,  15, 128,   0,   0, 
+     85, 128,   4,   0, 228, 160, 
+      4,   0,   0,   4,   0,   0, 
+     15, 128,   3,   0, 228, 160, 
       0,   0,   0, 128,   1,   0, 
-      0,  44,   0,   0,   0,   0, 
-      0,   0,   0,   1,   0,   0, 
-      0, 140,   1,   0,   0,   0, 
-      0,   0,   0, 152,   1,   0, 
-      0,   9,   1,   0,   0,   0, 
-      0,   0,   0, 255, 255, 255, 
-    255,   9,   0,   0,   0,  36, 
-      0,   0,   0,   0,   0,   0, 
-      0,   1,   0,   0,   0, 162, 
-      1,   0,   0,  37,   0,   0, 
-      0,   0,   0,   0,   0,   1, 
-      0,   0,   0, 174,   1,   0, 
-      0,  38,   0,   0,   0,   0, 
-      0,   0,   0,   1,   0,   0, 
-      0, 186,   1,   0,   0,  39, 
-      0,   0,   0,   0,   0,   0, 
-      0,   1,   0,   0,   0, 198, 
-      1,   0,   0,  40,   0,   0, 
-      0,   0,   0,   0,   0,   1, 
-      0,   0,   0, 210,   1,   0, 
-      0,  41,   0,   0,   0,   0, 
-      0,   0,   0,   1,   0,   0, 
-      0, 222,   1,   0,   0,  42, 
-      0,   0,   0,   0,   0,   0, 
-      0,   1,   0,   0,   0, 234, 
-      1,   0,   0,  43,   0,   0, 
-      0,   0,   0,   0,   0,   1, 
-      0,   0,   0, 246,   1,   0, 
-      0,  44,   0,   0,   0,   0, 
-      0,   0,   0,   1,   0,   0, 
-      0,   2,   2,   0,   0,   0, 
-      0,   0,   0,  14,   2,   0, 
-      0,   9,   1,   0,   0,   0, 
-      0,   0,   0, 255, 255, 255, 
-    255,   9,   0,   0,   0,  36, 
-      0,   0,   0,   0,   0,   0, 
-      0,   1,   0,   0,   0,  34, 
-      2,   0,   0,  37,   0,   0, 
-      0,   0,   0,   0,   0,   1, 
-      0,   0,   0,  46,   2,   0, 
-      0,  38,   0,   0,   0,   0, 
-      0,   0,   0,   1,   0,   0, 
-      0,  58,   2,   0,   0,  39, 
-      0,   0,   0,   0,   0,   0, 
-      0,   1,   0,   0,   0,  70, 
-      2,   0,   0,  40,   0,   0, 
-      0,   0,   0,   0,   0,   1, 
-      0,   0,   0,  82,   2,   0, 
-      0,  41,   0,   0,   0,   0, 
-      0,   0,   0,   1,   0,   0, 
-      0,  94,   2,   0,   0,  42, 
-      0,   0,   0,   0,   0,   0, 
-      0,   1,   0,   0,   0, 106, 
-      2,   0,   0,  43,   0,   0, 
-      0,   0,   0,   0,   0,   1, 
-      0,   0,   0, 118,   2,   0, 
-      0,  44,   0,   0,   0,   0, 
-      0,   0,   0,   1,   0,   0, 
-      0, 130,   2,   0,   0,   0, 
-      0,   0,   0, 186,   2,   0, 
-      0, 158,   2,   0,   0,   0, 
-      0,   0,   0, 255, 255, 255, 
-    255,   2,   0,   0,   0,  19, 
-      0,   0,   0,   0,   0,   0, 
-      0,   1,   0,   0,   0, 196, 
-      2,   0,   0,  13,   0,   0, 
-      0,   0,   0,   0,   0,   1, 
-      0,   0,   0, 208,   2,   0, 
-      0,   0,   0,   0,   0,   2, 
-      3,   0,   0, 230,   2,   0, 
-      0,   0,   0,   0,   0, 255, 
-    255, 255, 255,   0,   0,   0, 
-      0,   7,   3,   0,   0, 230, 
-      2,   0,   0,   0,   0,   0, 
-      0, 255, 255, 255, 255,   0, 
-      0,   0,   0,  10,   3,   0, 
-      0, 230,   2,   0,   0,   0, 
-      0,   0,   0, 255, 255, 255, 
-    255,   0,   0,   0,   0,  14, 
-      3,   0,   0, 230,   2,   0, 
-      0,   0,   0,   0,   0, 255,