Merge from mozilla-central.
authorDavid Anderson <danderson@mozilla.com>
Tue, 10 Jan 2012 14:18:18 -0800
changeset 109138 b1fcb67fde3fbec5185693c1b46db22db65f9830
parent 109136 23ce5e04429d0d69f5bffec07965d96f4fe21889 (current diff)
parent 85324 011e3cef606891433ee68734561bc7e6fd9406f8 (diff)
child 109139 db31f7b194e5a198c6c42d3dd4bb9aeef165c212
push id2248
push userakeybl@mozilla.com
push dateMon, 08 Oct 2012 19:23:44 +0000
treeherdermozilla-aurora@118a3b748323 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone12.0a1
Merge from mozilla-central.
b2g/installer/package-manifest.in
browser/base/content/browser.js
browser/components/wintaskbar/Makefile.in
browser/components/wintaskbar/test/Makefile.in
build/mobile/devicemanagerADB.py
build/mobile/devicemanagerSUT.py
config/autoconf.mk.in
configure.in
content/base/public/nsContentUtils.h
content/base/public/nsDOMFile.h
content/base/src/nsDOMFile.cpp
content/base/src/nsFrameLoader.cpp
content/base/src/nsRange.cpp
content/canvas/test/webgl/test_webgl_conformance_test_suite.html
content/events/src/nsContentEventHandler.cpp
content/events/src/nsEventStateManager.cpp
content/events/test/Makefile.in
content/html/content/src/nsHTMLMenuItemElement.h
content/html/document/src/nsHTMLDocument.cpp
content/html/document/src/nsHTMLDocument.h
db/sqlite3/src/Makefile.in
dom/Makefile.in
dom/base/nsDOMClassInfo.cpp
dom/base/nsDOMClassInfoClasses.h
dom/dom-config.mk
dom/src/geolocation/nsGeolocation.cpp
dom/src/geolocation/nsGeolocation.h
dom/system/b2g/RadioManager.cpp
dom/system/b2g/RadioManager.h
dom/system/b2g/nsIRadioWorker.idl
dom/telephony/Telephony.js
dom/telephony/Telephony.manifest
dom/telephony/mozIDOMTelephony.idl
embedding/android/GeckoAppShell.java
extensions/spellcheck/hunspell/src/csutil.cpp
intl/chardet/public/nsCharsetDetectionAdaptorCID.h
intl/chardet/public/nsICharsetDetectionAdaptor.h
js/src/config/autoconf.mk.in
js/src/configure.in
js/src/frontend/BytecodeEmitter.cpp
js/src/frontend/BytecodeEmitter.h
js/src/frontend/Parser.cpp
js/src/ion/IonBuilder.cpp
js/src/ion/IonBuilder.h
js/src/jsanalyze.cpp
js/src/jsanalyze.h
js/src/jsfun.h
js/src/jsgc.cpp
js/src/jsinfer.cpp
js/src/jsinterp.cpp
js/src/jsinterp.h
js/src/jsinterpinlines.h
js/src/jsobj.cpp
js/src/jsobj.h
js/src/jsobjinlines.h
js/src/jsopcode.cpp
js/src/jsopcode.h
js/src/jsopcode.tbl
js/src/jsprvtd.h
js/src/jsxdrapi.h
js/src/methodjit/Compiler.cpp
js/src/methodjit/Compiler.h
js/src/methodjit/FastOps.cpp
js/src/methodjit/InvokeHelpers.cpp
js/src/methodjit/LoopState.cpp
js/src/methodjit/MonoIC.cpp
js/src/methodjit/PolyIC.cpp
js/src/methodjit/StubCalls.cpp
js/src/methodjit/StubCalls.h
js/src/shell/js.cpp
js/src/tests/js1_8_5/regress/jstests.list
js/src/tests/js1_8_5/regress/regress-666599.js
js/src/vm/Debugger.cpp
js/xpconnect/src/dom_quickstubs.qsconf
js/xpconnect/src/xpcprivate.h
layout/base/nsLayoutUtils.h
layout/base/nsPresShell.cpp
layout/base/nsPresShell.h
layout/build/nsLayoutModule.cpp
layout/style/ua.css
layout/tables/crashtests/crashtests.list
layout/tables/nsTableFrame.cpp
memory/Makefile.in
memory/mozutils/Makefile.in
memory/mozutils/dummy.cpp
memory/mozutils/fixcrt.py
memory/mozutils/mozutils.def.in
mobile/android/base/GeckoApp.java
mobile/android/base/GeckoAppShell.java
mobile/xul/installer/package-manifest.in
mozglue/android/APKOpen.cpp
mozglue/android/APKOpen.h
mozglue/android/Makefile.in
mozglue/android/nsGeckoUtils.cpp
netwerk/test/unit/test_bug650955.js
other-licenses/android/APKOpen.cpp
other-licenses/android/APKOpen.h
other-licenses/android/Makefile.in
other-licenses/android/nsGeckoUtils.cpp
parser/html/nsHtml5Parser.cpp
parser/html/nsHtml5Parser.h
parser/htmlparser/public/nsIParser.h
parser/htmlparser/public/nsIParserFilter.h
parser/htmlparser/src/nsParser.cpp
parser/htmlparser/src/nsParser.h
testing/mochitest/runtestsremote.py
testing/testsuite-targets.mk
toolkit/components/downloads/nsDownloadManager.cpp
toolkit/mozapps/installer/packager.mk
toolkit/system/gnome/nsGSettingsService.cpp
xpcom/glue/AutoRestore.h
xpcom/glue/nsBaseHashtable.h
xpcom/idl-parser/xpidl.py
--- a/Makefile.in
+++ b/Makefile.in
@@ -54,28 +54,37 @@ include $(DEPTH)/config/autoconf.mk
 default::
 
 TIERS += base
 
 #
 # tier "base" - basic setup
 #
 tier_base_dirs = \
-	config \
-	build \
-	probes \
-	mfbt \
-	$(NULL)
+  config \
+  build \
+  probes \
+  mfbt \
+  $(NULL)
 
 ifndef LIBXUL_SDK
 ifeq (android,$(MOZ_WIDGET_TOOLKIT))
-tier_base_dirs += other-licenses/android other-licenses/skia-npapi
+tier_base_dirs += \
+  other-licenses/android \
+  other-licenses/skia-npapi \
+  $(NULL)
 endif
 
-tier_base_dirs += memory
+ifdef MOZ_MEMORY
+tier_base_dirs += memory/jemalloc
+endif
+tier_base_dirs += \
+  mozglue \
+  memory/mozalloc \
+  $(NULL)
 endif
 
 ifdef COMPILE_ENVIRONMENT
 include $(topsrcdir)/$(MOZ_BUILD_APP)/build.mk
 endif
 
 
 include $(topsrcdir)/config/config.mk
--- a/allmakefiles.sh
+++ b/allmakefiles.sh
@@ -69,29 +69,30 @@ config/doxygen.cfg
 config/expandlibs_config.py
 config/tests/src-simple/Makefile
 probes/Makefile
 extensions/Makefile
 "
 
 if [ ! "$LIBXUL_SDK" ]; then
   add_makefiles "
-    memory/Makefile
     memory/mozalloc/Makefile
-    memory/mozutils/Makefile
+    mozglue/Makefile
+    mozglue/build/Makefile
   "
   if [ "$MOZ_MEMORY" ]; then
     add_makefiles "
       memory/jemalloc/Makefile
     "
   fi
   if [ "$MOZ_WIDGET_TOOLKIT" = "android" ]; then
     add_makefiles "
       other-licenses/android/Makefile
       other-licenses/skia-npapi/Makefile
+      mozglue/android/Makefile
     "
   fi
 fi
 
 if [ "$OS_ARCH" = "WINNT" ]; then
   add_makefiles "
     build/win32/Makefile
     build/win32/crashinjectdll/Makefile
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -41,16 +41,19 @@ pref("toolkit.defaultChromeURI", "chrome
 pref("general.useragent.compatMode.firefox", true);
 pref("browser.chromeURL", "chrome://browser/content/");
 #ifdef MOZ_OFFICIAL_BRANDING
 pref("browser.homescreenURL", "file:///system/home/homescreen.html");
 #else
 pref("browser.homescreenURL", "file:///data/local/homescreen.html,file:///system/home/homescreen.html");
 #endif
 
+// URL for the dialer application.
+pref("dom.telephony.app.phone.url", "http://localhost:7777/dialer/dialer.html");
+
 // Device pixel to CSS px ratio, in percent. Set to -1 to calculate based on display density.
 pref("browser.viewport.scaleRatio", -1);
 
 /* disable text selection */
 pref("browser.ignoreNativeFrameTextSelection", true);
 
 /* cache prefs */
 pref("browser.cache.disk.enable", false);
@@ -386,10 +389,13 @@ pref("security.fileuri.strict_origin_pol
 // deep within the bowels of the widgetry system.  Remove me when GL
 // compositing isn't default disabled in widget/android.
 pref("layers.acceleration.force-enabled", true);
 
 // screen.enabled and screen.brightness properties.
 pref("dom.screenEnabledProperty.enabled", true);
 pref("dom.screenBrightnessProperty.enabled", true);
 
+// Temporary permission hack for WebSMS
+pref("dom.sms.enabled", true);
+pref("dom.sms.whitelist", "file://,http://localhost:6666");
 // Ignore X-Frame-Options headers.
 pref("b2g.ignoreXFrameOptions", true);
--- a/b2g/chrome/content/touch.js
+++ b/b2g/chrome/content/touch.js
@@ -81,17 +81,16 @@
       let eventTarget = this.target;
       let type = '';
       switch (evt.type) {
         case 'mousedown':
           debug('mousedown:');
 
           this.target = evt.target;
           this.timestamp = evt.timeStamp;
-          evt.target.setCapture(false);
 
           preventMouseEvents = false;
           canPreventMouseEvents = true;
           isNewTouchAction = true;
 
           contextMenuTimeout =
             this.sendContextMenu(evt.target, evt.pageX, evt.pageY, 2000);
           this.startX = evt.pageX;
@@ -121,27 +120,25 @@
           break;
 
         case 'mouseup':
           if (!eventTarget)
             return;
           debug('mouseup:');
 
           window.clearTimeout(contextMenuTimeout);
-          eventTarget.ownerDocument.releaseCapture();
           this.target = null;
           type = 'touchend';
           break;
 
         case 'unload':
           if (!eventTarget)
             return;
 
           window.clearTimeout(contextMenuTimeout);
-          eventTarget.ownerDocument.releaseCapture();
           this.target = null;
           TouchEventHandler.stop();
           return;
 
         case 'click':
           if (!isNewTouchAction) {
             debug('click: cancel');
 
--- a/b2g/installer/package-manifest.in
+++ b/b2g/installer/package-manifest.in
@@ -77,17 +77,17 @@
 @BINPATH@/mozcrt19.dll
 @BINPATH@/mozcpp19.dll
 #endif
 #endif
 #ifdef ANDROID
 @BINPATH@/AndroidManifest.xml
 @BINPATH@/resources.arsc
 @BINPATH@/classes.dex
-@BINPATH@/@DLL_PREFIX@mozutils@DLL_SUFFIX@
+@BINPATH@/@DLL_PREFIX@mozglue@DLL_SUFFIX@
 @BINPATH@/res/drawable
 @BINPATH@/res/drawable-hdpi
 @BINPATH@/res/layout
 #endif
 
 [browser]
 ; [Base Browser Files]
 #ifndef XP_UNIX
@@ -158,16 +158,17 @@
 @BINPATH@/components/dom_geolocation.xpt
 @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
 @BINPATH@/components/dom_range.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
 @BINPATH@/components/dom_traversal.xpt
 @BINPATH@/components/dom_views.xpt
 @BINPATH@/components/dom_xbl.xpt
 @BINPATH@/components/dom_xpath.xpt
 @BINPATH@/components/dom_xul.xpt
--- a/b2g/installer/removed-files.in
+++ b/b2g/installer/removed-files.in
@@ -1,1 +1,2 @@
 README.txt
+@DLL_PREFIX@mozutils@DLL_SUFFIX@
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -1781,16 +1781,18 @@ function BrowserShutdown() {
     gBrowser.removeTabsProgressListener(window.TabsProgressListener);
   } catch (ex) {
   }
 
   PlacesStarButton.uninit();
 
   gPrivateBrowsingUI.uninit();
 
+  TabsOnTop.uninit();
+
   TabsInTitlebar.uninit();
 
   var enumerator = Services.wm.getEnumerator(null);
   enumerator.getNext();
   if (!enumerator.hasMoreElements()) {
     document.persist("sidebar-box", "sidebarcommand");
     document.persist("sidebar-box", "width");
     document.persist("sidebar-box", "src");
@@ -5286,16 +5288,20 @@ function setToolbarVisibility(toolbar, i
 }
 
 var TabsOnTop = {
   init: function TabsOnTop_init() {
     this.syncUI();
     Services.prefs.addObserver(this._prefName, this, false);
   },
 
+  uninit: function TabsOnTop_uninit() {
+    Services.prefs.removeObserver(this._prefName, this);
+  },
+
   toggle: function () {
     this.enabled = !Services.prefs.getBoolPref(this._prefName);
   },
 
   syncUI: function () {
     let userEnabled = Services.prefs.getBoolPref(this._prefName);
     let enabled = userEnabled && gBrowser.tabContainer.visible;
 
--- a/browser/base/content/test/browser_urlbarCopying.js
+++ b/browser/base/content/test/browser_urlbarCopying.js
@@ -38,25 +38,39 @@ var tests = [
   // pageproxystate="valid" from this point on (due to the load)
   {
     loadURL: "http://example.com/",
     expectedURL: "example.com",
     copyExpected: "http://example.com/"
   },
   {
     copyVal: "<example.co>m",
-    copyExpected: "http://example.co"
+    copyExpected: "example.co"
   },
   {
     copyVal: "e<x>ample.com",
     copyExpected: "x"
   },
   {
     copyVal: "<e>xample.com",
-    copyExpected: "http://e"
+    copyExpected: "e"
+  },
+
+  {
+    loadURL: "http://example.com/foo",
+    expectedURL: "example.com/foo",
+    copyExpected: "http://example.com/foo"
+  },
+  {
+    copyVal: "<example.com>/foo",
+    copyExpected: "http://example.com"
+  },
+  {
+    copyVal: "<example>.com/foo",
+    copyExpected: "example"
   },
 
   // Test that userPass is stripped out
   {
     loadURL: "http://user:pass@mochi.test:8888/browser/browser/base/content/test/authenticate.sjs?user=user&pass=pass",
     expectedURL: "mochi.test:8888/browser/browser/base/content/test/authenticate.sjs?user=user&pass=pass",
     copyExpected: "http://mochi.test:8888/browser/browser/base/content/test/authenticate.sjs?user=user&pass=pass"
   },
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -505,20 +505,27 @@
       </method>
 
       <method name="_getSelectedValueForClipboard">
         <body><![CDATA[
           // Grab the actual input field's value, not our value, which could include moz-action:
           var inputVal = this.inputField.value;
           var selectedVal = inputVal.substring(this.selectionStart, this.selectionEnd);
 
-          // If the selection doesn't start at the beginning or URL bar is
-          // modified, nothing else to do here.
+          // If the selection doesn't start at the beginning or doesn't span the full domain or
+          // the URL bar is modified, nothing else to do here.
           if (this.selectionStart > 0 || this.valueIsTyped)
             return selectedVal;
+          // The selection doesn't span the full domain if it doesn't contain a slash and is
+          // followed by some character other than a slash.
+          if (selectedVal.indexOf("/") == -1) {
+            let remainder = inputVal.replace(selectedVal, "");
+            if (remainder != "" && remainder[0] != "/")
+              return selectedVal;
+          }
 
           let uriFixup = Cc["@mozilla.org/docshell/urifixup;1"].getService(Ci.nsIURIFixup);
 
           let uri;
           try {
             uri = uriFixup.createFixupURI(inputVal, Ci.nsIURIFixup.FIXUP_FLAG_USE_UTF8);
           } catch (e) {}
           if (!uri)
--- a/browser/components/places/tests/unit/test_clearHistory_shutdown.js
+++ b/browser/components/places/tests/unit/test_clearHistory_shutdown.js
@@ -136,16 +136,19 @@ function run_test() {
 
   print("Simulate and wait shutdown.");
   getDistinctNotifications().forEach(
     function (topic)
       Services.obs.addObserver(notificationsObserver, topic, false)
   );
 
   shutdownPlaces();
+
+  // Shutdown the download manager.
+  Services.obs.notifyObservers(null, "quit-application", null);
 }
 
 function getDistinctNotifications() {
   let ar = EXPECTED_NOTIFICATIONS.concat(UNEXPECTED_NOTIFICATIONS);
   return [ar[i] for (i in ar) if (ar.slice(0, i).indexOf(ar[i]) == -1)];
 }
 
 function storeCache(aURL, aContent) {
deleted file mode 100644
--- a/browser/components/wintaskbar/Makefile.in
+++ /dev/null
@@ -1,56 +0,0 @@
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is Aero Peek
-#
-# The Initial Developer of the Original Code is
-# Mozilla Corporation
-# Portions created by the Initial Developer are Copyright (C) 2009
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Rob Arnold <tellrob@gmail.com>
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either the GNU General Public License Version 2 or later (the "GPL"), or
-# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-DEPTH		= ../../..
-topsrcdir	= @top_srcdir@
-srcdir		= @srcdir@
-VPATH		= @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-ifdef ENABLE_TESTS
-DIRS += test
-endif
-
-MODULE = wintaskbar
-
-EXTRA_JS_MODULES = \
-	WindowsPreviewPerTab.jsm \
-	WindowsJumpLists.jsm \
-	$(NULL)
-
-include $(topsrcdir)/config/rules.mk
deleted file mode 100644
--- a/browser/components/wintaskbar/test/Makefile.in
+++ /dev/null
@@ -1,54 +0,0 @@
-#
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-#    Mozilla Corporation.
-# Portions created by the Initial Developer are Copyright (C) 2009
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Rob Arnold <robarnold@cmu.edu>
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of the GNU General Public License Version 2 or later (the "GPL"),
-# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-DEPTH		= ../../../..
-topsrcdir	= @top_srcdir@
-srcdir		= @srcdir@
-VPATH		= @srcdir@
-relativesrcdir  = browser/components/wintaskbar/test
-
-include $(DEPTH)/config/autoconf.mk
-include $(topsrcdir)/config/rules.mk
-
-_BROWSER_FILES = browser_taskbar_preview.js \
-    $(NULL)
-
-libs::	$(_BROWSER_FILES)
-	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
-
-
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -39,17 +39,17 @@
 #ifndef MOZ_STATIC_JS
 @BINPATH@/@DLL_PREFIX@mozjs@DLL_SUFFIX@
 #endif
 @BINPATH@/@DLL_PREFIX@plc4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@plds4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@xpcom@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@nspr4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@mozalloc@DLL_SUFFIX@
-@BINPATH@/@DLL_PREFIX@mozutils@DLL_SUFFIX@
+@BINPATH@/@DLL_PREFIX@mozglue@DLL_SUFFIX@
 #ifdef XP_MACOSX
 @BINPATH@/XUL
 #else
 @BINPATH@/@DLL_PREFIX@xul@DLL_SUFFIX@
 #endif
 #ifdef XP_MACOSX
 @BINPATH@/@MOZ_CHILD_PROCESS_NAME@.app/
 @BINPATH@/@DLL_PREFIX@plugin_child_interpose@DLL_SUFFIX@
--- a/browser/installer/removed-files.in
+++ b/browser/installer/removed-files.in
@@ -5,16 +5,17 @@
 # Inspector files are at the very end.
 .autoreg
 @DLL_PREFIX@jsj@DLL_SUFFIX@
 @DLL_PREFIX@sqlite3@DLL_SUFFIX@
 @DLL_PREFIX@xpcom_compat@DLL_SUFFIX@
 @DLL_PREFIX@xpistub@DLL_SUFFIX@
 @DLL_PREFIX@zlib@DLL_SUFFIX@
 @DLL_PREFIX@jemalloc@DLL_SUFFIX@
+@DLL_PREFIX@mozutils@DLL_SUFFIX@
 #ifdef MOZ_STATIC_JS
 @DLL_PREFIX@mozjs@DLL_SUFFIX@
 #endif
 LICENSE
 update.locale
 browserconfig.properties
 chrome/US.jar
 chrome/app-chrome.manifest
--- a/browser/installer/windows/nsis/maintenanceservice_installer.nsi
+++ b/browser/installer/windows/nsis/maintenanceservice_installer.nsi
@@ -203,18 +203,19 @@ Section "MaintenanceService"
   WriteRegStr HKLM "${MaintUninstallKey}" "UninstallString" \
                    '"$INSTDIR\uninstall.exe"'
   WriteRegStr HKLM "${MaintUninstallKey}" "DisplayIcon" \
                    "$INSTDIR\Uninstall.exe,0"
   WriteRegStr HKLM "${MaintUninstallKey}" "DisplayVersion" "${AppVersion}"
   WriteRegStr HKLM "${MaintUninstallKey}" "Publisher" "Mozilla"
   WriteRegStr HKLM "${MaintUninstallKey}" "Comments" \
                    "${BrandFullName} ${AppVersion} (${ARCH} ${AB_CD})"
+  WriteRegDWORD HKLM "${MaintUninstallKey}" "NoModify" 1
   ${GetSize} "$INSTDIR" "/S=0K" $R2 $R3 $R4
-  WriteRegDWORD HKLM "${MaintUninstallKey}" "EstimatedSize" $R2 
+  WriteRegDWORD HKLM "${MaintUninstallKey}" "EstimatedSize" $R2
 
   ; Write out that a maintenance service was attempted.
   ; We do this because on upgrades we will check this value and we only
   ; want to install once on the first upgrade to maintenance service.
   ; Also write out that we are currently installed, preferences will check
   ; this value to determine if we should show the service update pref.
   ; Since the Maintenance service can be installed either x86 or x64,
   ; always use the 64-bit registry for checking if an attempt was made.
--- a/build/autoconf/gcc-pr49911.m4
+++ b/build/autoconf/gcc-pr49911.m4
@@ -51,17 +51,17 @@ int main(void) {
 }
 ], true,
    ac_have_gcc_pr49911="yes",
    true)
 CXXFLAGS="$_SAVE_CXXFLAGS"
 
 AC_LANG_RESTORE
 
-if test "$ac_have_gcc_pr49911" == "yes"; then
+if test "$ac_have_gcc_pr49911" = "yes"; then
    AC_MSG_RESULT(yes)
    CFLAGS="$CFLAGS -fno-tree-vrp"
    CXXFLAGS="$CXXFLAGS -fno-tree-vrp"
 else
    AC_MSG_RESULT(no)
 fi
 fi
 ])
--- a/build/mobile/devicemanager.py
+++ b/build/mobile/devicemanager.py
@@ -203,24 +203,24 @@ class DeviceManager:
     #ex: '"name=value;name2=value2;etc=..." process args' -> 'process args'
     parts = appname.split('"')
     if (len(parts) > 2):
       appname = ' '.join(parts[2:]).strip()
   
     pieces = appname.split(' ')
     parts = pieces[0].split('/')
     app = parts[-1]
-    procre = re.compile('.*' + app + '.*')
 
     procList = self.getProcessList()
     if (procList == []):
       return None
       
     for proc in procList:
-      if (procre.match(proc[1])):
+      procName = proc[1].split('/')[-1]
+      if (procName == app):
         pid = proc[0]
         break
     return pid
 
   # external function
   # returns:
   #  success: output from testagent
   #  failure: None
@@ -341,34 +341,17 @@ class DeviceManager:
   # Either we will have /tests/fennec or /tests/firefox but we will never have
   # both.  Return the one that exists
   # TODO: ensure we can support org.mozilla.firefox
   # external function
   # returns:
   #  success: path for app root
   #  failure: None
   def getAppRoot(self):
-    devroot = self.getDeviceRoot()
-    if (devroot == None):
-      return None
-
-    if (self.dirExists(devroot + '/fennec')):
-      return devroot + '/fennec'
-    elif (self.dirExists(devroot + '/firefox')):
-      return devroot + '/firefox'
-    elif (self.dirExsts('/data/data/org.mozilla.fennec')):
-      return 'org.mozilla.fennec'
-    elif (self.dirExists('/data/data/org.mozilla.firefox')):
-      return 'org.mozilla.firefox'
-    elif (self.dirExists('/data/data/org.mozilla.fennec_aurora')):
-      return 'org.mozilla.fennec_aurora'
-    elif (self.dirExists('/data/data/org.mozilla.firefox_beta')):
-      return 'org.mozilla.firefox_beta'
-
-    # Failure (either not installed or not a recognized platform)
+    assert 0 == 1
     return None
 
   # Gets the directory location on the device for a specific test type
   # Type is one of: xpcshell|reftest|mochitest
   # external function
   # returns:
   #  success: path for test root
   #  failure: None
--- a/build/mobile/devicemanagerADB.py
+++ b/build/mobile/devicemanagerADB.py
@@ -253,16 +253,20 @@ class DeviceManagerADB(DeviceManager):
       parts = parts[2:]
     return self.launchProcess(parts, failIfRunning)
 
   # external function
   # returns:
   #  success: output filename
   #  failure: None
   def launchProcess(self, cmd, outputFile = "process.txt", cwd = '', env = '', failIfRunning=False):
+    if cmd[0] == "am":
+      self.checkCmd(["shell"] + cmd)
+      return outputFile
+
     acmd = ["shell", "am","start"]
     cmd = ' '.join(cmd).strip()
     i = cmd.find(" ")
     # SUT identifies the URL by looking for :\\ -- another strategy to consider
     re_url = re.compile('^[http|file|chrome|about].*')
     last = cmd.rfind(" ")
     uri = ""
     args = ""
@@ -277,17 +281,17 @@ class DeviceManagerADB(DeviceManager):
     if args != "":
       acmd.append("args")
       acmd.append(args)
     if uri != "":
       acmd.append("-d")
       acmd.append(''.join(['\'',uri, '\'']));
     print acmd
     self.checkCmd(acmd)
-    return outputFile;
+    return outputFile
 
   # external function
   # returns:
   #  success: output from testagent
   #  failure: None
   def killProcess(self, appname):
     procs = self.getProcessList()
     for (pid, name, user) in procs:
@@ -417,25 +421,24 @@ class DeviceManagerADB(DeviceManager):
 
   # Either we will have /tests/fennec or /tests/firefox but we will never have
   # both.  Return the one that exists
   # TODO: ensure we can support org.mozilla.firefox
   # external function
   # returns:
   #  success: path for app root
   #  failure: None
-  def getAppRoot(self):
+  def getAppRoot(self, packageName):
     devroot = self.getDeviceRoot()
     if (devroot == None):
       return None
 
-    if (self.dirExists(devroot + '/fennec')):
-      return devroot + '/fennec'
-    elif (self.dirExists(devroot + '/firefox')):
-      return devroot + '/firefox'
+    if (packageName and self.dirExists('/data/data/' + packageName)):
+      self.packageName = packageName
+      return '/data/data/' + packageName
     elif (self.packageName and self.dirExists('/data/data/' + self.packageName)):
       return '/data/data/' + self.packageName
 
     # Failure (either not installed or not a recognized platform)
     print "devicemanagerADB: getAppRoot failed"
     return None
 
   # Gets the directory location on the device for a specific test type
--- a/build/mobile/devicemanagerSUT.py
+++ b/build/mobile/devicemanagerSUT.py
@@ -547,24 +547,24 @@ class DeviceManagerSUT(DeviceManager):
     #ex: '"name=value;name2=value2;etc=..." process args' -> 'process args'
     parts = appname.split('"')
     if (len(parts) > 2):
       appname = ' '.join(parts[2:]).strip()
   
     pieces = appname.split(' ')
     parts = pieces[0].split('/')
     app = parts[-1]
-    procre = re.compile('.*' + app + '.*')
 
     procList = self.getProcessList()
     if (procList == []):
       return None
       
     for proc in procList:
-      if (procre.match(proc[1])):
+      procName = proc[1].split('/')[-1]
+      if (procName == app):
         pid = proc[0]
         break
     return pid
 
   # external function
   # returns:
   #  success: output from testagent
   #  failure: None
@@ -853,16 +853,25 @@ class DeviceManagerSUT(DeviceManager):
     deviceRoot = self.stripPrompt(data).strip('\n') + '/tests'
 
     if (not self.dirExists(deviceRoot)):
       if (self.mkDir(deviceRoot) == None):
         return None
 
     return deviceRoot
 
+  def getAppRoot(self, packageName):
+    try:
+      data = self.verifySendCMD(['getapproot '+packageName])
+    except:
+      return None
+  
+    appRoot = self.stripPrompt(data).strip('\n')
+    return appRoot
+
   # external function
   # returns:
   #  success: output of unzip command
   #  failure: None
   def unpackFile(self, filename):
     devroot = self.getDeviceRoot()
     if (devroot == None):
       return None
--- a/build/mobile/remoteautomation.py
+++ b/build/mobile/remoteautomation.py
@@ -117,16 +117,21 @@ class RemoteAutomation(Automation):
         except:
           print "WARNING: unable to remove directory: %s" % (dumpDir)
 
     def buildCommandLine(self, app, debuggerInfo, profileDir, testURL, extraArgs):
         # If remote profile is specified, use that instead
         if (self._remoteProfile):
             profileDir = self._remoteProfile
 
+        # Hack for robocop, if app & testURL == None and extraArgs contains the rest of the stuff, lets 
+        # assume extraArgs is all we need
+        if app == "am" and extraArgs[0] == "instrument":
+            return app, extraArgs
+ 
         cmd, args = Automation.buildCommandLine(self, app, debuggerInfo, profileDir, testURL, extraArgs)
         # Remove -foreground if it exists, if it doesn't this just returns
         try:
             args.remove('-foreground')
         except:
             pass
 #TODO: figure out which platform require NO_EM_RESTART
 #        return app, ['--environ:NO_EM_RESTART=1'] + args
--- a/build/mobile/robocop/Assert.java.in
+++ b/build/mobile/robocop/Assert.java.in
@@ -37,17 +37,19 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 package @ANDROID_PACKAGE_NAME@;
 
 public interface Assert {
   void dumpLog(String message);
   void setLogFile(String filename);
+  void setTestName(String testName);
 
+  void finalize();
   void ok(boolean condition, String name, String diag);
   void is(Object a, Object b, String name);
   void isnot(Object a, Object b, String name);
   void todo(boolean condition, String name, String diag);
   void todo_is(Object a, Object b, String name);
   void todo_isnot(Object a, Object b, String name);
   void info(String name, String message);
 }
--- a/build/mobile/robocop/Driver.java.in
+++ b/build/mobile/robocop/Driver.java.in
@@ -63,19 +63,9 @@ public interface Driver {
   int getHeight();
   int getGeckoTop();
   int getGeckoLeft();
   int getGeckoWidth();
   int getGeckoHeight();
 
   void startFrameRecording();
   int stopFrameRecording();
-  void dumpLog(String message);
-  void setLogFile(String filename);
-
-  void ok(boolean condition, String name, String diag);
-  void is(Object a, Object b, String name);
-  void isnot(Object a, Object b, String name);
-  void todo(boolean condition, String name, String diag);
-  void todo_is(Object a, Object b, String name);
-  void todo_isnot(Object a, Object b, String name);
-  void info(String name, String message);
 }
--- a/build/mobile/robocop/FennecNativeAssert.java.in
+++ b/build/mobile/robocop/FennecNativeAssert.java.in
@@ -44,16 +44,17 @@ import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileReader;
 import java.io.FileWriter;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Date;
 
 import java.lang.Class;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 import java.lang.reflect.InvocationHandler;
 import java.lang.Long;
 
@@ -72,17 +73,32 @@ public class FennecNativeAssert implemen
   
   // Objects for reflexive access of fennec classes.
 
   private LinkedList<testInfo> testList = new LinkedList<testInfo>();
 
   // If waiting for an event.
   private boolean asleep = false;
 
-  public FennecNativeAssert(){
+  // Internal state variables to make logging match up with existing mochitests
+  private int lineNumber = 0;
+  private int passed = 0;
+  private int failed = 0;
+  private int todo = 0;
+  
+  // Used to write the first line of the test file
+  private boolean logStarted = false;
+
+  // Used to write the test-start/test-end log lines
+  private String logTestName = "";
+
+  // Measure the time it takes to run test case
+  private long startTime = 0;
+
+  public FennecNativeAssert() {
   }
 
   // Write information to a logfile and logcat
   public void dumpLog(String message)
   {
     File file = new File(logFile);
     BufferedWriter bw = null;
 
@@ -105,66 +121,128 @@ public class FennecNativeAssert implemen
 
     Log.i("Robocop", message);
   }
 
   // Set the filename used for dumpLog.
   public void setLogFile(String filename)
   {
     logFile = filename;
+
+    //TODO: these two messages are mochitest specific
+    String message;
+    if (!logStarted) {
+      message = Integer.toString(lineNumber++) + " INFO SimpleTest START";
+      dumpLog(message);
+      logStarted = true;
+    }
+
+    if (logTestName != "") {
+      message = Integer.toString(lineNumber++) + " INFO TEST-END | " + logTestName;
+      long diff = (new Date().getTime()) - startTime;
+      message += " | finished in " + diff + "ms";
+      dumpLog(message);
+      logTestName = "";
+    }
   }
 
+  public void setTestName(String testName)
+  {
+    String[] nameParts = testName.split("\\.");
+    logTestName = nameParts[nameParts.length - 1];
+    startTime = new Date().getTime();
+
+    //TODO: this is mochitest specific
+    String message = Integer.toString(lineNumber++) + " INFO TEST-START | " + logTestName;
+    dumpLog(message);
+  }
 
   class testInfo {
     public boolean result;
     public String name;
     public String diag;
     public boolean todo;
     public testInfo(boolean r, String n, String d, boolean t) {
       result = r;
       name = n;
       diag = d;
       todo = t;
     }
 
   }
 
-
-  private void _logResult(testInfo test, String passString, String failString)
+  private void _logMochitestResult(testInfo test, String passString, String failString)
   {
     boolean isError = true;
     String resultString = failString;
-    if(test.result || test.todo){
+    if (test.result || test.todo) {
       isError = false;
     }
-    if(test.result)
+    if (test.result)
     {
       resultString = passString;
     }
-    String diag= test.name;
-    if(test.diag!=null) diag+= " - " + test.diag;
+    String diag = test.name;
+    if (test.diag != null) diag += " - " + test.diag;
 
-    String message = resultString + " | " + "ROBOCOP" + " | " + diag;
-    if(isError) {
-      if(logFile == null)
+    String message = Integer.toString(lineNumber++) + " INFO " + resultString + " | " + logTestName + " | " + diag;
+    if (isError) {
+      if (logFile == null)
       {
         assert(false);
       }
       else {
         dumpLog(message);
       }
     }
     else {
       dumpLog(message);
     }
+
+    if (test.todo) {
+      todo++;
+    } else if (isError) {
+      failed++;
+    } else {
+      passed++;
+    }
+  }
+
+  public void finalize()
+  {
+    // It appears that we call finalize during cleanup, this might be an invalid assertion.
+    String message;
+
+    if (logTestName != "") {
+      long diff = (new Date().getTime()) - startTime;
+
+      //TODO: this is mochitest specific
+      message = Integer.toString(lineNumber++) + " INFO TEST-END | " + logTestName;
+      message += " | finished in " + diff + "ms";
+      dumpLog(message);
+
+      logTestName = "";
+    }
+
+    //TODO: this is all mochitest specific
+    message = Integer.toString(lineNumber++) + " INFO TEST-START | Shutdown";
+    dumpLog(message);
+    message = Integer.toString(lineNumber++) + " INFO Passed: " + Integer.toString(passed);
+    dumpLog(message);
+    message = Integer.toString(lineNumber++) + " INFO Failed: " + Integer.toString(failed);
+    dumpLog(message);
+    message = Integer.toString(lineNumber++) + " INFO Todo: " + Integer.toString(todo);
+    dumpLog(message);
+    message = Integer.toString(lineNumber++) + " INFO SimpleTest FINISHED";
+    dumpLog(message);
   }
 
   public void ok(boolean condition, String name, String diag) {
     testInfo test = new testInfo(condition, name, diag, false);
-    _logResult(test, "TEST-PASS", "TEST-UNEXPECTED-FAIL");
+    _logMochitestResult(test, "TEST-PASS", "TEST-UNEXPECTED-FAIL");
     testList.add(test);
   }
 
   public void is(Object a, Object b, String name) {
     boolean pass = a.equals(b);
     String diag = "got " + a.toString() + ", expected " + b.toString();
     if(pass) {
       diag = a.toString() + " should equal " + b.toString();
@@ -178,17 +256,17 @@ public class FennecNativeAssert implemen
     if(pass) {
       diag = a.toString() + " should not equal " + b.toString();
     }
     ok(pass, name, diag);
   }
 
   public void todo(boolean condition, String name, String diag) {
     testInfo test = new testInfo(condition, name, diag, true);
-    _logResult(test, "TEST-UNEXPECTED-PASS", "TEST-KNOWN-FAIL");
+    _logMochitestResult(test, "TEST-UNEXPECTED-PASS", "TEST-KNOWN-FAIL");
     testList.add(test);
   }
 
   public void todo_is(Object a, Object b, String name) {
     boolean pass = a.equals(b);
     String diag = "got " + a.toString() + ", expected " + b.toString();
     if(pass) {
       diag = a.toString() + " should equal " + b.toString();
@@ -202,11 +280,11 @@ public class FennecNativeAssert implemen
     if(pass) {
       diag = a.toString() + " should not equal " + b.toString();
     }
     todo(pass, name, diag);
   }
 
   public void info(String name, String message) {
     testInfo test = new testInfo(true, name, message, false);
-    _logResult(test, "TEST-INFO", "INFO FAILED?");
+    _logMochitestResult(test, "TEST-INFO", "INFO FAILED?");
   }
 }
--- a/build/mobile/robocop/FennecNativeDriver.java.in
+++ b/build/mobile/robocop/FennecNativeDriver.java.in
@@ -65,32 +65,28 @@ import org.json.*;
 
 import com.jayway.android.robotium.solo.Solo;
 
 public class FennecNativeDriver implements Driver {
   // Map of IDs to element names.
   private HashMap locators = null;
   private Activity activity;
   private Solo solo;
-  private String logFile;
 
   // Objects for reflexive access of fennec classes.
   private ClassLoader classLoader;
   private Class gel;
   private Class ge;
   private Class gas;
   private Method registerGEL;
   private Method unregisterGEL;
   private Method sendGE;
   private Method _startFrameRecording;
   private Method _stopFrameRecording;
 
-
-  private LinkedList<testInfo> testList = new LinkedList<testInfo>();
-
   public FennecNativeDriver(Activity activity, Solo robocop){
     this.activity = activity;
     this.solo = robocop;
 
     // Set up table of fennec_ids.
     locators = convertTextToTable(getFile("/mnt/sdcard/fennec_ids.txt"));
 
     // Set up reflexive access of java classes and methods.
@@ -281,144 +277,21 @@ public class FennecNativeDriver implemen
         text.append('\n');
       }
     } catch(IOException e) {
       e.printStackTrace();
     }
     return text.toString();  
   }
 
-  // Write information to a logfile and logcat
-  public void dumpLog(String message)
-  {
-    File file = new File(logFile);
-    BufferedWriter bw = null;
-
-    try {
-      bw = new BufferedWriter(new FileWriter(logFile, true));
-      bw.write(message);
-      bw.newLine();
-    } catch(IOException e) {
-      e.printStackTrace();
-    } finally {
-      try {
-        if (bw != null) {
-          bw.flush();
-          bw.close();
-        }
-      } catch (IOException ex) {
-        ex.printStackTrace();
-      }
-    }
-
-    Log.i("Robocop", message);
-  }
-
-  // Set the filename used for dumpLog.
-  public void setLogFile(String filename)
-  {
-    logFile = filename;
-  }
-
   // Takes a string of "key=value" pairs split by \n and creates a hash table.
   public static HashMap convertTextToTable(String data)
   {
     HashMap retVal = new HashMap();
 
     String[] lines = data.split("\n");
     for (int i = 0; i < lines.length; i++) {
       String[] parts = lines[i].split("=");
       retVal.put(parts[0].trim(), parts[1].trim());
     }
     return retVal;
   }
-
-  class testInfo {
-    public boolean result;
-    public String name;
-    public String diag;
-    public boolean todo;
-    public testInfo(boolean r, String n, String d, boolean t) {
-      result = r;
-      name = n;
-      diag = d;
-      todo = t;
-    }
-
-  }
-
-
-  private void _logResult(testInfo test, String passString, String failString)
-  {
-    boolean isError = true;
-    String resultString = failString;
-    if(test.result || test.todo){
-      isError = false;
-    }
-    if(test.result)
-    {
-      resultString = passString;
-    }
-    String diag= test.name;
-    if(test.diag!=null) diag+= " - " + test.diag;
-
-    String message = resultString + " | " + "ROBOCOP" + " | " + diag;
-    if(isError) {
-      dumpLog(message);
-    }
-    else {
-      dumpLog(message);
-    }
-  }
-
-  public void ok(boolean condition, String name, String diag) {
-    testInfo test = new testInfo(condition, name, diag, false);
-    _logResult(test, "TEST-PASS", "TEST-UNEXPECTED-FAIL");
-    testList.add(test);
-  }
-
-  public void is(Object a, Object b, String name) {
-    boolean pass = a.equals(b);
-    String diag = "got " + a.toString() + ", expected " + b.toString();
-    if(pass) {
-      diag = a.toString() + " should equal " + b.toString();
-    }
-    ok(pass, name, diag);
-  }
-  
-  public void isnot(Object a, Object b, String name) {
-    boolean pass = !a.equals(b);
-    String diag = "didn't expect " + a.toString() + ", but got it";
-    if(pass) {
-      diag = a.toString() + " should not equal " + b.toString();
-    }
-    ok(pass, name, diag);
-  }
-
-  public void todo(boolean condition, String name, String diag) {
-    testInfo test = new testInfo(condition, name, diag, true);
-    _logResult(test, "TEST-UNEXPECTED-PASS", "TEST-KNOWN-FAIL");
-    testList.add(test);
-  }
-
-  public void todo_is(Object a, Object b, String name) {
-    boolean pass = a.equals(b);
-    String diag = "got " + a.toString() + ", expected " + b.toString();
-    if(pass) {
-      diag = a.toString() + " should equal " + b.toString();
-    }
-    todo(pass, name, diag);
-  }
-  
-  public void todo_isnot(Object a, Object b, String name) {
-    boolean pass = !a.equals(b);
-    String diag = "didn't expect " + a.toString() + ", but got it";
-    if(pass) {
-      diag = a.toString() + " should not equal " + b.toString();
-    }
-    todo(pass, name, diag);
-  }
-
-  public void info(String name, String message) {
-    testInfo test = new testInfo(true, name, message, false);
-    _logResult(test, "TEST-INFO", "INFO FAILED?");
-  }
 }
--- a/build/mobile/sutagent/android/DoCommand.java
+++ b/build/mobile/sutagent/android/DoCommand.java
@@ -132,17 +132,17 @@ public class DoCommand {
 
     String    currentDir = "/";
     String    sErrorPrefix = "##AGENT-WARNING## ";
     boolean bTraceOn = false;
 
     String ffxProvider = "org.mozilla.ffxcp";
     String fenProvider = "org.mozilla.fencp";
 
-    private final String prgVersion = "SUTAgentAndroid Version 1.03";
+    private final String prgVersion = "SUTAgentAndroid Version 1.04";
 
     public enum Command
         {
         RUN ("run"),
         EXEC ("exec"),
         ENVRUN ("envrun"),
         KILL ("kill"),
         PS ("ps"),
@@ -1280,17 +1280,17 @@ private void CancelNotification()
         String sRet = sErrorPrefix + " internal error [no context]";
         Context ctx = contextWrapper.getApplicationContext();
 
         if (ctx != null)
             {
             try {
                 Context appCtx = ctx.createPackageContext(AppName, 0);
                 ContextWrapper appCtxW = new ContextWrapper(appCtx);
-                sRet = appCtxW.getPackageResourcePath();
+                sRet = appCtxW.getApplicationInfo().dataDir;
                 appCtxW = null;
                 appCtx = null;
                 ctx = null;
                 System.gc();
                 }
             catch (NameNotFoundException e)
                 {
                 e.printStackTrace();
--- a/build/win32/Makefile.in
+++ b/build/win32/Makefile.in
@@ -57,17 +57,17 @@ DIRS += \
   $(NULL)
 
 PROGRAM = crashinject$(BIN_SUFFIX)
 USE_STATIC_LIBS = 1
 CPPSRCS = crashinject.cpp
 
 endif # ENABLE_TESTS
 
-MOZ_UTILS_LDFLAGS =
+MOZ_GLUE_LDFLAGS =
 
 include $(topsrcdir)/config/rules.mk
 
 ifdef WIN32_REDIST_DIR
 ifndef MOZ_DEBUG
 
 ifeq (1400,$(_MSC_VER))
 REDIST_FILES = \
--- a/build/win32/crashinjectdll/Makefile.in
+++ b/build/win32/crashinjectdll/Makefile.in
@@ -45,11 +45,11 @@ include $(DEPTH)/config/autoconf.mk
 
 LIBRARY_NAME = crashinjectdll
 DEFFILE = $(srcdir)/crashinjectdll.def
 FORCE_SHARED_LIB = 1
 USE_STATIC_LIBS = 1
 
 CPPSRCS = crashinjectdll.cpp
 
-MOZ_UTILS_LDFLAGS =
+MOZ_GLUE_LDFLAGS =
 
 include $(topsrcdir)/config/rules.mk
--- a/build/win32/vmwarerecordinghelper/Makefile.in
+++ b/build/win32/vmwarerecordinghelper/Makefile.in
@@ -46,11 +46,11 @@ include $(DEPTH)/config/autoconf.mk
 LIBRARY_NAME = vmwarerecordinghelper
 DEFFILE = $(srcdir)/$(LIBRARY_NAME).def
 
 FORCE_SHARED_LIB = 1
 USE_STATIC_LIBS = 1
 
 CPPSRCS = $(LIBRARY_NAME).cpp
 
-MOZ_UTILS_LDFLAGS =
+MOZ_GLUE_LDFLAGS =
 
 include $(topsrcdir)/config/rules.mk
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -620,18 +620,18 @@ USE_GSSAPI	= @USE_GSSAPI@
 MOZILLA_OFFICIAL = @MOZILLA_OFFICIAL@
 
 # Win32 options
 MOZ_BROWSE_INFO	= @MOZ_BROWSE_INFO@
 MOZ_TOOLS_DIR	= @MOZ_TOOLS_DIR@
 MOZ_QUANTIFY	= @MOZ_QUANTIFY@
 MSMANIFEST_TOOL = @MSMANIFEST_TOOL@
 WIN32_REDIST_DIR = @WIN32_REDIST_DIR@
-MOZ_UTILS_LDFLAGS = @MOZ_UTILS_LDFLAGS@
-MOZ_UTILS_PROGRAM_LDFLAGS = @MOZ_UTILS_PROGRAM_LDFLAGS@
+MOZ_GLUE_LDFLAGS = @MOZ_GLUE_LDFLAGS@
+MOZ_GLUE_PROGRAM_LDFLAGS = @MOZ_GLUE_PROGRAM_LDFLAGS@
 WIN32_CRT_LIBS = @WIN32_CRT_LIBS@
 
 # This is used to pass jemalloc flags to NSS
 DLLFLAGS = @DLLFLAGS@
 
 # Codesighs tools option, enables win32 mapfiles.
 MOZ_MAPINFO	= @MOZ_MAPINFO@
 
--- a/config/config.mk
+++ b/config/config.mk
@@ -238,23 +238,23 @@ endif # NS_TRACE_MALLOC
 
 endif # MOZ_DEBUG
 
 # We don't build a static CRT when building a custom CRT,
 # it appears to be broken. So don't link to jemalloc if
 # the Makefile wants static CRT linking.
 ifeq ($(MOZ_MEMORY)_$(USE_STATIC_LIBS),1_1)
 # Disable default CRT libs and add the right lib path for the linker
-MOZ_UTILS_LDFLAGS=
+MOZ_GLUE_LDFLAGS=
 endif
 
 endif # WINNT && !GNU_CC
 
-ifndef MOZ_UTILS_PROGRAM_LDFLAGS
-MOZ_UTILS_PROGRAM_LDFLAGS=$(MOZ_UTILS_LDFLAGS)
+ifndef MOZ_GLUE_PROGRAM_LDFLAGS
+MOZ_GLUE_PROGRAM_LDFLAGS=$(MOZ_GLUE_LDFLAGS)
 endif
 
 #
 # Build using PIC by default
 #
 _ENABLE_PIC=1
 
 # Determine if module being compiled is destined
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -787,17 +787,17 @@ endif # EXPORT_LIBRARY
 endif # LIBRARY_NAME
 
 ifneq (,$(filter-out %.$(LIB_SUFFIX),$(SHARED_LIBRARY_LIBS)))
 $(error SHARED_LIBRARY_LIBS must contain .$(LIB_SUFFIX) files only)
 endif
 
 # Create dependencies on static (and shared EXTRA_DSO_LIBS) libraries
 DO_EXPAND_LIBS = $(foreach f,$(1),$(if $(filter %.$(LIB_SUFFIX),$(f)),$(if $(wildcard $(f).$(LIBS_DESC_SUFFIX)),$(f).$(LIBS_DESC_SUFFIX),$(if $(wildcard $(f)),$(f)))))
-LIBS_DEPS = $(call DO_EXPAND_LIBS,$(filter %.$(LIB_SUFFIX),$(LIBS) $(if $(PROGRAM)$(SIMPLE_PROGRAMS),$(MOZ_UTILS_PROGRAM_LDFLAGS))))
+LIBS_DEPS = $(call DO_EXPAND_LIBS,$(filter %.$(LIB_SUFFIX),$(LIBS) $(if $(PROGRAM)$(SIMPLE_PROGRAMS),$(MOZ_GLUE_PROGRAM_LDFLAGS))))
 SHARED_LIBRARY_LIBS_DEPS = $(call DO_EXPAND_LIBS,$(SHARED_LIBRARY_LIBS))
 HOST_LIBS_DEPS = $(filter %.$(LIB_SUFFIX),$(HOST_LIBS))
 DSO_LDOPTS_DEPS = $(call DO_EXPAND_LIBS,$(EXTRA_DSO_LIBS) $(filter %.$(LIB_SUFFIX), $(EXTRA_DSO_LDOPTS)))
 
 # Dependencies which, if modified, should cause everything to rebuild
 GLOBAL_DEPS += Makefile Makefile.in $(DEPTH)/config/autoconf.mk $(topsrcdir)/config/config.mk
 
 ##############################################
@@ -888,17 +888,17 @@ alltags:
 
 #
 # PROGRAM = Foo
 # creates OBJS, links with LIBS to create Foo
 #
 $(PROGRAM): $(PROGOBJS) $(LIBS_DEPS) $(EXTRA_DEPS) $(EXE_DEF_FILE) $(RESFILE) $(GLOBAL_DEPS)
 	@$(RM) $@.manifest
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
-	$(EXPAND_LD) -NOLOGO -OUT:$@ -PDB:$(LINK_PDBFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
+	$(EXPAND_LD) -NOLOGO -OUT:$@ -PDB:$(LINK_PDBFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
 ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		if test -f "$(srcdir)/$@.manifest"; then \
 			echo "Embedding manifest from $(srcdir)/$@.manifest and $@.manifest"; \
 			mt.exe -NOLOGO -MANIFEST "$(win_srcdir)/$@.manifest" $@.manifest -OUTPUTRESOURCE:$@\;1; \
 		else \
 			echo "Embedding manifest from $@.manifest"; \
 			mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
@@ -910,20 +910,20 @@ ifdef MSMANIFEST_TOOL
 endif	# MSVC with manifest tool
 ifdef MOZ_PROFILE_GENERATE
 # touch it a few seconds into the future to work around FAT's
 # 2-second granularity
 	touch -t `date +%Y%m%d%H%M.%S -d "now+5seconds"` pgo.relink
 endif
 else # !WINNT || GNU_CC
 ifeq ($(CPP_PROG_LINK),1)
-	$(EXPAND_CCC) -o $@ $(CXXFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(WRAP_LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
+	$(EXPAND_CCC) -o $@ $(CXXFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(WRAP_LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
 	@$(call CHECK_STDCXX,$@)
 else # ! CPP_PROG_LINK
-	$(EXPAND_CC) -o $@ $(CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
+	$(EXPAND_CC) -o $@ $(CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
 endif # CPP_PROG_LINK
 endif # WINNT && !GNU_CC
 
 ifdef ENABLE_STRIP
 	$(STRIP) $@
 endif
 ifdef MOZ_POST_PROGRAM_COMMAND
 	$(MOZ_POST_PROGRAM_COMMAND) $@
@@ -959,29 +959,29 @@ endif
 # in one directory, it assumes everything to compile Foo is in
 # Foo.o (from either Foo.c or Foo.cpp).
 #
 # SIMPLE_PROGRAMS = Foo Bar
 # creates Foo.o Bar.o, links with LIBS to create Foo, Bar.
 #
 $(SIMPLE_PROGRAMS): %$(BIN_SUFFIX): %.$(OBJ_SUFFIX) $(LIBS_DEPS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
-	$(EXPAND_LD) -nologo -out:$@ -pdb:$(LINK_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
+	$(EXPAND_LD) -nologo -out:$@ -pdb:$(LINK_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
 ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
 		rm -f $@.manifest; \
 	fi
 endif	# MSVC with manifest tool
 else
 ifeq ($(CPP_PROG_LINK),1)
-	$(EXPAND_CCC) $(CXXFLAGS) -o $@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS)
+	$(EXPAND_CCC) $(CXXFLAGS) -o $@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS)
 	@$(call CHECK_STDCXX,$@)
 else
-	$(EXPAND_CC) $(CFLAGS) $(OUTOPTION)$@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS)
+	$(EXPAND_CC) $(CFLAGS) $(OUTOPTION)$@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS)
 endif # CPP_PROG_LINK
 endif # WINNT && !GNU_CC
 
 ifdef ENABLE_STRIP
 	$(STRIP) $@
 endif
 ifdef MOZ_POST_PROGRAM_COMMAND
 	$(MOZ_POST_PROGRAM_COMMAND) $@
@@ -1084,20 +1084,20 @@ endif
 $(SHARED_LIBRARY): $(OBJS) $(LOBJS) $(DEF_FILE) $(RESFILE) $(SHARED_LIBRARY_LIBS_DEPS) $(LIBRARY) $(EXTRA_DEPS) $(DSO_LDOPTS_DEPS) $(GLOBAL_DEPS)
 ifndef INCREMENTAL_LINKER
 	$(RM) $@
 endif
 ifdef DTRACE_LIB_DEPENDENT
 ifndef XP_MACOSX
 	dtrace -G -C -s $(MOZILLA_DTRACE_SRC) -o  $(DTRACE_PROBE_OBJ) $(shell $(EXPAND_LIBS) $(MOZILLA_PROBE_LIBS))
 endif
-	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(DTRACE_PROBE_OBJ) $(MOZILLA_PROBE_LIBS) $(RESFILE) $(LDFLAGS) $(MOZ_UTILS_LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
+	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(DTRACE_PROBE_OBJ) $(MOZILLA_PROBE_LIBS) $(RESFILE) $(LDFLAGS) $(MOZ_GLUE_LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
 	@$(RM) $(DTRACE_PROBE_OBJ)
 else # ! DTRACE_LIB_DEPENDENT
-	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(RESFILE) $(LDFLAGS) $(MOZ_UTILS_LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
+	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(RESFILE) $(LDFLAGS) $(MOZ_GLUE_LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
 endif # DTRACE_LIB_DEPENDENT
 	@$(call CHECK_STDCXX,$@)
 
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
 ifdef MSMANIFEST_TOOL
 ifdef EMBED_MANIFEST_AT
 	@if test -f $@.manifest; then \
 		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;$(EMBED_MANIFEST_AT); \
--- a/configure.in
+++ b/configure.in
@@ -545,47 +545,23 @@ if test -n "$CROSS_COMPILE" -a "$target"
     AC_TRY_COMPILE([], [return(0);],
 	[ac_cv_prog_hostcxx_works=1 AC_MSG_RESULT([yes])],
 	AC_MSG_ERROR([installation or configuration problem: host compiler $HOST_CXX cannot create executables.]) )
 
     CC=$_SAVE_CC
     CFLAGS=$_SAVE_CFLAGS
     LDFLAGS=$_SAVE_LDFLAGS
 
-    case "$build:$target" in
-      powerpc-apple-darwin8*:i?86-apple-darwin*)
-        dnl The Darwin cross compiler doesn't necessarily point itself at a
-        dnl root that has libraries for the proper architecture, it defaults
-        dnl to the system root.  The libraries in the system root on current
-        dnl versions of PPC OS X 10.4 aren't fat, so these target compiler
-        dnl checks will fail.  Fake a working SDK in that case.
-        _SAVE_CFLAGS=$CFLAGS
-        _SAVE_CXXFLAGS=$CXXLAGS
-        CFLAGS="-isysroot /Developer/SDKs/MacOSX10.5.sdk $CFLAGS"
-        CXXFLAGS="-isysroot /Developer/SDKs/MacOSX10.5.sdk $CXXFLAGS"
-        ;;
-    esac
-
     AC_CHECK_PROGS(CC, $CC "${target_alias}-gcc" "${target}-gcc", :)
     unset ac_cv_prog_CC
     AC_PROG_CC
     AC_CHECK_PROGS(CXX, $CXX "${target_alias}-g++" "${target}-g++", :)
     unset ac_cv_prog_CXX
     AC_PROG_CXX
 
-    case "$build:$target" in
-      powerpc-apple-darwin8*:i?86-apple-darwin*)
-        dnl Revert the changes made above.  From this point on, the target
-        dnl compiler will never be used without applying the SDK to CFLAGS
-        dnl (see --with-macos-sdk below).
-        CFLAGS=$_SAVE_CFLAGS
-        CXXFLAGS=$_SAVE_CXXFLAGS
-        ;;
-    esac
-
     AC_CHECK_PROGS(RANLIB, $RANLIB "${target_alias}-ranlib" "${target}-ranlib", :)
     AC_CHECK_PROGS(AR, $AR "${target_alias}-ar" "${target}-ar", :)
     MOZ_PATH_PROGS(AS, $AS "${target_alias}-as" "${target}-as", :)
     AC_CHECK_PROGS(LD, $LD "${target_alias}-ld" "${target}-ld", :)
     AC_CHECK_PROGS(STRIP, $STRIP "${target_alias}-strip" "${target}-strip", :)
     AC_CHECK_PROGS(WINDRES, $WINDRES "${target_alias}-windres" "${target}-windres", :)
     AC_DEFINE(CROSS_COMPILE)
 else
@@ -1161,19 +1137,16 @@ case "$target" in
 *-darwin*)
     if test -n "$_MACOSX_DEPLOYMENT_TARGET" ; then
         dnl Use the specified value
         export MACOSX_DEPLOYMENT_TARGET=$_MACOSX_DEPLOYMENT_TARGET
     else
         dnl No value specified on the command line or in the environment,
         dnl use architecture minimum.
         case "${target_cpu}" in
-          ppc*)
-            export MACOSX_DEPLOYMENT_TARGET=10.5
-            ;;
           i*86)
             export MACOSX_DEPLOYMENT_TARGET=10.5
             ;;
           x86_64)
             export MACOSX_DEPLOYMENT_TARGET=10.6
             ;;
         esac
     fi
@@ -1853,17 +1826,17 @@ if test "$GNU_CC"; then
     CFLAGS="$CFLAGS -fno-strict-aliasing"
     MKSHLIB='$(CXX) $(CXXFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -Wl,-h,$@ -o $@'
     MKCSHLIB='$(CC) $(CFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -Wl,-h,$@ -o $@'
     DSO_LDOPTS='-shared'
     if test "$GCC_USE_GNU_LD"; then
         # Don't allow undefined symbols in libraries
         DSO_LDOPTS="$DSO_LDOPTS -Wl,-z,defs"
     fi
-    WARNINGS_AS_ERRORS='-Werror'
+    WARNINGS_AS_ERRORS='-Werror -Wno-error=uninitialized'
     DSO_CFLAGS=''
     DSO_PIC_CFLAGS='-fPIC'
     ASFLAGS="$ASFLAGS -fPIC"
     _MOZ_RTTI_FLAGS_ON=-frtti
     _MOZ_RTTI_FLAGS_OFF=-fno-rtti
 
     # Turn on GNU specific features
     # -Wall - turn on all warnings
@@ -7133,27 +7106,27 @@ MOZ_ARG_ENABLE_BOOL(jemalloc,
 if test "$NS_TRACE_MALLOC"; then
     MOZ_MEMORY=
 fi
 if test "$MOZ_DMD"; then
     MOZ_MEMORY=
 fi
 
 if test "${OS_TARGET}" = "Android"; then
-  dnl On Android, we use WRAP_LDFLAGS to link everything to mozutils
+  dnl On Android, we use WRAP_LDFLAGS to link everything to mozglue
   :
 elif test "${OS_TARGET}" = "WINNT" -o "${OS_TARGET}" = "Darwin" -o "${OS_TARGET}" = "OS2"; then
-  dnl On Windows, OSX and OS2, we want to link all our binaries against mozutils
-  MOZ_UTILS_LDFLAGS='$(call EXPAND_LIBNAME_PATH,mozutils,$(LIBXUL_DIST)/lib)'
+  dnl On Windows, OSX and OS2, we want to link all our binaries against mozglue
+  MOZ_GLUE_LDFLAGS='$(call EXPAND_LIBNAME_PATH,mozglue,$(LIBXUL_DIST)/lib)'
 else
-  dnl On other Unix systems, we only want to link executables against mozutils
-  MOZ_UTILS_PROGRAM_LDFLAGS='$(MKSHLIB_FORCE_ALL) $(call EXPAND_LIBNAME_PATH,mozutils,$(LIBXUL_DIST)/lib) $(MKSHLIB_UNFORCE_ALL)'
+  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) $(MKSHLIB_UNFORCE_ALL)'
   if test -n "$GNU_CC"; then
-    dnl And we need mozutils symbols to be exported.
-    MOZ_UTILS_PROGRAM_LDFLAGS="$MOZ_UTILS_PROGRAM_LDFLAGS -rdynamic"
+    dnl And we need mozglue symbols to be exported.
+    MOZ_GLUE_PROGRAM_LDFLAGS="$MOZ_GLUE_PROGRAM_LDFLAGS -rdynamic"
   fi
 fi
 
 if test -z "$MOZ_MEMORY"; then
   case "${target}" in
     *-mingw*)
       if test -z "$WIN32_REDIST_DIR" -a -z "$MOZ_DEBUG"; then
         AC_MSG_WARN([When not building jemalloc, you need to set WIN32_REDIST_DIR to the path to the Visual C++ Redist (usually VCINSTALLDIR\redist\x86\Microsoft.VC80.CRT, for VC++ v8) if you intend to distribute your build.])
@@ -7196,17 +7169,17 @@ else
     ;;
   *-*freebsd*)
     AC_DEFINE(MOZ_MEMORY_BSD)
     ;;
   *-android*|*-linuxandroid*)
     AC_DEFINE(MOZ_MEMORY_LINUX)
     AC_DEFINE(MOZ_MEMORY_ANDROID)
     _WRAP_MALLOC=1
-    MOZ_UTILS_LDFLAGS=
+    MOZ_GLUE_LDFLAGS=
     ;;
   *-*linux*)
     AC_DEFINE(MOZ_MEMORY_LINUX)
     ;;
   *-netbsd*)
     AC_DEFINE(MOZ_MEMORY_BSD)
     ;;
   *-solaris*)
@@ -7218,21 +7191,21 @@ else
       WIN32_CRT_LIBS="msvcrt.lib msvcprt.lib"
     else
       WIN32_CRT_LIBS="msvcrtd.lib msvcprtd.lib"
     fi
     dnl Look for a broken crtdll.obj
     WIN32_CRTDLL_FULLPATH=`lib -nologo -list $WIN32_CRT_LIBS | grep crtdll\\.obj`
     lib -NOLOGO -OUT:crtdll.obj $WIN32_CRT_LIBS -EXTRACT:$WIN32_CRTDLL_FULLPATH
     if grep -q '__imp__\{0,1\}free' crtdll.obj; then
-      MOZ_UTILS_LDFLAGS='-LIBPATH:$(DIST)/lib -NODEFAULTLIB:msvcrt -NODEFAULTLIB:msvcrtd -NODEFAULTLIB:msvcprt -NODEFAULTLIB:msvcprtd -DEFAULTLIB:mozcrt'
+      MOZ_GLUE_LDFLAGS='-LIBPATH:$(DIST)/lib -NODEFAULTLIB:msvcrt -NODEFAULTLIB:msvcrtd -NODEFAULTLIB:msvcprt -NODEFAULTLIB:msvcprtd -DEFAULTLIB:mozcrt'
       dnl Also pass this to NSPR/NSS
-      DLLFLAGS="$DLLFLAGS $MOZ_UTILS_LDFLAGS"
+      DLLFLAGS="$DLLFLAGS $MOZ_GLUE_LDFLAGS"
     else
-      DLLFLAGS="$DLLFLAGS -LIBPATH:\$(DIST)/lib -DEFAULTLIB:mozutils"
+      DLLFLAGS="$DLLFLAGS -LIBPATH:\$(DIST)/lib -DEFAULTLIB:mozglue"
     fi
     rm crtdll.obj
 
     export DLLFLAGS
     ;;
   *)
     AC_MSG_ERROR([--enable-jemalloc not supported on ${target}])
     ;;
@@ -7241,26 +7214,26 @@ else
   if test "$OS_ARCH" != "WINNT"; then
     dnl NB: this must be kept in sync with jemalloc.h
     AC_DEFINE(HAVE_JEMALLOC_VALLOC)
   fi
   AC_DEFINE(HAVE_JEMALLOC_POSIX_MEMALIGN)
   AC_DEFINE(HAVE_JEMALLOC_MEMALIGN)
 fi # MOZ_MEMORY
 AC_SUBST(MOZ_MEMORY)
-AC_SUBST(MOZ_UTILS_LDFLAGS)
-AC_SUBST(MOZ_UTILS_PROGRAM_LDFLAGS)
+AC_SUBST(MOZ_GLUE_LDFLAGS)
+AC_SUBST(MOZ_GLUE_PROGRAM_LDFLAGS)
 AC_SUBST(WIN32_CRT_LIBS)
 dnl Need to set this for make because NSS doesn't have configure
 AC_SUBST(DLLFLAGS)
 
 dnl We need to wrap dlopen and related functions on Android because we use
 dnl our own linker.
 if test "$OS_TARGET" = Android; then
-    WRAP_LDFLAGS="${WRAP_LDFLAGS} -L$_objdir/dist/lib -lmozutils"
+    WRAP_LDFLAGS="${WRAP_LDFLAGS} -L$_objdir/dist/lib -lmozglue"
     if test "$MOZ_WIDGET_TOOLKIT" = android; then
         WRAP_LDFLAGS="${WRAP_LDFLAGS} -Wl,--wrap=dlopen,--wrap=dlclose,--wrap=dlerror,--wrap=dlsym,--wrap=dladdr,--wrap=getaddrinfo,--wrap=freeaddrinfo,--wrap=gai_strerror"
     fi
 fi
 
 dnl ========================================================
 dnl = Use malloc wrapper lib
 dnl ========================================================
@@ -9083,21 +9056,21 @@ if test -z "$MOZ_NATIVE_NSPR"; then
     ac_configure_args="$ac_configure_args --with-nspr-cflags='$NSPR_CFLAGS'"
     ac_configure_args="$ac_configure_args --with-nspr-libs='$NSPR_LIBS'"
 fi
 ac_configure_args="$ac_configure_args --with-dist-dir=../../dist"
 ac_configure_args="$ac_configure_args --prefix=$dist"
 ac_configure_args="$ac_configure_args --with-sync-build-files=$_topsrcdir"
 if test "$MOZ_MEMORY"; then
    ac_configure_args="$ac_configure_args --enable-jemalloc"
-   if test -n "$MOZ_UTILS_LDFLAGS"; then
-     export MOZ_UTILS_LDFLAGS
+   if test -n "$MOZ_GLUE_LDFLAGS"; then
+     export MOZ_GLUE_LDFLAGS
    fi
-   if test -n "$MOZ_UTILS_PROGRAM_LDFLAGS"; then
-     export MOZ_UTILS_PROGRAM_LDFLAGS
+   if test -n "$MOZ_GLUE_PROGRAM_LDFLAGS"; then
+     export MOZ_GLUE_PROGRAM_LDFLAGS
    fi
 fi
 export MOZ_APP_NAME
 AC_OUTPUT_SUBDIRS(js/src)
 ac_configure_args="$_SUBDIR_CONFIG_ARGS"
 
 fi # COMPILE_ENVIRONMENT && !LIBXUL_SDK_DIR
 
new file mode 100644
--- /dev/null
+++ b/content/base/crashtests/715056.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<html>
+<head>
+<script>
+
+function boom()
+{
+  var t1 = document.createTextNode("a");
+  var t2 = document.createTextNode("b");
+  document.appendChild(t1);
+  document.appendChild(t2);
+  var sel = window.getSelection();
+  sel.collapse(t2, 0)
+  document.normalize();
+  sel.removeAllRanges();
+}
+
+</script>
+</head>
+<body onload="boom();"></body>
+</html>
--- a/content/base/crashtests/crashtests.list
+++ b/content/base/crashtests/crashtests.list
@@ -100,8 +100,9 @@ load 693212.xhtml
 load 698974-1.html
 load 700090-1.html
 load 700090-2.html
 load 700512.html
 load xhr_html_nullresponse.html
 load 709384.html
 load 713417.html
 load 713417-2.html
+load 715056.html
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -1984,25 +1984,25 @@ private:
   bool mPushedSomething;
 #ifdef DEBUG
   JSContext* mPushedContext;
 #endif
 };
 
 class NS_STACK_CLASS nsAutoScriptBlocker {
 public:
-  nsAutoScriptBlocker(MOZILLA_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) {
-    MOZILLA_GUARD_OBJECT_NOTIFIER_INIT;
+  nsAutoScriptBlocker(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) {
+    MOZ_GUARD_OBJECT_NOTIFIER_INIT;
     nsContentUtils::AddScriptBlocker();
   }
   ~nsAutoScriptBlocker() {
     nsContentUtils::RemoveScriptBlocker();
   }
 private:
-  MOZILLA_DECL_USE_GUARD_OBJECT_NOTIFIER
+  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
 class NS_STACK_CLASS nsAutoScriptBlockerSuppressNodeRemoved :
                           public nsAutoScriptBlocker {
 public:
   nsAutoScriptBlockerSuppressNodeRemoved() {
 #ifdef DEBUG
     ++nsContentUtils::sDOMNodeRemovedSuppressCount;
--- a/content/base/public/nsDOMFile.h
+++ b/content/base/public/nsDOMFile.h
@@ -376,16 +376,16 @@ public:
 
 private:
   PRUint16 mCode;
 };
 
 class NS_STACK_CLASS nsDOMFileInternalUrlHolder {
 public:
   nsDOMFileInternalUrlHolder(nsIDOMBlob* aFile, nsIPrincipal* aPrincipal
-                             MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM);
+                             MOZ_GUARD_OBJECT_NOTIFIER_PARAM);
   ~nsDOMFileInternalUrlHolder();
   nsAutoString mUrl;
 private:
-  MOZILLA_DECL_USE_GUARD_OBJECT_NOTIFIER
+  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
 #endif
--- a/content/base/src/nsDOMFile.cpp
+++ b/content/base/src/nsDOMFile.cpp
@@ -654,18 +654,18 @@ nsDOMFileError::GetCode(PRUint16* aCode)
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////
 // nsDOMFileInternalUrlHolder implementation
 
 nsDOMFileInternalUrlHolder::nsDOMFileInternalUrlHolder(nsIDOMBlob* aFile,
                                                        nsIPrincipal* aPrincipal
-                                                       MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL) {
-  MOZILLA_GUARD_OBJECT_NOTIFIER_INIT;
+                                                       MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL) {
+  MOZ_GUARD_OBJECT_NOTIFIER_INIT;
   aFile->GetInternalUrl(aPrincipal, mUrl);
 }
  
 nsDOMFileInternalUrlHolder::~nsDOMFileInternalUrlHolder() {
   if (!mUrl.IsEmpty()) {
     nsCAutoString narrowUrl;
     CopyUTF16toUTF8(mUrl, narrowUrl);
     nsFileDataProtocolHandler::RemoveFileDataEntry(narrowUrl);
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -737,22 +737,22 @@ AllDescendantsOfType(nsIDocShellTreeItem
 
 /**
  * A class that automatically sets mInShow to false when it goes
  * out of scope.
  */
 class NS_STACK_CLASS AutoResetInShow {
   private:
     nsFrameLoader* mFrameLoader;
-    MOZILLA_DECL_USE_GUARD_OBJECT_NOTIFIER
+    MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
   public:
-    AutoResetInShow(nsFrameLoader* aFrameLoader MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM)
+    AutoResetInShow(nsFrameLoader* aFrameLoader MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
       : mFrameLoader(aFrameLoader)
     {
-      MOZILLA_GUARD_OBJECT_NOTIFIER_INIT;
+      MOZ_GUARD_OBJECT_NOTIFIER_INIT;
     }
     ~AutoResetInShow() { mFrameLoader->mInShow = false; }
 };
 
 
 bool
 nsFrameLoader::Show(PRInt32 marginWidth, PRInt32 marginHeight,
                     PRInt32 scrollbarPrefX, PRInt32 scrollbarPrefY,
--- a/content/base/src/nsRange.cpp
+++ b/content/base/src/nsRange.cpp
@@ -492,31 +492,31 @@ nsRange::CharacterDataChanged(nsIDocumen
     }
   }
 
   // Do the same thing for the end boundary, except for splitText of a node
   // with no parent then only switch to the new node if the start boundary
   // did so too (otherwise the range would end up with disconnected nodes).
   if (aContent == mEndParent &&
       aInfo->mChangeStart < static_cast<PRUint32>(mEndOffset)) {
-    if (aInfo->mDetails && (aContent->GetParent() || newStartNode)) {
+    if (aInfo->mDetails && (aContent->GetNodeParent() || newStartNode)) {
       // splitText(), aInfo->mDetails->mNextSibling is the new text node
       NS_ASSERTION(aInfo->mDetails->mType ==
                    CharacterDataChangeInfo::Details::eSplit,
                    "only a split can start before the end");
       NS_ASSERTION(static_cast<PRUint32>(mEndOffset) <= aInfo->mChangeEnd + 1,
                    "mEndOffset is beyond the end of this node");
       newEndOffset = static_cast<PRUint32>(mEndOffset) - aInfo->mChangeStart;
       newEndNode = aInfo->mDetails->mNextSibling;
 
       bool isCommonAncestor = IsInSelection() && mStartParent == mEndParent;
       if (isCommonAncestor && !newStartNode) {
         // The split occurs inside the range.
         UnregisterCommonAncestor(mStartParent);
-        RegisterCommonAncestor(mStartParent->GetParent());
+        RegisterCommonAncestor(mStartParent->GetNodeParent());
         newEndNode->SetDescendantOfCommonAncestorForRangeInSelection();
       } else if (mEndParent->IsDescendantOfCommonAncestorForRangeInSelection()) {
         newEndNode->SetDescendantOfCommonAncestorForRangeInSelection();
       }
     } else {
       mEndOffset = static_cast<PRUint32>(mEndOffset) <= aInfo->mChangeEnd ?
         aInfo->mChangeStart :
         mEndOffset + aInfo->mChangeStart - aInfo->mChangeEnd +
@@ -550,17 +550,17 @@ nsRange::CharacterDataChanged(nsIDocumen
       newStartOffset = mStartOffset;
     }
     if (!newEndNode) {
       newEndNode = mEndParent;
       newEndOffset = mEndOffset;
     }
     DoSetRange(newStartNode, newStartOffset, newEndNode, newEndOffset,
                newRoot ? newRoot : mRoot.get(),
-               !newEndNode->GetParent() || !newStartNode->GetParent());
+               !newEndNode->GetNodeParent() || !newStartNode->GetNodeParent());
   }
 }
 
 void
 nsRange::ContentAppended(nsIDocument* aDocument,
                          nsIContent*  aContainer,
                          nsIContent*  aFirstNewContent,
                          PRInt32      aNewIndexInContainer)
new file mode 100644
--- /dev/null
+++ b/content/canvas/test/webgl/conformance/glsl/matrices/00_test_list.txt
@@ -0,0 +1,2 @@
+glsl-mat4-to-mat3.html
+
new file mode 100644
--- /dev/null
+++ b/content/canvas/test/webgl/conformance/glsl/matrices/glsl-mat4-to-mat3.html
@@ -0,0 +1,70 @@
+<!--
+Copyright (c) 2011 The Chromium Authors. All rights reserved.
+Use of this source code is governed by a BSD-style license that can be
+found in the LICENSE file.
+ -->
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+  <title>GLSL mat4 to mat3 test</title>
+  <link rel="stylesheet" href="../../../resources/js-test-style.css"/>
+  <link rel="stylesheet" href="../../resources/glsl-feature-tests.css"/>
+  <script src="../../../resources/js-test-pre.js"></script>
+  <script src="../../resources/webgl-test.js"> </script>
+  <script src="../../resources/webgl-test-utils.js"> </script>
+  <script src="../../resources/glsl-generator.js"> </script>
+</head>
+<body>
+<div id="description"></div>
+<div id="console"></div>
+<script id="shader_emu" type="something-not-js">
+mat3 mat3_emu(mat4 m4) {
+  return mat3(
+      m4[0][0], m4[0][1], m4[0][2],
+      m4[1][0], m4[1][1], m4[1][2],
+      m4[2][0], m4[2][1], m4[2][2]);
+}
+</script>
+<script id="shader_test" type="something-not-js">
+  mat4 m4 = mat4($(input), $(input).yzwx, $(input).zwxy, $(input).wxyz);
+  mat3 m3 = $(conversion)(m4);
+  vec3 c;
+  if ($(input).y < 0.33) {
+    c = m3[0];
+  } else if ($(input).y > 0.66) {
+    c = m3[1];
+  } else {
+    c = m3[2];
+  }
+  $(output) = vec4(c, 1);
+</script>
+<script>
+// See resources glsl-generator runBasicTest for how this works
+var wtu = WebGLTestUtils;
+GLSLGenerator.runBasicTest({
+  gridRes: 8,
+  tests: [
+    {
+      name: "mat4 to mat3",
+      reference: {
+        shader: wtu.getScript("shader_test"),
+        subs: {
+          emu: wtu.getScript("shader_emu"),
+          conversion: "mat3_emu"
+        }
+      },
+      test: {
+        shader: wtu.getScript("shader_test"),
+        subs: {
+          conversion: "mat3"
+        },
+      }
+    }
+  ]
+});
+successfullyParsed = true;
+</script>
+</body>
+</html>
+
--- a/content/canvas/test/webgl/conformance/misc/00_test_list.txt
+++ b/content/canvas/test/webgl/conformance/misc/00_test_list.txt
@@ -1,11 +1,11 @@
 bad-arguments-test.html
 error-reporting.html
 instanceof-test.html
 invalid-passed-params.html
 is-object.html
 null-object-behaviour.html
 object-deletion-behaviour.html
-#shader-precision-format.html
+shader-precision-format.html
 type-conversion-test.html
 uninitialized-test.html
 webgl-specific.html
new file mode 100644
--- /dev/null
+++ b/content/canvas/test/webgl/conformance/misc/shader-precision-format.html
@@ -0,0 +1,83 @@
+<!--
+Copyright (c) 2011 Mozilla Foundation. All rights reserved.
+Use of this source code is governed by a BSD-style license that can be
+found in the LICENSE file.
+ -->
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>WebGL shader precision format test.</title>
+<link rel="stylesheet" href="../../resources/js-test-style.css"/>
+<script src="../../resources/js-test-pre.js"></script>
+<script src="../resources/webgl-test.js"> </script>
+<script src="../resources/webgl-test-utils.js"> </script>
+</head>
+<body>
+<canvas id="canvas" width="2" height="2" style="width: 40px; height: 40px;"></canvas>
+<div id="description"></div>
+<div id="console"></div>
+<script>
+var wtu = WebGLTestUtils;
+description(document.title);
+debug("Tests that WebGLShaderPrecisionFormat class and getShaderPrecisionFormat work.");
+debug("");
+var gl = create3DContext(document.getElementById("canvas"));
+
+function verifyShaderPrecisionFormat(shadertype, precisiontype) {
+    shouldBeTrue('gl.getShaderPrecisionFormat(' + shadertype + ', ' +
+                 precisiontype + ') instanceof WebGLShaderPrecisionFormat');
+}
+
+if (gl.getShaderPrecisionFormat == null || typeof gl.getShaderPrecisionFormat != 'function') {
+    debug("getShaderPrecisionFormat() function not found.");
+} else {
+    debug("");
+    debug("Test that getShaderPrecisionFormat returns a WebGLShaderPrecisionFormat object.");
+    debug("");
+
+    verifyShaderPrecisionFormat('gl.VERTEX_SHADER', 'gl.LOW_FLOAT');
+    verifyShaderPrecisionFormat('gl.VERTEX_SHADER', 'gl.MEDIUM_FLOAT');
+    verifyShaderPrecisionFormat('gl.VERTEX_SHADER', 'gl.HIGH_FLOAT');
+    verifyShaderPrecisionFormat('gl.VERTEX_SHADER', 'gl.LOW_INT');
+    verifyShaderPrecisionFormat('gl.VERTEX_SHADER', 'gl.MEDIUM_INT');
+    verifyShaderPrecisionFormat('gl.VERTEX_SHADER', 'gl.HIGH_INT');
+    verifyShaderPrecisionFormat('gl.FRAGMENT_SHADER', 'gl.LOW_FLOAT');
+    verifyShaderPrecisionFormat('gl.FRAGMENT_SHADER', 'gl.MEDIUM_FLOAT');
+    verifyShaderPrecisionFormat('gl.FRAGMENT_SHADER', 'gl.HIGH_FLOAT');
+    verifyShaderPrecisionFormat('gl.FRAGMENT_SHADER', 'gl.LOW_INT');
+    verifyShaderPrecisionFormat('gl.FRAGMENT_SHADER', 'gl.MEDIUM_INT');
+    verifyShaderPrecisionFormat('gl.FRAGMENT_SHADER', 'gl.HIGH_INT');
+
+    debug("");
+    debug("Test that getShaderPrecisionFormat throws an error with invalid parameters.");
+    debug("");
+
+    shouldGenerateGLError(gl, gl.INVALID_ENUM, 'gl.getShaderPrecisionFormat(gl.HIGH_INT, gl.VERTEX_SHADER)');
+
+    debug("");
+    debug("Test that WebGLShaderPrecisionFormat values are sensible.");
+    debug("");
+
+    var shaderPrecisionFormat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT);
+    shouldBeTrue('shaderPrecisionFormat.rangeMin >= 0 && shaderPrecisionFormat.rangeMin <= 128');
+    shouldBeTrue('shaderPrecisionFormat.rangeMax >= 0 && shaderPrecisionFormat.rangeMax <= 128');
+    shouldBeTrue('shaderPrecisionFormat.precision >= 0 && shaderPrecisionFormat.precision <= 128');
+
+    debug("");
+    debug("Test that getShaderPrecisionFormat returns the same thing every call.");
+    debug("");
+
+    var shaderPrecisionFormat2 = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT);
+    shouldBeTrue('shaderPrecisionFormat.rangeMin == shaderPrecisionFormat2.rangeMin');
+    shouldBeTrue('shaderPrecisionFormat.rangeMax == shaderPrecisionFormat2.rangeMax');
+    shouldBeTrue('shaderPrecisionFormat.precision == shaderPrecisionFormat2.precision');
+}
+
+finishTest();
+</script>
+
+</body>
+</html>
+
+
--- a/content/canvas/test/webgl/test_webgl_conformance_test_suite.html
+++ b/content/canvas/test/webgl/test_webgl_conformance_test_suite.html
@@ -45,17 +45,17 @@ function start() {
     kIsWindows = true;
   else if (navigator.platform.indexOf("Linux") == 0)
     kIsLinux = true;
   else if (navigator.platform.indexOf("Mac") == 0)
     kIsMac = true;
 
   var kIsWindowsVistaOrHigher = false;
   if (kIsWindows) {
-    // code borrowed from browser/components/wintaskbar/test/browser_taskbar_preview.js
+    // code borrowed from browser/modules/test/browser_taskbar_preview.js
     netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     var version = Components.classes["@mozilla.org/system-info;1"]
                             .getService(Components.interfaces.nsIPropertyBag2)
                             .getProperty("version");
     kIsWindowsVistaOrHigher = (parseFloat(version) >= 6.0);
   }
 
   function getEnv(env) {
@@ -318,17 +318,17 @@ function start() {
 
   SimpleTest.waitForExplicitFinish();
   SimpleTest.requestLongerTimeout(3);
 
   // we currently disable this test on version of Mac OSX older than 10.6,
   // due to various weird failures, including one making getRenderbufferParameter tests
   // on DEPTH_STENCIL fail
   if (kIsMac) {
-    // code borrowed from browser/components/wintaskbar/test/browser_taskbar_preview.js
+    // code borrowed from browser/modules/test/browser_taskbar_preview.js
     var is106orHigher = false;
     netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     var version = Components.classes["@mozilla.org/system-info;1"]
                             .getService(Components.interfaces.nsIPropertyBag2)
                             .getProperty("version");
     // the next line is correct: Mac OS 10.6 corresponds to Darwin version 10 !
     // Mac OS 10.5 would be Darwin version 9. the |version| string we've got here
     // is the Darwin version.
--- a/content/events/src/nsContentEventHandler.cpp
+++ b/content/events/src/nsContentEventHandler.cpp
@@ -805,17 +805,17 @@ nsContentEventHandler::OnQueryCharacterA
   NS_ENSURE_TRUE(rootWidget, NS_ERROR_FAILURE);
 
   // The root frame's widget might be different, e.g., the event was fired on
   // a popup but the rootFrame is the document root.
   if (rootWidget != aEvent->widget) {
     NS_PRECONDITION(aEvent->widget, "The event must have the widget");
     nsIView* view = nsIView::GetViewFor(aEvent->widget);
     NS_ENSURE_TRUE(view, NS_ERROR_FAILURE);
-    rootFrame = nsLayoutUtils::GetFrameFor(view);
+    rootFrame = view->GetFrame();
     NS_ENSURE_TRUE(rootFrame, NS_ERROR_FAILURE);
     rootWidget = rootFrame->GetNearestWidget();
     NS_ENSURE_TRUE(rootWidget, NS_ERROR_FAILURE);
   }
 
   nsQueryContentEvent eventOnRoot(true, NS_QUERY_CHARACTER_AT_POINT,
                                   rootWidget);
   eventOnRoot.refPoint = aEvent->refPoint;
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -1141,16 +1141,19 @@ nsEventStateManager::PreHandleEvent(nsPr
     // has completed and so |aTargetFrame| may have been deleted (moving
     // a bookmark, for example).  If this is the case, however, we know
     // that ClearFrameRefs() has been called and it cleared out
     // |mCurrentTarget|. As a result, we should pass |mCurrentTarget|
     // into UpdateCursor().
     GenerateDragGesture(aPresContext, (nsMouseEvent*)aEvent);
     UpdateCursor(aPresContext, aEvent, mCurrentTarget, aStatus);
     GenerateMouseEnterExit((nsGUIEvent*)aEvent);
+    // Flush pending layout changes, so that later mouse move events
+    // will go to the right nodes.
+    FlushPendingEvents(aPresContext);
     break;
   case NS_DRAGDROP_GESTURE:
     if (mClickHoldContextMenu) {
       // an external drag gesture event came in, not generated internally
       // by Gecko. Make sure we get rid of the click-hold timer.
       KillClickHoldTimer();
     }
     break;
--- a/content/events/test/Makefile.in
+++ b/content/events/test/Makefile.in
@@ -108,16 +108,17 @@ include $(topsrcdir)/config/rules.mk
 		test_bug662678.html \
 		test_bug667919-1.html \
 		test_bug667919-2.html \
 		test_bug667612.html \
 		empty.js \
 		test_bug689564.html \
 		test_bug698929.html \
 		test_eventctors.html \
+		test_bug635465.html \
 		$(NULL)
 
 #bug 585630
 ifneq (mobile,$(MOZ_BUILD_APP))
 _TEST_FILES += \
 		test_dragstart.html \
 		$(NULL)
 endif
new file mode 100644
--- /dev/null
+++ b/content/events/test/test_bug635465.html
@@ -0,0 +1,90 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=635465
+-->
+<head>
+  <meta charset="utf-8">
+  <title>Test for Bug 635465</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <style type="text/css">
+      #item {
+        position: relative;
+      }
+      .s-menu-section-submenu {
+        position: absolute;
+        display: none;
+      }
+      .open .s-menu-section-submenu {
+        display: block;
+      }
+</style>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=635465">Mozilla Bug 635465</a>
+<div id="display">
+  <div class="item" id="item"
+       onmouseover="showSubmenu(event)" onmouseout="hideSubmenu(event)">
+    <a href="#" id="firsthover">Hover me</a>
+    <div class="s-menu-section-submenu" id="menu">
+      <a href="#" id="secondhover">Now hover me</a>
+    </div>
+  </div>
+</div>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script type="application/javascript;version=1.8">
+
+/** Test for Bug 635465 **/
+function showSubmenu(event) {
+  var item = document.getElementById('item');
+
+  var width = item.offsetWidth;   // IT WORKS IF YOU REMOVE THIS LINE
+  
+  item.className='open';
+}
+
+function hideSubmenu(event) {
+  document.getElementById('item').className='';
+}
+
+SimpleTest.waitForExplicitFinish();
+
+function executeTests() {
+  // First flush out layout of firsthover
+  ok($("firsthover").getBoundingClientRect().height > 0, true,
+     "Should have a nonzero height before hover");
+
+  // Now trigger a mouseover on firsthover
+  synthesizeMouseAtCenter($("firsthover"), { type: "mousemove" });
+
+  ok($("secondhover").getBoundingClientRect().height > 0, true,
+     "Should have a nonzero height for submenu after hover");
+
+  // Now determine where secondhover is hanging out
+  var rect = $("secondhover").getBoundingClientRect();
+  synthesizeMouseAtCenter($("secondhover"), { type: "mousemove" });
+
+  // And another mouseover one pixel to the right of where the center used to be
+  synthesizeMouseAtPoint(rect.left + rect.width/2 + 1,
+                         rect.top + rect.height/2,
+                         { type: "mousemove" });
+
+  ok($("secondhover").getBoundingClientRect().height > 0, true,
+     "Should have a nonzero height for submenu after second hover");
+
+  // And check computed display of the menu
+  is(getComputedStyle($("menu"), "").display, "block", "Should have block display");
+
+  SimpleTest.finish();
+}
+
+SimpleTest.waitForFocus(executeTests);
+</script>
+</pre>
+</body>
+</html>
--- a/content/events/test/test_eventctors.html
+++ b/content/events/test/test_eventctors.html
@@ -386,14 +386,12 @@ while (testProps.length) {
     if (!(def in p)) {
       is(e[def], defaultMouseEventValues[def], "Wrong default value for " + def + "!");
     } else {
       is(e[def], p[def], "Wrong event init value for " + def + "!");
     }
   }
 }
 
-SimpleTest.finish();
-
 </script>
 </pre>
 </body>
 </html>
--- a/content/html/content/src/Makefile.in
+++ b/content/html/content/src/Makefile.in
@@ -40,16 +40,17 @@ topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= content
 LIBRARY_NAME	= gkconhtmlcon_s
 LIBXUL_LIBRARY	= 1
+FAIL_ON_WARNINGS = 1
 
 
 EXPORTS		= \
 		nsClientRect.h \
 		nsHTMLDNSPrefetch.h \
 		$(NULL)
 
 CPPSRCS		= \
--- a/content/html/content/src/nsHTMLMenuItemElement.h
+++ b/content/html/content/src/nsHTMLMenuItemElement.h
@@ -38,16 +38,18 @@
 #include "nsGenericHTMLElement.h"
 
 class Visitor;
 
 class nsHTMLMenuItemElement : public nsGenericHTMLElement,
                               public nsIDOMHTMLMenuItemElement
 {
 public:
+  using nsGenericElement::GetText;
+
   nsHTMLMenuItemElement(already_AddRefed<nsINodeInfo> aNodeInfo,
                         mozilla::dom::FromParser aFromParser);
   virtual ~nsHTMLMenuItemElement();
 
   /** Typesafe, non-refcounting cast from nsIContent.  Cheaper than QI. **/
   static nsHTMLMenuItemElement* FromContent(nsIContent* aContent)
   {
     if (aContent && aContent->IsHTML(nsGkAtoms::menuitem)) {
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -43,17 +43,16 @@
 #include "nsICharsetAlias.h"
 
 #include "nsCOMPtr.h"
 #include "nsXPIDLString.h"
 #include "nsPrintfCString.h"
 #include "nsReadableUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsHTMLDocument.h"
-#include "nsIParserFilter.h"
 #include "nsIHTMLContentSink.h"
 #include "nsIXMLContentSink.h"
 #include "nsHTMLParts.h"
 #include "nsHTMLStyleSheet.h"
 #include "nsGkAtoms.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIDOMNode.h" // for Find
@@ -98,19 +97,16 @@
 #include "nsGenericHTMLElement.h"
 #include "mozilla/css/Loader.h"
 #include "nsIHttpChannel.h"
 #include "nsIFile.h"
 #include "nsEventListenerManager.h"
 #include "nsFrameSelection.h"
 #include "nsISelectionPrivate.h"//for toStringwithformat code
 
-#include "nsICharsetDetector.h"
-#include "nsICharsetDetectionAdaptor.h"
-#include "nsCharsetDetectionAdaptorCID.h"
 #include "nsICharsetAlias.h"
 #include "nsContentUtils.h"
 #include "nsJSUtils.h"
 #include "nsIDocumentCharsetInfo.h"
 #include "nsIDocumentEncoder.h" //for outputting selection
 #include "nsICachingChannel.h"
 #include "nsIJSContextStack.h"
 #include "nsIContentViewer.h"
@@ -142,21 +138,16 @@
 #include "mozilla/Preferences.h"
 #include "nsMimeTypes.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 #define NS_MAX_DOCUMENT_WRITE_DEPTH 20
 
-#define DETECTOR_CONTRACTID_MAX 127
-static char g_detector_contractid[DETECTOR_CONTRACTID_MAX + 1];
-static bool gInitDetector = false;
-static bool gPlugDetector = false;
-
 #include "prmem.h"
 #include "prtime.h"
 
 // Find/Search Includes
 const PRInt32 kForward  = 0;
 const PRInt32 kBackward = 1;
 
 //#define DEBUG_charset
@@ -177,35 +168,16 @@ static bool ConvertToMidasInternalComman
                                             const nsAString & inParam,
                                             nsACString& outCommandID,
                                             nsACString& outParam,
                                             bool& isBoolean,
                                             bool& boolValue);
 
 static bool ConvertToMidasInternalCommand(const nsAString & inCommandID,
                                             nsACString& outCommandID);
-static int
-MyPrefChangedCallback(const char*aPrefName, void* instance_data)
-{
-  const nsAdoptingCString& detector_name =
-    Preferences::GetLocalizedCString("intl.charset.detector");
-
-  if (!detector_name.IsEmpty()) {
-    PL_strncpy(g_detector_contractid, NS_CHARSET_DETECTOR_CONTRACTID_BASE,
-               DETECTOR_CONTRACTID_MAX);
-    PL_strncat(g_detector_contractid, detector_name,
-               DETECTOR_CONTRACTID_MAX);
-    gPlugDetector = true;
-  } else {
-    g_detector_contractid[0]=0;
-    gPlugDetector = false;
-  }
-
-  return 0;
-}
 
 // ==================================================================
 // =
 // ==================================================================
 static void
 ReportUseOfDeprecatedMethod(nsHTMLDocument* aDoc, const char* aWarning)
 {
   nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
@@ -564,75 +536,16 @@ nsHTMLDocument::TryDefaultCharset( nsIMa
       aCharsetSource = kCharsetFromUserDefault;
       return true;
     }
   }
   return false;
 }
 
 void
-nsHTMLDocument::StartAutodetection(nsIDocShell *aDocShell, nsACString& aCharset,
-                                   const char* aCommand)
-{
-  if (mIsRegularHTML && 
-      nsHtml5Module::sEnabled && 
-      aCommand && 
-      (!nsCRT::strcmp(aCommand, "view") ||
-       !nsCRT::strcmp(aCommand, "view-source"))) {
-    return; // the HTML5 parser uses chardet directly
-  }
-  nsCOMPtr <nsIParserFilter> cdetflt;
-
-  nsresult rv_detect;
-  if(!gInitDetector) {
-    const nsAdoptingCString& detector_name =
-      Preferences::GetLocalizedCString("intl.charset.detector");
-
-    if(!detector_name.IsEmpty()) {
-      PL_strncpy(g_detector_contractid, NS_CHARSET_DETECTOR_CONTRACTID_BASE,
-                 DETECTOR_CONTRACTID_MAX);
-      PL_strncat(g_detector_contractid, detector_name,
-                 DETECTOR_CONTRACTID_MAX);
-      gPlugDetector = true;
-    }
-
-    Preferences::RegisterCallback(MyPrefChangedCallback,
-                                  "intl.charset.detector");
-
-    gInitDetector = true;
-  }
-
-  if (gPlugDetector) {
-    nsCOMPtr <nsICharsetDetector> cdet =
-      do_CreateInstance(g_detector_contractid, &rv_detect);
-    if (NS_SUCCEEDED(rv_detect)) {
-      cdetflt = do_CreateInstance(NS_CHARSET_DETECTION_ADAPTOR_CONTRACTID,
-                                  &rv_detect);
-
-      nsCOMPtr<nsICharsetDetectionAdaptor> adp = do_QueryInterface(cdetflt);
-      if (adp) {
-        nsCOMPtr<nsIWebShellServices> wss = do_QueryInterface(aDocShell);
-        if (wss) {
-          rv_detect = adp->Init(wss, cdet, this, mParser,
-                                PromiseFlatCString(aCharset).get(), aCommand);
-
-          if (mParser)
-            mParser->SetParserFilter(cdetflt);
-        }
-      }
-    }
-    else {
-      // IF we cannot create the detector, don't bother to
-      // create one next time.
-      gPlugDetector = false;
-    }
-  }
-}
-
-void
 nsHTMLDocument::SetDocumentCharacterSet(const nsACString& aCharSetID)
 {
   nsDocument::SetDocumentCharacterSet(aCharSetID);
   // Make sure to stash this charset on our channel as needed if it's a wyciwyg
   // channel.
   nsCOMPtr<nsIWyciwygChannel> wyciwygChannel = do_QueryInterface(mChannel);
   if (wyciwygChannel) {
     wyciwygChannel->SetCharsetAndSource(GetDocumentCharacterSetSource(),
@@ -907,23 +820,18 @@ nsHTMLDocument::StartDocumentLoad(const 
         rv = NS_OK;
       }
       
     } else {
       parserCharset = charset;
       parserCharsetSource = charsetSource;
     }
 
-    if(kCharsetFromAutoDetection > charsetSource && !isPostPage) {
-      StartAutodetection(docShell, charset, aCommand);
-    }
-
     // ahmed
     // Check if 864 but in Implicit mode !
-    // XXXbz why is this happening after StartAutodetection ?
     if ((textType == IBMBIDI_TEXTTYPE_LOGICAL) &&
         (charset.LowerCaseEqualsLiteral("ibm864"))) {
       charset.AssignLiteral("IBM864i");
     }
   }
 
   SetDocumentCharacterSetSource(charsetSource);
   SetDocumentCharacterSet(charset);
--- a/content/html/document/src/nsHTMLDocument.h
+++ b/content/html/document/src/nsHTMLDocument.h
@@ -267,19 +267,16 @@ protected:
                           nsIDocument* aParentDocument,
                           PRInt32& charsetSource, nsACString& aCharset);
   static bool UseWeakDocTypeDefault(PRInt32& aCharsetSource,
                                       nsACString& aCharset);
   static bool TryDefaultCharset(nsIMarkupDocumentViewer* aMarkupDV,
                                   PRInt32& aCharsetSource,
                                   nsACString& aCharset);
 
-  void StartAutodetection(nsIDocShell *aDocShell, nsACString& aCharset,
-                          const char* aCommand);
-
   // Override so we can munge the charset on our wyciwyg channel as needed.
   virtual void SetDocumentCharacterSet(const nsACString& aCharSetID);
 
   // mWriteState tracks the status of this document if the document is being
   // entirely created by script. In the normal load case, mWriteState will be
   // eNotWriting. Once document.open has been called (either implicitly or
   // explicitly), mWriteState will be eDocumentOpened. When document.close has
   // been called, mWriteState will become eDocumentClosed if there have been no
--- a/db/sqlite3/src/Makefile.in
+++ b/db/sqlite3/src/Makefile.in
@@ -73,19 +73,19 @@ sqlite-version.h: sqlite-version.py sqli
 	@$(PYTHON) $(topsrcdir)/config/Preprocessor.py $(DEFINES) \
 	  $(srcdir)/sqlite.def > $(DEFFILE)
 
 export:: sqlite-version.h
 endif
 endif
 
 ifeq (Darwin,$(OS_TARGET))
-# On OSX, with jemalloc enabled, having sqlite linked against mozutils
+# On OSX, with jemalloc enabled, having sqlite linked against mozglue
 # causes crashes in NSS standalone tools.
-MOZ_UTILS_LDFLAGS =
+MOZ_GLUE_LDFLAGS =
 endif
 
 # XXX Force -O2 optimisation on Mac because using the default -O3 causes
 # crashes. See bug 676499.
 ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 MODULE_OPTIMIZE_FLAGS = -O2
 endif
 
--- a/dom/Makefile.in
+++ b/dom/Makefile.in
@@ -78,22 +78,22 @@ DIRS += \
   plugins/base \
   plugins/ipc \
   indexedDB \
   system \
   ipc \
   workers \
   $(NULL)
 
-ifdef MOZ_B2G_RIL #{
+ifdef MOZ_B2G_RIL
 DIRS += \
   telephony \
   wifi \
   $(NULL)
-endif #}
+endif
 
 ifdef ENABLE_TESTS
 DIRS += tests
 ifneq (,$(filter gtk2 cocoa windows android qt os2,$(MOZ_WIDGET_TOOLKIT)))
 DIRS += plugins/test
 endif
 endif
 
--- a/dom/base/Makefile.in
+++ b/dom/base/Makefile.in
@@ -132,16 +132,20 @@ CPPSRCS =			\
 	$(NULL)
 
 include $(topsrcdir)/dom/dom-config.mk
 
 ifdef MOZ_JSDEBUGGER
 DEFINES += -DMOZ_JSDEBUGGER
 endif
 
+ifdef MOZ_B2G_RIL
+DEFINES += -DMOZ_B2G_RIL
+endif
+
 include $(topsrcdir)/config/config.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
 
 include $(topsrcdir)/config/rules.mk
 
 LOCAL_INCLUDES += \
 		-I$(topsrcdir)/js/xpconnect/src \
 		-I$(topsrcdir)/js/xpconnect/wrappers \
--- a/dom/base/Navigator.cpp
+++ b/dom/base/Navigator.cpp
@@ -70,16 +70,20 @@
 #include "mozilla/Telemetry.h"
 #include "BatteryManager.h"
 #include "SmsManager.h"
 #include "nsISmsService.h"
 #include "mozilla/Hal.h"
 #include "nsIWebNavigation.h"
 #include "mozilla/ClearOnShutdown.h"
 
+#ifdef MOZ_B2G_RIL
+#include "TelephonyFactory.h"
+#endif
+
 // This should not be in the namespace.
 DOMCI_DATA(Navigator, mozilla::dom::Navigator)
 
 namespace mozilla {
 namespace dom {
 
 static const char sJSStackContractID[] = "@mozilla.org/js/xpc/ContextStack;1";
 
@@ -118,16 +122,19 @@ Navigator::~Navigator()
 NS_INTERFACE_MAP_BEGIN(Navigator)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMNavigator)
   NS_INTERFACE_MAP_ENTRY(nsIDOMNavigator)
   NS_INTERFACE_MAP_ENTRY(nsIDOMClientInformation)
   NS_INTERFACE_MAP_ENTRY(nsIDOMNavigatorGeolocation)
   NS_INTERFACE_MAP_ENTRY(nsIDOMMozNavigatorBattery)
   NS_INTERFACE_MAP_ENTRY(nsIDOMNavigatorDesktopNotification)
   NS_INTERFACE_MAP_ENTRY(nsIDOMMozNavigatorSms)
+#ifdef MOZ_B2G_RIL
+  NS_INTERFACE_MAP_ENTRY(nsIDOMNavigatorTelephony)
+#endif
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(Navigator)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_ADDREF(Navigator)
 NS_IMPL_RELEASE(Navigator)
 
 void
 Navigator::Invalidate()
@@ -154,16 +161,22 @@ Navigator::Invalidate()
     mBatteryManager->Shutdown();
     mBatteryManager = nsnull;
   }
 
   if (mSmsManager) {
     mSmsManager->Shutdown();
     mSmsManager = nsnull;
   }
+
+#ifdef MOZ_B2G_RIL
+  if (mTelephony) {
+    mTelephony = nsnull;
+  }
+#endif
 }
 
 nsPIDOMWindow *
 Navigator::GetWindow()
 {
   nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mWindow));
 
   return win;
@@ -1013,16 +1026,44 @@ Navigator::GetMozSms(nsIDOMMozSmsManager
     mSmsManager->Init(window, scx);
   }
 
   NS_ADDREF(*aSmsManager = mSmsManager);
 
   return NS_OK;
 }
 
+#ifdef MOZ_B2G_RIL
+
+//*****************************************************************************
+//    nsNavigator::nsIDOMNavigatorTelephony
+//*****************************************************************************
+
+NS_IMETHODIMP
+Navigator::GetMozTelephony(nsIDOMTelephony** aTelephony)
+{
+  nsCOMPtr<nsIDOMTelephony> telephony = mTelephony;
+
+  if (!telephony) {
+    nsCOMPtr<nsPIDOMWindow> window = do_QueryReferent(mWindow);
+    NS_ENSURE_TRUE(window, NS_ERROR_FAILURE);
+
+    nsresult rv = NS_NewTelephony(window, getter_AddRefs(mTelephony));
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    // mTelephony may be null here!
+    telephony = mTelephony;
+  }
+
+  telephony.forget(aTelephony);
+  return NS_OK;
+}
+
+#endif // MOZ_B2G_RIL
+
 PRInt64
 Navigator::SizeOf() const
 {
   PRInt64 size = sizeof(*this);
 
   // TODO: add SizeOf() to nsMimeTypeArray, bug 674113.
   size += mMimeTypes ? sizeof(*mMimeTypes.get()) : 0;
   // TODO: add SizeOf() to nsPluginArray, bug 674114.
--- a/dom/base/Navigator.h
+++ b/dom/base/Navigator.h
@@ -53,16 +53,21 @@
 #include "nsWeakReference.h"
 
 class nsPluginArray;
 class nsMimeTypeArray;
 class nsGeolocation;
 class nsDesktopNotificationCenter;
 class nsPIDOMWindow;
 
+#ifdef MOZ_B2G_RIL
+#include "nsIDOMNavigatorTelephony.h"
+class nsIDOMTelephony;
+#endif
+
 //*****************************************************************************
 // Navigator: Script "navigator" object
 //*****************************************************************************
 
 namespace mozilla {
 namespace dom {
 
 namespace battery {
@@ -74,29 +79,36 @@ class SmsManager;
 } // namespace sms
 
 class Navigator : public nsIDOMNavigator,
                   public nsIDOMClientInformation,
                   public nsIDOMNavigatorGeolocation,
                   public nsIDOMNavigatorDesktopNotification,
                   public nsIDOMMozNavigatorBattery,
                   public nsIDOMMozNavigatorSms
+#ifdef MOZ_B2G_RIL
+                , public nsIDOMNavigatorTelephony
+#endif
 {
 public:
   Navigator(nsPIDOMWindow *aInnerWindow);
   virtual ~Navigator();
 
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMNAVIGATOR
   NS_DECL_NSIDOMCLIENTINFORMATION
   NS_DECL_NSIDOMNAVIGATORGEOLOCATION
   NS_DECL_NSIDOMNAVIGATORDESKTOPNOTIFICATION
   NS_DECL_NSIDOMMOZNAVIGATORBATTERY
   NS_DECL_NSIDOMMOZNAVIGATORSMS
 
+#ifdef MOZ_B2G_RIL
+  NS_DECL_NSIDOMNAVIGATORTELEPHONY
+#endif
+
   static void Init();
 
   void Invalidate();
   nsPIDOMWindow *GetWindow();
 
   void RefreshMIMEArray();
 
   static bool HasDesktopNotificationSupport();
@@ -113,16 +125,19 @@ private:
   bool IsSmsSupported() const;
 
   nsRefPtr<nsMimeTypeArray> mMimeTypes;
   nsRefPtr<nsPluginArray> mPlugins;
   nsRefPtr<nsGeolocation> mGeolocation;
   nsRefPtr<nsDesktopNotificationCenter> mNotification;
   nsRefPtr<battery::BatteryManager> mBatteryManager;
   nsRefPtr<sms::SmsManager> mSmsManager;
+#ifdef MOZ_B2G_RIL
+  nsCOMPtr<nsIDOMTelephony> mTelephony;
+#endif
   nsWeakPtr mWindow;
 };
 
 } // namespace dom
 } // namespace mozilla
 
 nsresult NS_GetNavigatorUserAgent(nsAString& aUserAgent);
 nsresult NS_GetNavigatorPlatform(nsAString& aPlatform);
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -511,16 +511,22 @@
 
 #include "nsIDOMBatteryManager.h"
 #include "BatteryManager.h"
 #include "nsIDOMSmsManager.h"
 #include "nsIDOMSmsMessage.h"
 #include "nsIDOMSmsEvent.h"
 #include "nsIPrivateDOMEvent.h"
 
+#ifdef MOZ_B2G_RIL
+#include "Telephony.h"
+#include "TelephonyCall.h"
+#include "CallEvent.h"
+#endif
+
 using namespace mozilla;
 using namespace mozilla::dom;
 
 static NS_DEFINE_CID(kDOMSOF_CID, NS_DOM_SCRIPT_OBJECT_FACTORY_CID);
 
 static const char kDOMStringBundleURL[] =
   "chrome://global/locale/dom/dom.properties";
 
@@ -1548,16 +1554,25 @@ static nsDOMClassInfoData sClassInfoData
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(MozCSSKeyframesRule, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
 
   NS_DEFINE_CLASSINFO_DATA(MediaQueryList, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(CustomEvent, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
+
+#ifdef MOZ_B2G_RIL
+  NS_DEFINE_CLASSINFO_DATA(Telephony, nsEventTargetSH,
+                           EVENTTARGET_SCRIPTABLE_FLAGS)
+  NS_DEFINE_CLASSINFO_DATA(TelephonyCall, nsEventTargetSH,
+                           EVENTTARGET_SCRIPTABLE_FLAGS)
+  NS_DEFINE_CLASSINFO_DATA(CallEvent, nsDOMGenericSH,
+                           DOM_DEFAULT_SCRIPTABLE_FLAGS)
+#endif
 };
 
 // Objects that should be constructable through |new Name();|
 struct nsContractIDMapData
 {
   PRInt32 mDOMClassInfoID;
   const char *mContractID;
 };
@@ -2336,16 +2351,19 @@ nsDOMClassInfo::Init()
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMNavigator)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMNavigatorGeolocation)
     DOM_CLASSINFO_MAP_CONDITIONAL_ENTRY(nsIDOMNavigatorDesktopNotification,
                                         Navigator::HasDesktopNotificationSupport())
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMClientInformation)
     DOM_CLASSINFO_MAP_CONDITIONAL_ENTRY(nsIDOMMozNavigatorBattery,
                                         battery::BatteryManager::HasSupport())
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMMozNavigatorSms)
+#ifdef MOZ_B2G_RIL
+    DOM_CLASSINFO_MAP_ENTRY(nsIDOMNavigatorTelephony)
+#endif
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(Plugin, nsIDOMPlugin)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMPlugin)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(PluginArray, nsIDOMPluginArray)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMPluginArray)
@@ -4240,16 +4258,33 @@ nsDOMClassInfo::Init()
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMMediaQueryList)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(CustomEvent, nsIDOMCustomEvent)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMCustomEvent)
     DOM_CLASSINFO_EVENT_MAP_ENTRIES
   DOM_CLASSINFO_MAP_END
 
+#ifdef MOZ_B2G_RIL
+  DOM_CLASSINFO_MAP_BEGIN(Telephony, nsIDOMTelephony)
+    DOM_CLASSINFO_MAP_ENTRY(nsIDOMTelephony)
+    DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
+  DOM_CLASSINFO_MAP_END
+
+  DOM_CLASSINFO_MAP_BEGIN(TelephonyCall, nsIDOMTelephonyCall)
+    DOM_CLASSINFO_MAP_ENTRY(nsIDOMTelephonyCall)
+    DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
+  DOM_CLASSINFO_MAP_END
+
+  DOM_CLASSINFO_MAP_BEGIN(CallEvent, nsIDOMCallEvent)
+    DOM_CLASSINFO_MAP_ENTRY(nsIDOMCallEvent)
+    DOM_CLASSINFO_MAP_ENTRY(nsIDOMEvent)
+  DOM_CLASSINFO_MAP_END
+#endif
+
 #ifdef NS_DEBUG
   {
     PRUint32 i = ArrayLength(sClassInfoData);
 
     if (i != eDOMClassInfoIDCount) {
       NS_ERROR("The number of items in sClassInfoData doesn't match the "
                "number of nsIDOMClassInfo ID's, this is bad! Fix it!");
 
--- a/dom/base/nsDOMClassInfoClasses.h
+++ b/dom/base/nsDOMClassInfoClasses.h
@@ -521,8 +521,14 @@ DOMCI_CLASS(Touch)
 DOMCI_CLASS(TouchList)
 DOMCI_CLASS(TouchEvent)
 
 DOMCI_CLASS(MozCSSKeyframeRule)
 DOMCI_CLASS(MozCSSKeyframesRule)
 
 DOMCI_CLASS(MediaQueryList)
 DOMCI_CLASS(CustomEvent)
+
+#ifdef MOZ_B2G_RIL
+DOMCI_CLASS(Telephony)
+DOMCI_CLASS(TelephonyCall)
+DOMCI_CLASS(CallEvent)
+#endif
--- a/dom/dom-config.mk
+++ b/dom/dom-config.mk
@@ -2,25 +2,32 @@ DOM_SRCDIRS = \
   dom/base \
   dom/battery \
   dom/sms/src \
   dom/src/events \
   dom/src/storage \
   dom/src/offline \
   dom/src/geolocation \
   dom/src/notification \
-  dom/telephony \
   dom/workers \
   content/xbl/src \
   content/xul/document/src \
   content/events/src \
   content/base/src \
   content/html/content/src \
   content/html/document/src \
   content/svg/content/src \
   layout/generic \
   layout/style \
   layout/xul/base/src \
   layout/xul/base/src/tree/src \
   $(NULL)
 
+ifdef MOZ_B2G_RIL
+DOM_SRCDIRS += \
+  dom/system/b2g \
+  dom/telephony \
+  dom/wifi \
+  $(NULL)
+endif
+
 LOCAL_INCLUDES += $(DOM_SRCDIRS:%=-I$(topsrcdir)/%)
 DEFINES += -D_IMPL_NS_LAYOUT
--- a/dom/sms/src/ril/SmsService.cpp
+++ b/dom/sms/src/ril/SmsService.cpp
@@ -32,30 +32,37 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "mozilla/dom/sms/SmsMessage.h"
 #include "SmsService.h"
-#include "RadioManager.h"
+#include "SystemWorkerManager.h"
 #include "jsapi.h"
+#include "nsIInterfaceRequestorUtils.h"
 
-using mozilla::dom::telephony::RadioManager;
+using mozilla::dom::telephony::SystemWorkerManager;
 
 namespace mozilla {
 namespace dom {
 namespace sms {
 
 NS_IMPL_ISUPPORTS1(SmsService, nsISmsService)
 
 SmsService::SmsService()
-  : mRIL(RadioManager::GetTelephone())
 {
+  nsIInterfaceRequestor* ireq = SystemWorkerManager::GetInterfaceRequestor();
+  NS_WARN_IF_FALSE(ireq, "The SystemWorkerManager has not been created!");
+
+  if (ireq) {
+    mRIL = do_GetInterface(ireq);
+    NS_WARN_IF_FALSE(mRIL, "This shouldn't fail!");
+  }
 }
 
 NS_IMETHODIMP
 SmsService::HasSupport(bool* aHasSupport)
 {
   *aHasSupport = true;
   return NS_OK;
 }
--- a/dom/src/geolocation/nsGeolocation.cpp
+++ b/dom/src/geolocation/nsGeolocation.cpp
@@ -503,46 +503,23 @@ NS_INTERFACE_MAP_BEGIN(nsGeolocationServ
 NS_INTERFACE_MAP_END
 
 NS_IMPL_THREADSAFE_ADDREF(nsGeolocationService)
 NS_IMPL_THREADSAFE_RELEASE(nsGeolocationService)
 
 
 static bool sGeoEnabled = true;
 static bool sGeoIgnoreLocationFilter = false;
-
-static int
-GeoEnabledChangedCallback(const char *aPrefName, void *aClosure)
-{
-  sGeoEnabled = Preferences::GetBool("geo.enabled", true);
-  return 0;
-}
-
-static int
-GeoIgnoreLocationFilterChangedCallback(const char *aPrefName, void *aClosure)
-{
-  sGeoIgnoreLocationFilter =
-    Preferences::GetBool("geo.ignore.location_filter", true);
-  return 0;
-}
-
+static PRInt32 sProviderTimeout = 6000; // Time, in milliseconds, to wait for the location provider to spin up.
 
 nsresult nsGeolocationService::Init()
 {
-  mTimeout = Preferences::GetInt("geo.timeout", 6000);
-
-  Preferences::RegisterCallback(GeoIgnoreLocationFilterChangedCallback,
-                                "geo.ignore.location_filter");
-
-  GeoIgnoreLocationFilterChangedCallback("geo.ignore.location_filter", nsnull);
-
-
-  Preferences::RegisterCallback(GeoEnabledChangedCallback, "geo.enabled");
-
-  GeoEnabledChangedCallback("geo.enabled", nsnull);
+  Preferences::AddIntVarCache(&sProviderTimeout, "geo.timeout", sProviderTimeout);
+  Preferences::AddBoolVarCache(&sGeoEnabled, "geo.enabled", sGeoEnabled);
+  Preferences::AddBoolVarCache(&sGeoIgnoreLocationFilter, "geo.ignore.location_filter", sGeoIgnoreLocationFilter);
 
   if (!sGeoEnabled)
     return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIGeolocationProvider> provider = do_GetService(NS_GEOLOCATION_PROVIDER_CONTRACTID);
   if (provider)
     mProviders.AppendObject(provider);
 
@@ -705,17 +682,17 @@ void
 nsGeolocationService::SetDisconnectTimer()
 {
   if (!mDisconnectTimer)
     mDisconnectTimer = do_CreateInstance("@mozilla.org/timer;1");
   else
     mDisconnectTimer->Cancel();
 
   mDisconnectTimer->Init(this,
-                         mTimeout,
+                         sProviderTimeout,
                          nsITimer::TYPE_ONE_SHOT);
 }
 
 void 
 nsGeolocationService::StopDevice()
 {
   if(mDisconnectTimer) {
     mDisconnectTimer->Cancel();
@@ -876,17 +853,17 @@ nsGeolocation::Shutdown()
 
 bool
 nsGeolocation::HasActiveCallbacks()
 {
   for (PRUint32 i = 0; i < mWatchingCallbacks.Length(); i++)
     if (mWatchingCallbacks[i]->IsActive())
       return true;
 
-  return false;
+  return mPendingCallbacks.Length() != 0;
 }
 
 void
 nsGeolocation::RemoveRequest(nsGeolocationRequest* aRequest)
 {
   mPendingCallbacks.RemoveElement(aRequest);
 
   // if it is in the mWatchingCallbacks, we can't do much
--- a/dom/src/geolocation/nsGeolocation.h
+++ b/dom/src/geolocation/nsGeolocation.h
@@ -129,17 +129,17 @@ public:
   static nsGeolocationService* GetGeolocationService();
   static nsGeolocationService* GetInstance();  // Non-Addref'ing
   static nsGeolocationService* gService;
 
   NS_DECL_ISUPPORTS
   NS_DECL_NSIGEOLOCATIONUPDATE
   NS_DECL_NSIOBSERVER
 
-  nsGeolocationService() {mTimeout = 6000;};
+  nsGeolocationService() {}
 
   nsresult Init();
 
   // Management of the nsGeolocation objects
   void AddLocator(nsGeolocation* locator);
   void RemoveLocator(nsGeolocation* locator);
 
   void SetCachedPosition(nsIDOMGeoPosition* aPosition);
@@ -158,19 +158,16 @@ private:
 
   ~nsGeolocationService();
 
   // Disconnect timer.  When this timer expires, it clears all pending callbacks
   // and closes down the provider, unless we are watching a point, and in that
   // case, we disable the disconnect timer.
   nsCOMPtr<nsITimer> mDisconnectTimer;
 
-  // Time, in milliseconds, to wait for the location provider to spin up.
-  PRInt32 mTimeout;
-
   // The object providing geo location information to us.
   nsCOMArray<nsIGeolocationProvider> mProviders;
 
   // mGeolocators are not owned here.  Their constructor
   // adds them to this list, and their destructor removes
   // them from this list.
   nsTArray<nsGeolocation*> mGeolocators;
 
--- a/dom/system/Makefile.in
+++ b/dom/system/Makefile.in
@@ -56,19 +56,19 @@ endif
 ifneq (,$(filter cocoa,$(MOZ_WIDGET_TOOLKIT)))
 DIRS = cocoa
 endif
 
 ifneq (,$(filter android,$(MOZ_WIDGET_TOOLKIT)))
 DIRS = android
 endif
 
-ifdef MOZ_B2G_RIL #{
+ifdef MOZ_B2G_RIL
 DIRS += b2g
-endif #}
+endif
 
 CPPSRCS     = \
   nsDeviceMotion.cpp \
   $(NULL)
 
 # We fire the nsDOMDeviceAcceleration
 LOCAL_INCLUDES += -I$(topsrcdir)/content/events/src
 
--- a/dom/system/b2g/Makefile.in
+++ b/dom/system/b2g/Makefile.in
@@ -46,26 +46,26 @@ MODULE           = dom
 LIBRARY_NAME     = domsystemb2g_s
 XPIDL_MODULE     = dom_system_b2g
 LIBXUL_LIBRARY   = 1
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/dom/dom-config.mk
 
 CPPSRCS = \
-  RadioManager.cpp \
+  SystemWorkerManager.cpp \
   $(NULL)
 
 ifeq (gonk,$(MOZ_WIDGET_TOOLKIT))
 CPPSRCS += AudioManager.cpp
 endif
 
 XPIDLSRCS = \
   nsIAudioManager.idl \
-  nsIRadioWorker.idl \
+  nsIWorkerHolder.idl \
   $(NULL)
 
 LOCAL_INCLUDES = \
   -I$(topsrcdir)/dom/base \
   -I$(topsrcdir)/dom/telephony \
   -I$(topsrcdir)/dom/wifi \
   -I$(topsrcdir)/content/events/src \
   $(NULL)
rename from dom/system/b2g/RadioManager.cpp
rename to dom/system/b2g/SystemWorkerManager.cpp
--- a/dom/system/b2g/RadioManager.cpp
+++ b/dom/system/b2g/SystemWorkerManager.cpp
@@ -32,56 +32,48 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
-#include "RadioManager.h"
-#include "nsIRadioWorker.h"
-#include "nsContentUtils.h"
-#include "nsIXPConnect.h"
-#include "nsIJSContextStack.h"
+#include "SystemWorkerManager.h"
+
 #include "nsIObserverService.h"
-#include "mozilla/dom/workers/Workers.h"
-#include "jstypedarray.h"
+#include "nsIJSContextStack.h"
+#include "nsITelephone.h"
+#include "nsIWifi.h"
+#include "nsIWorkerHolder.h"
+#include "nsIXPConnect.h"
 
+#include "jstypedarray.h"
+#include "mozilla/dom/workers/Workers.h"
+#include "mozilla/ipc/Ril.h"
+#include "nsContentUtils.h"
+#include "nsServiceManagerUtils.h"
 #include "nsTelephonyWorker.h"
-#include "nsITelephone.h"
+#include "nsThreadUtils.h"
 #include "nsWifiWorker.h"
-#include "nsIWifi.h"
 
-#include "nsThreadUtils.h"
-
-#if defined(MOZ_WIDGET_GONK)
-#include <android/log.h>
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
-#else
-#define LOG(args...)  printf(args);
-#endif
-
+USING_TELEPHONY_NAMESPACE
 USING_WORKERS_NAMESPACE
 using namespace mozilla::ipc;
 
-static NS_DEFINE_CID(kTelephonyWorkerCID, NS_TELEPHONYWORKER_CID);
-static NS_DEFINE_CID(kWifiWorkerCID, NS_WIFIWORKER_CID);
-
-// Topic we listen to for shutdown.
-#define PROFILE_BEFORE_CHANGE_TOPIC "profile-before-change"
-
-USING_TELEPHONY_NAMESPACE
-
 namespace {
 
+NS_DEFINE_CID(kTelephonyWorkerCID, NS_TELEPHONYWORKER_CID);
+NS_DEFINE_CID(kWifiWorkerCID, NS_WIFIWORKER_CID);
+
 // Doesn't carry a reference, we're owned by services.
-RadioManager* gInstance = nsnull;
+SystemWorkerManager *gInstance = nsnull;
 
-class ConnectWorkerToRIL : public WorkerTask {
+class ConnectWorkerToRIL : public WorkerTask
+{
 public:
   virtual bool RunTask(JSContext *aCx);
 };
 
 JSBool
 PostToRIL(JSContext *cx, uintN argc, jsval *vp)
 {
   NS_ASSERTION(!NS_IsMainThread(), "Expecting to be on the worker thread");
@@ -145,22 +137,24 @@ bool
 ConnectWorkerToRIL::RunTask(JSContext *aCx)
 {
   // Set up the postRILMessage on the function for worker -> RIL thread
   // communication.
   NS_ASSERTION(!NS_IsMainThread(), "Expecting to be on the worker thread");
   NS_ASSERTION(!JS_IsRunning(aCx), "Are we being called somehow?");
   JSObject *workerGlobal = JS_GetGlobalObject(aCx);
 
-  return JS_DefineFunction(aCx, workerGlobal, "postRILMessage", PostToRIL, 1, 0);
+  return !!JS_DefineFunction(aCx, workerGlobal, "postRILMessage", PostToRIL, 1,
+                             0);
 }
 
 class RILReceiver : public RilConsumer
 {
-  class DispatchRILEvent : public WorkerTask {
+  class DispatchRILEvent : public WorkerTask
+  {
   public:
     DispatchRILEvent(RilRawData *aMessage)
       : mMessage(aMessage)
     { }
 
     virtual bool RunTask(JSContext *aCx);
 
   private:
@@ -195,178 +189,185 @@ RILReceiver::DispatchRILEvent::RunTask(J
   memcpy(JS_GetTypedArrayData(array), mMessage->mData, mMessage->mSize);
   jsval argv[] = { OBJECT_TO_JSVAL(array) };
   return JS_CallFunctionName(aCx, obj, "onRILMessage", NS_ARRAY_LENGTH(argv),
                              argv, argv);
 }
 
 } // anonymous namespace
 
-RadioManager::RadioManager()
+SystemWorkerManager::SystemWorkerManager()
   : mShutdown(false)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
   NS_ASSERTION(!gInstance, "There should only be one instance!");
 }
 
-RadioManager::~RadioManager()
+SystemWorkerManager::~SystemWorkerManager()
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
   NS_ASSERTION(!gInstance || gInstance == this,
                "There should only be one instance!");
   gInstance = nsnull;
 }
 
 nsresult
-RadioManager::Init()
+SystemWorkerManager::Init()
 {
   NS_ASSERTION(NS_IsMainThread(), "We can only initialize on the main thread");
+  NS_ASSERTION(!mShutdown, "Already shutdown!");
 
-  nsCOMPtr<nsIObserverService> obs =
-    do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
-  if (!obs) {
-    NS_WARNING("Failed to get observer service!");
-    return NS_ERROR_FAILURE;
-  }
-
-  nsresult rv = obs->AddObserver(this, PROFILE_BEFORE_CHANGE_TOPIC, false);
+  JSContext *cx;
+  nsresult rv = nsContentUtils::ThreadJSContextStack()->GetSafeJSContext(&cx);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  JSContext *cx;
-  rv = nsContentUtils::ThreadJSContextStack()->GetSafeJSContext(&cx);
-  NS_ENSURE_SUCCESS(rv, rv);
   nsCxPusher pusher;
   if (!cx || !pusher.Push(cx, false)) {
     return NS_ERROR_FAILURE;
   }
 
   rv = InitTelephone(cx);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = InitWifi(cx);
   NS_ENSURE_SUCCESS(rv, rv);
 
+  nsCOMPtr<nsIObserverService> obs =
+    do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
+  if (!obs) {
+    NS_WARNING("Failed to get observer service!");
+    return NS_ERROR_FAILURE;
+  }
+
+  rv = obs->AddObserver(this, WORKERS_SHUTDOWN_TOPIC, false);
+  NS_ENSURE_SUCCESS(rv, rv);
+
   return NS_OK;
 }
 
 void
-RadioManager::Shutdown()
+SystemWorkerManager::Shutdown()
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
+  mShutdown = true;
+
   StopRil();
-  mTelephone = nsnull;
-  mWifi = nsnull;
+
+  mTelephoneWorker = nsnull;
+  mWifiWorker = nsnull;
 
-  mShutdown = true;
+  nsCOMPtr<nsIObserverService> obs =
+    do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
+  if (obs) {
+    obs->RemoveObserver(this, WORKERS_SHUTDOWN_TOPIC);
+  }
 }
 
 // static
-already_AddRefed<RadioManager>
-RadioManager::FactoryCreate()
+already_AddRefed<SystemWorkerManager>
+SystemWorkerManager::FactoryCreate()
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
-  nsRefPtr<RadioManager> instance(gInstance);
+  nsRefPtr<SystemWorkerManager> instance(gInstance);
 
   if (!instance) {
-    instance = new RadioManager();
+    instance = new SystemWorkerManager();
     if (NS_FAILED(instance->Init())) {
+      instance->Shutdown();
       return nsnull;
     }
 
     gInstance = instance;
   }
 
   return instance.forget();
 }
 
 // static
-already_AddRefed<nsITelephone>
-RadioManager::GetTelephone()
+nsIInterfaceRequestor*
+SystemWorkerManager::GetInterfaceRequestor()
+{
+  return gInstance;
+}
+
+NS_IMETHODIMP
+SystemWorkerManager::GetInterface(const nsIID &aIID, void **aResult)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
-  if (gInstance) {
-    nsCOMPtr<nsITelephone> retval = gInstance->mTelephone;
-    return retval.forget();
+  if (aIID.Equals(NS_GET_IID(nsITelephone))) {
+    return CallQueryInterface(mTelephoneWorker,
+                              reinterpret_cast<nsITelephone**>(aResult));
   }
 
-  return nsnull;
+  if (aIID.Equals(NS_GET_IID(nsIWifi))) {
+    return CallQueryInterface(mWifiWorker,
+                              reinterpret_cast<nsIWifi**>(aResult));
+  }
+
+  NS_WARNING("Got nothing for the requested IID!");
+  return NS_ERROR_NO_INTERFACE;
 }
 
 nsresult
-RadioManager::InitTelephone(JSContext *cx)
+SystemWorkerManager::InitTelephone(JSContext *cx)
 {
-  // The telephony worker component is a hack that gives us a global object for
-  // our own functions and makes creating the worker possible.
-  nsCOMPtr<nsIRadioWorker> worker(do_CreateInstance(kTelephonyWorkerCID));
+  // We're keeping as much of this implementation as possible in JS, so the real
+  // worker lives in nsTelephonyWorker.js. All we do here is hold it alive and
+  // hook it up to the RIL thread.
+  nsCOMPtr<nsIWorkerHolder> worker = do_CreateInstance(kTelephonyWorkerCID);
   NS_ENSURE_TRUE(worker, NS_ERROR_FAILURE);
 
   jsval workerval;
   nsresult rv = worker->GetWorker(&workerval);
   NS_ENSURE_SUCCESS(rv, rv);
-  NS_ASSERTION(!JSVAL_IS_PRIMITIVE(workerval), "bad worker value");
 
-  JSObject *workerobj = JSVAL_TO_OBJECT(workerval);
+  NS_ENSURE_TRUE(!JSVAL_IS_PRIMITIVE(workerval), NS_ERROR_UNEXPECTED);
 
   JSAutoRequest ar(cx);
   JSAutoEnterCompartment ac;
-  if (!ac.enter(cx, workerobj)) {
+  if (!ac.enter(cx, JSVAL_TO_OBJECT(workerval))) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
-  WorkerCrossThreadDispatcher *wctd = GetWorkerCrossThreadDispatcher(cx, workerval);
+  WorkerCrossThreadDispatcher *wctd =
+    GetWorkerCrossThreadDispatcher(cx, workerval);
   if (!wctd) {
     return NS_ERROR_FAILURE;
   }
 
   nsRefPtr<ConnectWorkerToRIL> connection = new ConnectWorkerToRIL();
   if (!wctd->PostTask(connection)) {
     return NS_ERROR_UNEXPECTED;
   }
 
   // Now that we're set up, connect ourselves to the RIL thread.
   mozilla::RefPtr<RILReceiver> receiver = new RILReceiver(wctd);
   StartRil(receiver);
 
-  mTelephone = do_QueryInterface(worker);
-  NS_ENSURE_TRUE(mTelephone, NS_ERROR_FAILURE);
-
+  mTelephoneWorker = worker;
   return NS_OK;
 }
 
 nsresult
-RadioManager::InitWifi(JSContext *cx)
+SystemWorkerManager::InitWifi(JSContext *cx)
 {
-  nsCOMPtr<nsIRadioWorker> worker(do_CreateInstance(kWifiWorkerCID));
+  nsCOMPtr<nsIWorkerHolder> worker = do_CreateInstance(kWifiWorkerCID);
   NS_ENSURE_TRUE(worker, NS_ERROR_FAILURE);
 
-  mWifi = do_QueryInterface(worker);
-  NS_ENSURE_TRUE(mWifi, NS_ERROR_FAILURE);
-
+  mWifiWorker = worker;
   return NS_OK;
 }
 
-
-NS_IMPL_ISUPPORTS1(RadioManager, nsIObserver)
+NS_IMPL_ISUPPORTS2(SystemWorkerManager, nsIObserver, nsIInterfaceRequestor)
 
 NS_IMETHODIMP
-RadioManager::Observe(nsISupports* aSubject, const char* aTopic,
-                      const PRUnichar* aData)
+SystemWorkerManager::Observe(nsISupports *aSubject, const char *aTopic,
+                             const PRUnichar *aData)
 {
-  if (!strcmp(aTopic, PROFILE_BEFORE_CHANGE_TOPIC)) {
+  if (!strcmp(aTopic, WORKERS_SHUTDOWN_TOPIC)) {
     Shutdown();
-
-    nsCOMPtr<nsIObserverService> obs =
-      do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
-    if (obs) {
-      if (NS_FAILED(obs->RemoveObserver(this, aTopic))) {
-        NS_WARNING("Failed to remove observer!");
-      }
-    }
-    else {
-      NS_WARNING("Failed to get observer service!");
-    }
   }
 
   return NS_OK;
 }
rename from dom/system/b2g/RadioManager.h
rename to dom/system/b2g/SystemWorkerManager.h
--- a/dom/system/b2g/RadioManager.h
+++ b/dom/system/b2g/SystemWorkerManager.h
@@ -32,75 +32,53 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
-#ifndef mozilla_dom_telephony_radio_h__
-#define mozilla_dom_telephony_radio_h__
+#ifndef mozilla_dom_system_b2g_systemworkermanager_h__
+#define mozilla_dom_system_b2g_systemworkermanager_h__
 
-#include "jsapi.h"
-#include "nsComponentManagerUtils.h"
-#include "nsCOMPtr.h"
-#include "nsDebug.h"
-#include "nsServiceManagerUtils.h"
-
-#include "nsIObserver.h"
-#include "mozilla/ipc/Ril.h"
-
-#define TELEPHONYRADIO_CONTRACTID "@mozilla.org/telephony/radio;1"
-#define TELEPHONYRADIOINTERFACE_CONTRACTID "@mozilla.org/telephony/radio-interface;1"
+#include "TelephonyCommon.h"
 
-#define BEGIN_TELEPHONY_NAMESPACE \
-  namespace mozilla { namespace dom { namespace telephony {
-#define END_TELEPHONY_NAMESPACE \
-  } /* namespace telephony */ } /* namespace dom */ } /* namespace mozilla */
-#define USING_TELEPHONY_NAMESPACE \
-  using namespace mozilla::dom::telephony;
+#include "nsIInterfaceRequestor.h"
+#include "nsIObserver.h"
 
-// {a5c3a6de-84c4-4b15-8611-8aeb8d97f8ba}
-#define TELEPHONYRADIO_CID \
-  {0xa5c3a6de, 0x84c4, 0x4b15, {0x86, 0x11, 0x8a, 0xeb, 0x8d, 0x97, 0xf8, 0xba}}
-
-// {a688f191-8ffc-47f3-8740-94a312cf59cb}}
-#define TELEPHONYRADIOINTERFACE_CID \
-  {0xd66e7ece, 0x41b1, 0x4608, {0x82, 0x80, 0x72, 0x50, 0xa6, 0x44, 0xe6, 0x6f}}
-
-
-class nsIXPConnectJSObjectHolder;
-class nsITelephone;
-class nsIWifi;
+class nsIWorkerHolder;
 
 BEGIN_TELEPHONY_NAMESPACE
 
-class RadioManager : public nsIObserver
+class SystemWorkerManager : public nsIObserver,
+                            public nsIInterfaceRequestor
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIOBSERVER
+  NS_DECL_NSIINTERFACEREQUESTOR
 
   nsresult Init();
   void Shutdown();
 
-  static already_AddRefed<RadioManager>
+  static already_AddRefed<SystemWorkerManager>
   FactoryCreate();
 
-  static already_AddRefed<nsITelephone>
-  GetTelephone();
+  static nsIInterfaceRequestor*
+  GetInterfaceRequestor();
 
-protected:
-  RadioManager();
-  ~RadioManager();
+private:
+  SystemWorkerManager();
+  ~SystemWorkerManager();
 
   nsresult InitTelephone(JSContext *cx);
   nsresult InitWifi(JSContext *cx);
 
-  nsCOMPtr<nsITelephone> mTelephone;
-  nsCOMPtr<nsIWifi> mWifi;
+  nsCOMPtr<nsIWorkerHolder> mTelephoneWorker;
+  nsCOMPtr<nsIWorkerHolder> mWifiWorker;
+
   bool mShutdown;
 };
 
 END_TELEPHONY_NAMESPACE
 
-#endif // mozilla_dom_telephony_radio_h__
+#endif // mozilla_dom_system_b2g_systemworkermanager_h__
rename from dom/system/b2g/nsIRadioWorker.idl
rename to dom/system/b2g/nsIWorkerHolder.idl
--- a/dom/system/b2g/nsIRadioWorker.idl
+++ b/dom/system/b2g/nsIWorkerHolder.idl
@@ -32,12 +32,13 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsISupports.idl"
 
-[scriptable, uuid(8f031451-ac25-4816-a09e-a075bb704e63)]
-interface nsIRadioWorker : nsISupports {
-    readonly attribute jsval worker;
+[scriptable, uuid(c04f3102-1ce8-4d57-9c27-8aece9c2740a)]
+interface nsIWorkerHolder : nsISupports
+{
+  readonly attribute jsval worker;
 };
new file mode 100644
--- /dev/null
+++ b/dom/telephony/CallEvent.cpp
@@ -0,0 +1,91 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "CallEvent.h"
+
+#include "nsDOMClassInfo.h"
+
+#include "Telephony.h"
+#include "TelephonyCall.h"
+
+USING_TELEPHONY_NAMESPACE
+
+// static
+already_AddRefed<CallEvent>
+CallEvent::Create(TelephonyCall* aCall)
+{
+  NS_ASSERTION(aCall, "Null pointer!");
+
+  nsRefPtr<CallEvent> event = new CallEvent();
+
+  event->mCall = aCall;
+
+  return event.forget();
+}
+
+NS_IMPL_CYCLE_COLLECTION_CLASS(CallEvent)
+
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(CallEvent,
+                                                  nsDOMEvent)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NATIVE_PTR(tmp->mCall->ToISupports(),
+                                               TelephonyCall, "mCall")
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(CallEvent,
+                                                nsDOMEvent)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCall)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(CallEvent)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMCallEvent)
+  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(CallEvent)
+NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent)
+
+NS_IMPL_ADDREF_INHERITED(CallEvent, nsDOMEvent)
+NS_IMPL_RELEASE_INHERITED(CallEvent, nsDOMEvent)
+
+DOMCI_DATA(CallEvent, CallEvent)
+
+NS_IMETHODIMP
+CallEvent::GetCall(nsIDOMTelephonyCall** aCall)
+{
+  nsCOMPtr<nsIDOMTelephonyCall> call = mCall.get();
+  call.forget(aCall);
+  return NS_OK;
+}
new file mode 100644
--- /dev/null
+++ b/dom/telephony/CallEvent.h
@@ -0,0 +1,99 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef mozilla_dom_telephony_callevent_h__
+#define mozilla_dom_telephony_callevent_h__
+
+#include "TelephonyCommon.h"
+
+#include "nsIDOMCallEvent.h"
+#include "nsIDOMEventTarget.h"
+
+#include "nsDOMEvent.h"
+
+BEGIN_TELEPHONY_NAMESPACE
+
+class CallEvent : public nsDOMEvent,
+                  public nsIDOMCallEvent
+{
+  nsRefPtr<TelephonyCall> mCall;
+
+public:
+  NS_DECL_ISUPPORTS_INHERITED
+  NS_FORWARD_TO_NSDOMEVENT
+  NS_DECL_NSIDOMCALLEVENT
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(CallEvent, nsDOMEvent)
+
+  static already_AddRefed<CallEvent>
+  Create(TelephonyCall* aCall);
+
+  nsresult
+  Dispatch(nsIDOMEventTarget* aTarget, const nsAString& aEventType)
+  {
+    NS_ASSERTION(aTarget, "Null pointer!");
+    NS_ASSERTION(!aEventType.IsEmpty(), "Empty event type!");
+
+    nsresult rv = InitEvent(aEventType, false, false);
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    rv = SetTrusted(true);
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    nsIDOMEvent* thisEvent =
+      static_cast<nsDOMEvent*>(const_cast<CallEvent*>(this));
+
+    bool dummy;
+    rv = aTarget->DispatchEvent(thisEvent, &dummy);
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    return NS_OK;
+  }
+
+private:
+  CallEvent()
+  : nsDOMEvent(nsnull, nsnull)
+  { }
+
+  ~CallEvent()
+  { }
+};
+
+END_TELEPHONY_NAMESPACE
+
+#endif // mozilla_dom_telephony_callevent_h__
--- a/dom/telephony/Makefile.in
+++ b/dom/telephony/Makefile.in
@@ -45,24 +45,31 @@ include $(DEPTH)/config/autoconf.mk
 MODULE           = dom
 LIBRARY_NAME     = domtelephony_s
 XPIDL_MODULE     = dom_telephony
 LIBXUL_LIBRARY   = 1
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/dom/dom-config.mk
 
+CPPSRCS = \
+  Telephony.cpp \
+  TelephonyCall.cpp \
+  CallEvent.cpp \
+  $(NULL)
+
 XPIDLSRCS = \
-  mozIDOMTelephony.idl \
+  nsIDOMNavigatorTelephony.idl \
+  nsIDOMTelephony.idl \
+  nsIDOMTelephonyCall.idl \
+  nsIDOMCallEvent.idl \
   nsITelephone.idl \
   $(NULL)
 
 EXTRA_COMPONENTS = \
-  Telephony.manifest \
-  Telephony.js \
   nsTelephonyWorker.manifest \
   nsTelephonyWorker.js \
   $(NULL)
 
 EXTRA_JS_MODULES = \
   ril_consts.js \
   ril_worker.js \
   $(NULL)
new file mode 100644
--- /dev/null
+++ b/dom/telephony/Telephony.cpp
@@ -0,0 +1,469 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "Telephony.h"
+
+#include "nsIDocument.h"
+#include "nsIURI.h"
+#include "nsPIDOMWindow.h"
+
+#include "jsapi.h"
+#include "mozilla/Preferences.h"
+#include "nsContentUtils.h"
+#include "nsDOMClassInfo.h"
+#include "nsIInterfaceRequestorUtils.h"
+#include "nsServiceManagerUtils.h"
+#include "SystemWorkerManager.h"
+
+#include "CallEvent.h"
+#include "TelephonyCall.h"
+
+USING_TELEPHONY_NAMESPACE
+using mozilla::Preferences;
+
+#define DOM_TELEPHONY_APP_PHONE_URL_PREF "dom.telephony.app.phone.url"
+
+namespace {
+
+template <class T>
+inline nsresult
+nsTArrayToJSArray(JSContext* aCx, JSObject* aGlobal,
+                  const nsTArray<nsRefPtr<T> >& aSourceArray,
+                  JSObject** aResultArray)
+{
+  NS_ASSERTION(aCx, "Null context!");
+  NS_ASSERTION(aGlobal, "Null global!");
+
+  JSAutoRequest ar(aCx);
+  JSAutoEnterCompartment ac;
+  if (!ac.enter(aCx, aGlobal)) {
+    NS_WARNING("Failed to enter compartment!");
+    return NS_ERROR_FAILURE;
+  }
+
+  JSObject* arrayObj;
+
+  if (aSourceArray.IsEmpty()) {
+    arrayObj = JS_NewArrayObject(aCx, 0, nsnull);
+  } else {
+    nsTArray<jsval> valArray;
+    valArray.SetLength(aSourceArray.Length());
+
+    for (PRUint32 index = 0; index < valArray.Length(); index++) {
+      nsISupports* obj = aSourceArray[index]->ToISupports();
+      nsresult rv =
+        nsContentUtils::WrapNative(aCx, aGlobal, obj, &valArray[index]);
+      NS_ENSURE_SUCCESS(rv, rv);
+    }
+
+    arrayObj = JS_NewArrayObject(aCx, valArray.Length(), valArray.Elements());
+  }
+
+  if (!arrayObj) {
+    return NS_ERROR_OUT_OF_MEMORY;
+  }
+
+  // XXX This is not what Jonas wants. He wants it to be live.
+  if (!JS_FreezeObject(aCx, arrayObj)) {
+    return NS_ERROR_FAILURE;
+  }
+
+  *aResultArray = arrayObj;
+  return NS_OK;
+}
+
+} // anonymous namespace
+
+Telephony::~Telephony()
+{
+  if (mTelephone && mTelephoneCallback) {
+    mTelephone->UnregisterCallback(mTelephoneCallback);
+  }
+
+  if (mRooted) {
+    NS_DROP_JS_OBJECTS(this, Telephony);
+  }
+}
+
+// static
+already_AddRefed<Telephony>
+Telephony::Create(nsPIDOMWindow* aOwner, nsITelephone* aTelephone)
+{
+  NS_ASSERTION(aOwner, "Null owner!");
+  NS_ASSERTION(aTelephone, "Null telephone!");
+
+  nsCOMPtr<nsIScriptGlobalObject> sgo = do_QueryInterface(aOwner);
+  NS_ENSURE_TRUE(sgo, nsnull);
+
+  nsCOMPtr<nsIScriptContext> scriptContext = sgo->GetContext();
+  NS_ENSURE_TRUE(scriptContext, nsnull);
+
+  nsRefPtr<Telephony> telephony = new Telephony();
+
+  telephony->mOwner = aOwner;
+  telephony->mScriptContext.swap(scriptContext);
+  telephony->mTelephone = aTelephone;
+  telephony->mTelephoneCallback = new TelephoneCallback(telephony);
+
+  nsresult rv = aTelephone->EnumerateCalls(telephony->mTelephoneCallback);
+  NS_ENSURE_SUCCESS(rv, nsnull);
+
+  rv = aTelephone->RegisterCallback(telephony->mTelephoneCallback);
+  NS_ENSURE_SUCCESS(rv, nsnull);
+
+  return telephony.forget();
+}
+
+void
+Telephony::SwitchActiveCall(TelephonyCall* aCall)
+{
+  if (mActiveCall) {
+    // Put the call on hold?
+    NS_NOTYETIMPLEMENTED("Implement me!");
+  }
+  mActiveCall = aCall;
+}
+
+NS_IMPL_CYCLE_COLLECTION_CLASS(Telephony)
+
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(Telephony,
+                                                  nsDOMEventTargetWrapperCache)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
+  NS_CYCLE_COLLECTION_TRAVERSE_EVENT_HANDLER(incoming)
+  for (PRUint32 index = 0; index < tmp->mCalls.Length(); index++) {
+    NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mCalls[i]");
+    cb.NoteXPCOMChild(tmp->mCalls[index]->ToISupports());
+  }
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(Telephony,
+                                               nsDOMEventTargetWrapperCache)
+  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_CALLBACK(tmp->mCallsArray, "mCallsArray")
+NS_IMPL_CYCLE_COLLECTION_TRACE_END
+
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(Telephony,
+                                                nsDOMEventTargetWrapperCache)
+  NS_CYCLE_COLLECTION_UNLINK_EVENT_HANDLER(incoming)
+  tmp->mCalls.Clear();
+  tmp->mActiveCall = nsnull;
+  tmp->mCallsArray = nsnull;
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(Telephony)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMTelephony)
+  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(Telephony)
+NS_INTERFACE_MAP_END_INHERITING(nsDOMEventTargetWrapperCache)
+
+NS_IMPL_ADDREF_INHERITED(Telephony, nsDOMEventTargetWrapperCache)
+NS_IMPL_RELEASE_INHERITED(Telephony, nsDOMEventTargetWrapperCache)
+
+DOMCI_DATA(Telephony, Telephony)
+
+NS_IMPL_ISUPPORTS1(Telephony::TelephoneCallback, nsITelephoneCallback)
+
+NS_IMETHODIMP
+Telephony::Dial(const nsAString& aNumber, nsIDOMTelephonyCall** aResult)
+{
+  NS_ENSURE_ARG(!aNumber.IsEmpty());
+
+  nsresult rv = mTelephone->Dial(aNumber);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  nsRefPtr<TelephonyCall> call =
+    TelephonyCall::Create(this, aNumber, nsITelephone::CALL_STATE_DIALING);
+  NS_ASSERTION(call, "This should never fail!");
+
+  NS_ASSERTION(mCalls.Contains(call), "Should have auto-added new call!");
+
+  call.forget(aResult);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+Telephony::GetMuted(bool* aMuted)
+{
+  nsresult rv = mTelephone->GetMicrophoneMuted(aMuted);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+Telephony::SetMuted(bool aMuted)
+{
+  nsresult rv = mTelephone->SetMicrophoneMuted(aMuted);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+Telephony::GetSpeakerEnabled(bool* aSpeakerEnabled)
+{
+  nsresult rv = mTelephone->GetSpeakerEnabled(aSpeakerEnabled);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+Telephony::SetSpeakerEnabled(bool aSpeakerEnabled)
+{
+  nsresult rv = mTelephone->SetSpeakerEnabled(aSpeakerEnabled);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+Telephony::GetActive(jsval* aActive)
+{
+  if (!mActiveCall) {
+    aActive->setNull();
+    return NS_OK;
+  }
+
+  nsresult rv =
+    nsContentUtils::WrapNative(mScriptContext->GetNativeContext(),
+                               mScriptContext->GetNativeGlobal(),
+                               mActiveCall->ToISupports(), aActive);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+Telephony::SetActive(const jsval& aActive)
+{
+  if (aActive.isObject()) {
+    nsIXPConnect* xpc = nsContentUtils::XPConnect();
+    NS_ASSERTION(xpc, "This should never be null!");
+
+    nsISupports* native =
+      xpc->GetNativeOfWrapper(mScriptContext->GetNativeContext(),
+                              &aActive.toObject());
+
+    nsCOMPtr<nsIDOMTelephonyCall> call = do_QueryInterface(native);
+    if (call) {
+      // See if this call has the same telephony object. Otherwise we can't use
+      // it.
+      TelephonyCall* concreteCall = static_cast<TelephonyCall*>(call.get());
+      if (this == concreteCall->mTelephony) {
+        SwitchActiveCall(concreteCall);
+        return NS_OK;
+      }
+    }
+  }
+
+  return NS_ERROR_INVALID_ARG;
+}
+
+NS_IMETHODIMP
+Telephony::GetCalls(jsval* aCalls)
+{
+  JSObject* calls = mCallsArray;
+  if (!calls) {
+    nsresult rv =
+      nsTArrayToJSArray(mScriptContext->GetNativeContext(),
+                        mScriptContext->GetNativeGlobal(), mCalls, &calls);
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    if (!mRooted) {
+      NS_HOLD_JS_OBJECTS(this, Telephony);
+      mRooted = true;
+    }
+
+    mCallsArray = calls;
+  }
+
+  aCalls->setObject(*calls);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+Telephony::StartTone(const nsAString& aDTMFChar)
+{
+  if (aDTMFChar.IsEmpty()) {
+    NS_WARNING("Empty tone string will be ignored");
+    return NS_OK;
+  }
+
+  if (aDTMFChar.Length() > 1) {
+    return NS_ERROR_INVALID_ARG;
+  }
+
+  nsresult rv = mTelephone->StartTone(aDTMFChar);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+Telephony::StopTone()
+{
+  nsresult rv = mTelephone->StopTone();
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+Telephony::SendTones(const nsAString& aTones, PRUint32 aToneDuration,
+                     PRUint32 aIntervalDuration)
+{
+  NS_NOTYETIMPLEMENTED("Implement me!");
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMPL_EVENT_HANDLER(Telephony, incoming)
+
+NS_IMETHODIMP
+Telephony::CallStateChanged(PRUint32 aCallIndex, PRUint16 aCallState,
+                            const nsAString& aNumber)
+{
+  // If we already know about this call then just update its state.
+  for (PRUint32 index = 0; index < mCalls.Length(); index++) {
+    nsRefPtr<TelephonyCall>& tempCall = mCalls[index];
+    if (tempCall->CallIndex() == aCallIndex) {
+      // This can call back and modify the array... Grab a real ref here.
+      nsRefPtr<TelephonyCall> call = tempCall;
+
+      // See if this should replace our current active call.
+      if (aCallState == nsITelephone::CALL_STATE_CONNECTED) {
+        SwitchActiveCall(call);
+      }
+
+      // Change state.
+      call->ChangeState(aCallState);
+      return NS_OK;
+    }
+  }
+
+  // Didn't know anything about this call before now, must be incoming.
+  NS_ASSERTION(aCallState == nsITelephone::CALL_STATE_INCOMING,
+               "Serious logic problem here!");
+
+  nsRefPtr<TelephonyCall> call =
+    TelephonyCall::Create(this, aNumber, aCallState, aCallIndex);
+  NS_ASSERTION(call, "This should never fail!");
+
+  NS_ASSERTION(mCalls.Contains(call), "Should have auto-added new call!");
+
+  // Dispatch incoming event.
+  nsRefPtr<CallEvent> event = CallEvent::Create(call);
+  NS_ASSERTION(event, "This should never fail!");
+
+  nsresult rv =
+    event->Dispatch(ToIDOMEventTarget(), NS_LITERAL_STRING("incoming"));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+Telephony::EnumerateCallState(PRUint32 aCallIndex, PRUint16 aCallState,
+                              const nsAString& aNumber, bool aIsActive,
+                              bool* aContinue)
+{
+#ifdef DEBUG
+  // Make sure we don't somehow add duplicates.
+  for (PRUint32 index = 0; index < mCalls.Length(); index++) {
+    NS_ASSERTION(mCalls[index]->CallIndex() != aCallIndex,
+                 "Something is really wrong here!");
+  }
+#endif
+  nsRefPtr<TelephonyCall> call =
+    TelephonyCall::Create(this, aNumber, aCallState, aCallIndex);
+  NS_ASSERTION(call, "This should never fail!");
+
+  NS_ASSERTION(mCalls.Contains(call), "Should have auto-added new call!");
+
+  if (aIsActive) {
+    NS_ASSERTION(!mActiveCall, "Already have an active call!");
+    mActiveCall = call;
+  }
+
+  *aContinue = true;
+  return NS_OK;
+}
+
+nsresult
+NS_NewTelephony(nsPIDOMWindow* aWindow, nsIDOMTelephony** aTelephony)
+{
+  NS_ASSERTION(aWindow, "Null pointer!");
+
+  // Make sure we're dealing with an inner window.
+  nsPIDOMWindow* innerWindow = aWindow->IsInnerWindow() ?
+                               aWindow :
+                               aWindow->GetCurrentInnerWindow();
+  NS_ENSURE_TRUE(innerWindow, NS_ERROR_FAILURE);
+
+  if (!nsContentUtils::CanCallerAccess(innerWindow)) {
+    return NS_ERROR_DOM_SECURITY_ERR;
+  }
+
+  nsCOMPtr<nsIDocument> document =
+    do_QueryInterface(innerWindow->GetExtantDocument());
+  NS_ENSURE_TRUE(document, NS_NOINTERFACE);
+
+  nsCOMPtr<nsIURI> documentURI;
+  nsresult rv = document->NodePrincipal()->GetURI(getter_AddRefs(documentURI));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  nsCString documentURL;
+  rv = documentURI->GetSpec(documentURL);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  nsCString phoneAppURL;
+  rv = Preferences::GetCString(DOM_TELEPHONY_APP_PHONE_URL_PREF, &phoneAppURL);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  nsRefPtr<Telephony> telephony;
+  if (phoneAppURL.Equals(documentURL, nsCaseInsensitiveCStringComparator())) {
+    nsIInterfaceRequestor* ireq = SystemWorkerManager::GetInterfaceRequestor();
+    NS_ENSURE_TRUE(ireq, NS_ERROR_UNEXPECTED);
+
+    nsCOMPtr<nsITelephone> telephone = do_GetInterface(ireq);
+    NS_ENSURE_TRUE(telephone, NS_ERROR_UNEXPECTED);
+
+    telephony = Telephony::Create(innerWindow, telephone);
+  }
+  telephony.forget(aTelephony);
+  return NS_OK;
+}
new file mode 100644
--- /dev/null
+++ b/dom/telephony/Telephony.h
@@ -0,0 +1,158 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef mozilla_dom_telephony_telephony_h__
+#define mozilla_dom_telephony_telephony_h__
+
+#include "TelephonyCommon.h"
+
+#include "nsIDOMTelephony.h"
+#include "nsIDOMTelephonyCall.h"
+#include "nsITelephone.h"
+
+class nsIScriptContext;
+class nsPIDOMWindow;
+
+BEGIN_TELEPHONY_NAMESPACE
+
+class Telephony : public nsDOMEventTargetWrapperCache,
+                  public nsIDOMTelephony
+{
+  nsCOMPtr<nsITelephone> mTelephone;
+  nsCOMPtr<nsITelephoneCallback> mTelephoneCallback;
+
+  NS_DECL_EVENT_HANDLER(incoming);
+
+  TelephonyCall* mActiveCall;
+  nsTArray<nsRefPtr<TelephonyCall> > mCalls;
+
+  // Cached calls array object. Cleared whenever mCalls changes and then rebuilt
+  // once a page looks for the liveCalls attribute.
+  JSObject* mCallsArray;
+
+  bool mRooted;
+
+public:
+  NS_DECL_ISUPPORTS_INHERITED
+  NS_DECL_NSIDOMTELEPHONY
+  NS_DECL_NSITELEPHONECALLBACK
+  NS_FORWARD_NSIDOMEVENTTARGET(nsDOMEventTargetWrapperCache::)
+  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_INHERITED(
+                                                   Telephony,
+                                                   nsDOMEventTargetWrapperCache)
+
+  static already_AddRefed<Telephony>
+  Create(nsPIDOMWindow* aOwner, nsITelephone* aTelephone);
+
+  nsIDOMEventTarget*
+  ToIDOMEventTarget() const
+  {
+    return static_cast<nsDOMEventTargetWrapperCache*>(
+             const_cast<Telephony*>(this));
+  }
+
+  nsISupports*
+  ToISupports() const
+  {
+    return ToIDOMEventTarget();
+  }
+
+  void
+  AddCall(TelephonyCall* aCall)
+  {
+    NS_ASSERTION(!mCalls.Contains(aCall), "Already know about this one!");
+    mCalls.AppendElement(aCall);
+    mCallsArray = nsnull;
+  }
+
+  void
+  RemoveCall(TelephonyCall* aCall)
+  {
+    NS_ASSERTION(mCalls.Contains(aCall), "Didn't know about this one!");
+    mCalls.RemoveElement(aCall);
+    mCallsArray = nsnull;
+  }
+
+  nsITelephone*
+  Telephone() const
+  {
+    return mTelephone;
+  }
+
+  nsPIDOMWindow*
+  Owner() const
+  {
+    return mOwner;
+  }
+
+  nsIScriptContext*
+  ScriptContext() const
+  {
+    return mScriptContext;
+  }
+
+private:
+  Telephony()
+  : mActiveCall(nsnull), mCallsArray(nsnull), mRooted(false)
+  { }
+
+  ~Telephony();
+
+  void
+  SwitchActiveCall(TelephonyCall* aCall);
+
+  class TelephoneCallback : public nsITelephoneCallback
+  {
+    Telephony* mTelephony;
+
+  public:
+    NS_DECL_ISUPPORTS
+    NS_FORWARD_NSITELEPHONECALLBACK(mTelephony->)
+
+    TelephoneCallback(Telephony* aTelephony)
+    : mTelephony(aTelephony)
+    {
+      NS_ASSERTION(mTelephony, "Null pointer!");
+    }
+  };
+};
+
+END_TELEPHONY_NAMESPACE
+
+#endif // mozilla_dom_telephony_telephony_h__
deleted file mode 100644
--- a/dom/telephony/Telephony.js
+++ /dev/null
@@ -1,448 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is Telephony.
- *
- * The Initial Developer of the Original Code is
- * the Mozilla Foundation.
- * Portions created by the Initial Developer are Copyright (C) 2011
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Philipp von Weitershausen <philipp@weitershausen.de>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-const TELEPHONY_CID = Components.ID("{37e248d2-02ff-469b-bb31-eef5a4a4bee3}");
-const TELEPHONY_CONTRACTID = "@mozilla.org/telephony;1";
-
-const TELEPHONY_CALL_CID = Components.ID("{6b9b3daf-e5ea-460b-89a5-641ee20dd577}");
-const TELEPHONY_CALL_CONTRACTID = "@mozilla.org/telephony-call;1";
-
-
-const DOM_RADIOSTATE_UNAVAILABLE   = "unavailable";
-const DOM_RADIOSTATE_OFF           = "off";
-const DOM_RADIOSTATE_READY         = "ready";
-
-const DOM_CARDSTATE_UNAVAILABLE    = "unavailable";
-const DOM_CARDSTATE_ABSENT         = "absent";
-const DOM_CARDSTATE_PIN_REQUIRED   = "pin_required";
-const DOM_CARDSTATE_PUK_REQUIRED   = "puk_required";
-const DOM_CARDSTATE_NETWORK_LOCKED = "network_locked";
-const DOM_CARDSTATE_NOT_READY      = "not_ready";
-const DOM_CARDSTATE_READY          = "ready";
-
-const DOM_CALL_READYSTATE_DIALING        = "dialing";
-const DOM_CALL_READYSTATE_RINGING        = "ringing";
-const DOM_CALL_READYSTATE_BUSY           = "busy";
-const DOM_CALL_READYSTATE_CONNECTING     = "connecting";
-const DOM_CALL_READYSTATE_CONNECTED      = "connected";
-const DOM_CALL_READYSTATE_DISCONNECTING  = "disconnecting";
-const DOM_CALL_READYSTATE_DISCONNECTED   = "disconnected";
-const DOM_CALL_READYSTATE_INCOMING       = "incoming";
-const DOM_CALL_READYSTATE_HOLDING        = "holding";
-const DOM_CALL_READYSTATE_HELD           = "held";
-
-const CALLINDEX_TEMPORARY_DIALING = -1;
-
-/**
- * Define an event listener slot on an object, e.g.
- *
- *   obj.onerror = function () {...}
- *
- * will register the function as an event handler for the "error" event
- * if the "error" slot was defined on 'obj' or its prototype.
- */
-function defineEventListenerSlot(object, event_type) {
-  let property_name = "on" + event_type;
-  let hidden_name = "_on" + event_type;
-  let bound_name = "_bound_on" + event_type;
-  object.__defineGetter__(property_name, function getter() {
-    return this[hidden_name];
-  });
-  object.__defineSetter__(property_name, function setter(handler) {
-    let old_handler = this[bound_name];
-    if (old_handler) {
-      this.removeEventListener(event_type, old_handler);
-    }
-    // Bind the handler to the object so that its 'this' is correct.
-    let bound_handler = handler.bind(this);
-    this.addEventListener(event_type, bound_handler);
-    this[hidden_name] = handler;
-    this[bound_name] = bound_handler;
-  });
-}
-
-
-/**
- * Base object for event targets.
- */
-function EventTarget() {}
-EventTarget.prototype = {
-
-  addEventListener: function addEventListener(type, handler) {
-    //TODO verify that handler is an nsIDOMEventListener (or function)
-    if (!this._listeners) {
-      this._listeners = {};
-    }
-    if (!this._listeners[type]) {
-      this._listeners[type] = [];
-    }
-    if (this._listeners[type].indexOf(handler) != -1) {
-      // The handler is already registered. Ignore.
-      return;
-    }
-    this._listeners[type].push(handler);
-  },
-
-  removeEventListener: function removeEventListener(type, handler) {
-     let list, index;
-     if (this._listeners &&
-         (list = this._listeners[type]) &&
-         (index = list.indexOf(handler) != -1)) {
-       list.splice(index, 1);
-       return;
-     }
-  },
-
-  dispatchEvent: function dispatchEvent(event) {
-    //TODO this does not deal with bubbling, defaultPrevented, canceling, etc.
-    //TODO disallow re-dispatch of the same event if it's already being
-    // dispatched (recursion).
-    if (!this._listeners) {
-      return;
-    }
-    let handlerList = this._listeners[event.type];
-    if (!handlerList) {
-      return;
-    }
-    event.target = this;
-
-    // We need to worry about event handler mutations during the event firing.
-    // The correct behaviour is to *not* call any listeners that are added
-    // during the firing and to *not* call any listeners that are removed
-    // during the firing. To address this, we make a copy of the listener list
-    // before dispatching and then double-check that each handler is still
-    // registered before firing it.
-    let handlers = handlerList.slice();
-    handlers.forEach(function (handler) {
-      if (handlerList.indexOf(handler) == -1) {
-        return;
-      }
-      switch (typeof handler) {
-        case "function":
-          handler(event);
-          break;
-        case "object":
-          handler.handleEvent(event);
-          break;
-      }
-    });
-  }
-};
-
-/**
- * Callback object that Telephony registers with nsITelephone.
- * Telephony can't use itself because that might overload event handler
- * attributes ('onfoobar').
- */
-function TelephoneCallback(telephony) {
-  this.telephony = telephony;
-}
-TelephoneCallback.prototype = {
-
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsITelephoneCallback]),
-
-  // nsITelephoneCallback
-
-  onsignalstrengthchange: function onsignalstrengthchange(event) {
-    this.telephony.signalStrength = event.signalStrength;
-    this.telephony._dispatchEventByType("signalstrengthchange");
-  },
-
-  onoperatorchange: function onoperatorchange(event) {
-    this.telephony.operator = event.operator;
-    this.telephony._dispatchEventByType("operatorchange");
-  },
-
-  onradiostatechange: function onradiostatechange(event) {
-    this.telephony.radioState = event.radioState;
-    this.telephony._dispatchEventByType("radiostatechange");
-  },
-
-  oncardstatechange: function oncardstatechange(event) {
-    this.telephony.cardState = event.cardState;
-    this.telephony._dispatchEventByType("cardstatechange");
-  },
-
-  oncallstatechange: function oncallstatechange(event) {
-    this.telephony._processCallState(event);
-  },
-
-};
-
-/**
- * The navigator.mozTelephony object.
- */
-function Telephony() {}
-Telephony.prototype = {
-
-  __proto__: EventTarget.prototype,
-
-  classID: TELEPHONY_CID,
-  classInfo: XPCOMUtils.generateCI({classID: TELEPHONY_CID,
-                                    contractID: TELEPHONY_CONTRACTID,
-                                    interfaces: [Ci.mozIDOMTelephony,
-                                                 Ci.nsIDOMEventTarget],
-                                    flags: Ci.nsIClassInfo.DOM_OBJECT,
-                                    classDescription: "Telephony"}),
-  QueryInterface: XPCOMUtils.generateQI([Ci.mozIDOMTelephony,
-                                         Ci.nsIDOMEventTarget,
-                                         Ci.nsIDOMGlobalPropertyInitializer]),
-
-  // nsIDOMGlobalPropertyInitializer
-
-  init: function init(window) {
-    this.window = window;
-    this.telephone = Cc["@mozilla.org/telephony/radio-interface;1"]
-                       .createInstance(Ci.nsITelephone);
-    this.telephoneCallback = new TelephoneCallback(this);
-    //TODO switch to method suggested by bz in bug 707507
-    window.addEventListener("unload", function onunload(event) {
-      this.telephone.unregisterCallback(this.telephoneCallback);
-      this.telephoneCallback = null;
-      this.window = null;
-    }.bind(this));
-    this.telephone.registerCallback(this.telephoneCallback);
-    this.callsByIndex = {};
-    this.liveCalls = [];
-
-    // Populate existing state.
-    let currentState = this.telephone.currentState;
-    let states = currentState.currentCalls;
-    for (let i = 0; i < states.length; i++) {
-      let state = states[i];
-      let call = new TelephonyCall(this.telephone, state.callIndex);
-      call.readyState = state.callState;
-      call.number = state.number;
-      this.liveCalls.push(call);
-      this.callsByIndex[state.callIndex] = call;
-    }
-
-    this.operator        = currentState.operator;
-    this.radioState      = currentState.radioState;
-    this.cardState       = currentState.cardState;
-    this.signalStrength  = currentState.signalStrength;
-  },
-
-  _dispatchEventByType: function _dispatchEventByType(type) {
-    let event = this.window.document.createEvent("Event");
-    event.initEvent(type, false, false);
-    //event.isTrusted = true;
-    this.dispatchEvent(event);
-  },
-
-  _dispatchCallEvent: function _dispatchCallEvent(call, type, target) {
-    let event = this.window.document.createEvent("Event");
-    event.initEvent(type, false, false);
-    event.call = call; //XXX this is probably not going to work
-    //event.isTrusted = true;
-    target = target || call;
-    target.dispatchEvent(event);
-  },
-
-  _processCallState: function _processCallState(state) {
-    // If the call is dialing, chances are good that we just kicked that off
-    // so there's a call object without a callIndex. Let's fix that.
-    if (state.callState == DOM_CALL_READYSTATE_DIALING) {
-      let call = this.callsByIndex[CALLINDEX_TEMPORARY_DIALING];
-      if (call) {
-        call.callIndex = state.callIndex;
-        delete this.callsByIndex[CALLINDEX_TEMPORARY_DIALING];
-        this.callsByIndex[call.callIndex] = call;
-        // Nothing else to do, since the initial call state will already be
-        // DOM_CALL_READYSTATE_DIALING, so there's no event to dispatch.
-        return;
-      }
-    }
-
-    // If there is an existing call object, update state and dispatch event
-    // on it.
-    let call = this.callsByIndex[state.callIndex];
-    if (call) {
-      if (call.readyState == state.callState) {
-        // No change in ready state, don't dispatch an event.
-        return;
-      }
-      if (state.readyState == DOM_CALL_READYSTATE_DISCONNECTED) {
-        let index = this.liveCalls.indexOf(call);
-        if (index != -1) {
-          this.liveCalls.splice(index, 1);
-        }
-        delete this.callsByIndex[call.callIndex];
-      }
-      call.readyState = state.callState;
-      this._dispatchCallEvent(call, "readystatechange");
-      this._dispatchCallEvent(call, state.callState);
-      return;
-    }
-
-    // There's no call object yet, so let's create a new one, except when
-    // the state notified means that the call is over.
-    if (state.readyState == DOM_CALL_READYSTATE_DISCONNECTED) {
-      return;
-    }
-    call = new TelephonyCall(this.telephone, state.callIndex);
-    call.number = state.number;
-    call.readyState = state.callState;
-    this.callsByIndex[state.callIndex] = call;
-    this.liveCalls.push(call);
-
-    let target;
-    if (call.readyState == DOM_CALL_READYSTATE_INCOMING) {
-      target = this;
-    } else {
-      target = call;
-      this._dispatchCallEvent(call, "readystatechange");
-    }
-    this._dispatchCallEvent(call, state.callState, target);
-  },
-
-  callsByIndex: null,
-
-  // mozIDOMTelephony
-
-  liveCalls: null,
-
-  dial: function dial(number) {
-    this.telephone.dial(number);
-
-    // We don't know ahead of time what callIndex the call is going to have
-    // so let's assign a temp value for now and sort it out on the first
-    // 'callstatechange' event.
-    //TODO ensure there isn't already an outgoing call
-    let callIndex = CALLINDEX_TEMPORARY_DIALING;
-    let call = new TelephonyCall(this.telephone, callIndex);
-    call.readyState = DOM_CALL_READYSTATE_DIALING;
-    call.number = number;
-    this.callsByIndex[callIndex] = call;
-    this.liveCalls.push(call);
-    return call;
-  },
-
-  startTone: function startTone(dtmfChar) {
-    this.telephone.startTone(dtmfChar);
-  },
-
-  stopTone: function stopTone() {
-    this.telephone.stopTone();
-  },
-
-  get muted() {
-    return this.telephone.microphoneMuted;
-  },
-  set muted(value) {
-    this.telephone.microphoneMuted = value;
-  },
-
-  get speakerOn() {
-    return this.telephone.speakerEnabled;
-  },
-  set speakerOn(value) {
-    this.telephone.speakerEnabled = value;
-  },
-
-  // Additional stuff that's useful.
-
-  signalStrength: null,
-  operator: null,
-  radioState: DOM_RADIOSTATE_UNAVAILABLE,
-  cardState: DOM_CARDSTATE_UNAVAILABLE,
-
-};
-defineEventListenerSlot(Telephony.prototype, DOM_CALL_READYSTATE_INCOMING);
-//XXX philikon's additions
-defineEventListenerSlot(Telephony.prototype, "radiostatechange");
-defineEventListenerSlot(Telephony.prototype, "cardstatechange");
-defineEventListenerSlot(Telephony.prototype, "signalstrengthchange");
-defineEventListenerSlot(Telephony.prototype, "operatorchange");
-
-
-function TelephonyCall(telephone, callIndex) {
-  this.telephone = telephone;
-  this.callIndex = callIndex;
-}
-TelephonyCall.prototype = {
-
-  __proto__: EventTarget.prototype,
-
-  classID: TELEPHONY_CALL_CID,
-  classInfo: XPCOMUtils.generateCI({classID: TELEPHONY_CALL_CID,
-                                    contractID: TELEPHONY_CALL_CONTRACTID,
-                                    interfaces: [Ci.mozIDOMTelephonyCall,
-                                                 Ci.nsIDOMEventTarget],
-                                    flags: Ci.nsIClassInfo.DOM_OBJECT,
-                                    classDescription: "TelephonyCall"}),
-  QueryInterface: XPCOMUtils.generateQI([Ci.mozIDOMTelephonyCall,
-                                         Ci.nsIDOMEventTarget]),
-
-
-  callIndex: null,
-
-  // mozIDOMTelephonyCall
-
-  number: null,
-  readyState: null,
-
-  answer: function answer() {
-    if (this.readyState != DOM_CALL_READYSTATE_INCOMING) {
-      throw "Can only answer an incoming call!";
-    }
-    this.telephone.answerCall();
-  },
-
-  disconnect: function disconnect() {
-    if (this.readyState == DOM_CALL_READYSTATE_INCOMING) {
-      this.telephone.rejectCall();
-    } else {
-      this.telephone.hangUp(this.callIndex);
-    }
-  },
-
-};
-defineEventListenerSlot(TelephonyCall.prototype, "readystatechange");
-defineEventListenerSlot(TelephonyCall.prototype, DOM_CALL_READYSTATE_RINGING);
-defineEventListenerSlot(TelephonyCall.prototype, DOM_CALL_READYSTATE_BUSY);
-defineEventListenerSlot(TelephonyCall.prototype, DOM_CALL_READYSTATE_CONNECTING);
-defineEventListenerSlot(TelephonyCall.prototype, DOM_CALL_READYSTATE_CONNECTED);
-defineEventListenerSlot(TelephonyCall.prototype, DOM_CALL_READYSTATE_DISCONNECTING);
-defineEventListenerSlot(TelephonyCall.prototype, DOM_CALL_READYSTATE_DISCONNECTED);
-
-
-const NSGetFactory = XPCOMUtils.generateNSGetFactory([Telephony]);
deleted file mode 100644
--- a/dom/telephony/Telephony.manifest
+++ /dev/null
@@ -1,4 +0,0 @@
-# Telephony.js
-component {37e248d2-02ff-469b-bb31-eef5a4a4bee3} Telephony.js
-contract @mozilla.org/telephony;1 {37e248d2-02ff-469b-bb31-eef5a4a4bee3}
-category JavaScript-navigator-property mozTelephony @mozilla.org/telephony;1
new file mode 100644
--- /dev/null
+++ b/dom/telephony/TelephonyCall.cpp
@@ -0,0 +1,245 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "TelephonyCall.h"
+
+#include "nsDOMClassInfo.h"
+
+#include "CallEvent.h"
+#include "Telephony.h"
+
+USING_TELEPHONY_NAMESPACE
+
+// static
+already_AddRefed<TelephonyCall>
+TelephonyCall::Create(Telephony* aTelephony, const nsAString& aNumber,
+                      PRUint16 aCallState, PRUint32 aCallIndex)
+{
+  NS_ASSERTION(aTelephony, "Null pointer!");
+  NS_ASSERTION(!aNumber.IsEmpty(), "Empty number!");
+  NS_ASSERTION(aCallIndex >= 1, "Invalid call index!");
+
+  nsRefPtr<TelephonyCall> call = new TelephonyCall();
+
+  call->mOwner = aTelephony->Owner();
+  call->mScriptContext = aTelephony->ScriptContext();
+  call->mTelephony = aTelephony;
+  call->mNumber = aNumber;
+  call->mCallIndex = aCallIndex;
+
+  call->ChangeStateInternal(aCallState, false);
+
+  return call.forget();
+}
+
+void
+TelephonyCall::ChangeStateInternal(PRUint16 aCallState, bool aFireEvents)
+{
+  nsRefPtr<TelephonyCall> kungFuDeathGrip(this);
+
+  nsString stateString;
+  switch (aCallState) {
+    case nsITelephone::CALL_STATE_DIALING:
+      stateString.AssignLiteral("dialing");
+      break;
+    case nsITelephone::CALL_STATE_RINGING:
+      stateString.AssignLiteral("ringing");
+      break;
+    case nsITelephone::CALL_STATE_BUSY:
+      stateString.AssignLiteral("busy");
+      break;
+    case nsITelephone::CALL_STATE_CONNECTING:
+      stateString.AssignLiteral("connecting");
+      break;
+    case nsITelephone::CALL_STATE_CONNECTED:
+      stateString.AssignLiteral("connected");
+      break;
+    case nsITelephone::CALL_STATE_HOLDING:
+      stateString.AssignLiteral("holding");
+      break;
+    case nsITelephone::CALL_STATE_HELD:
+      stateString.AssignLiteral("held");
+      break;
+    case nsITelephone::CALL_STATE_RESUMING:
+      stateString.AssignLiteral("resuming");
+      break;
+    case nsITelephone::CALL_STATE_DISCONNECTING:
+      stateString.AssignLiteral("disconnecting");
+      break;
+    case nsITelephone::CALL_STATE_DISCONNECTED:
+      stateString.AssignLiteral("disconnected");
+      break;
+    case nsITelephone::CALL_STATE_INCOMING:
+      stateString.AssignLiteral("incoming");
+      break;
+    default:
+      NS_NOTREACHED("Unknown state!");
+  }
+
+  mState = stateString;
+  mCallState = aCallState;
+
+  if (aCallState == nsITelephone::CALL_STATE_DISCONNECTED) {
+    NS_ASSERTION(mLive, "Should be live!");
+    mTelephony->RemoveCall(this);
+    mLive = false;
+  } else if (!mLive) {
+    mTelephony->AddCall(this);
+    mLive = true;
+  }
+
+  if (aFireEvents) {
+    nsRefPtr<CallEvent> event = CallEvent::Create(this);
+    NS_ASSERTION(event, "This should never fail!");
+
+    if (NS_FAILED(event->Dispatch(ToIDOMEventTarget(),
+                                  NS_LITERAL_STRING("statechange")))) {
+      NS_WARNING("Failed to dispatch statechange event!");
+    }
+
+    // This can change if the statechange handler called back here... Need to
+    // figure out something smarter.
+    if (mCallState == aCallState) {
+      event = CallEvent::Create(this);
+      NS_ASSERTION(event, "This should never fail!");
+
+      if (NS_FAILED(event->Dispatch(ToIDOMEventTarget(), stateString))) {
+        NS_WARNING("Failed to dispatch specific event!");
+      }
+    }
+  }
+}
+
+NS_IMPL_CYCLE_COLLECTION_CLASS(TelephonyCall)
+
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(TelephonyCall,
+                                                  nsDOMEventTargetWrapperCache)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NATIVE_PTR(tmp->mTelephony->ToISupports(),
+                                               Telephony, "mTelephony")
+  NS_CYCLE_COLLECTION_TRAVERSE_EVENT_HANDLER(statechange)
+  NS_CYCLE_COLLECTION_TRAVERSE_EVENT_HANDLER(dialing)
+  NS_CYCLE_COLLECTION_TRAVERSE_EVENT_HANDLER(ringing)
+  NS_CYCLE_COLLECTION_TRAVERSE_EVENT_HANDLER(busy)
+  NS_CYCLE_COLLECTION_TRAVERSE_EVENT_HANDLER(connecting)
+  NS_CYCLE_COLLECTION_TRAVERSE_EVENT_HANDLER(connected)
+  NS_CYCLE_COLLECTION_TRAVERSE_EVENT_HANDLER(disconnecting)
+  NS_CYCLE_COLLECTION_TRAVERSE_EVENT_HANDLER(disconnected)
+  NS_CYCLE_COLLECTION_TRAVERSE_EVENT_HANDLER(incoming)
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(TelephonyCall,
+                                                nsDOMEventTargetWrapperCache)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mTelephony)
+  NS_CYCLE_COLLECTION_UNLINK_EVENT_HANDLER(statechange)
+  NS_CYCLE_COLLECTION_UNLINK_EVENT_HANDLER(dialing)
+  NS_CYCLE_COLLECTION_UNLINK_EVENT_HANDLER(ringing)
+  NS_CYCLE_COLLECTION_UNLINK_EVENT_HANDLER(busy)
+  NS_CYCLE_COLLECTION_UNLINK_EVENT_HANDLER(connecting)
+  NS_CYCLE_COLLECTION_UNLINK_EVENT_HANDLER(connected)
+  NS_CYCLE_COLLECTION_UNLINK_EVENT_HANDLER(disconnecting)
+  NS_CYCLE_COLLECTION_UNLINK_EVENT_HANDLER(disconnected)
+  NS_CYCLE_COLLECTION_UNLINK_EVENT_HANDLER(incoming)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(TelephonyCall)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMTelephonyCall)
+  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(TelephonyCall)
+NS_INTERFACE_MAP_END_INHERITING(nsDOMEventTargetWrapperCache)
+
+NS_IMPL_ADDREF_INHERITED(TelephonyCall, nsDOMEventTargetWrapperCache)
+NS_IMPL_RELEASE_INHERITED(TelephonyCall, nsDOMEventTargetWrapperCache)
+
+DOMCI_DATA(TelephonyCall, TelephonyCall)
+
+NS_IMETHODIMP
+TelephonyCall::GetNumber(nsAString& aNumber)
+{
+  aNumber.Assign(mNumber);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+TelephonyCall::GetState(nsAString& aState)
+{
+  aState.Assign(mState);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+TelephonyCall::Answer()
+{
+  if (mCallState != nsITelephone::CALL_STATE_INCOMING) {
+    NS_WARNING("Answer on non-incoming call ignored!");
+    return NS_OK;
+  }
+
+  nsresult rv = mTelephony->Telephone()->AnswerCall(mCallIndex);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  ChangeStateInternal(nsITelephone::CALL_STATE_CONNECTING, true);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+TelephonyCall::HangUp()
+{
+  if (mCallState == nsITelephone::CALL_STATE_DISCONNECTING ||
+      mCallState == nsITelephone::CALL_STATE_DISCONNECTED) {
+    NS_WARNING("HangUp on previously disconnected call ignored!");
+    return NS_OK;
+  }
+
+  nsresult rv = mCallState == nsITelephone::CALL_STATE_INCOMING ?
+                mTelephony->Telephone()->RejectCall(mCallIndex) :
+                mTelephony->Telephone()->HangUp(mCallIndex);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  ChangeStateInternal(nsITelephone::CALL_STATE_DISCONNECTING, true);
+  return NS_OK;
+}
+
+NS_IMPL_EVENT_HANDLER(TelephonyCall, statechange)
+NS_IMPL_EVENT_HANDLER(TelephonyCall, dialing)
+NS_IMPL_EVENT_HANDLER(TelephonyCall, ringing)
+NS_IMPL_EVENT_HANDLER(TelephonyCall, busy)
+NS_IMPL_EVENT_HANDLER(TelephonyCall, connecting)
+NS_IMPL_EVENT_HANDLER(TelephonyCall, connected)
+NS_IMPL_EVENT_HANDLER(TelephonyCall, disconnecting)
+NS_IMPL_EVENT_HANDLER(TelephonyCall, disconnected)
+NS_IMPL_EVENT_HANDLER(TelephonyCall, incoming)
new file mode 100644
--- /dev/null
+++ b/dom/telephony/TelephonyCall.h
@@ -0,0 +1,131 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef mozilla_dom_telephony_telephonycall_h__
+#define mozilla_dom_telephony_telephonycall_h__
+
+#include "TelephonyCommon.h"
+
+#include "nsIDOMTelephonyCall.h"
+#include "nsITelephone.h"
+
+class nsPIDOMWindow;
+
+BEGIN_TELEPHONY_NAMESPACE
+
+class TelephonyCall : public nsDOMEventTargetWrapperCache,
+                      public nsIDOMTelephonyCall
+{
+  NS_DECL_EVENT_HANDLER(statechange);
+  NS_DECL_EVENT_HANDLER(dialing);
+  NS_DECL_EVENT_HANDLER(ringing);
+  NS_DECL_EVENT_HANDLER(busy);
+  NS_DECL_EVENT_HANDLER(connecting);
+  NS_DECL_EVENT_HANDLER(connected);
+  NS_DECL_EVENT_HANDLER(disconnecting);
+  NS_DECL_EVENT_HANDLER(disconnected);
+  NS_DECL_EVENT_HANDLER(incoming);
+
+  nsRefPtr<Telephony> mTelephony;
+
+  nsString mNumber;
+  nsString mState;
+
+  PRUint32 mCallIndex;
+  PRUint16 mCallState;
+  bool mLive;
+
+public:
+  NS_DECL_ISUPPORTS_INHERITED
+  NS_DECL_NSIDOMTELEPHONYCALL
+  NS_FORWARD_NSIDOMEVENTTARGET(nsDOMEventTargetWrapperCache::)
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(TelephonyCall,
+                                           nsDOMEventTargetWrapperCache)
+
+  static already_AddRefed<TelephonyCall>
+  Create(Telephony* aTelephony, const nsAString& aNumber, PRUint16 aCallState,
+         PRUint32 aCallIndex = PR_UINT32_MAX);
+
+  nsIDOMEventTarget*
+  ToIDOMEventTarget() const
+  {
+    return static_cast<nsDOMEventTargetWrapperCache*>(
+             const_cast<TelephonyCall*>(this));
+  }
+
+  nsISupports*
+  ToISupports() const
+  {
+    return ToIDOMEventTarget();
+  }
+
+  void
+  ChangeState(PRUint16 aCallState)
+  {
+    ChangeStateInternal(aCallState, true);
+  }
+
+  PRUint32
+  CallIndex() const
+  {
+    return mCallIndex;
+  }
+
+  PRUint16
+  CallState() const
+  {
+    return mCallState;
+  }
+
+private:
+  TelephonyCall()
+  : mCallIndex(PR_UINT32_MAX), mCallState(nsITelephone::CALL_STATE_UNKNOWN),
+    mLive(false)
+  { }
+
+  ~TelephonyCall()
+  { }
+
+  void
+  ChangeStateInternal(PRUint16 aCallState, bool aFireEvents);
+};
+
+END_TELEPHONY_NAMESPACE
+
+#endif // mozilla_dom_telephony_telephonycall_h__
new file mode 100644
--- /dev/null
+++ b/dom/telephony/TelephonyCommon.h
@@ -0,0 +1,68 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef mozilla_dom_telephony_telephonycommon_h__
+#define mozilla_dom_telephony_telephonycommon_h__
+
+#include "nsAutoPtr.h"
+#include "nsCOMPtr.h"
+#include "nsCycleCollectionParticipant.h"
+#include "nsDebug.h"
+#include "nsDOMEventTargetWrapperCache.h"
+#include "nsStringGlue.h"
+#include "nsTArray.h"
+
+#define BEGIN_TELEPHONY_NAMESPACE \
+  namespace mozilla { namespace dom { namespace telephony {
+#define END_TELEPHONY_NAMESPACE \
+  } /* namespace telephony */ } /* namespace dom */ } /* namespace mozilla */
+#define USING_TELEPHONY_NAMESPACE \
+  using namespace mozilla::dom::telephony;
+
+class nsIDOMTelephony;
+class nsIDOMTelephonyCall;
+
+BEGIN_TELEPHONY_NAMESPACE
+
+class Telephony;
+class TelephonyCall;
+
+END_TELEPHONY_NAMESPACE
+
+#endif // mozilla_dom_telephony_telephonycommon_h__
new file mode 100644
--- /dev/null
+++ b/dom/telephony/TelephonyFactory.h
@@ -0,0 +1,51 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef mozilla_dom_telephony_telephonyfactory_h__
+#define mozilla_dom_telephony_telephonyfactory_h__
+
+#include "nsIDOMTelephony.h"
+#include "nsPIDOMWindow.h"
+
+// Implemented in Telephony.cpp.
+
+nsresult
+NS_NewTelephony(nsPIDOMWindow* aWindow, nsIDOMTelephony** aTelephony);
+
+#endif // mozilla_dom_telephony_telephonyfactory_h__
deleted file mode 100644
--- a/dom/telephony/mozIDOMTelephony.idl
+++ /dev/null
@@ -1,87 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is Telephony.
- *
- * The Initial Developer of the Original Code is
- * the Mozilla Foundation.
- * Portions created by the Initial Developer are Copyright (C) 2011
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Philipp von Weitershausen <philipp@weitershausen.de>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#include "nsIDOMEventTarget.idl"
-#include "nsIDOMEvent.idl"
-interface nsIDOMEventListener;
-interface mozIDOMTelephonyCall;
-
-[scriptable, uuid(c7b0046b-ee80-447c-8a95-a389003891bc)]
-interface mozIDOMTelephony : nsIDOMEventTarget {
-
-  readonly attribute jsval liveCalls;
-  mozIDOMTelephonyCall dial(in DOMString number);
-  void startTone(in DOMString dtmfChar);
-  void stopTone();
-  attribute nsIDOMEventListener onincoming;
-
-  attribute boolean muted;
-  attribute boolean speakerOn;
-
-  //XXX philikon's additions
-  attribute nsIDOMEventListener onoperatorchange;
-  attribute nsIDOMEventListener onradiostatechange;
-  attribute nsIDOMEventListener oncardstatechange;
-  attribute nsIDOMEventListener onsignalstrengthchange;
-  readonly attribute jsval signalStrength;
-  readonly attribute jsval operator;
-  readonly attribute jsval radioState;
-  readonly attribute jsval cardState;
-};
-
-[scriptable, uuid(3d0060db-72ef-4b87-aceb-a16ed4c5253e)]
-interface mozIDOMTelephonyCall : nsIDOMEventTarget {
-
-  readonly attribute DOMString number;
-  readonly attribute DOMString readyState;
-
-  void answer();
-  void disconnect();
-
-  attribute nsIDOMEventListener onreadystatechange;
-  attribute nsIDOMEventListener onringing;
-  attribute nsIDOMEventListener onbusy;
-  attribute nsIDOMEventListener onconnecting;
-  attribute nsIDOMEventListener onconnected;
-  attribute nsIDOMEventListener ondisconnecting;
-  attribute nsIDOMEventListener ondisconnected;
-};
-
-[scriptable, uuid(c8c42b0c-a0dd-4702-9425-a7a80b2075c3)]
-interface mozIDOMTelephonyCallEvent : nsIDOMEvent {
-  readonly attribute mozIDOMTelephonyCall call;
-};
new file mode 100644
--- /dev/null
+++ b/dom/telephony/nsIDOMCallEvent.idl
@@ -0,0 +1,48 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsIDOMEvent.idl"
+
+interface nsIDOMTelephonyCall;
+
+[scriptable, builtinclass, uuid(95625a90-7f1c-493b-b4bd-73f05834c6dd)]
+interface nsIDOMCallEvent : nsIDOMEvent
+{
+  readonly attribute nsIDOMTelephonyCall call;
+};
new file mode 100644
--- /dev/null
+++ b/dom/telephony/nsIDOMNavigatorTelephony.idl
@@ -0,0 +1,48 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsISupports.idl"
+
+interface nsIDOMTelephony;
+
+[scriptable, builtinclass, uuid(fb2f5927-41ea-442a-8292-81074f69dc41)]
+interface nsIDOMNavigatorTelephony : nsISupports
+{
+  readonly attribute nsIDOMTelephony mozTelephony;
+};
new file mode 100644
--- /dev/null
+++ b/dom/telephony/nsIDOMTelephony.idl
@@ -0,0 +1,68 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *   Philipp von Weitershausen <philipp@weitershausen.de>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsIDOMEventTarget.idl"
+
+interface nsIDOMEventListener;
+interface nsIDOMTelephonyCall;
+
+[scriptable, builtinclass, uuid(047be0d8-a9cd-49aa-8948-2f60ff3a7a18)]
+interface nsIDOMTelephony : nsIDOMEventTarget
+{
+  nsIDOMTelephonyCall dial(in DOMString number);
+
+  attribute boolean muted;
+  attribute boolean speakerEnabled;
+
+  // The call that is "active", i.e. receives microphone input and tones
+  // generated via startTone.
+  attribute jsval active;
+
+  // Array of all calls that are currently connected.
+  readonly attribute jsval calls;
+
+  void startTone(in DOMString tone);
+  void stopTone();
+  void sendTones(in DOMString tones,
+                 [optional] in unsigned long toneDuration,
+                 [optional] in unsigned long intervalDuration);
+
+  attribute nsIDOMEventListener onincoming;
+};
new file mode 100644
--- /dev/null
+++ b/dom/telephony/nsIDOMTelephonyCall.idl
@@ -0,0 +1,64 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=40: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Telephony.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Ben Turner <bent.mozilla@gmail.com> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsIDOMEventTarget.idl"
+
+interface nsIDOMEventListener;
+
+[scriptable, builtinclass, uuid(832b7551-ff53-403f-9e2c-d7d28e2bb40b)]
+interface nsIDOMTelephonyCall : nsIDOMEventTarget
+{
+  readonly attribute DOMString number;
+
+  readonly attribute DOMString state;
+
+  void answer();
+  void hangUp();
+
+  attribute nsIDOMEventListener onstatechange;
+
+  attribute nsIDOMEventListener ondialing;
+  attribute nsIDOMEventListener onringing;
+  attribute nsIDOMEventListener onbusy;
+  attribute nsIDOMEventListener onconnecting;
+  attribute nsIDOMEventListener onconnected;
+  attribute nsIDOMEventListener ondisconnecting;
+  attribute nsIDOMEventListener ondisconnected;
+  attribute nsIDOMEventListener onincoming;
+};
--- a/dom/telephony/nsITelephone.idl
+++ b/dom/telephony/nsITelephone.idl
@@ -35,41 +35,68 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsISupports.idl"
 
 [scriptable, uuid(9b7e3a01-9c45-4af3-81bb-1bf08a842226)]
 interface nsITelephoneCallback : nsISupports
 {
-  void oncallstatechange(in jsval event);
+  // 'callState' uses the CALL_STATE values from nsITelephone.
+  void callStateChanged(in unsigned long callIndex,
+                        in unsigned short callState,
+                        in AString number);
 
-  //XXX philikon's additions
-  void onoperatorchange(in jsval event);
-  void onradiostatechange(in jsval event);
-  void oncardstatechange(in jsval event);
-  void onsignalstrengthchange(in jsval event);
+  // 'callState' uses the CALL_STATE values from nsITelephone. Return true to
+  // continue enumeration or false to cancel.
+  boolean enumerateCallState(in unsigned long callIndex,
+                             in unsigned short callState,
+                             in AString number,
+                             in boolean isActive);
 };
 
 [scriptable, uuid(5be6e41d-3aee-4f5c-8284-95cf529dd6fe)]
 interface nsITelephone : nsISupports
 {
+  const unsigned short CALL_STATE_UNKNOWN = 0;
+  const unsigned short CALL_STATE_DIALING = 1;
+  const unsigned short CALL_STATE_RINGING = 2;
+  const unsigned short CALL_STATE_BUSY = 3;
+  const unsigned short CALL_STATE_CONNECTING = 4;
+  const unsigned short CALL_STATE_CONNECTED = 5;
+  const unsigned short CALL_STATE_HOLDING = 6;
+  const unsigned short CALL_STATE_HELD = 7;
+  const unsigned short CALL_STATE_RESUMING = 8;
+  const unsigned short CALL_STATE_DISCONNECTING = 9;
+  const unsigned short CALL_STATE_DISCONNECTED = 10;
+  const unsigned short CALL_STATE_INCOMING = 11;
+
   readonly attribute jsval currentState;
+
   void registerCallback(in nsITelephoneCallback callback);
   void unregisterCallback(in nsITelephoneCallback callback);
 
   /**
+   * Will continue calling callback.enumerateCallState until the callback
+   * returns false.
+   */
+  void enumerateCalls(in nsITelephoneCallback callback);
+
+  /**
    * Functionality for making and managing phone calls.
    */
   void dial(in DOMString number);
-  void hangUp(in long callIndex);
+  void hangUp(in unsigned long callIndex);
+
   void startTone(in DOMString dtmfChar);
   void stopTone();
-  void answerCall();
-  void rejectCall();
+
+  void answerCall(in unsigned long callIndex);
+  void rejectCall(in unsigned long callIndex);
+
   attribute bool microphoneMuted;
   attribute bool speakerEnabled;
 
   /**
    * SMS-related functionality.
    */
   unsigned short getNumberOfMessagesForText(in DOMString text);
   void sendSMS(in DOMString number, in DOMString message);
--- a/dom/telephony/nsTelephonyWorker.h
+++ b/dom/telephony/nsTelephonyWorker.h
@@ -30,11 +30,12 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
+// This must always match the CID given in nsTelephonyWorker.manifest!
 #define NS_TELEPHONYWORKER_CID \
     { 0x2d831c8d, 0x6017, 0x435b, \
       { 0xa8, 0x0c, 0xe5, 0xd4, 0x22, 0x81, 0x0c, 0xea } }
--- a/dom/telephony/nsTelephonyWorker.js
+++ b/dom/telephony/nsTelephonyWorker.js
@@ -31,203 +31,249 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
+"use strict";
+
 const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 
+var RIL = {};
+Cu.import("resource://gre/modules/ril_consts.js", RIL);
+
 const DEBUG = true; // set to false to suppress debug messages
 
-const TELEPHONYWORKER_CONTRACTID = "@mozilla.org/telephony/worker;1";
-const TELEPHONYWORKER_CID        = Components.ID("{2d831c8d-6017-435b-a80c-e5d422810cea}");
+const TELEPHONYWORKER_CID =
+  Components.ID("{2d831c8d-6017-435b-a80c-e5d422810cea}");
 
-const DOM_CALL_READYSTATE_DIALING        = "dialing";
-const DOM_CALL_READYSTATE_RINGING        = "ringing";
-const DOM_CALL_READYSTATE_BUSY           = "busy";
-const DOM_CALL_READYSTATE_CONNECTING     = "connecting";
-const DOM_CALL_READYSTATE_CONNECTED      = "connected";
-const DOM_CALL_READYSTATE_DISCONNECTING  = "disconnecting";
-const DOM_CALL_READYSTATE_DISCONNECTED   = "disconnected";
-const DOM_CALL_READYSTATE_INCOMING       = "incoming";
-const DOM_CALL_READYSTATE_HOLDING        = "holding";
-const DOM_CALL_READYSTATE_HELD           = "held";
+const nsIAudioManager = Ci.nsIAudioManager;
+const nsITelephone = Ci.nsITelephone;
 
 const kSmsReceivedObserverTopic          = "sms-received";
 const DOM_SMS_DELIVERY_RECEIVED          = "received";
 
 XPCOMUtils.defineLazyServiceGetter(this, "gSmsService",
                                    "@mozilla.org/sms/smsservice;1",
                                    "nsISmsService");
 
+function convertRILCallState(state) {
+  switch (state) {
+    case RIL.CALL_STATE_ACTIVE:
+      return nsITelephone.CALL_STATE_CONNECTED;
+    case RIL.CALL_STATE_HOLDING:
+      return nsITelephone.CALL_STATE_HELD;
+    case RIL.CALL_STATE_DIALING:
+      return nsITelephone.CALL_STATE_DIALING;
+    case RIL.CALL_STATE_ALERTING:
+      return nsITelephone.CALL_STATE_RINGING;
+    case RIL.CALL_STATE_INCOMING:
+      return nsITelephone.CALL_STATE_INCOMING;
+    case RIL.CALL_STATE_WAITING:
+      return nsITelephone.CALL_STATE_HELD; // XXX This may not be right...
+    default:
+      throw new Error("Unknown rilCallState: " + state);
+  }
+}
+
 /**
  * Fake nsIAudioManager implementation so that we can run the telephony
  * code in a non-Gonk build.
  */
 let FakeAudioManager = {
   microphoneMuted: false,
   masterVolume: 1.0,
   masterMuted: false,
-  phoneState: Ci.nsIAudioManager.PHONE_STATE_CURRENT,
+  phoneState: nsIAudioManager.PHONE_STATE_CURRENT,
   _forceForUse: {},
   setForceForUse: function setForceForUse(usage, force) {
     this._forceForUse[usage] = force;
   },
   getForceForUse: function setForceForUse(usage) {
-    return this._forceForUse[usage] || Ci.nsIAudioManager.FORCE_NONE;
+    return this._forceForUse[usage] || nsIAudioManager.FORCE_NONE;
   }
 };
 
 XPCOMUtils.defineLazyGetter(this, "gAudioManager", function getAudioManager() {
   try {
     return Cc["@mozilla.org/telephony/audiomanager;1"]
-             .getService(Ci.nsIAudioManager);
+             .getService(nsIAudioManager);
   } catch (ex) {
     //TODO on the phone this should not fall back as silently.
     debug("Using fake audio manager.");
     return FakeAudioManager;
   }
 });
 
 
 function nsTelephonyWorker() {
   this.worker = new ChromeWorker("resource://gre/modules/ril_worker.js");
   this.worker.onerror = this.onerror.bind(this);
   this.worker.onmessage = this.onmessage.bind(this);
-
-  this._callbacks = [];
+  debug("Starting Worker\n");
   this.currentState = {
     signalStrength: null,
     operator:       null,
     radioState:     null,
-    cardState:      null,
-    currentCalls:   {}
+    cardState:      null
   };
 }
 nsTelephonyWorker.prototype = {
 
   classID:   TELEPHONYWORKER_CID,
   classInfo: XPCOMUtils.generateCI({classID: TELEPHONYWORKER_CID,
-                                    contractID: TELEPHONYWORKER_CONTRACTID,
-                                    classDescription: "TelephonyWorker",
-                                    interfaces: [Ci.nsIRadioWorker,
+                                    classDescription: "Telephone",
+                                    interfaces: [Ci.nsIWorkerHolder,
                                                  Ci.nsITelephone]}),
 
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIRadioWorker,
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsIWorkerHolder,
                                          Ci.nsITelephone]),
 
   onerror: function onerror(event) {
-    // It is very important to call preventDefault on the event here.
-    // If an exception is thrown on the worker, it bubbles out to the
-    // component that created it. If that component doesn't have an
-    // onerror handler, the worker will try to call the error reporter
-    // on the context it was created on. However, That doesn't work
-    // for component contexts and can result in crashes. This onerror
-    // handler has to make sure that it calls preventDefault on the
-    // incoming event.
-    event.preventDefault();
-
     debug("Got an error: " + event.filename + ":" +
           event.lineno + ": " + event.message + "\n");
+    event.preventDefault();
   },
 
   /**
    * Process the incoming message from the RIL worker:
    * (1) Update the current state. This way any component that hasn't
    *     been listening for callbacks can easily catch up by looking at
    *     this.currentState.
    * (2) Update state in related systems such as the audio.
    * (3) Multiplex the message to telephone callbacks.
    */
   onmessage: function onmessage(event) {
     let message = event.data;
     debug("Received message: " + JSON.stringify(message));
-    let value;
     switch (message.type) {
+      case "callStateChange":
+        // This one will handle its own notifications.
+        this.handleCallStateChange(message.call);
+        break;
+      case "callDisconnected":
+        // This one will handle its own notifications.
+        this.handleCallDisconnected(message.call);
+        break;
+      case "enumerateCalls":
+        // This one will handle its own notifications.
+        this.handleEnumerateCalls(message.calls);
+        break;
       case "signalstrengthchange":
         this.currentState.signalStrength = message.signalStrength;
         break;
       case "operatorchange":
         this.currentState.operator = message.operator;
         break;
       case "radiostatechange":
         this.currentState.radioState = message.radioState;
         break;
       case "cardstatechange":
         this.currentState.cardState = message.cardState;
         break;
-      case "callstatechange":
-        this.handleCallState(message);
-        break;
       case "sms-received":
         this.handleSmsReceived(message);
-        break;
+        return;
       default:
-        // Got some message from the RIL worker that we don't know about.
-        return;
+        throw new Error("Don't know about this message type: " + message.type);
     }
-    let methodname = "on" + message.type;
-    this._callbacks.forEach(function (callback) {
-      let method = callback[methodname];
-      if (typeof method != "function") {
-        return;
+  },
+
+  /**
+   * Track the active call and update the audio system as its state changes.
+   *
+   * XXX Needs some more work to support hold/resume.
+   */
+  _activeCall: null,
+  get activeCall() {
+    return this._activeCall;
+  },
+  set activeCall(val) {
+    if (val && !this._activeCall) {
+      // Enable audio.
+      switch (val.state) {
+        case nsITelephone.CALL_STATE_INCOMING:
+          gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_RINGTONE;
+          break;
+        case nsITelephone.CALL_STATE_DIALING: // Fall through...
+        case nsITelephone.CALL_STATE_CONNECTED:
+          gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_IN_CALL;
+          gAudioManager.setForceForUse(nsIAudioManager.USE_COMMUNICATION,
+                                       nsIAudioManager.FORCE_NONE);
+          break;
+        default:
+          throw new Error("Invalid call state for active call: " + val.state);
       }
-      method.call(callback, message);
-    });
+    } else if (!val && this._activeCall) {
+      // Disable audio.
+      gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_NORMAL;
+    }
+    this._activeCall = val;
   },
 
   /**
-   * Handle call state changes by updating our current state and
-   * the audio system.
+   * Handle call state changes by updating our current state and the audio
+   * system.
    */
-  handleCallState: function handleCallState(message) {
-    let currentCalls = this.currentState.currentCalls;
-    let oldState = currentCalls[message.callIndex];
-
-    // Update current state.
-    if (message.callState == DOM_CALL_READYSTATE_DISCONNECTED) {
-      delete currentCalls[message.callIndex];
-    } else {
-      currentCalls[message.callIndex] = message;
+  handleCallStateChange: function handleCallStateChange(call) {
+    debug("handleCallStateChange: " + JSON.stringify(call));
+    call.state = convertRILCallState(call.state);
+    if (call.state == nsITelephone.CALL_STATE_INCOMING ||
+        call.state == nsITelephone.CALL_STATE_DIALING ||
+        call.state == nsITelephone.CALL_STATE_CONNECTED) {
+      // This is now the active call.
+      this.activeCall = call;
     }
+    this._deliverCallback("callStateChanged",
+                          [call.callIndex, call.state, call.number]);
+  },
 
-    // Update the audio system.
-    //TODO this does not handle multiple concurrent calls yet.
-    switch (message.callState) {
-      case DOM_CALL_READYSTATE_DIALING:
-        this.worker.postMessage({type: "setMute", mute: false});
-        gAudioManager.phoneState = Ci.nsIAudioManager.PHONE_STATE_IN_CALL;
-        gAudioManager.setForceForUse(Ci.nsIAudioManager.USE_COMMUNICATION,
-                                     Ci.nsIAudioManager.FORCE_NONE);
-        break;
-      case DOM_CALL_READYSTATE_INCOMING:
-        gAudioManager.phoneState = Ci.nsIAudioManager.PHONE_STATE_RINGTONE;
+  /**
+   * Handle call disconnects by updating our current state and the audio system.
+   */
+  handleCallDisconnected: function handleCallStateChange(call) {
+    debug("handleCallDisconnected: " + JSON.stringify(call));
+    if (this.activeCall == call) {
+      // No loner active.
+      this.activeCall = null;
+    }
+    this._deliverCallback("callStateChanged",
+                          [call.callIndex, nsITelephone.CALL_STATE_DISCONNECTED,
+                           call.number]);
+  },
+
+  /**
+   * Handle calls delivered in response to a 'enumerateCalls' request.
+   */
+  handleEnumerateCalls: function handleEnumerateCalls(calls) {
+    debug("handleEnumerateCalls: " + JSON.stringify(calls));
+    let callback = this._enumerationCallbacks.shift();
+    let activeCallIndex = this.activeCall ? this.activeCall.callIndex : -1;
+    for (let i in calls) {
+      let call = calls[i];
+      let state = convertRILCallState(call.state);
+      let keepGoing;
+      try {
+        keepGoing =
+          callback.enumerateCallState(call.callIndex, state, call.number,
+                                      call.callIndex == activeCallIndex);
+      } catch (e) {
+        debug("callback handler for 'enumerateCallState' threw an " +
+              " exception: " + e);
+        keepGoing = true;
+      }
+      if (!keepGoing) {
         break;
-      case DOM_CALL_READYSTATE_CONNECTED:
-        if (!oldState ||
-            oldState.callState == DOM_CALL_READYSTATE_INCOMING ||
-            oldState.callState == DOM_CALL_READYSTATE_CONNECTING) {
-          // It's an incoming call, so tweak the audio now. If it was an
-          // outgoing call, it would have been tweaked at dialing.
-          this.worker.postMessage({type: "setMute", mute: false});
-          gAudioManager.phoneState = Ci.nsIAudioManager.PHONE_STATE_IN_CALL;
-          gAudioManager.setForceForUse(Ci.nsIAudioManager.USE_COMMUNICATION,
-                                       Ci.nsIAudioManager.FORCE_NONE);
-        }
-        break;
-      case DOM_CALL_READYSTATE_DISCONNECTED:
-        this.worker.postMessage({type: "setMute", mute: true});
-        gAudioManager.phoneState = Ci.nsIAudioManager.PHONE_STATE_NORMAL;
-        break;
+      }
     }
   },
 
   handleSmsReceived: function handleSmsReceived(message) {
     //TODO: put the sms into a database, assign it a proper id, yada yada
     let sms = gSmsService.createSmsMessage(-1,
                                            DOM_SMS_DELIVERY_RECEIVED,
                                            message.sender || null,
@@ -260,78 +306,122 @@ nsTelephonyWorker.prototype = {
     this.worker.postMessage({type: "startTone", dtmfChar: dtmfChar});
   },
 
   stopTone: function stopTone() {
     debug("Stopping Tone");
     this.worker.postMessage({type: "stopTone"});
   },
 
-  answerCall: function answerCall() {
-    this.worker.postMessage({type: "answerCall"});
+  answerCall: function answerCall(callIndex) {
+    this.worker.postMessage({type: "answerCall", callIndex: callIndex});
   },
 
-  rejectCall: function rejectCall() {
-    this.worker.postMessage({type: "rejectCall"});
+  rejectCall: function rejectCall(callIndex) {
+    this.worker.postMessage({type: "rejectCall", callIndex: callIndex});
   },
 
   get microphoneMuted() {
     return gAudioManager.microphoneMuted;
   },
   set microphoneMuted(value) {
     if (value == this.microphoneMuted) {
       return;
     }
     gAudioManager.phoneState = value ?
-      Ci.nsIAudioManager.PHONE_STATE_IN_COMMUNICATION :
-      Ci.nsIAudioManager.PHONE_STATE_IN_CALL;  //XXX why is this needed?
+      nsIAudioManager.PHONE_STATE_IN_COMMUNICATION :
+      nsIAudioManager.PHONE_STATE_IN_CALL;  //XXX why is this needed?
     gAudioManager.microphoneMuted = value;
   },
 
   get speakerEnabled() {
-    return (gAudioManager.getForceForUse(Ci.nsIAudioManager.USE_COMMUNICATION)
-            == Ci.nsIAudioManager.FORCE_SPEAKER);
+    return (gAudioManager.getForceForUse(nsIAudioManager.USE_COMMUNICATION) ==
+            nsIAudioManager.FORCE_SPEAKER);
   },
   set speakerEnabled(value) {
     if (value == this.speakerEnabled) {
       return;
     }
-    gAudioManager.phoneState = Ci.nsIAudioManager.PHONE_STATE_IN_CALL; // XXX why is this needed?
-    let force = value ? Ci.nsIAudioManager.FORCE_SPEAKER :
-                        Ci.nsIAudioManager.FORCE_NONE;
-    gAudioManager.setForceUse(Ci.nsIAudioManager.USE_COMMUNICATION, force);
+    gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_IN_CALL; // XXX why is this needed?
+    let force = value ? nsIAudioManager.FORCE_SPEAKER :
+                        nsIAudioManager.FORCE_NONE;
+    gAudioManager.setForceUse(nsIAudioManager.USE_COMMUNICATION, force);
   },
 
   getNumberOfMessagesForText: function getNumberOfMessagesForText(text) {
     //TODO: this assumes 7bit encoding, which is incorrect. Need to look
     // for characters not supported by 7bit alphabets and then calculate
     // length in UCS2 encoding.
     return Math.ceil(text.length / 160);
   },
 
   sendSMS: function sendSMS(number, message) {
     this.worker.postMessage({type: "sendSMS",
                              number: number,
                              body: message});
   },
 
   _callbacks: null,
+  _enumerationCallbacks: null,
 
   registerCallback: function registerCallback(callback) {
+    debug("Registering callback: " + callback);
+    if (this._callbacks) {
+      if (this._callbacks.indexOf(callback) != -1) {
+        throw new Error("Already registered this callback!");
+      }
+    } else {
+      this._callbacks = [];
+    }
     this._callbacks.push(callback);
   },
 
   unregisterCallback: function unregisterCallback(callback) {
-    let index = this._callbacks.indexOf(callback);
-    if (index == -1) {
-      throw "Callback not registered!";
+    debug("Unregistering callback: " + callback);
+    let index;
+    if (this._callbacks && (index = this._callbacks.indexOf(callback) != -1)) {
+      this._callbacks.splice(index, 1);
     }
-    this._callbacks.splice(index, 1);
+  },
+
+  enumerateCalls: function enumerateCalls(callback) {
+    debug("Requesting enumeration of calls for callback: " + callback);
+    this.worker.postMessage({type: "enumerateCalls"});
+    if (!this._enumerationCallbacks) {
+      this._enumerationCallbacks = [];
+    }
+    this._enumerationCallbacks.push(callback);
   },
 
+  _deliverCallback: function _deliverCallback(name, args) {
+    // We need to worry about callback registration state mutations during the
+    // callback firing. The behaviour we want is to *not* call any callbacks
+    // that are added during the firing and to *not* call any callbacks that are
+    // removed during the firing. To address this, we make a copy of the
+    // callback list before dispatching and then double-check that each callback
+    // is still registered before calling it.
+    if (!this._callbacks) {
+      return;
+    }
+    let callbacks = this._callbacks.slice();
+    for each (let callback in callbacks) {
+      if (this._callbacks.indexOf(callback) == -1) {
+        continue;
+      }
+      let handler = callback[name];
+      if (typeof handler != "function") {
+        throw new Error("No handler for " + name);
+      }
+      try {
+        handler.apply(callback, args);
+      } catch (e) {
+        debug("callback handler for " + name + " threw an exception: " + e);
+      }
+    }
+  },
 };
 
 const NSGetFactory = XPCOMUtils.generateNSGetFactory([nsTelephonyWorker]);
 
 let debug;
 if (DEBUG) {
   debug = function (s) {
     dump("-*- TelephonyWorker component: " + s + "\n");
--- a/dom/telephony/ril_consts.js
+++ b/dom/telephony/ril_consts.js
@@ -220,36 +220,16 @@ const DOM_RADIOSTATE_READY         = "re
 const DOM_CARDSTATE_UNAVAILABLE    = "unavailable";
 const DOM_CARDSTATE_ABSENT         = "absent";
 const DOM_CARDSTATE_PIN_REQUIRED   = "pin_required";
 const DOM_CARDSTATE_PUK_REQUIRED   = "puk_required";
 const DOM_CARDSTATE_NETWORK_LOCKED = "network_locked";
 const DOM_CARDSTATE_NOT_READY      = "not_ready";
 const DOM_CARDSTATE_READY          = "ready";
 
-const DOM_CALL_READYSTATE_DIALING        = "dialing";
-const DOM_CALL_READYSTATE_RINGING        = "ringing";
-const DOM_CALL_READYSTATE_BUSY           = "busy";
-const DOM_CALL_READYSTATE_CONNECTING     = "connecting";
-const DOM_CALL_READYSTATE_CONNECTED      = "connected";
-const DOM_CALL_READYSTATE_DISCONNECTING  = "disconnecting";
-const DOM_CALL_READYSTATE_DISCONNECTED   = "disconnected";
-const DOM_CALL_READYSTATE_INCOMING       = "incoming";
-const DOM_CALL_READYSTATE_HOLDING        = "holding";
-const DOM_CALL_READYSTATE_HELD           = "held";
-
-const RIL_TO_DOM_CALL_STATE = [
-  DOM_CALL_READYSTATE_CONNECTED, // CALL_READYSTATE_ACTIVE
-  DOM_CALL_READYSTATE_HELD,      // CALL_READYSTATE_HOLDING
-  DOM_CALL_READYSTATE_DIALING,   // CALL_READYSTATE_DIALING
-  DOM_CALL_READYSTATE_RINGING,   // CALL_READYSTATE_ALERTING
-  DOM_CALL_READYSTATE_INCOMING,  // CALL_READYSTATE_INCOMING
-  DOM_CALL_READYSTATE_HELD       // CALL_READYSTATE_WAITING (XXX is this right?)
-];
-
 
 /**
  * GSM PDU constants
  */
 
 // PDU TYPE-OF-ADDRESS
 const PDU_TOA_UNKNOWN       = 0x80; // Unknown. This is used when the user or
                                     // network has no a priori information
@@ -408,8 +388,12 @@ const PDU_ALPHABET_7BIT_DEFAULT = [
   "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
   "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
   "\xe4",   // LATIN SMALL LETTER A WITH DIAERESIS
   "\xf6",   // LATIN SMALL LETTER O WITH DIAERESIS
   "\xf1",   // LATIN SMALL LETTER N WITH TILDE
   "\xfc",   // LATIN SMALL LETTER U WITH DIAERESIS
   "\xe0"    // LATIN SMALL LETTER A WITH GRAVE
 ];
+
+
+// Allow this file to be imported via Components.utils.import().
+const EXPORTED_SYMBOLS = Object.keys(this);
--- a/dom/telephony/ril_worker.js
+++ b/dom/telephony/ril_worker.js
@@ -623,23 +623,23 @@ let RIL = {
     // match the format of the binary message.
     Buf.writeUint32(0);
     Buf.sendParcel();
   },
 
   /**
    * Hang up the phone.
    *
-   * @param index
+   * @param callIndex
    *        Call index (1-based) as reported by REQUEST_GET_CURRENT_CALLS.
    */
-  hangUp: function hangUp(index) {
+  hangUp: function hangUp(callIndex) {
     Buf.newParcel(REQUEST_HANGUP);
     Buf.writeUint32(1);
-    Buf.writeUint32(index);
+    Buf.writeUint32(callIndex);
     Buf.sendParcel();
   },
 
   /**
    * Mute or unmute the radio.
    *
    * @param mute
    *        Boolean to indicate whether to mute or unmute the radio.
@@ -814,17 +814,17 @@ RIL[REQUEST_GET_CURRENT_CALLS] = functio
     Phone.onCurrentCalls(null);
     return;
   }
 
   let calls = {};
   for (let i = 0; i < calls_length; i++) {
     let call = {
       state:              Buf.readUint32(), // CALL_STATE_*
-      index:              Buf.readUint32(), // GSM index (1-based)
+      callIndex:          Buf.readUint32(), // GSM index (1-based)
       toa:                Buf.readUint32(),
       isMpty:             Boolean(Buf.readUint32()),
       isMT:               Boolean(Buf.readUint32()),
       als:                Buf.readUint32(),
       isVoice:            Boolean(Buf.readUint32()),
       isVoicePrivacy:     Boolean(Buf.readUint32()),
       somethingOrOther:   Buf.readUint32(), //XXX TODO whatziz? not in ril.h, but it's in the output...
       number:             Buf.readString(), //TODO munge with TOA
@@ -836,17 +836,17 @@ RIL[REQUEST_GET_CURRENT_CALLS] = functio
     let uusInfoPresent = Buf.readUint32();
     if (uusInfoPresent == 1) {
       call.uusInfo = {
         type:     Buf.readUint32(),
         dcs:      Buf.readUint32(),
         userData: null //XXX TODO byte array?!?
       };
     }
-    calls[call.index] = call;
+    calls[call.callIndex] = call;
   }
   Phone.onCurrentCalls(calls);
 };
 RIL[REQUEST_DIAL] = function REQUEST_DIAL(length) {
   Phone.onDial();
 };
 RIL[REQUEST_GET_IMSI] = function REQUEST_GET_IMSI(length) {
   let imsi = Buf.readString();
@@ -1118,16 +1118,48 @@ let Phone = {
   iccStatus: null,
 
   /**
    * Active calls
    */
   currentCalls: {},
 
   /**
+   * Mute or unmute the radio.
+   */
+  _muted: true,
+
+  get muted() {
+    return this._muted;
+  },
+
+  set muted(val) {
+    val = Boolean(val);
+    if (this._muted != val) {
+      RIL.setMute(val);
+      this._muted = val;
+    }
+  },
+
+  _handleChangedCallState: function _handleChangedCallState(changedCall) {
+    let message = {type: "callStateChange",
+                   call: {callIndex: changedCall.callIndex,
+                          state: changedCall.state,
+                          number: changedCall.number,
+                          name: changedCall.name}};
+    this.sendDOMMessage(message);
+  },
+
+  _handleDisconnectedCall: function _handleDisconnectedCall(disconnectedCall) {
+    let message = {type: "callDisconnected",
+                   call: {callIndex: disconnectedCall.callIndex}};
+    this.sendDOMMessage(message);
+  },
+
+  /**
    * Handlers for messages from the RIL. They all begin with on* and are called
    * from RIL object.
    */
 
   onRadioStateChanged: function onRadioStateChanged(newState) {
     debug("Radio state changed from " + this.radioState + " to " + newState);
     if (this.radioState == newState) {
       // No change in state, return.
@@ -1213,63 +1245,56 @@ let Phone = {
     this.radioState = newState;
   },
 
   onCurrentCalls: function onCurrentCalls(newCalls) {
     // Go through the calls we currently have on file and see if any of them
     // changed state. Remove them from the newCalls map as we deal with them
     // so that only new calls remain in the map after we're done.
     for each (let currentCall in this.currentCalls) {
-      let callIndex = currentCall.index;
       let newCall;
       if (newCalls) {
-        newCall = newCalls[callIndex];
-        delete newCalls[callIndex];
+        newCall = newCalls[currentCall.callIndex];
+        delete newCalls[currentCall.callIndex];
       }
 
-      if (!newCall) {
-        // Call is no longer reported by the radio. Send disconnected
-        // state change.
-        this.sendDOMMessage({type:      "callstatechange",
-                             callState:  DOM_CALL_READYSTATE_DISCONNECTED,
-                             callIndex:  callIndex,
-                             number:     currentCall.number,
-                             name:       currentCall.name});
-        delete this.currentCalls[callIndex];
-        continue;
+      if (newCall) {
+        // Call is still valid.
+        if (newCall.state != currentCall.state) {
+          // State has changed.
+          currentCall.state = newCall.state;
+          this._handleChangedCallState(currentCall);
+        }
       }
-
-      if (newCall.state == currentCall.state) {
-        continue;
+      else {
+        // Call is no longer reported by the radio. Remove from our map and
+        // send disconnected state change.
+        delete this.currentCalls[currentCall.callIndex];
+        this._handleDisconnectedCall(currentCall);
       }
-
-      this._handleChangedCallState(newCall);
     }
 
     // Go through any remaining calls that are new to us.
     for each (let newCall in newCalls) {
       if (newCall.isVoice) {
+        // Format international numbers appropriately.
+        if (newCall.number &&
+            newCall.toa == TOA_INTERNATIONAL &&
+            newCall.number[0] != "+") {
+          newCall.number = "+" + newCall.number;
+        }
+        // Add to our map.
+        this.currentCalls[newCall.callIndex] = newCall;
         this._handleChangedCallState(newCall);
       }
     }
-  },
 
-  _handleChangedCallState: function handleChangedCallState(newCall) {
-    // Format international numbers appropriately.
-    if (newCall.number &&
-        newCall.toa == TOA_INTERNATIONAL &&
-        newCall.number[0] != "+") {
-      newCall.number = "+" + newCall.number;
-    }
-    this.currentCalls[newCall.index] = newCall;
-    this.sendDOMMessage({type:      "callstatechange",
-                         callState: RIL_TO_DOM_CALL_STATE[newCall.state],
-                         callIndex: newCall.index,
-                         number:    newCall.number,
-                         name:      newCall.name});
+    // Update our mute status. If there is anything in our currentCalls map then
+    // we know it's a voice call and we should leave audio on.
+    this.muted = Object.getOwnPropertyNames(this.currentCalls).length == 0;
   },
 
   onCallStateChanged: function onCallStateChanged() {
     RIL.getCurrentCalls();
   },
 
   onCallRing: function onCallRing(info) {
     // For now we don't need to do anything here because we'll also get a
@@ -1443,16 +1468,28 @@ let Phone = {
     if (DEBUG) debug("Requesting phone state");
     RIL.getRegistrationState();
     RIL.getGPRSRegistrationState(); //TODO only GSM
     RIL.getOperator();
     RIL.getNetworkSelectionMode();
   },
 
   /**
+   * Get a list of current voice calls.
+   */
+  enumerateCalls: function enumerateCalls() {
+    if (DEBUG) debug("Sending all current calls");
+    let calls = [];
+    for each (let call in this.currentCalls) {
+      calls.push(call);
+    }
+    this.sendDOMMessage({type: "enumerateCalls", calls: calls});
+  },
+
+  /**
    * Dial the phone.
    *
    * @param number
    *        String containing the number to dial.
    */
   dial: function dial(options) {
     RIL.dial(options.number, 0, 0);
   },
@@ -1492,39 +1529,47 @@ let Phone = {
    */
   hangUp: function hangUp(options) {
     //TODO need to check whether call is holding/waiting/background
     // and then use REQUEST_HANGUP_WAITING_OR_BACKGROUND
     RIL.hangUp(options.callIndex);
   },
 
   /**
-   * Mute or unmute the radio.
+   * Answer an incoming call.
    *
-   * @param mute
-   *        Boolean to indicate whether to mute or unmute the radio.
+   * @param callIndex
+   *        Call index of the call to answer.
    */
-  setMute: function setMute(options) {
-    //TODO need to check whether call is holding/waiting/background
-    // and then use REQUEST_HANGUP_WAITING_OR_BACKGROUND
-    RIL.setMute(options.mute);
-  },
-
-  /**
-   * Answer an incoming call.
-   */
-  answerCall: function answerCall() {
-    RIL.answerCall();
+  answerCall: function answerCall(options) {
+    // Check for races. Since we dispatched the incoming call notification the
+    // incoming call may have changed. The main thread thinks that it is
+    // answering the call with the given index, so only answer if that is still
+    // incoming.
+    let call = this.currentCalls[options.callIndex];
+    if (call && call.state == CALL_STATE_INCOMING) {
+      RIL.answerCall();
+    }
   },
 
   /**
    * Reject an incoming call.
+   *
+   * @param callIndex
+   *        Call index of the call to reject.
    */
-  rejectCall: function rejectCall() {
-    RIL.rejectCall();
+  rejectCall: function rejectCall(options) {
+    // Check for races. Since we dispatched the incoming call notification the
+    // incoming call may have changed. The main thread thinks that it is
+    // rejecting the call with the given index, so only reject if that is still
+    // incoming.
+    let call = this.currentCalls[options.callIndex];
+    if (call && call.state == CALL_STATE_INCOMING) {
+      RIL.rejectCall();
+    }
   },
 
   /**
    * Send an SMS.
    *
    * @param number
    *        String containing the recipient number.
    * @param body
--- a/dom/tests/mochitest/geolocation/Makefile.in
+++ b/dom/tests/mochitest/geolocation/Makefile.in
@@ -52,16 +52,17 @@ include $(topsrcdir)/config/rules.mk
 		test_clearWatch.html \
 		test_clearWatch_invalid.html \
 		test_manyCurrentConcurrent.html \
 		test_manyCurrentSerial.html \
 		test_manyWatchConcurrent.html \
 		test_manyWatchSerial.html \
 		test_manyWindows.html \
 		test_optional_api_params.html \
+		test_shutdown.html \
 		test_windowClose.html \
 		test_timerRestartWatch.html \
 		test_worseAccuracyDoesNotBlockCallback.html \
 		geolocation.html \
 		geolocation_common.js  \
 		network_geolocation.sjs \
 		windowTest.html \
 		$(NULL)
--- a/dom/tests/mochitest/geolocation/geolocation_common.js
+++ b/dom/tests/mochitest/geolocation/geolocation_common.js
@@ -59,16 +59,23 @@ function worse_geolocationProvider()
 
 function resume_geolocationProvider()
 {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
   prefs.setCharPref("geo.wifi.uri", "http://mochi.test:8888/tests/dom/tests/mochitest/geolocation/network_geolocation.sjs");
 }
 
+function delay_geolocationProvider(delay)
+{
+  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+  var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
+  prefs.setCharPref("geo.wifi.uri", "http://mochi.test:8888/tests/dom/tests/mochitest/geolocation/network_geolocation.sjs?delay=" + delay);
+}
+
 function check_geolocation(location) {
 
   ok(location, "Check to see if this location is non-null");
 
   ok("timestamp" in location, "Check to see if there is a timestamp");
 
   // eventually, coords may be optional (eg, when civic addresses are supported)
   ok("coords" in location, "Check to see if this location has a coords");
--- a/dom/tests/mochitest/geolocation/network_geolocation.sjs
+++ b/dom/tests/mochitest/geolocation/network_geolocation.sjs
@@ -26,16 +26,17 @@ function getPosition(action)
       lng: -122.08769,
     },
     accuracy: (action == "worse-accuracy") ? 100 : 42,
   };
   
   return JSON.stringify(response);
 }
 
+var timer;
 function handleRequest(request, response)
 {
   var params = parseQueryString(request.queryString);
 
   if (params.action == "stop-responding") {
       return;
   }
 
@@ -49,14 +50,24 @@ function handleRequest(request, response
 
     for (var i=0; i< len; i++) {
         var c = Math.floor(Math.random() * chars.length);
         position += chars.substring(c, c+1);
     }
   }
 
   var response;
+  response.processAsync();
   response.setStatusLine("1.0", 200, "OK");
   response.setHeader("Cache-Control", "no-cache", false);
   response.setHeader("Content-Type", "aplication/x-javascript", false);
-  response.write(position);
+
+  var delay = 0;
+  if ('delay' in params) {
+    delay = params.delay;
+  }
+  timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
+  timer.initWithCallback(function() {
+    response.write(position);
+    response.finish();
+  }, delay, timer.TYPE_ONE_SHOT);
 }
 
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/geolocation/test_shutdown.html
@@ -0,0 +1,58 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=716127
+-->
+<head>
+  <title>Test for getCurrentPosition </title>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="geolocation_common.js"></script>
+
+<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=716127">Mozilla Bug 716127</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+
+SimpleTest.waitForExplicitFinish();
+
+resume_geolocationProvider();
+force_prompt(true);
+
+function successCallback(position) {
+  check_geolocation(position);
+
+  SpecialPowers.pushPrefEnv({'set': [['geo.timeout', 100]]}, function() {
+      delay_geolocationProvider(1000);
+      force_prompt(true);
+      navigator.geolocation.getCurrentPosition(success2, handle_error, {maximumAge: 0});
+  });
+}
+
+function errorCallback() {
+  ok(false, "unexpected error");
+  SimpleTest.finish();
+}
+
+navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
+
+function success2(position) {
+  check_geolocation(position);
+  reset_prompt();
+  SimpleTest.finish();
+}
+
+function handle_error() {
+  ok(false, "geolocation provider should not have timed out");
+  SimpleTest.finish();
+}
+</script>
+</pre>
+</body>
+</html>
+
--- a/dom/wifi/nsWifiWorker.js
+++ b/dom/wifi/nsWifiWorker.js
@@ -815,20 +815,20 @@ function nsWifiWorker() {
   debug("Wifi starting");
 }
 
 nsWifiWorker.prototype = {
   classID:   WIFIWORKER_CID,
   classInfo: XPCOMUtils.generateCI({classID: WIFIWORKER_CID,
                                     contractID: WIFIWORKER_CONTRACTID,
                                     classDescription: "WifiWorker",
-                                    interfaces: [Ci.nsIRadioWorker,
+                                    interfaces: [Ci.nsIWorkerHolder,
                                                  Ci.nsIWifi]}),
 
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIRadioWorker,
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsIWorkerHolder,
                                          Ci.nsIWifi]),
 
   setWifiEnabled: function(enable) {
     WifiManager.setWifiEnabled(enable, function (ok) {
       debug(ok);
     });
   },
 
--- a/editor/libeditor/text/tests/test_bug596001.html
+++ b/editor/libeditor/text/tests/test_bug596001.html
@@ -41,16 +41,15 @@ function testTab(prefix, callback) {
       callback();
     },
     callback
   );
 }
 
 testTab("", function() {
   testTab("foo", function() {
-    SimpleTest.finish();
   });
 });
 
 </script>
 </pre>
 </body>
 </html>
--- a/embedding/android/GeckoAppShell.java
+++ b/embedding/android/GeckoAppShell.java
@@ -273,17 +273,17 @@ public class GeckoAppShell
         return retVal;
     }
 
     // java-side stuff
     public static void loadGeckoLibs(String apkName) {
         // The package data lib directory isn't placed in ld.so's
         // search path, so we have to manually load libraries that
         // libxul will depend on.  Not ideal.
-        System.loadLibrary("mozutils");
+        System.loadLibrary("mozglue");
         GeckoApp geckoApp = GeckoApp.mAppContext;
         String homeDir;
         if (Build.VERSION.SDK_INT < 8 ||
             geckoApp.getApplication().getPackageResourcePath().startsWith("/data") ||
             geckoApp.getApplication().getPackageResourcePath().startsWith("/system")) {
             File home = geckoApp.getFilesDir();
             homeDir = home.getPath();
             // handle the application being moved to phone from sdcard
--- a/extensions/spellcheck/hunspell/src/README.hunspell
+++ b/extensions/spellcheck/hunspell/src/README.hunspell
@@ -31,17 +31,17 @@
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 ******* END LICENSE BLOCK *******
 
 Hunspell Version:   1.3.2
-Additional Patches: 694002, 710967
+Additional Patches: 694002, 710967, 710940
 
 Hunspell Author: László Németh
 MySpell Author: Kevin Hendricks & David Einstein
 
 Hunspell is a spell checker and morphological analyser library. Hunspell
 is based on OpenOffice.org's Myspell. Documentation, tests, and examples
 are available at http://hunspell.sourceforge.net.
 
--- a/extensions/spellcheck/hunspell/src/csutil.cpp
+++ b/extensions/spellcheck/hunspell/src/csutil.cpp
@@ -5518,39 +5518,44 @@ struct cs_info * get_current_cs(const ch
 
   return ccs;
 }
 #else
 // XXX This function was rewritten for mozilla. Instead of storing the
 // conversion tables static in this file, create them when needed
 // with help the mozilla backend.
 struct cs_info * get_current_cs(const char * es) {
-  struct cs_info *ccs;
+  struct cs_info *ccs = new cs_info[256];
+  // Initialze the array with dummy data so that we wouldn't need
+  // to return null in case of failures.
+  for (int i = 0; i <= 0xff; ++i) {
+    ccs[i].ccase = false;
+    ccs[i].clower = i;
+    ccs[i].cupper = i;
+  }
 
   nsCOMPtr<nsIUnicodeEncoder> encoder; 
   nsCOMPtr<nsIUnicodeDecoder> decoder; 
 
   nsresult rv;
   nsCOMPtr<nsICharsetConverterManager> ccm = do_GetService(kCharsetConverterManagerCID, &rv);
   if (NS_FAILED(rv))
-    return nsnull;
+    return ccs;
 
   rv = ccm->GetUnicodeEncoder(es, getter_AddRefs(encoder));
   if (NS_FAILED(rv))
-    return nsnull;
+    return ccs;
   encoder->SetOutputErrorBehavior(encoder->kOnError_Signal, nsnull, '?');
   rv = ccm->GetUnicodeDecoder(es, getter_AddRefs(decoder));
   if (NS_FAILED(rv))
-    return nsnull;
+    return ccs;
   decoder->SetInputErrorBehavior(decoder->kOnError_Signal);
 
   if (NS_FAILED(rv))
-    return nsnull;
-
-  ccs = new cs_info[256];
+    return ccs;
 
   for (unsigned int i = 0; i <= 0xff; ++i) {
     bool success = false;
     // We want to find the upper/lowercase equivalents of each byte
     // in this 1-byte character encoding.  Call our encoding/decoding
     // APIs separately for each byte since they may reject some of the
     // bytes, and we want to handle errors separately for each byte.
     char lower, upper;
--- a/gfx/layers/opengl/LayerManagerOGLProgram.h
+++ b/gfx/layers/opengl/LayerManagerOGLProgram.h
@@ -54,65 +54,16 @@ namespace layers {
   do {                                                                  \
     NS_ASSERTION(mGL->GetUserData(&sCurrentProgramKey) == this, \
                  "SetUniform with wrong program active!");              \
   } while (0)
 #else
 #define ASSERT_THIS_PROGRAM
 #endif
 
-struct UniformValue {
-  UniformValue() {
-    memset(this, 0, sizeof(UniformValue));
-  }
-
-  void setInt(const int i) {
-    value.i[0] = i;
-  }
-
-  void setFloat(const float f) {
-    value.f[0] = f;
-  }
-
-  void setFloatN(const float *f, const int n) {
-    memcpy(value.f, f, sizeof(float)*n);
-  }
-
-  void setColor(const gfxRGBA& c) {
-    value.f[0] = float(c.r);
-    value.f[1] = float(c.g);
-    value.f[2] = float(c.b);
-    value.f[3] = float(c.a);
-  }
-
-  bool equalsInt(const int i) {
-    return i == value.i[0];
-  }
-
-  bool equalsFloat(const float f) {
-    return f == value.f[0];
-  }
-
-  bool equalsFloatN(const float *f, const int n) {
-    return memcmp(f, value.f, sizeof(float)*n) == 0;
-  }
-
-  bool equalsColor(const gfxRGBA& c) {
-    return value.f[0] == float(c.r) &&
-      value.f[1] == float(c.g) &&
-      value.f[2] == float(c.b) &&
-      value.f[3] == float(c.a);
-  }
-
-  union {
-    int i[1];
-    float f[16];
-  } value;
-};
-
 class LayerManagerOGLProgram {
 protected:
 #ifdef CHECK_CURRENT_PROGRAM
   static int sCurrentProgramKey;
 #endif
 
 public:
   typedef mozilla::gl::GLContext GLContext;
@@ -141,91 +92,66 @@ public:
     mGL->fUseProgram(mProgram);
 #if CHECK_CURRENT_PROGRAM
     mGL->SetUserData(&sCurrentProgramKey, this);
 #endif
   }
 
   void SetUniform(GLuint aUniform, float aFloatValue) {
     ASSERT_THIS_PROGRAM;
-
     if (aUniform == GLuint(-1))
       return;
-
-    if (!mUniformValues[aUniform].equalsFloat(aFloatValue)) {
-      mGL->fUniform1f(aUniform, aFloatValue);
-      mUniformValues[aUniform].setFloat(aFloatValue);
-    }
+    mGL->fUniform1f(aUniform, aFloatValue);
   }
 
   void SetUniform(GLuint aUniform, const gfxRGBA& aColor) {
     ASSERT_THIS_PROGRAM;
-
     if (aUniform == GLuint(-1))
       return;
-
-    if (!mUniformValues[aUniform].equalsColor(aColor)) {
-      mGL->fUniform4f(aUniform, float(aColor.r), float(aColor.g), float(aColor.b), float(aColor.a));
-      mUniformValues[aUniform].setColor(aColor);
-    }
+    mGL->fUniform4f(aUniform, float(aColor.r), float(aColor.g), float(aColor.b), float(aColor.a));
   }
 
   void SetUniform(GLuint aUniform, int aLength, float *aFloatValues) {
     ASSERT_THIS_PROGRAM;
 
     if (aUniform == GLuint(-1))
       return;
 
-    if (!mUniformValues[aUniform].equalsFloatN(aFloatValues, aLength)) {
-      if (aLength == 1) {
-        mGL->fUniform1fv(aUniform, 1, aFloatValues);
-      } else if (aLength == 2) {
-        mGL->fUniform2fv(aUniform, 1, aFloatValues);
-      } else if (aLength == 3) {
-        mGL->fUniform3fv(aUniform, 1, aFloatValues);
-      } else if (aLength == 4) {
-        mGL->fUniform4fv(aUniform, 1, aFloatValues);
-      } else {
-        NS_NOTREACHED("Bogus aLength param");
-      }
-      mUniformValues[aUniform].setFloatN(aFloatValues, aLength);
+    if (aLength == 1) {
+      mGL->fUniform1fv(aUniform, 1, aFloatValues);
+    } else if (aLength == 2) {
+      mGL->fUniform2fv(aUniform, 1, aFloatValues);
+    } else if (aLength == 3) {
+      mGL->fUniform3fv(aUniform, 1, aFloatValues);
+    } else if (aLength == 4) {
+      mGL->fUniform4fv(aUniform, 1, aFloatValues);
+    } else {
+      NS_NOTREACHED("Bogus aLength param");
     }
   }
 
   void SetUniform(GLuint aUniform, GLint aIntValue) {
     ASSERT_THIS_PROGRAM;
-
     if (aUniform == GLuint(-1))
       return;
-
-    if (!mUniformValues[aUniform].equalsInt(aIntValue)) {
-      mGL->fUniform1i(aUniform, aIntValue);
-      mUniformValues[aUniform].setInt(aIntValue);
-    }
+    mGL->fUniform1i(aUniform, aIntValue);
   }
 
   void SetMatrixUniform(GLuint aUniform, const float *aFloatValues) {
     ASSERT_THIS_PROGRAM;
-
     if (aUniform == GLuint(-1))
       return;
-
-    if (!mUniformValues[aUniform].equalsFloatN(aFloatValues, 16)) {
-      mGL->fUniformMatrix4fv(aUniform, 1, false, aFloatValues);
-      mUniformValues[aUniform].setFloatN(aFloatValues, 16);
-    }
+    mGL->fUniformMatrix4fv(aUniform, 1, false, aFloatValues);
   }
 
 protected:
   nsRefPtr<GLContext> mGL;
 
   GLuint mProgram;
 
-  nsTArray<UniformValue> mUniformValues;
-
   GLint CreateShader(GLenum aShaderType,
                      const char *aShaderSource)
   {
     GLint success, len = 0;
 
     GLint sh = mGL->fCreateShader(aShaderType);
     mGL->fShaderSource(sh, 1, (const GLchar**)&aShaderSource, NULL);
     mGL->fCompileShader(sh);
@@ -317,44 +243,16 @@ protected:
     mGL->fDeleteShader(fragmentShader);
 
     if (!success) {
       mGL->fDeleteProgram(mProgram);
       mProgram = 0;
       return false;
     }
 
-    // Now query uniforms, so that we can initialize mUniformValues
-    // note that for simplicity, mUniformLocations is indexed by the
-    // uniform -location-, and not the uniform -index-.  This means
-    // that it might have a bunch of unused space as locations dense
-    // like indices are; however, there are unlikely to be enough for
-    // our shaders for this to become a significant memory issue.
-    GLint count, maxnamelen;
-    nsCAutoString uname;
-    GLint maxloc = 0;
-    mGL->fGetProgramiv(mProgram, LOCAL_GL_ACTIVE_UNIFORMS, &count);
-    mGL->fGetProgramiv(mProgram, LOCAL_GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxnamelen);
-    uname.SetCapacity(maxnamelen);
-    for (int i = 0; i < count; ++i) {
-      GLsizei namelen;
-      GLint usize;
-      GLenum utype;
-
-      mGL->fGetActiveUniform(mProgram, i, maxnamelen, &namelen, &usize, &utype, uname.BeginWriting());
-      uname.SetLength(namelen);
-      GLint uloc = mGL->fGetUniformLocation(mProgram, uname.BeginReading());
-      if (maxloc < uloc)
-        maxloc = uloc;
-    }
-
-    // Note +1: the last valid index needs to be 'maxloc', so we need
-    // to set the array length to 1 more than that.
-    mUniformValues.SetLength(maxloc+1);
-    
     return true;
   }
 
   void GetAttribLocations(const char **aAttribNames,
                           GLint *aAttribLocations)
   {
     NS_ASSERTION(mProgram != 0, "GetAttribLocations called with no program!");
 
@@ -378,21 +276,21 @@ protected:
  * A LayerProgram is the base of all further LayerPrograms.
  *
  * It has a number of attributes and uniforms common to all layer programs.
  *
  * Attribute inputs:
  *   aVertexCoord  - vertex coordinate
  *
  * Uniforms:
- *   uTransformMatrix - a transform matrix
- *   uQuadTransform
- *   uProjMatrix      - projection matrix
- *   uOffset          - a vec4 offset to apply to the transformed coordinates
- *   uLayerOpacity    - a float, the layer opacity (final colors will be multiplied by this)
+ *   uLayerTransform     - a transform matrix
+ *   uLayerQuadTransform
+ *   uMatrixProj         - projection matrix
+ *   uRenderTargetOffset - a vec4 offset to apply to the transformed coordinates
+ *   uLayerOpacity       - a float, the layer opacity (final colors will be multiplied by this)
  */
 
 class LayerProgram  :
   public LayerManagerOGLProgram
 {
 public:
   enum {
     TransformMatrixUniform = 0,
@@ -758,17 +656,17 @@ public:
 };
 
 /*
  * A CopyProgram is an OpenGL program that copies a 4-channel texture
  * to the destination, making no attempt to transform any incoming
  * vertices.  It has the following attributes and uniforms:
  *
  * Attribute inputs:
- *   aVertex       - vertex coordinate
+ *   aVertexCoord  - vertex coordinate
  *   aTexCoord     - texture coordinate
  *
  * Uniforms:
  *   uTexture      - 2D texture unit which to sample
  */
 
 class CopyProgram :
   public LayerManagerOGLProgram
--- a/intl/chardet/public/Makefile.in
+++ b/intl/chardet/public/Makefile.in
@@ -45,20 +45,18 @@ include $(DEPTH)/config/autoconf.mk
 MODULE		= chardet
 
 XPIDLSRCS       = \
                 nsIDocumentCharsetInfo.idl \
                 nsIDocCharset.idl \
 		$(NULL)
 
 EXPORTS		= \
-		nsCharsetDetectionAdaptorCID.h \
 		nsDetectionConfident.h \
 		nsDocumentCharsetInfoCID.h \
-		nsICharsetDetectionAdaptor.h \
 		nsICharsetDetectionObserver.h \
 		nsICharsetDetector.h \
 		nsIStringCharsetDetector.h \
 		nsXMLEncodingCID.h \
 		$(NULL)
 
 include $(topsrcdir)/config/rules.mk
 
deleted file mode 100644
--- a/intl/chardet/public/nsCharsetDetectionAdaptorCID.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1999
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#ifndef nsCDETAdaptorCID_h__
-#define nsCDETAdaptorCID_h__
-
-#include "nscore.h"
-
-#define NS_CHARSET_DETECTION_ADAPTOR_CONTRACTID "@mozilla.org/intl/charsetdetectionadaptor;1"
-
-// {12BB8F17-2389-11d3-B3BF-00805F8A6670}
-#define NS_CHARSET_DETECTION_ADAPTOR_CID \
-{ 0x12bb8f17, 0x2389, 0x11d3, { 0xb3, 0xbf, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0x70 } }
-
-
-#endif // nsCDETAdaptorCID_h__
deleted file mode 100644
--- a/intl/chardet/public/nsICharsetDetectionAdaptor.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1999
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-#ifndef nsICDETAdaptor_h__
-#define nsICDETAdaptor_h__
-#include "nsISupports.h"
-
-class nsICharsetDetector;
-class nsIWebShellServices;
-class nsIDocument;
-class nsIParser;
-
-// {12BB8F13-2389-11d3-B3BF-00805F8A6670}
-#define NS_ICHARSETDETECTIONADAPTOR_IID \
-{ 0x12bb8f13, 0x2389, 0x11d3, { 0xb3, 0xbf, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0x70 } }
-
-/*  
-   This interface is defined to be serverd as an Adaptor between
-   nsIWebShellServices, nsICharsetDetector and nsIParserFilter
-
-   It make the nsICharsetDetector implementation independent from the
-   nsIParserFilter and nsIWebShellServices
- */
-
-class nsICharsetDetectionAdaptor : public nsISupports {
-public:  
-  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICHARSETDETECTIONADAPTOR_IID)
-  /*   
-     Initialize it by setup the nsICharsetDetector and the 
-     nsIWebShellServices
-   */
-  NS_IMETHOD Init(nsIWebShellServices* aDocShell, nsICharsetDetector *aDetector, 
-                  nsIDocument* aDocument, nsIParser* aParser, 
-                  const char* aCharset, const char* aCommand=nsnull) = 0;
-};
-
-NS_DEFINE_STATIC_IID_ACCESSOR(nsICharsetDetectionAdaptor,
-                              NS_ICHARSETDETECTIONADAPTOR_IID)
-
-#endif /* nsICDETAdaptor_h__ */
--- a/intl/chardet/src/nsCharDetConstructors.h
+++ b/intl/chardet/src/nsCharDetConstructors.h
@@ -44,23 +44,21 @@
 #ifndef nsCharDetConstructors_h__
 #define nsCharDetConstructors_h__
 
 // chardet
 #include "nsISupports.h"
 #include "nsICharsetDetector.h"
 #include "nsICharsetAlias.h"
 #include "nsDocumentCharsetInfo.h"
-#include "nsICharsetDetectionAdaptor.h"
 #include "nsICharsetDetectionObserver.h"
 #include "nsIStringCharsetDetector.h"
 #include "nsCyrillicDetector.h"
 #include "nsDocumentCharsetInfoCID.h"
 #include "nsXMLEncodingCID.h"
-#include "nsCharsetDetectionAdaptorCID.h"
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDocumentCharsetInfo)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsRUProbDetector)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsUKProbDetector)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsRUStringProbDetector)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsUKStringProbDetector)
 
 #ifdef INCLUDE_DBGDETECTOR
--- a/intl/chardet/src/nsCharDetDll.h
+++ b/intl/chardet/src/nsCharDetDll.h
@@ -38,11 +38,10 @@
 #ifndef nsCharDetDll_h__
 #define nsCharDetDll_h__
 
 #include "prtypes.h"
 #include "nsIFactory.h"
 #include "nsICharsetDetector.h"
 #include "nsICharsetDetectionObserver.h"
 #include "nsIStringCharsetDetector.h"
-#include "nsICharsetDetectionAdaptor.h"
 
 #endif /* nsCharDetDll_h__ */
--- a/ipc/app/MozillaRuntimeMainAndroid.cpp
+++ b/ipc/app/MozillaRuntimeMainAndroid.cpp
@@ -44,17 +44,17 @@
 int
 main(int argc, char* argv[])
 {
     // Check for the absolute minimum number of args we need to move
     // forward here. We expect the last arg to be the child process type.
     if (argc < 2)
         return 1;
 
-    void *mozloader_handle = dlopen("libmozutils.so", RTLD_LAZY);
+    void *mozloader_handle = dlopen("libmozglue.so", RTLD_LAZY);
     if (!mozloader_handle) {
       __android_log_print(ANDROID_LOG_ERROR, "GeckoChildLoad",
                           "Couldn't load mozloader because %s", dlerror());
         return 1;
     }
 
     typedef int (*ChildProcessInit_t)(int, char**);
     ChildProcessInit_t fChildProcessInit =
--- a/js/src/build/autoconf/gcc-pr49911.m4
+++ b/js/src/build/autoconf/gcc-pr49911.m4
@@ -51,17 +51,17 @@ int main(void) {
 }
 ], true,
    ac_have_gcc_pr49911="yes",
    true)
 CXXFLAGS="$_SAVE_CXXFLAGS"
 
 AC_LANG_RESTORE
 
-if test "$ac_have_gcc_pr49911" == "yes"; then
+if test "$ac_have_gcc_pr49911" = "yes"; then
    AC_MSG_RESULT(yes)
    CFLAGS="$CFLAGS -fno-tree-vrp"
    CXXFLAGS="$CXXFLAGS -fno-tree-vrp"
 else
    AC_MSG_RESULT(no)
 fi
 fi
 ])
--- a/js/src/config/autoconf.mk.in
+++ b/js/src/config/autoconf.mk.in
@@ -306,18 +306,18 @@ MOZ_OS2_HIGH_MEMORY = @MOZ_OS2_HIGH_MEMO
 
 MOZILLA_OFFICIAL = @MOZILLA_OFFICIAL@
 
 # Win32 options
 MOZ_BROWSE_INFO	= @MOZ_BROWSE_INFO@
 MOZ_TOOLS_DIR	= @MOZ_TOOLS_DIR@
 MOZ_QUANTIFY	= @MOZ_QUANTIFY@
 MSMANIFEST_TOOL = @MSMANIFEST_TOOL@
-MOZ_UTILS_LDFLAGS = @MOZ_UTILS_LDFLAGS@
-MOZ_UTILS_PROGRAM_LDFLAGS = @MOZ_UTILS_PROGRAM_LDFLAGS@
+MOZ_GLUE_LDFLAGS = @MOZ_GLUE_LDFLAGS@
+MOZ_GLUE_PROGRAM_LDFLAGS = @MOZ_GLUE_PROGRAM_LDFLAGS@
 
 # Codesighs tools option, enables win32 mapfiles.
 MOZ_MAPINFO	= @MOZ_MAPINFO@
 
 QEMU_CANT_RUN_JS_SHELL = @QEMU_CANT_RUN_JS_SHELL@
 
 MACOS_SDK_DIR	= @MACOS_SDK_DIR@
 NEXT_ROOT	= @NEXT_ROOT@
--- a/js/src/config/config.mk
+++ b/js/src/config/config.mk
@@ -238,23 +238,23 @@ endif # NS_TRACE_MALLOC
 
 endif # MOZ_DEBUG
 
 # We don't build a static CRT when building a custom CRT,
 # it appears to be broken. So don't link to jemalloc if
 # the Makefile wants static CRT linking.
 ifeq ($(MOZ_MEMORY)_$(USE_STATIC_LIBS),1_1)
 # Disable default CRT libs and add the right lib path for the linker
-MOZ_UTILS_LDFLAGS=
+MOZ_GLUE_LDFLAGS=
 endif
 
 endif # WINNT && !GNU_CC
 
-ifndef MOZ_UTILS_PROGRAM_LDFLAGS
-MOZ_UTILS_PROGRAM_LDFLAGS=$(MOZ_UTILS_LDFLAGS)
+ifndef MOZ_GLUE_PROGRAM_LDFLAGS
+MOZ_GLUE_PROGRAM_LDFLAGS=$(MOZ_GLUE_LDFLAGS)
 endif
 
 #
 # Build using PIC by default
 #
 _ENABLE_PIC=1
 
 # Determine if module being compiled is destined
--- a/js/src/config/rules.mk
+++ b/js/src/config/rules.mk
@@ -787,17 +787,17 @@ endif # EXPORT_LIBRARY
 endif # LIBRARY_NAME
 
 ifneq (,$(filter-out %.$(LIB_SUFFIX),$(SHARED_LIBRARY_LIBS)))
 $(error SHARED_LIBRARY_LIBS must contain .$(LIB_SUFFIX) files only)
 endif
 
 # Create dependencies on static (and shared EXTRA_DSO_LIBS) libraries
 DO_EXPAND_LIBS = $(foreach f,$(1),$(if $(filter %.$(LIB_SUFFIX),$(f)),$(if $(wildcard $(f).$(LIBS_DESC_SUFFIX)),$(f).$(LIBS_DESC_SUFFIX),$(if $(wildcard $(f)),$(f)))))
-LIBS_DEPS = $(call DO_EXPAND_LIBS,$(filter %.$(LIB_SUFFIX),$(LIBS) $(if $(PROGRAM)$(SIMPLE_PROGRAMS),$(MOZ_UTILS_PROGRAM_LDFLAGS))))
+LIBS_DEPS = $(call DO_EXPAND_LIBS,$(filter %.$(LIB_SUFFIX),$(LIBS) $(if $(PROGRAM)$(SIMPLE_PROGRAMS),$(MOZ_GLUE_PROGRAM_LDFLAGS))))
 SHARED_LIBRARY_LIBS_DEPS = $(call DO_EXPAND_LIBS,$(SHARED_LIBRARY_LIBS))
 HOST_LIBS_DEPS = $(filter %.$(LIB_SUFFIX),$(HOST_LIBS))
 DSO_LDOPTS_DEPS = $(call DO_EXPAND_LIBS,$(EXTRA_DSO_LIBS) $(filter %.$(LIB_SUFFIX), $(EXTRA_DSO_LDOPTS)))
 
 # Dependencies which, if modified, should cause everything to rebuild
 GLOBAL_DEPS += Makefile Makefile.in $(DEPTH)/config/autoconf.mk $(topsrcdir)/config/config.mk
 
 ##############################################
@@ -888,17 +888,17 @@ alltags:
 
 #
 # PROGRAM = Foo
 # creates OBJS, links with LIBS to create Foo
 #
 $(PROGRAM): $(PROGOBJS) $(LIBS_DEPS) $(EXTRA_DEPS) $(EXE_DEF_FILE) $(RESFILE) $(GLOBAL_DEPS)
 	@$(RM) $@.manifest
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
-	$(EXPAND_LD) -NOLOGO -OUT:$@ -PDB:$(LINK_PDBFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
+	$(EXPAND_LD) -NOLOGO -OUT:$@ -PDB:$(LINK_PDBFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
 ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		if test -f "$(srcdir)/$@.manifest"; then \
 			echo "Embedding manifest from $(srcdir)/$@.manifest and $@.manifest"; \
 			mt.exe -NOLOGO -MANIFEST "$(win_srcdir)/$@.manifest" $@.manifest -OUTPUTRESOURCE:$@\;1; \
 		else \
 			echo "Embedding manifest from $@.manifest"; \
 			mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
@@ -910,20 +910,20 @@ ifdef MSMANIFEST_TOOL
 endif	# MSVC with manifest tool
 ifdef MOZ_PROFILE_GENERATE
 # touch it a few seconds into the future to work around FAT's
 # 2-second granularity
 	touch -t `date +%Y%m%d%H%M.%S -d "now+5seconds"` pgo.relink
 endif
 else # !WINNT || GNU_CC
 ifeq ($(CPP_PROG_LINK),1)
-	$(EXPAND_CCC) -o $@ $(CXXFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(WRAP_LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
+	$(EXPAND_CCC) -o $@ $(CXXFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(WRAP_LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
 	@$(call CHECK_STDCXX,$@)
 else # ! CPP_PROG_LINK
-	$(EXPAND_CC) -o $@ $(CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
+	$(EXPAND_CC) -o $@ $(CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
 endif # CPP_PROG_LINK
 endif # WINNT && !GNU_CC
 
 ifdef ENABLE_STRIP
 	$(STRIP) $@
 endif
 ifdef MOZ_POST_PROGRAM_COMMAND
 	$(MOZ_POST_PROGRAM_COMMAND) $@
@@ -959,29 +959,29 @@ endif
 # in one directory, it assumes everything to compile Foo is in
 # Foo.o (from either Foo.c or Foo.cpp).
 #
 # SIMPLE_PROGRAMS = Foo Bar
 # creates Foo.o Bar.o, links with LIBS to create Foo, Bar.
 #
 $(SIMPLE_PROGRAMS): %$(BIN_SUFFIX): %.$(OBJ_SUFFIX) $(LIBS_DEPS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
-	$(EXPAND_LD) -nologo -out:$@ -pdb:$(LINK_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
+	$(EXPAND_LD) -nologo -out:$@ -pdb:$(LINK_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
 ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
 		rm -f $@.manifest; \
 	fi
 endif	# MSVC with manifest tool
 else
 ifeq ($(CPP_PROG_LINK),1)
-	$(EXPAND_CCC) $(CXXFLAGS) -o $@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS)
+	$(EXPAND_CCC) $(CXXFLAGS) -o $@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS)
 	@$(call CHECK_STDCXX,$@)
 else
-	$(EXPAND_CC) $(CFLAGS) $(OUTOPTION)$@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_UTILS_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS)
+	$(EXPAND_CC) $(CFLAGS) $(OUTOPTION)$@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(WRAP_LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS)
 endif # CPP_PROG_LINK
 endif # WINNT && !GNU_CC
 
 ifdef ENABLE_STRIP
 	$(STRIP) $@
 endif
 ifdef MOZ_POST_PROGRAM_COMMAND
 	$(MOZ_POST_PROGRAM_COMMAND) $@
@@ -1084,20 +1084,20 @@ endif
 $(SHARED_LIBRARY): $(OBJS) $(LOBJS) $(DEF_FILE) $(RESFILE) $(SHARED_LIBRARY_LIBS_DEPS) $(LIBRARY) $(EXTRA_DEPS) $(DSO_LDOPTS_DEPS) $(GLOBAL_DEPS)
 ifndef INCREMENTAL_LINKER
 	$(RM) $@
 endif
 ifdef DTRACE_LIB_DEPENDENT
 ifndef XP_MACOSX
 	dtrace -G -C -s $(MOZILLA_DTRACE_SRC) -o  $(DTRACE_PROBE_OBJ) $(shell $(EXPAND_LIBS) $(MOZILLA_PROBE_LIBS))
 endif
-	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(DTRACE_PROBE_OBJ) $(MOZILLA_PROBE_LIBS) $(RESFILE) $(LDFLAGS) $(MOZ_UTILS_LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
+	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(DTRACE_PROBE_OBJ) $(MOZILLA_PROBE_LIBS) $(RESFILE) $(LDFLAGS) $(MOZ_GLUE_LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
 	@$(RM) $(DTRACE_PROBE_OBJ)
 else # ! DTRACE_LIB_DEPENDENT
-	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(RESFILE) $(LDFLAGS) $(MOZ_UTILS_LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
+	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(RESFILE) $(LDFLAGS) $(MOZ_GLUE_LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
 endif # DTRACE_LIB_DEPENDENT
 	@$(call CHECK_STDCXX,$@)
 
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
 ifdef MSMANIFEST_TOOL
 ifdef EMBED_MANIFEST_AT
 	@if test -f $@.manifest; then \
 		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;$(EMBED_MANIFEST_AT); \
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -537,47 +537,23 @@ if test "$target" != "$host"; then
     AC_TRY_COMPILE([], [return(0);],
 	[ac_cv_prog_hostcxx_works=1 AC_MSG_RESULT([yes])],
 	AC_MSG_ERROR([installation or configuration problem: host compiler $HOST_CXX cannot create executables.]) )
 
     CC=$_SAVE_CC
     CFLAGS=$_SAVE_CFLAGS
     LDFLAGS=$_SAVE_LDFLAGS
 
-    case "$build:$target" in
-      powerpc-apple-darwin8*:i?86-apple-darwin*)
-        dnl The Darwin cross compiler doesn't necessarily point itself at a
-        dnl root that has libraries for the proper architecture, it defaults
-        dnl to the system root.  The libraries in the system root on current
-        dnl versions of PPC OS X 10.4 aren't fat, so these target compiler
-        dnl checks will fail.  Fake a working SDK in that case.
-        _SAVE_CFLAGS=$CFLAGS
-        _SAVE_CXXFLAGS=$CXXLAGS
-        CFLAGS="-isysroot /Developer/SDKs/MacOSX10.5.sdk $CFLAGS"
-        CXXFLAGS="-isysroot /Developer/SDKs/MacOSX10.5.sdk $CXXFLAGS"
-        ;;
-    esac
-
     AC_CHECK_PROGS(CC, $CC "${target_alias}-gcc" "${target}-gcc", :)
     unset ac_cv_prog_CC
     AC_PROG_CC
     AC_CHECK_PROGS(CXX, $CXX "${target_alias}-g++" "${target}-g++", :)
     unset ac_cv_prog_CXX
     AC_PROG_CXX
 
-    case "$build:$target" in
-      powerpc-apple-darwin8*:i?86-apple-darwin*)
-        dnl Revert the changes made above.  From this point on, the target
-        dnl compiler will never be used without applying the SDK to CFLAGS
-        dnl (see --with-macos-sdk below).
-        CFLAGS=$_SAVE_CFLAGS
-        CXXFLAGS=$_SAVE_CXXFLAGS
-        ;;
-    esac
-
     AC_CHECK_PROGS(RANLIB, $RANLIB "${target_alias}-ranlib" "${target}-ranlib", :)
     AC_CHECK_PROGS(AR, $AR "${target_alias}-ar" "${target}-ar", :)
     MOZ_PATH_PROGS(AS, $AS "${target_alias}-as" "${target}-as", :)
     AC_CHECK_PROGS(LD, $LD "${target_alias}-ld" "${target}-ld", :)
     AC_CHECK_PROGS(STRIP, $STRIP "${target_alias}-strip" "${target}-strip", :)
     AC_CHECK_PROGS(WINDRES, $WINDRES "${target_alias}-windres" "${target}-windres", :)
     AC_DEFINE(CROSS_COMPILE)
 
@@ -1137,19 +1113,16 @@ case "$target" in
 *-darwin*)
     if test -n "$_MACOSX_DEPLOYMENT_TARGET" ; then
         dnl Use the specified value
         export MACOSX_DEPLOYMENT_TARGET=$_MACOSX_DEPLOYMENT_TARGET
     else
         dnl No value specified on the command line or in the environment,
         dnl use architecture minimum.
         case "${target_cpu}" in
-          ppc*)
-            export MACOSX_DEPLOYMENT_TARGET=10.5
-            ;;
           i*86)
             export MACOSX_DEPLOYMENT_TARGET=10.5
             ;;
           x86_64)
             export MACOSX_DEPLOYMENT_TARGET=10.6
             ;;
         esac
     fi
@@ -1794,17 +1767,17 @@ dnl ====================================
 if test "$GNU_CC"; then
     MKSHLIB='$(CXX) $(CXXFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -Wl,-h,$@ -o $@'
     MKCSHLIB='$(CC) $(CFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -Wl,-h,$@ -o $@'
     DSO_LDOPTS='-shared'
     if test "$GCC_USE_GNU_LD"; then
         # Don't allow undefined symbols in libraries
         DSO_LDOPTS="$DSO_LDOPTS -Wl,-z,defs"
     fi
-    WARNINGS_AS_ERRORS='-Werror'
+    WARNINGS_AS_ERRORS='-Werror -Wno-error=uninitialized'
     DSO_CFLAGS=''
     DSO_PIC_CFLAGS='-fPIC'
     ASFLAGS="$ASFLAGS -fPIC"
     _MOZ_RTTI_FLAGS_ON=-frtti
     _MOZ_RTTI_FLAGS_OFF=-fno-rtti
 
     # Turn on GNU specific features
     # -Wall - turn on all warnings
@@ -2966,16 +2939,21 @@ fi
 MOZ_ALIGN_OF_TYPE(JS_ALIGN_OF_POINTER, void*, 2 4 8 16)
 MOZ_SIZE_OF_TYPE(JS_BYTES_PER_DOUBLE, double, 6 8 10 12 14)
 
 MOZ_CHECK_HEADERS(endian.h)
 if test "$ac_cv_header_endian_h" = yes; then
     AC_DEFINE(JS_HAVE_ENDIAN_H)
 fi
 
+MOZ_CHECK_HEADERS([machine/endian.h],[],[],[#include <sys/types.h>])
+if test "$ac_cv_header_machine_endian_h" = yes; then
+    AC_DEFINE(JS_HAVE_MACHINE_ENDIAN_H)
+fi
+
 MOZ_CHECK_HEADERS(sys/isa_defs.h)
 if test "$ac_cv_header_sys_isa_defs_h" = yes; then
     AC_DEFINE(JS_HAVE_SYS_ISA_DEFS_H)
 fi
 
 dnl Check for uint and uint_t.
 dnl ========================================================
 AC_MSG_CHECKING(for uint)
@@ -4310,33 +4288,33 @@ if test "$MOZ_MEMORY"; then
   *-netbsd*)
     AC_DEFINE(MOZ_MEMORY_BSD)
     ;;
   *-solaris*)
     AC_DEFINE(MOZ_MEMORY_SOLARIS)
     ;;
   *-mingw*)
     AC_DEFINE(MOZ_MEMORY_WINDOWS)
-    # the interesting bits will get passed down in MOZ_UTILS_LDFLAGS
+    # the interesting bits will get passed down in MOZ_GLUE_LDFLAGS
     ;;
   *)
     AC_MSG_ERROR([--enable-jemalloc not supported on ${target}])
     ;;
   esac
 
   if test "$OS_ARCH" != "Darwin"; then
     dnl NB: this must be kept in sync with jemalloc.h
     AC_DEFINE(HAVE_JEMALLOC_VALLOC)
     AC_DEFINE(HAVE_JEMALLOC_POSIX_MEMALIGN)
     AC_DEFINE(HAVE_JEMALLOC_MEMALIGN)
   fi
 fi
 AC_SUBST(MOZ_MEMORY)
-AC_SUBST(MOZ_UTILS_LDFLAGS)
-AC_SUBST(MOZ_UTILS_PROGRAM_LDFLAGS)
+AC_SUBST(MOZ_GLUE_LDFLAGS)
+AC_SUBST(MOZ_GLUE_PROGRAM_LDFLAGS)
 
 dnl ========================================================
 dnl = Use malloc wrapper lib
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(wrap-malloc,
 [  --enable-wrap-malloc    Wrap malloc calls (gnu linker only)],
     _WRAP_MALLOC=1,
     _WRAP_MALLOC= )
--- a/js/src/ctypes/libffi/aclocal.m4
+++ b/js/src/ctypes/libffi/aclocal.m4
@@ -7359,16 +7359,821 @@ func_append ()
   eval "$[1]=\$$[1]\$[2]"
 }
 
 _LT_EOF
     ;;
   esac
 ])
 
+# ltdl.m4 - Configure ltdl for the target system. -*-Autoconf-*-
+#
+#   Copyright (C) 1999-2006, 2007, 2008 Free Software Foundation, Inc.
+#   Written by Thomas Tanner, 1999
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 17 LTDL_INIT
+
+# LT_CONFIG_LTDL_DIR(DIRECTORY, [LTDL-MODE])
+# ------------------------------------------
+# DIRECTORY contains the libltdl sources.  It is okay to call this
+# function multiple times, as long as the same DIRECTORY is always given.
+AC_DEFUN([LT_CONFIG_LTDL_DIR],
+[AC_BEFORE([$0], [LTDL_INIT])
+_$0($*)
+])# LT_CONFIG_LTDL_DIR
+
+# We break this out into a separate macro, so that we can call it safely
+# internally without being caught accidentally by the sed scan in libtoolize.
+m4_defun([_LT_CONFIG_LTDL_DIR],
+[dnl remove trailing slashes
+m4_pushdef([_ARG_DIR], m4_bpatsubst([$1], [/*$]))
+m4_case(_LTDL_DIR,
+	[], [dnl only set lt_ltdl_dir if _ARG_DIR is not simply `.'
+	     m4_if(_ARG_DIR, [.],
+	             [],
+		 [m4_define([_LTDL_DIR], _ARG_DIR)
+	          _LT_SHELL_INIT([lt_ltdl_dir=']_ARG_DIR['])])],
+    [m4_if(_ARG_DIR, _LTDL_DIR,
+	    [],
+	[m4_fatal([multiple libltdl directories: `]_LTDL_DIR[', `]_ARG_DIR['])])])
+m4_popdef([_ARG_DIR])
+])# _LT_CONFIG_LTDL_DIR
+
+# Initialise:
+m4_define([_LTDL_DIR], [])
+
+
+# _LT_BUILD_PREFIX
+# ----------------
+# If Autoconf is new enough, expand to `${top_build_prefix}', otherwise
+# to `${top_builddir}/'.
+m4_define([_LT_BUILD_PREFIX],
+[m4_ifdef([AC_AUTOCONF_VERSION],
+   [m4_if(m4_version_compare(m4_defn([AC_AUTOCONF_VERSION]), [2.62]),
+	  [-1], [m4_ifdef([_AC_HAVE_TOP_BUILD_PREFIX],
+			  [${top_build_prefix}],
+			  [${top_builddir}/])],
+	  [${top_build_prefix}])],
+   [${top_builddir}/])[]dnl
+])
+
+
+# LTDL_CONVENIENCE
+# ----------------
+# sets LIBLTDL to the link flags for the libltdl convenience library and
+# LTDLINCL to the include flags for the libltdl header and adds
+# --enable-ltdl-convenience to the configure arguments.  Note that
+# AC_CONFIG_SUBDIRS is not called here.  LIBLTDL will be prefixed with
+# '${top_build_prefix}' if available, otherwise with '${top_builddir}/',
+# and LTDLINCL will be prefixed with '${top_srcdir}/' (note the single
+# quotes!).  If your package is not flat and you're not using automake,
+# define top_build_prefix, top_builddir, and top_srcdir appropriately
+# in your Makefiles.
+AC_DEFUN([LTDL_CONVENIENCE],
+[AC_BEFORE([$0], [LTDL_INIT])dnl
+dnl Although the argument is deprecated and no longer documented,
+dnl LTDL_CONVENIENCE used to take a DIRECTORY orgument, if we have one
+dnl here make sure it is the same as any other declaration of libltdl's
+dnl location!  This also ensures lt_ltdl_dir is set when configure.ac is
+dnl not yet using an explicit LT_CONFIG_LTDL_DIR.
+m4_ifval([$1], [_LT_CONFIG_LTDL_DIR([$1])])dnl
+_$0()
+])# LTDL_CONVENIENCE
+
+# AC_LIBLTDL_CONVENIENCE accepted a directory argument in older libtools,
+# now we have LT_CONFIG_LTDL_DIR:
+AU_DEFUN([AC_LIBLTDL_CONVENIENCE],
+[_LT_CONFIG_LTDL_DIR([m4_default([$1], [libltdl])])
+_LTDL_CONVENIENCE])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBLTDL_CONVENIENCE], [])
+
+
+# _LTDL_CONVENIENCE
+# -----------------
+# Code shared by LTDL_CONVENIENCE and LTDL_INIT([convenience]).
+m4_defun([_LTDL_CONVENIENCE],
+[case $enable_ltdl_convenience in
+  no) AC_MSG_ERROR([this package needs a convenience libltdl]) ;;
+  "") enable_ltdl_convenience=yes
+      ac_configure_args="$ac_configure_args --enable-ltdl-convenience" ;;
+esac
+LIBLTDL='_LT_BUILD_PREFIX'"${lt_ltdl_dir+$lt_ltdl_dir/}libltdlc.la"
+LTDLDEPS=$LIBLTDL
+LTDLINCL='-I${top_srcdir}'"${lt_ltdl_dir+/$lt_ltdl_dir}"
+
+AC_SUBST([LIBLTDL])
+AC_SUBST([LTDLDEPS])
+AC_SUBST([LTDLINCL])
+
+# For backwards non-gettext consistent compatibility...
+INCLTDL="$LTDLINCL"
+AC_SUBST([INCLTDL])
+])# _LTDL_CONVENIENCE
+
+
+# LTDL_INSTALLABLE
+# ----------------
+# sets LIBLTDL to the link flags for the libltdl installable library
+# and LTDLINCL to the include flags for the libltdl header and adds
+# --enable-ltdl-install to the configure arguments.  Note that
+# AC_CONFIG_SUBDIRS is not called from here.  If an installed libltdl
+# is not found, LIBLTDL will be prefixed with '${top_build_prefix}' if
+# available, otherwise with '${top_builddir}/', and LTDLINCL will be
+# prefixed with '${top_srcdir}/' (note the single quotes!).  If your
+# package is not flat and you're not using automake, define top_build_prefix,
+# top_builddir, and top_srcdir appropriately in your Makefiles.
+# In the future, this macro may have to be called after LT_INIT.
+AC_DEFUN([LTDL_INSTALLABLE],
+[AC_BEFORE([$0], [LTDL_INIT])dnl
+dnl Although the argument is deprecated and no longer documented,
+dnl LTDL_INSTALLABLE used to take a DIRECTORY orgument, if we have one
+dnl here make sure it is the same as any other declaration of libltdl's
+dnl location!  This also ensures lt_ltdl_dir is set when configure.ac is
+dnl not yet using an explicit LT_CONFIG_LTDL_DIR.
+m4_ifval([$1], [_LT_CONFIG_LTDL_DIR([$1])])dnl
+_$0()
+])# LTDL_INSTALLABLE
+
+# AC_LIBLTDL_INSTALLABLE accepted a directory argument in older libtools,
+# now we have LT_CONFIG_LTDL_DIR:
+AU_DEFUN([AC_LIBLTDL_INSTALLABLE],
+[_LT_CONFIG_LTDL_DIR([m4_default([$1], [libltdl])])
+_LTDL_INSTALLABLE])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBLTDL_INSTALLABLE], [])
+
+
+# _LTDL_INSTALLABLE
+# -----------------
+# Code shared by LTDL_INSTALLABLE and LTDL_INIT([installable]).
+m4_defun([_LTDL_INSTALLABLE],
+[if test -f $prefix/lib/libltdl.la; then
+  lt_save_LDFLAGS="$LDFLAGS"
+  LDFLAGS="-L$prefix/lib $LDFLAGS"
+  AC_CHECK_LIB([ltdl], [lt_dlinit], [lt_lib_ltdl=yes])
+  LDFLAGS="$lt_save_LDFLAGS"
+  if test x"${lt_lib_ltdl-no}" = xyes; then
+    if test x"$enable_ltdl_install" != xyes; then
+      # Don't overwrite $prefix/lib/libltdl.la without --enable-ltdl-install
+      AC_MSG_WARN([not overwriting libltdl at $prefix, force with `--enable-ltdl-install'])
+      enable_ltdl_install=no
+    fi
+  elif test x"$enable_ltdl_install" = xno; then
+    AC_MSG_WARN([libltdl not installed, but installation disabled])
+  fi
+fi
+
+# If configure.ac declared an installable ltdl, and the user didn't override
+# with --disable-ltdl-install, we will install the shipped libltdl.
+case $enable_ltdl_install in
+  no) ac_configure_args="$ac_configure_args --enable-ltdl-install=no"
+      LIBLTDL="-lltdl"
+      LTDLDEPS=
+      LTDLINCL=
+      ;;
+  *)  enable_ltdl_install=yes
+      ac_configure_args="$ac_configure_args --enable-ltdl-install"
+      LIBLTDL='_LT_BUILD_PREFIX'"${lt_ltdl_dir+$lt_ltdl_dir/}libltdl.la"
+      LTDLDEPS=$LIBLTDL
+      LTDLINCL='-I${top_srcdir}'"${lt_ltdl_dir+/$lt_ltdl_dir}"
+      ;;
+esac
+
+AC_SUBST([LIBLTDL])
+AC_SUBST([LTDLDEPS])
+AC_SUBST([LTDLINCL])
+
+# For backwards non-gettext consistent compatibility...
+INCLTDL="$LTDLINCL"
+AC_SUBST([INCLTDL])
+])# LTDL_INSTALLABLE
+
+
+# _LTDL_MODE_DISPATCH
+# -------------------
+m4_define([_LTDL_MODE_DISPATCH],
+[dnl If _LTDL_DIR is `.', then we are configuring libltdl itself:
+m4_if(_LTDL_DIR, [],
+	[],
+    dnl if _LTDL_MODE was not set already, the default value is `subproject':
+    [m4_case(m4_default(_LTDL_MODE, [subproject]),
+	  [subproject], [AC_CONFIG_SUBDIRS(_LTDL_DIR)
+			  _LT_SHELL_INIT([lt_dlopen_dir="$lt_ltdl_dir"])],
+	  [nonrecursive], [_LT_SHELL_INIT([lt_dlopen_dir="$lt_ltdl_dir"; lt_libobj_prefix="$lt_ltdl_dir/"])],
+	  [recursive], [],
+	[m4_fatal([unknown libltdl mode: ]_LTDL_MODE)])])dnl
+dnl Be careful not to expand twice:
+m4_define([$0], [])
+])# _LTDL_MODE_DISPATCH
+
+
+# _LT_LIBOBJ(MODULE_NAME)
+# -----------------------
+# Like AC_LIBOBJ, except that MODULE_NAME goes into _LT_LIBOBJS instead
+# of into LIBOBJS.
+AC_DEFUN([_LT_LIBOBJ], [
+  m4_pattern_allow([^_LT_LIBOBJS$])
+  _LT_LIBOBJS="$_LT_LIBOBJS $1.$ac_objext"
+])# _LT_LIBOBJS
+
+
+# LTDL_INIT([OPTIONS])
+# --------------------
+# Clients of libltdl can use this macro to allow the installer to
+# choose between a shipped copy of the ltdl sources or a preinstalled
+# version of the library.  If the shipped ltdl sources are not in a
+# subdirectory named libltdl, the directory name must be given by
+# LT_CONFIG_LTDL_DIR.
+AC_DEFUN([LTDL_INIT],
+[dnl Parse OPTIONS
+_LT_SET_OPTIONS([$0], [$1])
+
+dnl We need to keep our own list of libobjs separate from our parent project,
+dnl and the easiest way to do that is redefine the AC_LIBOBJs macro while
+dnl we look for our own LIBOBJs.
+m4_pushdef([AC_LIBOBJ], m4_defn([_LT_LIBOBJ]))
+m4_pushdef([AC_LIBSOURCES])
+
+dnl If not otherwise defined, default to the 1.5.x compatible subproject mode:
+m4_if(_LTDL_MODE, [],
+        [m4_define([_LTDL_MODE], m4_default([$2], [subproject]))
+        m4_if([-1], [m4_bregexp(_LTDL_MODE, [\(subproject\|\(non\)?recursive\)])],
+                [m4_fatal([unknown libltdl mode: ]_LTDL_MODE)])])
+
+AC_ARG_WITH([included_ltdl],
+    [AS_HELP_STRING([--with-included-ltdl],
+                    [use the GNU ltdl sources included here])])
+
+if test "x$with_included_ltdl" != xyes; then
+  # We are not being forced to use the included libltdl sources, so
+  # decide whether there is a useful installed version we can use.
+  AC_CHECK_HEADER([ltdl.h],
+      [AC_CHECK_DECL([lt_dlinterface_register],
+	   [AC_CHECK_LIB([ltdl], [lt_dladvise_preload],
+	       [with_included_ltdl=no],
+	       [with_included_ltdl=yes])],
+	   [with_included_ltdl=yes],
+	   [AC_INCLUDES_DEFAULT
+	    #include <ltdl.h>])],
+      [with_included_ltdl=yes],
+      [AC_INCLUDES_DEFAULT]
+  )
+fi
+
+dnl If neither LT_CONFIG_LTDL_DIR, LTDL_CONVENIENCE nor LTDL_INSTALLABLE
+dnl was called yet, then for old times' sake, we assume libltdl is in an
+dnl eponymous directory:
+AC_PROVIDE_IFELSE([LT_CONFIG_LTDL_DIR], [], [_LT_CONFIG_LTDL_DIR([libltdl])])
+
+AC_ARG_WITH([ltdl_include],
+    [AS_HELP_STRING([--with-ltdl-include=DIR],
+                    [use the ltdl headers installed in DIR])])
+
+if test -n "$with_ltdl_include"; then
+  if test -f "$with_ltdl_include/ltdl.h"; then :
+  else
+    AC_MSG_ERROR([invalid ltdl include directory: `$with_ltdl_include'])
+  fi
+else
+  with_ltdl_include=no
+fi
+
+AC_ARG_WITH([ltdl_lib],
+    [AS_HELP_STRING([--with-ltdl-lib=DIR],
+                    [use the libltdl.la installed in DIR])])
+
+if test -n "$with_ltdl_lib"; then
+  if test -f "$with_ltdl_lib/libltdl.la"; then :
+  else
+    AC_MSG_ERROR([invalid ltdl library directory: `$with_ltdl_lib'])
+  fi
+else
+  with_ltdl_lib=no
+fi
+
+case ,$with_included_ltdl,$with_ltdl_include,$with_ltdl_lib, in
+  ,yes,no,no,)
+	m4_case(m4_default(_LTDL_TYPE, [convenience]),
+	    [convenience], [_LTDL_CONVENIENCE],
+	    [installable], [_LTDL_INSTALLABLE],
+	  [m4_fatal([unknown libltdl build type: ]_LTDL_TYPE)])
+	;;
+  ,no,no,no,)
+	# If the included ltdl is not to be used, then use the
+	# preinstalled libltdl we found.
+	AC_DEFINE([HAVE_LTDL], [1],
+	  [Define this if a modern libltdl is already installed])
+	LIBLTDL=-lltdl
+	LTDLDEPS=
+	LTDLINCL=
+	;;
+  ,no*,no,*)
+	AC_MSG_ERROR([`--with-ltdl-include' and `--with-ltdl-lib' options must be used together])
+	;;
+  *)	with_included_ltdl=no
+	LIBLTDL="-L$with_ltdl_lib -lltdl"
+	LTDLDEPS=
+	LTDLINCL="-I$with_ltdl_include"
+	;;
+esac
+INCLTDL="$LTDLINCL"
+
+# Report our decision...
+AC_MSG_CHECKING([where to find libltdl headers])
+AC_MSG_RESULT([$LTDLINCL])
+AC_MSG_CHECKING([where to find libltdl library])
+AC_MSG_RESULT([$LIBLTDL])
+
+_LTDL_SETUP
+
+dnl restore autoconf definition.
+m4_popdef([AC_LIBOBJ])
+m4_popdef([AC_LIBSOURCES])
+
+AC_CONFIG_COMMANDS_PRE([
+    _ltdl_libobjs=
+    _ltdl_ltlibobjs=
+    if test -n "$_LT_LIBOBJS"; then
+      # Remove the extension.
+      _lt_sed_drop_objext='s/\.o$//;s/\.obj$//'
+      for i in `for i in $_LT_LIBOBJS; do echo "$i"; done | sed "$_lt_sed_drop_objext" | sort -u`; do
+        _ltdl_libobjs="$_ltdl_libobjs $lt_libobj_prefix$i.$ac_objext"
+        _ltdl_ltlibobjs="$_ltdl_ltlibobjs $lt_libobj_prefix$i.lo"
+      done
+    fi
+    AC_SUBST([ltdl_LIBOBJS], [$_ltdl_libobjs])
+    AC_SUBST([ltdl_LTLIBOBJS], [$_ltdl_ltlibobjs])
+])
+
+# Only expand once:
+m4_define([LTDL_INIT])
+])# LTDL_INIT
+
+# Old names:
+AU_DEFUN([AC_LIB_LTDL], [LTDL_INIT($@)])
+AU_DEFUN([AC_WITH_LTDL], [LTDL_INIT($@)])
+AU_DEFUN([LT_WITH_LTDL], [LTDL_INIT($@)])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIB_LTDL], [])
+dnl AC_DEFUN([AC_WITH_LTDL], [])
+dnl AC_DEFUN([LT_WITH_LTDL], [])
+
+
+# _LTDL_SETUP
+# -----------
+# Perform all the checks necessary for compilation of the ltdl objects
+#  -- including compiler checks and header checks.  This is a public
+# interface  mainly for the benefit of libltdl's own configure.ac, most
+# other users should call LTDL_INIT instead.
+AC_DEFUN([_LTDL_SETUP],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([LT_SYS_MODULE_EXT])dnl
+AC_REQUIRE([LT_SYS_MODULE_PATH])dnl
+AC_REQUIRE([LT_SYS_DLSEARCH_PATH])dnl
+AC_REQUIRE([LT_LIB_DLLOAD])dnl
+AC_REQUIRE([LT_SYS_SYMBOL_USCORE])dnl
+AC_REQUIRE([LT_FUNC_DLSYM_USCORE])dnl
+AC_REQUIRE([LT_SYS_DLOPEN_DEPLIBS])dnl
+AC_REQUIRE([gl_FUNC_ARGZ])dnl
+
+m4_require([_LT_CHECK_OBJDIR])dnl
+m4_require([_LT_HEADER_DLFCN])dnl
+m4_require([_LT_CHECK_DLPREOPEN])dnl
+m4_require([_LT_DECL_SED])dnl
+
+dnl Don't require this, or it will be expanded earlier than the code
+dnl that sets the variables it relies on:
+_LT_ENABLE_INSTALL
+
+dnl _LTDL_MODE specific code must be called at least once:
+_LTDL_MODE_DISPATCH
+
+# In order that ltdl.c can compile, find out the first AC_CONFIG_HEADERS
+# the user used.  This is so that ltdl.h can pick up the parent projects
+# config.h file, The first file in AC_CONFIG_HEADERS must contain the
+# definitions required by ltdl.c.
+# FIXME: Remove use of undocumented AC_LIST_HEADERS (2.59 compatibility).
+AC_CONFIG_COMMANDS_PRE([dnl
+m4_pattern_allow([^LT_CONFIG_H$])dnl
+m4_ifset([AH_HEADER],
+    [LT_CONFIG_H=AH_HEADER],
+    [m4_ifset([AC_LIST_HEADERS],
+	    [LT_CONFIG_H=`echo "AC_LIST_HEADERS" | $SED 's,^[[      ]]*,,;s,[[ :]].*$,,'`],
+	[])])])
+AC_SUBST([LT_CONFIG_H])
+
+AC_CHECK_HEADERS([unistd.h dl.h sys/dl.h dld.h mach-o/dyld.h dirent.h],
+	[], [], [AC_INCLUDES_DEFAULT])
+
+AC_CHECK_FUNCS([closedir opendir readdir], [], [AC_LIBOBJ([lt__dirent])])
+AC_CHECK_FUNCS([strlcat strlcpy], [], [AC_LIBOBJ([lt__strl])])
+
+AC_DEFINE_UNQUOTED([LT_LIBEXT],["$libext"],[The archive extension])
+
+name=ltdl
+LTDLOPEN=`eval "\\$ECHO \"$libname_spec\""`
+AC_SUBST([LTDLOPEN])
+])# _LTDL_SETUP
+
+
+# _LT_ENABLE_INSTALL
+# ------------------
+m4_define([_LT_ENABLE_INSTALL],
+[AC_ARG_ENABLE([ltdl-install],
+    [AS_HELP_STRING([--enable-ltdl-install], [install libltdl])])
+
+case ,${enable_ltdl_install},${enable_ltdl_convenience} in
+  *yes*) ;;
+  *) enable_ltdl_convenience=yes ;;
+esac
+
+m4_ifdef([AM_CONDITIONAL],
+[AM_CONDITIONAL(INSTALL_LTDL, test x"${enable_ltdl_install-no}" != xno)
+ AM_CONDITIONAL(CONVENIENCE_LTDL, test x"${enable_ltdl_convenience-no}" != xno)])
+])# _LT_ENABLE_INSTALL
+
+
+# LT_SYS_DLOPEN_DEPLIBS
+# ---------------------
+AC_DEFUN([LT_SYS_DLOPEN_DEPLIBS],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_CACHE_CHECK([whether deplibs are loaded by dlopen],
+  [lt_cv_sys_dlopen_deplibs],
+  [# PORTME does your system automatically load deplibs for dlopen?
+  # or its logical equivalent (e.g. shl_load for HP-UX < 11)
+  # For now, we just catch OSes we know something about -- in the
+  # future, we'll try test this programmatically.
+  lt_cv_sys_dlopen_deplibs=unknown
+  case $host_os in
+  aix3*|aix4.1.*|aix4.2.*)
+    # Unknown whether this is true for these versions of AIX, but
+    # we want this `case' here to explicitly catch those versions.
+    lt_cv_sys_dlopen_deplibs=unknown
+    ;;
+  aix[[4-9]]*)
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  amigaos*)
+    case $host_cpu in
+    powerpc)
+      lt_cv_sys_dlopen_deplibs=no
+      ;;
+    esac
+    ;;
+  darwin*)
+    # Assuming the user has installed a libdl from somewhere, this is true
+    # If you are looking for one http://www.opendarwin.org/projects/dlcompat
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  freebsd* | dragonfly*)
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  gnu* | linux* | k*bsd*-gnu)
+    # GNU and its variants, using gnu ld.so (Glibc)
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  hpux10*|hpux11*)
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  interix*)
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  irix[[12345]]*|irix6.[[01]]*)
+    # Catch all versions of IRIX before 6.2, and indicate that we don't
+    # know how it worked for any of those versions.
+    lt_cv_sys_dlopen_deplibs=unknown
+    ;;
+  irix*)
+    # The case above catches anything before 6.2, and it's known that
+    # at 6.2 and later dlopen does load deplibs.
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  netbsd*)
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  openbsd*)
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  osf[[1234]]*)
+    # dlopen did load deplibs (at least at 4.x), but until the 5.x series,
+    # it did *not* use an RPATH in a shared library to find objects the
+    # library depends on, so we explicitly say `no'.
+    lt_cv_sys_dlopen_deplibs=no
+    ;;
+  osf5.0|osf5.0a|osf5.1)
+    # dlopen *does* load deplibs and with the right loader patch applied
+    # it even uses RPATH in a shared library to search for shared objects
+    # that the library depends on, but there's no easy way to know if that
+    # patch is installed.  Since this is the case, all we can really
+    # say is unknown -- it depends on the patch being installed.  If
+    # it is, this changes to `yes'.  Without it, it would be `no'.
+    lt_cv_sys_dlopen_deplibs=unknown
+    ;;
+  osf*)
+    # the two cases above should catch all versions of osf <= 5.1.  Read
+    # the comments above for what we know about them.
+    # At > 5.1, deplibs are loaded *and* any RPATH in a shared library
+    # is used to find them so we can finally say `yes'.
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  qnx*)
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  solaris*)
+    lt_cv_sys_dlopen_deplibs=yes
+    ;;
+  sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+    libltdl_cv_sys_dlopen_deplibs=yes
+    ;;
+  esac
+  ])
+if test "$lt_cv_sys_dlopen_deplibs" != yes; then
+ AC_DEFINE([LTDL_DLOPEN_DEPLIBS], [1],
+    [Define if the OS needs help to load dependent libraries for dlopen().])
+fi
+])# LT_SYS_DLOPEN_DEPLIBS
+
+# Old name:
+AU_ALIAS([AC_LTDL_SYS_DLOPEN_DEPLIBS], [LT_SYS_DLOPEN_DEPLIBS])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LTDL_SYS_DLOPEN_DEPLIBS], [])
+
+
+# LT_SYS_MODULE_EXT
+# -----------------
+AC_DEFUN([LT_SYS_MODULE_EXT],
+[m4_require([_LT_SYS_DYNAMIC_LINKER])dnl
+AC_CACHE_CHECK([which extension is used for runtime loadable modules],
+  [libltdl_cv_shlibext],
+[
+module=yes
+eval libltdl_cv_shlibext=$shrext_cmds
+  ])
+if test -n "$libltdl_cv_shlibext"; then
+  m4_pattern_allow([LT_MODULE_EXT])dnl
+  AC_DEFINE_UNQUOTED([LT_MODULE_EXT], ["$libltdl_cv_shlibext"],
+    [Define to the extension used for runtime loadable modules, say, ".so".])
+fi
+])# LT_SYS_MODULE_EXT
+
+# Old name:
+AU_ALIAS([AC_LTDL_SHLIBEXT], [LT_SYS_MODULE_EXT])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LTDL_SHLIBEXT], [])
+
+
+# LT_SYS_MODULE_PATH
+# ------------------
+AC_DEFUN([LT_SYS_MODULE_PATH],
+[m4_require([_LT_SYS_DYNAMIC_LINKER])dnl
+AC_CACHE_CHECK([which variable specifies run-time module search path],
+  [lt_cv_module_path_var], [lt_cv_module_path_var="$shlibpath_var"])
+if test -n "$lt_cv_module_path_var"; then
+  m4_pattern_allow([LT_MODULE_PATH_VAR])dnl
+  AC_DEFINE_UNQUOTED([LT_MODULE_PATH_VAR], ["$lt_cv_module_path_var"],
+    [Define to the name of the environment variable that determines the run-time module search path.])
+fi
+])# LT_SYS_MODULE_PATH
+
+# Old name:
+AU_ALIAS([AC_LTDL_SHLIBPATH], [LT_SYS_MODULE_PATH])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LTDL_SHLIBPATH], [])
+
+
+# LT_SYS_DLSEARCH_PATH
+# --------------------
+AC_DEFUN([LT_SYS_DLSEARCH_PATH],
+[m4_require([_LT_SYS_DYNAMIC_LINKER])dnl
+AC_CACHE_CHECK([for the default library search path],
+  [lt_cv_sys_dlsearch_path],
+  [lt_cv_sys_dlsearch_path="$sys_lib_dlsearch_path_spec"])
+if test -n "$lt_cv_sys_dlsearch_path"; then
+  sys_dlsearch_path=
+  for dir in $lt_cv_sys_dlsearch_path; do
+    if test -z "$sys_dlsearch_path"; then
+      sys_dlsearch_path="$dir"
+    else
+      sys_dlsearch_path="$sys_dlsearch_path$PATH_SEPARATOR$dir"
+    fi
+  done
+  m4_pattern_allow([LT_DLSEARCH_PATH])dnl
+  AC_DEFINE_UNQUOTED([LT_DLSEARCH_PATH], ["$sys_dlsearch_path"],
+    [Define to the system default library search path.])
+fi
+])# LT_SYS_DLSEARCH_PATH
+
+# Old name:
+AU_ALIAS([AC_LTDL_SYSSEARCHPATH], [LT_SYS_DLSEARCH_PATH])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LTDL_SYSSEARCHPATH], [])
+
+
+# _LT_CHECK_DLPREOPEN
+# -------------------
+m4_defun([_LT_CHECK_DLPREOPEN],
+[m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+AC_CACHE_CHECK([whether libtool supports -dlopen/-dlpreopen],
+  [libltdl_cv_preloaded_symbols],
+  [if test -n "$lt_cv_sys_global_symbol_pipe"; then
+    libltdl_cv_preloaded_symbols=yes
+  else
+    libltdl_cv_preloaded_symbols=no
+  fi
+  ])
+if test x"$libltdl_cv_preloaded_symbols" = xyes; then
+  AC_DEFINE([HAVE_PRELOADED_SYMBOLS], [1],
+    [Define if libtool can extract symbol lists from object files.])
+fi
+])# _LT_CHECK_DLPREOPEN
+
+
+# LT_LIB_DLLOAD
+# -------------
+AC_DEFUN([LT_LIB_DLLOAD],
+[m4_pattern_allow([^LT_DLLOADERS$])
+LT_DLLOADERS=
+AC_SUBST([LT_DLLOADERS])
+
+AC_LANG_PUSH([C])
+
+LIBADD_DLOPEN=
+AC_SEARCH_LIBS([dlopen], [dl],
+	[AC_DEFINE([HAVE_LIBDL], [1],
+		   [Define if you have the libdl library or equivalent.])
+	if test "$ac_cv_search_dlopen" != "none required" ; then
+	  LIBADD_DLOPEN="-ldl"
+	fi
+	libltdl_cv_lib_dl_dlopen="yes"
+	LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dlopen.la"],
+    [AC_LINK_IFELSE([AC_LANG_PROGRAM([[#if HAVE_DLFCN_H
+#  include <dlfcn.h>
+#endif
+    ]], [[dlopen(0, 0);]])],
+	    [AC_DEFINE([HAVE_LIBDL], [1],
+		       [Define if you have the libdl library or equivalent.])
+	    libltdl_cv_func_dlopen="yes"
+	    LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dlopen.la"],
+	[AC_CHECK_LIB([svld], [dlopen],
+		[AC_DEFINE([HAVE_LIBDL], [1],
+			 [Define if you have the libdl library or equivalent.])
+	        LIBADD_DLOPEN="-lsvld" libltdl_cv_func_dlopen="yes"
+		LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dlopen.la"])])])
+if test x"$libltdl_cv_func_dlopen" = xyes || test x"$libltdl_cv_lib_dl_dlopen" = xyes
+then
+  lt_save_LIBS="$LIBS"
+  LIBS="$LIBS $LIBADD_DLOPEN"
+  AC_CHECK_FUNCS([dlerror])
+  LIBS="$lt_save_LIBS"
+fi
+AC_SUBST([LIBADD_DLOPEN])
+
+LIBADD_SHL_LOAD=
+AC_CHECK_FUNC([shl_load],
+	[AC_DEFINE([HAVE_SHL_LOAD], [1],
+		   [Define if you have the shl_load function.])
+	LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}shl_load.la"],
+    [AC_CHECK_LIB([dld], [shl_load],
+	    [AC_DEFINE([HAVE_SHL_LOAD], [1],
+		       [Define if you have the shl_load function.])
+	    LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}shl_load.la"
+	    LIBADD_SHL_LOAD="-ldld"])])
+AC_SUBST([LIBADD_SHL_LOAD])
+
+case $host_os in
+darwin[[1567]].*)
+# We only want this for pre-Mac OS X 10.4.
+  AC_CHECK_FUNC([_dyld_func_lookup],
+	[AC_DEFINE([HAVE_DYLD], [1],
+		   [Define if you have the _dyld_func_lookup function.])
+	LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dyld.la"])
+  ;;
+beos*)
+  LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}load_add_on.la"
+  ;;
+cygwin* | mingw* | os2* | pw32*)
+  AC_CHECK_DECLS([cygwin_conv_path], [], [], [[#include <sys/cygwin.h>]])
+  LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}loadlibrary.la"
+  ;;
+esac
+
+AC_CHECK_LIB([dld], [dld_link],
+	[AC_DEFINE([HAVE_DLD], [1],
+		   [Define if you have the GNU dld library.])
+		LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dld_link.la"])
+AC_SUBST([LIBADD_DLD_LINK])
+
+m4_pattern_allow([^LT_DLPREOPEN$])
+LT_DLPREOPEN=
+if test -n "$LT_DLLOADERS"
+then
+  for lt_loader in $LT_DLLOADERS; do
+    LT_DLPREOPEN="$LT_DLPREOPEN-dlpreopen $lt_loader "
+  done
+  AC_DEFINE([HAVE_LIBDLLOADER], [1],
+            [Define if libdlloader will be built on this platform])
+fi
+AC_SUBST([LT_DLPREOPEN])
+
+dnl This isn't used anymore, but set it for backwards compatibility
+LIBADD_DL="$LIBADD_DLOPEN $LIBADD_SHL_LOAD"
+AC_SUBST([LIBADD_DL])
+
+AC_LANG_POP
+])# LT_LIB_DLLOAD
+
+# Old name:
+AU_ALIAS([AC_LTDL_DLLIB], [LT_LIB_DLLOAD])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LTDL_DLLIB], [])
+
+
+# LT_SYS_SYMBOL_USCORE
+# --------------------
+# does the compiler prefix global symbols with an underscore?
+AC_DEFUN([LT_SYS_SYMBOL_USCORE],
+[m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+AC_CACHE_CHECK([for _ prefix in compiled symbols],
+  [lt_cv_sys_symbol_underscore],
+  [lt_cv_sys_symbol_underscore=no
+  cat > conftest.$ac_ext <<_LT_EOF
+void nm_test_func(){}
+int main(){nm_test_func;return 0;}
+_LT_EOF
+  if AC_TRY_EVAL(ac_compile); then
+    # Now try to grab the symbols.
+    ac_nlist=conftest.nm
+    if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $ac_nlist) && test -s "$ac_nlist"; then
+      # See whether the symbols have a leading underscore.
+      if grep '^. _nm_test_func' "$ac_nlist" >/dev/null; then
+        lt_cv_sys_symbol_underscore=yes
+      else
+        if grep '^. nm_test_func ' "$ac_nlist" >/dev/null; then
+	  :
+        else
+	  echo "configure: cannot find nm_test_func in $ac_nlist" >&AS_MESSAGE_LOG_FD
+        fi
+      fi
+    else
+      echo "configure: cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
+    fi
+  else
+    echo "configure: failed program was:" >&AS_MESSAGE_LOG_FD
+    cat conftest.c >&AS_MESSAGE_LOG_FD
+  fi
+  rm -rf conftest*
+  ])
+  sys_symbol_underscore=$lt_cv_sys_symbol_underscore
+  AC_SUBST([sys_symbol_underscore])
+])# LT_SYS_SYMBOL_USCORE
+
+# Old name:
+AU_ALIAS([AC_LTDL_SYMBOL_USCORE], [LT_SYS_SYMBOL_USCORE])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LTDL_SYMBOL_USCORE], [])
+
+
+# LT_FUNC_DLSYM_USCORE
+# --------------------
+AC_DEFUN([LT_FUNC_DLSYM_USCORE],
+[AC_REQUIRE([LT_SYS_SYMBOL_USCORE])dnl
+if test x"$lt_cv_sys_symbol_underscore" = xyes; then
+  if test x"$libltdl_cv_func_dlopen" = xyes ||
+     test x"$libltdl_cv_lib_dl_dlopen" = xyes ; then
+	AC_CACHE_CHECK([whether we have to add an underscore for dlsym],
+	  [libltdl_cv_need_uscore],
+	  [libltdl_cv_need_uscore=unknown
+          save_LIBS="$LIBS"
+          LIBS="$LIBS $LIBADD_DLOPEN"
+	  _LT_TRY_DLOPEN_SELF(
+	    [libltdl_cv_need_uscore=no], [libltdl_cv_need_uscore=yes],
+	    [],				 [libltdl_cv_need_uscore=cross])
+	  LIBS="$save_LIBS"
+	])
+  fi
+fi
+
+if test x"$libltdl_cv_need_uscore" = xyes; then
+  AC_DEFINE([NEED_USCORE], [1],
+    [Define if dlsym() requires a leading underscore in symbol names.])
+fi
+])# LT_FUNC_DLSYM_USCORE
+
+# Old name:
+AU_ALIAS([AC_LTDL_DLSYM_USCORE], [LT_FUNC_DLSYM_USCORE])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LTDL_DLSYM_USCORE], [])
+
 # Helper functions for option handling.                    -*- Autoconf -*-
 #
 #   Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
 #   Written by Gary V. Vaughan, 2004
 #
 # This file is free software; the Free Software Foundation gives
 # unlimited permission to copy and/or distribute it, with or without
 # modifications, as long as this notice is preserved.
--- a/js/src/ctypes/libffi/configure
+++ b/js/src/ctypes/libffi/configure
@@ -747,16 +747,17 @@ am__EXEEXT_TRUE
 LTLIBOBJS
 LIBOBJS
 toolexeclibdir
 toolexecdir
 FFI_DEBUG_FALSE
 FFI_DEBUG_TRUE
 TARGETDIR
 TARGET
+sys_symbol_underscore
 HAVE_LONG_DOUBLE
 ALLOCA
 PA64_HPUX_FALSE
 PA64_HPUX_TRUE
 PA_HPUX_FALSE
 PA_HPUX_TRUE
 PA_LINUX_FALSE
 PA_LINUX_TRUE
@@ -12356,16 +12357,73 @@ fi
 $as_echo "$libffi_cv_as_string_pseudo_op" >&6; }
     if test "x$libffi_cv_as_string_pseudo_op" = xyes; then
 
 $as_echo "#define HAVE_AS_STRING_PSEUDO_OP 1" >>confdefs.h
 
     fi
 fi
 
+if test x$TARGET = xX86_WIN64; then
+    { $as_echo "$as_me:$LINENO: checking for _ prefix in compiled symbols" >&5
+$as_echo_n "checking for _ prefix in compiled symbols... " >&6; }
+if test "${lt_cv_sys_symbol_underscore+set}" = set; then
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_sys_symbol_underscore=no
+  cat > conftest.$ac_ext <<_LT_EOF
+void nm_test_func(){}
+int main(){nm_test_func;return 0;}
+_LT_EOF
+  if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; then
+    # Now try to grab the symbols.
+    ac_nlist=conftest.nm
+    if { (eval echo "$as_me:$LINENO: \"$NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $ac_nlist\"") >&5
+  (eval $NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $ac_nlist) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && test -s "$ac_nlist"; then
+      # See whether the symbols have a leading underscore.
+      if grep '^. _nm_test_func' "$ac_nlist" >/dev/null; then
+        lt_cv_sys_symbol_underscore=yes
+      else
+        if grep '^. nm_test_func ' "$ac_nlist" >/dev/null; then
+	  :
+        else
+	  echo "configure: cannot find nm_test_func in $ac_nlist" >&5
+        fi
+      fi
+    else
+      echo "configure: cannot run $lt_cv_sys_global_symbol_pipe" >&5
+    fi
+  else
+    echo "configure: failed program was:" >&5
+    cat conftest.c >&5
+  fi
+  rm -rf conftest*
+
+fi
+{ $as_echo "$as_me:$LINENO: result: $lt_cv_sys_symbol_underscore" >&5
+$as_echo "$lt_cv_sys_symbol_underscore" >&6; }
+  sys_symbol_underscore=$lt_cv_sys_symbol_underscore
+
+
+    if test "x$sys_symbol_underscore" = xyes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define SYMBOL_UNDERSCORE 1
+_ACEOF
+
+    fi
+fi
+
 case "$target" in
      *-apple-darwin1* | *-*-freebsd* | *-*-openbsd* | *-pc-solaris*)
 
 $as_echo "#define FFI_MMAP_EXEC_WRIT 1" >>confdefs.h
 
      ;;
 esac
 
--- a/js/src/ctypes/libffi/configure.ac
+++ b/js/src/ctypes/libffi/configure.ac
@@ -310,16 +310,23 @@ if test x$TARGET = xX86 || test x$TARGET
 		       [libffi_cv_as_string_pseudo_op=no])
     ])
     if test "x$libffi_cv_as_string_pseudo_op" = xyes; then
        AC_DEFINE(HAVE_AS_STRING_PSEUDO_OP, 1,
 	       [Define if your assembler supports .string.])
     fi
 fi
 
+if test x$TARGET = xX86_WIN64; then
+    LT_SYS_SYMBOL_USCORE
+    if test "x$sys_symbol_underscore" = xyes; then
+        AC_DEFINE(SYMBOL_UNDERSCORE, 1, [Define if symbols are underscored.])
+    fi
+fi
+
 case "$target" in
      # Darwin 10 (OSX 10.6) and beyond allocate non-executable pages
      *-apple-darwin1* | *-*-freebsd* | *-*-openbsd* | *-pc-solaris*)
        AC_DEFINE(FFI_MMAP_EXEC_WRIT, 1,
                  [Cannot use malloc on this target, so, we revert to
                    alternative means])
      ;;
 esac
--- a/js/src/ctypes/libffi/src/x86/win64.S
+++ b/js/src/ctypes/libffi/src/x86/win64.S
@@ -227,32 +227,40 @@ ret_void$:
 	xor	rax, rax
 
 	lea	rsp, QWORD PTR [rbp+16]
 	pop	rbp
 	ret	0
 ffi_call_win64 ENDP
 _TEXT	ENDS
 END
-#else        
+
+#else
+
+#ifdef SYMBOL_UNDERSCORE
+#define SYMBOL_NAME(name) _##name
+#else
+#define SYMBOL_NAME(name) name
+#endif
+
 .text
 
-.extern _ffi_closure_win64_inner
+.extern SYMBOL_NAME(ffi_closure_win64_inner)
 
 # ffi_closure_win64 will be called with these registers set:
 #    rax points to 'closure'
 #    r11 contains a bit mask that specifies which of the
 #    first four parameters are float or double
 #
 # It must move the parameters passed in registers to their stack location,
 # call ffi_closure_win64_inner for the actual work, then return the result.
 # 
 	.balign 16
-        .globl _ffi_closure_win64	
-_ffi_closure_win64:     
+        .globl SYMBOL_NAME(ffi_closure_win64)
+SYMBOL_NAME(ffi_closure_win64):
 	# copy register arguments onto stack
 	test	$1,%r11
 	jne	.Lfirst_is_float	
 	mov	%rcx, 8(%rsp)
 	jmp	.Lsecond
 .Lfirst_is_float:
 	movlpd	%xmm0, 8(%rsp)
 
@@ -282,27 +290,27 @@ END
 
 .Ldone:
 #.ALLOCSTACK 40
 	sub	$40, %rsp
 #.ENDPROLOG
 	mov	%rax, %rcx	# context is first parameter
 	mov	%rsp, %rdx	# stack is second parameter
 	add	$48, %rdx	# point to start of arguments
-	mov	$_ffi_closure_win64_inner, %rax
+	mov	$SYMBOL_NAME(ffi_closure_win64_inner), %rax
 	callq	*%rax		# call the real closure function
 	add	$40, %rsp
 	movq	%rax, %xmm0	# If the closure returned a float,
                                 # ffi_closure_win64_inner wrote it to rax
 	retq
 .ffi_closure_win64_end:
 
 	.balign 16
-        .globl	_ffi_call_win64
-_ffi_call_win64:        
+        .globl	SYMBOL_NAME(ffi_call_win64)
+SYMBOL_NAME(ffi_call_win64):
         # copy registers onto stack
 	mov	%r9,32(%rsp)
 	mov	%r8,24(%rsp)
 	mov	%rdx,16(%rsp)
 	mov	%rcx,8(%rsp)
         #.PUSHREG rbp
 	push	%rbp
         #.ALLOCSTACK 48
new file mode 100644
--- /dev/null
+++ b/js/src/ctypes/patches-libffi/03-bug-712594.patch
@@ -0,0 +1,1072 @@
+commit 5b9cd52784339a42e417174a55e310e214d435f9
+Author: Anthony Green <green@moxielogic.com>
+Date:   Mon Nov 22 15:19:57 2010 -0500
+
+    win64-underscore patch
+
+diff --git a/aclocal.m4 b/aclocal.m4
+index 0ef4b09..4079f82 100644
+--- a/aclocal.m4
++++ b/aclocal.m4
+@@ -7364,6 +7364,811 @@ _LT_EOF
+   esac
+ ])
+ 
++# ltdl.m4 - Configure ltdl for the target system. -*-Autoconf-*-
++#
++#   Copyright (C) 1999-2006, 2007, 2008 Free Software Foundation, Inc.
++#   Written by Thomas Tanner, 1999
++#
++# This file is free software; the Free Software Foundation gives
++# unlimited permission to copy and/or distribute it, with or without
++# modifications, as long as this notice is preserved.
++
++# serial 17 LTDL_INIT
++
++# LT_CONFIG_LTDL_DIR(DIRECTORY, [LTDL-MODE])
++# ------------------------------------------
++# DIRECTORY contains the libltdl sources.  It is okay to call this
++# function multiple times, as long as the same DIRECTORY is always given.
++AC_DEFUN([LT_CONFIG_LTDL_DIR],
++[AC_BEFORE([$0], [LTDL_INIT])
++_$0($*)
++])# LT_CONFIG_LTDL_DIR
++
++# We break this out into a separate macro, so that we can call it safely
++# internally without being caught accidentally by the sed scan in libtoolize.
++m4_defun([_LT_CONFIG_LTDL_DIR],
++[dnl remove trailing slashes
++m4_pushdef([_ARG_DIR], m4_bpatsubst([$1], [/*$]))
++m4_case(_LTDL_DIR,
++	[], [dnl only set lt_ltdl_dir if _ARG_DIR is not simply `.'
++	     m4_if(_ARG_DIR, [.],
++	             [],
++		 [m4_define([_LTDL_DIR], _ARG_DIR)
++	          _LT_SHELL_INIT([lt_ltdl_dir=']_ARG_DIR['])])],
++    [m4_if(_ARG_DIR, _LTDL_DIR,
++	    [],
++	[m4_fatal([multiple libltdl directories: `]_LTDL_DIR[', `]_ARG_DIR['])])])
++m4_popdef([_ARG_DIR])
++])# _LT_CONFIG_LTDL_DIR
++
++# Initialise:
++m4_define([_LTDL_DIR], [])
++
++
++# _LT_BUILD_PREFIX
++# ----------------
++# If Autoconf is new enough, expand to `${top_build_prefix}', otherwise
++# to `${top_builddir}/'.
++m4_define([_LT_BUILD_PREFIX],
++[m4_ifdef([AC_AUTOCONF_VERSION],
++   [m4_if(m4_version_compare(m4_defn([AC_AUTOCONF_VERSION]), [2.62]),
++	  [-1], [m4_ifdef([_AC_HAVE_TOP_BUILD_PREFIX],
++			  [${top_build_prefix}],
++			  [${top_builddir}/])],
++	  [${top_build_prefix}])],
++   [${top_builddir}/])[]dnl
++])
++
++
++# LTDL_CONVENIENCE
++# ----------------
++# sets LIBLTDL to the link flags for the libltdl convenience library and
++# LTDLINCL to the include flags for the libltdl header and adds
++# --enable-ltdl-convenience to the configure arguments.  Note that
++# AC_CONFIG_SUBDIRS is not called here.  LIBLTDL will be prefixed with
++# '${top_build_prefix}' if available, otherwise with '${top_builddir}/',
++# and LTDLINCL will be prefixed with '${top_srcdir}/' (note the single
++# quotes!).  If your package is not flat and you're not using automake,
++# define top_build_prefix, top_builddir, and top_srcdir appropriately
++# in your Makefiles.
++AC_DEFUN([LTDL_CONVENIENCE],
++[AC_BEFORE([$0], [LTDL_INIT])dnl
++dnl Although the argument is deprecated and no longer documented,
++dnl LTDL_CONVENIENCE used to take a DIRECTORY orgument, if we have one
++dnl here make sure it is the same as any other declaration of libltdl's
++dnl location!  This also ensures lt_ltdl_dir is set when configure.ac is
++dnl not yet using an explicit LT_CONFIG_LTDL_DIR.
++m4_ifval([$1], [_LT_CONFIG_LTDL_DIR([$1])])dnl
++_$0()
++])# LTDL_CONVENIENCE
++
++# AC_LIBLTDL_CONVENIENCE accepted a directory argument in older libtools,
++# now we have LT_CONFIG_LTDL_DIR:
++AU_DEFUN([AC_LIBLTDL_CONVENIENCE],
++[_LT_CONFIG_LTDL_DIR([m4_default([$1], [libltdl])])
++_LTDL_CONVENIENCE])
++
++dnl aclocal-1.4 backwards compatibility:
++dnl AC_DEFUN([AC_LIBLTDL_CONVENIENCE], [])
++
++
++# _LTDL_CONVENIENCE
++# -----------------
++# Code shared by LTDL_CONVENIENCE and LTDL_INIT([convenience]).
++m4_defun([_LTDL_CONVENIENCE],
++[case $enable_ltdl_convenience in
++  no) AC_MSG_ERROR([this package needs a convenience libltdl]) ;;
++  "") enable_ltdl_convenience=yes
++      ac_configure_args="$ac_configure_args --enable-ltdl-convenience" ;;
++esac
++LIBLTDL='_LT_BUILD_PREFIX'"${lt_ltdl_dir+$lt_ltdl_dir/}libltdlc.la"
++LTDLDEPS=$LIBLTDL
++LTDLINCL='-I${top_srcdir}'"${lt_ltdl_dir+/$lt_ltdl_dir}"
++
++AC_SUBST([LIBLTDL])
++AC_SUBST([LTDLDEPS])
++AC_SUBST([LTDLINCL])
++
++# For backwards non-gettext consistent compatibility...
++INCLTDL="$LTDLINCL"
++AC_SUBST([INCLTDL])
++])# _LTDL_CONVENIENCE
++
++
++# LTDL_INSTALLABLE
++# ----------------
++# sets LIBLTDL to the link flags for the libltdl installable library
++# and LTDLINCL to the include flags for the libltdl header and adds
++# --enable-ltdl-install to the configure arguments.  Note that
++# AC_CONFIG_SUBDIRS is not called from here.  If an installed libltdl
++# is not found, LIBLTDL will be prefixed with '${top_build_prefix}' if
++# available, otherwise with '${top_builddir}/', and LTDLINCL will be
++# prefixed with '${top_srcdir}/' (note the single quotes!).  If your
++# package is not flat and you're not using automake, define top_build_prefix,
++# top_builddir, and top_srcdir appropriately in your Makefiles.
++# In the future, this macro may have to be called after LT_INIT.
++AC_DEFUN([LTDL_INSTALLABLE],
++[AC_BEFORE([$0], [LTDL_INIT])dnl
++dnl Although the argument is deprecated and no longer documented,
++dnl LTDL_INSTALLABLE used to take a DIRECTORY orgument, if we have one
++dnl here make sure it is the same as any other declaration of libltdl's
++dnl location!  This also ensures lt_ltdl_dir is set when configure.ac is
++dnl not yet using an explicit LT_CONFIG_LTDL_DIR.
++m4_ifval([$1], [_LT_CONFIG_LTDL_DIR([$1])])dnl
++_$0()
++])# LTDL_INSTALLABLE
++
++# AC_LIBLTDL_INSTALLABLE accepted a directory argument in older libtools,
++# now we have LT_CONFIG_LTDL_DIR:
++AU_DEFUN([AC_LIBLTDL_INSTALLABLE],
++[_LT_CONFIG_LTDL_DIR([m4_default([$1], [libltdl])])
++_LTDL_INSTALLABLE])
++
++dnl aclocal-1.4 backwards compatibility:
++dnl AC_DEFUN([AC_LIBLTDL_INSTALLABLE], [])
++
++
++# _LTDL_INSTALLABLE
++# -----------------
++# Code shared by LTDL_INSTALLABLE and LTDL_INIT([installable]).
++m4_defun([_LTDL_INSTALLABLE],
++[if test -f $prefix/lib/libltdl.la; then
++  lt_save_LDFLAGS="$LDFLAGS"
++  LDFLAGS="-L$prefix/lib $LDFLAGS"
++  AC_CHECK_LIB([ltdl], [lt_dlinit], [lt_lib_ltdl=yes])
++  LDFLAGS="$lt_save_LDFLAGS"
++  if test x"${lt_lib_ltdl-no}" = xyes; then
++    if test x"$enable_ltdl_install" != xyes; then
++      # Don't overwrite $prefix/lib/libltdl.la without --enable-ltdl-install
++      AC_MSG_WARN([not overwriting libltdl at $prefix, force with `--enable-ltdl-install'])
++      enable_ltdl_install=no
++    fi
++  elif test x"$enable_ltdl_install" = xno; then
++    AC_MSG_WARN([libltdl not installed, but installation disabled])
++  fi
++fi
++
++# If configure.ac declared an installable ltdl, and the user didn't override
++# with --disable-ltdl-install, we will install the shipped libltdl.
++case $enable_ltdl_install in
++  no) ac_configure_args="$ac_configure_args --enable-ltdl-install=no"
++      LIBLTDL="-lltdl"
++      LTDLDEPS=
++      LTDLINCL=
++      ;;
++  *)  enable_ltdl_install=yes
++      ac_configure_args="$ac_configure_args --enable-ltdl-install"
++      LIBLTDL='_LT_BUILD_PREFIX'"${lt_ltdl_dir+$lt_ltdl_dir/}libltdl.la"
++      LTDLDEPS=$LIBLTDL
++      LTDLINCL='-I${top_srcdir}'"${lt_ltdl_dir+/$lt_ltdl_dir}"
++      ;;
++esac
++
++AC_SUBST([LIBLTDL])
++AC_SUBST([LTDLDEPS])
++AC_SUBST([LTDLINCL])
++
++# For backwards non-gettext consistent compatibility...
++INCLTDL="$LTDLINCL"
++AC_SUBST([INCLTDL])
++])# LTDL_INSTALLABLE
++
++
++# _LTDL_MODE_DISPATCH
++# -------------------
++m4_define([_LTDL_MODE_DISPATCH],
++[dnl If _LTDL_DIR is `.', then we are configuring libltdl itself:
++m4_if(_LTDL_DIR, [],
++	[],
++    dnl if _LTDL_MODE was not set already, the default value is `subproject':
++    [m4_case(m4_default(_LTDL_MODE, [subproject]),
++	  [subproject], [AC_CONFIG_SUBDIRS(_LTDL_DIR)
++			  _LT_SHELL_INIT([lt_dlopen_dir="$lt_ltdl_dir"])],
++	  [nonrecursive], [_LT_SHELL_INIT([lt_dlopen_dir="$lt_ltdl_dir"; lt_libobj_prefix="$lt_ltdl_dir/"])],
++	  [recursive], [],
++	[m4_fatal([unknown libltdl mode: ]_LTDL_MODE)])])dnl
++dnl Be careful not to expand twice:
++m4_define([$0], [])
++])# _LTDL_MODE_DISPATCH
++
++
++# _LT_LIBOBJ(MODULE_NAME)
++# -----------------------
++# Like AC_LIBOBJ, except that MODULE_NAME goes into _LT_LIBOBJS instead
++# of into LIBOBJS.
++AC_DEFUN([_LT_LIBOBJ], [
++  m4_pattern_allow([^_LT_LIBOBJS$])
++  _LT_LIBOBJS="$_LT_LIBOBJS $1.$ac_objext"
++])# _LT_LIBOBJS
++
++
++# LTDL_INIT([OPTIONS])
++# --------------------
++# Clients of libltdl can use this macro to allow the installer to
++# choose between a shipped copy of the ltdl sources or a preinstalled
++# version of the library.  If the shipped ltdl sources are not in a
++# subdirectory named libltdl, the directory name must be given by
++# LT_CONFIG_LTDL_DIR.
++AC_DEFUN([LTDL_INIT],
++[dnl Parse OPTIONS
++_LT_SET_OPTIONS([$0], [$1])
++
++dnl We need to keep our own list of libobjs separate from our parent project,
++dnl and the easiest way to do that is redefine the AC_LIBOBJs macro while
++dnl we look for our own LIBOBJs.
++m4_pushdef([AC_LIBOBJ], m4_defn([_LT_LIBOBJ]))
++m4_pushdef([AC_LIBSOURCES])
++
++dnl If not otherwise defined, default to the 1.5.x compatible subproject mode:
++m4_if(_LTDL_MODE, [],
++        [m4_define([_LTDL_MODE], m4_default([$2], [subproject]))
++        m4_if([-1], [m4_bregexp(_LTDL_MODE, [\(subproject\|\(non\)?recursive\)])],
++                [m4_fatal([unknown libltdl mode: ]_LTDL_MODE)])])
++
++AC_ARG_WITH([included_ltdl],
++    [AS_HELP_STRING([--with-included-ltdl],
++                    [use the GNU ltdl sources included here])])
++
++if test "x$with_included_ltdl" != xyes; then
++  # We are not being forced to use the included libltdl sources, so
++  # decide whether there is a useful installed version we can use.
++  AC_CHECK_HEADER([ltdl.h],
++      [AC_CHECK_DECL([lt_dlinterface_register],
++	   [AC_CHECK_LIB([ltdl], [lt_dladvise_preload],
++	       [with_included_ltdl=no],
++	       [with_included_ltdl=yes])],
++	   [with_included_ltdl=yes],
++	   [AC_INCLUDES_DEFAULT
++	    #include <ltdl.h>])],
++      [with_included_ltdl=yes],
++      [AC_INCLUDES_DEFAULT]
++  )
++fi
++
++dnl If neither LT_CONFIG_LTDL_DIR, LTDL_CONVENIENCE nor LTDL_INSTALLABLE
++dnl was called yet, then for old times' sake, we assume libltdl is in an
++dnl eponymous directory:
++AC_PROVIDE_IFELSE([LT_CONFIG_LTDL_DIR], [], [_LT_CONFIG_LTDL_DIR([libltdl])])
++
++AC_ARG_WITH([ltdl_include],
++    [AS_HELP_STRING([--with-ltdl-include=DIR],
++                    [use the ltdl headers installed in DIR])])
++
++if test -n "$with_ltdl_include"; then
++  if test -f "$with_ltdl_include/ltdl.h"; then :
++  else
++    AC_MSG_ERROR([invalid ltdl include directory: `$with_ltdl_include'])
++  fi
++else
++  with_ltdl_include=no
++fi
++
++AC_ARG_WITH([ltdl_lib],
++    [AS_HELP_STRING([--with-ltdl-lib=DIR],
++                    [use the libltdl.la installed in DIR])])
++
++if test -n "$with_ltdl_lib"; then
++  if test -f "$with_ltdl_lib/libltdl.la"; then :
++  else
++    AC_MSG_ERROR([invalid ltdl library directory: `$with_ltdl_lib'])
++  fi
++else
++  with_ltdl_lib=no
++fi
++
++case ,$with_included_ltdl,$with_ltdl_include,$with_ltdl_lib, in
++  ,yes,no,no,)
++	m4_case(m4_default(_LTDL_TYPE, [convenience]),
++	    [convenience], [_LTDL_CONVENIENCE],
++	    [installable], [_LTDL_INSTALLABLE],
++	  [m4_fatal([unknown libltdl build type: ]_LTDL_TYPE)])
++	;;
++  ,no,no,no,)
++	# If the included ltdl is not to be used, then use the
++	# preinstalled libltdl we found.
++	AC_DEFINE([HAVE_LTDL], [1],
++	  [Define this if a modern libltdl is already installed])
++	LIBLTDL=-lltdl
++	LTDLDEPS=
++	LTDLINCL=
++	;;
++  ,no*,no,*)
++	AC_MSG_ERROR([`--with-ltdl-include' and `--with-ltdl-lib' options must be used together])
++	;;
++  *)	with_included_ltdl=no
++	LIBLTDL="-L$with_ltdl_lib -lltdl"
++	LTDLDEPS=
++	LTDLINCL="-I$with_ltdl_include"
++	;;
++esac
++INCLTDL="$LTDLINCL"
++
++# Report our decision...
++AC_MSG_CHECKING([where to find libltdl headers])
++AC_MSG_RESULT([$LTDLINCL])
++AC_MSG_CHECKING([where to find libltdl library])
++AC_MSG_RESULT([$LIBLTDL])
++
++_LTDL_SETUP
++
++dnl restore autoconf definition.
++m4_popdef([AC_LIBOBJ])
++m4_popdef([AC_LIBSOURCES])
++
++AC_CONFIG_COMMANDS_PRE([
++    _ltdl_libobjs=
++    _ltdl_ltlibobjs=
++    if test -n "$_LT_LIBOBJS"; then
++      # Remove the extension.
++      _lt_sed_drop_objext='s/\.o$//;s/\.obj$//'
++      for i in `for i in $_LT_LIBOBJS; do echo "$i"; done | sed "$_lt_sed_drop_objext" | sort -u`; do
++        _ltdl_libobjs="$_ltdl_libobjs $lt_libobj_prefix$i.$ac_objext"
++        _ltdl_ltlibobjs="$_ltdl_ltlibobjs $lt_libobj_prefix$i.lo"
++      done
++    fi
++    AC_SUBST([ltdl_LIBOBJS], [$_ltdl_libobjs])
++    AC_SUBST([ltdl_LTLIBOBJS], [$_ltdl_ltlibobjs])
++])
++
++# Only expand once:
++m4_define([LTDL_INIT])
++])# LTDL_INIT
++
++# Old names:
++AU_DEFUN([AC_LIB_LTDL], [LTDL_INIT($@)])
++AU_DEFUN([AC_WITH_LTDL], [LTDL_INIT($@)])
++AU_DEFUN([LT_WITH_LTDL], [LTDL_INIT($@)])
++dnl aclocal-1.4 backwards compatibility:
++dnl AC_DEFUN([AC_LIB_LTDL], [])
++dnl AC_DEFUN([AC_WITH_LTDL], [])
++dnl AC_DEFUN([LT_WITH_LTDL], [])
++
++
++# _LTDL_SETUP
++# -----------
++# Perform all the checks necessary for compilation of the ltdl objects
++#  -- including compiler checks and header checks.  This is a public
++# interface  mainly for the benefit of libltdl's own configure.ac, most
++# other users should call LTDL_INIT instead.
++AC_DEFUN([_LTDL_SETUP],
++[AC_REQUIRE([AC_PROG_CC])dnl
++AC_REQUIRE([LT_SYS_MODULE_EXT])dnl
++AC_REQUIRE([LT_SYS_MODULE_PATH])dnl
++AC_REQUIRE([LT_SYS_DLSEARCH_PATH])dnl
++AC_REQUIRE([LT_LIB_DLLOAD])dnl
++AC_REQUIRE([LT_SYS_SYMBOL_USCORE])dnl
++AC_REQUIRE([LT_FUNC_DLSYM_USCORE])dnl
++AC_REQUIRE([LT_SYS_DLOPEN_DEPLIBS])dnl
++AC_REQUIRE([gl_FUNC_ARGZ])dnl
++
++m4_require([_LT_CHECK_OBJDIR])dnl
++m4_require([_LT_HEADER_DLFCN])dnl
++m4_require([_LT_CHECK_DLPREOPEN])dnl
++m4_require([_LT_DECL_SED])dnl
++
++dnl Don't require this, or it will be expanded earlier than the code
++dnl that sets the variables it relies on:
++_LT_ENABLE_INSTALL
++
++dnl _LTDL_MODE specific code must be called at least once:
++_LTDL_MODE_DISPATCH
++
++# In order that ltdl.c can compile, find out the first AC_CONFIG_HEADERS
++# the user used.  This is so that ltdl.h can pick up the parent projects
++# config.h file, The first file in AC_CONFIG_HEADERS must contain the
++# definitions required by ltdl.c.
++# FIXME: Remove use of undocumented AC_LIST_HEADERS (2.59 compatibility).
++AC_CONFIG_COMMANDS_PRE([dnl
++m4_pattern_allow([^LT_CONFIG_H$])dnl
++m4_ifset([AH_HEADER],
++    [LT_CONFIG_H=AH_HEADER],
++    [m4_ifset([AC_LIST_HEADERS],
++	    [LT_CONFIG_H=`echo "AC_LIST_HEADERS" | $SED 's,^[[      ]]*,,;s,[[ :]].*$,,'`],
++	[])])])
++AC_SUBST([LT_CONFIG_H])
++
++AC_CHECK_HEADERS([unistd.h dl.h sys/dl.h dld.h mach-o/dyld.h dirent.h],
++	[], [], [AC_INCLUDES_DEFAULT])
++
++AC_CHECK_FUNCS([closedir opendir readdir], [], [AC_LIBOBJ([lt__dirent])])
++AC_CHECK_FUNCS([strlcat strlcpy], [], [AC_LIBOBJ([lt__strl])])
++
++AC_DEFINE_UNQUOTED([LT_LIBEXT],["$libext"],[The archive extension])
++
++name=ltdl
++LTDLOPEN=`eval "\\$ECHO \"$libname_spec\""`
++AC_SUBST([LTDLOPEN])
++])# _LTDL_SETUP
++
++
++# _LT_ENABLE_INSTALL
++# ------------------
++m4_define([_LT_ENABLE_INSTALL],
++[AC_ARG_ENABLE([ltdl-install],
++    [AS_HELP_STRING([--enable-ltdl-install], [install libltdl])])
++
++case ,${enable_ltdl_install},${enable_ltdl_convenience} in
++  *yes*) ;;
++  *) enable_ltdl_convenience=yes ;;
++esac
++
++m4_ifdef([AM_CONDITIONAL],
++[AM_CONDITIONAL(INSTALL_LTDL, test x"${enable_ltdl_install-no}" != xno)
++ AM_CONDITIONAL(CONVENIENCE_LTDL, test x"${enable_ltdl_convenience-no}" != xno)])
++])# _LT_ENABLE_INSTALL
++
++
++# LT_SYS_DLOPEN_DEPLIBS
++# ---------------------
++AC_DEFUN([LT_SYS_DLOPEN_DEPLIBS],
++[AC_REQUIRE([AC_CANONICAL_HOST])dnl
++AC_CACHE_CHECK([whether deplibs are loaded by dlopen],
++  [lt_cv_sys_dlopen_deplibs],
++  [# PORTME does your system automatically load deplibs for dlopen?
++  # or its logical equivalent (e.g. shl_load for HP-UX < 11)
++  # For now, we just catch OSes we know something about -- in the
++  # future, we'll try test this programmatically.
++  lt_cv_sys_dlopen_deplibs=unknown
++  case $host_os in
++  aix3*|aix4.1.*|aix4.2.*)
++    # Unknown whether this is true for these versions of AIX, but
++    # we want this `case' here to explicitly catch those versions.
++    lt_cv_sys_dlopen_deplibs=unknown
++    ;;
++  aix[[4-9]]*)
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  amigaos*)
++    case $host_cpu in
++    powerpc)
++      lt_cv_sys_dlopen_deplibs=no
++      ;;
++    esac
++    ;;
++  darwin*)
++    # Assuming the user has installed a libdl from somewhere, this is true
++    # If you are looking for one http://www.opendarwin.org/projects/dlcompat
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  freebsd* | dragonfly*)
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  gnu* | linux* | k*bsd*-gnu)
++    # GNU and its variants, using gnu ld.so (Glibc)
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  hpux10*|hpux11*)
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  interix*)
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  irix[[12345]]*|irix6.[[01]]*)
++    # Catch all versions of IRIX before 6.2, and indicate that we don't
++    # know how it worked for any of those versions.
++    lt_cv_sys_dlopen_deplibs=unknown
++    ;;
++  irix*)
++    # The case above catches anything before 6.2, and it's known that
++    # at 6.2 and later dlopen does load deplibs.
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  netbsd*)
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  openbsd*)
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  osf[[1234]]*)
++    # dlopen did load deplibs (at least at 4.x), but until the 5.x series,
++    # it did *not* use an RPATH in a shared library to find objects the
++    # library depends on, so we explicitly say `no'.
++    lt_cv_sys_dlopen_deplibs=no
++    ;;
++  osf5.0|osf5.0a|osf5.1)
++    # dlopen *does* load deplibs and with the right loader patch applied
++    # it even uses RPATH in a shared library to search for shared objects
++    # that the library depends on, but there's no easy way to know if that
++    # patch is installed.  Since this is the case, all we can really
++    # say is unknown -- it depends on the patch being installed.  If
++    # it is, this changes to `yes'.  Without it, it would be `no'.
++    lt_cv_sys_dlopen_deplibs=unknown
++    ;;
++  osf*)
++    # the two cases above should catch all versions of osf <= 5.1.  Read
++    # the comments above for what we know about them.
++    # At > 5.1, deplibs are loaded *and* any RPATH in a shared library
++    # is used to find them so we can finally say `yes'.
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  qnx*)
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  solaris*)
++    lt_cv_sys_dlopen_deplibs=yes
++    ;;
++  sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
++    libltdl_cv_sys_dlopen_deplibs=yes
++    ;;
++  esac
++  ])
++if test "$lt_cv_sys_dlopen_deplibs" != yes; then
++ AC_DEFINE([LTDL_DLOPEN_DEPLIBS], [1],
++    [Define if the OS needs help to load dependent libraries for dlopen().])
++fi
++])# LT_SYS_DLOPEN_DEPLIBS
++
++# Old name:
++AU_ALIAS([AC_LTDL_SYS_DLOPEN_DEPLIBS], [LT_SYS_DLOPEN_DEPLIBS])
++dnl aclocal-1.4 backwards compatibility:
++dnl AC_DEFUN([AC_LTDL_SYS_DLOPEN_DEPLIBS], [])
++
++
++# LT_SYS_MODULE_EXT
++# -----------------
++AC_DEFUN([LT_SYS_MODULE_EXT],
++[m4_require([_LT_SYS_DYNAMIC_LINKER])dnl
++AC_CACHE_CHECK([which extension is used for runtime loadable modules],
++  [libltdl_cv_shlibext],
++[
++module=yes
++eval libltdl_cv_shlibext=$shrext_cmds
++  ])
++if test -n "$libltdl_cv_shlibext"; then
++  m4_pattern_allow([LT_MODULE_EXT])dnl
++  AC_DEFINE_UNQUOTED([LT_MODULE_EXT], ["$libltdl_cv_shlibext"],
++    [Define to the extension used for runtime loadable modules, say, ".so".])
++fi
++])# LT_SYS_MODULE_EXT
++
++# Old name:
++AU_ALIAS([AC_LTDL_SHLIBEXT], [LT_SYS_MODULE_EXT])
++dnl aclocal-1.4 backwards compatibility:
++dnl AC_DEFUN([AC_LTDL_SHLIBEXT], [])
++
++
++# LT_SYS_MODULE_PATH
++# ------------------
++AC_DEFUN([LT_SYS_MODULE_PATH],
++[m4_require([_LT_SYS_DYNAMIC_LINKER])dnl
++AC_CACHE_CHECK([which variable specifies run-time module search path],
++  [lt_cv_module_path_var], [lt_cv_module_path_var="$shlibpath_var"])
++if test -n "$lt_cv_module_path_var"; then
++  m4_pattern_allow([LT_MODULE_PATH_VAR])dnl
++  AC_DEFINE_UNQUOTED([LT_MODULE_PATH_VAR], ["$lt_cv_module_path_var"],
++    [Define to the name of the environment variable that determines the run-time module search path.])
++fi
++])# LT_SYS_MODULE_PATH
++
++# Old name:
++AU_ALIAS([AC_LTDL_SHLIBPATH], [LT_SYS_MODULE_PATH])
++dnl aclocal-1.4 backwards compatibility:
++dnl AC_DEFUN([AC_LTDL_SHLIBPATH], [])
++
++
++# LT_SYS_DLSEARCH_PATH
++# --------------------
++AC_DEFUN([LT_SYS_DLSEARCH_PATH],
++[m4_require([_LT_SYS_DYNAMIC_LINKER])dnl
++AC_CACHE_CHECK([for the default library search path],
++  [lt_cv_sys_dlsearch_path],
++  [lt_cv_sys_dlsearch_path="$sys_lib_dlsearch_path_spec"])
++if test -n "$lt_cv_sys_dlsearch_path"; then
++  sys_dlsearch_path=
++  for dir in $lt_cv_sys_dlsearch_path; do
++    if test -z "$sys_dlsearch_path"; then
++      sys_dlsearch_path="$dir"
++    else
++      sys_dlsearch_path="$sys_dlsearch_path$PATH_SEPARATOR$dir"
++    fi
++  done
++  m4_pattern_allow([LT_DLSEARCH_PATH])dnl
++  AC_DEFINE_UNQUOTED([LT_DLSEARCH_PATH], ["$sys_dlsearch_path"],
++    [Define to the system default library search path.])
++fi
++])# LT_SYS_DLSEARCH_PATH
++
++# Old name:
++AU_ALIAS([AC_LTDL_SYSSEARCHPATH], [LT_SYS_DLSEARCH_PATH])
++dnl aclocal-1.4 backwards compatibility:
++dnl AC_DEFUN([AC_LTDL_SYSSEARCHPATH], [])
++
++
++# _LT_CHECK_DLPREOPEN
++# -------------------
++m4_defun([_LT_CHECK_DLPREOPEN],
++[m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
++AC_CACHE_CHECK([whether libtool supports -dlopen/-dlpreopen],
++  [libltdl_cv_preloaded_symbols],
++  [if test -n "$lt_cv_sys_global_symbol_pipe"; then
++    libltdl_cv_preloaded_symbols=yes
++  else
++    libltdl_cv_preloaded_symbols=no
++  fi
++  ])
++if test x"$libltdl_cv_preloaded_symbols" = xyes; then
++  AC_DEFINE([HAVE_PRELOADED_SYMBOLS], [1],
++    [Define if libtool can extract symbol lists from object files.])
++fi
++])# _LT_CHECK_DLPREOPEN
++
++
++# LT_LIB_DLLOAD
++# -------------
++AC_DEFUN([LT_LIB_DLLOAD],
++[m4_pattern_allow([^LT_DLLOADERS$])
++LT_DLLOADERS=
++AC_SUBST([LT_DLLOADERS])
++
++AC_LANG_PUSH([C])
++
++LIBADD_DLOPEN=
++AC_SEARCH_LIBS([dlopen], [dl],
++	[AC_DEFINE([HAVE_LIBDL], [1],
++		   [Define if you have the libdl library or equivalent.])
++	if test "$ac_cv_search_dlopen" != "none required" ; then
++	  LIBADD_DLOPEN="-ldl"
++	fi
++	libltdl_cv_lib_dl_dlopen="yes"
++	LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dlopen.la"],
++    [AC_LINK_IFELSE([AC_LANG_PROGRAM([[#if HAVE_DLFCN_H
++#  include <dlfcn.h>
++#endif
++    ]], [[dlopen(0, 0);]])],
++	    [AC_DEFINE([HAVE_LIBDL], [1],
++		       [Define if you have the libdl library or equivalent.])
++	    libltdl_cv_func_dlopen="yes"
++	    LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dlopen.la"],
++	[AC_CHECK_LIB([svld], [dlopen],
++		[AC_DEFINE([HAVE_LIBDL], [1],
++			 [Define if you have the libdl library or equivalent.])
++	        LIBADD_DLOPEN="-lsvld" libltdl_cv_func_dlopen="yes"
++		LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dlopen.la"])])])
++if test x"$libltdl_cv_func_dlopen" = xyes || test x"$libltdl_cv_lib_dl_dlopen" = xyes
++then
++  lt_save_LIBS="$LIBS"
++  LIBS="$LIBS $LIBADD_DLOPEN"
++  AC_CHECK_FUNCS([dlerror])
++  LIBS="$lt_save_LIBS"
++fi
++AC_SUBST([LIBADD_DLOPEN])
++
++LIBADD_SHL_LOAD=
++AC_CHECK_FUNC([shl_load],
++	[AC_DEFINE([HAVE_SHL_LOAD], [1],
++		   [Define if you have the shl_load function.])
++	LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}shl_load.la"],
++    [AC_CHECK_LIB([dld], [shl_load],
++	    [AC_DEFINE([HAVE_SHL_LOAD], [1],
++		       [Define if you have the shl_load function.])
++	    LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}shl_load.la"
++	    LIBADD_SHL_LOAD="-ldld"])])
++AC_SUBST([LIBADD_SHL_LOAD])
++
++case $host_os in
++darwin[[1567]].*)
++# We only want this for pre-Mac OS X 10.4.
++  AC_CHECK_FUNC([_dyld_func_lookup],
++	[AC_DEFINE([HAVE_DYLD], [1],
++		   [Define if you have the _dyld_func_lookup function.])
++	LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}dyld.la"])
++  ;;
++beos*)
++  LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}load_add_on.la"
++  ;;
++cygwin* | mingw* | os2* | pw32*)
++  AC_CHECK_DECLS