Merge from mozilla-central.
authorDavid Anderson <danderson@mozilla.com>
Fri, 15 Jun 2012 15:23:58 -0700
changeset 112634 c55f5f8b93857e2b08331a1b4fafd979d3ebb444
parent 112633 7873fae10b14f486fb8462456dcb7ff1fbbe3f3a (current diff)
parent 101592 4e3362864fbd8c5b5c073bdb1b43f0745b3e6444 (diff)
child 112635 17db7530ad47b8ccf906317330358858a66d89b5
push id1708
push userakeybl@mozilla.com
push dateMon, 19 Nov 2012 21:10:21 +0000
treeherdermozilla-beta@27b14fe50103 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone16.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge from mozilla-central.
accessible/src/base/AccEvent.cpp
accessible/src/base/NotificationController.cpp
accessible/src/generic/Accessible.cpp
accessible/src/generic/Accessible.h
accessible/src/generic/DocAccessible.cpp
accessible/src/generic/DocAccessible.h
b2g/installer/package-manifest.in
browser/app/nsBrowserApp.cpp
browser/base/content/browser.js
browser/base/content/browser.xul
browser/components/nsBrowserContentHandler.js
browser/components/shell/src/nsWindowsShellService.cpp
browser/locales/en-US/chrome/browser/browser.dtd
build/mobile/devicemanagerSUT.py
config/autoconf.mk.in
configure.in
content/base/public/nsContentUtils.h
content/base/public/nsIDocument.h
content/base/public/nsTreeSanitizer.h
content/base/src/nsContentIterator.cpp
content/base/src/nsContentSink.cpp
content/base/src/nsDocument.cpp
content/base/src/nsFrameLoader.cpp
content/base/src/nsFrameLoader.h
content/base/src/nsGkAtomList.h
content/base/src/nsImageLoadingContent.cpp
content/base/src/nsImageLoadingContent.h
content/base/src/nsNodeInfoManager.cpp
content/base/src/nsTreeSanitizer.cpp
content/canvas/src/WebGLContext.cpp
content/canvas/src/WebGLContextGL.cpp
content/canvas/src/nsCanvasRenderingContext2D.cpp
content/canvas/src/nsCanvasRenderingContext2DAzure.cpp
content/canvas/test/test_canvas.html
content/events/public/nsEventNameList.h
content/events/src/nsDOMEvent.cpp
content/events/src/nsDOMEvent.h
content/events/src/nsDOMSimpleGestureEvent.cpp
content/events/src/nsDOMTouchEvent.cpp
content/events/src/nsDOMTouchEvent.h
content/events/src/nsEventListenerManager.cpp
content/events/src/nsEventListenerManager.h
content/html/content/src/nsGenericHTMLElement.cpp
content/html/content/src/nsHTMLIFrameElement.cpp
content/html/content/src/nsHTMLMediaElement.cpp
content/html/document/src/nsHTMLDocument.cpp
content/media/nsAudioStream.cpp
content/media/nsBuiltinDecoderStateMachine.cpp
content/svg/content/src/SVGPathData.cpp
content/svg/content/src/nsSVGSVGElement.cpp
content/xbl/src/nsXBLBinding.cpp
content/xbl/src/nsXBLInsertionPoint.cpp
content/xbl/src/nsXBLPrototypeBinding.cpp
content/xul/content/src/nsXULElement.cpp
content/xul/templates/src/nsXULTemplateQueryProcessorXML.cpp
docshell/base/nsDSURIContentListener.cpp
docshell/base/nsDocShell.cpp
dom/base/nsDOMClassInfo.cpp
dom/base/nsDOMClassInfoClasses.h
dom/base/nsDOMScriptObjectFactory.cpp
dom/base/nsDOMWindowUtils.cpp
dom/base/nsFocusManager.cpp
dom/base/nsGlobalWindow.cpp
dom/base/nsGlobalWindow.h
dom/base/nsIBaseDOMException.h
dom/base/nsPIDOMWindow.h
dom/indexedDB/IndexedDatabaseManager.cpp
dom/interfaces/base/nsIDOMWindowUtils.idl
dom/interfaces/css/nsIDOMCSS2Properties.idl
dom/interfaces/svg/nsIDOMSVGException.idl
dom/interfaces/xpath/nsIDOMXPathException.idl
dom/ipc/PBrowser.ipdl
dom/ipc/PContent.ipdl
dom/ipc/TabChild.cpp
dom/ipc/TabChild.h
dom/ipc/TabParent.cpp
dom/ipc/TabParent.h
dom/plugins/base/nsPluginHost.cpp
dom/plugins/base/nsPluginHost.h
dom/plugins/base/nsPluginTags.cpp
dom/plugins/base/nsPluginTags.h
dom/plugins/ipc/PluginModuleChild.cpp
dom/src/storage/nsDOMStorage.cpp
dom/workers/RuntimeService.cpp
editor/libeditor/base/DeleteRangeTxn.cpp
editor/libeditor/base/DeleteTextTxn.cpp
editor/libeditor/base/nsEditor.cpp
editor/libeditor/base/nsEditor.h
editor/libeditor/html/nsHTMLDataTransfer.cpp
editor/txmgr/src/nsTransactionItem.cpp
embedding/android/GeckoAppShell.java
embedding/components/windowwatcher/src/nsWindowWatcher.cpp
extensions/auth/nsAuthGSSAPI.h
extensions/auth/nsAuthSASL.h
extensions/auth/nsHttpNegotiateAuth.h
extensions/permissions/nsContentBlocker.h
gfx/gl/GLContext.cpp
gfx/gl/GLContext.h
gfx/gl/GLContextProviderEGL.cpp
gfx/gl/GLContextProviderGLX.cpp
gfx/src/nsDeviceContext.cpp
gfx/tests/gfxFontSelectionTest.cpp
gfx/tests/gfxTextRunPerfTest.cpp
gfx/thebes/gfxASurface.cpp
gfx/thebes/gfxCachedTempSurface.cpp
gfx/thebes/gfxContext.cpp
gfx/thebes/gfxFT2Fonts.cpp
gfx/thebes/gfxFont.cpp
gfx/thebes/gfxFont.h
gfx/thebes/gfxImageSurface.cpp
gfx/thebes/gfxImageSurface.h
gfx/thebes/gfxPangoFonts.cpp
gfx/thebes/gfxPattern.cpp
gfx/thebes/gfxPlatform.cpp
gfx/thebes/gfxPlatformFontList.cpp
gfx/thebes/gfxPlatformFontList.h
gfx/thebes/gfxPlatformGtk.cpp
gfx/thebes/gfxPlatformGtk.h
gfx/thebes/gfxWindowsPlatform.cpp
gfx/thebes/gfxXlibNativeRenderer.cpp
gfx/thebes/gfxXlibNativeRenderer.h
image/encoders/jpeg/nsJPEGEncoder.h
intl/locale/src/mac/nsCollationMacUC.h
intl/uconv/src/nsCharsetConverterManager.cpp
js/jsd/jsd_xpc.cpp
js/jsd/jsd_xpc.h
js/public/Vector.h
js/src/frontend/BytecodeCompiler.cpp
js/src/frontend/BytecodeEmitter.cpp
js/src/frontend/BytecodeEmitter.h
js/src/frontend/Parser.cpp
js/src/frontend/Parser.h
js/src/gc/Marking.cpp
js/src/gc/Marking.h
js/src/jsanalyze.h
js/src/jsapi.cpp
js/src/jsapi.h
js/src/jsarray.cpp
js/src/jscntxt.cpp
js/src/jscntxt.h
js/src/jsfriendapi.cpp
js/src/jsfriendapi.h
js/src/jsfun.h
js/src/jsgc.cpp
js/src/jsgc.h
js/src/jsgcinlines.h
js/src/jsinterp.cpp
js/src/jsiter.cpp
js/src/jsobj.cpp
js/src/jsobj.h
js/src/jsobjinlines.h
js/src/jsopcode.cpp
js/src/jspropertycache.cpp
js/src/jsproxy.cpp
js/src/jsreflect.cpp
js/src/jsscope.cpp
js/src/jsscript.cpp
js/src/jsscript.h
js/src/jsstr.cpp
js/src/jstypedarray.cpp
js/src/methodjit/BaseAssembler.h
js/src/methodjit/Compiler.cpp
js/src/shell/js.cpp
js/src/shell/jsworkers.cpp
js/src/vm/Debugger.cpp
js/src/vm/GlobalObject.cpp
js/src/vm/RegExpObject.cpp
js/src/vm/ScopeObject.cpp
js/src/vm/ScopeObject.h
js/src/vm/Stack.cpp
js/src/vm/String.h
js/xpconnect/src/XPCComponents.cpp
js/xpconnect/src/XPCJSID.cpp
js/xpconnect/src/XPCJSRuntime.cpp
js/xpconnect/src/XPCQuickStubs.cpp
js/xpconnect/src/XPCQuickStubs.h
js/xpconnect/src/XPCWrappedJS.cpp
js/xpconnect/src/XPCWrappedJSClass.cpp
js/xpconnect/src/XPCWrappedNative.cpp
js/xpconnect/src/nsXPConnect.cpp
js/xpconnect/src/xpcprivate.h
js/xpconnect/src/xpcpublic.h
layout/base/nsIPresShell.h
layout/build/Makefile.in
layout/build/nsLayoutModule.cpp
layout/generic/crashtests/crashtests.list
layout/generic/nsColumnSetFrame.cpp
layout/generic/nsFrame.cpp
layout/generic/nsHTMLReflowState.cpp
layout/generic/nsHTMLReflowState.h
layout/generic/nsSelection.cpp
layout/mathml/nsMathMLmactionFrame.cpp
layout/mathml/nsMathMLmactionFrame.h
layout/reftests/abs-pos/reftest.list
layout/reftests/bugs/reftest.list
layout/reftests/canvas/reftest.list
layout/reftests/columns/ahem.css
layout/reftests/columns/columnfill-auto-ref.html
layout/reftests/columns/columnfill-auto.html
layout/reftests/columns/columnfill-balance-ref.html
layout/reftests/columns/columnfill-balance.html
layout/reftests/columns/columnfill-change-ref.html
layout/reftests/columns/columnfill-change.html
layout/reftests/columns/columnfill-overflow-style-ref.html
layout/reftests/columns/columnfill-overflow-style.html
layout/reftests/mathml/reftest.list
layout/reftests/reftest.list
layout/reftests/svg/reftest.list
layout/reftests/text-overflow/reftest.list
layout/style/nsCSSProps.cpp
layout/style/nsCSSProps.h
layout/style/nsComputedDOMStyle.cpp
layout/style/nsComputedDOMStyle.h
layout/style/nsRuleNode.cpp
layout/style/nsStyleStruct.cpp
layout/style/nsStyleStruct.h
layout/style/test/property_database.js
layout/style/ua.css
layout/svg/base/src/nsSVGGlyphFrame.cpp
layout/svg/base/src/nsSVGImageFrame.cpp
layout/svg/base/src/nsSVGIntegrationUtils.cpp
layout/svg/base/src/nsSVGOuterSVGFrame.cpp
layout/svg/base/src/nsSVGPathGeometryFrame.cpp
layout/svg/base/src/nsSVGUtils.cpp
layout/tools/reftest/reftest.js
layout/tools/reftest/remotereftest.py
memory/mozjemalloc/jemalloc.c
mobile/android/base/GeckoApp.java
mobile/android/base/GeckoAppShell.java
mobile/android/base/Makefile.in
mobile/android/base/resources/drawable-hdpi/tabs_carat.png
mobile/android/base/resources/drawable-land-hdpi-v14/tabs_carat.png
mobile/android/base/resources/drawable-land-mdpi-v14/tabs_carat.png
mobile/android/base/resources/drawable-land-xhdpi-v14/tabs_carat.png
mobile/android/base/resources/drawable-sw600dp-hdpi/tabs_carat.png
mobile/android/base/resources/drawable-sw600dp-mdpi/tabs_carat.png
mobile/android/base/resources/drawable-sw600dp-xhdpi/tabs_carat.png
mobile/android/base/resources/drawable-xhdpi-v11/tabs_carat.png
mobile/android/base/resources/drawable-xlarge-hdpi/tabs_carat.png
mobile/android/base/resources/drawable-xlarge-mdpi/tabs_carat.png
mobile/android/base/resources/drawable-xlarge-xhdpi/tabs_carat.png
mobile/android/base/resources/drawable/tabs_carat.png
mobile/android/base/resources/xml/preferences.xml
mobile/android/base/sync/net/CompletedEntity.java
mobile/xul/chrome/content/browser.js
mobile/xul/installer/package-manifest.in
modules/libjar/nsJAR.h
modules/libjar/zipwriter/src/nsZipHeader.h
modules/libjar/zipwriter/src/nsZipWriter.h
modules/libpref/src/Preferences.cpp
netwerk/base/public/nsAsyncRedirectVerifyHelper.h
netwerk/base/src/RedirectChannelRegistrar.h
netwerk/base/src/nsChannelClassifier.h
netwerk/base/src/nsDNSPrefetch.h
netwerk/base/src/nsIOService.h
netwerk/base/src/nsIOThreadPool.cpp
netwerk/base/src/nsInputStreamPump.h
netwerk/base/src/nsPACMan.cpp
netwerk/base/src/nsPACMan.h
netwerk/base/src/nsProtocolProxyService.cpp
netwerk/base/src/nsProtocolProxyService.h
netwerk/base/src/nsServerSocket.cpp
netwerk/base/src/nsSocketTransportService2.cpp
netwerk/base/src/nsStandardURL.h
netwerk/base/src/nsStreamTransportService.cpp
netwerk/base/src/nsSyncStreamListener.h
netwerk/cache/nsCacheService.cpp
netwerk/cache/nsDeleteDir.cpp
netwerk/cache/nsDiskCacheDeviceSQL.cpp
netwerk/cache/nsDiskCacheDeviceSQL.h
netwerk/cookie/nsCookieService.cpp
netwerk/dns/nsDNSService2.cpp
netwerk/dns/nsDNSService2.h
netwerk/dns/nsEffectiveTLDService.h
netwerk/dns/nsHostResolver.cpp
netwerk/mime/nsMIMEHeaderParamImpl.cpp
netwerk/protocol/ftp/nsFTPChannel.cpp
netwerk/protocol/ftp/nsFtpControlConnection.h
netwerk/protocol/http/SpdySession2.h
netwerk/protocol/http/SpdySession3.h
netwerk/protocol/http/nsHttpChannel.cpp
netwerk/protocol/http/nsHttpConnectionMgr.h
netwerk/protocol/http/nsHttpDigestAuth.h
netwerk/protocol/http/nsHttpNTLMAuth.cpp
netwerk/protocol/viewsource/nsViewSourceChannel.h
netwerk/protocol/websocket/WebSocketChannel.cpp
netwerk/streamconv/converters/nsMultiMixedConv.h
netwerk/system/win32/nsNotifyAddrListener.cpp
netwerk/test/TestCallbacks.cpp
netwerk/test/TestCommon.h
netwerk/test/TestProtocols.cpp
netwerk/wifi/nsWifiAccessPoint.h
netwerk/wifi/nsWifiMonitor.cpp
netwerk/wifi/nsWifiMonitor.h
parser/html/nsHtml5Module.cpp
parser/html/nsHtml5StreamParser.cpp
parser/html/nsHtml5TreeOpExecutor.cpp
parser/html/nsHtml5TreeOpExecutor.h
parser/html/nsParserUtils.cpp
parser/xml/src/nsSAXXMLReader.h
rdf/base/src/nsRDFXMLSerializer.cpp
rdf/base/src/rdfTriplesSerializer.cpp
rdf/datasource/src/nsFileSystemDataSource.h
security/manager/ssl/src/SSLServerCertVerification.cpp
security/manager/ssl/src/nsKeygenThread.cpp
security/manager/ssl/src/nsNSSComponent.cpp
security/manager/ssl/src/nsNSSIOLayer.cpp
security/manager/ssl/src/nsPSMBackgroundThread.cpp
security/manager/ssl/src/nsPSMBackgroundThread.h
startupcache/StartupCache.cpp
storage/src/mozStorageConnection.cpp
storage/src/mozStorageConnection.h
testing/jetpack/jetpack-location.txt
testing/marionette/tests/Makefile.in
testing/marionette/tests/unit/head_mar.js
testing/marionette/tests/unit/test_marionette_err.js
testing/marionette/tests/unit/test_marionette_exec.js
testing/marionette/tests/unit/test_marionette_execAsync.js
testing/marionette/tests/unit/test_marionette_execjs.js
testing/marionette/tests/unit/xpcshell.ini
testing/mochitest/android-failures.json
testing/mochitest/runtests.py
testing/mochitest/runtestsremote.py
testing/mochitest/tests/SimpleTest/setup.js
testing/xpcshell/xpcshell.ini
toolkit/components/aboutmemory/content/aboutMemory.js
toolkit/components/startup/nsAppStartup.cpp
toolkit/components/telemetry/TelemetryHistograms.h
toolkit/components/telemetry/TelemetryPing.js
toolkit/components/telemetry/tests/unit/test_TelemetryPing.js
toolkit/components/url-classifier/nsUrlClassifierDBService.cpp
toolkit/content/widgets/videocontrols.xml
toolkit/mozapps/update/nsUpdateService.js
toolkit/mozapps/update/test/unit/head_update.js.in
toolkit/mozapps/update/test/unit/test_0030_general.js
toolkit/profile/nsToolkitProfileService.cpp
toolkit/system/windowsproxy/nsWindowsSystemProxySettings.cpp
uriloader/base/nsURILoader.h
uriloader/exthandler/nsExternalHelperAppService.h
uriloader/exthandler/nsExternalProtocolHandler.h
uriloader/prefetch/OfflineCacheUpdateGlue.h
uriloader/prefetch/nsOfflineCacheUpdate.cpp
uriloader/prefetch/nsOfflineCacheUpdate.h
uriloader/prefetch/nsOfflineCacheUpdateService.cpp
uriloader/prefetch/nsPrefetchService.cpp
uriloader/prefetch/nsPrefetchService.h
webapprt/linux/Makefile.in
webapprt/linux/webapprt.cpp
widget/android/AndroidBridge.cpp
widget/android/AndroidBridge.h
widget/android/GfxInfo.cpp
widget/android/nsAppShell.cpp
widget/android/nsWindow.cpp
widget/cocoa/nsChildView.h
widget/cocoa/nsChildView.mm
widget/nsGUIEvent.h
widget/windows/JumpListBuilder.cpp
widget/windows/JumpListBuilder.h
widget/windows/LSPAnnotator.cpp
widget/windows/WinTaskbar.cpp
widget/windows/WinTaskbar.h
widget/windows/nsDataObj.h
widget/windows/nsDeviceContextSpecWin.h
widget/windows/nsNativeDragSource.h
widget/windows/nsNativeDragTarget.h
widget/windows/nsTextStore.h
widget/windows/nsWinGesture.cpp
widget/windows/nsWindow.cpp
widget/windows/nsWindow.h
widget/xpwidgets/nsBaseWidget.cpp
widget/xpwidgets/nsBaseWidget.h
widget/xpwidgets/nsIdleService.cpp
xpcom/base/nsAgg.h
xpcom/base/nsCycleCollector.cpp
xpcom/base/nsMemoryReporterManager.cpp
xpcom/build/nsXPComInit.cpp
xpcom/build/nsXULAppAPI.h
xpcom/components/nsCategoryManager.h
xpcom/components/nsComponentManager.h
xpcom/ds/nsAtomTable.cpp
xpcom/ds/nsHashPropertyBag.cpp
xpcom/ds/nsINIParserImpl.cpp
xpcom/ds/nsObserverList.h
xpcom/ds/nsObserverService.h
xpcom/ds/nsStringEnumerator.cpp
xpcom/ds/nsSupportsArray.cpp
xpcom/ds/nsSupportsArray.h
xpcom/ds/nsUnicharBuffer.h
xpcom/ds/nsVariant.h
xpcom/glue/nsCycleCollectionParticipant.cpp
xpcom/glue/nsCycleCollectionParticipant.h
xpcom/glue/nsEnumeratorUtils.cpp
xpcom/glue/nsTArray.h
xpcom/glue/nsThreadUtils.cpp
xpcom/glue/nsThreadUtils.h
xpcom/idl-parser/xpidl.py
xpcom/io/nsAppFileLocationProvider.h
xpcom/io/nsDirectoryService.h
xpcom/io/nsInputStreamTee.cpp
xpcom/io/nsLocalFileUnix.cpp
xpcom/io/nsLocalFileUnix.h
xpcom/io/nsMultiplexInputStream.cpp
xpcom/io/nsPipe3.cpp
xpcom/io/nsStorageStream.cpp
xpcom/io/nsStorageStream.h
xpcom/io/nsStreamUtils.cpp
xpcom/io/nsStringStream.cpp
xpcom/io/nsUnicharInputStream.cpp
xpcom/reflect/xptinfo/src/xptiprivate.h
xpcom/threads/LazyIdleThread.cpp
xpcom/threads/LazyIdleThread.h
xpcom/threads/TimerThread.cpp
xpcom/threads/TimerThread.h
xpcom/threads/nsProcess.h
xpcom/threads/nsProcessCommon.cpp
xpcom/threads/nsThread.h
xpcom/threads/nsThreadPool.cpp
xpcom/threads/nsThreadPool.h
xpcom/threads/nsTimerImpl.h
xpfe/appshell/src/nsContentTreeOwner.cpp
xulrunner/app/nsXULRunnerApp.cpp
--- a/accessible/src/generic/Accessible.cpp
+++ b/accessible/src/generic/Accessible.cpp
@@ -644,18 +644,17 @@ Accessible::VisibilityState()
   return vstates &= ~states::INVISIBLE;
 }
 
 PRUint64
 Accessible::NativeState()
 {
   PRUint64 state = 0;
 
-  DocAccessible* document = Document();
-  if (!document || !document->IsInDocument(this))
+  if (!IsInDocument())
     state |= states::STALE;
 
   if (mContent->IsElement()) {
     nsEventStates elementState = mContent->AsElement()->State();
 
     if (elementState.HasState(NS_EVENT_STATE_INVALID))
       state |= states::INVALID;
 
--- a/accessible/src/generic/Accessible.h
+++ b/accessible/src/generic/Accessible.h
@@ -684,16 +684,21 @@ public:
    */
   static void TranslateString(const nsString& aKey, nsAString& aStringOut);
 
   /**
    * Return true if the accessible is defunct.
    */
   bool IsDefunct() const { return mFlags & eIsDefunct; }
 
+  /**
+   * Return true if the accessible is no longer in the document.
+   */
+  bool IsInDocument() const { return !(mFlags & eIsNotInDocument); }
+
 protected:
 
   //////////////////////////////////////////////////////////////////////////////
   // Initializing, cache and tree traverse methods
 
   /**
    * Cache accessible children.
    */
@@ -732,40 +737,41 @@ protected:
   inline void SetChildrenFlag(ChildrenFlags aFlag)
     { mFlags = (mFlags & ~kChildrenFlagsMask) | aFlag; }
 
   /**
    * Flags used to describe the state of this accessible.
    * @note keep these flags in sync with ChildrenFlags
    */
   enum StateFlags {
-    eIsDefunct = 1 << 2 // accessible is defunct
+    eIsDefunct = 1 << 2, // accessible is defunct
+    eIsNotInDocument = 1 << 3 // accessible is not in document
   };
 
   /**
    * Flags describing the type of this accessible.
    * @note keep these flags in sync with ChildrenFlags and StateFlags
    */
   enum AccessibleTypes {
-    eApplicationAccessible = 1 << 3,
-    eAutoCompleteAccessible = 1 << 4,
-    eAutoCompletePopupAccessible = 1 << 5,
-    eComboboxAccessible = 1 << 6,
-    eDocAccessible = 1 << 7,
-    eHyperTextAccessible = 1 << 8,
-    eHTMLFileInputAccessible = 1 << 9,
-    eHTMLListItemAccessible = 1 << 10,
-    eImageAccessible = 1 << 11,
-    eImageMapAccessible = 1 << 12,
-    eListControlAccessible = 1 << 13,
-    eMenuButtonAccessible = 1 << 14,
-    eMenuPopupAccessible = 1 << 15,
-    eRootAccessible = 1 << 16,
-    eTextLeafAccessible = 1 << 17,
-    eXULTreeAccessible = 1 << 18
+    eApplicationAccessible = 1 << 4,
+    eAutoCompleteAccessible = 1 << 5,
+    eAutoCompletePopupAccessible = 1 << 6,
+    eComboboxAccessible = 1 << 7,
+    eDocAccessible = 1 << 8,
+    eHyperTextAccessible = 1 << 9,
+    eHTMLFileInputAccessible = 1 << 10,
+    eHTMLListItemAccessible = 1 << 11,
+    eImageAccessible = 1 << 12,
+    eImageMapAccessible = 1 << 13,
+    eListControlAccessible = 1 << 14,
+    eMenuButtonAccessible = 1 << 15,
+    eMenuPopupAccessible = 1 << 16,
+    eRootAccessible = 1 << 17,
+    eTextLeafAccessible = 1 << 18,
+    eXULTreeAccessible = 1 << 19
   };
 
   //////////////////////////////////////////////////////////////////////////////
   // Miscellaneous helpers
 
   /**
    * Return ARIA role (helper method).
    */
@@ -866,16 +872,17 @@ protected:
   nsRefPtr<Accessible> mParent;
   nsTArray<nsRefPtr<Accessible> > mChildren;
   PRInt32 mIndexInParent;
 
   static const PRUint32 kChildrenFlagsMask =
     eChildrenUninitialized | eMixedChildren | eEmbeddedChildren;
 
   PRUint32 mFlags;
+  friend class DocAccessible;
 
   nsAutoPtr<EmbeddedObjCollector> mEmbeddedObjCollector;
   PRInt32 mIndexOfEmbeddedChild;
   friend class EmbeddedObjCollector;
 
   nsAutoPtr<AccGroupInfo> mGroupInfo;
   friend class AccGroupInfo;
 
--- a/accessible/src/generic/DocAccessible.cpp
+++ b/accessible/src/generic/DocAccessible.cpp
@@ -2015,16 +2015,18 @@ DocAccessible::CacheChildrenInSubtree(Ac
       FireDelayedAccessibleEvent(nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_COMPLETE,
                                  aRoot->GetContent());
   }
 }
 
 void
 DocAccessible::UncacheChildrenInSubtree(Accessible* aRoot)
 {
+  aRoot->mFlags |= eIsNotInDocument;
+
   if (aRoot->IsElement())
     RemoveDependentIDsFor(aRoot);
 
   PRUint32 count = aRoot->ContentChildCount();
   for (PRUint32 idx = 0; idx < count; idx++)
     UncacheChildrenInSubtree(aRoot->ContentChildAt(idx));
 
   if (aRoot->IsPrimaryForNode() &&
--- a/accessible/src/generic/DocAccessible.h
+++ b/accessible/src/generic/DocAccessible.h
@@ -238,28 +238,16 @@ public:
 
   /**
    * Return whether the given DOM node has an accessible or not.
    */
   bool HasAccessible(nsINode* aNode) const
     { return GetAccessible(aNode); }
 
   /**
-   * Return true if the given accessible is in document.
-   */
-  bool IsInDocument(Accessible* aAccessible) const
-  {
-    Accessible* acc = aAccessible;
-    while (acc && !acc->IsPrimaryForNode())
-      acc = acc->Parent();
-
-    return acc ? mNodeToAccessibleMap.Get(acc->GetNode()) : false;
-  }
-
-  /**
    * Return the cached accessible by the given unique ID within this document.
    *
    * @note   the unique ID matches with the uniqueID() of nsAccessNode
    *
    * @param  aUniqueID  [in] the unique ID used to cache the node.
    */
   Accessible* GetAccessibleByUniqueID(void* aUniqueID)
   {
--- a/accessible/src/html/HTMLCanvasAccessible.cpp
+++ b/accessible/src/html/HTMLCanvasAccessible.cpp
@@ -6,17 +6,19 @@
 #include "HTMLCanvasAccessible.h"
 
 #include "Role.h"
 
 using namespace mozilla::a11y;
 
 HTMLCanvasAccessible::
   HTMLCanvasAccessible(nsIContent* aContent, DocAccessible* aDoc) :
-  HyperTextAccessible(aContent, aDoc)
+  HyperTextAccessibleWrap(aContent, aDoc)
 {
 }
 
+NS_IMPL_ISUPPORTS_INHERITED0(HTMLCanvasAccessible, HyperTextAccessible)
+
 role
 HTMLCanvasAccessible::NativeRole()
 {
   return roles::CANVAS;
 }
--- a/accessible/src/html/HTMLCanvasAccessible.h
+++ b/accessible/src/html/HTMLCanvasAccessible.h
@@ -1,30 +1,33 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "HyperTextAccessible.h"
-
 #ifndef mozilla_a11y_HTMLCanvasAccessible_h__
 #define mozilla_a11y_HTMLCanvasAccessible_h__
 
+#include "HyperTextAccessibleWrap.h"
+
 namespace mozilla {
 namespace a11y {
 
 /**
  * HTML canvas accessible (html:canvas).
  */
-class HTMLCanvasAccessible : public HyperTextAccessible
+class HTMLCanvasAccessible : public HyperTextAccessibleWrap
 {
 public:
   HTMLCanvasAccessible(nsIContent* aContent, DocAccessible* aDoc);
   virtual ~HTMLCanvasAccessible() { }
 
+  // nsISupports
+  NS_DECL_ISUPPORTS_INHERITED
+
   // Accessible
   virtual a11y::role NativeRole();
 };
 
 } // namespace a11y
 } // namespace mozilla
 
 #endif
--- a/accessible/src/jsat/AccessFu.jsm
+++ b/accessible/src/jsat/AccessFu.jsm
@@ -29,43 +29,41 @@ var AccessFu = {
    * @param {boolean} aForceEnabled Skip platform accessibility check and enable
    *  AccessFu.
    */
   attach: function attach(aWindow) {
     if (this.chromeWin)
       // XXX: only supports attaching to one window now.
       throw new Error('Only one window could be attached to AccessFu');
 
-    dump('AccessFu attach!! ' + Services.appinfo.OS + '\n');
+    dump('[AccessFu] attach\n');
     this.chromeWin = aWindow;
     this.presenters = [];
 
     this.prefsBranch = Cc['@mozilla.org/preferences-service;1']
       .getService(Ci.nsIPrefService).getBranch('accessibility.accessfu.');
     this.prefsBranch.addObserver('activate', this, false);
+    this.prefsBranch.addObserver('explorebytouch', this, false);
 
-    let accessPref = ACCESSFU_DISABLE;
-    try {
-      accessPref = this.prefsBranch.getIntPref('activate');
-    } catch (x) {
-    }
+    if (Services.appinfo.OS == 'Android')
+      Services.obs.addObserver(this, 'Accessibility:Settings', false);
 
-    this._processPreferences(accessPref);
+    this._processPreferences();
   },
 
   /**
    * Start AccessFu mode, this primarily means controlling the virtual cursor
    * with arrow keys.
    */
   _enable: function _enable() {
     if (this._enabled)
       return;
     this._enabled = true;
 
-    dump('AccessFu enable');
+    dump('[AccessFu] enable\n');
     this.addPresenter(new VisualPresenter());
 
     // Implicitly add the Android presenter on Android.
     if (Services.appinfo.OS == 'Android')
       this.addPresenter(new AndroidPresenter());
 
     VirtualCursorController.attach(this.chromeWin);
 
@@ -80,54 +78,63 @@ var AccessFu = {
   /**
    * Disable AccessFu and return to default interaction mode.
    */
   _disable: function _disable() {
     if (!this._enabled)
       return;
     this._enabled = false;
 
-    dump('AccessFu disable');
+    dump('[AccessFu] disable\n');
 
     this.presenters.forEach(function(p) { p.detach(); });
     this.presenters = [];
 
     VirtualCursorController.detach();
 
     Services.obs.removeObserver(this, 'accessible-event');
     this.chromeWin.removeEventListener('DOMActivate', this, true);
     this.chromeWin.removeEventListener('resize', this, true);
     this.chromeWin.removeEventListener('scroll', this, true);
     this.chromeWin.removeEventListener('TabOpen', this, true);
     this.chromeWin.removeEventListener('focus', this, true);
   },
 
-  _processPreferences: function _processPreferences(aPref) {
+  _processPreferences: function _processPreferences(aEnabled, aTouchEnabled) {
+    let accessPref = ACCESSFU_DISABLE;
+    try {
+      accessPref = (aEnabled == undefined) ?
+        this.prefsBranch.getIntPref('activate') : aEnabled;
+    } catch (x) {
+    }
+
+    let ebtPref = ACCESSFU_DISABLE;
+    try {
+      ebtPref = (aTouchEnabled == undefined) ?
+        this.prefsBranch.getIntPref('explorebytouch') : aTouchEnabled;
+    } catch (x) {
+    }
+
     if (Services.appinfo.OS == 'Android') {
-      if (aPref == ACCESSFU_AUTO) {
-        if (!this._observingSystemSettings) {
-          Services.obs.addObserver(this, 'Accessibility:Settings', false);
-          this._observingSystemSettings = true;
-        }
+      if (accessPref == ACCESSFU_AUTO) {
         Cc['@mozilla.org/android/bridge;1'].
           getService(Ci.nsIAndroidBridge).handleGeckoMessage(
             JSON.stringify({ gecko: { type: 'Accessibility:Ready' } }));
         return;
       }
-
-      if (this._observingSystemSettings) {
-        Services.obs.removeObserver(this, 'Accessibility:Settings');
-        this._observingSystemSettings = false;
-      }
     }
 
-    if (aPref == ACCESSFU_ENABLE)
+    if (accessPref == ACCESSFU_ENABLE)
       this._enable();
     else
       this._disable();
+
+    VirtualCursorController.exploreByTouch = ebtPref == ACCESSFU_ENABLE;
+    dump('[AccessFu] Explore by touch: ' +
+          VirtualCursorController.exploreByTouch + '\n');
   },
 
   addPresenter: function addPresenter(presenter) {
     this.presenters.push(presenter);
     presenter.attach(this.chromeWin);
   },
 
   handleEvent: function handleEvent(aEvent) {
@@ -180,32 +187,30 @@ var AccessFu = {
         break;
       }
     }
   },
 
   observe: function observe(aSubject, aTopic, aData) {
     switch (aTopic) {
       case 'Accessibility:Settings':
-        if (JSON.parse(aData).enabled)
-          this._enable();
-        else
-          this._disable();
+        this._processPreferences(JSON.parse(aData).enabled + 0,
+                                 JSON.parse(aData).exploreByTouch + 0);
         break;
       case 'nsPref:changed':
-        if (aData == 'activate')
-          this._processPreferences(this.prefsBranch.getIntPref('activate'));
+        this._processPreferences(this.prefsBranch.getIntPref('activate'),
+                                 this.prefsBranch.getIntPref('explorebytouch'));
         break;
       case 'accessible-event':
         let event;
         try {
           event = aSubject.QueryInterface(Ci.nsIAccessibleEvent);
           this._handleAccEvent(event);
         } catch (ex) {
-          dump(ex);
+          dump('[AccessFu] ' + ex + '\n');
           return;
         }
     }
   },
 
   _handleAccEvent: function _handleAccEvent(aEvent) {
     switch (aEvent.eventType) {
       case Ci.nsIAccessibleEvent.EVENT_VIRTUALCURSOR_CHANGED:
@@ -388,20 +393,17 @@ var AccessFu = {
 
     return location.protocol != "about:";
   },
 
   // A hash of documents that don't yet have an accessible tree.
   _pendingDocuments: {},
 
   // So we don't enable/disable twice
-  _enabled: false,
-
-  // Observing accessibility settings
-  _observingSystemSettings: false
+  _enabled: false
 };
 
 function getAccessible(aNode) {
   try {
     return Cc['@mozilla.org/accessibleRetrieval;1'].
       getService(Ci.nsIAccessibleRetrieval).getAccessibleFor(aNode);
   } catch (e) {
     return null;
--- a/accessible/src/jsat/VirtualCursorController.jsm
+++ b/accessible/src/jsat/VirtualCursorController.jsm
@@ -12,21 +12,409 @@ const Cr = Components.results;
 var EXPORTED_SYMBOLS = ['VirtualCursorController'];
 
 Cu.import('resource://gre/modules/XPCOMUtils.jsm');
 Cu.import('resource://gre/modules/Services.jsm');
 
 var gAccRetrieval = Cc['@mozilla.org/accessibleRetrieval;1'].
   getService(Ci.nsIAccessibleRetrieval);
 
+var TraversalRules = {
+  Simple: {
+    getMatchRoles: function SimpleTraversalRule_getmatchRoles(aRules) {
+      aRules.value = this._matchRoles;
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function SimpleTraversalRule_match(aAccessible) {
+      switch (aAccessible.role) {
+      case Ci.nsIAccessibleRole.ROLE_COMBOBOX:
+        // We don't want to ignore the subtree because this is often
+        // where the list box hangs out.
+        return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+      case Ci.nsIAccessibleRole.ROLE_TEXT_LEAF:
+        {
+          // Nameless text leaves are boring, skip them.
+          let name = aAccessible.name;
+          if (name && name.trim())
+            return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+          else
+            return Ci.nsIAccessibleTraversalRule.FILTER_IGNORE;
+        }
+      case Ci.nsIAccessibleRole.ROLE_LINK:
+        // If the link has children we should land on them instead.
+        // Image map links don't have children so we need to match those.
+        if (aAccessible.childCount == 0)
+          return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+        else
+          return Ci.nsIAccessibleTraversalRule.FILTER_IGNORE;
+      default:
+        // Ignore the subtree, if there is one. So that we don't land on
+        // the same content that was already presented by its parent.
+        return Ci.nsIAccessibleTraversalRule.FILTER_MATCH |
+          Ci.nsIAccessibleTraversalRule.FILTER_IGNORE_SUBTREE;
+      }
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule]),
+
+    _matchRoles: [
+      Ci.nsIAccessibleRole.ROLE_MENUITEM,
+      Ci.nsIAccessibleRole.ROLE_LINK,
+      Ci.nsIAccessibleRole.ROLE_PAGETAB,
+      Ci.nsIAccessibleRole.ROLE_GRAPHIC,
+      // XXX: Find a better solution for ROLE_STATICTEXT.
+      // It allows to filter list bullets but at the same time it
+      // filters CSS generated content too as an unwanted side effect.
+      // Ci.nsIAccessibleRole.ROLE_STATICTEXT,
+      Ci.nsIAccessibleRole.ROLE_TEXT_LEAF,
+      Ci.nsIAccessibleRole.ROLE_PUSHBUTTON,
+      Ci.nsIAccessibleRole.ROLE_CHECKBUTTON,
+      Ci.nsIAccessibleRole.ROLE_RADIOBUTTON,
+      Ci.nsIAccessibleRole.ROLE_COMBOBOX,
+      Ci.nsIAccessibleRole.ROLE_PROGRESSBAR,
+      Ci.nsIAccessibleRole.ROLE_BUTTONDROPDOWN,
+      Ci.nsIAccessibleRole.ROLE_BUTTONMENU,
+      Ci.nsIAccessibleRole.ROLE_CHECK_MENU_ITEM,
+      Ci.nsIAccessibleRole.ROLE_PASSWORD_TEXT,
+      Ci.nsIAccessibleRole.ROLE_RADIO_MENU_ITEM,
+      Ci.nsIAccessibleRole.ROLE_TOGGLE_BUTTON,
+      Ci.nsIAccessibleRole.ROLE_ENTRY
+    ]
+  },
+
+  Anchor: {
+    getMatchRoles: function AnchorTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_LINK];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function AnchorTraversalRule_match(aAccessible)
+    {
+      // We want to ignore links, only focus named anchors.
+      let state = {};
+      let extraState = {};
+      aAccessible.getState(state, extraState);
+      if (state.value & Ci.nsIAccessibleStates.STATE_LINKED) {
+        return Ci.nsIAccessibleTraversalRule.FILTER_IGNORE;
+      } else {
+        return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+      }
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  Button: {
+    getMatchRoles: function ButtonTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = this._matchRoles;
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function ButtonTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule]),
+
+    _matchRoles: [
+      Ci.nsIAccessibleRole.ROLE_PUSHBUTTON,
+      Ci.nsIAccessibleRole.ROLE_SPINBUTTON,
+      Ci.nsIAccessibleRole.ROLE_TOGGLE_BUTTON,
+      Ci.nsIAccessibleRole.ROLE_BUTTONDROPDOWN,
+      Ci.nsIAccessibleRole.ROLE_BUTTONDROPDOWNGRID
+    ]
+  },
+
+  Combobox: {
+    getMatchRoles: function ComboboxTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_COMBOBOX,
+                      Ci.nsIAccessibleRole.ROLE_LISTBOX];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function ComboboxTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  Entry: {
+    getMatchRoles: function EntryTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_ENTRY,
+                      Ci.nsIAccessibleRole.ROLE_PASSWORD_TEXT];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function EntryTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  FormElement: {
+    getMatchRoles: function FormElementTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = this._matchRoles;
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function FormElementTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule]),
+
+    _matchRoles: [
+      Ci.nsIAccessibleRole.ROLE_PUSHBUTTON,
+      Ci.nsIAccessibleRole.ROLE_SPINBUTTON,
+      Ci.nsIAccessibleRole.ROLE_TOGGLE_BUTTON,
+      Ci.nsIAccessibleRole.ROLE_BUTTONDROPDOWN,
+      Ci.nsIAccessibleRole.ROLE_BUTTONDROPDOWNGRID,
+      Ci.nsIAccessibleRole.ROLE_COMBOBOX,
+      Ci.nsIAccessibleRole.ROLE_LISTBOX,
+      Ci.nsIAccessibleRole.ROLE_ENTRY,
+      Ci.nsIAccessibleRole.ROLE_PASSWORD_TEXT,
+      Ci.nsIAccessibleRole.ROLE_PAGETAB,
+      Ci.nsIAccessibleRole.ROLE_RADIOBUTTON,
+      Ci.nsIAccessibleRole.ROLE_RADIO_MENU_ITEM,
+      Ci.nsIAccessibleRole.ROLE_SLIDER,
+      Ci.nsIAccessibleRole.ROLE_CHECKBUTTON,
+      Ci.nsIAccessibleRole.ROLE_CHECK_MENU_ITEM
+    ]
+  },
+
+  Graphic: {
+    getMatchRoles: function GraphicTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_GRAPHIC];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function GraphicTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  Heading: {
+    getMatchRoles: function HeadingTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_HEADING];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function HeadingTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  ListItem: {
+    getMatchRoles: function ListItemTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_LISTITEM,
+                      Ci.nsIAccessibleRole.ROLE_TERM];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function ListItemTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  Link: {
+    getMatchRoles: function LinkTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_LINK];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function LinkTraversalRule_match(aAccessible)
+    {
+      // We want to ignore anchors, only focus real links.
+      let state = {};
+      let extraState = {};
+      aAccessible.getState(state, extraState);
+      if (state.value & Ci.nsIAccessibleStates.STATE_LINKED) {
+        return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+      } else {
+        return Ci.nsIAccessibleTraversalRule.FILTER_IGNORE;
+      }
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  List: {
+    getMatchRoles: function ListTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_LIST,
+                      Ci.nsIAccessibleRole.ROLE_DEFINITION_LIST];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function ListTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  PageTab: {
+    getMatchRoles: function PageTabTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_PAGETAB];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function PageTabTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  RadioButton: {
+    getMatchRoles: function RadioButtonTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_RADIOBUTTON,
+                      Ci.nsIAccessibleRole.ROLE_RADIO_MENU_ITEM];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function RadioButtonTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  Separator: {
+    getMatchRoles: function SeparatorTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_SEPARATOR];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function SeparatorTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  Table: {
+    getMatchRoles: function TableTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_TABLE];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function TableTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  },
+
+  Checkbox: {
+    getMatchRoles: function CheckboxTraversalRule_getMatchRoles(aRules)
+    {
+      aRules.value = [Ci.nsIAccessibleRole.ROLE_CHECKBUTTON,
+                      Ci.nsIAccessibleRole.ROLE_CHECK_MENU_ITEM];
+      return aRules.value.length;
+    },
+
+    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
+      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
+
+    match: function CheckboxTraversalRule_match(aAccessible)
+    {
+      return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
+    },
+
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule])
+  }
+};
+
 var VirtualCursorController = {
   NOT_EDITABLE: 0,
   SINGLE_LINE_EDITABLE: 1,
   MULTI_LINE_EDITABLE: 2,
 
+  explorebytouch: false,
+
   attach: function attach(aWindow) {
     this.chromeWin = aWindow;
     this.chromeWin.document.addEventListener('keypress', this, true);
   },
 
   detach: function detach() {
     this.chromeWin.document.removeEventListener('keypress', this, true);
   },
@@ -40,16 +428,33 @@ var VirtualCursorController = {
     }
   },
 
   handleEvent: function handleEvent(aEvent) {
     let document = this._getBrowserApp().selectedBrowser.contentDocument;
     let target = aEvent.target;
 
     switch (aEvent.keyCode) {
+      case 0:
+        // an alphanumeric key was pressed, handle it separately.
+        // If it was pressed with either alt or ctrl, just pass through.
+        // If it was pressed with meta, pass the key on without the meta.
+        if (this._isEditableText(target) ||
+            aEvent.ctrlKey || aEvent.altKey || aEvent.metaKey)
+          return;
+
+        let key = String.fromCharCode(aEvent.charCode);
+        let methodName = '', rule = {};
+        try {
+          [methodName, rule] = this.keyMap[key];
+        } catch (x) {
+          return;
+        }
+        this[methodName](document, false, rule);
+        break;
       case aEvent.DOM_VK_END:
         this.moveForward(document, true);
         break;
       case aEvent.DOM_VK_HOME:
         this.moveBackward(document, true);
         break;
       case aEvent.DOM_VK_RIGHT:
         if (this._isEditableText(target)) {
@@ -109,40 +514,40 @@ var VirtualCursorController = {
       return this.SINGLE_LINE_EDITABLE;
 
     if (aElement instanceof Ci.nsIDOMHTMLTextAreaElement)
       return this.MULTI_LINE_EDITABLE;
 
     return this.NOT_EDITABLE;
   },
 
-  moveForward: function moveForward(document, last) {
-    let virtualCursor = this.getVirtualCursor(document);
-    if (last) {
-      virtualCursor.moveLast(this.SimpleTraversalRule);
+  moveForward: function moveForward(aDocument, aLast, aRule) {
+    let virtualCursor = this.getVirtualCursor(aDocument);
+    if (aLast) {
+      virtualCursor.moveLast(TraversalRules.Simple);
     } else {
       try {
-        virtualCursor.moveNext(this.SimpleTraversalRule);
+        virtualCursor.moveNext(aRule || TraversalRules.Simple);
       } catch (x) {
         this.moveCursorToObject(
-          gAccRetrieval.getAccessibleFor(document.activeElement));
+            gAccRetrieval.getAccessibleFor(aDocument.activeElement), aRule);
       }
     }
   },
 
-  moveBackward: function moveBackward(document, first) {
-    let virtualCursor = this.getVirtualCursor(document);
-    if (first) {
-      virtualCursor.moveFirst(this.SimpleTraversalRule);
+  moveBackward: function moveBackward(aDocument, aFirst, aRule) {
+    let virtualCursor = this.getVirtualCursor(aDocument);
+    if (aFirst) {
+      virtualCursor.moveFirst(TraversalRules.Simple);
     } else {
       try {
-        virtualCursor.movePrevious(this.SimpleTraversalRule);
+        virtualCursor.movePrevious(aRule || TraversalRules.Simple);
       } catch (x) {
         this.moveCursorToObject(
-          gAccRetrieval.getAccessibleFor(document.activeElement));
+            gAccRetrieval.getAccessibleFor(aDocument.activeElement), aRule);
       }
     }
   },
 
   activateCurrent: function activateCurrent(document) {
     let virtualCursor = this.getVirtualCursor(document);
     let acc = virtualCursor.position;
 
@@ -155,18 +560,18 @@ var VirtualCursorController = {
       // engine could expose nsCoreUtiles::DispatchMouseEvent()?
       let docAcc = gAccRetrieval.getAccessibleFor(this.chromeWin.document);
       let docX = {}, docY = {}, docW = {}, docH = {};
       docAcc.getBounds(docX, docY, docW, docH);
 
       let objX = {}, objY = {}, objW = {}, objH = {};
       acc.getBounds(objX, objY, objW, objH);
 
-      let x = Math.round((objX.value - docX.value) + objW.value/2);
-      let y = Math.round((objY.value - docY.value) + objH.value/2);
+      let x = Math.round((objX.value - docX.value) + objW.value / 2);
+      let y = Math.round((objY.value - docY.value) + objH.value / 2);
 
       let cwu = this.chromeWin.QueryInterface(Ci.nsIInterfaceRequestor).
         getInterface(Ci.nsIDOMWindowUtils);
       cwu.sendMouseEventToWindow('mousedown', x, y, 0, 1, 0, false);
       cwu.sendMouseEventToWindow('mouseup', x, y, 0, 1, 0, false);
     }
   },
 
@@ -181,79 +586,46 @@ var VirtualCursorController = {
       let vc = null;
       try {
         vc = doc.QueryInterface(Ci.nsIAccessibleCursorable).virtualCursor;
       } catch (x) {
         doc = doc.parentDocument;
         continue;
       }
       if (vc)
-        vc.moveNext(aRule || this.SimpleTraversalRule, aAccessible, true);
+        vc.moveNext(aRule || TraversalRules.Simple, aAccessible, true);
       break;
     }
   },
 
-  SimpleTraversalRule: {
-    getMatchRoles: function SimpleTraversalRule_getmatchRoles(aRules) {
-      aRules.value = this._matchRoles;
-      return this._matchRoles.length;
-    },
-
-    preFilter: Ci.nsIAccessibleTraversalRule.PREFILTER_DEFUNCT |
-      Ci.nsIAccessibleTraversalRule.PREFILTER_INVISIBLE,
-
-    match: function SimpleTraversalRule_match(aAccessible) {
-      switch (aAccessible.role) {
-      case Ci.nsIAccessibleRole.ROLE_COMBOBOX:
-        // We don't want to ignore the subtree because this is often
-        // where the list box hangs out.
-        return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
-      case Ci.nsIAccessibleRole.ROLE_TEXT_LEAF:
-        {
-          // Nameless text leaves are boring, skip them.
-          let name = aAccessible.name;
-          if (name && name.trim())
-            return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
-          else
-            return Ci.nsIAccessibleTraversalRule.FILTER_IGNORE;
-        }
-      case Ci.nsIAccessibleRole.ROLE_LINK:
-        // If the link has children we should land on them instead.
-        // Image map links don't have children so we need to match those.
-        if (aAccessible.childCount == 0)
-          return Ci.nsIAccessibleTraversalRule.FILTER_MATCH;
-        else
-          return Ci.nsIAccessibleTraversalRule.FILTER_IGNORE;
-      default:
-        // Ignore the subtree, if there is one. So that we don't land on
-        // the same content that was already presented by its parent.
-        return Ci.nsIAccessibleTraversalRule.FILTER_MATCH |
-          Ci.nsIAccessibleTraversalRule.FILTER_IGNORE_SUBTREE;
-      }
-    },
-
-    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessibleTraversalRule]),
-
-    _matchRoles: [
-      Ci.nsIAccessibleRole.ROLE_MENUITEM,
-      Ci.nsIAccessibleRole.ROLE_LINK,
-      Ci.nsIAccessibleRole.ROLE_PAGETAB,
-      Ci.nsIAccessibleRole.ROLE_GRAPHIC,
-      // XXX: Find a better solution for ROLE_STATICTEXT.
-      // It allows to filter list bullets but at the same time it
-      // filters CSS generated content too as an unwanted side effect.
-      // Ci.nsIAccessibleRole.ROLE_STATICTEXT,
-      Ci.nsIAccessibleRole.ROLE_TEXT_LEAF,
-      Ci.nsIAccessibleRole.ROLE_PUSHBUTTON,
-      Ci.nsIAccessibleRole.ROLE_CHECKBUTTON,
-      Ci.nsIAccessibleRole.ROLE_RADIOBUTTON,
-      Ci.nsIAccessibleRole.ROLE_COMBOBOX,
-      Ci.nsIAccessibleRole.ROLE_PROGRESSBAR,
-      Ci.nsIAccessibleRole.ROLE_BUTTONDROPDOWN,
-      Ci.nsIAccessibleRole.ROLE_BUTTONMENU,
-      Ci.nsIAccessibleRole.ROLE_CHECK_MENU_ITEM,
-      Ci.nsIAccessibleRole.ROLE_PASSWORD_TEXT,
-      Ci.nsIAccessibleRole.ROLE_RADIO_MENU_ITEM,
-      Ci.nsIAccessibleRole.ROLE_TOGGLE_BUTTON,
-      Ci.nsIAccessibleRole.ROLE_ENTRY
-    ]
+  keyMap: {
+    a: ['moveForward', TraversalRules.Anchor],
+    A: ['moveBackward', TraversalRules.Anchor],
+    b: ['moveForward', TraversalRules.Button],
+    B: ['moveBackward', TraversalRules.Button],
+    c: ['moveForward', TraversalRules.Combobox],
+    C: ['moveBackward', TraversalRules.Combobox],
+    e: ['moveForward', TraversalRules.Entry],
+    E: ['moveBackward', TraversalRules.Entry],
+    f: ['moveForward', TraversalRules.FormElement],
+    F: ['moveBackward', TraversalRules.FormElement],
+    g: ['moveForward', TraversalRules.Graphic],
+    G: ['moveBackward', TraversalRules.Graphic],
+    h: ['moveForward', TraversalRules.Heading],
+    H: ['moveBackward', TraversalRules.Heading],
+    i: ['moveForward', TraversalRules.ListItem],
+    I: ['moveBackward', TraversalRules.ListItem],
+    k: ['moveForward', TraversalRules.Link],
+    K: ['moveBackward', TraversalRules.Link],
+    l: ['moveForward', TraversalRules.List],
+    L: ['moveBackward', TraversalRules.List],
+    p: ['moveForward', TraversalRules.PageTab],
+    P: ['moveBackward', TraversalRules.PageTab],
+    r: ['moveForward', TraversalRules.RadioButton],
+    R: ['moveBackward', TraversalRules.RadioButton],
+    s: ['moveForward', TraversalRules.Separator],
+    S: ['moveBackward', TraversalRules.Separator],
+    t: ['moveForward', TraversalRules.Table],
+    T: ['moveBackward', TraversalRules.Table],
+    x: ['moveForward', TraversalRules.Checkbox],
+    X: ['moveBackward', TraversalRules.Checkbox]
   }
 };
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -488,8 +488,11 @@ pref("device.storage.enabled", true);
 
 pref("media.plugins.enabled", true);
 
 // Disable printing (particularly, window.print())
 pref("dom.disable_window_print", true);
 
 // Disable window.showModalDialog
 pref("dom.disable_window_showModalDialog", true);
+
+// Turns on gralloc-based direct texturing for Gonk
+pref("gfx.gralloc.enabled", false);
--- a/b2g/chrome/content/shell.js
+++ b/b2g/chrome/content/shell.js
@@ -575,8 +575,78 @@ window.addEventListener('ContentStart', 
   });
 
   window.addEventListener('unload', function removeIdleObjects() {
     Services.idle.removeIdleObserver(idleHandler, idleTimeout);
     power.removeWakeLockListener(wakeLockHandler);
   });
 })();
 
+// This is the backend for Gaia's screenshot feature.
+// Gaia requests a screenshot by sending a mozContentEvent with
+// detail.type set to 'save-screenshot'.  Then we take a screenshot
+// save it in device storage (external) and send a mozChromeEvent with
+// detail.type set to 'saved-screenshot' and detail.filename set to
+// the filename.
+window.addEventListener('ContentStart', function ss_onContentStart() {
+  content.addEventListener('mozContentEvent', function ss_onMozContentEvent(e) {
+    if (e.detail.type !== 'save-screenshot')
+      return;
+
+    try {
+      var canvas = document.createElementNS('http://www.w3.org/1999/xhtml',
+                                            'canvas');
+      var width = window.innerWidth;
+      var height = window.innerHeight;
+      canvas.setAttribute('width', width);
+      canvas.setAttribute('height', height);
+
+      var context = canvas.getContext('2d');
+      var flags =
+        context.DRAWWINDOW_DRAW_CARET |
+        context.DRAWWINDOW_DRAW_VIEW |
+        context.DRAWWINDOW_USE_WIDGET_LAYERS;
+      context.drawWindow(window, 0, 0, width, height,
+                         'rgb(255,255,255)', flags);
+
+      var filename = 'screenshots/' +
+        new Date().toISOString().slice(0,-5).replace(/[:T]/g, '-') +
+        '.png';
+
+      var file = canvas.mozGetAsFile(filename, 'image/png');
+      var storage = navigator.getDeviceStorage('pictures')[0];
+      if (!storage) { // If we don't have an SD card to save to, send an error
+        shell.sendEvent(content, 'mozChromeEvent', {
+          type: 'save-screenshot-no-card'
+        });
+        return;
+      }
+
+      var saveRequest = storage.addNamed(file, filename);
+      saveRequest.onsuccess = function ss_onsuccess() {
+        try {
+          shell.sendEvent(content, 'mozChromeEvent', {
+            type: 'save-screenshot-success',
+            filename: filename
+          });
+        } catch(e) {
+          dump('exception in onsuccess ' + e + '\n');
+        }
+      };
+      saveRequest.onerror = function ss_onerror() {
+        try {
+          shell.sendEvent(content, 'mozChromeEvent', {
+            type: 'save-screenshot-error',
+            error: saveRequest.error.name
+          });
+        } catch(e) {
+          dump('exception in onerror ' + e + '\n');
+        }
+      };
+    } catch(e) {
+      dump('exception while saving screenshot: ' + e + '\n');
+      shell.sendEvent(content, 'mozChromeEvent', {
+        type: 'save-screenshot-error',
+        error: String(e)
+      });
+    }
+  });
+});
--- a/b2g/installer/package-manifest.in
+++ b/b2g/installer/package-manifest.in
@@ -172,16 +172,17 @@
 @BINPATH@/components/dom_notification.xpt
 @BINPATH@/components/dom_html.xpt
 @BINPATH@/components/dom_indexeddb.xpt
 @BINPATH@/components/dom_offline.xpt
 @BINPATH@/components/dom_json.xpt
 #ifdef MOZ_B2G_RIL
 @BINPATH@/components/dom_mms.xpt
 #endif
+@BINPATH@/components/dom_browserelement.xpt
 @BINPATH@/components/dom_power.xpt
 @BINPATH@/components/dom_range.xpt
 @BINPATH@/components/dom_settings.xpt
 @BINPATH@/components/dom_sidebar.xpt
 @BINPATH@/components/dom_sms.xpt
 @BINPATH@/components/dom_storage.xpt
 @BINPATH@/components/dom_stylesheets.xpt
 @BINPATH@/components/dom_threads.xpt
--- a/browser/app/nsBrowserApp.cpp
+++ b/browser/app/nsBrowserApp.cpp
@@ -85,26 +85,28 @@ public:
 
 XRE_GetFileFromPathType XRE_GetFileFromPath;
 XRE_CreateAppDataType XRE_CreateAppData;
 XRE_FreeAppDataType XRE_FreeAppData;
 #ifdef XRE_HAS_DLL_BLOCKLIST
 XRE_SetupDllBlocklistType XRE_SetupDllBlocklist;
 #endif
 XRE_TelemetryAccumulateType XRE_TelemetryAccumulate;
+XRE_StartupTimelineRecordType XRE_StartupTimelineRecord;
 XRE_mainType XRE_main;
 
 static const nsDynamicFunctionLoad kXULFuncs[] = {
     { "XRE_GetFileFromPath", (NSFuncPtr*) &XRE_GetFileFromPath },
     { "XRE_CreateAppData", (NSFuncPtr*) &XRE_CreateAppData },
     { "XRE_FreeAppData", (NSFuncPtr*) &XRE_FreeAppData },
 #ifdef XRE_HAS_DLL_BLOCKLIST
     { "XRE_SetupDllBlocklist", (NSFuncPtr*) &XRE_SetupDllBlocklist },
 #endif
     { "XRE_TelemetryAccumulate", (NSFuncPtr*) &XRE_TelemetryAccumulate },
+    { "XRE_StartupTimelineRecord", (NSFuncPtr*) &XRE_StartupTimelineRecord },
     { "XRE_main", (NSFuncPtr*) &XRE_main },
     { nsnull, nsnull }
 };
 
 static int do_main(int argc, char* argv[])
 {
   nsCOMPtr<nsIFile> appini;
   nsresult rv;
@@ -184,18 +186,41 @@ bool IsPrefetchDisabledViaService()
   RegQueryValueExW(baseKey, L"FFPrefetchDisabled", 0, NULL,
                    reinterpret_cast<LPBYTE>(&disabledValue),
                    &disabledValueSize);
   RegCloseKey(baseKey);
   return disabledValue == 1;
 }
 #endif
 
+/* Local implementation of PR_Now, since the executable can't depend on NSPR */
+static PRTime _PR_Now()
+{
+#ifdef XP_WIN
+  MOZ_STATIC_ASSERT(sizeof(PRTime) == sizeof(FILETIME), "PRTime must have the same size as FILETIME");
+  FILETIME ft;
+  GetSystemTimeAsFileTime(&ft);
+  PRTime now;
+  CopyMemory(&now, &ft, sizeof(PRTime));
+#ifdef __GNUC__
+  return (now - 116444736000000000LL) / 10LL;
+#else
+  return (now - 116444736000000000i64) / 10i64;
+#endif
+
+#else
+  struct timeval tm;
+  gettimeofday(&tm, 0);
+  return (((PRTime)tm.tv_sec * 1000000LL) + (PRTime)tm.tv_usec);
+#endif
+}
+
 int main(int argc, char* argv[])
 {
+  PRTime start = _PR_Now();
   char exePath[MAXPATHLEN];
 
 #ifdef XP_MACOSX
   TriggerQuirks();
 #endif
 
   nsresult rv = mozilla::BinaryPath::Get(argv[0], exePath);
   if (NS_FAILED(rv)) {
@@ -212,34 +237,24 @@ int main(int argc, char* argv[])
   int gotCounters;
 #if defined(XP_UNIX)
   struct rusage initialRUsage;
   gotCounters = !getrusage(RUSAGE_SELF, &initialRUsage);
 #elif defined(XP_WIN)
   // Don't change the order of these enumeration constants, the order matters
   // for reporting telemetry data.  If new values are added adjust the
   // STARTUP_USING_PRELOAD histogram.
-  enum PreloadReason { PRELOAD_NONE, PRELOAD_SERVICE, PRELOAD_IOCOUNT };
+  enum PreloadReason { PRELOAD_NONE, PRELOAD_SERVICE };
   PreloadReason preloadReason = PRELOAD_NONE;
 
-  // GetProcessIoCounters().ReadOperationCount seems to have little to
-  // do with actual read operations. It reports 0 or 1 at this stage
-  // in the program. Luckily 1 coincides with when prefetch is
-  // enabled. If Windows prefetch didn't happen we can do our own
-  // faster dll preloading.
-  // The MozillaMaintenance service issues a command to disable the
-  // prefetch by replacing all found .pf files with 0 byte read only
-  // files.
   IO_COUNTERS ioCounters;
   gotCounters = GetProcessIoCounters(GetCurrentProcess(), &ioCounters);
 
   if (IsPrefetchDisabledViaService()) {
     preloadReason = PRELOAD_SERVICE;
-  } else if ((gotCounters && !ioCounters.ReadOperationCount)) {
-    preloadReason = PRELOAD_IOCOUNT;
   }
 
   if (preloadReason != PRELOAD_NONE)
 #endif
   {
       XPCOMGlueEnablePreload();
   }
 
@@ -252,16 +267,18 @@ int main(int argc, char* argv[])
   *lastSlash = 0;
 
   rv = XPCOMGlueLoadXULFunctions(kXULFuncs);
   if (NS_FAILED(rv)) {
     Output("Couldn't load XRE functions.\n");
     return 255;
   }
 
+  XRE_StartupTimelineRecord(mozilla::StartupTimeline::START, start);
+
 #ifdef XRE_HAS_DLL_BLOCKLIST
   XRE_SetupDllBlocklist();
 #endif
 
 #if defined(XP_WIN)
   XRE_TelemetryAccumulate(mozilla::Telemetry::STARTUP_USING_PRELOAD,
                           preloadReason);
 #endif
--- a/browser/base/content/browser-appmenu.inc
+++ b/browser/base/content/browser-appmenu.inc
@@ -157,17 +157,17 @@
           <menuitem id="appmenu_pageInspect"
                     hidden="true"
                     label="&inspectMenu.label;"
                     type="checkbox"
                     command="Tools:Inspect"
                     key="key_inspect"/>
           <menuitem id="appmenu_responsiveUI"
                     hidden="true"
-                    label="&responsiveUI.label;"
+                    label="&responsiveDesignTool.label;"
                     type="checkbox"
                     command="Tools:ResponsiveUI"
                     key="key_responsiveUI"/>
           <menuitem id="appmenu_debugger"
                     hidden="true"
                     type="checkbox"
                     label="&debuggerMenu.label2;"
                     key="key_debugger"
--- a/browser/base/content/browser-menubar.inc
+++ b/browser/base/content/browser-menubar.inc
@@ -533,18 +533,18 @@
                             hidden="true"
                             label="&inspectMenu.label;"
                             accesskey="&inspectMenu.accesskey;"
                             key="key_inspect"
                             command="Tools:Inspect"/>
                   <menuitem id="menu_responsiveUI"
                             type="checkbox"
                             hidden="true"
-                            label="&responsiveUI.label;"
-                            accesskey="&responsiveUI.accesskey;"
+                            label="&responsiveDesignTool.label;"
+                            accesskey="&responsiveDesignTool.accesskey;"
                             key="key_responsiveUI"
                             command="Tools:ResponsiveUI"/>
                   <menuitem id="menu_debugger"
                             hidden="true"
                             type="checkbox"
                             label="&debuggerMenu.label2;"
                             key="key_debugger"
                             command="Tools:Debugger"/>
--- a/browser/base/content/browser-sets.inc
+++ b/browser/base/content/browser-sets.inc
@@ -248,17 +248,17 @@
     />
     <key id="key_inspect" key="&inspectMenu.commandkey;" command="Inspector:Inspect"
 #ifdef XP_MACOSX
         modifiers="accel,alt"
 #else
         modifiers="accel,shift"
 #endif
     />
-    <key id="key_responsiveUI" key="&responsiveUI.commandkey;" command="Tools:ResponsiveUI"
+    <key id="key_responsiveUI" key="&responsiveDesignTool.commandkey;" command="Tools:ResponsiveUI"
 #ifdef XP_MACOSX
         modifiers="accel,alt"
 #else
         modifiers="accel,shift"
 #endif
     />
     <key id="key_scratchpad" keycode="&scratchpad.keycode;" modifiers="shift"
          keytext="&scratchpad.keytext;" command="Tools:Scratchpad"/>
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -254,33 +254,33 @@ panel[noactions] > richlistbox > richlis
 #urlbar[pageproxystate="invalid"] > #urlbar-icons > .urlbar-icon:not(#go-button),
 #urlbar[pageproxystate="valid"] > #urlbar-icons > #go-button,
 #urlbar[pageproxystate="invalid"][focused="true"] > #urlbar-go-button ~ toolbarbutton,
 #urlbar[pageproxystate="valid"] > #urlbar-go-button,
 #urlbar:not([focused="true"]) > #urlbar-go-button {
   visibility: collapse;
 }
 
-#urlbar[pageproxystate="invalid"] > #identity-box > #identity-box-inner > #identity-icon-labels {
+#urlbar[pageproxystate="invalid"] > #identity-box > #identity-icon-labels {
   visibility: collapse;
 }
 
 #urlbar[pageproxystate="invalid"] > #identity-box {
   pointer-events: none;
 }
 
 #identity-icon-labels {
   max-width: 18em;
 }
 
 #identity-icon-country-label {
   direction: ltr;
 }
 
-#identity-box.verifiedIdentity > #identity-box-inner > #identity-icon-labels > #identity-icon-label {
+#identity-box.verifiedIdentity > #identity-icon-labels > #identity-icon-label {
   -moz-margin-end: 0.25em !important;
 }
 
 #wrapper-search-container > #search-container > #searchbar > .searchbar-textbox > .autocomplete-textbox-container > .textbox-input-box > html|*.textbox-input {
   visibility: hidden;
 }
 
 /* ::::: Unified Back-/Forward Button ::::: */
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -4416,17 +4416,19 @@ var TabsProgressListener = {
     // pages have any privilege themselves.
     // We can't look for this during onLocationChange since at that point the
     // document URI is not yet the about:-uri of the error page.
 
     if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
         Components.isSuccessCode(aStatus) &&
         /^about:/.test(aWebProgress.DOMWindow.document.documentURI)) {
       aBrowser.addEventListener("click", BrowserOnClick, false);
-      aBrowser.addEventListener("pagehide", function onPageHide() {
+      aBrowser.addEventListener("pagehide", function onPageHide(event) {
+        if (event.target.defaultView.frameElement)
+          return;
         aBrowser.removeEventListener("click", BrowserOnClick, false);
         aBrowser.removeEventListener("pagehide", onPageHide, true);
       }, true);
 
       // We also want to make changes to page UI for unprivileged about pages.
       BrowserOnAboutPageLoad(aWebProgress.DOMWindow.document);
     }
   },
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -479,29 +479,26 @@
             <image id="webapps-notification-icon" class="notification-anchor-icon" role="button"/>
             <image id="plugins-notification-icon" class="notification-anchor-icon" role="button"/>
           </box>
           <!-- Use onclick instead of normal popup= syntax since the popup
                code fires onmousedown, and hence eats our favicon drag events.
                We only add the identity-box button to the tab order when the location bar
                has focus, otherwise pressing F6 focuses it instead of the location bar -->
           <box id="identity-box" role="button"
+               align="center"
                onclick="gIdentityHandler.handleIdentityButtonEvent(event);"
                onkeypress="gIdentityHandler.handleIdentityButtonEvent(event);"
                ondragstart="gIdentityHandler.onDragStart(event);">
-            <hbox id="identity-box-inner" align="center">
-              <hbox id="page-proxy-stack"
-                    onclick="PageProxyClickHandler(event);">
-                <image id="page-proxy-favicon"
-                       pageproxystate="invalid"/>
-              </hbox>
-              <hbox id="identity-icon-labels">
-                <label id="identity-icon-label" class="plain" flex="1"/>
-                <label id="identity-icon-country-label" class="plain"/>
-              </hbox>
+            <image id="page-proxy-favicon"
+                   onclick="PageProxyClickHandler(event);"
+                   pageproxystate="invalid"/>
+            <hbox id="identity-icon-labels">
+              <label id="identity-icon-label" class="plain" flex="1"/>
+              <label id="identity-icon-country-label" class="plain"/>
             </hbox>
           </box>
           <box id="urlbar-display-box" align="center">
             <label id="urlbar-display" value="&urlbar.switchToTab.label;"/>
           </box>
           <hbox id="urlbar-icons">
             <image id="page-report-button"
                    class="urlbar-icon"
@@ -1042,17 +1039,17 @@
                          class="devtools-toolbarbutton"
                          command="Tools:WebConsole"/>
           <toolbarbutton id="developer-toolbar-inspector"
                          label="&inspectorButton.label;"
                          class="devtools-toolbarbutton"
                          hidden="true"
                          command="Tools:Inspect"/>
           <toolbarbutton id="developer-toolbar-responsiveui"
-                         label="&responsiveUI.label;"
+                         label="&responsiveDesignTool.label;"
                          class="devtools-toolbarbutton"
                          hidden="true"
                          command="Tools:ResponsiveUI"/>
           <toolbarbutton id="developer-toolbar-debugger"
                          label="&scriptsButton.label;"
                          class="devtools-toolbarbutton"
                          hidden="true"
                          command="Tools:Debugger"/>
--- a/browser/base/content/test/browser_gestureSupport.js
+++ b/browser/base/content/test/browser_gestureSupport.js
@@ -40,16 +40,17 @@ function test()
   test_thresholdGesture("twist", "right", "left", "MozRotateGesture");
 }
 
 let test_eventCount = 0;
 let test_expectedType;
 let test_expectedDirection;
 let test_expectedDelta;
 let test_expectedModifiers;
+let test_expectedClickCount;
 
 function test_gestureListener(evt)
 {
   is(evt.type, test_expectedType,
      "evt.type (" + evt.type + ") does not match expected value");
   is(evt.target, test_utils.elementFromPoint(20, 20, false, false),
      "evt.target (" + evt.target + ") does not match expected value");
   is(evt.clientX, 20,
@@ -70,16 +71,20 @@ function test_gestureListener(evt)
      "evt.shiftKey did not match expected value");
   is(evt.ctrlKey, (test_expectedModifiers & Components.interfaces.nsIDOMNSEvent.CONTROL_MASK) != 0,
      "evt.ctrlKey did not match expected value");
   is(evt.altKey, (test_expectedModifiers & Components.interfaces.nsIDOMNSEvent.ALT_MASK) != 0,
      "evt.altKey did not match expected value");
   is(evt.metaKey, (test_expectedModifiers & Components.interfaces.nsIDOMNSEvent.META_MASK) != 0,
      "evt.metaKey did not match expected value");
 
+  if (evt.type == "MozTapGesture") {
+    is(evt.clickCount, test_expectedClickCount, "evt.clickCount does not match");
+  }
+
   test_eventCount++;
 }
 
 function test_helper1(type, direction, delta, modifiers)
 {
   // Setup the expected values
   test_expectedType = type;
   test_expectedDirection = direction;
@@ -90,16 +95,34 @@ function test_helper1(type, direction, d
 
   document.addEventListener(type, test_gestureListener, true);
   test_utils.sendSimpleGestureEvent(type, 20, 20, direction, delta, modifiers);
   document.removeEventListener(type, test_gestureListener, true);
 
   is(expectedEventCount, test_eventCount, "Event (" + type + ") was never received by event listener");
 }
 
+function test_clicks(type, clicks)
+{
+  // Setup the expected values
+  test_expectedType = type;
+  test_expectedDirection = 0;
+  test_expectedDelta = 0;
+  test_expectedModifiers = 0;
+  test_expectedClickCount = clicks;
+
+  let expectedEventCount = test_eventCount + 1;
+
+  document.addEventListener(type, test_gestureListener, true);
+  test_utils.sendSimpleGestureEvent(type, 20, 20, 0, 0, 0, clicks);
+  document.removeEventListener(type, test_gestureListener, true);
+
+  is(expectedEventCount, test_eventCount, "Event (" + type + ") was never received by event listener");
+}
+
 function test_TestEventListeners()
 {
   let e = test_helper1;  // easier to type this name
 
   // Swipe gesture event
   e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_LEFT, 0.0, 0);
   e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_RIGHT, 0.0, 0);
   e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_UP, 0.0, 0);
@@ -121,18 +144,23 @@ function test_TestEventListeners()
 
   // rotate gesture events
   e("MozRotateGestureStart", SimpleGestureEvent.ROTATION_CLOCKWISE, 33.0, 0);
   e("MozRotateGestureUpdate", SimpleGestureEvent.ROTATION_COUNTERCLOCKWISE, -13.0, 0);
   e("MozRotateGestureUpdate", SimpleGestureEvent.ROTATION_CLOCKWISE, 13.0, 0);
   e("MozRotateGesture", SimpleGestureEvent.ROTATION_CLOCKWISE, 33.0, 0);
   
   // Tap and presstap gesture events
-  e("MozTapGesture", 0, 0.0, 0);
-  e("MozPressTapGesture", 0, 0.0, 0);
+  test_clicks("MozTapGesture", 1);
+  test_clicks("MozTapGesture", 2);
+  test_clicks("MozTapGesture", 3);
+  test_clicks("MozPressTapGesture", 1);
+
+  // simple delivery test for edgeui gesture
+  e("MozEdgeUIGesture", 0, 0, 0);
 
   // event.shiftKey
   let modifier = Components.interfaces.nsIDOMNSEvent.SHIFT_MASK;
   e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_RIGHT, 0, modifier);
 
   // event.metaKey
   modifier = Components.interfaces.nsIDOMNSEvent.META_MASK;
   e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_RIGHT, 0, modifier);
@@ -166,17 +194,17 @@ function test_helper2(type, direction, d
   }
   ok(successful, "Unable to create SimpleGestureEvent");
 
   try {
     event.initSimpleGestureEvent(type, true, true, window, 1,
                                  10, 10, 10, 10,
                                  ctrlKey, altKey, shiftKey, metaKey,
                                  1, window,
-                                 direction, delta);
+                                 direction, delta, 0);
     successful = true;
   }
   catch (ex) {
     successful = false;
   }
   ok(successful, "event.initSimpleGestureEvent should not fail");
 
   // Make sure the event fields match the expected values
--- a/browser/base/content/test/browser_tabfocus.js
+++ b/browser/base/content/test/browser_tabfocus.js
@@ -21,17 +21,20 @@ function test() {
   function check()
   {
     // wait for both tabs to load
     if (++loadCount != 2)
       return;
 
     browser1.removeEventListener("load", check, true);
     browser2.removeEventListener("load", check, true);
+    executeSoon(_run_focus_tests);
+  }
 
+  function _run_focus_tests() {
     window.focus();
 
     _browser_tabfocus_test_lastfocus = gURLBar;
     _browser_tabfocus_test_lastfocuswindow = window;
 
     window.addEventListener("focus", _browser_tabfocus_test_eventOccured, true);
     window.addEventListener("blur", _browser_tabfocus_test_eventOccured, true);
 
--- a/browser/components/migration/src/MigrationUtils.jsm
+++ b/browser/components/migration/src/MigrationUtils.jsm
@@ -33,17 +33,17 @@ function getMigrationBundle() {
   if (!gMigrationBundle) {
     gMigrationBundle = Services.strings.createBundle(
      "chrome://browser/locale/migration/migration.properties"); 
   }
   return gMigrationBundle;
 }
 
 /**
- * Figure out what is the default browser, and if there is a migraotr
+ * Figure out what is the default browser, and if there is a migrator
  * for it, return that migrator's internal name.
  * For the time being, the "internal name" of a migraotr is its contract-id
  * trailer (e.g. ie for @mozilla.org/profile/migrator;1?app=browser&type=ie),
  * but it will soon be exposed properly.
  */
 function getMigratorKeyForDefaultBrowser() {
   // Don't map Firefox to the Firefox migrator, because we don't
   // expect it to ever show up as an option in the wizard.
@@ -443,17 +443,18 @@ let MigrationUtils = Object.freeze({
 
   /*
    * Returns the migrator for the given source, if any data is available
    * for this source, or null otherwise.
    *
    * @param aKey internal name of the migration source.
    *             Supported values: ie (windows),
    *                               safari (mac/windows),
-   *                               chrome (mac/windows/linux).
+   *                               chrome (mac/windows/linux),
+   *                               firefox.
    *
    * If null is returned,  either no data can be imported
    * for the given migrator, or aMigratorKey is invalid  (e.g. ie on mac,
    * or mosaic everywhere).  This method should be used rather than direct
    * getService for future compatibility (see bug 718280).
    *
    * @return profile migrator implementing nsIBrowserProfileMigrator, if it can
    *         import any data, null otherwise.
@@ -463,23 +464,49 @@ let MigrationUtils = Object.freeze({
     if (this._migrators.has(aKey)) {
       migrator = this._migrators.get(aKey);
     }
     else {
       try {
         migrator = Cc["@mozilla.org/profile/migrator;1?app=browser&type=" +
                       aKey].createInstance(Ci.nsIBrowserProfileMigrator);
       }
-      catch(ex) { Cu.reportError(ex); }
+      catch(ex) { }
       this._migrators.set(aKey, migrator);
     }
 
     return migrator && migrator.sourceExists ? migrator : null;
   },
 
+  // Iterates the available migrators, in the most suitable
+  // order for the running platform.
+  get migrators() {
+    let migratorKeysOrdered = [
+#ifdef XP_WIN
+      "ie", "chrome", "safari"
+#elifdef XP_MACOSX
+      "safari", "chrome"
+#elifdef XP_UNIX
+      "chrome"
+#endif
+    ];
+
+    // If a supported default browser is found check it first
+    // so that the wizard defaults to import from that browser.
+    let defaultBrowserKey = getMigratorKeyForDefaultBrowser();
+    if (defaultBrowserKey)
+      migratorKeysOrdered.sort(function (a, b) b == defaultBrowserKey ? 1 : 0);
+
+    for (let migratorKey of migratorKeysOrdered) {
+      let migrator = this.getMigrator(migratorKey);
+      if (migrator)
+        yield migrator;
+    }
+  },
+
   // Whether or not we're in the process of startup migration
   get isStartupMigration() gProfileStartup != null,
 
   /**
    * In the case of startup migration, this is set to the nsIProfileStartup
    * instance passed to ProfileMigrator's migrate.
    *
    * @see showMigrationWizard
@@ -563,16 +590,30 @@ let MigrationUtils = Object.freeze({
       let defaultBrowserKey = getMigratorKeyForDefaultBrowser();
       if (defaultBrowserKey) {
         migrator = this.getMigrator(defaultBrowserKey);
         if (migrator)
           migratorKey = defaultBrowserKey;
       }
     }
 
+    if (!migrator) {
+      // If there's no migrator set so far, ensure that there is at least one
+      // migrator available before opening the wizard.
+      try {
+        this.migrators.next();
+      }
+      catch(ex) {
+        this.finishMigration();
+        if (!(ex instanceof StopIteration))
+          throw ex;
+        return;
+      }
+    }
+
     let params = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
     let keyCSTR = Cc["@mozilla.org/supports-cstring;1"].
                   createInstance(Ci.nsISupportsCString);
     keyCSTR.data = migratorKey;
     let skipImportSourcePageBool = Cc["@mozilla.org/supports-PRBool;1"].
                                    createInstance(Ci.nsISupportsPRBool);
     skipImportSourcePageBool.data = skipSourcePage;
     params.appendElement(keyCSTR, false);
--- a/browser/components/nsBrowserContentHandler.js
+++ b/browser/components/nsBrowserContentHandler.js
@@ -857,17 +857,17 @@ let AboutHomeUtils = {
       name: defaultEngine.name
     , searchUrl: submission.uri.spec
     }
     this._storage.setItem("search-engine", JSON.stringify(engine));
   },
 
   loadSnippetsURL: function AHU_loadSnippetsURL()
   {
-    const STARTPAGE_VERSION = 2;
+    const STARTPAGE_VERSION = 3;
     let updateURL = Services.prefs
                             .getCharPref(this.SNIPPETS_URL_PREF)
                             .replace("%STARTPAGE_VERSION%", STARTPAGE_VERSION);
     updateURL = Services.urlFormatter.formatURL(updateURL);
     this._storage.setItem("snippets-update-url", updateURL);
   },
 };
 
--- a/browser/components/shell/src/nsWindowsShellService.cpp
+++ b/browser/components/shell/src/nsWindowsShellService.cpp
@@ -598,41 +598,41 @@ DynSHOpenWithDialog(HWND hwndParent, con
 
   return SUCCEEDED(SHOpenWithDialogFn(hwndParent, poainfo)) ? NS_OK :
                                                               NS_ERROR_FAILURE;
 }
 
 NS_IMETHODIMP
 nsWindowsShellService::SetDefaultBrowser(bool aClaimAllTypes, bool aForAllUsers)
 {
-  if (IsWin8OrLater()) {
-    OPENASINFO info;
-    info.pcszFile = L"http";
-    info.pcszClass = NULL;
-    info.oaifInFlags = OAIF_FORCE_REGISTRATION | 
-                       OAIF_URL_PROTOCOL |
-                       OAIF_REGISTER_EXT;
-    nsresult rv = DynSHOpenWithDialog(NULL, &info);
-    NS_ENSURE_SUCCESS(rv, rv);
-    bool isDefaultBrowser = false;
-    return SUCCEEDED(IsDefaultBrowser(&isDefaultBrowser)) && 
-           isDefaultBrowser ? S_OK : NS_ERROR_FAILURE;
-  }
-
   nsAutoString appHelperPath;
   if (NS_FAILED(GetHelperPath(appHelperPath)))
     return NS_ERROR_FAILURE;
 
   if (aForAllUsers) {
     appHelperPath.AppendLiteral(" /SetAsDefaultAppGlobal");
   } else {
     appHelperPath.AppendLiteral(" /SetAsDefaultAppUser");
   }
 
-  return LaunchHelper(appHelperPath);
+  nsresult rv = LaunchHelper(appHelperPath);
+  if (NS_SUCCEEDED(rv) && IsWin8OrLater()) {
+    OPENASINFO info;
+    info.pcszFile = L"http";
+    info.pcszClass = NULL;
+    info.oaifInFlags = OAIF_FORCE_REGISTRATION | 
+                       OAIF_URL_PROTOCOL |
+                       OAIF_REGISTER_EXT;
+    nsresult rv = DynSHOpenWithDialog(NULL, &info);
+    NS_ENSURE_SUCCESS(rv, rv);
+    bool isDefaultBrowser = false;
+    rv = NS_SUCCEEDED(IsDefaultBrowser(&isDefaultBrowser)) &&
+         isDefaultBrowser ? S_OK : NS_ERROR_FAILURE;
+  }
+  return rv;
 }
 
 NS_IMETHODIMP
 nsWindowsShellService::GetShouldCheckDefaultBrowser(bool* aResult)
 {
   NS_ENSURE_ARG_POINTER(aResult);
 
   // If we've already checked, the browser has been started and this is a 
--- a/browser/config/mozconfigs/linux32/debug
+++ b/browser/config/mozconfigs/linux32/debug
@@ -1,11 +1,12 @@
 ac_add_options --enable-debug
 ac_add_options --enable-trace-malloc
 ac_add_options --enable-signmar
+ENABLE_MARIONETTE=1
 
 . $topsrcdir/build/unix/mozconfig.linux
 
 # Avoid dependency on libstdc++ 4.5
 ac_add_options --enable-stdcxx-compat
 
 # Needed to enable breakpad in application.ini
 export MOZILLA_OFFICIAL=1
--- a/browser/config/mozconfigs/linux64/debug
+++ b/browser/config/mozconfigs/linux64/debug
@@ -1,11 +1,12 @@
 ac_add_options --enable-debug
 ac_add_options --enable-trace-malloc
 ac_add_options --enable-signmar
+ENABLE_MARIONETTE=1
 
 . $topsrcdir/build/unix/mozconfig.linux
 
 # Avoid dependency on libstdc++ 4.5
 ac_add_options --enable-stdcxx-compat
 
 # Needed to enable breakpad in application.ini
 export MOZILLA_OFFICIAL=1
--- a/browser/config/mozconfigs/macosx32/debug
+++ b/browser/config/mozconfigs/macosx32/debug
@@ -1,12 +1,13 @@
 . $topsrcdir/build/macosx/mozconfig.leopard
 ac_add_options --enable-debug
 ac_add_options --enable-trace-malloc
 ac_add_options --enable-signmar
+ENABLE_MARIONETTE=1
 
 # Enable parallel compiling
 mk_add_options MOZ_MAKE_FLAGS="-j12"
 
 # Needed to enable breakpad in application.ini
 export MOZILLA_OFFICIAL=1
 
 ac_add_options --with-macbundlename-prefix=Firefox
--- a/browser/config/mozconfigs/macosx64/debug
+++ b/browser/config/mozconfigs/macosx64/debug
@@ -1,14 +1,15 @@
 . $topsrcdir/build/macosx/common
 
 ac_add_options --enable-debug
 ac_add_options --enable-trace-malloc
 ac_add_options --enable-accessibility
 ac_add_options --enable-signmar
+ENABLE_MARIONETTE=1
 
 # Enable parallel compiling
 mk_add_options MOZ_MAKE_FLAGS="-j12"
 
 # Needed to enable breakpad in application.ini
 export MOZILLA_OFFICIAL=1
 
 ac_add_options --with-macbundlename-prefix=Firefox
--- a/browser/config/mozconfigs/win32/debug
+++ b/browser/config/mozconfigs/win32/debug
@@ -1,11 +1,12 @@
 ac_add_options --enable-debug
 ac_add_options --enable-trace-malloc
 ac_add_options --enable-signmar
+ENABLE_MARIONETTE=1
 
 # Needed to enable breakpad in application.ini
 export MOZILLA_OFFICIAL=1
 
 mk_add_options MOZ_MAKE_FLAGS=-j1
 
 if test "$PROCESSOR_ARCHITECTURE" = "AMD64" -o "$PROCESSOR_ARCHITEW6432" = "AMD64"; then
   . $topsrcdir/build/win32/mozconfig.vs2010-win64
--- a/browser/config/mozconfigs/win64/debug
+++ b/browser/config/mozconfigs/win64/debug
@@ -1,14 +1,15 @@
 ac_add_options --target=x86_64-pc-mingw32
 ac_add_options --host=x86_64-pc-mingw32
 
 ac_add_options --enable-debug
 ac_add_options --enable-trace-malloc
 ac_add_options --enable-signmar
+ENABLE_MARIONETTE=1
 
 # Needed to enable breakpad in application.ini
 export MOZILLA_OFFICIAL=1
 
 mk_add_options MOZ_MAKE_FLAGS=-j1
 
 # Package js shell.
 export MOZ_PACKAGE_JSSHELL=1
--- a/browser/devtools/commandline/GcliCommands.jsm
+++ b/browser/devtools/commandline/GcliCommands.jsm
@@ -244,17 +244,17 @@ gcli.addCommand({
 });
 
 /**
  * 'edit' command
  */
 gcli.addCommand({
   name: "edit",
   description: gcli.lookup("editDesc"),
-  manual: gcli.lookup("editManual"),
+  manual: gcli.lookup("editManual2"),
   params: [
      {
        name: 'resource',
        type: {
          name: 'resource',
          include: 'text/css'
        },
        description: gcli.lookup("editResourceDesc")
--- a/browser/devtools/commandline/gcli.jsm
+++ b/browser/devtools/commandline/gcli.jsm
@@ -7915,53 +7915,57 @@ help.startup = function() {
 help.shutdown = function() {
   canon.removeCommand(helpCommandSpec);
 };
 
 /**
  * Create a block of data suitable to be passed to the help_list.html template
  */
 function getListTemplateData(args, context) {
+  var matchingCommands = canon.getCommands().filter(function(command) {
+    if (command.hidden) {
+      return false;
+    }
+
+    if (args.search && command.name.indexOf(args.search) !== 0) {
+      // Filtered out because they don't match the search
+      return false;
+    }
+    if (!args.search && command.name.indexOf(' ') != -1) {
+      // We don't show sub commands with plain 'help'
+      return false;
+    }
+    return true;
+  });
+  matchingCommands.sort();
+
+  var heading;
+  if (matchingCommands.length === 0) {
+    heading = l10n.lookupFormat('helpListNone', [ args.search ]);
+  }
+  else if (args.search == null) {
+    heading = l10n.lookup('helpListAll');
+  }
+  else {
+    heading = l10n.lookupFormat('helpListPrefix', [ args.search ]);
+  }
+
   return {
     l10n: l10n.propertyLookup,
     includeIntro: args.search == null,
+    matchingCommands: matchingCommands,
+    heading: heading,
 
     onclick: function(ev) {
       util.updateCommand(ev.currentTarget, context);
     },
 
     ondblclick: function(ev) {
       util.executeCommand(ev.currentTarget, context);
     },
-
-    getHeading: function() {
-      return args.search == null ?
-              'Available Commands:' :
-              'Commands starting with \'' + args.search + '\':';
-    },
-
-    getMatchingCommands: function() {
-      var matching = canon.getCommands().filter(function(command) {
-        if (command.hidden) {
-          return false;
-        }
-
-        if (args.search && command.name.indexOf(args.search) !== 0) {
-          // Filtered out because they don't match the search
-          return false;
-        }
-        if (!args.search && command.name.indexOf(' ') != -1) {
-          // We don't show sub commands with plain 'help'
-          return false;
-        }
-        return true;
-      });
-      matching.sort();
-      return matching;
-    }
   };
 }
 
 /**
  * Create a block of data suitable to be passed to the help_man.html template
  */
 function getManTemplateData(command, context) {
   var manTemplateData = {
@@ -7981,20 +7985,20 @@ function getManTemplateData(command, con
       var parent = element.ownerDocument.createElement('div');
       util.setContents(parent, text);
       return parent.childNodes;
     },
 
     getTypeDescription: function(param) {
       var input = '';
       if (param.defaultValue === undefined) {
-        input = 'required';
+        input = l10n.lookup('helpManRequired');
       }
       else if (param.defaultValue === null) {
-        input = 'optional';
+        input = l10n.lookup('helpManOptional');
       }
       else {
         input = param.defaultValue;
       }
       return '(' + param.type.name + ', ' + input + ')';
     }
   };
 
@@ -8061,20 +8065,20 @@ define("text!gcli/commands/help_man.html
   "    </ul>\n" +
   "  </div>\n" +
   "\n" +
   "</div>\n" +
   "");
 
 define("text!gcli/commands/help_list.html", [], "\n" +
   "<div>\n" +
-  "  <h3>${getHeading()}</h3>\n" +
+  "  <h3>${heading}</h3>\n" +
   "\n" +
   "  <table>\n" +
-  "    <tr foreach=\"command in ${getMatchingCommands()}\"\n" +
+  "    <tr foreach=\"command in ${matchingCommands}\"\n" +
   "        onclick=\"${onclick}\" ondblclick=\"${ondblclick}\">\n" +
   "      <th class=\"gcli-help-name\">${command.name}</th>\n" +
   "      <td class=\"gcli-help-arrow\">-</td>\n" +
   "      <td>\n" +
   "        ${command.description}\n" +
   "        <span class=\"gcli-out-shortcut\" data-command=\"help ${command.name}\">help ${command.name}</span>\n" +
   "      </td>\n" +
   "    </tr>\n" +
--- a/browser/devtools/commandline/test/browser_gcli_web.js
+++ b/browser/devtools/commandline/test/browser_gcli_web.js
@@ -2010,33 +2010,33 @@ define('gclitest/testHelp', ['require', 
           /Get help/
         ]
       });
     }
 
     helpers.exec(options, {
       typed: 'help nomatch',
       args: { search: 'nomatch' },
-      outputMatch: /Commands starting with 'nomatch':$/
+      outputMatch: /No commands starting with 'nomatch'$/
     });
 
     helpers.exec(options, {
       typed: 'help help',
       args: { search: 'help' },
       outputMatch: [
         /Synopsis:/,
         /Provide help either/,
         /\(string, optional\)/
       ]
     });
 
     helpers.exec(options, {
       typed: 'help a b',
       args: { search: 'a b' },
-      outputMatch: /Commands starting with 'a b':$/
+      outputMatch: /No commands starting with 'a b'$/
     });
 
     helpers.exec(options, {
       typed: 'help hel',
       args: { search: 'hel' },
       outputMatch: [
         /Commands starting with 'hel':/,
         /Get help on the available commands/
--- a/browser/installer/Makefile.in
+++ b/browser/installer/Makefile.in
@@ -39,16 +39,24 @@ endif
 ifdef MOZ_ENABLE_GNOME_COMPONENT
 DEFINES += -DMOZ_ENABLE_GNOME_COMPONENT=1
 endif
 
 ifeq (gtk2, $(MOZ_WIDGET_TOOLKIT))
 DEFINES += -DMOZ_GTK2=1
 endif
 
+ifdef MOZ_NATIVE_NSPR
+DEFINES += -DMOZ_NATIVE_NSPR=1
+endif
+
+ifdef MOZ_NATIVE_NSS
+DEFINES += -DMOZ_NATIVE_NSS=1
+endif
+
 ifdef NSS_DISABLE_DBM
 DEFINES += -DNSS_DISABLE_DBM=1
 endif
 
 ifdef _MSC_VER
 DEFINES += -D_MSC_VER=$(_MSC_VER)
 endif
 
@@ -143,8 +151,12 @@ ifdef MOZ_PKG_MANIFEST_P
 	-diff -u $(DIST)/pack-list.txt $(DIST)/bin-list.txt
 	rm -f $(DIST)/pack-list.txt $(DIST)/bin-list.txt
 endif
 
 installer:: removed-files
 ifdef INSTALLER_DIR
 	$(MAKE) -C $(INSTALLER_DIR)
 endif
+
+ifdef ENABLE_MARIONETTE
+DEFINES += -DENABLE_MARIONETTE=1
+endif
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -55,19 +55,21 @@
 #endif
 @BINPATH@/@DLL_PREFIX@mozalloc@DLL_SUFFIX@
 #ifdef MOZ_SHARED_MOZGLUE
 @BINPATH@/@DLL_PREFIX@mozglue@DLL_SUFFIX@
 #endif
 #ifndef MOZ_STATIC_JS
 @BINPATH@/@DLL_PREFIX@mozjs@DLL_SUFFIX@
 #endif
+#ifndef MOZ_NATIVE_NSPR
 @BINPATH@/@DLL_PREFIX@nspr4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@plc4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@plds4@DLL_SUFFIX@
+#endif
 @BINPATH@/@DLL_PREFIX@xpcom@DLL_SUFFIX@
 #ifdef XP_MACOSX
 @BINPATH@/XUL
 #else
 @BINPATH@/@DLL_PREFIX@xul@DLL_SUFFIX@
 #endif
 #ifdef XP_MACOSX
 @BINPATH@/@MOZ_CHILD_PROCESS_NAME@.app/
@@ -106,17 +108,19 @@
 @BINPATH@/@MOZ_APP_NAME@
 #endif
 @BINPATH@/application.ini
 #ifdef MOZ_UPDATER
 @BINPATH@/update-settings.ini
 #endif
 @BINPATH@/platform.ini
 #ifndef XP_OS2
+#ifndef MOZ_NATIVE_SQLITE
 @BINPATH@/@DLL_PREFIX@mozsqlite3@DLL_SUFFIX@
+#endif
 #else
 @BINPATH@/mozsqlt3@DLL_SUFFIX@
 #endif
 @BINPATH@/blocklist.xml
 #ifdef XP_UNIX
 @BINPATH@/run-mozilla.sh
 #ifndef XP_MACOSX
 @BINPATH@/mozilla-xremote-client
@@ -179,16 +183,17 @@
 @BINPATH@/components/dom_notification.xpt
 @BINPATH@/components/dom_html.xpt
 @BINPATH@/components/dom_indexeddb.xpt
 @BINPATH@/components/dom_offline.xpt
 @BINPATH@/components/dom_json.xpt
 #ifdef MOZ_B2G_RIL
 @BINPATH@/components/dom_mms.xpt
 #endif
+@BINPATH@/components/dom_browserelement.xpt
 @BINPATH@/components/dom_power.xpt
 @BINPATH@/components/dom_range.xpt
 @BINPATH@/components/dom_settings.xpt
 @BINPATH@/components/dom_sidebar.xpt
 @BINPATH@/components/dom_sms.xpt
 @BINPATH@/components/dom_storage.xpt
 @BINPATH@/components/dom_stylesheets.xpt
 @BINPATH@/components/dom_traversal.xpt
@@ -456,16 +461,22 @@
 @BINPATH@/components/SettingsManager.manifest
 @BINPATH@/components/Webapps.js
 @BINPATH@/components/Webapps.manifest
 @BINPATH@/components/AppsService.js
 @BINPATH@/components/AppsService.manifest
 
 @BINPATH@/components/ContactManager.js
 @BINPATH@/components/ContactManager.manifest
+#ifdef ENABLE_MARIONETTE
+@BINPATH@/chrome/marionette@JAREXT@
+@BINPATH@/chrome/marionette.manifest
+@BINPATH@/components/MarionetteComponents.manifest
+@BINPATH@/components/marionettecomponent.js
+#endif
 
 ; Modules
 @BINPATH@/modules/*
 
 ; Safe Browsing
 #ifdef MOZ_SAFE_BROWSING
 @BINPATH@/components/nsSafebrowsingApplication.manifest
 @BINPATH@/components/nsSafebrowsingApplication.js
@@ -580,26 +591,28 @@
 @BINPATH@/components/dom_svg.xpt
 @BINPATH@/components/dom_smil.xpt
 
 ; [Personal Security Manager]
 ;
 ; NSS libraries are signed in the staging directory,
 ; meaning their .chk files are created there directly.
 ;
+#ifndef MOZ_NATIVE_NSS
 @BINPATH@/@DLL_PREFIX@freebl3@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@nss3@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@nssckbi@DLL_SUFFIX@
 #ifndef NSS_DISABLE_DBM
 @BINPATH@/@DLL_PREFIX@nssdbm3@DLL_SUFFIX@
 #endif
 @BINPATH@/@DLL_PREFIX@nssutil3@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@smime3@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@softokn3@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@ssl3@DLL_SUFFIX@
+#endif
 @BINPATH@/chrome/pippki@JAREXT@
 @BINPATH@/chrome/pippki.manifest
 @BINPATH@/components/pipboot.xpt
 @BINPATH@/components/pipnss.xpt
 @BINPATH@/components/pippki.xpt
 
 ; for Solaris SPARC
 #ifdef SOLARIS
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -209,19 +209,19 @@ These should match what Safari and other
 
 <!ENTITY inspectMenu.label            "Inspect">
 <!ENTITY inspectMenu.accesskey        "T">
 <!ENTITY inspectMenu.commandkey       "I">
 
 <!ENTITY inspectContextMenu.label     "Inspect Element">
 <!ENTITY inspectContextMenu.accesskey "Q">
 
-<!ENTITY responsiveUI.label            "Responsive Mode">
-<!ENTITY responsiveUI.accesskey        "R">
-<!ENTITY responsiveUI.commandkey       "M">
+<!ENTITY responsiveDesignTool.label   "Responsive Design View">
+<!ENTITY responsiveDesignTool.accesskey "R">
+<!ENTITY responsiveDesignTool.commandkey "M">
 
 <!-- LOCALIZATION NOTE (scratchpad.label): This menu item label appears
   -  in the Tools menu. See bug 653093.
   -  The Scratchpad is intended to provide a simple text editor for creating
   -  and evaluating bits of JavaScript code for the purposes of function
   -  prototyping, experimentation and convenient scripting.
   -
   -  It's quite possible that you won't have a good analogue for the word
--- a/browser/locales/en-US/chrome/browser/devtools/gcli.properties
+++ b/browser/locales/en-US/chrome/browser/devtools/gcli.properties
@@ -132,16 +132,38 @@ helpManDescription=Description
 # LOCALIZATION NOTE (helpManParameters): A heading shown above the parameters
 # in a help page for a command in the console.
 helpManParameters=Parameters
 
 # LOCALIZATION NOTE (helpManNone): Some text shown under the parameters
 # heading in a help page for a command which has no parameters.
 helpManNone=None
 
+# LOCALIZATION NOTE (helpListAll): The heading shown in response to the 'help'
+# command when used without a filter, just above the list of known commands.
+helpListAll=Available Commands:
+
+# LOCALIZATION NOTE (helpListPrefix): The heading shown in response to the
+# 'help <search>' command (i.e. with a search string), just above the list of
+# matching commands.
+helpListPrefix=Commands starting with '%1$S':
+
+# LOCALIZATION NOTE (helpListNone): The heading shown in response to the 'help
+# <search>' command (i.e. with a search string), when there are no matching
+# commands.
+helpListNone=No commands starting with '%1$S'
+
+# LOCALIZATION NOTE (helpManRequired): When the 'help x' command wants to show
+# the manual for the 'x' command it needs to be able to describe the
+# parameters as either required or optional. See also 'helpManOptional'.
+helpManRequired=required
+
+# LOCALIZATION NOTE (helpManOptional): See description of 'helpManRequired'
+helpManOptional=optional
+
 # LOCALIZATION NOTE (subCommands): Text shown as part of the output of the
 # 'help' command when the command in question has sub-commands, before a list
 # of the matching sub-commands
 subCommands=Sub-Commands
 
 # LOCALIZATION NOTE (subCommandsNone): Text shown as part of the output of the
 # 'help' command when the command in question should have sub-commands but in
 # fact has none
--- a/browser/locales/en-US/chrome/browser/devtools/gclicommands.properties
+++ b/browser/locales/en-US/chrome/browser/devtools/gclicommands.properties
@@ -309,24 +309,24 @@ breakNotFound=Breakpoint was not found
 consolecloseDesc=Close the console
 
 # LOCALIZATION NOTE (consoleopenDesc) A very short description of the
 # 'console open' command. This string is designed to be shown in a menu
 # alongside the command name, which is why it should be as short as possible.
 consoleopenDesc=Open the console
 
 # LOCALIZATION NOTE (editDesc) A very short description of the 'edit'
-# command. See editManual for a fuller description of what it does. This
+# command. See editManual2 for a fuller description of what it does. This
 # string is designed to be shown in a menu alongside the command name, which
 # is why it should be as short as possible.
 editDesc=Tweak a page resource
 
-# LOCALIZATION NOTE (editManual) A fuller description of the 'edit' command,
+# LOCALIZATION NOTE (editManual2) A fuller description of the 'edit' command,
 # displayed when the user asks for help on what it does.
-editManual=Edit one of the resources that is part of this page (or maybe any generic web resource?)
+editManual2=Edit one of the resources that is part of this page
 
 # LOCALIZATION NOTE (editResourceDesc) A very short string to describe the
 # 'resource' parameter to the 'edit' command, which is displayed in a dialog
 # when the user is using this command.
 editResourceDesc=URL to edit
 
 # LOCALIZATION NOTE (editLineToJumpToDesc) A very short string to describe the
 # 'line' parameter to the 'edit' command, which is displayed in a dialog
--- a/browser/themes/gnomestripe/browser.css
+++ b/browser/themes/gnomestripe/browser.css
@@ -996,34 +996,34 @@ toolbar[iconsize="small"] #feed-button {
   margin-top: 2px;
   margin-bottom: 2px;
   -moz-margin-start: 4px;
   -moz-margin-end: 3px;
   list-style-image: url(chrome://browser/skin/identity-icons-generic.png);
   -moz-image-region: rect(0, 16px, 16px, 0);
 }
 
-.verifiedDomain > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon[pageproxystate="valid"] {
+.verifiedDomain > #page-proxy-favicon[pageproxystate="valid"] {
   list-style-image: url(chrome://browser/skin/identity-icons-https.png);
 }
 
-.verifiedIdentity > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon[pageproxystate="valid"] {
+.verifiedIdentity > #page-proxy-favicon[pageproxystate="valid"] {
   list-style-image: url(chrome://browser/skin/identity-icons-https-ev.png);
 }
 
-.mixedContent > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon[pageproxystate="valid"] {
+.mixedContent > #page-proxy-favicon[pageproxystate="valid"] {
   list-style-image: url(chrome://browser/skin/identity-icons-https-mixed.png);
 }
 
-#identity-box:hover > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon {
+#identity-box:hover > #page-proxy-favicon {
   -moz-image-region: rect(0, 32px, 16px, 16px);
 }
 
-#identity-box:hover:active > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon,
-#identity-box[open=true] > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon {
+#identity-box:hover:active > #page-proxy-favicon,
+#identity-box[open=true] > #page-proxy-favicon {
   -moz-image-region: rect(0, 48px, 16px, 32px);
 }
 
 #page-proxy-favicon[pageproxystate="invalid"] {
   opacity: 0.3;
 }
 
 /* Identity indicator */
--- a/browser/themes/pinstripe/browser.css
+++ b/browser/themes/pinstripe/browser.css
@@ -1053,30 +1053,30 @@ toolbar[mode="icons"] #zoom-in-button {
   width: 16px;
   height: 16px;
   margin: 0px;
   padding: 0px;
   list-style-image: url(chrome://browser/skin/identity-icons-generic.png);
   -moz-image-region: rect(0, 16px, 16px, 0);
 }
 
-.verifiedDomain > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon[pageproxystate="valid"] {
+.verifiedDomain > #page-proxy-favicon[pageproxystate="valid"] {
   list-style-image: url(chrome://browser/skin/identity-icons-https.png);
 }
 
-.verifiedIdentity > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon[pageproxystate="valid"] {
+.verifiedIdentity > #page-proxy-favicon[pageproxystate="valid"] {
   list-style-image: url(chrome://browser/skin/identity-icons-https-ev.png);
 }
 
-.mixedContent > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon[pageproxystate="valid"] {
+.mixedContent > #page-proxy-favicon[pageproxystate="valid"] {
   list-style-image: url(chrome://browser/skin/identity-icons-https-mixed.png);
 }
 
-#identity-box:hover:active > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon,
-#identity-box[open=true] > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon {
+#identity-box:hover:active > #page-proxy-favicon,
+#identity-box[open=true] > #page-proxy-favicon {
   -moz-image-region: rect(0, 32px, 16px, 16px);
 }
 
 #page-proxy-favicon[pageproxystate="invalid"] {
   opacity: 0.3;
 }
 
 #wrapper-urlbar-container[place="palette"] {
--- a/browser/themes/winstripe/browser.css
+++ b/browser/themes/winstripe/browser.css
@@ -1428,38 +1428,38 @@ html|*.urlbar-input:-moz-lwtheme:-moz-pl
   margin-top: 1px;
   margin-bottom: 1px;
   -moz-margin-start: 3px;
   -moz-margin-end: 2px;
   list-style-image: url(chrome://browser/skin/identity-icons-generic.png);
   -moz-image-region: rect(0, 16px, 16px, 0);
 }
 
-@conditionalForwardWithUrlbar@ + #urlbar-container > #urlbar > #identity-box > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon {
+@conditionalForwardWithUrlbar@ + #urlbar-container > #urlbar > #identity-box > #page-proxy-favicon {
   -moz-margin-end: 1px;
 }
 
-.verifiedDomain > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon[pageproxystate="valid"] {
+.verifiedDomain > #page-proxy-favicon[pageproxystate="valid"] {
   list-style-image: url(chrome://browser/skin/identity-icons-https.png);
 }
 
-.verifiedIdentity > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon[pageproxystate="valid"] {
+.verifiedIdentity > #page-proxy-favicon[pageproxystate="valid"] {
   list-style-image: url(chrome://browser/skin/identity-icons-https-ev.png);
 }
 
-.mixedContent > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon[pageproxystate="valid"] {
+.mixedContent > #page-proxy-favicon[pageproxystate="valid"] {
   list-style-image: url(chrome://browser/skin/identity-icons-https-mixed.png);
 }
 
-#identity-box:hover > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon {
+#identity-box:hover > #page-proxy-favicon {
   -moz-image-region: rect(0, 32px, 16px, 16px);
 }
 
-#identity-box:hover:active > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon,
-#identity-box[open=true] > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon {
+#identity-box:hover:active > #page-proxy-favicon,
+#identity-box[open=true] > #page-proxy-favicon {
   -moz-image-region: rect(0, 48px, 16px, 32px);
 }
 
 #page-proxy-favicon[pageproxystate="invalid"] {
   opacity: 0.3;
 }
 
 /* autocomplete */
--- a/build/mobile/devicemanager.py
+++ b/build/mobile/devicemanager.py
@@ -2,16 +2,17 @@
 # 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 time
 import hashlib
 import socket
 import os
 import re
+import StringIO
 
 class FileError(Exception):
   " Signifies an error which occurs while doing a file operation."
 
   def __init__(self, msg = ''):
     self.msg = msg
 
   def __str__(self):
@@ -468,16 +469,43 @@ class DeviceManager:
   @abstractmethod
   def getCurrentTime(self):
     """
     external function
     returns:
     success: time in ms
     failure: None
     """
+
+  def recordLogcat(self):
+    """
+    external function
+    returns:
+    success: file is created in <testroot>/logcat.log
+    failure: 
+    """
+    #TODO: spawn this off in a separate thread/process so we can collect all the logcat information
+
+    # Right now this is just clearing the logcat so we can only see what happens after this call.
+    buf = StringIO.StringIO()
+    self.shell(['/system/bin/logcat', '-c'], buf)
+
+  def getLogcat(self):
+    """
+    external function
+    returns: data from the local file
+    success: file is in 'filename'
+    failure: None
+    """
+    buf = StringIO.StringIO()
+    if self.shell(["/system/bin/logcat", "-d", "dalvikvm:S", "ConnectivityService:S", "WifiMonitor:S", "WifiStateTracker:S", "wpa_supplicant:S", "NetworkStateTracker:S"], buf) != 0:
+      return None
+
+    return str(buf.getvalue()[0:-1]).rstrip().split('\r')
+
     
 class NetworkTools:
   def __init__(self):
     pass
 
   # Utilities to get the local ip address
   def getInterfaceIp(self, ifname):
     if os.name != "nt":
--- a/build/mobile/devicemanagerSUT.py
+++ b/build/mobile/devicemanagerSUT.py
@@ -258,17 +258,17 @@ class DeviceManagerSUT(DeviceManager):
     cmdline = subprocess.list2cmdline(cmd)
     if env:
       cmdline = '%s %s' % (self.formatEnvString(env), cmdline)
 
     try:
       if cwd:
         self.sendCmds(['execcwd %s %s' % (cwd, cmdline)], outputfile)
       else:
-        self.sendCmds(['exec %s' % cmdline], outputfile)
+        self.sendCmds(['exec su -c "%s"' % cmdline], outputfile)
     except AgentError:
       return None
 
     # dig through the output to get the return code
     lastline = _pop_last_line(outputfile)
     if lastline:
       m = re.search('return code \[([0-9]+)\]', lastline)
       if m:
--- a/caps/src/nsNullPrincipalURI.h
+++ b/caps/src/nsNullPrincipalURI.h
@@ -10,24 +10,25 @@
 
 #ifndef __nsNullPrincipalURI_h__
 #define __nsNullPrincipalURI_h__
 
 #include "nsIURI.h"
 #include "nsISizeOf.h"
 #include "nsAutoPtr.h"
 #include "nsString.h"
+#include "mozilla/Attributes.h"
 
 // {51fcd543-3b52-41f7-b91b-6b54102236e6}
 #define NS_NULLPRINCIPALURI_IMPLEMENTATION_CID \
   {0x51fcd543, 0x3b52, 0x41f7, \
     {0xb9, 0x1b, 0x6b, 0x54, 0x10, 0x22, 0x36, 0xe6} }
 
-class nsNullPrincipalURI : public nsIURI
-                         , public nsISizeOf
+class nsNullPrincipalURI MOZ_FINAL : public nsIURI
+                                   , public nsISizeOf
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIURI
 
   // nsISizeOf
   virtual size_t SizeOfExcludingThis(nsMallocSizeOfFun aMallocSizeOf) const;
   virtual size_t SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf) const;
--- a/chrome/src/nsChromeProtocolHandler.h
+++ b/chrome/src/nsChromeProtocolHandler.h
@@ -3,26 +3,28 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsChromeProtocolHandler_h___
 #define nsChromeProtocolHandler_h___
 
 #include "nsIProtocolHandler.h"
 #include "nsWeakReference.h"
+#include "mozilla/Attributes.h"
 
 #define NS_CHROMEPROTOCOLHANDLER_CID                 \
 { /* 61ba33c0-3031-11d3-8cd0-0060b0fc14a3 */         \
     0x61ba33c0,                                      \
     0x3031,                                          \
     0x11d3,                                          \
     {0x8c, 0xd0, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
 }
 
-class nsChromeProtocolHandler : public nsIProtocolHandler, public nsSupportsWeakReference
+class nsChromeProtocolHandler MOZ_FINAL : public nsIProtocolHandler,
+                                          public nsSupportsWeakReference
 {
 public:
     NS_DECL_ISUPPORTS
 
     // nsIProtocolHandler methods:
     NS_DECL_NSIPROTOCOLHANDLER
 
     // nsChromeProtocolHandler methods:
--- a/config/JarMaker.py
+++ b/config/JarMaker.py
@@ -285,18 +285,19 @@ class JarMaker(object):
 
     jarfile = os.path.join(jardir, jarfile)
     jf = None
     if self.outputFormat == 'jar':
       #jar
       jarfilepath = jarfile + '.jar'
       try:
         os.makedirs(os.path.dirname(jarfilepath))
-      except OSError:
-        pass
+      except OSError, error:
+        if error.errno != errno.EEXIST:
+          raise
       jf = ZipFile(jarfilepath, 'a', lock = True)
       outHelper = self.OutputHelper_jar(jf)
     else:
       outHelper = getattr(self, 'OutputHelper_' + self.outputFormat)(jarfile)
     register = {}
     # This loop exits on either
     # - the end of the jar.mn file
     # - an line in the jar.mn file that's not part of a jar section
@@ -418,17 +419,21 @@ class JarMaker(object):
       except OSError, e:
         if e.errno != errno.ENOENT:
           raise
       return open(out, 'wb')
     def ensureDirFor(self, name):
       out = os.path.join(self.basepath, name)
       outdir = os.path.dirname(out)
       if not os.path.isdir(outdir):
-        os.makedirs(outdir)
+        try:
+          os.makedirs(outdir)
+        except OSError, error:
+          if error.errno != errno.EEXIST:
+            raise
       return out
 
   class OutputHelper_symlink(OutputHelper_flat):
     '''Subclass of OutputHelper_flat that provides a helper for
     creating a symlink including creating the parent directories.
     '''
     def symlink(self, src, dest):
       out = self.ensureDirFor(dest)
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -524,16 +524,17 @@ MOZ_ENABLE_CAIRO_FT	= @MOZ_ENABLE_CAIRO_
 MOZ_ENABLE_GTK2		= @MOZ_ENABLE_GTK2@
 MOZ_ENABLE_QT		= @MOZ_ENABLE_QT@
 MOZ_ENABLE_XREMOTE	= @MOZ_ENABLE_XREMOTE@
 MOZ_ENABLE_DWRITE_FONT	= @MOZ_ENABLE_DWRITE_FONT@
 MOZ_ENABLE_D2D_SURFACE	= @MOZ_ENABLE_D2D_SURFACE@
 MOZ_ENABLE_D3D9_LAYER	= @MOZ_ENABLE_D3D9_LAYER@
 MOZ_ENABLE_D3D10_LAYER  = @MOZ_ENABLE_D3D10_LAYER@
 MOZ_METRO	= @MOZ_METRO@
+MAKEPRI	= @MAKEPRI@
 CRTDLLVERSION	= @CRTDLLVERSION@
 CRTEXPDLLVERSION	= @CRTEXPDLLVERSION@
 
 MOZ_GTK2_CFLAGS		= @MOZ_GTK2_CFLAGS@
 MOZ_GTK2_LIBS		= @MOZ_GTK2_LIBS@
 
 MOZ_QT_CFLAGS		= @MOZ_QT_CFLAGS@
 MOZ_QT_LIBS		= @MOZ_QT_LIBS@
--- a/config/makefiles/target_export.mk
+++ b/config/makefiles/target_export.mk
@@ -25,8 +25,24 @@ export:: $(PARALLEL_DIRS_export)
 
 $(PARALLEL_DIRS_export): %_export: %/Makefile
 	+@$(call SUBMAKE,export,$*)
 endif
 
 export:: $(SUBMAKEFILES) $(MAKE_DIRS) $(if $(XPIDLSRCS),$(IDL_DIR))
 	$(LOOP_OVER_DIRS)
 	$(LOOP_OVER_TOOL_DIRS)
+
+
+#
+# Rule to create list of libraries for final link
+#
+# todo: use pre-req deps rather than conditionals
+export:: export-gen-final-lib-link-list
+export-gen-final-lib-link-list:
+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
--- a/config/makefiles/test/Makefile.in
+++ b/config/makefiles/test/Makefile.in
@@ -11,22 +11,24 @@ VPATH     = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 USE_AUTOTARGETS_MK  = 1
 MAKEUTILS_UNIT_TEST = 1
 include $(topsrcdir)/config/makefiles/makeutils.mk
 
 dir-ts = .deps/test
-check-arglist     = $(dir-ts)/arglist.ts
-check-autotargets = $(dir-ts)/autotargets_mk.ts
-check-XinY        = $(dir-ts)/check_XinY_mk.ts
+check-arglist        = $(dir-ts)/arglist.ts
+check-autotargets    = $(dir-ts)/autotargets_mk.ts
+check-export-targets = $(dir-ts)/export-targets-mk.ts
+check-XinY           = $(dir-ts)/check_XinY_mk.ts
 check-tests =\
   $(check-arglist) \
   $(check-autotargets) \
+  $(check-export-targets) \
   $(check-XinY) \
   $(NULL)
 
 
 ##------------------_##
 ##---]  TARGETS  [---##
 ##------------------_##
 all::
@@ -96,9 +98,27 @@ check-autotargets-preqs=\
   $(srcdir)/check-autotargets.mk \
   $(eval include $(srcdir)/check-autotargets.mk) \
   $(NULL)
 
 $(check-autotargets): $(check-autotargets-preqs)
 	@$(TOUCH) $@
 # </CHECK: autotargets.mk>
 
+
+###########################################################################
+# <CHECK: export-targets.mk>
+check-export-targets-preqs=\
+  $(call mkdir_deps,$(dir-ts)) \
+  $(topsrcdir)/config/makefiles/makeutils.mk \
+  $(topsrcdir)/config/makefiles/target_export.mk \
+  $(srcdir)/check-export-targets.mk \
+  checkup \
+  $(NULL)
+
+# include then test
+checkup: $(eval include $(srcdir)/check-export-targets.mk)
+
+$(check-export-targets): $(check-export-targets-preqs)
+	@$(TOUCH) $@
+# </CHECK: export-targets.mk>
+
 endif #} findstring check
new file mode 100644
--- /dev/null
+++ b/config/makefiles/test/check-export-targets.mk
@@ -0,0 +1,33 @@
+# -*- 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/.
+
+ifdef VERBOSE
+  $(warning loading test)
+endif
+
+MOZILLA_DIR ?= $(topsrcdir)
+checkup = \
+  check-final-lib-link-list \
+  $(NULL)
+
+checkup: $(checkup)
+
+
+# <CHECK: final-lib-link-list>
+LIBRARY_NAME   = foo# real_data: xptcmd
+EXPORT_LIBRARY = foo# real_data: ../..
+undefine IS_COMPONENT
+
+test-data = $(CURDIR)/check-export-targets-test-data
+FINAL_LINK_LIBS     = $(test-data)
+STATIC_LIBRARY_NAME = /dev/null
+
+check-final-lib-link-list: export-gen-final-lib-link-list
+	@cat $(test-data)
+# </CHECK: final-lib-link-list>
+
+
+include $(topsrcdir)/config/makefiles/target_export.mk
--- a/config/makefiles/test/check_XinY.mk
+++ b/config/makefiles/test/check_XinY.mk
@@ -19,17 +19,17 @@ val  := invalid
 $(call errorifneq,$(zero),$(words $(call is_XinY,foo,$(val))))
 $(call errorifneq,$(zero),$(words $(call is_XinY,clean,$(val))))
 $(call errorifneq,$(zero),$(words $(call is_XinY,clean%,$(val))))
 
 # verify strcmp('clean')
 val  := clean
 $(call errorifneq,$(zero),$(words $(call is_XinY,foo,$(val))))
 $(call errorifneq,$(one),$(words $(call is_XinY,clean,$(val))))
-$(call errorifneq,$(one,$(words $(call is_XinY,clean%,$(val)))))
+$(call errorifneq,$(one),$(words $(call is_XinY,clean%,$(val))))
 $(call errorifneq,$(one),$(words $(call is_XinY,%clean,$(val))))
 
 # List match for 'clean'
 val     := blah clean distclean FcleanG clean-level-1
 wanted  := clean distclean clean-level-1
 $(call errorifneq,$(zero),$(words $(call is_XinY_debug,foo,$(val))))
 $(call errorifneq,$(one),$(words $(call is_XinY,clean,$(val))))
 $(call errorifneq,$(one),$(words $(call is_XinY,distclean,$(val))))
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -621,29 +621,16 @@ ifneq (,$(DIRS)$(TOOL_DIRS)$(PARALLEL_DI
 	$(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
 
 HOST_LIBS_DEPS = $(filter %.$(LIB_SUFFIX),$(HOST_LIBS))
 
 # Dependencies which, if modified, should cause everything to rebuild
 GLOBAL_DEPS += Makefile Makefile.in $(DEPTH)/config/autoconf.mk $(topsrcdir)/config/config.mk
--- a/configure.in
+++ b/configure.in
@@ -69,17 +69,17 @@ GTK2_VERSION=2.10.0
 WINDRES_VERSION=2.14.90
 W32API_VERSION=3.14
 GNOMEVFS_VERSION=2.0
 GNOMEUI_VERSION=2.2.0
 GCONF_VERSION=1.2.1
 GIO_VERSION=2.18
 STARTUP_NOTIFICATION_VERSION=0.8
 DBUS_VERSION=0.60
-SQLITE_VERSION=3.7.12.1
+SQLITE_VERSION=3.7.13
 LIBNOTIFY_VERSION=0.4
 
 MSMANIFEST_TOOL=
 
 dnl Set various checks
 dnl ========================================================
 MISSING_X=
 AC_PROG_AWK
@@ -3156,52 +3156,16 @@ else
     dnl = Check for Xss
     dnl ========================================================
     MOZ_CHECK_HEADER(X11/extensions/scrnsaver.h,
         AC_CHECK_LIB(Xss, XScreenSaverQueryInfo,
             [XSS_LIBS="-lXss $XEXT_LIBS $XLIBS"
              AC_DEFINE(HAVE_LIBXSS)],, $XEXT_LIBS $XLIBS))
 
 	LDFLAGS="$_SAVE_LDFLAGS"
-
-    dnl ========================================================
-    dnl = Check for freetype2 and its functionality
-    dnl ========================================================
-    PKG_CHECK_MODULES(FT2, freetype2 >= 6.1.0, _HAVE_FREETYPE2=1, _HAVE_FREETYPE2=)
-
-    if test "$_HAVE_FREETYPE2"; then
-    	_SAVE_LIBS="$LIBS"
-    	_SAVE_CFLAGS="$CFLAGS"
-    	LIBS="$LIBS $FT2_LIBS"
-    	CFLAGS="$CFLAGS $FT2_CFLAGS"
-
-        AC_CACHE_CHECK(for FT_Bitmap_Size.y_ppem,
-            ac_cv_member_FT_Bitmap_Size_y_ppem,
-            [AC_TRY_COMPILE([#include <ft2build.h>
-                             #include FT_FREETYPE_H],
-                            [FT_Bitmap_Size s;
-                             if (sizeof s.y_ppem) return 0;
-                             return 1],
-                            ac_cv_member_FT_Bitmap_Size_y_ppem=yes,
-                            ac_cv_member_FT_Bitmap_Size_y_ppem=no)])
-        if test "$ac_cv_member_FT_Bitmap_Size_y_ppem" = yes; then
-            HAVE_FT_BITMAP_SIZE_Y_PPEM=1
-        else
-            HAVE_FT_BITMAP_SIZE_Y_PPEM=0
-        fi
-        AC_DEFINE_UNQUOTED(HAVE_FT_BITMAP_SIZE_Y_PPEM,
-                           $HAVE_FT_BITMAP_SIZE_Y_PPEM,
-                           [FT_Bitmap_Size structure includes y_ppem field])
-
-        AC_CHECK_FUNCS(FT_GlyphSlot_Embolden FT_Load_Sfnt_Table FT_Select_Size)
-
-    	LIBS="$_SAVE_LIBS"
-    	CFLAGS="$_SAVE_CFLAGS"
-    fi
-
 fi # $no_x
 
 AC_SUBST(XCFLAGS)
 AC_SUBST(XLDFLAGS)
 AC_SUBST(XLIBS)
 AC_SUBST(XEXT_LIBS)
 AC_SUBST(XT_LIBS)
 AC_SUBST(XSS_LIBS)
@@ -4562,16 +4526,17 @@ cairo-gtk2|cairo-gtk2-x11)
 
     AC_DEFINE(MOZ_X11)
     MOZ_X11=1
     USE_FC_FREETYPE=1
 
     TK_CFLAGS='$(MOZ_GTK2_CFLAGS)'
     TK_LIBS='$(MOZ_GTK2_LIBS)'
     AC_DEFINE(MOZ_WIDGET_GTK2)
+    AC_DEFINE(MOZ_WIDGET_GTK,2)
     MOZ_PDF_PRINTING=1
     MOZ_INSTRUMENT_EVENT_LOOP=1
     ;;
 
 cairo-qt)
     MOZ_WIDGET_TOOLKIT=qt
     MOZ_ENABLE_QT=1
     if test -z "$WITHOUT_X11"; then
@@ -4734,17 +4699,17 @@ dnl ====================================
 if test "$MOZ_ENABLE_QT"
 then
     MOZ_ARG_WITH_STRING(qtdir,
     [  --with-qtdir=\$dir       Specify Qt directory ],
     [ QTDIR=$withval])
 
     if test -z "$QTDIR"; then
         PKG_CHECK_MODULES(MOZ_QT, QtGui QtNetwork QtCore QtOpenGL)
-        PKG_CHECK_MODULES(MOZ_QT5, QtWidgets QtMultimedia QtPrintSupport QtQuick1,
+        PKG_CHECK_MODULES(MOZ_QT5, QtWidgets QtMultimedia QtPrintSupport,
                       MOZ_ENABLE_QT5=1,
                       MOZ_ENABLE_QT5=)
         if test "$MOZ_ENABLE_QT5"; then
             echo "Using qt5"
             MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS $MOZ_QT5_CFLAGS"
             MOZ_QT_LIBS="$MOZ_QT_LIBS $MOZ_QT5_LIBS"
         fi
 
@@ -4761,22 +4726,19 @@ then
         MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtNetwork"
         MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtXml"
         MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtDeclarative"
         HOST_MOC="$QTDIR/bin/moc"
         HOST_RCC="$QTDIR/bin/rcc"
 
         # QtWidgets was introduced only in Qt5
         if test -d $QTDIR/include/QtWidgets; then
-            echo "Using qt5"
             MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtWidgets"
-            MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtMultimedia"
             MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtPrintSupport"
-            MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtQuick1"
-            MOZ_QT_LIBS="$MOZ_QT_LIBS -lQtWidgets -lQtMultimedia -lQtPrintSupport -lQtQuick1"
+            MOZ_QT_LIBS="$MOZ_QT_LIBS -lQtWidgets -lQtPrintSupport"
         fi
     fi
     if test -z "$HOST_MOC"; then
         AC_MSG_ERROR([No acceptable moc preprocessor found. Qt SDK is not installed or --with-qt is
 incorrect])
     fi
     if test -z "$HOST_RCC"; then
         AC_MSG_ERROR([No acceptable rcc preprocessor found. Qt SDK is not installed or --with-qt is
@@ -7008,17 +6970,17 @@ elif test "${OS_TARGET}" = "WINNT" -o "$
   else
     MOZ_GLUE_LDFLAGS='-L$(LIBXUL_DIST)/lib $(call EXPAND_LIBNAME,mozglue)'
   fi
 else
   dnl On other Unix systems, we only want to link executables against mozglue
   MOZ_GLUE_PROGRAM_LDFLAGS='$(MKSHLIB_FORCE_ALL) $(call EXPAND_LIBNAME_PATH,mozglue,$(LIBXUL_DIST)/lib)'
   dnl On other Unix systems, where mozglue is a static library, jemalloc is
   dnl separated for the SDK, so we need to add it here.
-  if test "$MOZ_MEMORY" = 1; then
+  if test "$MOZ_MEMORY" = 1 -o \( "$LIBXUL_SDK" -a -f "$LIBXUL_SDK/lib/${LIB_PREFIX}memory.${LIB_SUFFIX}" \); then
     MOZ_GLUE_PROGRAM_LDFLAGS="$MOZ_GLUE_PROGRAM_LDFLAGS "'$(call EXPAND_LIBNAME_PATH,memory,$(LIBXUL_DIST)/lib)'
   fi
   MOZ_GLUE_PROGRAM_LDFLAGS="$MOZ_GLUE_PROGRAM_LDFLAGS "'$(MKSHLIB_UNFORCE_ALL)'
   if test -n "$GNU_CC"; then
     dnl And we need mozglue symbols to be exported.
     MOZ_GLUE_PROGRAM_LDFLAGS="$MOZ_GLUE_PROGRAM_LDFLAGS -rdynamic"
   fi
   if test "$MOZ_LINKER" = 1; then
@@ -7394,16 +7356,27 @@ MOZ_ARG_ENABLE_BOOL(functiontimer,
 [  --enable-functiontimer  Enable NS_FUNCTION_TIMER ],
     NS_FUNCTION_TIMER=1,
     NS_FUNCTION_TIMER= )
 if test -n "$NS_FUNCTION_TIMER"; then
     AC_DEFINE(NS_FUNCTION_TIMER)
 fi
 
 dnl ========================================================
+dnl = Enable runtime visual profiling logger
+dnl ========================================================
+MOZ_ARG_ENABLE_BOOL(visual-event-tracer,
+[  --enable-visual-event-tracer   Enable visual event tracer instrumentation],
+    MOZ_VISUAL_EVENT_TRACER=1,
+    MOZ_VISUAL_EVENT_TRACER=)
+if test -n "$MOZ_VISUAL_EVENT_TRACER"; then
+    AC_DEFINE(MOZ_VISUAL_EVENT_TRACER)
+fi
+
+dnl ========================================================
 dnl Turn on reflow counting
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(reflow-perf,
 [  --enable-reflow-perf    Enable reflow performance tracing],
     MOZ_REFLOW_PERF=1,
     MOZ_REFLOW_PERF= )
 if test -n "$MOZ_REFLOW_PERF"; then
     AC_DEFINE(MOZ_REFLOW_PERF)
@@ -7872,27 +7845,74 @@ fi
 AC_SUBST(GLIB_CFLAGS)
 AC_SUBST(GLIB_LIBS)
 AC_SUBST(GLIB_GMODULE_LIBS)
 
 dnl ========================================================
 dnl Graphics checks.
 dnl ========================================================
 
-if test "${OS_ARCH}" = "Darwin" -o "${MOZ_WIDGET_TOOLKIT}" = "android" -o "${MOZ_WIDGET_TOOLKIT}" = "gtk2"; then
+if test "${OS_TARGET}" = "WINNT" -o "${OS_ARCH}" = "Darwin" -o "${MOZ_WIDGET_TOOLKIT}" = "android" -o "${MOZ_WIDGET_TOOLKIT}" = "gtk2"; then
 MOZ_ENABLE_SKIA=1
 else
 MOZ_ENABLE_SKIA=
 fi
 
 MOZ_ARG_ENABLE_BOOL(skia,
 [  --enable-skia   Enable use of Skia],
 MOZ_ENABLE_SKIA=1,
 MOZ_ENABLE_SKIA=)
 
+if test "$USE_FC_FREETYPE"; then
+    if test "$COMPILE_ENVIRONMENT"; then
+        dnl ========================================================
+        dnl = Check for freetype2 and its functionality
+        dnl ========================================================
+        PKG_CHECK_MODULES(FT2, freetype2 >= 6.1.0, _HAVE_FREETYPE2=1, _HAVE_FREETYPE2=)
+
+        if test "$_HAVE_FREETYPE2"; then
+            _SAVE_LIBS="$LIBS"
+            _SAVE_CFLAGS="$CFLAGS"
+            LIBS="$LIBS $FT2_LIBS"
+            CFLAGS="$CFLAGS $FT2_CFLAGS"
+
+            AC_CACHE_CHECK(for FT_Bitmap_Size.y_ppem,
+                ac_cv_member_FT_Bitmap_Size_y_ppem,
+                [AC_TRY_COMPILE([#include <ft2build.h>
+                                 #include FT_FREETYPE_H],
+                                [FT_Bitmap_Size s;
+                                 if (sizeof s.y_ppem) return 0;
+                                 return 1],
+                                ac_cv_member_FT_Bitmap_Size_y_ppem=yes,
+                                ac_cv_member_FT_Bitmap_Size_y_ppem=no)])
+            if test "$ac_cv_member_FT_Bitmap_Size_y_ppem" = yes; then
+                HAVE_FT_BITMAP_SIZE_Y_PPEM=1
+            else
+                HAVE_FT_BITMAP_SIZE_Y_PPEM=0
+            fi
+            AC_DEFINE_UNQUOTED(HAVE_FT_BITMAP_SIZE_Y_PPEM,
+                               $HAVE_FT_BITMAP_SIZE_Y_PPEM,
+                               [FT_Bitmap_Size structure includes y_ppem field])
+
+            AC_CHECK_FUNCS(FT_GlyphSlot_Embolden FT_Load_Sfnt_Table FT_Select_Size)
+
+            LIBS="$_SAVE_LIBS"
+            CFLAGS="$_SAVE_CFLAGS"
+        fi
+
+        _SAVE_CPPFLAGS="$CPPFLAGS"
+        CPPFLAGS="$CPPFLAGS $FT2_CFLAGS $XCFLAGS"
+        MOZ_CHECK_HEADERS([fontconfig/fcfreetype.h], ,
+            [AC_MSG_ERROR(Can't find header fontconfig/fcfreetype.h.)], [#include <fontconfig/fontconfig.h>])
+        CPPFLAGS="$_SAVE_CPPFLAGS"
+    else
+        AC_DEFINE(HAVE_FONTCONFIG_FCFREETYPE_H)
+    fi
+fi
+
 dnl ========================================================
 dnl Check for pixman and cairo
 dnl ========================================================
 
 MOZ_TREE_CAIRO=1
 MOZ_ARG_ENABLE_BOOL(system-cairo,
 [  --enable-system-cairo   Use system cairo (located with pkgconfig)],
 MOZ_TREE_CAIRO=,
@@ -8667,28 +8687,16 @@ dnl Check for headers, etc. needed by We
 if test "$MOZ_GL_DEFAULT_PROVIDER" = "GLX"; then
     MOZ_CHECK_HEADER(GL/glx.h)
     if test "$ac_cv_header_GL_glx_h" != "yes"; then
         AC_MSG_ERROR([Can't find header GL/glx.h for WebGL (install mesa-common-dev (Ubuntu), mesa-libGL-devel (Fedora), or Mesa-devel (openSUSE))])
     fi
 fi # MOZ_GL_DEFAULT_PROVIDER=GLX
 fi # COMPILE_ENVIRONMENT
 
-if test "$USE_FC_FREETYPE"; then
-    if test "$COMPILE_ENVIRONMENT"; then
-    	_SAVE_CPPFLAGS="$CPPFLAGS"
-    	CPPFLAGS="$CPPFLAGS $FT2_CFLAGS $XCFLAGS"
-        MOZ_CHECK_HEADERS([fontconfig/fcfreetype.h], ,
-            [AC_MSG_ERROR(Can't find header fontconfig/fcfreetype.h.)], [#include <fontconfig/fontconfig.h>])
-    	CPPFLAGS="$_SAVE_CPPFLAGS"
-    else
-        AC_DEFINE(HAVE_FONTCONFIG_FCFREETYPE_H)
-    fi
-fi
-
 dnl Set various defines and substitutions
 dnl ========================================================
 
 if test "$OS_ARCH" = "Darwin"; then
   AC_DEFINE(XP_UNIX)
   AC_DEFINE(UNIX_ASYNC_DNS)
 elif test "$OS_ARCH" != "WINNT" -a "$OS_ARCH" != "OS2"; then
   AC_DEFINE(XP_UNIX)
new file mode 100644
--- /dev/null
+++ b/content/base/crashtests/543645.html
@@ -0,0 +1,14 @@
+<!doctype html>
+<body> <span></span> <script>
+function boom() {
+  var range = document.createRange();
+  range.setEnd(document.body.childNodes[2], 0);
+  window.addEventListener("DOMNodeInserted", f, true);
+  function f() {
+    window.removeEventListener("DOMNodeInserted", f, true);
+    range.deleteContents();
+  }
+  range.deleteContents();
+}
+window.addEventListener("load", boom, false);
+</script>
--- a/content/base/crashtests/crashtests.list
+++ b/content/base/crashtests/crashtests.list
@@ -61,16 +61,17 @@ load 483818-1.html
 load 493281-1.html
 load 493281-2.html
 load 490760-1.xhtml
 load 494810-1.html
 load 509536-1.html
 load 522516-1.html
 load 529670.html
 load 535926-1.html
+load 543645.html
 load 551631-1.html
 load 554230-1.xhtml
 load 552651.html
 load 558973.html
 load 561981-1.html
 load 561981-2.html
 load 564079-1.html 
 load 564114.html
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -87,18 +87,18 @@ class Loader;
 
 namespace dom {
 class Link;
 class Element;
 } // namespace dom
 } // namespace mozilla
 
 #define NS_IDOCUMENT_IID \
-{ 0x077dcff0, 0x400d, 0x4d3c, \
-  { 0xbd, 0x4d, 0x5f, 0xd5, 0xe1, 0xa6, 0x63, 0x07 } }
+{ 0x8c6a1e62, 0xd5ad, 0x4297, \
+  { 0xb9, 0x41, 0x64, 0x49, 0x22, 0x2e, 0xc4, 0xf0 } }
 
 // Flag for AddStyleSheet().
 #define NS_STYLESHEET_FROM_CATALOG                (1 << 0)
 
 // Enum for requesting a particular type of document when creating a doc
 enum DocumentFlavor {
   DocumentFlavorLegacyGuess, // compat with old code until made HTML5-compliant
   DocumentFlavorHTML, // HTMLDocument with HTMLness bit set to true
@@ -674,16 +674,22 @@ public:
   /**
    * Return the window containing the document (the outer window).
    */
   nsPIDOMWindow *GetWindow() const
   {
     return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
   }
 
+  bool IsInBackgroundWindow() const
+  {
+    nsPIDOMWindow* outer = mWindow ? mWindow->GetOuterWindow() : nsnull;
+    return outer && outer->IsBackground();
+  }
+  
   /**
    * Return the inner window used as the script compilation scope for
    * this document. If you're not absolutely sure you need this, use
    * GetWindow().
    */
   nsPIDOMWindow* GetInnerWindow()
   {
     return mRemovedFromDocShell ? GetInnerWindowInternal() : mWindow;
--- a/content/base/public/nsTreeSanitizer.h
+++ b/content/base/public/nsTreeSanitizer.h
@@ -173,16 +173,21 @@ class NS_STACK_CLASS nsTreeSanitizer {
      *              otherwise
      */
     bool SanitizeStyleSheet(const nsAString& aOriginal,
                               nsAString& aSanitized,
                               nsIDocument* aDocument,
                               nsIURI* aBaseURI);
 
     /**
+     * Removes all attributes from an element node.
+     */
+    void RemoveAllAttributes(nsIContent* aElement);
+
+    /**
      * The whitelist of HTML elements.
      */
     static nsTHashtable<nsISupportsHashKey>* sElementsHTML;
 
     /**
      * The whitelist of non-presentational HTML attributes.
      */
     static nsTHashtable<nsISupportsHashKey>* sAttributesHTML;
--- a/content/base/src/nsContentIterator.cpp
+++ b/content/base/src/nsContentIterator.cpp
@@ -1108,17 +1108,17 @@ nsContentIterator::GetCurrentNode()
 /******************************************************
  * nsContentSubtreeIterator
  ******************************************************/
 
 
 /*
  *  A simple iterator class for traversing the content in "top subtree" order
  */
-class nsContentSubtreeIterator : public nsContentIterator 
+class nsContentSubtreeIterator : public nsContentIterator
 {
 public:
   nsContentSubtreeIterator() : nsContentIterator(false) {}
   virtual ~nsContentSubtreeIterator() {}
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsContentSubtreeIterator, nsContentIterator)
 
@@ -1137,30 +1137,28 @@ public:
   // Must override these because we don't do PositionAt
   virtual void First();
 
   // Must override these because we don't do PositionAt
   virtual void Last();
 
 protected:
 
-  nsresult GetTopAncestorInRange(nsINode *aNode,
-                                 nsCOMPtr<nsINode> *outAnestor);
+  // Returns the highest inclusive ancestor of aNode that's in the range
+  // (possibly aNode itself).  Returns null if aNode is null, or is not itself
+  // in the range.
+  nsINode* GetTopAncestorInRange(nsINode* aNode);
 
   // no copy's or assigns  FIX ME
   nsContentSubtreeIterator(const nsContentSubtreeIterator&);
   nsContentSubtreeIterator& operator=(const nsContentSubtreeIterator&);
 
   nsRefPtr<nsRange> mRange;
+
   // these arrays all typically are used and have elements
-#if 0
-  nsAutoTArray<nsIContent*, 8> mStartNodes;
-  nsAutoTArray<PRInt32, 8>     mStartOffsets;
-#endif
-
   nsAutoTArray<nsIContent*, 8> mEndNodes;
   nsAutoTArray<PRInt32, 8>     mEndOffsets;
 };
 
 NS_IMPL_ADDREF_INHERITED(nsContentSubtreeIterator, nsContentIterator)
 NS_IMPL_RELEASE_INHERITED(nsContentSubtreeIterator, nsContentIterator)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsContentSubtreeIterator)
@@ -1190,194 +1188,145 @@ NS_NewContentSubtreeIterator()
 
 
 
 /******************************************************
  * Init routines
  ******************************************************/
 
 
-nsresult nsContentSubtreeIterator::Init(nsINode* aRoot)
+nsresult
+nsContentSubtreeIterator::Init(nsINode* aRoot)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 
-nsresult nsContentSubtreeIterator::Init(nsIDOMRange* aRange)
+nsresult
+nsContentSubtreeIterator::Init(nsIDOMRange* aRange)
 {
-  if (!aRange) 
-    return NS_ERROR_NULL_POINTER; 
+  MOZ_ASSERT(aRange);
 
   mIsDone = false;
 
   mRange = static_cast<nsRange*>(aRange);
-  
+
   // get the start node and offset, convert to nsINode
-  nsCOMPtr<nsIDOMNode> commonParent;
-  nsCOMPtr<nsIDOMNode> startParent;
-  nsCOMPtr<nsIDOMNode> endParent;
-  nsCOMPtr<nsINode> nStartP;
-  nsCOMPtr<nsINode> nEndP;
-  nsCOMPtr<nsINode> n;
-  nsINode *firstCandidate = nsnull;
-  nsINode *lastCandidate = nsnull;
-  PRInt32 indx, startIndx, endIndx;
-
-  // get common content parent
-  if (NS_FAILED(aRange->GetCommonAncestorContainer(getter_AddRefs(commonParent))) || !commonParent)
-    return NS_ERROR_FAILURE;
-  mCommonParent = do_QueryInterface(commonParent);
-
-  // get start content parent
-  if (NS_FAILED(aRange->GetStartContainer(getter_AddRefs(startParent))) || !startParent)
-    return NS_ERROR_FAILURE;
-  nStartP = do_QueryInterface(startParent);
-  aRange->GetStartOffset(&startIndx);
-
-  // get end content parent
-  if (NS_FAILED(aRange->GetEndContainer(getter_AddRefs(endParent))) || !endParent)
-    return NS_ERROR_FAILURE;
-  nEndP = do_QueryInterface(endParent);
-  aRange->GetEndOffset(&endIndx);
+  mCommonParent = mRange->GetCommonAncestor();
+  nsINode* startParent = mRange->GetStartParent();
+  PRInt32 startOffset = mRange->StartOffset();
+  nsINode* endParent = mRange->GetEndParent();
+  PRInt32 endOffset = mRange->EndOffset();
+  MOZ_ASSERT(mCommonParent && startParent && endParent);
 
   // short circuit when start node == end node
-  if (startParent == endParent)
-  {
-    nsINode* nChild = nStartP->GetFirstChild();
-  
-    if (!nChild) // no children, must be a text node or empty container
-    {
-      // all inside one text node - empty subtree iterator
+  if (startParent == endParent) {
+    nsINode* child = startParent->GetFirstChild();
+
+    if (!child || startOffset == endOffset) {
+      // Text node, empty container, or collapsed
       MakeEmpty();
       return NS_OK;
     }
-    else
-    {
-      if (startIndx == endIndx)  // collapsed range
-      {
-        MakeEmpty();
-        return NS_OK;
-      }
-    }
   }
-  
+
   // cache ancestors
-#if 0
-  nsContentUtils::GetAncestorsAndOffsets(startParent, startIndx,
-                                         &mStartNodes, &mStartOffsets);
-#endif
-  nsContentUtils::GetAncestorsAndOffsets(endParent, endIndx,
+  nsContentUtils::GetAncestorsAndOffsets(endParent->AsDOMNode(), endOffset,
                                          &mEndNodes, &mEndOffsets);
 
+  nsINode* firstCandidate = nsnull;
+  nsINode* lastCandidate = nsnull;
+
   // find first node in range
-  aRange->GetStartOffset(&indx);
+  PRInt32 offset = mRange->StartOffset();
 
-  if (!nStartP->GetChildCount()) // no children, start at the node itself
-  {
-    n = nStartP;
-  }
-  else
-  {
-    nsINode* nChild = nStartP->GetChildAt(indx);
-    if (!nChild)  // offset after last child
-    {
-      n = nStartP;
-    }
-    else
-    {
-      firstCandidate = nChild;
+  nsINode* node;
+  if (!startParent->GetChildCount()) {
+    // no children, start at the node itself
+    node = startParent;
+  } else {
+    nsINode* child = startParent->GetChildAt(offset);
+    if (!child) {
+      // offset after last child
+      node = startParent;
+    } else {
+      firstCandidate = child;
     }
   }
-  
-  if (!firstCandidate)
-  {
-    // then firstCandidate is next node after cN
-    firstCandidate = GetNextSibling(n, nsnull);
 
-    if (!firstCandidate)
-    {
+  if (!firstCandidate) {
+    // then firstCandidate is next node after node
+    firstCandidate = GetNextSibling(node, nsnull);
+
+    if (!firstCandidate) {
       MakeEmpty();
       return NS_OK;
     }
   }
-  
+
   firstCandidate = GetDeepFirstChild(firstCandidate, nsnull);
-  
-  // confirm that this first possible contained node
-  // is indeed contained.  Else we have a range that
-  // does not fully contain any node.
-  
+
+  // confirm that this first possible contained node is indeed contained.  Else
+  // we have a range that does not fully contain any node.
+
   bool nodeBefore, nodeAfter;
-  if (NS_FAILED(nsRange::CompareNodeToRange(firstCandidate, mRange,
-                                            &nodeBefore, &nodeAfter)))
-    return NS_ERROR_FAILURE;
+  MOZ_ALWAYS_TRUE(NS_SUCCEEDED(
+    nsRange::CompareNodeToRange(firstCandidate, mRange, &nodeBefore, &nodeAfter)));
 
-  if (nodeBefore || nodeAfter)
-  {
+  if (nodeBefore || nodeAfter) {
     MakeEmpty();
     return NS_OK;
   }
 
-  // cool, we have the first node in the range.  Now we walk
-  // up its ancestors to find the most senior that is still
-  // in the range.  That's the real first node.
-  if (NS_FAILED(GetTopAncestorInRange(firstCandidate, address_of(mFirst))))
-    return NS_ERROR_FAILURE;
+  // cool, we have the first node in the range.  Now we walk up its ancestors
+  // to find the most senior that is still in the range.  That's the real first
+  // node.
+  mFirst = GetTopAncestorInRange(firstCandidate);
 
   // now to find the last node
-  aRange->GetEndOffset(&indx);
-  PRInt32 numChildren = nEndP->GetChildCount();
+  offset = mRange->EndOffset();
+  PRInt32 numChildren = endParent->GetChildCount();
 
-  if (indx > numChildren) indx = numChildren;
-  if (!indx)
-  {
-    n = nEndP;
+  if (offset > numChildren) {
+    offset = numChildren;
+  }
+  if (!offset) {
+    node = endParent;
+  } else if (!numChildren) {
+    // no children, must be a text node
+    node = endParent;
+  } else {
+    lastCandidate = endParent->GetChildAt(--offset);
+    NS_ASSERTION(lastCandidate,
+                 "tree traversal trouble in nsContentSubtreeIterator::Init");
   }
-  else
-  {
-    if (!numChildren) // no children, must be a text node
-    {
-      n = nEndP;
-    }
-    else
-    {
-      lastCandidate = nEndP->GetChildAt(--indx);
-      NS_ASSERTION(lastCandidate,
-                   "tree traversal trouble in nsContentSubtreeIterator::Init");
-    }
+
+  if (!lastCandidate) {
+    // then lastCandidate is prev node before node
+    lastCandidate = GetPrevSibling(node, nsnull);
   }
-  
-  if (!lastCandidate)
-  {
-    // then lastCandidate is prev node before n
-    lastCandidate = GetPrevSibling(n, nsnull);
-  }
-  
+
   lastCandidate = GetDeepLastChild(lastCandidate, nsnull);
-  
-  // confirm that this last possible contained node
-  // is indeed contained.  Else we have a range that
-  // does not fully contain any node.
-  
-  if (NS_FAILED(nsRange::CompareNodeToRange(lastCandidate, mRange, &nodeBefore,
-                                            &nodeAfter)))
-    return NS_ERROR_FAILURE;
+
+  // confirm that this last possible contained node is indeed contained.  Else
+  // we have a range that does not fully contain any node.
 
-  if (nodeBefore || nodeAfter)
-  {
+  MOZ_ALWAYS_TRUE(NS_SUCCEEDED(
+    nsRange::CompareNodeToRange(lastCandidate, mRange, &nodeBefore, &nodeAfter)));
+
+  if (nodeBefore || nodeAfter) {
     MakeEmpty();
     return NS_OK;
   }
 
-  // cool, we have the last node in the range.  Now we walk
-  // up its ancestors to find the most senior that is still
-  // in the range.  That's the real first node.
-  if (NS_FAILED(GetTopAncestorInRange(lastCandidate, address_of(mLast))))
-    return NS_ERROR_FAILURE;
-  
+  // cool, we have the last node in the range.  Now we walk up its ancestors to
+  // find the most senior that is still in the range.  That's the real first
+  // node.
+  mLast = GetTopAncestorInRange(lastCandidate);
+
   mCurNode = mFirst;
 
   return NS_OK;
 }
 
 /****************************************************************
  * nsContentSubtreeIterator overrides of ContentIterator routines
  ****************************************************************/
@@ -1399,77 +1348,72 @@ nsContentSubtreeIterator::Last()
 
   mCurNode = mLast;
 }
 
 
 void
 nsContentSubtreeIterator::Next()
 {
-  if (mIsDone || !mCurNode) 
+  if (mIsDone || !mCurNode) {
     return;
+  }
 
-  if (mCurNode == mLast) 
-  {
+  if (mCurNode == mLast) {
     mIsDone = true;
     return;
   }
 
-  nsINode *nextNode = GetNextSibling(mCurNode, nsnull);
+  nsINode* nextNode = GetNextSibling(mCurNode, nsnull);
   NS_ASSERTION(nextNode, "No next sibling!?! This could mean deadlock!");
 
-/*
-  nextNode = GetDeepFirstChild(nextNode);
-  return GetTopAncestorInRange(nextNode, address_of(mCurNode));
-*/
   PRInt32 i = mEndNodes.IndexOf(nextNode);
-  while (i != -1)
-  {
+  while (i != -1) {
     // as long as we are finding ancestors of the endpoint of the range,
     // dive down into their children
     nextNode = nextNode->GetFirstChild();
     NS_ASSERTION(nextNode, "Iterator error, expected a child node!");
 
     // should be impossible to get a null pointer.  If we went all the way
-    // down the child chain to the bottom without finding an interior node, 
+    // down the child chain to the bottom without finding an interior node,
     // then the previous node should have been the last, which was
     // was tested at top of routine.
     i = mEndNodes.IndexOf(nextNode);
   }
 
   mCurNode = nextNode;
 
   // This shouldn't be needed, but since our selection code can put us
   // in a situation where mLast is in generated content, we need this
   // to stop the iterator when we've walked past past the last node!
   mIsDone = mCurNode == nsnull;
-
-  return;
 }
 
 
 void
 nsContentSubtreeIterator::Prev()
 {
   // Prev should be optimized to use the mStartNodes, just as Next
   // uses mEndNodes.
-  if (mIsDone || !mCurNode) 
+  if (mIsDone || !mCurNode) {
     return;
+  }
 
-  if (mCurNode == mFirst) 
-  {
+  if (mCurNode == mFirst) {
     mIsDone = true;
     return;
   }
 
-  nsINode *prevNode = PrevNode(GetDeepFirstChild(mCurNode, nsnull), nsnull);
+  nsINode* prevNode = GetDeepFirstChild(mCurNode, nsnull);
+
+  prevNode = PrevNode(prevNode, nsnull);
 
   prevNode = GetDeepLastChild(prevNode, nsnull);
-  
-  GetTopAncestorInRange(prevNode, address_of(mCurNode));
+
+  mCurNode = GetTopAncestorInRange(prevNode);
 
   // This shouldn't be needed, but since our selection code can put us
   // in a situation where mFirst is in generated content, we need this
   // to stop the iterator when we've walked past past the first node!
   mIsDone = mCurNode == nsnull;
 }
 
 
@@ -1480,55 +1424,43 @@ nsContentSubtreeIterator::PositionAt(nsI
 
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 /****************************************************************
  * nsContentSubtreeIterator helper routines
  ****************************************************************/
 
-nsresult
-nsContentSubtreeIterator::GetTopAncestorInRange(nsINode *aNode,
-                                                nsCOMPtr<nsINode> *outAncestor)
+nsINode*
+nsContentSubtreeIterator::GetTopAncestorInRange(nsINode* aNode)
 {
-  if (!aNode) 
-    return NS_ERROR_NULL_POINTER;
-  if (!outAncestor) 
-    return NS_ERROR_NULL_POINTER;
-  
-  
+  if (!aNode) {
+    return nsnull;
+  }
+
   // sanity check: aNode is itself in the range
   bool nodeBefore, nodeAfter;
-  if (NS_FAILED(nsRange::CompareNodeToRange(aNode, mRange, &nodeBefore,
-                                            &nodeAfter)))
-    return NS_ERROR_FAILURE;
+  nsresult res = nsRange::CompareNodeToRange(aNode, mRange,
+                                             &nodeBefore, &nodeAfter);
+  NS_ASSERTION(NS_SUCCEEDED(res) && !nodeBefore && !nodeAfter,
+               "aNode isn't in mRange, or something else weird happened");
+  if (NS_FAILED(res) || nodeBefore || nodeAfter) {
+    return nsnull;
+  }
 
-  if (nodeBefore || nodeAfter)
-    return NS_ERROR_FAILURE;
-  
   nsCOMPtr<nsINode> parent, tmp;
-  while (aNode)
-  {
+  while (aNode) {
     parent = aNode->GetNodeParent();
-    if (!parent)
-    {
-      if (tmp)
-      {
-        *outAncestor = tmp;
-        return NS_OK;
-      }
-      else return NS_ERROR_FAILURE;
+    if (!parent) {
+      return tmp;
     }
-    if (NS_FAILED(nsRange::CompareNodeToRange(parent, mRange, &nodeBefore,
-                                              &nodeAfter)))
-      return NS_ERROR_FAILURE;
+    MOZ_ALWAYS_TRUE(NS_SUCCEEDED(
+      nsRange::CompareNodeToRange(parent, mRange, &nodeBefore, &nodeAfter)));
 
-    if (nodeBefore || nodeAfter)
-    {
-      *outAncestor = aNode;
-      return NS_OK;
+    if (nodeBefore || nodeAfter) {
+      return aNode;
     }
     tmp = aNode;
     aNode = parent;
   }
-  return NS_ERROR_FAILURE;
+
+  MOZ_NOT_REACHED("This should only be possible if aNode was null");
 }
-
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -1551,18 +1551,19 @@ nsContentSink::WillParseImpl(void)
 
   if (sEnablePerfMode == 0) {
     nsIViewManager* vm = shell->GetViewManager();
     NS_ENSURE_TRUE(vm, NS_ERROR_FAILURE);
     PRUint32 lastEventTime;
     vm->GetLastUserEventTime(lastEventTime);
 
     bool newDynLower =
-      (currentTime - mBeginLoadTime) > PRUint32(sInitialPerfTime) &&
-      (currentTime - lastEventTime) < PRUint32(sInteractiveTime);
+      mDocument->IsInBackgroundWindow() ||
+      ((currentTime - mBeginLoadTime) > PRUint32(sInitialPerfTime) &&
+       (currentTime - lastEventTime) < PRUint32(sInteractiveTime));
     
     if (mDynamicLowerValue != newDynLower) {
       FavorPerformanceHint(!newDynLower, 0);
       mDynamicLowerValue = newDynLower;
     }
   }
   
   mDeflectedCount = 0;
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -2174,16 +2174,22 @@ nsDocument::ResetToURI(nsIURI *aURI, nsI
       nsresult rv =
         securityManager->GetCodebasePrincipal(mDocumentURI,
                                               getter_AddRefs(principal));
       if (NS_SUCCEEDED(rv)) {
         SetPrincipal(principal);
       }
     }
   }
+
+  // Refresh the principal on the compartment.
+  nsPIDOMWindow* win = GetInnerWindow();
+  if (win) {
+    win->RefreshCompartmentPrincipal();
+  }
 }
 
 nsresult
 nsDocument::ResetStylesheetsToURI(nsIURI* aURI)
 {
   NS_PRECONDITION(aURI, "Null URI passed to ResetStylesheetsToURI");
 
   mozAutoDocUpdate upd(this, UPDATE_STYLE, true);
@@ -8411,17 +8417,18 @@ nsDocument::CreateTouch(nsIDOMWindow* aV
                                       aForce));
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocument::CreateTouchList(nsIVariant* aPoints,
                             nsIDOMTouchList** aRetVal)
 {
-  nsRefPtr<nsDOMTouchList> retval = new nsDOMTouchList();
+  nsRefPtr<nsDOMTouchList> retval =
+    new nsDOMTouchList(static_cast<nsIDocument*>(this));
   if (aPoints) {
     PRUint16 type;
     aPoints->GetDataType(&type);
     if (type == nsIDataType::VTYPE_INTERFACE ||
         type == nsIDataType::VTYPE_INTERFACE_IS) {
       nsCOMPtr<nsISupports> data;
       aPoints->GetAsISupports(getter_AddRefs(data));
       nsCOMPtr<nsIDOMTouch> point = do_QueryInterface(data);
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -2206,8 +2206,16 @@ nsFrameLoader::GetTabChildGlobalAsEventT
 
 NS_IMETHODIMP
 nsFrameLoader::GetOwnerElement(nsIDOMElement **aElement)
 {
   nsCOMPtr<nsIDOMElement> ownerElement = do_QueryInterface(mOwnerContent);
   ownerElement.forget(aElement);
   return NS_OK;
 }
+
+void
+nsFrameLoader::SetRemoteBrowser(nsITabParent* aTabParent)
+{
+  MOZ_ASSERT(!mRemoteBrowser);
+  MOZ_ASSERT(!mCurrentRemoteFrame);
+  mRemoteBrowser = static_cast<TabParent*>(aTabParent);
+}
--- a/content/base/src/nsFrameLoader.h
+++ b/content/base/src/nsFrameLoader.h
@@ -22,16 +22,17 @@
 #include "Layers.h"
 #include "mozilla/dom/Element.h"
 
 class nsIURI;
 class nsSubDocumentFrame;
 class nsIView;
 class nsIInProcessContentFrameMessageManager;
 class AutoResetInShow;
+class nsITabParent;
 
 namespace mozilla {
 namespace dom {
 class PBrowserParent;
 class TabParent;
 }
 
 namespace layout {
@@ -251,16 +252,26 @@ public:
   }
   nsFrameMessageManager* GetFrameMessageManager() { return mMessageManager; }
 
   mozilla::dom::Element* GetOwnerContent() { return mOwnerContent; }
   bool ShouldClipSubdocument() { return mClipSubdocument; }
 
   bool ShouldClampScrollPosition() { return mClampScrollPosition; }
 
+  /**
+   * Tell this FrameLoader to use a particular remote browser.
+   *
+   * This will assert if mRemoteBrowser or mCurrentRemoteFrame is non-null.  In
+   * practice, this means you can't have successfully run TryRemoteBrowser() on
+   * this object, which means you can't have called ShowRemoteFrame() or
+   * ReallyStartLoading().
+   */
+  void SetRemoteBrowser(nsITabParent* aTabParent);
+
 private:
 
   void SetOwnerContent(mozilla::dom::Element* aContent);
 
   bool ShouldUseRemoteProcess();
 
   /**
    * Is this a frameloader for a bona fide <iframe mozbrowser>?  (I.e., does
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -1638,16 +1638,17 @@ GK_ATOM(onMozSwipeGesture, "onMozSwipeGe
 GK_ATOM(onMozMagnifyGestureStart, "onMozMagnifyGestureStart")
 GK_ATOM(onMozMagnifyGestureUpdate, "onMozMagnifyGestureUpdate")
 GK_ATOM(onMozMagnifyGesture, "onMozMagnifyGesture")
 GK_ATOM(onMozRotateGestureStart, "onMozRotateGestureStart")
 GK_ATOM(onMozRotateGestureUpdate, "onMozRotateGestureUpdate")
 GK_ATOM(onMozRotateGesture, "onMozRotateGesture")
 GK_ATOM(onMozTapGesture, "onMozTapGesture")
 GK_ATOM(onMozPressTapGesture, "onMozPressTapGesture")
+GK_ATOM(onMozEdgeUIGesture, "onMozEdgeUIGesture")
 
 // Touch events
 GK_ATOM(onMozTouchDown, "onMozTouchDown")
 GK_ATOM(onMozTouchMove, "onMozTouchMove")
 GK_ATOM(onMozTouchUp, "onMozTouchUp")
 
 // orientation support
 GK_ATOM(ondevicemotion, "ondevicemotion")
--- a/content/base/src/nsImageLoadingContent.cpp
+++ b/content/base/src/nsImageLoadingContent.cpp
@@ -267,24 +267,16 @@ nsImageLoadingContent::OnStopDecode(imgI
 
   // If the pending request is loaded, switch to it.
   if (aRequest == mPendingRequest) {
     MakePendingRequestCurrent();
   }
   NS_ABORT_IF_FALSE(aRequest == mCurrentRequest,
                     "One way or another, we should be current by now");
 
-  if (mCurrentRequestNeedsResetAnimation) {
-    nsCOMPtr<imgIContainer> container;
-    mCurrentRequest->GetImage(getter_AddRefs(container));
-    if (container)
-      container->ResetAnimation();
-    mCurrentRequestNeedsResetAnimation = false;
-  }
-
   // We just loaded all the data we're going to get. If we're visible and
   // haven't done an initial paint (*), we want to make sure the image starts
   // decoding immediately, for two reasons:
   //
   // 1) This image is sitting idle but might need to be decoded as soon as we
   // start painting, in which case we've wasted time.
   //
   // 2) We want to block onload until all visible images are decoded. We do this
@@ -574,16 +566,17 @@ nsImageLoadingContent::LoadImageWithChan
 
   // Do the load.
   nsCOMPtr<imgIRequest>& req = PrepareNextRequest();
   nsresult rv = nsContentUtils::GetImgLoader()->
     LoadImageWithChannel(aChannel, this, doc, aListener,
                          getter_AddRefs(req));
   if (NS_SUCCEEDED(rv)) {
     TrackImage(req);
+    ResetAnimationIfNeeded();
   } else {
     // If we don't have a current URI, we might as well store this URI so people
     // know what we tried (and failed) to load.
     if (!mCurrentRequest)
       aChannel->GetURI(getter_AddRefs(mCurrentURI));
     FireEvent(NS_LITERAL_STRING("error"));
     return rv;
   }
@@ -741,16 +734,17 @@ nsImageLoadingContent::LoadImage(nsIURI*
   nsresult rv;
   rv = nsContentUtils::LoadImage(aNewURI, aDocument,
                                  aDocument->NodePrincipal(),
                                  aDocument->GetDocumentURI(),
                                  this, loadFlags,
                                  getter_AddRefs(req));
   if (NS_SUCCEEDED(rv)) {
     TrackImage(req);
+    ResetAnimationIfNeeded();
 
     // Handle cases when we just ended up with a pending request but it's
     // already done.  In that situation we have to synchronously switch that
     // request to being the current request, because websites depend on that
     // behavior.
     if (req == mPendingRequest) {
       PRUint32 pendingLoadStatus;
       rv = req->GetImageStatus(&pendingLoadStatus);
@@ -1023,16 +1017,17 @@ nsImageLoadingContent::PreparePendingReq
 void
 nsImageLoadingContent::MakePendingRequestCurrent()
 {
   MOZ_ASSERT(mPendingRequest);
   PrepareCurrentRequest() = mPendingRequest;
   mPendingRequest = nsnull;
   mCurrentRequestNeedsResetAnimation = mPendingRequestNeedsResetAnimation;
   mPendingRequestNeedsResetAnimation = false;
+  ResetAnimationIfNeeded();
 }
 
 void
 nsImageLoadingContent::ClearCurrentRequest(nsresult aReason)
 {
   if (!mCurrentRequest) {
     // Even if we didn't have a current request, we might have been keeping
     // a URI as a placeholder for a failed load. Clear that now.
@@ -1088,16 +1083,28 @@ nsImageLoadingContent::GetRegisteredFlag
     return &mCurrentRequestRegistered;
   } else if (aRequest == mPendingRequest) {
     return &mPendingRequestRegistered;
   } else {
     return nsnull;
   }
 }
 
+void
+nsImageLoadingContent::ResetAnimationIfNeeded()
+{
+  if (mCurrentRequest && mCurrentRequestNeedsResetAnimation) {
+    nsCOMPtr<imgIContainer> container;
+    mCurrentRequest->GetImage(getter_AddRefs(container));
+    if (container)
+      container->ResetAnimation();
+    mCurrentRequestNeedsResetAnimation = false;
+  }
+}
+
 bool
 nsImageLoadingContent::HaveSize(imgIRequest *aImage)
 {
   // Handle the null case
   if (!aImage)
     return false;
 
   // Query the image
--- a/content/base/src/nsImageLoadingContent.h
+++ b/content/base/src/nsImageLoadingContent.h
@@ -281,16 +281,22 @@ protected:
    *
    * @returns A pointer to the boolean flag for a given image request, or
    *          |nsnull| if the request is not either |mPendingRequest| or
    *          |mCurrentRequest|.
    */
   bool* GetRegisteredFlagForRequest(imgIRequest* aRequest);
 
   /**
+   * Reset animation of the current request if |mNewRequestsWillNeedAnimationReset|
+   * was true when the request was prepared.
+   */
+  void ResetAnimationIfNeeded();
+
+  /**
    * Static helper method to tell us if we have the size of a request. The
    * image may be null.
    */
   static bool HaveSize(imgIRequest *aImage);
 
   /**
    * Adds/Removes a given imgIRequest from our document's tracker.
    *
--- a/content/base/src/nsTreeSanitizer.cpp
+++ b/content/base/src/nsTreeSanitizer.cpp
@@ -1404,16 +1404,21 @@ nsTreeSanitizer::SanitizeChildren(nsINod
   while (node) {
     if (node->IsElement()) {
       mozilla::dom::Element* elt = node->AsElement();
       nsINodeInfo* nodeInfo = node->NodeInfo();
       nsIAtom* localName = nodeInfo->NameAtom();
       PRInt32 ns = nodeInfo->NamespaceID();
 
       if (MustPrune(ns, localName, elt)) {
+        RemoveAllAttributes(node);
+        nsIContent* descendant = node;
+        while ((descendant = descendant->GetNextNode(node))) {
+          RemoveAllAttributes(descendant);
+        }
         nsIContent* next = node->GetNextNonChildNode(aRoot);
         node->GetParent()->RemoveChild(node);
         node = next;
         continue;
       }
       if (nsGkAtoms::style == localName) {
         // If styles aren't allowed, style elements got pruned above. Even
         // if styles are allowed, non-HTML, non-SVG style elements got pruned
@@ -1447,16 +1452,17 @@ nsTreeSanitizer::SanitizeChildren(nsINod
                              true,
                              mAllowStyles,
                              false);
         }
         node = node->GetNextNonChildNode(aRoot);
         continue;
       }
       if (MustFlatten(ns, localName)) {
+        RemoveAllAttributes(node);
         nsIContent* next = node->GetNextNode(aRoot);
         nsIContent* parent = node->GetParent();
         nsCOMPtr<nsIContent> child; // Must keep the child alive during move
         nsresult rv;
         while ((child = node->GetFirstChild())) {
           parent->InsertBefore(child, node, &rv);
           if (NS_FAILED(rv)) {
             break;
@@ -1500,16 +1506,27 @@ nsTreeSanitizer::SanitizeChildren(nsINod
     if (!mAllowComments && node->IsNodeOfType(nsINode::eCOMMENT)) {
       node->GetNodeParent()->RemoveChild(node);
     }
     node = next;
   }
 }
 
 void
+nsTreeSanitizer::RemoveAllAttributes(nsIContent* aElement)
+{
+  const nsAttrName* attrName;
+  while ((attrName = aElement->GetAttrNameAt(0))) {
+    PRInt32 attrNs = attrName->NamespaceID();
+    nsCOMPtr<nsIAtom> attrLocal = attrName->LocalName();
+    aElement->UnsetAttr(attrNs, attrLocal, false);
+  }
+}
+
+void
 nsTreeSanitizer::InitializeStatics()
 {
   NS_PRECONDITION(!sElementsHTML, "Initializing a second time.");
 
   sElementsHTML = new nsTHashtable<nsISupportsHashKey> ();
   sElementsHTML->Init(ArrayLength(kElementsHTML));
   for (PRUint32 i = 0; kElementsHTML[i]; i++) {
     sElementsHTML->PutEntry(*kElementsHTML[i]);
--- a/content/base/test/file_x-frame-options_main.html
+++ b/content/base/test/file_x-frame-options_main.html
@@ -9,11 +9,16 @@ window.addEventListener('load', parent.t
 </head>
 <body>
 
 <iframe id="control1" src="http://mochi.test:8888/tests/content/base/test/file_x-frame-options_page.sjs?testid=control1"></iframe><br>
 <iframe id="control2" src="http://example.com/tests/content/base/test/file_x-frame-options_page.sjs?testid=control2"></iframe><br>
 <iframe id="deny" src="http://mochi.test:8888/tests/content/base/test/file_x-frame-options_page.sjs?testid=deny&xfo=deny"></iframe><br>
 <iframe id="sameorigin1" src="http://mochi.test:8888/tests/content/base/test/file_x-frame-options_page.sjs?testid=sameorigin1&xfo=sameorigin"></iframe><br>
 <iframe id="sameorigin2" src="http://example.com/tests/content/base/test/file_x-frame-options_page.sjs?testid=sameorigin2&xfo=sameorigin"></iframe><br>
+<iframe id="sameorigin5" src="http://example.com/tests/content/base/test/file_x-frame-options_page.sjs?testid=sameorigin5&xfo=sameorigin2"></iframe><br>
+<iframe id="sameorigin6" src="http://mochi.test:8888/tests/content/base/test/file_x-frame-options_page.sjs?testid=sameorigin6&xfo=sameorigin2"></iframe><br>
+<iframe id="sameorigin7" src="http://mochi.test:8888/tests/content/base/test/file_x-frame-options_page.sjs?testid=sameorigin7&xfo=sameorigin3"></iframe><br>
+<iframe id="sameorigin8" src="http://example.com/tests/content/base/test/file_x-frame-options_page.sjs?testid=sameorigin8&xfo=sameorigin3"></iframe><br>
+<iframe id="mixedpolicy" src="http://mochi.test:8888/tests/content/base/test/file_x-frame-options_page.sjs?testid=mixedpolicy&xfo=mixedpolicy"></iframe><br>
 
 </body>
 </html>
--- a/content/base/test/file_x-frame-options_page.sjs
+++ b/content/base/test/file_x-frame-options_page.sjs
@@ -12,13 +12,22 @@ function handleRequest(request, response
 
   // X-Frame-Options header value
   if (query['xfo'] == "deny") {
     response.setHeader("X-Frame-Options", "DENY", false);
   }
   else if (query['xfo'] == "sameorigin") {
     response.setHeader("X-Frame-Options", "SAMEORIGIN", false);
   }
+  else if (query['xfo'] == "sameorigin2") {
+    response.setHeader("X-Frame-Options", "SAMEORIGIN, SAMEORIGIN", false);
+  }
+  else if (query['xfo'] == "sameorigin3") {
+    response.setHeader("X-Frame-Options", "SAMEORIGIN,SAMEORIGIN , SAMEORIGIN", false);
+  }
+  else if (query['xfo'] == "mixedpolicy") {
+    response.setHeader("X-Frame-Options", "DENY,SAMEORIGIN", false);
+  }
 
   // from the test harness we'll be checking for the presence of this element
   // to test if the page loaded
   response.write("<h1 id=\"test\">" + query["testid"] + "</h1>");
 }
--- a/content/base/test/test_x-frame-options.html
+++ b/content/base/test/test_x-frame-options.html
@@ -78,16 +78,41 @@ var testFramesLoaded = function() {
   var test4 = frame.contentDocument.getElementById("test").textContent;
   is(test4, "sameorigin1", "test sameorigin1");
 
   // iframe from different origin, X-F-O: SAMEORIGIN - should not load
   frame = harness.contentDocument.getElementById("sameorigin2");
   var test5 = frame.contentDocument.getElementById("test");
   is(test5, null, "test sameorigin2");
 
+  // iframe from different origin, X-F-O: SAMEORIGIN, SAMEORIGIN - should not load
+  frame = harness.contentDocument.getElementById("sameorigin5");
+  var test6 = frame.contentDocument.getElementById("test");
+  is(test6, null, "test sameorigin5");
+
+  // iframe from same origin, X-F-O: SAMEORIGIN, SAMEORIGIN - should load
+  frame = harness.contentDocument.getElementById("sameorigin6");
+  var test7 = frame.contentDocument.getElementById("test").textContent;
+  is(test7, "sameorigin6", "test sameorigin6");
+
+  // iframe from same origin, X-F-O: SAMEORIGIN,SAMEORIGIN, SAMEORIGIN - should load
+  frame = harness.contentDocument.getElementById("sameorigin7");
+  var test8 = frame.contentDocument.getElementById("test").textContent;
+  is(test8, "sameorigin7", "test sameorigin7");
+
+  // iframe from same origin, X-F-O: SAMEORIGIN,SAMEORIGIN, SAMEORIGIN - should not load
+  frame = harness.contentDocument.getElementById("sameorigin8");
+  var test9 = frame.contentDocument.getElementById("test");
+  is(test9, null, "test sameorigin8");
+
+  // iframe from same origin, X-F-O: DENY,SAMEORIGIN - should not load
+  frame = harness.contentDocument.getElementById("mixedpolicy");
+  var test10 = frame.contentDocument.getElementById("test");
+  is(test10, null, "test mixedpolicy");
+
   // call tests to check principal comparison, e.g. a document can open a window
   // to a data: or javascript: document which frames an
   // X-Frame-Options: SAMEORIGIN document and the frame should load
   testFrameInJSURI();
 }
 
 // test that a document can be framed under a javascript: URL opened by the
 // same site as the frame
new file mode 100644
--- /dev/null
+++ b/content/canvas/crashtests/746813-1.html
@@ -0,0 +1,6 @@
+<!DOCTYPE html>
+<html>
+<body onload="document.getElementById('c').getContext('2d').mozCurrentTransformInverse;">
+<canvas id="c" width="772" height="76441"></canvas>
+</body>
+</html>
--- a/content/canvas/crashtests/crashtests.list
+++ b/content/canvas/crashtests/crashtests.list
@@ -1,11 +1,12 @@
 load 360293-1.html
 load 421715-1.html
 load 553938-1.html
 load 647480.html
 load 0px-size-font-667225.html
 load texImage2D.html
 load 729116.html
 load 745699-1.html
+load 746813-1.html
 # this test crashes in a bunch places still
 #load 745818-large-source.html
 load 743499-negative-size.html
--- a/content/canvas/src/WebGLContext.cpp
+++ b/content/canvas/src/WebGLContext.cpp
@@ -856,17 +856,23 @@ bool WebGLContext::IsExtensionSupported(
         case WebGL_EXT_texture_filter_anisotropic:
             isSupported = gl->IsExtensionSupported(GLContext::EXT_texture_filter_anisotropic);
             break;
         case WebGL_WEBGL_lose_context:
             // We always support this extension.
             isSupported = true;
             break;
         case WebGL_WEBGL_compressed_texture_s3tc:
-            isSupported = gl->IsExtensionSupported(GLContext::EXT_texture_compression_s3tc);
+            if (gl->IsExtensionSupported(GLContext::EXT_texture_compression_s3tc)) {
+                isSupported = true;
+            } else {
+                isSupported = gl->IsExtensionSupported(GLContext::EXT_texture_compression_dxt1) &&
+                              gl->IsExtensionSupported(GLContext::ANGLE_texture_compression_dxt3) &&
+                              gl->IsExtensionSupported(GLContext::ANGLE_texture_compression_dxt5);
+            }
             break;
         default:
             isSupported = false;
     }
 
     return isSupported;
 }
 
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -3928,18 +3928,16 @@ WebGLContext::ReadPixels(WebGLint x, Web
     }
 
     MakeContextCurrent();
 
     if (mBoundFramebuffer) {
         // prevent readback of arbitrary video memory through uninitialized renderbuffers!
         if (!mBoundFramebuffer->CheckAndInitializeRenderbuffers())
             return ErrorInvalidFramebufferOperation("readPixels: incomplete framebuffer");
-    } else {
-        EnsureBackbufferClearedAsNeeded();
     }
     // Now that the errors are out of the way, on to actually reading
 
     // If we won't be reading any pixels anyways, just skip the actual reading
     if (width == 0 || height == 0)
         return DummyFramebufferOperation("readPixels");
 
     if (CanvasUtils::CheckSaneSubrectSize(x, y, width, height, framebufferWidth, framebufferHeight)) {
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -1536,16 +1536,19 @@ nsCanvasRenderingContext2D::SetMozCurren
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::GetMozCurrentTransformInverse(JSContext* cx,
                                                           jsval* matrix)
 {
+    if (!EnsureSurface())
+        return NS_ERROR_FAILURE;
+
     gfxMatrix ctm = mThebes->CurrentMatrix();
 
     if (!mThebes->CurrentMatrix().IsSingular()) {
         ctm.Invert();
     } else {
         double NaN = JSVAL_TO_DOUBLE(JS_GetNaNValue(cx));
         ctm = gfxMatrix(NaN, NaN, NaN, NaN, NaN, NaN);
     }
--- a/content/canvas/src/nsCanvasRenderingContext2DAzure.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2DAzure.cpp
@@ -1530,109 +1530,138 @@ nsCanvasRenderingContext2DAzure::Restore
 
 //
 // transformations
 //
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2DAzure::Scale(float x, float y)
 {
-  if (!FloatValidate(x,y))
+  if (!mTarget) {
+    return NS_ERROR_FAILURE;
+  }
+  if (!FloatValidate(x,y)) {
     return NS_OK;
+  }
 
   TransformWillUpdate();
 
   Matrix newMatrix = mTarget->GetTransform();
   mTarget->SetTransform(newMatrix.Scale(x, y));
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2DAzure::Rotate(float angle)
 {
-  if (!FloatValidate(angle))
+  if (!mTarget) {
+    return NS_ERROR_FAILURE;
+  }
+  if (!FloatValidate(angle)) {
     return NS_OK;
+  }
 
   TransformWillUpdate();
 
   Matrix rotation = Matrix::Rotation(angle);
   mTarget->SetTransform(rotation * mTarget->GetTransform());
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2DAzure::Translate(float x, float y)
 {
+  if (!mTarget) {
+    return NS_ERROR_FAILURE;
+  }
   if (!FloatValidate(x,y)) {
     return NS_OK;
   }
 
   TransformWillUpdate();
 
   Matrix newMatrix = mTarget->GetTransform();
   mTarget->SetTransform(newMatrix.Translate(x, y));
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2DAzure::Transform(float m11, float m12, float m21, float m22, float dx, float dy)
 {
+  if (!mTarget) {
+    return NS_ERROR_FAILURE;
+  }
   if (!FloatValidate(m11,m12,m21,m22,dx,dy)) {
     return NS_OK;
   }
 
   TransformWillUpdate();
 
   Matrix matrix(m11, m12, m21, m22, dx, dy);
   mTarget->SetTransform(matrix * mTarget->GetTransform());
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2DAzure::SetTransform(float m11, float m12, float m21, float m22, float dx, float dy)
 {
+  if (!mTarget) {
+    return NS_ERROR_FAILURE;
+  }
   if (!FloatValidate(m11,m12,m21,m22,dx,dy)) {
     return NS_OK;
   }
 
   TransformWillUpdate();
 
   Matrix matrix(m11, m12, m21, m22, dx, dy);
   mTarget->SetTransform(matrix);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2DAzure::SetMozCurrentTransform(JSContext* cx,
                                                         const jsval& matrix)
 {
+  if (!mTarget) {
+    return NS_ERROR_FAILURE;
+  }
+
   nsresult rv;
   Matrix newCTM;
 
   if (!JSValToMatrix(cx, matrix, &newCTM, &rv)) {
     return rv;
   }
 
   mTarget->SetTransform(newCTM);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2DAzure::GetMozCurrentTransform(JSContext* cx,
                                                         jsval* matrix)
 {
+  if (!mTarget) {
+    return NS_ERROR_FAILURE;
+  }
+
   return MatrixToJSVal(mTarget->GetTransform(), cx, matrix);
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2DAzure::SetMozCurrentTransformInverse(JSContext* cx,
                                                                const jsval& matrix)
 {
+  if (!mTarget) {
+    return NS_ERROR_FAILURE;
+  }
+
   nsresult rv;
   Matrix newCTMInverse;
 
   if (!JSValToMatrix(cx, matrix, &newCTMInverse, &rv)) {
     return rv;
   }
 
   // XXX ERRMSG we need to report an error to developers here! (bug 329026)
@@ -1642,16 +1671,20 @@ nsCanvasRenderingContext2DAzure::SetMozC
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2DAzure::GetMozCurrentTransformInverse(JSContext* cx,
                                                                jsval* matrix)
 {
+  if (!mTarget) {
+    return NS_ERROR_FAILURE;
+  }
+
   Matrix ctm = mTarget->GetTransform();
 
   if (!ctm.Invert()) {
     double NaN = JSVAL_TO_DOUBLE(JS_GetNaNValue(cx));
     ctm = Matrix(NaN, NaN, NaN, NaN, NaN, NaN);
   }
 
   return MatrixToJSVal(ctm, cx, matrix);
--- a/content/canvas/test/test_canvas.html
+++ b/content/canvas/test/test_canvas.html
@@ -5931,17 +5931,22 @@ var ctx = canvas.getContext('2d');
 ctx.fillStyle = '#0f0';
 ctx.fillRect(0, 0, 100, 50);
 
 var g = ctx.createLinearGradient(50, 25, 50, 25); // zero-length line (undefined direction)
 g.addColorStop(0, '#f00');
 g.addColorStop(1, '#f00');
 ctx.fillStyle = g;
 ctx.fillRect(0, 0, 100, 50);
-todo_isPixel(ctx, 40,20, 0,255,0,255, 2);
+
+if (IsAzureEnabled() && IsAzureSkia()) {
+  isPixel(ctx, 40,20, 0,255,0,255, 2);
+} else {
+  todo_isPixel(ctx, 40,20, 0,255,0,255, 2);
+}
 
 
 }
 </script>
 
 <!-- [[[ test_2d.gradient.linear.nonfinite.html ]]] -->
 
 <p>Canvas test: 2d.gradient.linear.nonfinite</p>
--- a/content/canvas/test/webgl/conformance/reading/read-pixels-test.html
+++ b/content/canvas/test/webgl/conformance/reading/read-pixels-test.html
@@ -14,16 +14,17 @@ found in the LICENSE file.
 <script src="../resources/webgl-test-utils.js"> </script>
 </head>
 <body>
 <canvas id="example" width="200" height="200" style="width: 20px; height: 20px"></canvas>
 <div id="description"></div>
 <div id="console"></div>
 <script>
 description("Checks that ReadPixels works as expected.");
+testPassed("read-pixels-test start: " + (new Date().getTime()));
 
 var wtu = WebGLTestUtils;
 var canvas = document.getElementById("example");
 var gl = create3DContext(canvas);
 
 if (window.initNonKhronosFramework) {
    window.initNonKhronosFramework(true);
 }
@@ -175,16 +176,17 @@ function continueTestPart1() {
   canvas.width = width;
   canvas.height = height;
   if (gl.getError() != gl.CONTEXT_LOST_WEBGL) {
     continueTestPart2();
   }
 }
 
 function continueTestPart2() {
+testPassed("read-pixels-test continueTestPart2: " + (new Date().getTime()));
   gl.viewport(0, 0, 1024, 1024);
   var program = wtu.setupTexturedQuad(gl);
   var loc = gl.getUniformLocation(program, "tex");
   gl.disable(gl.BLEND);
   gl.disable(gl.DEPTH_TEST);
   var colors = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]];
   var textures = [];
   var results = [];
@@ -212,14 +214,23 @@ function continueTestPart2() {
     var color = colors[ii];
     actual = [buf[0], buf[1], buf[2], buf[3]];
     expected = [color[0], color[1], color[2], color[3]];
     shouldBe("actual", "expected");
   }
   glErrorShouldBe(gl, gl.NO_ERROR, "there should be no GL errors");
 
   debug("");
-  finishTest();
+
+  // bug 763355: temporary logging of exceptions here to understand intermittent timeout
+  // in this test, apparently in this finishTest() call.
+  try {
+    testPassed("read-pixels-test calling finishTest: " + (new Date().getTime()));
+    finishTest();
+    testPassed("read-pixels-test after finishTest: " + (new Date().getTime()));
+  } catch(e) {
+    testFailed("finishTest generated exception: " + e);
+  }
 }
 </script>
 </body>
 </html>
 
--- a/content/canvas/test/webgl/resources/js-test-pre.js
+++ b/content/canvas/test/webgl/resources/js-test-pre.js
@@ -464,19 +464,22 @@ function gc() {
         temp += "foo";
         gcRec(n-1);
     }
     for (var i = 0; i < 1000; i++)
         gcRec(10);
 }
 
 function finishTest() {
+  testPassed("beginning of finishTest: " + (new Date().getTime()));
+
   successfullyParsed = true;
   var epilogue = document.createElement("script");
   epilogue.onload = function() {
+    testPassed("finishTest epilogue onload: " + (new Date().getTime()));
     if (window.nonKhronosFrameworkNotifyDone) {
       window.nonKhronosFrameworkNotifyDone();
     }
   };
 
   var basePath = "";
   var expectedBase = "js-test-pre.js";
   var scripts = document.getElementsByTagName('script');
@@ -485,10 +488,11 @@ function finishTest() {
     var l = src.length;
     if (src.substr(l - expectedBase.length) == expectedBase) {
       basePath = src.substr(0, l - expectedBase.length);
       break;
     }
   }
   epilogue.src = basePath + "js-test-post.js";
   document.body.appendChild(epilogue);
+  testPassed("end of finishTest: " + (new Date().getTime()));
 }
 
--- a/content/events/public/nsEventNameList.h
+++ b/content/events/public/nsEventNameList.h
@@ -707,16 +707,20 @@ NON_IDL_EVENT(MozRotateGesture,
 NON_IDL_EVENT(MozTapGesture,
               NS_SIMPLE_GESTURE_TAP,
               EventNameType_None,
               NS_SIMPLE_GESTURE_EVENT)
 NON_IDL_EVENT(MozPressTapGesture,
               NS_SIMPLE_GESTURE_PRESSTAP,
               EventNameType_None,
               NS_SIMPLE_GESTURE_EVENT)
+NON_IDL_EVENT(MozEdgeUIGesture,
+              NS_SIMPLE_GESTURE_EDGEUI,
+              EventNameType_None,
+              NS_SIMPLE_GESTURE_EVENT)
 
 NON_IDL_EVENT(MozTouchDown,
               NS_MOZTOUCH_DOWN,
               EventNameType_None,
               NS_MOZTOUCH_EVENT)
 NON_IDL_EVENT(MozTouchMove,
               NS_MOZTOUCH_MOVE,
               EventNameType_None,
--- a/content/events/src/Makefile.in
+++ b/content/events/src/Makefile.in
@@ -61,35 +61,38 @@ CPPSRCS		= \
 		nsDOMEventTargetHelper.cpp \
 		nsDOMScrollAreaEvent.cpp \
 		nsDOMTransitionEvent.cpp \
 		nsDOMAnimationEvent.cpp \
 		nsDOMPopStateEvent.cpp \
 		nsDOMHashChangeEvent.cpp \
 		nsDOMCloseEvent.cpp \
 		nsDOMSettingsEvent.cpp \
+		nsDOMContactChangeEvent.cpp \
 		nsDOMTouchEvent.cpp \
 		nsDOMCustomEvent.cpp \
 		nsDOMCompositionEvent.cpp \
+		nsDOMApplicationEvent.cpp \
 		$(NULL)
 
 # we don't want the shared lib, but we want to force the creation of a static lib.
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/config/config.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
 include $(topsrcdir)/config/rules.mk
 
 LOCAL_INCLUDES	+= \
              -I$(srcdir)/../../base/src \
              -I$(srcdir)/../../html/content/src \
              -I$(srcdir)/../../xul/content/src \
              -I$(srcdir)/../../xml/content/src \
              -I$(srcdir)/../../../dom/base \
              -I$(srcdir)/../../../dom/settings \
+             -I$(srcdir)/../../../dom/contacts \
              -I$(srcdir)/../../../dom/src/storage \
              -I$(srcdir)/../../../layout/generic \
              -I$(srcdir)/../../../layout/xul/base/src \
              -I$(srcdir)/../../../layout/xul/base/src/tree/src \
              $(NULL)
 
 DEFINES += -D_IMPL_NS_LAYOUT
 
new file mode 100644
--- /dev/null
+++ b/content/events/src/nsDOMApplicationEvent.cpp
@@ -0,0 +1,67 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+* License, v. 2.0. If a copy of the MPL was not distributed with this file,
+* You can obtain one at http://mozilla.org/MPL/2.0/. */
+ 
+#include "nsDOMApplicationEvent.h"
+#include "nsContentUtils.h"
+#include "DictionaryHelpers.h"
+ 
+DOMCI_DATA(MozApplicationEvent, nsDOMMozApplicationEvent)
+
+NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMMozApplicationEvent)
+
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsDOMMozApplicationEvent, nsDOMEvent)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mApplication)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsDOMMozApplicationEvent, nsDOMEvent)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mApplication)
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMMozApplicationEvent)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMMozApplicationEvent)
+  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(MozApplicationEvent)
+NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent)
+ 
+NS_IMPL_ADDREF_INHERITED(nsDOMMozApplicationEvent, nsDOMEvent)
+NS_IMPL_RELEASE_INHERITED(nsDOMMozApplicationEvent, nsDOMEvent)
+ 
+NS_IMETHODIMP
+nsDOMMozApplicationEvent::GetApplication(mozIDOMApplication** aApplication)
+{
+  NS_IF_ADDREF(*aApplication = mApplication);
+  return NS_OK;
+}
+ 
+NS_IMETHODIMP
+nsDOMMozApplicationEvent::InitMozApplicationEvent(const nsAString& aType,
+                                                  bool aCanBubble,
+                                                  bool aCancelable,
+                                                  mozIDOMApplication* aApplication)
+{
+  nsresult rv = nsDOMEvent::InitEvent(aType, aCanBubble, aCancelable);
+  NS_ENSURE_SUCCESS(rv, rv);
+ 
+  mApplication = aApplication;
+
+  return NS_OK;
+}
+ 
+nsresult
+nsDOMMozApplicationEvent::InitFromCtor(const nsAString& aType, JSContext* aCx, jsval* aVal)
+{
+  mozilla::dom::MozApplicationEventInit d;
+  nsresult rv = d.Init(aCx, aVal);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return InitMozApplicationEvent(aType, d.bubbles, d.cancelable, d.application);
+}
+ 
+nsresult
+NS_NewDOMMozApplicationEvent(nsIDOMEvent** aInstancePtrResult,
+                             nsPresContext* aPresContext,
+                             nsEvent* aEvent)
+{
+  nsDOMMozApplicationEvent* e = new nsDOMMozApplicationEvent(aPresContext, aEvent);
+  return CallQueryInterface(e, aInstancePtrResult);
+}
new file mode 100644
--- /dev/null
+++ b/content/events/src/nsDOMApplicationEvent.h
@@ -0,0 +1,32 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+* License, v. 2.0. If a copy of the MPL was not distributed with this file,
+* You can obtain one at http://mozilla.org/MPL/2.0/. */
+ 
+#ifndef nsDOMApplicationEvent_h__
+#define nsDOMApplicationEvent_h__
+ 
+#include "nsIDOMApplicationRegistry.h"
+#include "nsDOMEvent.h"
+ 
+class nsDOMMozApplicationEvent : public nsDOMEvent,
+                                 public nsIDOMMozApplicationEvent
+{
+public:
+  nsDOMMozApplicationEvent(nsPresContext* aPresContext, nsEvent* aEvent)
+    : nsDOMEvent(aPresContext, aEvent) {}
+
+  NS_DECL_ISUPPORTS_INHERITED
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMMozApplicationEvent, nsDOMEvent)
+  // Forward to base class
+  NS_FORWARD_TO_NSDOMEVENT
+ 
+  NS_DECL_NSIDOMMOZAPPLICATIONEVENT
+ 
+  virtual nsresult InitFromCtor(const nsAString& aType, JSContext* aCx, jsval* aVal);
+
+private:
+  nsCOMPtr<mozIDOMApplication> mApplication;
+};
+ 
+#endif // nsDOMContactChangeEvent_h__
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/content/events/src/nsDOMContactChangeEvent.cpp
@@ -0,0 +1,67 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsDOMContactChangeEvent.h"
+#include "nsContentUtils.h"
+#include "DictionaryHelpers.h"
+
+DOMCI_DATA(MozContactChangeEvent, nsDOMMozContactChangeEvent)
+
+NS_INTERFACE_MAP_BEGIN(nsDOMMozContactChangeEvent)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMMozContactChangeEvent)
+  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(MozContactChangeEvent)
+NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent)
+
+NS_IMPL_ADDREF_INHERITED(nsDOMMozContactChangeEvent, nsDOMEvent)
+NS_IMPL_RELEASE_INHERITED(nsDOMMozContactChangeEvent, nsDOMEvent)
+
+NS_IMETHODIMP
+nsDOMMozContactChangeEvent::GetContactID(nsAString& aContactID)
+{
+  aContactID = mContactID;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDOMMozContactChangeEvent::GetReason(nsAString& aReason)
+{
+  aReason = mReason;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDOMMozContactChangeEvent::InitMozContactChangeEvent(const nsAString& aType,
+                                                      bool aCanBubble,
+                                                      bool aCancelable,
+                                                      const nsAString& aContactID,
+                                                      const nsAString& aReason)
+{
+  nsresult rv = nsDOMEvent::InitEvent(aType, aCanBubble, aCancelable);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  mContactID = aContactID;
+  mReason = aReason;
+
+  return NS_OK;
+}
+
+nsresult
+nsDOMMozContactChangeEvent::InitFromCtor(const nsAString& aType,
+                                         JSContext* aCx, jsval* aVal)
+{
+  mozilla::dom::MozContactChangeEventInit d;
+  nsresult rv = d.Init(aCx, aVal);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return InitMozContactChangeEvent(aType, d.bubbles, d.cancelable, d.contactID, d.reason);
+}
+
+nsresult
+NS_NewDOMMozContactChangeEvent(nsIDOMEvent** aInstancePtrResult,
+                               nsPresContext* aPresContext,
+                               nsEvent* aEvent) 
+{
+  nsDOMMozContactChangeEvent* e = new nsDOMMozContactChangeEvent(aPresContext, aEvent);
+  return CallQueryInterface(e, aInstancePtrResult);
+}
new file mode 100644
--- /dev/null
+++ b/content/events/src/nsDOMContactChangeEvent.h
@@ -0,0 +1,33 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef nsDOMContactChangeEvent_h__
+#define nsDOMContactChangeEvent_h__
+
+#include "nsIDOMContactManager.h"
+#include "nsDOMEvent.h"
+
+class nsDOMMozContactChangeEvent : public nsDOMEvent,
+                                   public nsIDOMMozContactChangeEvent
+{
+public:
+  nsDOMMozContactChangeEvent(nsPresContext* aPresContext, nsEvent* aEvent)
+    : nsDOMEvent(aPresContext, aEvent) {}
+                     
+  NS_DECL_ISUPPORTS_INHERITED
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMMozContactChangeEvent, nsDOMEvent)
+  // Forward to base class
+  NS_FORWARD_TO_NSDOMEVENT
+
+  NS_DECL_NSIDOMMOZCONTACTCHANGEEVENT
+
+  virtual nsresult InitFromCtor(const nsAString& aType,
+                                JSContext* aCx, jsval* aVal);
+private:
+  nsString mContactID;
+  nsString mReason;
+};
+
+#endif // nsDOMContactChangeEvent_h__
--- a/content/events/src/nsDOMEvent.cpp
+++ b/content/events/src/nsDOMEvent.cpp
@@ -72,16 +72,17 @@ static const char* const sEventNames[] =
   "MozMagnifyGestureStart",
   "MozMagnifyGestureUpdate",
   "MozMagnifyGesture",
   "MozRotateGestureStart",
   "MozRotateGestureUpdate",
   "MozRotateGesture",
   "MozTapGesture",
   "MozPressTapGesture",
+  "MozEdgeUIGesture",
   "MozTouchDown",
   "MozTouchMove",
   "MozTouchUp",
   "touchstart",
   "touchend",
   "touchmove",
   "touchcancel",
   "touchenter",
@@ -834,16 +835,17 @@ nsDOMEvent::DuplicatePrivateData()
     {
       nsSimpleGestureEvent* oldSimpleGestureEvent = static_cast<nsSimpleGestureEvent*>(mEvent);
       nsSimpleGestureEvent* simpleGestureEvent = 
         new nsSimpleGestureEvent(false, msg, nsnull, 0, 0.0);
       NS_ENSURE_TRUE(simpleGestureEvent, NS_ERROR_OUT_OF_MEMORY);
       isInputEvent = true;
       simpleGestureEvent->direction = oldSimpleGestureEvent->direction;
       simpleGestureEvent->delta = oldSimpleGestureEvent->delta;
+      simpleGestureEvent->clickCount = oldSimpleGestureEvent->clickCount;
       newEvent = simpleGestureEvent;
       break;
     }
     case NS_TRANSITION_EVENT:
     {
       nsTransitionEvent* oldTransitionEvent =
         static_cast<nsTransitionEvent*>(mEvent);
       newEvent = new nsTransitionEvent(false, msg,
@@ -1498,16 +1500,18 @@ const char* nsDOMEvent::GetEventName(PRU
   case NS_SIMPLE_GESTURE_ROTATE_UPDATE:
     return sEventNames[eDOMEvents_MozRotateGestureUpdate];
   case NS_SIMPLE_GESTURE_ROTATE:
     return sEventNames[eDOMEvents_MozRotateGesture];
   case NS_SIMPLE_GESTURE_TAP:
     return sEventNames[eDOMEvents_MozTapGesture];
   case NS_SIMPLE_GESTURE_PRESSTAP:
     return sEventNames[eDOMEvents_MozPressTapGesture];
+  case NS_SIMPLE_GESTURE_EDGEUI:
+    return sEventNames[eDOMEvents_MozEdgeUIGesture];
   case NS_MOZTOUCH_DOWN:
     return sEventNames[eDOMEvents_MozTouchDown];
   case NS_MOZTOUCH_MOVE:
     return sEventNames[eDOMEvents_MozTouchMove];
   case NS_MOZTOUCH_UP:
     return sEventNames[eDOMEvents_MozTouchUp];
   case NS_SCROLLEDAREACHANGED:
     return sEventNames[eDOMEvents_MozScrolledAreaChanged];
--- a/content/events/src/nsDOMEvent.h
+++ b/content/events/src/nsDOMEvent.h
@@ -155,16 +155,17 @@ public:
     eDOMEvents_MozMagnifyGestureStart,
     eDOMEvents_MozMagnifyGestureUpdate,
     eDOMEvents_MozMagnifyGesture,
     eDOMEvents_MozRotateGestureStart,
     eDOMEvents_MozRotateGestureUpdate,
     eDOMEvents_MozRotateGesture,
     eDOMEvents_MozTapGesture,
     eDOMEvents_MozPressTapGesture,
+    eDOMEvents_MozEdgeUIGesture,
     eDOMEvents_MozTouchDown,
     eDOMEvents_MozTouchMove,
     eDOMEvents_MozTouchUp,
     eDOMEvents_touchstart,
     eDOMEvents_touchend,
     eDOMEvents_touchmove,
     eDOMEvents_touchcancel,
     eDOMEvents_touchenter,
--- a/content/events/src/nsDOMSimpleGestureEvent.cpp
+++ b/content/events/src/nsDOMSimpleGestureEvent.cpp
@@ -54,16 +54,25 @@ nsDOMSimpleGestureEvent::GetDirection(PR
 NS_IMETHODIMP
 nsDOMSimpleGestureEvent::GetDelta(PRFloat64 *aDelta)
 {
   NS_ENSURE_ARG_POINTER(aDelta);
   *aDelta = static_cast<nsSimpleGestureEvent*>(mEvent)->delta;
   return NS_OK;
 }
 
+/* readonly attribute unsigned long clickCount; */
+NS_IMETHODIMP
+nsDOMSimpleGestureEvent::GetClickCount(PRUint32 *aClickCount)
+{
+  NS_ENSURE_ARG_POINTER(aClickCount);
+  *aClickCount = static_cast<nsSimpleGestureEvent*>(mEvent)->clickCount;
+  return NS_OK;
+}
+
 NS_IMETHODIMP
 nsDOMSimpleGestureEvent::InitSimpleGestureEvent(const nsAString& aTypeArg,
                                                 bool aCanBubbleArg,
                                                 bool aCancelableArg,
                                                 nsIDOMWindow* aViewArg,
                                                 PRInt32 aDetailArg,
                                                 PRInt32 aScreenX, 
                                                 PRInt32 aScreenY,
@@ -71,17 +80,18 @@ nsDOMSimpleGestureEvent::InitSimpleGestu
                                                 PRInt32 aClientY,
                                                 bool aCtrlKeyArg,
                                                 bool aAltKeyArg,
                                                 bool aShiftKeyArg,
                                                 bool aMetaKeyArg,
                                                 PRUint16 aButton,
                                                 nsIDOMEventTarget* aRelatedTarget,
                                                 PRUint32 aDirectionArg,
-                                                PRFloat64 aDeltaArg)
+                                                PRFloat64 aDeltaArg,
+                                                PRUint32 aClickCountArg)
 {
   nsresult rv = nsDOMMouseEvent::InitMouseEvent(aTypeArg,
                                                 aCanBubbleArg,
                                                 aCancelableArg,
                                                 aViewArg,
                                                 aDetailArg,
                                                 aScreenX, 
                                                 aScreenY,
@@ -93,16 +103,17 @@ nsDOMSimpleGestureEvent::InitSimpleGestu
                                                 aMetaKeyArg,
                                                 aButton,
                                                 aRelatedTarget);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsSimpleGestureEvent* simpleGestureEvent = static_cast<nsSimpleGestureEvent*>(mEvent);
   simpleGestureEvent->direction = aDirectionArg;
   simpleGestureEvent->delta = aDeltaArg;
+  simpleGestureEvent->clickCount = aClickCountArg;
 
   return NS_OK;
 }
 
 nsresult NS_NewDOMSimpleGestureEvent(nsIDOMEvent** aInstancePtrResult,
                                      nsPresContext* aPresContext,
                                      nsSimpleGestureEvent *aEvent)
 {
--- a/content/events/src/nsDOMTouchEvent.cpp
+++ b/content/events/src/nsDOMTouchEvent.cpp
@@ -123,53 +123,56 @@ nsDOMTouch::Equals(nsIDOMTouch* aTouch)
   aTouch->GetRadiusY(&radiusY);
   return mRefPoint != aTouch->mRefPoint ||
          (mForce != force) ||
          (mRotationAngle != orientation) ||
          (mRadius.x != radiusX) || (mRadius.y != radiusY);
 }
 
 // TouchList
-nsDOMTouchList::nsDOMTouchList(nsTArray<nsCOMPtr<nsIDOMTouch> > &aTouches)
-{
-  mPoints.AppendElements(aTouches);
-}
 
 DOMCI_DATA(TouchList, nsDOMTouchList)
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMTouchList)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMTouchList)
+  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
   NS_INTERFACE_MAP_ENTRY(nsIDOMTouchList)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(TouchList)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsDOMTouchList)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSTARRAY_OF_NSCOMPTR(mPoints)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mParent)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-
+NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsDOMTouchList)
+  NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
+NS_IMPL_CYCLE_COLLECTION_TRACE_END
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDOMTouchList)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSTARRAY(mPoints)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mParent)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsDOMTouchList)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsDOMTouchList)
 
 NS_IMETHODIMP
 nsDOMTouchList::GetLength(PRUint32* aLength)
 {
   *aLength = mPoints.Length();
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMTouchList::Item(PRUint32 aIndex, nsIDOMTouch** aRetVal)
 {
-  NS_IF_ADDREF(*aRetVal = mPoints.SafeElementAt(aIndex, nsnull));
+  NS_IF_ADDREF(*aRetVal = nsDOMTouchList::GetItemAt(aIndex));
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMTouchList::IdentifiedTouch(PRInt32 aIdentifier, nsIDOMTouch** aRetVal)
 {
   *aRetVal = nsnull;
   for (PRUint32 i = 0; i < mPoints.Length(); ++i) {
@@ -179,16 +182,22 @@ nsDOMTouchList::IdentifiedTouch(PRInt32 
         aIdentifier == identifier) {
       point.swap(*aRetVal);
       break;
     }
   }
   return NS_OK;
 }
 
+nsIDOMTouch*
+nsDOMTouchList::GetItemAt(PRUint32 aIndex)
+{
+  return mPoints.SafeElementAt(aIndex, nsnull);
+}
+
 // TouchEvent
 
 nsDOMTouchEvent::nsDOMTouchEvent(nsPresContext* aPresContext,
                                  nsTouchEvent* aEvent)
   : nsDOMUIEvent(aPresContext, aEvent ? aEvent :
                                         new nsTouchEvent(false, 0, nsnull))
 {
   if (aEvent) {
@@ -283,19 +292,21 @@ nsDOMTouchEvent::GetTouches(nsIDOMTouchL
     // for touchend events, remove any changed touches from the touches array
     nsTArray<nsCOMPtr<nsIDOMTouch> > unchangedTouches;
     nsTArray<nsCOMPtr<nsIDOMTouch> > touches = touchEvent->touches;
     for (PRUint32 i = 0; i < touches.Length(); ++i) {
       if (!touches[i]->mChanged) {
         unchangedTouches.AppendElement(touches[i]);
       }
     }
-    t = new nsDOMTouchList(unchangedTouches);
+    t = new nsDOMTouchList(static_cast<nsIDOMTouchEvent*>(this),
+                           unchangedTouches);
   } else {
-    t = new nsDOMTouchList(touchEvent->touches);
+    t = new nsDOMTouchList(static_cast<nsIDOMTouchEvent*>(this),
+                           touchEvent->touches);
   }
   mTouches = t;
   return CallQueryInterface(mTouches, aTouches);
 }
 
 NS_IMETHODIMP
 nsDOMTouchEvent::GetTargetTouches(nsIDOMTouchList** aTargetTouches)
 {
@@ -315,17 +326,18 @@ nsDOMTouchEvent::GetTargetTouches(nsIDOM
     if ((mEvent->message != NS_TOUCH_END &&
          mEvent->message != NS_TOUCH_CANCEL) || !touches[i]->mChanged) {
       nsIDOMEventTarget* targetPtr = touches[i]->GetTarget();
       if (targetPtr == mEvent->target) {
         targetTouches.AppendElement(touches[i]);
       }
     }
   }
-  mTargetTouches = new nsDOMTouchList(targetTouches);
+  mTargetTouches = new nsDOMTouchList(static_cast<nsIDOMTouchEvent*>(this),
+                                      targetTouches);
   return CallQueryInterface(mTargetTouches, aTargetTouches);
 }
 
 NS_IMETHODIMP
 nsDOMTouchEvent::GetChangedTouches(nsIDOMTouchList** aChangedTouches)
 {
   NS_ENSURE_ARG_POINTER(aChangedTouches);
   NS_ENSURE_STATE(mEvent);
@@ -337,17 +349,18 @@ nsDOMTouchEvent::GetChangedTouches(nsIDO
   nsTArray<nsCOMPtr<nsIDOMTouch> > changedTouches;
   nsTouchEvent* touchEvent = static_cast<nsTouchEvent*>(mEvent);
   nsTArray<nsCOMPtr<nsIDOMTouch> > touches = touchEvent->touches;
   for (PRUint32 i = 0; i < touches.Length(); ++i) {
     if (touches[i]->mChanged) {
       changedTouches.AppendElement(touches[i]);
     }
   }
-  mChangedTouches = new nsDOMTouchList(changedTouches);
+  mChangedTouches = new nsDOMTouchList(static_cast<nsIDOMTouchEvent*>(this),
+                                       changedTouches);
   return CallQueryInterface(mChangedTouches, aChangedTouches);
 }
 
 NS_IMETHODIMP
 nsDOMTouchEvent::GetAltKey(bool* aAltKey)
 {
   *aAltKey = static_cast<nsInputEvent*>(mEvent)->IsAlt();
   return NS_OK;
--- a/content/events/src/nsDOMTouchEvent.h
+++ b/content/events/src/nsDOMTouchEvent.h
@@ -4,16 +4,18 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsDOMTouchEvent_h_
 #define nsDOMTouchEvent_h_
 
 #include "nsDOMUIEvent.h"
 #include "nsIDOMTouchEvent.h"
 #include "nsString.h"
 #include "nsTArray.h"
+#include "nsIDocument.h"
+#include "dombindings.h"
 
 class nsDOMTouch : public nsIDOMTouch
 {
 public:
   nsDOMTouch(nsIDOMEventTarget* aTarget,
              PRInt32 aIdentifier,
              PRInt32 aPageX,
              PRInt32 aPageY,
@@ -90,37 +92,56 @@ protected:
   nsIntPoint mPagePoint;
   nsIntPoint mClientPoint;
   nsIntPoint mScreenPoint;
   nsIntPoint mRadius;
   float mRotationAngle;
   float mForce;
 };
 
-class nsDOMTouchList : public nsIDOMTouchList
+class nsDOMTouchList MOZ_FINAL : public nsIDOMTouchList,
+                                 public nsWrapperCache
 {
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_CYCLE_COLLECTION_CLASS(nsDOMTouchList)
+  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(nsDOMTouchList)
   NS_DECL_NSIDOMTOUCHLIST
 
-  nsDOMTouchList() { }
-  nsDOMTouchList(nsTArray<nsCOMPtr<nsIDOMTouch> > &aTouches);
-  
+  nsDOMTouchList(nsISupports *aParent) : mParent(aParent)
+  {
+    SetIsDOMBinding();
+  }
+  nsDOMTouchList(nsISupports *aParent,
+                 nsTArray<nsCOMPtr<nsIDOMTouch> > &aTouches)
+   : mPoints(aTouches),
+     mParent(aParent)
+  {
+    SetIsDOMBinding();
+  }
+
+  virtual JSObject* WrapObject(JSContext *cx, JSObject *scope,
+                               bool *triedToWrap)
+  {
+    return mozilla::dom::binding::TouchList::create(cx, scope, this,
+                                                    triedToWrap);
+  }
+
+  nsISupports *GetParentObject()
+  {
+    return mParent;
+  }
+
   void Append(nsIDOMTouch* aPoint)
   {
     mPoints.AppendElement(aPoint);
   }
 
-  nsIDOMTouch* GetItemAt(PRUint32 aIndex)
-  {
-    return mPoints.SafeElementAt(aIndex, nsnull);
-  }
 protected:
   nsTArray<nsCOMPtr<nsIDOMTouch> > mPoints;
+  nsCOMPtr<nsISupports> mParent;
 };
 
 class nsDOMTouchEvent : public nsDOMUIEvent,
                         public nsIDOMTouchEvent
 {
 public:
   nsDOMTouchEvent(nsPresContext* aPresContext, nsTouchEvent* aEvent);
   virtual ~nsDOMTouchEvent();
--- a/content/events/src/nsEventListenerManager.cpp
+++ b/content/events/src/nsEventListenerManager.cpp
@@ -1029,16 +1029,29 @@ nsEventListenerManager::SetJSEventListen
 {
   JSObject *handler;
   if (JSVAL_IS_PRIMITIVE(v) ||
       !JS_ObjectIsCallable(cx, handler = JSVAL_TO_OBJECT(v))) {
     RemoveScriptEventListener(aEventName);
     return NS_OK;
   }
 
+  // Now ensure that we're working in the compartment of aScope from now on.
+  JSAutoEnterCompartment ac;
+  if (!ac.enter(cx, aScope)) {
+    return NS_ERROR_UNEXPECTED;
+  }
+
+  // Rewrap the handler into the new compartment, if needed.
+  jsval tempVal = v;
+  if (!JS_WrapValue(cx, &tempVal)) {
+    return NS_ERROR_UNEXPECTED;
+  }
+  handler = &tempVal.toObject();
+
   // We might not have a script context, e.g. if we're setting a listener
   // on a dead Window.
   nsIScriptContext *context = nsJSUtils::GetStaticScriptContext(cx, aScope);
   NS_ENSURE_TRUE(context, NS_ERROR_FAILURE);
 
   JSObject *scope = ::JS_GetGlobalForObject(cx, aScope);
   // Untrusted events are always permitted for non-chrome script
   // handlers.
--- a/content/events/src/nsEventListenerManager.h
+++ b/content/events/src/nsEventListenerManager.h
@@ -254,17 +254,19 @@ protected:
   bool IsDeviceType(PRUint32 aType);
   void EnableDevice(PRUint32 aType);
   void DisableDevice(PRUint32 aType);
 
 public:
   /**
    * Set the "inline" event listener for aEventName to |v|.  This
    * might actually remove the event listener, depending on the value
-   * of |v|.
+   * of |v|.  Note that on entry to this function cx and aScope might
+   * not be in the same compartment, though cx and v are guaranteed to
+   * be in the same compartment.
    */
   nsresult SetJSEventListenerToJsval(nsIAtom *aEventName, JSContext *cx,
                                      JSObject *aScope, const jsval &v);
   /**
    * Get the value of the "inline" event listener for aEventName.
    * This may cause lazy compilation if the listener is uncompiled.
    */
   void GetJSEventListener(nsIAtom *aEventName, jsval *vp);
--- a/content/html/content/src/Makefile.in
+++ b/content/html/content/src/Makefile.in
@@ -13,16 +13,17 @@ include $(DEPTH)/config/autoconf.mk
 MODULE		= content
 LIBRARY_NAME	= gkconhtmlcon_s
 LIBXUL_LIBRARY	= 1
 FAIL_ON_WARNINGS = 1
 
 
 EXPORTS		= \
 		nsGenericHTMLElement.h \
+		nsHTMLIFrameElement.h \
 		nsClientRect.h \
 		nsHTMLDNSPrefetch.h \
 		nsTimeRanges.h \
 		$(NULL)
 
 CPPSRCS		= \
 		HTMLPropertiesCollection.cpp \
 		nsClientRect.cpp \
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -4182,17 +4182,18 @@ nsGenericHTMLElement::SetItemValueText(c
 }
 
 static void
 nsDOMSettableTokenListPropertyDestructor(void *aObject, nsIAtom *aProperty,
                                          void *aPropertyValue, void *aData)
 {
   nsDOMSettableTokenList* list =
     static_cast<nsDOMSettableTokenList*>(aPropertyValue);
-  NS_IF_RELEASE(list);
+  list->DropReference();
+  NS_RELEASE(list);
 }
 
 nsDOMSettableTokenList*
 nsGenericHTMLElement::GetTokenList(nsIAtom* aAtom)
 {
   nsDOMSettableTokenList* list = NULL;
   if (HasProperties()) {
     list = static_cast<nsDOMSettableTokenList*>(GetProperty(aAtom));
--- a/content/html/content/src/nsGenericHTMLFrameElement.cpp
+++ b/content/html/content/src/nsGenericHTMLFrameElement.cpp
@@ -93,31 +93,41 @@ nsGenericHTMLFrameElement::GetContentWin
                "Uh, this window should always be an outer window!");
 
   return CallQueryInterface(win, aContentWindow);
 }
 
 nsresult
 nsGenericHTMLFrameElement::EnsureFrameLoader()
 {
-  if (!GetParent() || !IsInDoc() || mFrameLoader) {
+  if (!GetParent() || !IsInDoc() || mFrameLoader || mFrameLoaderCreationDisallowed) {
     // If frame loader is there, we just keep it around, cached
     return NS_OK;
   }
 
   mFrameLoader = nsFrameLoader::Create(this, mNetworkCreated);
   if (!mFrameLoader) {
     // Strangely enough, this method doesn't actually ensure that the
     // frameloader exists.  It's more of a best-effort kind of thing.
     return NS_OK;
   }
 
   return NS_OK;
 }
 
+nsresult
+nsGenericHTMLFrameElement::CreateRemoteFrameLoader(nsITabParent* aTabParent)
+{
+  MOZ_ASSERT(!mFrameLoader);
+  EnsureFrameLoader();
+  NS_ENSURE_STATE(mFrameLoader);
+  mFrameLoader->SetRemoteBrowser(aTabParent);
+  return NS_OK;
+}
+
 NS_IMETHODIMP
 nsGenericHTMLFrameElement::GetFrameLoader(nsIFrameLoader **aFrameLoader)
 {
   NS_IF_ADDREF(*aFrameLoader = mFrameLoader);
   return NS_OK;
 }
 
 NS_IMETHODIMP_(already_AddRefed<nsFrameLoader>)
@@ -291,8 +301,26 @@ nsGenericHTMLFrameElement::GetReallyIsBr
                                            "dom.mozBrowserFramesWhitelist")) {
     return NS_OK;
   }
 
   // Otherwise, succeed.
   *aOut = true;
   return NS_OK;
 }
+
+NS_IMETHODIMP
+nsGenericHTMLFrameElement::DisallowCreateFrameLoader()
+{
+  MOZ_ASSERT(!mFrameLoader);
+  MOZ_ASSERT(!mFrameLoaderCreationDisallowed);
+  mFrameLoaderCreationDisallowed = true;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsGenericHTMLFrameElement::AllowCreateFrameLoader()
+{
+  MOZ_ASSERT(!mFrameLoader);
+  MOZ_ASSERT(mFrameLoaderCreationDisallowed);
+  mFrameLoaderCreationDisallowed = false;
+  return NS_OK;
+}
--- a/content/html/content/src/nsGenericHTMLFrameElement.h
+++ b/content/html/content/src/nsGenericHTMLFrameElement.h
@@ -20,16 +20,17 @@ class nsGenericHTMLFrameElement : public
                                   public nsIMozBrowserFrame
 {
 public:
   nsGenericHTMLFrameElement(already_AddRefed<nsINodeInfo> aNodeInfo,
                             mozilla::dom::FromParser aFromParser)
     : nsGenericHTMLElement(aNodeInfo)
     , mNetworkCreated(aFromParser == mozilla::dom::FROM_PARSER_NETWORK)
     , mBrowserFrameListenersRegistered(false)
+    , mFrameLoaderCreationDisallowed(false)
   {
   }
 
   virtual ~nsGenericHTMLFrameElement();
 
   NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr);
   NS_DECL_NSIFRAMELOADEROWNER
   NS_DECL_NSIDOMMOZBROWSERFRAME
@@ -94,9 +95,10 @@ protected:
   nsRefPtr<nsFrameLoader> mFrameLoader;
 
   // True when the element is created by the parser
   // using NS_FROM_PARSER_NETWORK flag.
   // If the element is modified, it may lose the flag.
   bool                    mNetworkCreated;
 
   bool                    mBrowserFrameListenersRegistered;
+  bool                    mFrameLoaderCreationDisallowed;
 };
--- a/content/html/content/src/nsHTMLIFrameElement.cpp
+++ b/content/html/content/src/nsHTMLIFrameElement.cpp
@@ -1,108 +1,57 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/Util.h"
 
-#include "nsIDOMHTMLIFrameElement.h"
-#include "nsGenericHTMLFrameElement.h"
+#include "nsHTMLIFrameElement.h"
 #include "nsIDOMDocument.h"
-#include "nsIDOMGetSVGDocument.h"
 #include "nsIDOMSVGDocument.h"
 #include "nsGkAtoms.h"
 #include "nsIDocument.h"
 #include "nsMappedAttributes.h"
 #include "nsDOMError.h"
 #include "nsRuleData.h"
 #include "nsStyleConsts.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
-class nsHTMLIFrameElement : public nsGenericHTMLFrameElement
-                          , public nsIDOMHTMLIFrameElement
-                          , public nsIDOMGetSVGDocument
-{
-public:
-  nsHTMLIFrameElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                      mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
-  virtual ~nsHTMLIFrameElement();
-
-  // nsISupports
-  NS_DECL_ISUPPORTS_INHERITED
-
-  // nsIDOMNode
-  NS_FORWARD_NSIDOMNODE(nsGenericHTMLFrameElement::)
-
-  // nsIDOMElement
-  NS_FORWARD_NSIDOMELEMENT(nsGenericHTMLFrameElement::)
-
-  // nsIDOMHTMLElement
-  NS_FORWARD_NSIDOMHTMLELEMENT(nsGenericHTMLFrameElement::)
-
-  // nsIDOMHTMLIFrameElement
-  NS_DECL_NSIDOMHTMLIFRAMEELEMENT
-
-  // nsIDOMGetSVGDocument
-  NS_DECL_NSIDOMGETSVGDOCUMENT
-
-  // nsIContent
-  virtual bool ParseAttribute(PRInt32 aNamespaceID,
-                                nsIAtom* aAttribute,
-                                const nsAString& aValue,
-                                nsAttrValue& aResult);
-  NS_IMETHOD_(bool) IsAttributeMapped(const nsIAtom* aAttribute) const;
-  virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const;
-
-  virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
-  virtual nsXPCClassInfo* GetClassInfo();
-  virtual nsIDOMNode* AsDOMNode() { return this; }
-
-protected:
-  virtual void GetItemValueText(nsAString& text);
-  virtual void SetItemValueText(const nsAString& text);
-};
-
-
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(IFrame)
 
-
 nsHTMLIFrameElement::nsHTMLIFrameElement(already_AddRefed<nsINodeInfo> aNodeInfo,
                                          FromParser aFromParser)
   : nsGenericHTMLFrameElement(aNodeInfo, aFromParser)
 {
 }
 
 nsHTMLIFrameElement::~nsHTMLIFrameElement()
 {
 }
 
-
 NS_IMPL_ADDREF_INHERITED(nsHTMLIFrameElement,nsGenericElement)
 NS_IMPL_RELEASE_INHERITED(nsHTMLIFrameElement,nsGenericElement)
 
 DOMCI_NODE_DATA(HTMLIFrameElement, nsHTMLIFrameElement)
 
 // QueryInterface implementation for nsHTMLIFrameElement
 NS_INTERFACE_TABLE_HEAD(nsHTMLIFrameElement)
   NS_HTML_CONTENT_INTERFACE_TABLE_BEGIN(nsHTMLIFrameElement)
     NS_INTERFACE_TABLE_ENTRY(nsHTMLIFrameElement, nsIDOMHTMLIFrameElement)
     NS_INTERFACE_TABLE_ENTRY(nsHTMLIFrameElement, nsIDOMGetSVGDocument)
   NS_OFFSET_AND_INTERFACE_TABLE_END
   NS_HTML_CONTENT_INTERFACE_TABLE_TO_MAP_SEGUE(nsHTMLIFrameElement,
                                                nsGenericHTMLFrameElement)
 NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLASSINFO(HTMLIFrameElement)
 
-
 NS_IMPL_ELEMENT_CLONE(nsHTMLIFrameElement)
 
-
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, Align, align)
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, FrameBorder, frameborder)
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, Height, height)
 NS_IMPL_URI_ATTR(nsHTMLIFrameElement, LongDesc, longdesc)
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, MarginHeight, marginheight)
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, MarginWidth, marginwidth)
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, Name, name)
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, Scrolling, scrolling)
new file mode 100644
--- /dev/null
+++ b/content/html/content/src/nsHTMLIFrameElement.h
@@ -0,0 +1,52 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsGenericHTMLFrameElement.h"
+#include "nsIDOMHTMLIFrameElement.h"
+#include "nsIDOMGetSVGDocument.h"
+
+class nsHTMLIFrameElement : public nsGenericHTMLFrameElement
+                          , public nsIDOMHTMLIFrameElement
+                          , public nsIDOMGetSVGDocument
+{
+public:
+  nsHTMLIFrameElement(already_AddRefed<nsINodeInfo> aNodeInfo,
+                      mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
+  virtual ~nsHTMLIFrameElement();
+
+  // nsISupports
+  NS_DECL_ISUPPORTS_INHERITED
+
+  // nsIDOMNode
+  NS_FORWARD_NSIDOMNODE(nsGenericHTMLFrameElement::)
+
+  // nsIDOMElement
+  NS_FORWARD_NSIDOMELEMENT(nsGenericHTMLFrameElement::)
+
+  // nsIDOMHTMLElement
+  NS_FORWARD_NSIDOMHTMLELEMENT(nsGenericHTMLFrameElement::)
+
+  // nsIDOMHTMLIFrameElement
+  NS_DECL_NSIDOMHTMLIFRAMEELEMENT
+
+  // nsIDOMGetSVGDocument
+  NS_DECL_NSIDOMGETSVGDOCUMENT
+
+  // nsIContent
+  virtual bool ParseAttribute(PRInt32 aNamespaceID,
+                                nsIAtom* aAttribute,
+                                const nsAString& aValue,
+                                nsAttrValue& aResult);
+  NS_IMETHOD_(bool) IsAttributeMapped(const nsIAtom* aAttribute) const;
+  virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const;
+
+  virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
+  virtual nsXPCClassInfo* GetClassInfo();
+  virtual nsIDOMNode* AsDOMNode() { return this; }
+
+protected:
+  virtual void GetItemValueText(nsAString& text);
+  virtual void SetItemValueText(const nsAString& text);
+};
--- a/content/html/content/src/nsHTMLMediaElement.cpp
+++ b/content/html/content/src/nsHTMLMediaElement.cpp
@@ -2149,17 +2149,17 @@ nsHTMLMediaElement::CanHandleMediaType(c
     *aCodecList = gWebMCodecs;
     return CANPLAY_YES;
   }
 #endif
 
 #ifdef MOZ_GSTREAMER
   if (IsH264Type(nsDependentCString(aMIMEType))) {
     *aCodecList = gH264Codecs;
-    return CANPLAY_YES;
+    return CANPLAY_MAYBE;
   }
 #endif
 #ifdef MOZ_MEDIA_PLUGINS
   if (GetMediaPluginHost()->FindDecoder(nsDependentCString(aMIMEType), aCodecList))
     return CANPLAY_MAYBE;
 #endif
   return CANPLAY_NO;
 }
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -260,16 +260,17 @@ include $(topsrcdir)/config/rules.mk
 		test_ol_attributes_reflection.html \
 		test_bug651956.html \
 		test_bug694503.html \
 		test_object_plugin_nav.html \
 		test_bug742030.html \
 		test_bug742549.html \
 		test_bug745685.html \
 		test_input_file_picker.html \
+		test_bug763626.html \
 		$(NULL)
 
 _BROWSER_TEST_FILES = \
 		browser_bug649778.js \
 		file_bug649778.html \
 		file_bug649778.html^headers^ \
 		$(NULL)
 
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug763626.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=763626
+-->
+<head>
+<title>Test for Bug 763626</title>
+
+<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+
+<script type="application/javascript">
+
+SimpleTest.waitForExplicitFinish();
+
+function boom()
+{
+  var r = document.createElement("div").itemRef;
+  SpecialPowers.DOMWindowUtils.garbageCollect();
+  is("" + r, "", "ToString should return empty string when element is gone");
+  SimpleTest.finish();
+}
+
+</script>
+</head>
+
+<body onload="boom();"></body>
+</html>
+
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -37,16 +37,17 @@
 #include "nsIWebNavigation.h"
 #include "nsIBaseWindow.h"
 #include "nsIWebShellServices.h"
 #include "nsIScriptContext.h"
 #include "nsIXPConnect.h"
 #include "nsContentList.h"
 #include "nsDOMError.h"
 #include "nsIPrincipal.h"
+#include "nsJSPrincipals.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsAttrName.h"
 #include "nsNodeUtils.h"
 
 #include "nsNetCID.h"
 #include "nsICookieService.h"
 
 #include "nsIServiceManager.h"
@@ -1550,16 +1551,23 @@ nsHTMLDocument::Open(const nsAString& aC
   ++mWriteLevel;
 
   CreateAndAddWyciwygChannel();
 
   --mWriteLevel;
 
   SetReadyStateInternal(nsIDocument::READYSTATE_LOADING);
 
+  // After changing everything around, make sure that the principal on the
+  // document's compartment exactly matches NodePrincipal().
+  DebugOnly<JSObject*> wrapper = GetWrapperPreserveColor();
+  MOZ_ASSERT_IF(wrapper,
+                JS_GetCompartmentPrincipals(js::GetObjectCompartment(wrapper)) ==
+                nsJSPrincipals::get(NodePrincipal()));
+
   NS_ENSURE_SUCCESS(rv, rv);
   return CallQueryInterface(this, aReturn);
 }
 
 NS_IMETHODIMP
 nsHTMLDocument::Clear()
 {
   // This method has been deprecated
--- a/content/media/nsAudioStream.cpp
+++ b/content/media/nsAudioStream.cpp
@@ -378,19 +378,20 @@ void nsAudioStream::ShutdownLibrary()
   }
 #endif
 }
 
 nsIThread *
 nsAudioStream::GetThread()
 {
   if (!mAudioPlaybackThread) {
-    NS_NewThread(getter_AddRefs(mAudioPlaybackThread),
-                 nsnull,
-                 MEDIA_THREAD_STACK_SIZE);
+    NS_NewNamedThread("Audio Stream",
+                      getter_AddRefs(mAudioPlaybackThread),
+                      nsnull,
+                      MEDIA_THREAD_STACK_SIZE);
   }
   return mAudioPlaybackThread;
 }
 
 class AsyncShutdownPlaybackThread : public nsRunnable
 {
 public:
   AsyncShutdownPlaybackThread(nsIThread* aThread) : mThread(aThread) {}
--- a/content/media/nsBuiltinDecoderStateMachine.cpp
+++ b/content/media/nsBuiltinDecoderStateMachine.cpp
@@ -259,17 +259,17 @@ StateMachineTracker& StateMachineTracker
 }
 
 void StateMachineTracker::EnsureGlobalStateMachine() 
 {
   NS_ASSERTION(NS_IsMainThread(), "Should be on main thread.");
   ReentrantMonitorAutoEnter mon(mMonitor);
   if (mStateMachineCount == 0) {
     NS_ASSERTION(!mStateMachineThread, "Should have null state machine thread!");
-    DebugOnly<nsresult> rv = NS_NewThread(&mStateMachineThread, nsnull);
+    DebugOnly<nsresult> rv = NS_NewNamedThread("Media State", &mStateMachineThread, nsnull);
     NS_ABORT_IF_FALSE(NS_SUCCEEDED(rv), "Can't create media state machine thread");
   }
   mStateMachineCount++;
 }
 
 #ifdef DEBUG
 bool StateMachineTracker::IsQueued(nsBuiltinDecoderStateMachine* aStateMachine)
 {
@@ -1612,19 +1612,20 @@ nsBuiltinDecoderStateMachine::StartDecod
   NS_ASSERTION(!StateMachineTracker::Instance().IsQueued(this),
     "Should not already have a pending request for a new decode thread.");
   NS_ASSERTION(OnStateMachineThread(), "Should be on state machine thread.");
   NS_ASSERTION(!mDecodeThread, "Should not have decode thread yet");
   NS_ASSERTION(mRequestedNewDecodeThread, "Should have requested this...");
 
   mRequestedNewDecodeThread = false;
 
-  nsresult rv = NS_NewThread(getter_AddRefs(mDecodeThread),
-                              nsnull,
-                              MEDIA_THREAD_STACK_SIZE);
+  nsresult rv = NS_NewNamedThread("Media Decode",
+                                  getter_AddRefs(mDecodeThread),
+                                  nsnull,
+                                  MEDIA_THREAD_STACK_SIZE);
   if (NS_FAILED(rv)) {
     // Give up, report error to media element.
     nsCOMPtr<nsIRunnable> event =
       NS_NewRunnableMethod(mDecoder, &nsBuiltinDecoder::DecodeError);
     NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL);
     return rv;
   }
 
@@ -1639,24 +1640,26 @@ nsBuiltinDecoderStateMachine::StartDecod
 nsresult
 nsBuiltinDecoderStateMachine::StartAudioThread()
 {
   NS_ASSERTION(OnStateMachineThread() || OnDecodeThread(),
                "Should be on state machine or decode thread.");
   mDecoder->GetReentrantMonitor().AssertCurrentThreadIn();
   mStopAudioThread = false;
   if (HasAudio() && !mAudioThread && !mAudioCaptured) {
-    nsresult rv = NS_NewThread(getter_AddRefs(mAudioThread),
-                               nsnull,
-                               MEDIA_THREAD_STACK_SIZE);
+    nsresult rv = NS_NewNamedThread("Media Audio",
+                                    getter_AddRefs(mAudioThread),
+                                    nsnull,
+                                    MEDIA_THREAD_STACK_SIZE);
     if (NS_FAILED(rv)) {
       LOG(PR_LOG_DEBUG, ("%p Changed state to SHUTDOWN because failed to create audio thread", mDecoder.get()));
       mState = DECODER_STATE_SHUTDOWN;
       return rv;
     }
+
     nsCOMPtr<nsIRunnable> event =
       NS_NewRunnableMethod(this, &nsBuiltinDecoderStateMachine::AudioLoop);
     mAudioThread->Dispatch(event, NS_DISPATCH_NORMAL);
   }
   return NS_OK;
 }
 
 PRInt64 nsBuiltinDecoderStateMachine::AudioDecodedUsecs() const
--- a/content/media/test/Makefile.in
+++ b/content/media/test/Makefile.in
@@ -120,31 +120,26 @@ include $(topsrcdir)/config/rules.mk
 		test_video_to_canvas.html \
 		use_large_cache.js \
 		test_audiowrite.html \
 		test_mozHasAudio.html \
 		test_source_media.html \
 		$(NULL)
 
 # Bug 759221
-# These tests are not built on Android because they were failing when we
-# enabled these tests on Android. The intent is to re-enable them as soon
-# as possible, and/or switch to a cleaner way to manage known-to-fail tests.
-ifneq ($(OS_TARGET),Android)
 _TEST_FILES += \
 		test_autoplay_contentEditable.html \
 		test_buffered.html \
 		test_bug448534.html \
 		test_bug463162.xhtml \
 		test_decoder_disable.html \
 		test_media_selection.html \
 		test_playback.html \
 		test_seekLies.html \
 		$(NULL)
-endif
 
 # Don't run in suite
 ifndef MOZ_SUITE
 _TEST_FILES += test_play_twice.html
 else
 $(warning test_play_twice.html is disabled pending investigation. Bug 598252)
 endif
 
@@ -244,20 +239,16 @@ ifdef MOZ_OGG
 		test_a4_tone.html \
 		file_audio_event_adopt_iframe.html \
 		test_audio_event_adopt.html \
 		test_referer.html \
 		test_bug726904.html \
 		$(NULL)
 
 # Bug 759221
-# These tests are not built on Android because they were failing when we
-# enabled these tests on Android. The intent is to re-enable them as soon
-# as possible, and/or switch to a cleaner way to manage known-to-fail tests.
-ifneq ($(OS_TARGET),Android)
 _TEST_FILES += \
 		test_bug686137.html \
 		test_contentDuration1.html \
 		test_contentDuration2.html \
 		test_contentDuration3.html \
 		test_contentDuration4.html \
 		test_contentDuration5.html \
 		test_contentDuration6.html \
@@ -267,17 +258,16 @@ ifneq ($(OS_TARGET),Android)
 		contentDuration3.sjs \
 		contentDuration4.sjs \
 		contentDuration5.sjs \
 		contentDuration6.sjs \
 		contentDuration7.sjs \
 		test_framebuffer.html \
 		test_seekable2.html \
 		$(NULL)
-endif
 else
 _TEST_FILES += \
 		test_can_play_type_no_ogg.html \
 		$(NULL)
 endif
 
 ifdef MOZ_WEBM
 _TEST_FILES += \
@@ -291,27 +281,22 @@ endif
 
 ifdef MOZ_WAVE
 _TEST_FILES += \
 		test_can_play_type_wave.html \
 		$(NULL)
 
 
 # Bug 759221
-# These tests are not built on Android because they were failing when we
-# enabled these tests on Android. The intent is to re-enable them as soon
-# as possible, and/or switch to a cleaner way to manage known-to-fail tests.
-ifneq ($(OS_TARGET),Android)
 _TEST_FILES += \
 		test_fragment_play.html \
 		test_fragment_noplay.html \
 		test_wave_data_u8.html \
 		test_wave_data_s16.html \
 		$(NULL)
-endif
 else
 _TEST_FILES += \
 		test_can_play_type_no_wave.html \
 		$(NULL)
 endif
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
--- a/content/svg/content/src/DOMSVGMatrix.cpp
+++ b/content/svg/content/src/DOMSVGMatrix.cpp
@@ -230,17 +230,17 @@ NS_IMETHODIMP DOMSVGMatrix::Rotate(float
 /* nsIDOMSVGMatrix rotateFromVector (in float x, in float y); */
 NS_IMETHODIMP DOMSVGMatrix::RotateFromVector(float x, float y,
                                              nsIDOMSVGMatrix **_retval)
 {
   *_retval = nsnull;
   NS_ENSURE_FINITE2(x, y, NS_ERROR_ILLEGAL_VALUE);
 
   if (x == 0.0 || y == 0.0)
-    return NS_ERROR_DOM_SVG_INVALID_VALUE_ERR;
+    return NS_ERROR_RANGE_ERR;
 
   NS_ADDREF(*_retval =
     new DOMSVGMatrix(gfxMatrix(Matrix()).Rotate(atan2(y, x))));
   return NS_OK;
 }
 
 /* nsIDOMSVGMatrix flipX (); */
 NS_IMETHODIMP DOMSVGMatrix::FlipX(nsIDOMSVGMatrix **_retval)
@@ -264,34 +264,34 @@ NS_IMETHODIMP DOMSVGMatrix::FlipY(nsIDOM
 
 /* nsIDOMSVGMatrix skewX (in float angle); */
 NS_IMETHODIMP DOMSVGMatrix::SkewX(float angle, nsIDOMSVGMatrix **_retval)
 {
   *_retval = nsnull;
   NS_ENSURE_FINITE(angle, NS_ERROR_ILLEGAL_VALUE);
 
   double ta = tan( angle*radPerDegree );
-  NS_ENSURE_FINITE(ta, NS_ERROR_DOM_SVG_INVALID_VALUE_ERR);
+  NS_ENSURE_FINITE(ta, NS_ERROR_RANGE_ERR);
 
   const gfxMatrix& mx = Matrix();
   gfxMatrix skewMx(mx.xx, mx.yx,
                    (float) (mx.xy + mx.xx*ta), (float) (mx.yy + mx.yx*ta),
                    mx.x0, mx.y0);
   NS_ADDREF(*_retval = new DOMSVGMatrix(skewMx));
   return NS_OK;
 }
 
 /* nsIDOMSVGMatrix skewY (in float angle); */
 NS_IMETHODIMP DOMSVGMatrix::SkewY(float angle, nsIDOMSVGMatrix **_retval)
 {
   *_retval = nsnull;
   NS_ENSURE_FINITE(angle, NS_ERROR_ILLEGAL_VALUE);
 
   double ta = tan( angle*radPerDegree );
-  NS_ENSURE_FINITE(ta, NS_ERROR_DOM_SVG_INVALID_VALUE_ERR);
+  NS_ENSURE_FINITE(ta, NS_ERROR_RANGE_ERR);
 
   const gfxMatrix& mx = Matrix();
   gfxMatrix skewMx((float) (mx.xx + mx.xy*ta), (float) (mx.yx + mx.yy*ta),
                    mx.xy, mx.yy,
                    mx.x0, mx.y0);
   NS_ADDREF(*_retval = new DOMSVGMatrix(skewMx));
   return NS_OK;
 }
--- a/content/svg/content/src/DOMSVGStringList.cpp
+++ b/content/svg/content/src/DOMSVGStringList.cpp
@@ -108,17 +108,17 @@ DOMSVGStringList::GetItem(PRUint32 index
 }
 
 NS_IMETHODIMP
 DOMSVGStringList::InsertItemBefore(const nsAString & newItem,
                                    PRUint32 index,
                                    nsAString & _retval)
 {
   if (newItem.IsEmpty()) { // takes care of DOMStringIsNull too
-    return NS_ERROR_DOM_SVG_INVALID_VALUE_ERR;
+    return NS_ERROR_DOM_SYNTAX_ERR;
   }
   index = NS_MIN(index, InternalList().Length());
 
   // Ensure we have enough memory so we can avoid complex error handling below:
   if (!InternalList().SetCapacity(InternalList().Length() + 1)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
@@ -134,17 +134,17 @@ DOMSVGStringList::InsertItemBefore(const
 }
 
 NS_IMETHODIMP
 DOMSVGStringList::ReplaceItem(const nsAString & newItem,
                               PRUint32 index,
                               nsAString & _retval)
 {
   if (newItem.IsEmpty()) { // takes care of DOMStringIsNull too
-    return NS_ERROR_DOM_SVG_INVALID_VALUE_ERR;
+    return NS_ERROR_DOM_SYNTAX_ERR;
   }
   if (index >= InternalList().Length()) {
     return NS_ERROR_DOM_INDEX_SIZE_ERR;
   }
 
   _retval = InternalList()[index];
   nsAttrValue emptyOrOldValue =
     mElement->WillChangeStringList(mIsConditionalProcessingAttribute,
--- a/content/svg/content/src/SVGPathData.cpp
+++ b/content/svg/content/src/SVGPathData.cpp
@@ -489,24 +489,24 @@ SVGPathData::ConstructPath(gfxContext *a
   NS_ABORT_IF_FALSE(i == mData.Length(), "Very, very bad - mData corrupt");
 
   MAYBE_APPROXIMATE_ZERO_LENGTH_SUBPATH_SQUARE_CAPS;
 }
 
 already_AddRefed<gfxFlattenedPath>
 SVGPathData::ToFlattenedPath(const gfxMatrix& aMatrix) const
 {
-  nsRefPtr<gfxContext> ctx =
+  nsRefPtr<gfxContext> tmpCtx =
     new gfxContext(gfxPlatform::GetPlatform()->ScreenReferenceSurface());
 
-  ctx->SetMatrix(aMatrix);
-  ConstructPath(ctx);
-  ctx->IdentityMatrix();
+  tmpCtx->SetMatrix(aMatrix);
+  ConstructPath(tmpCtx);
+  tmpCtx->IdentityMatrix();
 
-  return ctx->GetFlattenedPath();
+  return tmpCtx->GetFlattenedPath();
 }
 
 static double
 AngleOfVector(const gfxPoint& aVector)
 {
   // C99 says about atan2 "A domain error may occur if both arguments are
   // zero" and "On a domain error, the function returns an implementation-
   // defined value". In the case of atan2 the implementation-defined value
--- a/content/svg/content/src/SVGTransform.cpp
+++ b/content/svg/content/src/SVGTransform.cpp
@@ -120,32 +120,32 @@ SVGTransform::SetRotate(float aAngle, fl
   mOriginX = aCx;
   mOriginY = aCy;
 }
 
 nsresult
 SVGTransform::SetSkewX(float aAngle)
 {
   double ta = tan(aAngle*radPerDegree);
-  NS_ENSURE_FINITE(ta, NS_ERROR_DOM_SVG_INVALID_VALUE_ERR);
+  NS_ENSURE_FINITE(ta, NS_ERROR_RANGE_ERR);
 
   mType    = nsIDOMSVGTransform::SVG_TRANSFORM_SKEWX;
   mMatrix.Reset();
   mMatrix.xy = ta;
   mAngle   = aAngle;
   mOriginX = 0.f;
   mOriginY = 0.f;
   return NS_OK;
 }
 
 nsresult
 SVGTransform::SetSkewY(float aAngle)
 {
   double ta = tan(aAngle*radPerDegree);
-  NS_ENSURE_FINITE(ta, NS_ERROR_DOM_SVG_INVALID_VALUE_ERR);
+  NS_ENSURE_FINITE(ta, NS_ERROR_RANGE_ERR);
 
   mType    = nsIDOMSVGTransform::SVG_TRANSFORM_SKEWY;
   mMatrix.Reset();
   mMatrix.yx = ta;
   mAngle   = aAngle;
   mOriginX = 0.f;
   mOriginY = 0.f;
   return NS_OK;
--- a/content/svg/content/src/nsSVGSVGElement.cpp
+++ b/content/svg/content/src/nsSVGSVGElement.cpp
@@ -676,26 +676,17 @@ nsSVGSVGElement::GetCTM(nsIDOMSVGMatrix 
   NS_IF_ADDREF(*aCTM);
   return NS_OK;
 }
 
 /* nsIDOMSVGMatrix getScreenCTM (); */
 NS_IMETHODIMP
 nsSVGSVGElement::GetScreenCTM(nsIDOMSVGMatrix **aCTM)
 {
-  gfxMatrix m;
-  if (IsRoot()) {
-    // Consistency with other elements would have us return only the
-    // eFromUserSpace transforms, but this is what we've been doing for
-    // a while, and it keeps us consistent with WebKit and Opera (if not
-    // really with the ambiguous spec).
-    m = PrependLocalTransformsTo(m);
-  } else {
-    m = nsSVGUtils::GetCTM(this, true);
-  }
+  gfxMatrix m = nsSVGUtils::GetCTM(this, true);
   *aCTM = m.IsSingular() ? nsnull : new DOMSVGMatrix(m);
   NS_IF_ADDREF(*aCTM);
   return NS_OK;
 }
 
 /* nsIDOMSVGMatrix getTransformToElement (in nsIDOMSVGElement element); */
 NS_IMETHODIMP
 nsSVGSVGElement::GetTransformToElement(nsIDOMSVGElement *element,
@@ -737,17 +728,17 @@ NS_IMETHODIMP
 nsSVGSVGElement::SetZoomAndPan(PRUint16 aZoomAndPan)
 {
   if (aZoomAndPan == nsIDOMSVGZoomAndPan::SVG_ZOOMANDPAN_DISABLE ||
       aZoomAndPan == nsIDOMSVGZoomAndPan::SVG_ZOOMANDPAN_MAGNIFY) {
     mEnumAttributes[ZOOMANDPAN].SetBaseValue(aZoomAndPan, this);
     return NS_OK;
   }
 
-  return NS_ERROR_DOM_SVG_INVALID_VALUE_ERR;
+  return NS_ERROR_RANGE_ERR;
 }
 
 //----------------------------------------------------------------------
 // helper methods for implementing SVGZoomEvent:
 
 NS_IMETHODIMP
 nsSVGSVGElement::SetCurrentScaleTranslate(float s, float x, float y)
 {
--- a/content/svg/content/src/nsSVGViewElement.cpp
+++ b/content/svg/content/src/nsSVGViewElement.cpp
@@ -73,17 +73,17 @@ NS_IMETHODIMP
 nsSVGViewElement::SetZoomAndPan(PRUint16 aZoomAndPan)
 {
   if (aZoomAndPan == nsIDOMSVGZoomAndPan::SVG_ZOOMANDPAN_DISABLE ||
       aZoomAndPan == nsIDOMSVGZoomAndPan::SVG_ZOOMANDPAN_MAGNIFY) {
     mEnumAttributes[ZOOMANDPAN].SetBaseValue(aZoomAndPan, this);
     return NS_OK;
   }
 
-  return NS_ERROR_DOM_SVG_INVALID_VALUE_ERR;
+  return NS_ERROR_RANGE_ERR;
 }
 
 //----------------------------------------------------------------------
 // nsIDOMSVGFitToViewBox methods
 
 /* readonly attribute nsIDOMSVGAnimatedRect viewBox; */
 NS_IMETHODIMP
 nsSVGViewElement::GetViewBox(nsIDOMSVGAnimatedRect * *aViewBox)
--- a/content/svg/content/test/Makefile.in
+++ b/content/svg/content/test/Makefile.in
@@ -46,16 +46,17 @@ include $(topsrcdir)/config/rules.mk
 		test_isSupported.xhtml \
 		test_lang.xhtml \
 		test_nonAnimStrings.xhtml \
 		test_pathAnimInterpolation.xhtml \
 		test_pathSeg.xhtml \
 		test_pointAtLength.xhtml \
 		test_pointer-events.xhtml \
 		test_pointer-events-2.xhtml \
+		test_pointer-events-3.xhtml \
 		test_scientific.html \
 		scientific-helper.svg \
 		test_SVGAnimatedImageSMILDisabled.html \
 		animated-svg-image-helper.html \
 		animated-svg-image-helper.svg \
 		test_stroke-linecap-hit-testing.xhtml \
 		test_SVG_namespace_ids.html \
 		test_SVGLengthList.xhtml \
--- a/content/svg/content/test/getCTM-helper.svg
+++ b/content/svg/content/test/getCTM-helper.svg
@@ -22,16 +22,22 @@
     </svg>
     <foreignObject id="fO" x="30" y="40" width="100" height="100" transform="translate(1, 1)">
       <!-- current layout implementation ignores x="50" and y="60".
            thus, I made getCTM and getScreenCTM do the same. -->
       <svg id="outer" x="50" y="60" width="100" height="100">
         <g id="g2" transform="translate(600, 700)"/>
       </svg>
     </foreignObject>
+    <foreignObject x="30" y="40" width="100" height="100" transform="translate(1, 1)">
+      <html xmlns="http://www.w3.org/1999/xhtml" style="width: 100%; height: 100%">
+        <svg xmlns="http://www.w3.org/2000/svg" id="outer2" 
+             width="100" height="100" viewBox="100 100 200 200"/>
+      </html>
+    </foreignObject>
     <!-- something invalid -->
     <foreignObject>
       <g id="g3"/>
     </foreignObject>
     <image>
       <g id="g4"/>
     </image>
     <use xlink:href="#sym" id="use"/>
--- a/content/svg/content/test/test_SVGMatrix.xhtml
+++ b/content/svg/content/test/test_SVGMatrix.xhtml
@@ -82,18 +82,18 @@ function testInverse()
     "Unexpected result after inverting matrix");
 
   // Test non-invertable
   m = createMatrix(0, 0, 1, 0, 0, 0);
   try {
     m.inverse();
     ok(false, "Failed to throw exception when inverting singular matrix");
   } catch (e) {
-    is(e.code, SVGException.SVG_MATRIX_NOT_INVERTABLE,
-      "Got unexpected exception " + e + ", expected SVG_MATRIX_NOT_INVERTABLE");
+    is(e.name, "InvalidStateError",
+      "Got unexpected exception " + e + ", expected InvalidStateError");
   }
 }
 
 // SVGMatrix translate(in float x, in float y);
 function testTranslate()
 {
   var m = createMatrix(2, 0, 0, 1, 120, 100);
   roughCmpMatrix(m.translate(100, -50), [2, 0, 0, 1, 320, 50],
@@ -139,18 +139,18 @@ function testRotateFromVector()
                   120, 100],
                  "Unexpected result after rotateFromVector");
 
   // Test bad input (1)
   try {
     m.rotateFromVector(1, 0);
     ok(false, "Failed to throw exception with zero coord for rotateFromVector");
   } catch (e) {
-    is(e.code, SVGException.SVG_INVALID_VALUE_ERR,
-      "Got unexpected exception " + e + ", expected SVG_INVALID_VALUE_ERR");
+    is(e.name, "RangeError",
+      "Got unexpected exception " + e + ", expected TypeError");
   }
 
   // Test bad input (2)
   try {
     m.rotateFromVector(0, 1);
     ok(false, "Failed to throw exception with zero coord for rotateFromVector");
   } catch (e) { }
 }
--- a/content/svg/content/test/test_getCTM.html
+++ b/content/svg/content/test/test_getCTM.html
@@ -27,16 +27,17 @@ function runTest()
   var buggy = doc.getElementById("buggy");
   is(buggy.getCTM().e, 30, "buggy.getCTM().e");
   is(buggy.getCTM().f, 40, "buggy.getCTM().f");
 
   var root = doc.documentElement;
   var inner = doc.getElementById("inner");
   var g1 = doc.getElementById("g1");
   var outer = doc.getElementById("outer");
+  var outer2 = doc.getElementById("outer2");
   var g2 = doc.getElementById("g2");
   var g3 = doc.getElementById("g3");
   var g4 = doc.getElementById("g4");
   var g5 = doc.getElementById("g5");
   var sym = doc.getElementById("sym");
   var symbolRect = doc.getElementById("symbolRect");
   var fO = doc.getElementById("fO");
   /* Tests the consistency with nearestViewportElement
@@ -77,16 +78,19 @@ function runTest()
   is((function(){try{return inner.getScreenCTM().e}catch(e){return e}})(), 45, "inner.getScreenCTM().e");
   is((function(){try{return inner.getScreenCTM().f}catch(e){return e}})(), 68, "inner.getScreenCTM().f");
   // g1.farthestViewportElement == root
   is((function(){try{return g1.getScreenCTM().e}catch(e){return e}})(), 45, "g1.getScreenCTM().e");
   is((function(){try{return g1.getScreenCTM().f}catch(e){return e}})(), 68, "g1.getScreenCTM().f");
   // outer.farthestViewportElement == null (but actually == root)
   is((function(){try{return outer.getScreenCTM().e}catch(e){return e}})(), 46, "outer.getScreenCTM().e");
   is((function(){try{return outer.getScreenCTM().f}catch(e){return e}})(), 69, "outer.getScreenCTM().f");
+  // outer.farthestViewportElement == null (but actually == root)
+  is((function(){try{return outer2.getScreenCTM().e}catch(e){return e}})(), -19, "outer2.getScreenCTM().e");
+  is((function(){try{return outer2.getScreenCTM().f}catch(e){return e}})(), -8, "outer2.getScreenCTM().f");
   // g2.farthestViewportElement == outer (but actually == root)
   is((function(){try{return g2.getScreenCTM().e}catch(e){return e}})(), 646, "g2.getScreenCTM().e");
   is((function(){try{return g2.getScreenCTM().f}catch(e){return e}})(), 769, "g2.getScreenCTM().f");
   // g3.farthestViewportElement == null (but actually == null)
   is((function(){try{return g3.getScreenCTM()}catch(e){return e}})(), null, "g3.getScreenCTM()");
   // symbolRect.farthestViewportElement == root
   is((function(){try{return symbolRect.getScreenCTM().e}catch(e){return e}})(), 85, "symbolRect.getScreenCTM().e");
   is((function(){try{return symbolRect.getScreenCTM().f}catch(e){return e}})(), 108, "symbolRect.getScreenCTM().f");
new file mode 100644
--- /dev/null
+++ b/content/svg/content/test/test_pointer-events-3.xhtml
@@ -0,0 +1,56 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=762679
+-->
+<head>
+  <title>Test pointer events for small objects scaled up</title>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body onload="run()">
+<script class="testbody" type="text/javascript">
+<![CDATA[
+
+SimpleTest.waitForExplicitFinish();
+
+function run()
+{
+  var svgDoc = document.getElementById("svg");
+  var div = document.getElementById("div");
+  // Get the coords of the origin of the SVG canvas:
+  var originX = div.offsetLeft;
+  var originY = div.offsetTop;
+  var circle = document.getElementById("circle");
+
+  var elementFromPoint = document.elementFromPoint(originX + 150, originY + 51);
+  is(elementFromPoint, circle, "Top of circle should hit");
+
+  var elementFromPoint = document.elementFromPoint(originX + 249, originY + 150);
+  is(elementFromPoint, circle, "Right of circle should hit");
+
+  var elementFromPoint = document.elementFromPoint(originX + 150, originY + 249);
+  is(elementFromPoint, circle, "Bottom of circle should hit");
+
+  var elementFromPoint = document.elementFromPoint(originX + 51, originY + 150);
+  is(elementFromPoint, circle, "Left of circle should hit");
+
+  SimpleTest.finish();
+}
+
+]]>
+</script>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=762679">Mozilla Bug 762679</a>
+<p id="display"></p>
+<div id="content">
+
+  <div width="100%" height="1" id="div">
+  </div>
+  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="400" id="svg">
+    <circle id="circle" cx="1.5" cy="1.5" r="1" transform="scale(100, 100)"/>
+  </svg>
+
+</div>
+<pre id="test">
+</pre>
+</body>
+</html>
--- a/db/sqlite3/README.MOZILLA
+++ b/db/sqlite3/README.MOZILLA
@@ -1,11 +1,11 @@
-This is sqlite 3.7.12.1
+This is sqlite 3.7.13
 
--- Ryan VanderMeulen <ryanvm@gmail.com>, 05/2012
+-- Ryan VanderMeulen <ryanvm@gmail.com>, 06/2012
 
 See http://www.sqlite.org/ for more info.
 
 We have a mozilla-specific Makefile.in in src/ (normally no
 Makefile.in there) that we use to build.
 
 To move to a new version:
 
--- a/db/sqlite3/src/sqlite3.c
+++ b/db/sqlite3/src/sqlite3.c
@@ -1,11 +1,11 @@
 /******************************************************************************
 ** This file is an amalgamation of many separate C source files from SQLite
-** version 3.7.12.1.  By combining all the individual C code files into this 
+** version 3.7.13.  By combining all the individual C code files into this 
 ** single large file, the entire code can be compiled as a single translation
 ** unit.  This allows many compilers to do optimizations that would not be
 ** possible if the files were compiled separately.  Performance improvements
 ** of 5% or more are commonly seen when SQLite is compiled as a single
 ** translation unit.
 **
 ** This file is all you need to compile SQLite.  To use SQLite in other
 ** programs, you need this file and the "sqlite3.h" header file that defines
@@ -438,25 +438,32 @@
 /*
 ** The TCL headers are only needed when compiling the TCL bindings.
 */
 #if defined(SQLITE_TCL) || defined(TCLSH)
 # include <tcl.h>
 #endif
 
 /*
-** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
-** Setting NDEBUG makes the code smaller and run faster.  So the following
-** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
-** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
+** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
+** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
+** make it true by defining or undefining NDEBUG.
+**
+** Setting NDEBUG makes the code smaller and run faster by disabling the
+** number assert() statements in the code.  So we want the default action
+** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
+** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
 ** feature.
 */
 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
 # define NDEBUG 1
 #endif
+#if defined(NDEBUG) && defined(SQLITE_DEBUG)
+# undef NDEBUG
+#endif
 
 /*
 ** The testcase() macro is used to aid in coverage testing.  When 
 ** doing coverage testing, the condition inside the argument to
 ** testcase() must be evaluated both true and false in order to
 ** get full branch coverage.  The testcase() macro is inserted
 ** to help ensure adequate test coverage in places where simple
 ** condition/decision coverage is inadequate.  For example, testcase()
@@ -652,19 +659,19 @@ extern "C" {
 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
 ** string contains the date and time of the check-in (UTC) and an SHA1
 ** hash of the entire source tree.
 **
 ** See also: [sqlite3_libversion()],
 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
 ** [sqlite_version()] and [sqlite_source_id()].
 */
-#define SQLITE_VERSION        "3.7.12.1"
-#define SQLITE_VERSION_NUMBER 3007012
-#define SQLITE_SOURCE_ID      "2012-05-22 02:45:53 6d326d44fd1d626aae0e8456e5fa2049f1ce0789"
+#define SQLITE_VERSION        "3.7.13"
+#define SQLITE_VERSION_NUMBER 3007013
+#define SQLITE_SOURCE_ID      "2012-06-11 02:05:22 f5b5a13f7394dc143aa136f1d4faba6839eaa6dc"
 
 /*
 ** CAPI3REF: Run-Time Library Version Numbers
 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
 **
 ** These interfaces provide the same information as the [SQLITE_VERSION],
 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
 ** but are associated with the library instead of the header file.  ^(Cautious
@@ -1023,16 +1030,17 @@ SQLITE_API int sqlite3_exec(
 */
 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
@@ -2714,22 +2722,22 @@ SQLITE_API char *sqlite3_vsnprintf(int,c
 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
 ** option is used.
 **
 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
 ** implementation of these routines to be omitted.  That capability
 ** is no longer provided.  Only built-in memory allocators can be used.
 **
-** The Windows OS interface layer calls
+** Prior to SQLite version 3.7.10, the Windows OS interface layer called
 ** the system malloc() and free() directly when converting
 ** filenames between the UTF-8 encoding used by SQLite
 ** and whatever filename encoding is used by the particular Windows
-** installation.  Memory allocation errors are detected, but
-** they are reported back as [SQLITE_CANTOPEN] or
+** installation.  Memory allocation errors were detected, but
+** they were reported back as [SQLITE_CANTOPEN] or
 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
 **
 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
 ** must be either NULL or else pointers obtained from a prior
 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
 ** not yet been released.
 **
 ** The application must not read or write any part of
@@ -3120,28 +3128,30 @@ SQLITE_API void sqlite3_progress_handler
 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
 **     a VFS object that provides the operating system interface that should
 **     be used to access the database file on disk. ^If this option is set to
 **     an empty string the default VFS object is used. ^Specifying an unknown
 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
 **     present, then the VFS specified by the option takes precedence over
 **     the value passed as the fourth parameter to sqlite3_open_v2().
 **
-**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw" or
-**     "rwc". Attempting to set it to any other value is an error)^. 
+**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
+**     "rwc", or "memory". Attempting to set it to any other value is
+**     an error)^. 
 **     ^If "ro" is specified, then the database is opened for read-only 
 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
 **     third argument to sqlite3_prepare_v2(). ^If the mode option is set to 
 **     "rw", then the database is opened for read-write (but not create) 
 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
 **     been set. ^Value "rwc" is equivalent to setting both 
-**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If sqlite3_open_v2() is 
-**     used, it is an error to specify a value for the mode parameter that is 
-**     less restrictive than that specified by the flags passed as the third 
-**     parameter.
+**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
+**     set to "memory" then a pure [in-memory database] that never reads
+**     or writes from disk is used. ^It is an error to specify a value for
+**     the mode parameter that is less restrictive than that specified by
+**     the flags passed in the third parameter to sqlite3_open_v2().
 **
 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
 **     "private". ^Setting it to "shared" is equivalent to setting the
 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
 **     a URI filename, its value overrides any behaviour requested by setting
@@ -4995,16 +5005,53 @@ SQLITE_API int sqlite3_sleep(int);
 ** using [sqlite3_free].
 ** Hence, if this variable is modified directly, either it should be
 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
 ** or else the use of the [temp_store_directory pragma] should be avoided.
 */
 SQLITE_API char *sqlite3_temp_directory;
 
 /*
+** CAPI3REF: Name Of The Folder Holding Database Files
+**
+** ^(If this global variable is made to point to a string which is
+** the name of a folder (a.k.a. directory), then all database files
+** specified with a relative pathname and created or accessed by
+** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
+** to be relative to that directory.)^ ^If this variable is a NULL
+** pointer, then SQLite assumes that all database files specified
+** with a relative pathname are relative to the current directory
+** for the process.  Only the windows VFS makes use of this global
+** variable; it is ignored by the unix VFS.
+**
+** Changing the value of this variable while a database connection is
+** open can result in a corrupt database.
+**
+** It is not safe to read or modify this variable in more than one
+** thread at a time.  It is not safe to read or modify this variable
+** if a [database connection] is being used at the same time in a separate
+** thread.
+** It is intended that this variable be set once
+** as part of process initialization and before any SQLite interface
+** routines have been called and that this variable remain unchanged
+** thereafter.
+**
+** ^The [data_store_directory pragma] may modify this variable and cause
+** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
+** the [data_store_directory pragma] always assumes that any string
+** that this variable points to is held in memory obtained from 
+** [sqlite3_malloc] and the pragma may attempt to free that memory
+** using [sqlite3_free].
+** Hence, if this variable is modified directly, either it should be
+** made NULL or made to point to memory obtained from [sqlite3_malloc]
+** or else the use of the [data_store_directory pragma] should be avoided.
+*/
+SQLITE_API char *sqlite3_data_directory;
+
+/*
 ** CAPI3REF: Test For Auto-Commit Mode
 ** KEYWORDS: {autocommit mode}
 **
 ** ^The sqlite3_get_autocommit() interface returns non-zero or
 ** zero if the given database connection is or is not in autocommit mode,
 ** respectively.  ^Autocommit mode is on by default.
 ** ^Autocommit mode is disabled by a [BEGIN] statement.
 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
@@ -5172,17 +5219,16 @@ SQLITE_API void *sqlite3_rollback_hook(s
 SQLITE_API void *sqlite3_update_hook(
   sqlite3*, 
   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
   void*
 );
 
 /*
 ** CAPI3REF: Enable Or Disable Shared Pager Cache
-** KEYWORDS: {shared cache}
 **
 ** ^(This routine enables or disables the sharing of the database cache
 ** and schema data structures between [database connection | connections]
 ** to the same database. Sharing is enabled if the argument is true
 ** and disabled if the argument is false.)^
 **
 ** ^Cache sharing is enabled and disabled for an entire process.
 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
@@ -9011,17 +9057,17 @@ SQLITE_PRIVATE int sqlite3PagerCloseWal(
 #ifdef SQLITE_ENABLE_ZIPVFS
 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
 #endif
 
 /* Functions used to query pager state and configuration. */
 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
-SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
+SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
@@ -9281,38 +9327,33 @@ SQLITE_PRIVATE void sqlite3PCacheSetDefa
 #  define SQLITE_OS_OS2 0
 # endif
 #else
 # ifndef SQLITE_OS_WIN
 #  define SQLITE_OS_WIN 0
 # endif
 #endif
 
-/*
-** Define the maximum size of a temporary filename
-*/
 #if SQLITE_OS_WIN
 # include <windows.h>
-# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
-#elif SQLITE_OS_OS2
+#endif
+
+#if SQLITE_OS_OS2
 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
 # endif
 # define INCL_DOSDATETIME
 # define INCL_DOSFILEMGR
 # define INCL_DOSERRORS
 # define INCL_DOSMISC
 # define INCL_DOSPROCESS
 # define INCL_DOSMODULEMGR
 # define INCL_DOSSEMAPHORES
 # include <os2.h>
 # include <uconv.h>
-# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
-#else
-# define SQLITE_TEMPNAME_SIZE 200
 #endif
 
 /*
 ** Determine if we are dealing with Windows NT.
 **
 ** We ought to be able to determine if we are compiling for win98 or winNT
 ** using the _WIN32_WINNT macro as follows:
 **
@@ -9336,16 +9377,32 @@ SQLITE_PRIVATE void sqlite3PCacheSetDefa
 ** reduced API.
 */
 #if defined(_WIN32_WCE)
 # define SQLITE_OS_WINCE 1
 #else
 # define SQLITE_OS_WINCE 0
 #endif
 
+/*
+** Determine if we are dealing with WindowsRT (Metro) as this has a different and
+** incompatible API from win32.
+*/
+#if !defined(SQLITE_OS_WINRT)
+# define SQLITE_OS_WINRT 0
+#endif
+
+/*
+** When compiled for WinCE or WinRT, there is no concept of the current
+** directory.
+ */
+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
+# define SQLITE_CURDIR 1
+#endif
+
 /* If the SET_FULLSYNC macro is not defined above, then make it
 ** a no-op
 */
 #ifndef SET_FULLSYNC
 # define SET_FULLSYNC(x,y)
 #endif
 
 /*
@@ -11626,17 +11683,19 @@ SQLITE_PRIVATE void sqlite3ExprAssignVar
 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
-SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
+SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
+SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
+SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
@@ -12031,16 +12090,17 @@ SQLITE_PRIVATE   int sqlite3Utf8To8(unsi
 #  define sqlite3VtabInSync(db) 0
 #  define sqlite3VtabLock(X) 
 #  define sqlite3VtabUnlock(X)
 #  define sqlite3VtabUnlockList(X)
 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
 #else
 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
+SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
@@ -12485,16 +12545,19 @@ static const char * const azCompileOpt[]
   "CASE_SENSITIVE_LIKE",
 #endif
 #ifdef SQLITE_CHECK_PAGES
   "CHECK_PAGES",
 #endif
 #ifdef SQLITE_COVERAGE_TEST
   "COVERAGE_TEST",
 #endif
+#ifdef SQLITE_CURDIR
+  "CURDIR",
+#endif
 #ifdef SQLITE_DEBUG
   "DEBUG",
 #endif
 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
 #endif
 #ifdef SQLITE_DISABLE_DIRSYNC
   "DISABLE_DIRSYNC",
@@ -18338,17 +18401,17 @@ struct sqlite3_mutex {
 **
 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
 ** which is only available if your application was compiled with 
 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
 ** this out as well.
 */
 #if 0
-#if SQLITE_OS_WINCE
+#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
 # define mutexIsNT()  (1)
 #else
   static int mutexIsNT(void){
     static int osType = 0;
     if( osType==0 ){
       OSVERSIONINFO sInfo;
       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
       GetVersionEx(&sInfo);
@@ -18391,28 +18454,34 @@ static sqlite3_mutex winMutex_staticMute
 static int winMutex_isInit = 0;
 /* As winMutexInit() and winMutexEnd() are called as part
 ** of the sqlite3_initialize and sqlite3_shutdown()
 ** processing, the "interlocked" magic is probably not
 ** strictly necessary.
 */
 static long winMutex_lock = 0;
 
+SQLITE_API extern void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
+
 static int winMutexInit(void){ 
   /* The first to increment to 1 does actual initialization */
   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
     int i;
     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
+#if SQLITE_OS_WINRT
+      InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
+#else
       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
+#endif
     }
     winMutex_isInit = 1;
   }else{
     /* Someone else is in the process of initing the static mutexes */
     while( !winMutex_isInit ){
-      Sleep(1);
+      sqlite3_win32_sleep(1);
     }
   }
   return SQLITE_OK; 
 }
 
 static int winMutexEnd(void){ 
   /* The first to decrement to 0 does actual shutdown 
   ** (which should be the last to shutdown.) */
@@ -18476,17 +18545,21 @@ static sqlite3_mutex *winMutexAlloc(int 
   switch( iType ){
     case SQLITE_MUTEX_FAST:
     case SQLITE_MUTEX_RECURSIVE: {
       p = sqlite3MallocZero( sizeof(*p) );
       if( p ){  
 #ifdef SQLITE_DEBUG
         p->id = iType;
 #endif
+#if SQLITE_OS_WINRT
+        InitializeCriticalSectionEx(&p->mutex, 0, 0);
+#else
         InitializeCriticalSection(&p->mutex);
+#endif
       }
       break;
     }
     default: {
       assert( winMutex_isInit==1 );
       assert( iType-2 >= 0 );
       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
       p = &winMutex_staticMutexes[iType-2];
@@ -25069,17 +25142,17 @@ struct unixFile {
   int openFlags;                      /* The flags specified at open() */
 #endif
 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
   unsigned fsFlags;                   /* cached details from statfs() */
 #endif
 #if OS_VXWORKS
   struct vxworksFileId *pId;          /* Unique file ID */
 #endif
-#ifndef NDEBUG
+#ifdef SQLITE_DEBUG
   /* The next group of variables are used to track whether or not the
   ** transaction counter in bytes 24-27 of database files are updated
   ** whenever any part of the database changes.  An assertion fault will
   ** occur if a file is updated without also updating the transaction
   ** counter.  This test is made to avoid new problems similar to the
   ** one described by ticket #3584. 
   */
   unsigned char transCntrChng;   /* True if the transaction counter changed */
@@ -25104,17 +25177,16 @@ struct unixFile {
 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
 #else
 # define UNIXFILE_DIRSYNC    0x00
 #endif
 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
 #define UNIXFILE_DELETE      0x20     /* Delete on close */
 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
-#define UNIXFILE_CHOWN      0x100     /* File ownership was changed */
 
 /*
 ** Include code that is common to all os_*.c files
 */
 /************** Include os_common.h in the middle of os_unix.c ***************/
 /************** Begin file os_common.h ***************************************/
 /*
 ** 2004 May 22
@@ -25358,16 +25430,25 @@ SQLITE_API int sqlite3_open_file_count =
 **
 ** The safest way to deal with the problem is to always use this wrapper
 ** which always has the same well-defined interface.
 */
 static int posixOpen(const char *zFile, int flags, int mode){
   return open(zFile, flags, mode);
 }
 
+/*
+** On some systems, calls to fchown() will trigger a message in a security
+** log if they come from non-root processes.  So avoid calling fchown() if
+** we are not running as root.
+*/
+static int posixFchown(int fd, uid_t uid, gid_t gid){
+  return geteuid() ? 0 : fchown(fd,uid,gid);
+}
+
 /* Forward reference */
 static int openDirectory(const char*, int*);
 
 /*
 ** Many system calls are accessed through pointer-to-functions so that
 ** they may be overridden at runtime to facilitate fault injection during
 ** testing and sandboxing.  The following array holds the names and pointers
 ** to all overrideable system calls.
@@ -25469,17 +25550,17 @@ static struct unix_syscall {
 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
 
   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
 
   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
 
-  { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
+  { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
 
   { "umask",        (sqlite3_syscall_ptr)umask,           0 },
 #define osUmask     ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
 
 }; /* End of the overrideable system calls */
 
 /*
@@ -26613,17 +26694,17 @@ static int unixLock(sqlite3_file *id, in
       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
       if( rc!=SQLITE_BUSY ){
         pFile->lastErrno = tErrno;
       }
     }
   }
   
 
-#ifndef NDEBUG
+#ifdef SQLITE_DEBUG
   /* Set up the transaction-counter change checking flags when
   ** transitioning from a SHARED to a RESERVED lock.  The change
   ** from SHARED to RESERVED marks the beginning of a normal
   ** write operation (not a hot journal rollback).
   */
   if( rc==SQLITE_OK
    && pFile->eFileLock<=SHARED_LOCK
    && eFileLock==RESERVED_LOCK
@@ -26692,17 +26773,17 @@ static int posixUnlock(sqlite3_file *id,
     return SQLITE_OK;
   }
   unixEnterMutex();
   pInode = pFile->pInode;
   assert( pInode->nShared!=0 );
   if( pFile->eFileLock>SHARED_LOCK ){
     assert( pInode->eFileLock==pFile->eFileLock );
 
-#ifndef NDEBUG
+#ifdef SQLITE_DEBUG
     /* When reducing a lock such that other processes can start
     ** reading the database file again, make sure that the
     ** transaction counter was updated if any part of the database
     ** file changed.  If the transaction counter is not updated,
     ** other connections to the same file might not realize that
     ** the file has changed and hence might not know to flush their
     ** cache.  The use of a stale cache can lead to database corruption.
     */
@@ -27891,17 +27972,17 @@ static int afpUnlock(sqlite3_file *id, i
   pInode = pFile->pInode;
   assert( pInode->nShared!=0 );
   if( pFile->eFileLock>SHARED_LOCK ){
     assert( pInode->eFileLock==pFile->eFileLock );
     SimulateIOErrorBenign(1);
     SimulateIOError( h=(-1) )
     SimulateIOErrorBenign(0);
     
-#ifndef NDEBUG
+#ifdef SQLITE_DEBUG
     /* When reducing a lock such that other processes can start
     ** reading the database file again, make sure that the
     ** transaction counter was updated if any part of the database
     ** file changed.  If the transaction counter is not updated,
     ** other connections to the same file might not realize that
     ** the file has changed and hence might not know to flush their
     ** cache.  The use of a stale cache can lead to database corruption.
     */
@@ -28195,17 +28276,17 @@ static int unixWrite(
   ** file), the bytes in the locking range should never be read or written. */
 #if 0
   assert( pFile->pUnused==0
        || offset>=PENDING_BYTE+512
        || offset+amt<=PENDING_BYTE 
   );
 #endif
 
-#ifndef NDEBUG
+#ifdef SQLITE_DEBUG
   /* If we are doing a normal write to a database file (as opposed to
   ** doing a hot-journal rollback or a write to some file other than a
   ** normal database file) then record the fact that the database
   ** has changed.  If the transaction counter is modified, record that
   ** fact too.
   */
   if( pFile->inNormalWrite ){
     pFile->dbUpdate = 1;  /* The database has been modified */
@@ -28486,17 +28567,17 @@ static int unixTruncate(sqlite3_file *id
     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   }
 
   rc = robust_ftruncate(pFile->h, (off_t)nByte);
   if( rc ){
     pFile->lastErrno = errno;
     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   }else{
-#ifndef NDEBUG
+#ifdef SQLITE_DEBUG
     /* If we are doing a normal write to a database file (as opposed to
     ** doing a hot-journal rollback or a write to some file other than a
     ** normal database file) and we truncate the file to zero length,
     ** that effectively updates the change counter.  This might happen
     ** when restoring a database using the backup API from a zero-length
     ** source.
     */
     if( pFile->inNormalWrite && nByte==0 ){
@@ -28643,17 +28724,17 @@ static int unixFileControl(sqlite3_file 
     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
       return SQLITE_OK;
     }
     case SQLITE_FCNTL_VFSNAME: {
       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
       return SQLITE_OK;
     }
-#ifndef NDEBUG
+#ifdef SQLITE_DEBUG
     /* The pager calls this method to signal that it has done
     ** a rollback and that the database is therefore unchanged and
     ** it hence it is OK for the transaction change counter to be
     ** unchanged.
     */
     case SQLITE_FCNTL_DB_UNCHANGED: {
       ((unixFile*)id)->dbUpdate = 0;
       return SQLITE_OK;
@@ -28994,24 +29075,19 @@ static int unixOpenSharedMemory(unixFile
       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
       if( pShmNode->h<0 ){
         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
         goto shm_open_err;
       }
 
       /* If this process is running as root, make sure that the SHM file
       ** is owned by the same user that owns the original database.  Otherwise,
-      ** the original owner will not be able to connect. If this process is
-      ** not root, the following fchown() will fail, but we don't care.  The
-      ** if(){..} and the UNIXFILE_CHOWN flag are purely to silence compiler
-      ** warnings.
-      */
-      if( osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid)==0 ){
-        pDbFd->ctrlFlags |= UNIXFILE_CHOWN;
-      }
+      ** the original owner will not be able to connect.
+      */
+      osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
   
       /* Check to see if another process is holding the dead-man switch.
       ** If not, truncate the file to zero length. 
       */
       rc = SQLITE_OK;
       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
         if( robust_ftruncate(pShmNode->h, 0) ){
           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
@@ -30207,23 +30283,20 @@ static int unixOpen(
     }
     if( fd<0 ){
       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
       goto open_finished;
     }
 
     /* If this process is running as root and if creating a new rollback
     ** journal or WAL file, set the ownership of the journal or WAL to be
-    ** the same as the original database.  If we are not running as root,
-    ** then the fchown() call will fail, but that's ok.  The "if(){}" and
-    ** the setting of the UNIXFILE_CHOWN flag are purely to silence compiler
-    ** warnings from gcc.
+    ** the same as the original database.
     */
     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
-      if( osFchown(fd, uid, gid)==0 ){ p->ctrlFlags |= UNIXFILE_CHOWN; }
+      osFchown(fd, uid, gid);
     }
   }
   assert( fd>=0 );
   if( pOutFlags ){
     *pOutFlags = flags;
   }
 
   if( p->pUnused ){
@@ -32175,22 +32248,37 @@ SQLITE_API int sqlite3_open_file_count =
 #endif
 
 #endif /* !defined(_OS_COMMON_H_) */
 
 /************** End of os_common.h *******************************************/
 /************** Continuing where we left off in os_win.c *********************/
 
 /*
+** Macro to find the minimum of two numeric values.
+*/
+#ifndef MIN
+# define MIN(x,y) ((x)<(y)?(x):(y))
+#endif
+
+/*
 ** Some Microsoft compilers lack this definition.
 */
 #ifndef INVALID_FILE_ATTRIBUTES
 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
 #endif
 
+#ifndef