Merged to actionmonkey stage 1! Yay.
authorbenjamin@smedbergs.us
Fri, 25 Jan 2008 12:07:10 -0500
changeset 81 c44369c08f6589473ff14827f7c0001428eae19e
parent 80 07783adadb3b0f82cea9c4f71d2f410d3ccb5c17
child 82 ba505859ba00a5a9298ad653bb5e124cb263c5f4
push id1
push userbsmedberg@mozilla.com
push dateTue, 15 Apr 2008 21:51:22 +0000
Merged to actionmonkey stage 1! Yay.
NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS
NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS2
TArray-allocator
clientpy-skipcheckouts
comarray.patch
compmgr-more
comptr-rewrite.patch
dont-delete-gcobjects
fix-garburator.patch
gc-default-context
gcAlloc-factoring
gccontexts
gcobject-nodelete.patch
hashentry-fixups.patch
js-shell-threading
jsref-with-threadsafe-mmgc
jstrace-function
maybegc
necko-deadlocks
no-attributes-configure-check
nsAttrAndChildArray
nsListenerStruct
nsPresShellIterator
nsSlots
nscore-class-annotation-types
prerewrite_fixes.patch
remove-cyclec.patch
remove-nsDOMNodeAllocator
remove-nsDOMNodeAllocator2
rm-gcthingflags
root-contentutils
root-layout-stuff
series
stack-comptr-fixup2
stack-rooting
suspend-request-macros
thread-destructor-fix
unbraced-if-fixes.patch
widget-suck
xpcom-request-contexts
xpcomgcbase.patch
xpconnect-allocations
xpconnect-finalizers
xpconnect-gc-mainthread-only
xpconnect-scope-finalizer-assertions
--- a/NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS
+++ b/NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS
@@ -1,12 +1,16 @@
 diff --git a/xpcom/glue/nsTObserverArray.h b/xpcom/glue/nsTObserverArray.h
 --- a/xpcom/glue/nsTObserverArray.h
 +++ b/xpcom/glue/nsTObserverArray.h
-@@ -203,7 +203,7 @@ class nsTObserverArray : public nsTObser
+@@ -371,9 +371,9 @@ class nsTObserverArray : public nsAutoTO
+ // Note that this macro only works if the array holds pointers to XPCOM objects.
  #define NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS(array_, obstype_, func_, params_) \
    PR_BEGIN_MACRO                                                             \
-     nsTObserverArray<obstype_>::ForwardIterator iter_(array_);               \
+-    nsTObserverArray<obstype_ *>::ForwardIterator iter_(array_);             \
 -    nsCOMPtr<obstype_> obs_;                                                 \
+-    while (iter_.HasMore()) {                                                 \
++    nsTObserverArray<obstype_>::ForwardIterator iter_(array_);               \
 +    obstype_* obs_;                                                          \
-     while ((obs_ = iter_.GetNext())) {                                       \
++    while (iter_.HasMore()) {                                                \
+       obs_ = iter_.GetNext();                                                \
        obs_ -> func_ params_ ;                                                \
      }                                                                        \
new file mode 100644
--- /dev/null
+++ b/NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS2
@@ -0,0 +1,12 @@
+diff --git a/xpcom/glue/nsTObserverArray.h b/xpcom/glue/nsTObserverArray.h
+--- a/xpcom/glue/nsTObserverArray.h
++++ b/xpcom/glue/nsTObserverArray.h
+@@ -371,7 +371,7 @@ class nsTObserverArray : public nsAutoTO
+ // Note that this macro only works if the array holds pointers to XPCOM objects.
+ #define NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS(array_, obstype_, func_, params_) \
+   PR_BEGIN_MACRO                                                             \
+-    nsTObserverArray<obstype_>::ForwardIterator iter_(array_);               \
++    nsTObserverArray<obstype_*>::ForwardIterator iter_(array_);              \
+     obstype_* obs_;                                                          \
+     while (iter_.HasMore()) {                                                \
+       obs_ = iter_.GetNext();                                                \
--- a/TArray-allocator
+++ b/TArray-allocator
@@ -126,17 +126,17 @@ deleted file mode 100644
 -  if (mHdr->mLength >= mHdr->mCapacity)  // should never be greater than...
 -    return;
 -
 -  size_type length = Length();
 -
 -  if (IsAutoArray() && GetAutoArrayBuffer()->mCapacity >= length) {
 -    Header* header = GetAutoArrayBuffer();
 -
--    // copy data, but don't copy the header to avoid overwritng mCapacity
+-    // Copy data, but don't copy the header to avoid overwriting mCapacity
 -    header->mLength = length;
 -    memcpy(header + 1, mHdr + 1, length * elemSize);
 -
 -    NS_Free(mHdr);
 -    mHdr = header;
 -    return;
 -  }
 -
@@ -321,47 +321,47 @@ diff --git a/xpcom/glue/nsTArray.h b/xpc
 +    typedef typename nsTArray_base<Allocator>::index_type index_type;
 +    using nsTArray_base<Allocator>::NoIndex;
 +    using nsTArray_base<Allocator>::Length;
 +    using nsTArray_base<Allocator>::mHdr;
 +    using nsTArray_base<Allocator>::ShrinkCapacity;
  
      //
      // Finalization method
-@@ -507,8 +515,8 @@ class nsTArray : public nsTArray_base {
+@@ -527,8 +535,8 @@ class nsTArray : public nsTArray_base {
      }
  
      // A variation on the AppendElements method defined above.
 -    template<class Item>
 -    elem_type *AppendElements(const nsTArray<Item>& array) {
 +    template<class Item, class ItemAllocator>
 +    elem_type *AppendElements(const nsTArray<Item, ItemAllocator>& array) {
        return AppendElements(array.Elements(), array.Length());
      }
  
-@@ -626,7 +634,7 @@ class nsTArray : public nsTArray_base {
+@@ -646,7 +654,7 @@ class nsTArray : public nsTArray_base {
      //              greater than the current length of the array.
      // @param count the number of elements to insert
      elem_type *InsertElementsAt(index_type index, size_type count) {
 -      if (!nsTArray_base::InsertSlotsAt(index, count, sizeof(elem_type))) {
 +      if (!nsTArray_base<Allocator>::InsertSlotsAt(index, count, sizeof(elem_type))) {
          return nsnull;
        }
  
-@@ -649,7 +657,7 @@ class nsTArray : public nsTArray_base {
+@@ -669,7 +677,7 @@ class nsTArray : public nsTArray_base {
      template<class Item>
      elem_type *InsertElementsAt(index_type index, size_type count,
                                  const Item& item) {
 -      if (!nsTArray_base::InsertSlotsAt(index, count, sizeof(elem_type))) {
 +      if (!nsTArray_base<Allocator>::InsertSlotsAt(index, count, sizeof(elem_type))) {
          return nsnull;
        }
  
-@@ -735,4 +743,260 @@ class nsAutoTArray : public nsTArray<E> 
-     char mAutoBuf[sizeof(Header) + N * sizeof(elem_type)];
+@@ -763,4 +771,256 @@ class nsAutoTArray<E, 0> : public nsTArr
+     nsAutoTArray() {}
  };
  
 +template<class Allocator>
 +typename nsTArray_base<Allocator>::Header
 +nsTArray_base<Allocator>::sEmptyHdr = { 0, 0, 0 };
 +
 +template<class Allocator>
 +nsTArray_base<Allocator>::nsTArray_base()
@@ -404,21 +404,17 @@ diff --git a/xpcom/glue/nsTArray.h b/xpc
 +    header->mCapacity = capacity;
 +    header->mIsAutoArray = 0;
 +    mHdr = header;
 +    
 +    return PR_TRUE;
 +  }
 +
 +  // Use doubling algorithm when forced to increase available capacity.
-+  NS_ASSERTION(mHdr->mCapacity > 0, "should not have buffer of zero size");
-+  size_type temp = mHdr->mCapacity;
-+  while (temp < capacity)
-+    temp <<= 1;
-+  capacity = temp;
++  capacity = PR_MAX(capacity, mHdr->mCapacity << 1);
 +
 +  Header *header;
 +  if (UsesAutoArrayBuffer()) {
 +    // Alloc and copy
 +    header = static_cast<Header*>
 +      (Allocator::Alloc(sizeof(Header) + capacity * elemSize));
 +    if (!header)
 +      return PR_FALSE;
@@ -449,17 +445,17 @@ diff --git a/xpcom/glue/nsTArray.h b/xpc
 +  if (mHdr->mLength >= mHdr->mCapacity)  // should never be greater than...
 +    return;
 +
 +  size_type length = Length();
 +
 +  if (IsAutoArray() && GetAutoArrayBuffer()->mCapacity >= length) {
 +    Header* header = GetAutoArrayBuffer();
 +
-+    // copy data, but don't copy the header to avoid overwritng mCapacity
++    // Copy data, but don't copy the header to avoid overwriting mCapacity
 +    header->mLength = length;
 +    memcpy(header + 1, mHdr + 1, length * elemSize);
 +
 +    Allocator::Free(mHdr);
 +    mHdr = header;
 +    return;
 +  }
 +
deleted file mode 100644
--- a/clientpy-skipcheckouts
+++ /dev/null
@@ -1,51 +0,0 @@
-diff --git a/client.py b/client.py
---- a/client.py
-+++ b/client.py
-@@ -63,9 +63,24 @@ o.add_option("-m", "--mozilla-repo", des
- o.add_option("-m", "--mozilla-repo", dest="mozilla_repo",
-              default=None,
-              help="URL of Mozilla repository to pull from (default: use hg default in .hg/hgrc)")
-+o.add_option("--skip-mozilla", dest="skip_mozilla",
-+             action="store_true", default=False,
-+             help="Skip pulling the Mozilla repository.")
-+
- o.add_option("-t", "--tamarin-repo", dest="tamarin_repo",
-              default=None,
-              help="URL of Tamarin repository to pull from (default: use hg default in js/tamarin/.hg/hgrc; or if that file doesn't exist, use \"" + DEFAULT_TAMARIN_REPO + "\".)")
-+o.add_option("--skip-tamarin", dest="skip_tamarin",
-+             action="store_true", default=False,
-+             help="Skip pulling the Tamarin repository.")
-+
-+o.add_option("--skip-nspr", dest="skip_nspr",
-+             action="store_true", default=False,
-+             help="Skip pulling the NSPR repository.")
-+o.add_option("--skip-nss", dest="skip_nss",
-+             action="store_true", default=False,
-+             help="Skip pulling the NSS repository.")
-+
- o.add_option("--hg", dest="hg", default=os.environ.get('HG', 'hg'),
-              help="The location of the hg binary")
- o.add_option("--cvs", dest="cvs", default=os.environ.get('CVS', 'cvs'),
-@@ -106,10 +121,18 @@ fixup_repo_options(options)
- fixup_repo_options(options)
- 
- if action in ('checkout', 'co'):
--    do_cvs_checkout(NSPR_DIRS, NSPR_CO_TAG, options.cvsroot, options.cvs)
--    do_cvs_checkout(NSS_DIRS, NSS_CO_TAG, options.cvsroot, options.cvs)
--    do_hg_pull('js/tamarin', options.tamarin_repo, options.hg)
--    do_hg_pull('.', options.mozilla_repo, options.hg)
-+    if not options.skip_nspr:
-+        do_cvs_checkout(NSPR_DIRS, NSPR_CO_TAG, options.cvsroot, options.cvs)
-+
-+    if not options.skip_nss:
-+        do_cvs_checkout(NSS_DIRS, NSS_CO_TAG, options.cvsroot, options.cvs)
-+
-+    if not options.skip_tamarin:
-+        do_hg_pull('js/tamarin', options.tamarin_repo, options.hg)
-+
-+    if not options.skip_mozilla:
-+        do_hg_pull('.', options.mozilla_repo, options.hg)
-+
- else:
-     o.print_help()
-     sys.exit(2)
--- a/comarray.patch
+++ b/comarray.patch
@@ -23,17 +23,17 @@ diff --git a/browser/components/migratio
  class nsIPrefService;
 -class nsVoidArray;
  
  class nsSeamonkeyProfileMigrator : public nsNetscapeProfileMigratorBase, 
                                     public nsIBrowserProfileMigrator
 diff --git a/content/base/public/nsContentUtils.h b/content/base/public/nsContentUtils.h
 --- a/content/base/public/nsContentUtils.h
 +++ b/content/base/public/nsContentUtils.h
-@@ -89,7 +89,6 @@ class nsIScriptContext;
+@@ -92,7 +92,6 @@ class nsIScriptContext;
  class nsIScriptContext;
  template<class E> class nsCOMArray;
  class nsIPref;
 -class nsVoidArray;
  struct JSRuntime;
  class nsICaseConversion;
  class nsIWidget;
 diff --git a/content/base/public/nsIContent.h b/content/base/public/nsIContent.h
@@ -76,27 +76,16 @@ diff --git a/content/base/src/nsRange.h 
  #include "nsIDOMNode.h"
  #include "prmon.h"
  #include "nsStubMutationObserver.h"
 -
 -class nsVoidArray;
  
  // -------------------------------------------------------------------------------
  
-diff --git a/content/events/src/nsEventListenerManager.h b/content/events/src/nsEventListenerManager.h
---- a/content/events/src/nsEventListenerManager.h
-+++ b/content/events/src/nsEventListenerManager.h
-@@ -49,7 +49,6 @@
- #include "nsCycleCollectionParticipant.h"
- 
- class nsIDOMEvent;
--class nsVoidArray;
- class nsIAtom;
- struct EventTypeData;
- 
 diff --git a/editor/libeditor/html/nsHTMLEditRules.h b/editor/libeditor/html/nsHTMLEditRules.h
 --- a/editor/libeditor/html/nsHTMLEditRules.h
 +++ b/editor/libeditor/html/nsHTMLEditRules.h
 @@ -49,7 +49,6 @@
  #include "TypeInState.h"
  #include "nsReadableUtils.h"
  
 -class nsVoidArray;
--- a/compmgr-more
+++ b/compmgr-more
@@ -1,346 +1,326 @@
 diff --git a/xpcom/components/nsComponentManager.cpp b/xpcom/components/nsComponentManager.cpp
 --- a/xpcom/components/nsComponentManager.cpp
 +++ b/xpcom/components/nsComponentManager.cpp
-@@ -172,8 +172,8 @@ nsCreateInstanceFromCategory::get(const 
-      */
-     nsresult rv;
-     nsXPIDLCString value;
--    nsCOMPtr<nsIComponentManager> compMgr;
--    nsCOMPtr<nsICategoryManager> catman =
-+    nsIComponentManager* compMgr = nsnull;
-+    nsICategoryManager* catman =
-         do_GetService(kCategoryManagerCID, &rv);
- 
-     void *result = NULL;
-@@ -194,7 +194,7 @@ nsCreateInstanceFromCategory::get(const 
-         rv = NS_ERROR_SERVICE_NOT_AVAILABLE;
-         goto error;
-     }
--    NS_GetComponentManager(getter_AddRefs(compMgr));
-+    NS_GetComponentManager(&compMgr);
-     if (!compMgr) {
-         rv = NS_ERROR_SERVICE_NOT_AVAILABLE;
-         goto error;
-@@ -216,7 +216,7 @@ nsGetServiceFromCategory::get(const nsII
+@@ -168,7 +168,7 @@ nsGetServiceFromCategory::get(const nsII
  {
      nsresult rv;
      nsXPIDLCString value;
 -    nsCOMPtr<nsICategoryManager> catman;
 +    nsICategoryManager* catman = nsnull;
      void *result = NULL;
      nsComponentManagerImpl *compMgr = nsComponentManagerImpl::gComponentManager;
      if (!compMgr) {
-@@ -232,7 +232,7 @@ nsGetServiceFromCategory::get(const nsII
+@@ -184,7 +184,7 @@ nsGetServiceFromCategory::get(const nsII
  
      rv = compMgr->nsComponentManagerImpl::GetService(kCategoryManagerCID,
                                                       NS_GET_IID(nsICategoryManager),
 -                                                     getter_AddRefs(catman));
 +                                                     (void**)&catman);
      if (NS_FAILED(rv)) goto error;
  
      /* find the contractID for category.entry */
-@@ -563,12 +563,12 @@ ConvertFactoryEntryToCID(PLDHashTable *t
+@@ -515,12 +515,12 @@ ConvertFactoryEntryToCID(PLDHashTable *t
                           void *data, nsISupports **retval)
  {
      nsresult rv;
 -    nsCOMPtr<nsISupportsID> wrapper;
 +    nsISupportsID* wrapper = nsnull;
  
      nsComponentManagerImpl *cm = static_cast<nsComponentManagerImpl *>(data);
  
      rv = cm->CreateInstanceByContractID(NS_SUPPORTS_ID_CONTRACTID, nsnull,
 -           NS_GET_IID(nsISupportsID), getter_AddRefs(wrapper));
 +           NS_GET_IID(nsISupportsID), (void**)&wrapper);
  
      NS_ENSURE_SUCCESS(rv, rv);
  
-@@ -593,12 +593,12 @@ ConvertContractIDKeyToString(PLDHashTabl
+@@ -545,12 +545,12 @@ ConvertContractIDKeyToString(PLDHashTabl
                               void *data, nsISupports **retval)
  {
      nsresult rv;
 -    nsCOMPtr<nsISupportsCString> wrapper;
 +    nsISupportsCString* wrapper = nsnull;
  
      nsComponentManagerImpl *cm = static_cast<nsComponentManagerImpl *>(data);
  
      rv = cm->CreateInstanceByContractID(NS_SUPPORTS_CSTRING_CONTRACTID, nsnull,
 -                NS_GET_IID(nsISupportsCString), getter_AddRefs(wrapper));
 +                NS_GET_IID(nsISupportsCString), (void**)&wrapper);
  
      NS_ENSURE_SUCCESS(rv, rv);
  
-@@ -616,10 +616,10 @@ static nsresult GetLocationFromDirectory
+@@ -568,10 +568,10 @@ static nsresult GetLocationFromDirectory
  static nsresult GetLocationFromDirectoryService(const char* prop,
                                                  nsIFile** aDirectory)
  {
 -    nsCOMPtr<nsIProperties> directoryService;
 +    nsIProperties* directoryService = nsnull;
      nsDirectoryService::Create(nsnull,
                                 NS_GET_IID(nsIProperties),
 -                               getter_AddRefs(directoryService));
 +                               (void**)&directoryService);
  
      if (!directoryService)
          return NS_ERROR_FAILURE;
-@@ -895,12 +895,12 @@ nsComponentManagerImpl::ReadPersistentRe
+@@ -847,12 +847,12 @@ nsComponentManagerImpl::ReadPersistentRe
          return NS_ERROR_FILE_NOT_FOUND;
      }
  
 -    nsCOMPtr<nsIFile> file;
 -    mRegistryFile->Clone(getter_AddRefs(file));
 +    nsIFile* file = nsnull;
 +    mRegistryFile->Clone(&file);
      if (!file)
          return NS_ERROR_OUT_OF_MEMORY;
  
 -    nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(file));
 +    nsILocalFile* localFile(do_QueryInterface(file));
  
      rv = localFile->OpenNSPRFileDesc(PR_RDONLY, 0444, &fd);
      if (NS_FAILED(rv))
-@@ -975,13 +975,13 @@ nsComponentManagerImpl::ReadPersistentRe
+@@ -927,13 +927,13 @@ nsComponentManagerImpl::ReadPersistentRe
  
          PRInt64 a = nsCRT::atoll(values[1]);
  
 -        nsCOMPtr<nsILocalFile> lf;
 +        nsILocalFile* lf = nsnull;
          rv = FileForRegistryLocation(nsDependentCString(values[0], lengths[0]),
 -                                     getter_AddRefs(lf));
 +                                     &lf);
          if (NS_FAILED(rv))
              continue;
  
 -        nsCOMPtr<nsIHashable> lfhash(do_QueryInterface(lf));
 +        nsIHashable* lfhash(do_QueryInterface(lf));
          if (!lf) {
              NS_ERROR("nsLocalFile does not implement nsIHashable");
              continue;
-@@ -1213,7 +1213,7 @@ ClassIDWriter(PLDHashTable *table,
+@@ -1165,7 +1165,7 @@ ClassIDWriter(PLDHashTable *table,
  
      char *contractID = nsnull, *className = nsnull;
  
 -    nsCOMPtr<nsIClassInfo> classInfo = do_QueryInterface(factoryEntry->mFactory);
 +    nsIClassInfo* classInfo = do_QueryInterface(factoryEntry->mFactory);
      if (classInfo)
      {
          classInfo->GetContractID(&contractID);
-@@ -1258,7 +1258,7 @@ AutoRegEntryWriter(nsIHashable *aKey, PR
+@@ -1210,7 +1210,7 @@ AutoRegEntryWriter(nsIHashable *aKey, PR
  {
      PRFileDesc* fd = (PRFileDesc*) aClosure;
  
 -    nsCOMPtr<nsILocalFile> lf(do_QueryInterface(aKey));
 +    nsILocalFile* lf(do_QueryInterface(aKey));
  
      nsCAutoString location;
      nsComponentManagerImpl::gComponentManager->
-@@ -1275,12 +1275,12 @@ nsComponentManagerImpl::WritePersistentR
+@@ -1227,12 +1227,12 @@ nsComponentManagerImpl::WritePersistentR
      if (!mRegistryFile)
          return NS_ERROR_FAILURE;  // this should have been set by Init().
  
 -    nsCOMPtr<nsIFile> file;
 -    mRegistryFile->Clone(getter_AddRefs(file));
 +    nsIFile* file = nsnull;
 +    mRegistryFile->Clone(&file);
      if (!file)
          return NS_ERROR_OUT_OF_MEMORY;
  
 -    nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(file));
 +    nsILocalFile* localFile(do_QueryInterface(file));
  
      nsCAutoString originalLeafName;
      localFile->GetNativeLeafName(originalLeafName);
-@@ -1360,8 +1360,8 @@ out:
+@@ -1312,8 +1312,8 @@ out:
      if(exists && NS_FAILED(mRegistryFile->Remove(PR_FALSE)))
          return PR_FALSE;
  
 -    nsCOMPtr<nsIFile> parent;
 -    mRegistryFile->GetParent(getter_AddRefs(parent));
 +    nsIFile* parent = nsnull;
 +    mRegistryFile->GetParent(&parent);
  
      rv = localFile->MoveToNative(parent, originalLeafName);
      mRegistryDirty = PR_FALSE;
-@@ -1501,7 +1501,7 @@ nsComponentManagerImpl::GetClassObject(c
+@@ -1453,7 +1453,7 @@ nsComponentManagerImpl::GetClassObject(c
  {
      nsresult rv;
  
 -    nsCOMPtr<nsIFactory> factory;
 +    nsIFactory* factory = nsnull;
  
  #ifdef PR_LOGGING
      if (PR_LOG_TEST(nsComponentManagerLog, PR_LOG_DEBUG))
-@@ -1515,7 +1515,7 @@ nsComponentManagerImpl::GetClassObject(c
+@@ -1467,7 +1467,7 @@ nsComponentManagerImpl::GetClassObject(c
  
      PR_ASSERT(aResult != nsnull);
  
 -    rv = FindFactory(aClass, getter_AddRefs(factory));
 +    rv = FindFactory(aClass, &factory);
      if (NS_FAILED(rv)) return rv;
  
      rv = factory->QueryInterface(aIID, aResult);
-@@ -1534,7 +1534,7 @@ nsComponentManagerImpl::GetClassObjectBy
+@@ -1486,7 +1486,7 @@ nsComponentManagerImpl::GetClassObjectBy
  {
      nsresult rv;
  
 -    nsCOMPtr<nsIFactory> factory;
 +    nsIFactory* factory = nsnull;
  
  #ifdef PR_LOGGING
      if (PR_LOG_TEST(nsComponentManagerLog, PR_LOG_DEBUG))
-@@ -1545,7 +1545,7 @@ nsComponentManagerImpl::GetClassObjectBy
+@@ -1497,7 +1497,7 @@ nsComponentManagerImpl::GetClassObjectBy
  
      PR_ASSERT(aResult != nsnull);
  
 -    rv = FindFactory(contractID, strlen(contractID), getter_AddRefs(factory));
 +    rv = FindFactory(contractID, strlen(contractID), &factory);
      if (NS_FAILED(rv)) return rv;
  
      rv = factory->QueryInterface(aIID, aResult);
-@@ -1910,7 +1910,7 @@ nsComponentManagerImpl::GetService(const
+@@ -1862,7 +1862,7 @@ nsComponentManagerImpl::GetService(const
      }
  
      if (entry && entry->mServiceObject) {
 -        nsCOMPtr<nsISupports> supports = entry->mServiceObject;
 +        nsISupports* supports = entry->mServiceObject;
          mon.Exit();
          return supports->QueryInterface(aIID, result);
      }
-@@ -1920,13 +1920,13 @@ nsComponentManagerImpl::GetService(const
+@@ -1872,13 +1872,13 @@ nsComponentManagerImpl::GetService(const
      if (NS_FAILED(rv))
          return rv; // NOP_AND_BREAK
  #endif
 -    nsCOMPtr<nsISupports> service;
 +    nsISupports* service = nsnull;
      // We need to not be holding the service manager's monitor while calling
      // CreateInstance, because it invokes user code which could try to re-enter
      // the service manager:
      mon.Exit();
  
 -    rv = CreateInstance(aClass, nsnull, aIID, getter_AddRefs(service));
 +    rv = CreateInstance(aClass, nsnull, aIID, (void**)&service);
  
      mon.Enter();
  
-@@ -1950,7 +1950,7 @@ nsComponentManagerImpl::GetService(const
+@@ -1902,7 +1902,7 @@ nsComponentManagerImpl::GetService(const
      }
  
      entry->mServiceObject = service;
 -    *result = service.get();
 +    *result = service;
      if (!*result) {
          NS_ERROR("Factory did not return an object but returned success!");
          return NS_ERROR_SERVICE_NOT_FOUND;
-@@ -2100,8 +2100,8 @@ nsComponentManagerImpl::IsServiceInstant
+@@ -2052,8 +2052,8 @@ nsComponentManagerImpl::IsServiceInstant
      }
  
      if (entry && entry->mServiceObject) {
 -        nsCOMPtr<nsISupports> service;
 -        rv = entry->mServiceObject->QueryInterface(aIID, getter_AddRefs(service));
 +        nsISupports* service = nsnull;
 +        rv = entry->mServiceObject->QueryInterface(aIID, (void**)&service);
          *result = (service!=nsnull);
      }
      return rv;
-@@ -2145,8 +2145,8 @@ NS_IMETHODIMP nsComponentManagerImpl::Is
+@@ -2097,8 +2097,8 @@ NS_IMETHODIMP nsComponentManagerImpl::Is
      }   // exit monitor
  
      if (entry && entry->mServiceObject) {
 -        nsCOMPtr<nsISupports> service;
 -        rv = entry->mServiceObject->QueryInterface(aIID, getter_AddRefs(service));
 +        nsISupports* service = nsnull;
 +        rv = entry->mServiceObject->QueryInterface(aIID, (void**)&service);
          *result = (service!=nsnull);
      }
      return rv;
-@@ -2211,7 +2211,7 @@ nsComponentManagerImpl::GetServiceByCont
+@@ -2163,7 +2163,7 @@ nsComponentManagerImpl::GetServiceByCont
  
      if (entry) {
          if (entry->mServiceObject) {
 -            nsCOMPtr<nsISupports> serviceObject = entry->mServiceObject;
 +            nsISupports* serviceObject = entry->mServiceObject;
  
              // We need to not be holding the service manager's monitor while calling
              // QueryInterface, because it invokes user code which could try to re-enter
-@@ -2227,13 +2227,13 @@ nsComponentManagerImpl::GetServiceByCont
+@@ -2179,13 +2179,13 @@ nsComponentManagerImpl::GetServiceByCont
  #endif
      }
  
 -    nsCOMPtr<nsISupports> service;
 +    nsISupports* service = nsnull;
      // We need to not be holding the service manager's monitor while calling
      // CreateInstance, because it invokes user code which could try to re-enter
      // the service manager:
      mon.Exit();
  
 -    rv = CreateInstanceByContractID(aContractID, nsnull, aIID, getter_AddRefs(service));
 +    rv = CreateInstanceByContractID(aContractID, nsnull, aIID, (void**)&service);
  
      mon.Enter();
  
-@@ -2259,8 +2259,7 @@ nsComponentManagerImpl::GetServiceByCont
+@@ -2211,8 +2211,7 @@ nsComponentManagerImpl::GetServiceByCont
      }
  
      entry->mServiceObject = service;
 -    *result = service.get();
 -    NS_ADDREF(static_cast<nsISupports*>(*result));
 +    *result = service;
      return rv;
  }
  
-@@ -2695,13 +2694,13 @@ nsComponentManagerImpl::LoaderForType(Lo
+@@ -2647,13 +2646,13 @@ nsComponentManagerImpl::LoaderForType(Lo
                   "LoaderType out of range");
  
      if (!mLoaderData[aType].loader) {
 -        nsCOMPtr<nsIModuleLoader> loader;
 +        nsIModuleLoader* loader = nsnull;
          loader = do_GetServiceFromCategory("module-loader",
                                             mLoaderData[aType].type.get());
          if (!loader)
              return nsnull;
  
 -        loader.swap(mLoaderData[aType].loader);
 +        swap(loader, mLoaderData[aType].loader);
      }
  
      return mLoaderData[aType].loader;
-@@ -2712,10 +2711,10 @@ nsComponentManagerImpl::GetAllLoaders()
+@@ -2664,10 +2663,10 @@ nsComponentManagerImpl::GetAllLoaders()
  {
      NS_ASSERTION(mCategoryManager, "nsComponentManager used uninitialized");
  
 -    nsCOMPtr<nsISimpleEnumerator> loaderEnum;
 +    nsISimpleEnumerator* loaderEnum = nsnull;
      mCategoryManager->EnumerateCategory("module-loader",
 -                                        getter_AddRefs(loaderEnum));
 -    nsCOMPtr<nsIUTF8StringEnumerator>
 +                                        &loaderEnum);
 +    nsIUTF8StringEnumerator*
          loaderStrings(do_QueryInterface(loaderEnum));
      if (loaderStrings) {
          PRBool hasMore;
-@@ -2894,7 +2893,7 @@ nsresult
+@@ -2846,7 +2845,7 @@ nsresult
  nsresult
  nsComponentManagerImpl::AutoRegisterImpl(nsIFile   *inDirSpec,
                            nsCOMArray<nsILocalFile> &aLeftovers,
 -                          nsTArray<DeferredModule> &aDeferred)
 +                          nsTArray<DeferredModule, GCAllocator> &aDeferred)
  {
      NS_ASSERTION(inDirSpec, "inDirSpec must not be null");
  
-@@ -2908,7 +2907,7 @@ nsComponentManagerImpl::AutoRegisterImpl
+@@ -2860,7 +2859,7 @@ nsComponentManagerImpl::AutoRegisterImpl
      if (isDir)
          return AutoRegisterDirectory(inDirSpec, aLeftovers, aDeferred);
  
 -    nsCOMPtr<nsILocalFile> lf(do_QueryInterface(inDirSpec));
 +    nsILocalFile* lf(do_QueryInterface(inDirSpec));
      if (!lf)
          return NS_NOINTERFACE;
  
-@@ -2921,19 +2920,19 @@ nsresult
+@@ -2873,19 +2872,19 @@ nsresult
  nsresult
  nsComponentManagerImpl::AutoRegisterDirectory(nsIFile *inDirSpec,
                            nsCOMArray<nsILocalFile>    &aLeftovers,
 -                          nsTArray<DeferredModule>    &aDeferred)
 -{
 -    nsCOMPtr<nsISimpleEnumerator> entries;
 -    nsresult rv = inDirSpec->GetDirectoryEntries(getter_AddRefs(entries));
 +                          nsTArray<DeferredModule, GCAllocator>    &aDeferred)
@@ -357,101 +337,101 @@ diff --git a/xpcom/components/nsComponen
      while (NS_SUCCEEDED(entries->HasMoreElements(&hasMore)) && hasMore) {
 -        entries->GetNext(getter_AddRefs(elem));
 -        nsCOMPtr<nsILocalFile> lf(do_QueryInterface(elem));
 +        entries->GetNext(&elem);
 +        nsILocalFile* lf(do_QueryInterface(elem));
          if (!lf) {
              NS_ERROR("Directory enumerator misbehaving");
              continue;
-@@ -2960,13 +2959,13 @@ nsComponentManagerImpl::AutoRegisterComp
+@@ -2912,13 +2911,13 @@ nsComponentManagerImpl::AutoRegisterComp
  nsComponentManagerImpl::AutoRegisterComponent(PRInt32 unused,
                                                nsIFile *component)
  {
 -    nsCOMPtr<nsILocalFile> lf(do_QueryInterface(component));
 +    nsILocalFile* lf(do_QueryInterface(component));
      if (!lf)
          return NS_NOINTERFACE;
  
      GetAllLoaders();
  
 -    nsTArray<DeferredModule> deferred;
 +    nsTArray<DeferredModule, GCAllocator> deferred;
  
      nsresult rv = AutoRegisterComponent(lf, deferred);
      if (deferred.Length())
-@@ -2977,7 +2976,7 @@ nsComponentManagerImpl::AutoRegisterComp
+@@ -2929,7 +2928,7 @@ nsComponentManagerImpl::AutoRegisterComp
  
  nsresult
  nsComponentManagerImpl::AutoRegisterComponent(nsILocalFile*  aComponentFile,
 -                                   nsTArray<DeferredModule> &aDeferred,
 +                                   nsTArray<DeferredModule, GCAllocator> &aDeferred,
                                     LoaderType                minLoader)
  {
      nsresult rv;
-@@ -2994,7 +2993,7 @@ nsComponentManagerImpl::AutoRegisterComp
+@@ -2946,7 +2945,7 @@ nsComponentManagerImpl::AutoRegisterComp
          extension.LowerCaseEqualsLiteral(".xpt"))
          return NS_OK;
  
 -    nsCOMPtr<nsIHashable> lfhash(do_QueryInterface(aComponentFile));
 +    nsIHashable* lfhash(do_QueryInterface(aComponentFile));
      if (!lfhash) {
          NS_ERROR("localfile not implementing nsIHashable!");
          return NS_NOINTERFACE;
-@@ -3010,11 +3009,11 @@ nsComponentManagerImpl::AutoRegisterComp
+@@ -2962,11 +2961,11 @@ nsComponentManagerImpl::AutoRegisterComp
  
      const char *registryType = nsnull;
  
 -    nsCOMPtr<nsIModule> module;
 +    nsIModule* module = nsnull;
  
      if (minLoader == NS_LOADER_TYPE_NATIVE) {
          rv = mNativeModuleLoader.LoadModule(aComponentFile,
 -                                            getter_AddRefs(module));
 +                                            &module);
          if (NS_SUCCEEDED(rv)) {
              if (!module) {
                  NS_ERROR("Module loader succeeded without returning a module");
-@@ -3032,7 +3031,7 @@ nsComponentManagerImpl::AutoRegisterComp
+@@ -2984,7 +2983,7 @@ nsComponentManagerImpl::AutoRegisterComp
              if (!loader)
                  continue;
  
 -            rv = loader->LoadModule(aComponentFile, getter_AddRefs(module));
 +            rv = loader->LoadModule(aComponentFile, &module);
              if (NS_SUCCEEDED(rv)) {
                  if (!module) {
                      NS_ERROR("Module loader succeeded without returning a module.");
-@@ -3071,7 +3070,7 @@ void
+@@ -3023,7 +3022,7 @@ void
  void
  nsComponentManagerImpl::LoadLeftoverComponents(
    nsCOMArray<nsILocalFile> &aLeftovers,
 -  nsTArray<DeferredModule> &aDeferred,
 +  nsTArray<DeferredModule, GCAllocator> &aDeferred,
    LoaderType                minLoader)
  {
      NS_ASSERTION(minLoader >= GetLoaderCount(), "Corrupted minLoader");
-@@ -3097,7 +3096,7 @@ nsComponentManagerImpl::LoadLeftoverComp
+@@ -3049,7 +3048,7 @@ nsComponentManagerImpl::LoadLeftoverComp
  }
  
  void
 -nsComponentManagerImpl::LoadDeferredModules(nsTArray<DeferredModule> &aDeferred)
 +nsComponentManagerImpl::LoadDeferredModules(nsTArray<DeferredModule, GCAllocator> &aDeferred)
  {
      // We keep looping through deferred components until one of
      // 1) they're all gone
-@@ -3116,7 +3115,7 @@ nsComponentManagerImpl::LoadDeferredModu
+@@ -3068,7 +3067,7 @@ nsComponentManagerImpl::LoadDeferredModu
                                                   d.location.get(),
                                                   d.type);
              if (NS_SUCCEEDED(rv) && d.modTime != 0) {
 -                nsCOMPtr<nsIHashable> lfhash(do_QueryInterface(d.file));
 +                nsIHashable* lfhash(do_QueryInterface(d.file));
                  if (lfhash)
                      mAutoRegEntries.Put(lfhash, d.modTime);
              }
-@@ -3141,19 +3140,19 @@ nsComponentManagerImpl::AutoUnregisterCo
+@@ -3093,19 +3092,19 @@ nsComponentManagerImpl::AutoUnregisterCo
      if (NS_FAILED(rv))
          return rv;
  
 -    nsCOMPtr<nsILocalFile> lf(do_QueryInterface(component));
 +    nsILocalFile* lf(do_QueryInterface(component));
      if (!lf)
          return NS_NOINTERFACE;
  
@@ -465,44 +445,44 @@ diff --git a/xpcom/components/nsComponen
              if (!loader)
                  continue;
  
 -            if (NS_SUCCEEDED(loader->LoadModule(lf, getter_AddRefs(module))) &&
 +            if (NS_SUCCEEDED(loader->LoadModule(lf, &module)) &&
                  module) {
                  break;
              }
-@@ -3165,7 +3164,7 @@ nsComponentManagerImpl::AutoUnregisterCo
+@@ -3117,7 +3116,7 @@ nsComponentManagerImpl::AutoUnregisterCo
  
      rv = module->UnregisterSelf(this, lf, location.get());
  
 -    nsCOMPtr<nsIHashable> lfhash(do_QueryInterface(lf));
 +    nsIHashable* lfhash(do_QueryInterface(lf));
      mAutoRegEntries.Remove(lfhash);
  
      return rv;
-@@ -3236,7 +3235,7 @@ nsComponentManagerImpl::EnumerateContrac
+@@ -3188,7 +3187,7 @@ nsComponentManagerImpl::EnumerateContrac
  
  static void
  RegisterStaticModule(const char *key, nsIModule* module,
 -                     nsTArray<DeferredModule> &deferred)
 +                     nsTArray<DeferredModule, GCAllocator> &deferred)
  {
      nsresult rv = module->
          RegisterSelf(nsComponentManagerImpl::gComponentManager,
-@@ -3282,7 +3281,7 @@ nsComponentManagerImpl::AutoRegister(nsI
+@@ -3234,7 +3233,7 @@ nsComponentManagerImpl::AutoRegister(nsI
                                    aSpec, "start");
  
      nsCOMArray<nsILocalFile> leftovers;
 -    nsTArray<DeferredModule> deferred;
 +    nsTArray<DeferredModule, GCAllocator> deferred;
  
      if (!aSpec)
          mStaticModuleLoader.EnumerateModules(RegisterStaticModule,
-@@ -3313,18 +3312,18 @@ nsComponentManagerImpl::AutoRegister(nsI
+@@ -3265,18 +3264,18 @@ nsComponentManagerImpl::AutoRegister(nsI
              NS_WARNING("Couldn't register mComponentsDir");
          }
  
 -        nsCOMPtr<nsISimpleEnumerator> dirList;
 +        nsISimpleEnumerator* dirList = nsnull;
          rv = nsDirectoryService::gService->Get(NS_XPCOM_COMPONENT_DIR_LIST,
                                                 NS_GET_IID(nsISimpleEnumerator),
 -                                               getter_AddRefs(dirList));
@@ -516,26 +496,26 @@ diff --git a/xpcom/components/nsComponen
                     hasMore) {
 -                dirList->GetNext(getter_AddRefs(elem));
 -                nsCOMPtr<nsIFile> dir(do_QueryInterface(elem));
 +                dirList->GetNext(&elem);
 +                nsIFile* dir(do_QueryInterface(elem));
                  if (dir) {
                      AutoRegisterImpl(dir, leftovers, deferred);
                  }
-@@ -3344,7 +3343,7 @@ nsComponentManagerImpl::AutoRegister(nsI
+@@ -3296,7 +3295,7 @@ nsComponentManagerImpl::AutoRegister(nsI
          if (deferred.Length())
              LoadDeferredModules(deferred);
  
 -        nsCOMPtr<nsIConsoleService>
 +        nsIConsoleService*
              cs(do_GetService(NS_CONSOLESERVICE_CONTRACTID));
  
          if (cs) {
-@@ -3559,19 +3558,19 @@ nsFactoryEntry::GetFactory(nsIFactory **
+@@ -3511,19 +3510,19 @@ nsFactoryEntry::GetFactory(nsIFactory **
          if (mLoaderType == NS_LOADER_TYPE_INVALID)
              return NS_ERROR_FAILURE;
  
 -        nsCOMPtr<nsIModule> module;
 +        nsIModule* module = nsnull;
  
          if (mLoaderType == NS_LOADER_TYPE_STATIC) {
              rv = nsComponentManagerImpl::gComponentManager->
@@ -549,17 +529,17 @@ diff --git a/xpcom/components/nsComponen
 +            nsILocalFile* moduleFile = nsnull;
              rv = nsComponentManagerImpl::gComponentManager->
                  FileForRegistryLocation(nsDependentCString(mLocationKey),
 -                                        getter_AddRefs(moduleFile));
 +                                        &moduleFile);
              NS_ENSURE_SUCCESS(rv, rv);
  
              nsIModuleLoader* loader =
-@@ -3581,7 +3580,7 @@ nsFactoryEntry::GetFactory(nsIFactory **
+@@ -3533,7 +3532,7 @@ nsFactoryEntry::GetFactory(nsIFactory **
                  return NS_ERROR_FAILURE;
  
              rv = loader->LoadModule(moduleFile,
 -                                    getter_AddRefs(module));
 +                                    &module);
          }
  
          if (NS_FAILED(rv))
--- a/comptr-rewrite.patch
+++ b/comptr-rewrite.patch
@@ -852,110 +852,36 @@ diff --git a/xpcom/base/nsAutoPtr.h b/xp
 -  }
 -
 -#endif // !defined(HAVE_CPP_TROUBLE_COMPARING_TO_ZERO)
 -
 -/*****************************************************************************/
 +#define nsRefPtr nsCOMPtr
  
  #endif // !defined(nsAutoPtr_h___)
-diff --git a/xpcom/components/nsCategoryManagerUtils.h b/xpcom/components/nsCategoryManagerUtils.h
---- a/xpcom/components/nsCategoryManagerUtils.h
-+++ b/xpcom/components/nsCategoryManagerUtils.h
-@@ -46,7 +46,7 @@ NS_CreateServicesFromCategory(const char
-                               nsISupports *origin,
-                               const char *observerTopic);
- 
--class NS_COM nsCreateInstanceFromCategory : public nsCOMPtr_helper
-+class NS_COM nsCreateInstanceFromCategory
- {
- public:
-     nsCreateInstanceFromCategory(const char *aCategory, const char *aEntry,
-@@ -58,9 +58,16 @@ public:
-     {
-         // nothing else to do;
-     }
--    virtual nsresult NS_FASTCALL operator()( const nsIID& aIID, void** aInstancePtr) const;
-+
-+    template<class D>
-+    operator D*() const
-+    {
-+        return static_cast<D*>(get(NS_GET_TEMPLATE_IID(D)));
-+    }
- 
- private:
-+    void* get(const nsIID &aIID) const;
-+
-     const char *mCategory;  // Do not free.  This char * is not owned.
-     const char *mEntry;     // Do not free.  This char * is not owned.
- 
 diff --git a/xpcom/components/nsComponentManager.cpp b/xpcom/components/nsComponentManager.cpp
 --- a/xpcom/components/nsComponentManager.cpp
 +++ b/xpcom/components/nsComponentManager.cpp
-@@ -163,8 +163,8 @@ static void GetIDString(const nsID& aCID
+@@ -163,12 +163,13 @@ static void GetIDString(const nsID& aCID
                  (PRUint32) aCID.m3[6], (PRUint32) aCID.m3[7]);
  }
  
 -nsresult
--nsCreateInstanceFromCategory::operator()(const nsIID& aIID, void** aInstancePtr) const
-+void*
-+nsCreateInstanceFromCategory::get(const nsIID& aIID) const
- {
-     /*
-      * If I were a real man, I would consolidate this with
-@@ -176,6 +176,8 @@ nsCreateInstanceFromCategory::operator()
-     nsCOMPtr<nsICategoryManager> catman =
-         do_GetService(kCategoryManagerCID, &rv);
- 
-+    void *result = NULL;
-+
-     if (NS_FAILED(rv)) goto error;
- 
-     if (!mCategory || !mEntry) {
-@@ -193,26 +195,29 @@ nsCreateInstanceFromCategory::operator()
-         goto error;
-     }
-     NS_GetComponentManager(getter_AddRefs(compMgr));
--    if (!compMgr)
--        return NS_ERROR_FAILURE;
--    rv = compMgr->CreateInstanceByContractID(value, mOuter, aIID, aInstancePtr);
-+    if (!compMgr) {
-+        rv = NS_ERROR_SERVICE_NOT_AVAILABLE;
-+        goto error;
-+    }
-+    rv = compMgr->CreateInstanceByContractID(value, mOuter, aIID, &result);
-     if (NS_FAILED(rv)) {
-     error:
--        *aInstancePtr = 0;
-+        result = NULL;
-     }
- 
-     if (mErrorPtr)
-         *mErrorPtr = rv;
--    return rv;
--}
--
--
--nsresult
 -nsGetServiceFromCategory::operator()(const nsIID& aIID, void** aInstancePtr) const
-+    return result;
-+}
-+
-+
 +void*
 +nsGetServiceFromCategory::get(const nsIID& aIID) const
  {
      nsresult rv;
      nsXPIDLCString value;
      nsCOMPtr<nsICategoryManager> catman;
 +    void *result = NULL;
      nsComponentManagerImpl *compMgr = nsComponentManagerImpl::gComponentManager;
      if (!compMgr) {
          rv = NS_ERROR_NOT_INITIALIZED;
-@@ -241,14 +246,14 @@ nsGetServiceFromCategory::operator()(con
+@@ -197,14 +198,14 @@ nsGetServiceFromCategory::operator()(con
  
      rv = compMgr->
          nsComponentManagerImpl::GetServiceByContractID(value,
 -                                                       aIID, aInstancePtr);
 +                                                       aIID, &result);
      if (NS_FAILED(rv)) {
      error:
 -        *aInstancePtr = 0;
--- a/dont-delete-gcobjects
+++ b/dont-delete-gcobjects
@@ -1,22 +1,22 @@
 diff --git a/chrome/src/nsChromeRegistry.cpp b/chrome/src/nsChromeRegistry.cpp
 --- a/chrome/src/nsChromeRegistry.cpp
 +++ b/chrome/src/nsChromeRegistry.cpp
-@@ -329,18 +329,6 @@ nsChromeRegistry::nsProviderArray::Enume
+@@ -334,18 +334,6 @@ nsChromeRegistry::nsProviderArray::Enume
    }
  }
  
 -void
 -nsChromeRegistry::nsProviderArray::Clear()
 -{
 -  PRInt32 i = mArray.Count();
 -  while (i--) {
 -    ProviderEntry* entry = reinterpret_cast<ProviderEntry*>(mArray[i]);
--    delete entry;
+-    NS_GetGC()->Free(entry);
 -  }
 -
 -  mArray.Clear();
 -}
 -
  nsChromeRegistry::PackageEntry::PackageEntry(const nsACString& aPackage) :
    package(aPackage), flags(0)
  {
@@ -30,35 +30,8 @@ diff --git a/chrome/src/nsChromeRegistry
 -    void    Clear();
 +    void    Clear()
 +    {
 +      mArray.Clear();
 +    }
  
    private:
      ProviderEntry* GetProvider(const nsACString& aPreferred, MatchType aType);
-diff --git a/content/xul/document/src/nsXULContentSink.cpp b/content/xul/document/src/nsXULContentSink.cpp
---- a/content/xul/document/src/nsXULContentSink.cpp
-+++ b/content/xul/document/src/nsXULContentSink.cpp
-@@ -940,7 +940,6 @@ XULContentSinkImpl::OpenTag(const PRUnic
-     nsVoidArray* children;
-     rv = mContextStack.GetTopChildren(&children);
-     if (NS_FAILED(rv)) {
--        delete element;
-         return rv;
-     }
- 
-@@ -1147,7 +1146,6 @@ XULContentSinkImpl::OpenScript(const PRU
-           }
- 
-           if (NS_FAILED(rv)) {
--              delete script;
-               return rv;
-           }
- 
-@@ -1162,7 +1160,6 @@ XULContentSinkImpl::OpenScript(const PRU
-       nsVoidArray* children;
-       rv = mContextStack.GetTopChildren(&children);
-       if (NS_FAILED(rv)) {
--          delete script;
-           return rv;
-       }
- 
--- a/fix-garburator.patch
+++ b/fix-garburator.patch
@@ -88,37 +88,37 @@ diff --git a/uriloader/base/nsURILoader.
 -  LOG(("  Downstream DocumentOpenInfo would be: 0x%p", nextLink.get()));
 +  LOG(("  Downstream DocumentOpenInfo would be: 0x%p", nextLink));
    
    // Make sure nextLink starts with the contentListener that said it wanted the
    // results of this decode.
 diff --git a/uriloader/exthandler/nsExternalHelperAppService.cpp b/uriloader/exthandler/nsExternalHelperAppService.cpp
 --- a/uriloader/exthandler/nsExternalHelperAppService.cpp
 +++ b/uriloader/exthandler/nsExternalHelperAppService.cpp
-@@ -621,7 +621,7 @@ NS_IMETHODIMP nsExternalHelperAppService
+@@ -624,7 +624,7 @@ NS_IMETHODIMP nsExternalHelperAppService
      mimeSvc->GetFromTypeAndExtension(aMimeContentType, fileExtension,
                                       getter_AddRefs(mimeInfo));
    } 
 -  LOG(("Type/Ext lookup found 0x%p\n", mimeInfo.get()));
 +  LOG(("Type/Ext lookup found 0x%p\n", mimeInfo));
  
    // No mimeinfo -> we can't continue. probably OOM.
    if (!mimeInfo)
 diff --git a/uriloader/prefetch/nsOfflineCacheUpdate.cpp b/uriloader/prefetch/nsOfflineCacheUpdate.cpp
 --- a/uriloader/prefetch/nsOfflineCacheUpdate.cpp
 +++ b/uriloader/prefetch/nsOfflineCacheUpdate.cpp
-@@ -1112,7 +1112,7 @@ nsOfflineCacheUpdateService::OnStateChan
+@@ -1631,7 +1631,7 @@ nsOfflineCacheUpdateService::OnStateChan
          if (!doc) return NS_OK;
  
          LOG(("nsOfflineCacheUpdateService::OnStateChange [%p, doc=%p]",
 -             this, doc.get()));
 +             this, doc));
  
-         nsRefPtr<nsOfflineCacheUpdate> update;
-         if (mDocUpdates.Get(doc, getter_AddRefs(update))) {
+ 
+         PendingUpdate *pendingUpdate;
 diff --git a/xpcom/io/nsIFastLoadService.idl b/xpcom/io/nsIFastLoadService.idl
 --- a/xpcom/io/nsIFastLoadService.idl
 +++ b/xpcom/io/nsIFastLoadService.idl
 @@ -149,7 +149,7 @@ inline nsresult
  inline nsresult
  NS_AddFastLoadDependency(nsIFile* aFile)
  {
 -    nsCOMPtr<nsIFastLoadService> fastLoadService(do_GetFastLoadService());
@@ -747,17 +747,17 @@ deleted file mode 100644
 -        printf("Should Release and destroy one |TestRefObject|:\n");
 -    }
 -
 -    return 0;
 -}
 diff --git a/xpcom/threads/nsThread.cpp b/xpcom/threads/nsThread.cpp
 --- a/xpcom/threads/nsThread.cpp
 +++ b/xpcom/threads/nsThread.cpp
-@@ -483,7 +483,7 @@ nsThread::ProcessNextEvent(PRBool mayWai
+@@ -503,7 +503,7 @@ nsThread::ProcessNextEvent(PRBool mayWai
    nsresult rv = NS_OK;
  
    if (event) {
 -    LOG(("THRD(%p) running [%p]\n", this, event.get()));
 +    LOG(("THRD(%p) running [%p]\n", this, event));
      ++mRunningEvent;
      event->Run();
      --mRunningEvent;
--- a/gc-default-context
+++ b/gc-default-context
@@ -1,28 +1,28 @@
 diff --git a/js/src/jsapi.cpp b/js/src/jsapi.cpp
 --- a/js/src/jsapi.cpp
 +++ b/js/src/jsapi.cpp
-@@ -2439,6 +2439,12 @@ JS_SetGCParameter(JSRuntime *rt, JSGCPar
+@@ -2427,6 +2427,12 @@ JS_SetGCParameter(JSRuntime *rt, JSGCPar
      }
  }
  
 +JS_PUBLIC_API(void)
 +JS_SetGCDefaultContext(JSContext *cx)
 +{
 +    cx->runtime->gc->defaultGCContext = cx;
 +}
 +
  JS_PUBLIC_API(intN)
  JS_AddExternalStringFinalizer(JSStringFinalizeOp finalizer)
  {
 diff --git a/js/src/jsapi.h b/js/src/jsapi.h
 --- a/js/src/jsapi.h
 +++ b/js/src/jsapi.h
-@@ -1074,6 +1074,24 @@ JS_SetGCParameter(JSRuntime *rt, JSGCPar
+@@ -1077,6 +1077,24 @@ JS_SetGCParameter(JSRuntime *rt, JSGCPar
  JS_SetGCParameter(JSRuntime *rt, JSGCParamKey key, uint32 value);
  
  /*
 + * Specify a JSContext to use as the default context for GC.
 + *
 + * Call this before calling any methods on the MMgc::GC object directly.
 + * Otherwise garbage collection will crash.
 + *
@@ -40,94 +40,99 @@ diff --git a/js/src/jsapi.h b/js/src/jsa
 +
 +/*
   * Add a finalizer for external strings created by JS_NewExternalString (see
   * below) using a type-code returned from this function, and that understands
   * how to free or release the memory pointed at by JS_GetStringChars(str).
 diff --git a/js/src/jsgc.cpp b/js/src/jsgc.cpp
 --- a/js/src/jsgc.cpp
 +++ b/js/src/jsgc.cpp
-@@ -92,18 +92,19 @@ namespace
+@@ -92,12 +92,19 @@ namespace
  }
  
  #ifdef JS_THREADSAFE
--#define PENDING_GC_CONTEXT(gc, thread) ((thread)->pendingGCContext)
--#define PENDING_GC_KIND(gc, thread)    ((thread)->pendingGCKind)
-+#define PENDING_GC_SETTINGS(gc, thread) (thread)
+-#define GC_PENDING_CONTEXT(gc, thread) ((thread)->gcPendingContext)
+-#define GC_PENDING_KIND(gc, thread)    ((thread)->gcPendingKind)
++#define GC_PENDING_SETTINGS(gc, thread) (thread)
  #else
--/* Single-threaded equivalent of JSThread::gcContext. */
--static JSContext *g_pendingGCContext = NULL;
--
--/* Single-threaded equivalent of JSThread::gcKind. */
--static JSGCInvocationKind g_pendingGCKind = GC_NOT_RUNNING;
--
--#define PENDING_GC_CONTEXT(gc, thread) ((gc)->pendingGCContext)
--#define PENDING_GC_KIND(gc, thread)    ((gc)->pendingGCKind)
+-#define GC_PENDING_CONTEXT(gc, thread) ((gc)->gcPendingContext)
+-#define GC_PENDING_KIND(gc, thread)    ((gc)->gcPendingKind)
 -#endif
-+#define PENDING_GC_SETTINGS(gc, thread) (gc)
++#define GC_PENDING_SETTINGS(gc, thread) (gc)
 +#endif
 +
-+#define PENDING_GC_CONTEXT(gc, thread)                                        \
-+    (PENDING_GC_SETTINGS(gc, thread)->pendingGCContext)
++#define GC_PENDING_CONTEXT(gc, thread)                                        \
++    (GC_PENDING_SETTINGS(gc, thread)->gcPendingContext)
 +#define DETERMINE_GC_CONTEXT(gc, thread)                                      \
-+    (PENDING_GC_CONTEXT(gc, thread)                                           \
-+     ? PENDING_GC_CONTEXT(gc, thread)                                         \
++    (GC_PENDING_CONTEXT(gc, thread)                                           \
++     ? GC_PENDING_CONTEXT(gc, thread)                                         \
 +     : gc->defaultGCContext)
-+#define PENDING_GC_KIND(gc, thread)                                           \
-+    (PENDING_GC_SETTINGS(gc, thread)->pendingGCKind)
++#define GC_PENDING_KIND(gc, thread)                                           \
++    (GC_PENDING_SETTINGS(gc, thread)->gcPendingKind)
  
  JS_STATIC_ASSERT(sizeof(JSStackHeader) >= 2 * sizeof(jsval));
  
-@@ -719,11 +720,12 @@ JSGC::JSGC(JSRuntime *_rt)
+@@ -710,11 +717,12 @@ JSGC::JSGC(JSRuntime *_rt)
  JSGC::JSGC(JSRuntime *_rt)
      : GC(MMgc::GCHeap::GetGCHeap()), 
        GCCallback(this),
 +      rt(_rt),
  #ifndef JS_THREADSAFE
-       pendingGCContext(NULL),
-       pendingGCKind(GC_NOT_RUNNING),
+       gcPendingContext(NULL),
+       gcPendingKind(GC_NOT_RUNNING),
  #endif
 -      rt(_rt)
 +      defaultGCContext(NULL)
  {
      /* Incremental mode requires more work; see MMgc docs. */
      incremental = false;
-@@ -744,7 +746,8 @@ JSGC::precollect()
+@@ -735,7 +743,8 @@ JSGC::precollect()
      JSThread *thread = js_GetCurrentThread(rt);
  #endif
  
--    cx = PENDING_GC_CONTEXT(this, thread);
+-    cx = GC_PENDING_CONTEXT(this, thread);
 +    cx = DETERMINE_GC_CONTEXT(this, thread);
 +    JS_ASSERT(cx);
-     gckind = PENDING_GC_KIND(this, thread);
+     gckind = GC_PENDING_KIND(this, thread);
  
      /*
-@@ -856,7 +859,7 @@ JSGC::enterExclusiveGC()
+@@ -847,7 +856,7 @@ JSGC::enterExclusiveGC()
  
      rt->gcPoke = JS_FALSE;
  
--    rt->gcContext = PENDING_GC_CONTEXT(this, thread);
+-    rt->gcContext = GC_PENDING_CONTEXT(this, thread);
 +    rt->gcContext = DETERMINE_GC_CONTEXT(this, thread);
-     rt->gcKind = PENDING_GC_KIND(this, thread);
+     rt->gcKind = GC_PENDING_KIND(this, thread);
  }
  
-@@ -919,7 +922,7 @@ JSGC::postcollect()
+@@ -910,7 +919,7 @@ JSGC::postcollect()
  #ifdef JS_THREADSAFE
      JSThread *thread = js_GetCurrentThread(rt);
  #endif
--    JSContext *cx = PENDING_GC_CONTEXT(this, thread);
+-    JSContext *cx = GC_PENDING_CONTEXT(this, thread);
 +    JSContext *cx = DETERMINE_GC_CONTEXT(this, thread);
-     JSGCInvocationKind gckind = PENDING_GC_KIND(this, thread);
+     JSGCInvocationKind gckind = GC_PENDING_KIND(this, thread);
  
      /* Execute JSGC_END callback outside the lock. */
 diff --git a/js/src/jsgc.h b/js/src/jsgc.h
 --- a/js/src/jsgc.h
 +++ b/js/src/jsgc.h
-@@ -123,6 +123,9 @@ public:
-     JSContext *pendingGCContext;
-     JSGCInvocationKind pendingGCKind;
+@@ -115,15 +115,17 @@ private:
+     virtual void
+     postsweep();
+ 
++    JSRuntime *rt;
++    JSTracer tracer;
++
+ #ifndef JS_THREADSAFE
+ public:
+     JSContext *gcPendingContext;
+     JSGCInvocationKind gcPendingKind;
  #endif
-+
+ 
+-private: 
+-    JSRuntime *rt;
+-    JSTracer tracer;
 +public:
 +    JSContext *defaultGCContext;
  };
  
  JS_BEGIN_EXTERN_C
deleted file mode 100644
--- a/gcAlloc-factoring
+++ /dev/null
@@ -1,174 +0,0 @@
-diff --git a/js/src/jsgc.cpp b/js/src/jsgc.cpp
---- a/js/src/jsgc.cpp
-+++ b/js/src/jsgc.cpp
-@@ -132,6 +132,9 @@ typedef struct JSPtrTableInfo {
-     uint16      linearGrowthThreshold;
- } JSPtrTableInfo;
- 
-+static void *
-+gcAlloc(JSContext *cx, size_t nbytes, int flags);
-+
- #define GC_ITERATOR_TABLE_MIN     4
- #define GC_ITERATOR_TABLE_LINEAR  1024
- 
-@@ -375,11 +378,15 @@ js_InitGC(JSRuntime *rt, uint32 maxbytes
-      * Allocate the object responsible for SpiderMonkey's exact marking.
-      * We enter an MMgc request, temporarily, around this allocation.
-      */
-+#ifdef JS_THREADSAFE
-     rt->gc->OnEnterRequest();
-+#endif
-     rt->gcMarker = new(rt->gc) JSRuntimeGCMarker(rt);
-     if (!rt->gcMarker)
-         return JS_FALSE;
-+#ifdef JS_THREADSAFE
-     rt->gc->OnLeaveRequest();
-+#endif
- 
-     /*
-      * Note: This allocation is from a non-threadsafe allocator.  This is only
-@@ -931,17 +938,44 @@ JSGC::postcollect()
-     }
- }
- 
-+static void *
-+gcAlloc(JSContext *cx, size_t nbytes, int flags)
-+{
-+    JSRuntime *rt = cx->runtime;
-+    JSGC *gc = rt->gc;
-+    JSContext *savedGCContext;
-+    JSGCInvocationKind savedGCKind;
-+    void *p;
-+
-+#ifdef JS_THREADSAFE
-+    JSThread *thread = cx->thread;
-+    JS_ASSERT(thread == js_GetCurrentThread(rt));
-+
-+    JS_ASSERT(!gc->IsGCRunning());
-+    if (gc->IsGCRunning())
-+        return NULL;
-+#endif
-+
-+    /* Enter possible GC region. */
-+    savedGCContext = PENDING_GC_CONTEXT(gc, thread);
-+    PENDING_GC_CONTEXT(gc, thread) = cx;
-+    savedGCKind = PENDING_GC_KIND(gc, thread);
-+    PENDING_GC_KIND(gc, thread) = GC_LAST_DITCH;
-+
-+    p = gc->Alloc(nbytes, flags);
-+
-+    /* Leave possible GC region. */
-+    PENDING_GC_CONTEXT(gc, thread) = savedGCContext;
-+    PENDING_GC_KIND(gc, thread) = savedGCKind;
-+
-+    return p;
-+}
-+
- void *
- js_NewGCThing(JSContext *cx, uintN flags, size_t nbytes)
- {
--    JSRuntime *rt;
-     void *thing;
-     JSLocalRootStack *lrs;
--#ifdef JS_THREADSAFE
--    JSThread *thread;
--#endif
--    JSContext *savedGCContext;
--    JSGCInvocationKind savedGCKind;
- 
-     /*
-      * Since we currently store gcThingFlags for a jsdouble at offset 8,
-@@ -950,32 +984,12 @@ js_NewGCThing(JSContext *cx, uintN flags
-     if ((flags & GCF_TYPEMASK) == GCX_DOUBLE)
-         nbytes++;
- 
--    rt = cx->runtime;
--#ifdef JS_THREADSAFE
--    JS_ASSERT(!rt->gc->IsGCRunning());
--    if (rt->gc->IsGCRunning())
--        return NULL;
--
--    JS_ASSERT(cx->thread == js_GetCurrentThread(rt));
--    thread = cx->thread;
--#endif
--
--    /* Enter possible GC region. */
--    savedGCContext = PENDING_GC_CONTEXT(rt->gc, thread);
--    PENDING_GC_CONTEXT(rt->gc, thread) = cx;
--    savedGCKind = PENDING_GC_KIND(rt->gc, thread);
--    PENDING_GC_KIND(rt->gc, thread) = GC_LAST_DITCH;
--
--    thing = rt->gc->Alloc(nbytes,
--                          gc_type_is_finalized[flags & GCF_TYPEMASK]
--                          ? (MMgc::GC::kZero
--                             | MMgc::GC::kContainsPointers
--                             | MMgc::GC::kFinalize)
--                          : 0);
--
--    /* Leave possible GC region. */
--    PENDING_GC_CONTEXT(rt->gc, thread) = savedGCContext;
--    PENDING_GC_KIND(rt->gc, thread) = savedGCKind;
-+    thing = gcAlloc(cx, nbytes,
-+                    gc_type_is_finalized[flags & GCF_TYPEMASK]
-+                    ? (MMgc::GC::kZero
-+                       | MMgc::GC::kContainsPointers
-+                       | MMgc::GC::kFinalize)
-+                    : 0);
- 
-     if (!thing) {
-         JS_ReportOutOfMemory(cx);
-diff --git a/js/src/jsgc.h b/js/src/jsgc.h
---- a/js/src/jsgc.h
-+++ b/js/src/jsgc.h
-@@ -50,6 +50,25 @@
- #include "MMgc.h"
- #include <new>
- 
-+/*
-+ * Kinds of js_GC invocation.
-+ */
-+typedef enum JSGCInvocationKind {
-+    GC_NOT_RUNNING,
-+
-+    /* Normal invocation. */
-+    GC_NORMAL,
-+
-+    /* Called from js_DestroyContext for last JSContext in a JSRuntime. */
-+    GC_LAST_CONTEXT,
-+
-+    /*
-+     * Called from js_NewGCThing as a last-ditch GC attempt. See comments
-+     * before js_GC definition for details.
-+     */
-+    GC_LAST_DITCH
-+} JSGCInvocationKind;
-+
- class JSGC
-     : public MMgc::GC, private MMgc::GCCallback
- {
-@@ -296,25 +315,6 @@ extern JS_FRIEND_API(void)
- extern JS_FRIEND_API(void)
- js_TraceContext(JSTracer *trc, JSContext *acx);
- 
--/*
-- * Kinds of js_GC invocation.
-- */
--typedef enum JSGCInvocationKind {
--    GC_NOT_RUNNING,
--
--    /* Normal invocation. */
--    GC_NORMAL,
--
--    /* Called from js_DestroyContext for last JSContext in a JSRuntime. */
--    GC_LAST_CONTEXT,
--
--    /*
--     * Called from js_NewGCThing as a last-ditch GC attempt. See comments
--     * before js_GC definition for details.
--     */
--    GC_LAST_DITCH
--} JSGCInvocationKind;
--
- extern void
- js_GC(JSContext *cx, JSGCInvocationKind gckind);
- 
deleted file mode 100644
--- a/gccontexts
+++ /dev/null
@@ -1,145 +0,0 @@
-diff --git a/js/src/jsgc.cpp b/js/src/jsgc.cpp
---- a/js/src/jsgc.cpp
-+++ b/js/src/jsgc.cpp
-@@ -92,8 +92,8 @@ namespace
- }
- 
- #ifdef JS_THREADSAFE
--#define PENDING_GC_CONTEXT(thread) ((thread)->pendingGCContext)
--#define PENDING_GC_KIND(thread)    ((thread)->pendingGCKind)
-+#define PENDING_GC_CONTEXT(gc, thread) ((thread)->pendingGCContext)
-+#define PENDING_GC_KIND(gc, thread)    ((thread)->pendingGCKind)
- #else
- /* Single-threaded equivalent of JSThread::gcContext. */
- static JSContext *g_pendingGCContext = NULL;
-@@ -101,8 +101,8 @@ static JSContext *g_pendingGCContext = N
- /* Single-threaded equivalent of JSThread::gcKind. */
- static JSGCInvocationKind g_pendingGCKind = GC_NOT_RUNNING;
- 
--#define PENDING_GC_CONTEXT(ignore) g_pendingGCContext
--#define PENDING_GC_KIND(ignore)    g_pendingGCKind
-+#define PENDING_GC_CONTEXT(gc, thread) ((gc)->pendingGCContext)
-+#define PENDING_GC_KIND(gc, thread)    ((gc)->pendingGCKind)
- #endif
- 
- JS_STATIC_ASSERT(sizeof(JSStackHeader) >= 2 * sizeof(jsval));
-@@ -712,10 +712,16 @@ JSGC::JSGC(JSRuntime *_rt)
- JSGC::JSGC(JSRuntime *_rt)
-     : GC(MMgc::GCHeap::GetGCHeap()), 
-       GCCallback(this),
-+#ifndef JS_THREADSAFE
-+      pendingGCContext(NULL),
-+      pendingGCKind(GC_NOT_RUNNING),
-+#endif
-       rt(_rt)
- {
-     /* Incremental mode requires more work; see MMgc docs. */
-     incremental = false;
-+
-+    /* We leave the tracer uninitialized. */
- }
- 
- bool
-@@ -731,8 +737,8 @@ JSGC::precollect()
-     JSThread *thread = js_GetCurrentThread(rt);
- #endif
- 
--    cx = PENDING_GC_CONTEXT(thread);
--    gckind = PENDING_GC_KIND(thread);
-+    cx = PENDING_GC_CONTEXT(this, thread);
-+    gckind = PENDING_GC_KIND(this, thread);
- 
-     /*
-      * Don't collect garbage if the runtime isn't up, and cx is not the last
-@@ -843,8 +849,8 @@ JSGC::enterExclusiveGC()
- 
-     rt->gcPoke = JS_FALSE;
- 
--    rt->gcContext = PENDING_GC_CONTEXT(thread);
--    rt->gcKind = PENDING_GC_KIND(thread);
-+    rt->gcContext = PENDING_GC_CONTEXT(this, thread);
-+    rt->gcKind = PENDING_GC_KIND(this, thread);
- }
- 
- void
-@@ -906,8 +912,8 @@ JSGC::postcollect()
- #ifdef JS_THREADSAFE
-     JSThread *thread = js_GetCurrentThread(rt);
- #endif
--    JSContext *cx = PENDING_GC_CONTEXT(thread);
--    JSGCInvocationKind gckind = PENDING_GC_KIND(thread);
-+    JSContext *cx = PENDING_GC_CONTEXT(this, thread);
-+    JSGCInvocationKind gckind = PENDING_GC_KIND(this, thread);
- 
-     /* Execute JSGC_END callback outside the lock. */
-     if (rt->gcCallback) {
-@@ -955,10 +961,10 @@ js_NewGCThing(JSContext *cx, uintN flags
- #endif
- 
-     /* Enter possible GC region. */
--    savedGCContext = PENDING_GC_CONTEXT(thread);
--    PENDING_GC_CONTEXT(thread) = cx;
--    savedGCKind = PENDING_GC_KIND(thread);
--    PENDING_GC_KIND(thread) = GC_LAST_DITCH;
-+    savedGCContext = PENDING_GC_CONTEXT(rt->gc, thread);
-+    PENDING_GC_CONTEXT(rt->gc, thread) = cx;
-+    savedGCKind = PENDING_GC_KIND(rt->gc, thread);
-+    PENDING_GC_KIND(rt->gc, thread) = GC_LAST_DITCH;
- 
-     thing = rt->gc->Alloc(nbytes,
-                           gc_type_is_finalized[flags & GCF_TYPEMASK]
-@@ -968,8 +974,8 @@ js_NewGCThing(JSContext *cx, uintN flags
-                           : 0);
- 
-     /* Leave possible GC region. */
--    PENDING_GC_CONTEXT(thread) = savedGCContext;
--    PENDING_GC_KIND(thread) = savedGCKind;
-+    PENDING_GC_CONTEXT(rt->gc, thread) = savedGCContext;
-+    PENDING_GC_KIND(rt->gc, thread) = savedGCKind;
- 
-     if (!thing) {
-         JS_ReportOutOfMemory(cx);
-@@ -1468,18 +1474,19 @@ js_GC(JSContext *cx, JSGCInvocationKind 
- {
-     JSContext *savedGCContext;
-     JSGCInvocationKind savedGCKind;
-+    JSGC *gc = cx->runtime->gc;
- 
-     /* Enter GC region. */
--    savedGCContext = PENDING_GC_CONTEXT(cx->thread);
--    PENDING_GC_CONTEXT(cx->thread) = cx;
--    savedGCKind = PENDING_GC_KIND(cx->thread);
--    PENDING_GC_KIND(cx->thread) = gckind;
--
--    cx->runtime->gc->CollectWithBookkeeping(false, THREAD_IS_IN_REQUEST(cx));
-+    savedGCContext = PENDING_GC_CONTEXT(gc, cx->thread);
-+    PENDING_GC_CONTEXT(gc, cx->thread) = cx;
-+    savedGCKind = PENDING_GC_KIND(gc, cx->thread);
-+    PENDING_GC_KIND(gc, cx->thread) = gckind;
-+
-+    gc->CollectWithBookkeeping(false, THREAD_IS_IN_REQUEST(cx));
- 
-     /* Leave GC region. */
--    PENDING_GC_CONTEXT(cx->thread) = savedGCContext;
--    PENDING_GC_KIND(cx->thread) = savedGCKind;
-+    PENDING_GC_CONTEXT(gc, cx->thread) = savedGCContext;
-+    PENDING_GC_KIND(gc, cx->thread) = savedGCKind;
- }
- 
- void
-diff --git a/js/src/jsgc.h b/js/src/jsgc.h
---- a/js/src/jsgc.h
-+++ b/js/src/jsgc.h
-@@ -98,6 +98,12 @@ private:
-  
-     JSRuntime *rt;
-     JSTracer tracer;
-+
-+#ifndef JS_THREADSAFE
-+public:
-+    JSContext *pendingGCContext;
-+    JSGCInvocationKind pendingGCKind;
-+#endif
- };
- 
- JS_BEGIN_EXTERN_C
--- a/gcobject-nodelete.patch
+++ b/gcobject-nodelete.patch
@@ -1,8 +1,20 @@
+diff --git a/chrome/src/nsChromeRegistry.cpp b/chrome/src/nsChromeRegistry.cpp
+--- a/chrome/src/nsChromeRegistry.cpp
++++ b/chrome/src/nsChromeRegistry.cpp
+@@ -340,7 +340,7 @@ nsChromeRegistry::nsProviderArray::Clear
+   PRInt32 i = mArray.Count();
+   while (i--) {
+     ProviderEntry* entry = reinterpret_cast<ProviderEntry*>(mArray[i]);
+-    delete entry;
++    NS_GetGC()->Free(entry);
+   }
+ 
+   mArray.Clear();
 diff --git a/content/html/content/src/nsHTMLFormElement.cpp b/content/html/content/src/nsHTMLFormElement.cpp
 --- a/content/html/content/src/nsHTMLFormElement.cpp
 +++ b/content/html/content/src/nsHTMLFormElement.cpp
 @@ -259,7 +259,7 @@ protected:
     * @param aFormSubmission the submission object
     * @param aEvent the DOM event that was passed to us for the submit
     */
 -  nsresult BuildSubmission(nsCOMPtr<nsIFormSubmission>& aFormSubmission, 
@@ -527,16 +539,46 @@ diff --git a/content/html/content/src/ns
 +    list->Item(0, &node);
  
      if (node) {
 -      nsCOMPtr<nsISupports> tmp(do_QueryInterface(node));
 +      nsISupports* tmp(do_QueryInterface(node));
        NS_ENSURE_TRUE(mNameLookupTable.Put(aName, tmp),NS_ERROR_FAILURE);
      }
    }
+diff --git a/content/xul/document/src/nsXULContentSink.cpp b/content/xul/document/src/nsXULContentSink.cpp
+--- a/content/xul/document/src/nsXULContentSink.cpp
++++ b/content/xul/document/src/nsXULContentSink.cpp
+@@ -940,7 +940,7 @@ XULContentSinkImpl::OpenTag(const PRUnic
+     nsVoidArray* children;
+     rv = mContextStack.GetTopChildren(&children);
+     if (NS_FAILED(rv)) {
+-        delete element;
++        NS_GetGC()->Free(element);
+         return rv;
+     }
+ 
+@@ -1162,7 +1162,7 @@ XULContentSinkImpl::OpenScript(const PRU
+           }
+ 
+           if (NS_FAILED(rv)) {
+-              delete script;
++              NS_GetGC()->Free(script);
+               return rv;
+           }
+ 
+@@ -1177,7 +1177,7 @@ XULContentSinkImpl::OpenScript(const PRU
+       nsVoidArray* children;
+       rv = mContextStack.GetTopChildren(&children);
+       if (NS_FAILED(rv)) {
+-          delete script;
++          NS_GetGC()->Free(script);
+           return rv;
+       }
+ 
 diff --git a/docshell/shistory/src/nsSHEntry.cpp b/docshell/shistory/src/nsSHEntry.cpp
 --- a/docshell/shistory/src/nsSHEntry.cpp
 +++ b/docshell/shistory/src/nsSHEntry.cpp
 @@ -82,7 +82,6 @@ nsresult nsSHEntry::Startup()
  
  void nsSHEntry::Shutdown()
  {
 -  delete gHistoryTracker;
@@ -901,17 +943,17 @@ diff --git a/dom/src/base/nsJSEnvironmen
  
 -  nsCOMPtr<nsIURI> uri;
 -  prin->GetURI(getter_AddRefs(uri));
 +  nsIURI* uri = nsnull;
 +  prin->GetURI(&uri);
    if (!uri) {
      printf("No URI, maybe the system principal.\n");
      return;
-@@ -852,18 +852,18 @@ nsJSContext::DOMBranchCallback(JSContext
+@@ -852,18 +852,18 @@ nsJSContext::DOMOperationCallback(JSCont
    // If we get here we're most likely executing an infinite loop in JS,
    // we'll tell the user about this and we'll give the user the option
    // of stopping the execution of the script.
 -  nsCOMPtr<nsPIDOMWindow> win(do_QueryInterface(ctx->GetGlobalObject()));
 +  nsPIDOMWindow* win(do_QueryInterface(ctx->GetGlobalObject()));
    NS_ENSURE_TRUE(win, JS_TRUE);
  
    nsIDocShell *docShell = win->GetDocShell();
@@ -924,104 +966,104 @@ diff --git a/dom/src/base/nsJSEnvironmen
    // Get the nsIPrompt interface from the docshell
 -  nsCOMPtr<nsIPrompt> prompt;
 -  ireq->GetInterface(NS_GET_IID(nsIPrompt), getter_AddRefs(prompt));
 +  nsIPrompt* prompt = nsnull;
 +  ireq->GetInterface(NS_GET_IID(nsIPrompt), (void**)&prompt);
    NS_ENSURE_TRUE(prompt, JS_TRUE);
  
    nsresult rv;
-@@ -875,12 +875,12 @@ nsJSContext::DOMBranchCallback(JSContext
+@@ -877,12 +877,12 @@ nsJSContext::DOMOperationCallback(JSCont
    if (debugPossible) {
      PRBool jsds_IsOn = PR_FALSE;
      const char jsdServiceCtrID[] = "@mozilla.org/js/jsd/debugger-service;1";
 -    nsCOMPtr<jsdIExecutionHook> jsdHook;  
 -    nsCOMPtr<jsdIDebuggerService> jsds = do_GetService(jsdServiceCtrID, &rv);
 +    jsdIExecutionHook* jsdHook = nsnull;  
 +    jsdIDebuggerService* jsds = do_GetService(jsdServiceCtrID, &rv);
    
      // Check if there's a user for the debugger service that's 'on' for us
      if (NS_SUCCEEDED(rv)) {
 -      jsds->GetDebuggerHook(getter_AddRefs(jsdHook));
 +      jsds->GetDebuggerHook(&jsdHook);
        jsds->GetIsOn(&jsds_IsOn);
        if (jsds_IsOn) { // If this is not true, the next call would start jsd...
          rv = jsds->OnForRuntime(cx->runtime);
-@@ -896,13 +896,13 @@ nsJSContext::DOMBranchCallback(JSContext
+@@ -898,13 +898,13 @@ nsJSContext::DOMOperationCallback(JSCont
  #endif
  
    // Get localizable strings
 -  nsCOMPtr<nsIStringBundleService>
 +  nsIStringBundleService*
      stringService(do_GetService(NS_STRINGBUNDLE_CONTRACTID));
    if (!stringService)
      return JS_TRUE;
  
 -  nsCOMPtr<nsIStringBundle> bundle;
 -  stringService->CreateBundle(kDOMStringBundleURL, getter_AddRefs(bundle));
 +  nsIStringBundle* bundle = nsnull;
 +  stringService->CreateBundle(kDOMStringBundleURL, &bundle);
    if (!bundle)
      return JS_TRUE;
    
-@@ -1048,7 +1048,7 @@ nsJSContext::JSOptionChangedCallback(con
+@@ -1052,7 +1052,7 @@ nsJSContext::JSOptionChangedCallback(con
    // need to enable this directly from InitContext
    if ((newDefaultJSOptions & JSOPTION_STRICT) == 0) {
      nsIScriptGlobalObject *global = context->GetGlobalObject();
 -    nsCOMPtr<nsIDOMChromeWindow> chromeWindow(do_QueryInterface(global));
 +    nsIDOMChromeWindow* chromeWindow(do_QueryInterface(global));
      if (chromeWindow)
        newDefaultJSOptions |= JSOPTION_STRICT;
    }
-@@ -1231,7 +1231,7 @@ nsJSContext::EvaluateStringWithValue(con
+@@ -1234,7 +1234,7 @@ nsJSContext::EvaluateStringWithValue(con
      nsIScriptGlobalObject *global = GetGlobalObject();
      if (!global)
        return NS_ERROR_FAILURE;
 -    nsCOMPtr<nsIScriptObjectPrincipal> objPrincipal =
 +    nsIScriptObjectPrincipal* objPrincipal =
        do_QueryInterface(global, &rv);
      if (NS_FAILED(rv))
        return NS_ERROR_FAILURE;
-@@ -1256,7 +1256,7 @@ nsJSContext::EvaluateStringWithValue(con
+@@ -1259,7 +1259,7 @@ nsJSContext::EvaluateStringWithValue(con
    // from native code via XPConnect uses the right context.  Do this whether
    // or not the SecurityManager said "ok", in order to simplify control flow
    // below where we pop before returning.
 -  nsCOMPtr<nsIJSContextStack> stack =
 +  nsIJSContextStack* stack =
             do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
    if (NS_FAILED(rv) || NS_FAILED(stack->Push(mContext))) {
      JSPRINCIPALS_DROP(mContext, jsprin);
-@@ -1429,7 +1429,7 @@ nsJSContext::EvaluateString(const nsAStr
+@@ -1432,7 +1432,7 @@ nsJSContext::EvaluateString(const nsAStr
      aPrincipal->GetJSPrincipals(mContext, &jsprin);
    }
    else {
 -    nsCOMPtr<nsIScriptObjectPrincipal> objPrincipal =
 +    nsIScriptObjectPrincipal* objPrincipal =
        do_QueryInterface(GetGlobalObject(), &rv);
      if (NS_FAILED(rv))
        return NS_ERROR_FAILURE;
-@@ -1453,7 +1453,7 @@ nsJSContext::EvaluateString(const nsAStr
+@@ -1456,7 +1456,7 @@ nsJSContext::EvaluateString(const nsAStr
    // from native code via XPConnect uses the right context.  Do this whether
    // or not the SecurityManager said "ok", in order to simplify control flow
    // below where we pop before returning.
 -  nsCOMPtr<nsIJSContextStack> stack =
 +  nsIJSContextStack* stack =
             do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
    if (NS_FAILED(rv) || NS_FAILED(stack->Push(mContext))) {
      JSPRINCIPALS_DROP(mContext, jsprin);
-@@ -1662,7 +1662,7 @@ nsJSContext::ExecuteScript(void *aScript
+@@ -1667,7 +1667,7 @@ nsJSContext::ExecuteScript(void *aScript
  
    // Push our JSContext on our thread's context stack, in case native code
    // called from JS calls back into JS via XPConnect.
 -  nsCOMPtr<nsIJSContextStack> stack =
 +  nsIJSContextStack* stack =
             do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
    if (NS_FAILED(rv) || NS_FAILED(stack->Push(mContext))) {
      return NS_ERROR_FAILURE;
-@@ -1745,16 +1745,16 @@ nsJSContext::JSObjectFromInterface(nsISu
+@@ -1749,16 +1749,16 @@ nsJSContext::JSObjectFromInterface(nsISu
    }
    // Get the jsobject associated with this target
    nsresult rv;
 -  nsCOMPtr<nsIXPConnectJSObjectHolder> jsholder;
 +  nsIXPConnectJSObjectHolder* jsholder = nsnull;
    rv = nsContentUtils::XPConnect()->WrapNative(mContext, (JSObject *)aScope,
                                                 aTarget,
                                                 NS_GET_IID(nsISupports),
@@ -1032,67 +1074,67 @@ diff --git a/dom/src/base/nsJSEnvironmen
 -  nsCOMPtr<nsIXPConnectWrappedNative> wrapper = do_QueryInterface(jsholder);
 +  nsIXPConnectWrappedNative* wrapper = do_QueryInterface(jsholder);
    NS_ASSERTION(wrapper, "wrapper must impl nsIXPConnectWrappedNative");
 -  nsCOMPtr<nsISupports> targetSupp = do_QueryInterface(aTarget);
 +  nsISupports* targetSupp = do_QueryInterface(aTarget);
    NS_ASSERTION(wrapper->Native() == targetSupp, "Native should be the target!");
  #endif
    return jsholder->GetJSObject(aRet);
-@@ -1822,7 +1822,7 @@ nsJSContext::CompileFunction(void* aTarg
+@@ -1826,7 +1826,7 @@ nsJSContext::CompileFunction(void* aTarg
    nsIScriptGlobalObject *global = GetGlobalObject();
    if (global) {
      // XXXbe why the two-step QI? speed up via a new GetGlobalObjectData func?
 -    nsCOMPtr<nsIScriptObjectPrincipal> globalData = do_QueryInterface(global);
 +    nsIScriptObjectPrincipal* globalData = do_QueryInterface(global);
      if (globalData) {
        nsIPrincipal *prin = globalData->GetPrincipal();
        if (!prin)
-@@ -1879,7 +1879,7 @@ nsJSContext::CallEventHandler(nsISupport
+@@ -1883,7 +1883,7 @@ nsJSContext::CallEventHandler(nsISupport
    // xxxmarkh - this comment is no longer true - principals are not used at
    // all now, and never were in some cases.
  
 -  nsCOMPtr<nsIJSContextStack> stack =
 +  nsIJSContextStack* stack =
      do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
    if (NS_FAILED(rv) || NS_FAILED(stack->Push(mContext)))
      return NS_ERROR_FAILURE;
-@@ -1890,7 +1890,7 @@ nsJSContext::CallEventHandler(nsISupport
+@@ -1894,7 +1894,7 @@ nsJSContext::CallEventHandler(nsISupport
      // We're not done yet!  Some event listeners are confused about their
      // script context, so check whether we might actually be the wrong script
      // context.  To be safe, do CheckFunctionAccess checks for both.
 -    nsCOMPtr<nsIContent> content = do_QueryInterface(aTarget);
 +    nsIContent* content = do_QueryInterface(aTarget);
      if (content) {
        // XXXbz XBL2/sXBL issue
        nsIDocument* ownerDoc = content->GetOwnerDoc();
-@@ -2005,7 +2005,7 @@ nsJSContext::BindCompiledEventHandler(ns
+@@ -2009,7 +2009,7 @@ nsJSContext::BindCompiledEventHandler(ns
  
    // Push our JSContext on our thread's context stack, in case native code
    // called from JS calls back into JS via XPConnect.
 -  nsCOMPtr<nsIJSContextStack> stack =
 +  nsIJSContextStack* stack =
             do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
    if (NS_FAILED(rv) || NS_FAILED(stack->Push(mContext))) {
      return NS_ERROR_FAILURE;
-@@ -2221,11 +2221,11 @@ nsJSContext::GetGlobalObject()
+@@ -2225,11 +2225,11 @@ nsJSContext::GetGlobalObject()
      return nsnull;
    }
  
 -  nsCOMPtr<nsIScriptGlobalObject> sgo;
 +  nsIScriptGlobalObject* sgo = nsnull;
    nsISupports *priv =
      (nsISupports *)::JS_GetPrivate(mContext, global);
  
 -  nsCOMPtr<nsIXPConnectWrappedNative> wrapped_native =
 +  nsIXPConnectWrappedNative* wrapped_native =
      do_QueryInterface(priv);
  
    if (wrapped_native) {
-@@ -2256,17 +2256,16 @@ nsJSContext::CreateNativeGlobalForInner(
+@@ -2260,17 +2260,16 @@ nsJSContext::CreateNativeGlobalForInner(
  {
    nsIXPConnect *xpc = nsContentUtils::XPConnect();
    PRUint32 flags = aIsChrome? nsIXPConnect::FLAG_SYSTEM_GLOBAL_OBJECT : 0;
 -  nsCOMPtr<nsIXPConnectJSObjectHolder> jsholder;
 +  nsIXPConnectJSObjectHolder* jsholder = nsnull;
    nsresult rv = xpc->
            InitClassesWithNewWrappedGlobal(mContext,
                                            aNewInner, NS_GET_IID(nsISupports),
@@ -1103,44 +1145,44 @@ diff --git a/dom/src/base/nsJSEnvironmen
      return rv;
    jsholder->GetJSObject(reinterpret_cast<JSObject **>(aNativeGlobal));
 -  *aHolder = jsholder.get();
 -  NS_ADDREF(*aHolder);
 +  *aHolder = jsholder;
    return NS_OK;
  }
  
-@@ -2340,7 +2339,7 @@ nsJSContext::InitContext(nsIScriptGlobal
+@@ -2344,7 +2343,7 @@ nsJSContext::InitContext(nsIScriptGlobal
  
    JSObject *global = ::JS_GetGlobalObject(mContext);
  
 -  nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
 +  nsIXPConnectJSObjectHolder* holder = nsnull;
  
    // If there's already a global object in mContext we won't tell
    // XPConnect to wrap aGlobalObject since it's already wrapped.
-@@ -2348,7 +2347,7 @@ nsJSContext::InitContext(nsIScriptGlobal
+@@ -2352,7 +2351,7 @@ nsJSContext::InitContext(nsIScriptGlobal
    nsresult rv;
  
    if (!global) {
 -    nsCOMPtr<nsIDOMChromeWindow> chromeWindow(do_QueryInterface(aGlobalObject));
 +    nsIDOMChromeWindow* chromeWindow(do_QueryInterface(aGlobalObject));
      PRUint32 flags = 0;
      
      if (chromeWindow) {
-@@ -2367,7 +2366,7 @@ nsJSContext::InitContext(nsIScriptGlobal
+@@ -2371,7 +2370,7 @@ nsJSContext::InitContext(nsIScriptGlobal
      rv = xpc->InitClassesWithNewWrappedGlobal(mContext, aGlobalObject,
                                                NS_GET_IID(nsISupports),
                                                flags,
 -                                              getter_AddRefs(holder));
 +                                              &holder);
      NS_ENSURE_SUCCESS(rv, rv);
  
      // Now check whether we need to grab a pointer to the
-@@ -2386,15 +2385,15 @@ nsJSContext::InitContext(nsIScriptGlobal
+@@ -2390,15 +2389,15 @@ nsJSContext::InitContext(nsIScriptGlobal
      rv = xpc->InitClasses(mContext, global);
      NS_ENSURE_SUCCESS(rv, rv);
  
 -    nsCOMPtr<nsIClassInfo> ci(do_QueryInterface(aGlobalObject));
 +    nsIClassInfo* ci(do_QueryInterface(aGlobalObject));
  
      if (ci) {
        rv = xpc->WrapNative(mContext, global, aGlobalObject,
@@ -1149,35 +1191,35 @@ diff --git a/dom/src/base/nsJSEnvironmen
 +                           &holder);
        NS_ENSURE_SUCCESS(rv, rv);
  
 -      nsCOMPtr<nsIXPConnectWrappedNative> wrapper(do_QueryInterface(holder));
 +      nsIXPConnectWrappedNative* wrapper(do_QueryInterface(holder));
        NS_ENSURE_TRUE(wrapper, NS_ERROR_FAILURE);
  
        rv = wrapper->RefreshPrototype();
-@@ -2470,7 +2469,7 @@ nsJSContext::ConvertSupportsTojsvals(nsI
+@@ -2474,7 +2473,7 @@ nsJSContext::ConvertSupportsTojsvals(nsI
    nsresult rv = NS_OK;
  
    // If the array implements nsIJSArgArray, just grab the values directly.
 -  nsCOMPtr<nsIJSArgArray> fastArray = do_QueryInterface(aArgs);
 +  nsIJSArgArray* fastArray = do_QueryInterface(aArgs);
    if (fastArray != nsnull) {
      *aMarkp = nsnull;
      return fastArray->GetArgs(aArgc, aArgv);
-@@ -2491,7 +2490,7 @@ nsJSContext::ConvertSupportsTojsvals(nsI
+@@ -2495,7 +2494,7 @@ nsJSContext::ConvertSupportsTojsvals(nsI
    PRUint32 argCtr, argCount;
    // This general purpose function may need to convert an arg array
    // (window.arguments, event-handler args) and a generic property.
 -  nsCOMPtr<nsIArray> argsArray(do_QueryInterface(aArgs));
 +  nsIArray* argsArray(do_QueryInterface(aArgs));
  
    if (argsArray) {
      rv = argsArray->GetLength(&argCount);
-@@ -2507,15 +2506,15 @@ nsJSContext::ConvertSupportsTojsvals(nsI
+@@ -2511,15 +2510,15 @@ nsJSContext::ConvertSupportsTojsvals(nsI
  
    if (argsArray) {
      for (argCtr = 0; argCtr < argCount && NS_SUCCEEDED(rv); argCtr++) {
 -      nsCOMPtr<nsISupports> arg;
 +      nsISupports* arg = nsnull;
        jsval *thisval = argv + argCtr;
        argsArray->QueryElementAt(argCtr, NS_GET_IID(nsISupports),
 -                                getter_AddRefs(arg));
@@ -1186,17 +1228,17 @@ diff --git a/dom/src/base/nsJSEnvironmen
          *thisval = JSVAL_NULL;
          continue;
        }
 -      nsCOMPtr<nsIVariant> variant(do_QueryInterface(arg));
 +      nsIVariant* variant(do_QueryInterface(arg));
        if (variant != nsnull) {
          rv = xpc->VariantToJS(mContext, (JSObject *)aScope, variant, 
                                thisval);
-@@ -2530,14 +2529,14 @@ nsJSContext::ConvertSupportsTojsvals(nsI
+@@ -2534,14 +2533,14 @@ nsJSContext::ConvertSupportsTojsvals(nsI
  #ifdef NS_DEBUG
            // but first, check its not another nsISupportsPrimitive, as
            // these are now deprecated for use with script contexts.
 -          nsCOMPtr<nsISupportsPrimitive> prim(do_QueryInterface(arg));
 +          nsISupportsPrimitive* prim(do_QueryInterface(arg));
            NS_ASSERTION(prim == nsnull,
                         "Don't pass nsISupportsPrimitives - use nsIVariant!");
  #endif
@@ -1204,134 +1246,134 @@ diff --git a/dom/src/base/nsJSEnvironmen
 +          nsIXPConnectJSObjectHolder* wrapper = nsnull;
            rv = xpc->WrapNative(mContext, (JSObject *)aScope, arg,
                                 NS_GET_IID(nsISupports),
 -                               getter_AddRefs(wrapper));
 +                               &wrapper);
            if (NS_SUCCEEDED(rv)) {
              JSObject *obj;
              rv = wrapper->GetJSObject(&obj);
-@@ -2549,7 +2548,7 @@ nsJSContext::ConvertSupportsTojsvals(nsI
+@@ -2553,7 +2552,7 @@ nsJSContext::ConvertSupportsTojsvals(nsI
        }
      }
    } else {
 -    nsCOMPtr<nsIVariant> variant(do_QueryInterface(aArgs));
 +    nsIVariant* variant(do_QueryInterface(aArgs));
      if (variant)
        rv = xpc->VariantToJS(mContext, (JSObject *)aScope, variant, argv);
      else {
-@@ -2572,7 +2571,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2576,7 +2575,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
  {
    NS_PRECONDITION(aArg, "Empty arg");
  
 -  nsCOMPtr<nsISupportsPrimitive> argPrimitive(do_QueryInterface(aArg));
 +  nsISupportsPrimitive* argPrimitive(do_QueryInterface(aArg));
    if (!argPrimitive)
      return NS_ERROR_NO_INTERFACE;
  
-@@ -2582,7 +2581,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2586,7 +2585,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
  
    switch(type) {
      case nsISupportsPrimitive::TYPE_CSTRING : {
 -      nsCOMPtr<nsISupportsCString> p(do_QueryInterface(argPrimitive));
 +      nsISupportsCString* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
        nsCAutoString data;
-@@ -2598,7 +2597,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2602,7 +2601,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
        break;
      }
      case nsISupportsPrimitive::TYPE_STRING : {
 -      nsCOMPtr<nsISupportsString> p(do_QueryInterface(argPrimitive));
 +      nsISupportsString* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
        nsAutoString data;
-@@ -2617,7 +2616,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2621,7 +2620,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
        break;
      }
      case nsISupportsPrimitive::TYPE_PRBOOL : {
 -      nsCOMPtr<nsISupportsPRBool> p(do_QueryInterface(argPrimitive));
 +      nsISupportsPRBool* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
        PRBool data;
-@@ -2629,7 +2628,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2633,7 +2632,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
        break;
      }
      case nsISupportsPrimitive::TYPE_PRUINT8 : {
 -      nsCOMPtr<nsISupportsPRUint8> p(do_QueryInterface(argPrimitive));
 +      nsISupportsPRUint8* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
        PRUint8 data;
-@@ -2641,7 +2640,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2645,7 +2644,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
        break;
      }
      case nsISupportsPrimitive::TYPE_PRUINT16 : {
 -      nsCOMPtr<nsISupportsPRUint16> p(do_QueryInterface(argPrimitive));
 +      nsISupportsPRUint16* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
        PRUint16 data;
-@@ -2653,7 +2652,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2657,7 +2656,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
        break;
      }
      case nsISupportsPrimitive::TYPE_PRUINT32 : {
 -      nsCOMPtr<nsISupportsPRUint32> p(do_QueryInterface(argPrimitive));
 +      nsISupportsPRUint32* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
        PRUint32 data;
-@@ -2665,7 +2664,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2669,7 +2668,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
        break;
      }
      case nsISupportsPrimitive::TYPE_CHAR : {
 -      nsCOMPtr<nsISupportsChar> p(do_QueryInterface(argPrimitive));
 +      nsISupportsChar* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
        char data;
-@@ -2680,7 +2679,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2684,7 +2683,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
        break;
      }
      case nsISupportsPrimitive::TYPE_PRINT16 : {
 -      nsCOMPtr<nsISupportsPRInt16> p(do_QueryInterface(argPrimitive));
 +      nsISupportsPRInt16* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
        PRInt16 data;
-@@ -2692,7 +2691,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2696,7 +2695,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
        break;
      }
      case nsISupportsPrimitive::TYPE_PRINT32 : {
 -      nsCOMPtr<nsISupportsPRInt32> p(do_QueryInterface(argPrimitive));
 +      nsISupportsPRInt32* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
        PRInt32 data;
-@@ -2704,7 +2703,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2708,7 +2707,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
        break;
      }
      case nsISupportsPrimitive::TYPE_FLOAT : {
 -      nsCOMPtr<nsISupportsFloat> p(do_QueryInterface(argPrimitive));
 +      nsISupportsFloat* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
        float data;
-@@ -2718,7 +2717,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2722,7 +2721,7 @@ nsJSContext::AddSupportsPrimitiveTojsval
        break;
      }
      case nsISupportsPrimitive::TYPE_DOUBLE : {
 -      nsCOMPtr<nsISupportsDouble> p(do_QueryInterface(argPrimitive));
 +      nsISupportsDouble* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
        double data;
-@@ -2732,25 +2731,25 @@ nsJSContext::AddSupportsPrimitiveTojsval
+@@ -2736,25 +2735,25 @@ nsJSContext::AddSupportsPrimitiveTojsval
        break;
      }
      case nsISupportsPrimitive::TYPE_INTERFACE_POINTER : {
 -      nsCOMPtr<nsISupportsInterfacePointer> p(do_QueryInterface(argPrimitive));
 +      nsISupportsInterfacePointer* p(do_QueryInterface(argPrimitive));
        NS_ENSURE_TRUE(p, NS_ERROR_UNEXPECTED);
  
 -      nsCOMPtr<nsISupports> data;
@@ -1353,60 +1395,60 @@ diff --git a/dom/src/base/nsJSEnvironmen
 -      nsCOMPtr<nsIXPConnectJSObjectHolder> wrapper;
 +      nsIXPConnectJSObjectHolder* wrapper = nsnull;
        rv = xpc->WrapNative(cx, ::JS_GetGlobalObject(cx), data,
 -                           *iid, getter_AddRefs(wrapper));
 +                           *iid, &wrapper);
        NS_ENSURE_SUCCESS(rv, rv);
  
        JSObject *obj;
-@@ -3489,11 +3488,10 @@ nsresult
+@@ -3508,11 +3507,10 @@ nsresult
  nsresult
  nsJSRuntime::CreateContext(nsIScriptContext **aContext)
  {
 -  nsCOMPtr<nsIScriptContext> scriptContext;
 +  nsIScriptContext* scriptContext = nsnull;
  
    *aContext = new nsJSContext(sRuntime);
    NS_ENSURE_TRUE(*aContext, NS_ERROR_OUT_OF_MEMORY);
 -  NS_ADDREF(*aContext);
    return NS_OK;
  }
  
-@@ -3576,10 +3574,10 @@ ObjectPrincipalFinder(JSContext *cx, JSO
+@@ -3595,10 +3593,10 @@ ObjectPrincipalFinder(JSContext *cx, JSO
    if (!sSecurityManager)
      return nsnull;
  
 -  nsCOMPtr<nsIPrincipal> principal;
 +  nsIPrincipal* principal = nsnull;
    nsresult rv =
      sSecurityManager->GetObjectPrincipal(cx, obj,
 -                                         getter_AddRefs(principal));
 +                                         &principal);
  
    if (NS_FAILED(rv) || !principal) {
      return nsnull;
-@@ -3759,7 +3757,6 @@ nsresult NS_CreateJSRuntime(nsIScriptRun
+@@ -3776,7 +3774,6 @@ nsresult NS_CreateJSRuntime(nsIScriptRun
    *aRuntime = new nsJSRuntime();
    if (*aRuntime == nsnull)
      return NS_ERROR_OUT_OF_MEMORY;
 -  NS_IF_ADDREF(*aRuntime);
    return NS_OK;
  }
  
-@@ -3769,7 +3766,7 @@ nsresult NS_CreateJSRuntime(nsIScriptRun
+@@ -3786,7 +3783,7 @@ nsresult NS_CreateJSRuntime(nsIScriptRun
  // to/from nsISupports.
  // When consumed by non-JS (eg, another script language), conversion is done
  // on-the-fly.
 -class nsJSArgArray : public nsIJSArgArray, public nsIArray {
 +class nsJSArgArray : public XPCOMGCFinalizedObject, public nsIJSArgArray, public nsIArray {
  public:
    nsJSArgArray(JSContext *aContext, PRUint32 argc, jsval *argv, nsresult *prv);
    ~nsJSArgArray();
-@@ -3900,7 +3897,6 @@ nsresult NS_CreateJSArgv(JSContext *aCon
+@@ -3917,7 +3914,6 @@ nsresult NS_CreateJSArgv(JSContext *aCon
    if (ret == nsnull)
      return NS_ERROR_OUT_OF_MEMORY;
    if (NS_FAILED(rv)) {
 -    delete ret;
      return rv;
    }
    return ret->QueryInterface(NS_GET_IID(nsIArray), (void **)aArray);
 diff --git a/dom/src/base/nsJSTimeoutHandler.cpp b/dom/src/base/nsJSTimeoutHandler.cpp
@@ -1416,28 +1458,16 @@ diff --git a/dom/src/base/nsJSTimeoutHan
  static const char kSetTimeoutStr[] = "setTimeout";
  
  // Our JS nsIScriptTimeoutHandler implementation.
 -class nsJSScriptTimeoutHandler: public nsIScriptTimeoutHandler
 +class nsJSScriptTimeoutHandler: public XPCOMGCFinalizedObject, public nsIScriptTimeoutHandler
  {
  public:
    // nsISupports
-@@ -168,9 +168,9 @@ nsJSScriptTimeoutHandler::Init(nsIScript
- 
-   mContext = aContext;
- 
--  nsCOMPtr<nsIXPCNativeCallContext> ncc;
-+  nsIXPCNativeCallContext* ncc = nsnull;
-   nsresult rv = nsContentUtils::XPConnect()->
--    GetCurrentNativeCallContext(getter_AddRefs(ncc));
-+    GetCurrentNativeCallContext(&ncc);
-   NS_ENSURE_SUCCESS(rv, rv);
- 
-   if (!ncc)
 @@ -258,16 +258,16 @@ nsJSScriptTimeoutHandler::Init(nsIScript
      // Create our arg array - leave an extra slot for a secret final argument
      // that indicates to the called function how "late" the timeout is.  We
      // will fill that in when SetLateness is called.
 -    nsCOMPtr<nsIArray> array;
 +    nsIArray* array = nsnull;
      rv = NS_CreateJSArgv(cx, (argc > 1) ? argc - 1 : argc, nsnull,
 -                         getter_AddRefs(array));
@@ -1821,31 +1851,26 @@ diff --git a/js/src/xpconnect/loader/moz
              }
 -            nsCOMPtr<nsIObjectInputStream> objectInput;
 -            flSvc->GetInputStream(getter_AddRefs(objectInput));
 +            nsIObjectInputStream* objectInput = nsnull;
 +            flSvc->GetInputStream(&objectInput);
              if (objectInput) {
                  flSvc->SetInputStream(nsnull);
                  objectInput->Close();
-@@ -1301,19 +1298,19 @@ mozJSComponentLoader::Import(const nsACS
+@@ -1301,7 +1298,7 @@ mozJSComponentLoader::Import(const nsACS
      // This function should only be called from JS.
      nsresult rv;
  
 -    nsCOMPtr<nsIXPConnect> xpc =
 +    nsIXPConnect* xpc =
          do_GetService(kXPConnectServiceContractID, &rv);
      NS_ENSURE_SUCCESS(rv, rv);
      
--    nsCOMPtr<nsIXPCNativeCallContext> cc;
--    rv = xpc->GetCurrentNativeCallContext(getter_AddRefs(cc));
-+    nsIXPCNativeCallContext* cc = nsnull;
-+    rv = xpc->GetCurrentNativeCallContext(&cc);
-     NS_ENSURE_SUCCESS(rv, rv);
- 
+@@ -1312,8 +1309,8 @@ mozJSComponentLoader::Import(const nsACS
  #ifdef DEBUG
      {
      // ensure that we are being call from JS, from this method
 -    nsCOMPtr<nsIInterfaceInfo> info;
 -    rv = cc->GetCalleeInterface(getter_AddRefs(info));
 +    nsIInterfaceInfo* info = nsnull;
 +    rv = cc->GetCalleeInterface(&info);
      NS_ENSURE_SUCCESS(rv, rv);
@@ -2002,46 +2027,46 @@ diff --git a/js/src/xpconnect/src/xpcwra
 -        (proto && proto->GetScriptableInfo() != mScriptableInfo)))
 -    {
 -        delete mScriptableInfo;
 -    }
 -
      // cleanup the tearoffs...
  
      XPCWrappedNativeTearOffChunk* chunk;
-@@ -1407,8 +1400,8 @@ XPCWrappedNative::InitTearOff(XPCCallCon
+@@ -1417,8 +1410,8 @@ XPCWrappedNative::InitTearOff(XPCCallCon
          // Guard against trying to build a tearoff for a shared nsIClassInfo.
          if(iid->Equals(NS_GET_IID(nsIClassInfo)))
          {
 -            nsCOMPtr<nsISupports> alternate_identity(do_QueryInterface(obj));
 -            if(alternate_identity.get() != identity)
 +            nsISupports* alternate_identity(do_QueryInterface(obj));
 +            if(alternate_identity != identity)
              {
                  NS_RELEASE(obj);
                  aTearOff->SetInterface(nsnull);
-@@ -1432,7 +1425,7 @@ XPCWrappedNative::InitTearOff(XPCCallCon
+@@ -1442,7 +1435,7 @@ XPCWrappedNative::InitTearOff(XPCCallCon
          // The code in this block also does a check for the double wrapped
          // nsIPropertyBag case.
  
 -        nsCOMPtr<nsIXPConnectWrappedJS> wrappedJS(do_QueryInterface(obj));
 +        nsIXPConnectWrappedJS* wrappedJS(do_QueryInterface(obj));
          if(wrappedJS)
          {
              JSObject* jso = nsnull;
-@@ -2403,7 +2396,7 @@ XPCWrappedNative::GetObjectPrincipal() c
+@@ -2411,7 +2404,7 @@ XPCWrappedNative::GetObjectPrincipal() c
  {
      nsIPrincipal* principal = GetScope()->GetPrincipal();
  #ifdef DEBUG
 -    nsCOMPtr<nsIScriptObjectPrincipal> objPrin(do_QueryInterface(mIdentity));
 +    nsIScriptObjectPrincipal* objPrin(do_QueryInterface(mIdentity));
      NS_ASSERTION(!objPrin || objPrin->GetPrincipal() == principal,
                   "Principal mismatch.  Expect bad things to happen");
  #endif
-@@ -2685,8 +2678,8 @@ XPCWrappedNative::HandlePossibleNameCase
+@@ -2693,8 +2686,8 @@ XPCWrappedNative::HandlePossibleNameCase
              if(e)
              {
                  nsresult rv;
 -                nsCOMPtr<nsIStackFrame> loc = nsnull;
 -                rv = e->GetLocation(getter_AddRefs(loc));
 +                nsIStackFrame* loc = nsnull;
 +                rv = e->GetLocation(&loc);
                  if(NS_SUCCEEDED(rv) && loc) {
@@ -2065,28 +2090,28 @@ diff --git a/layout/generic/nsTextFrameT
 @@ -428,7 +428,6 @@ nsTextFrameTextRunCache::Init() {
  
  void
  nsTextFrameTextRunCache::Shutdown() {
 -    delete gTextRuns;
      gTextRuns = nsnull;
  }
  
-@@ -1267,8 +1266,8 @@ static gfxFontGroup*
+@@ -1268,8 +1267,8 @@ static gfxFontGroup*
  static gfxFontGroup*
  GetFontGroupForFrame(nsIFrame* aFrame)
  {
 -  nsCOMPtr<nsIFontMetrics> metrics;
 -  nsLayoutUtils::GetFontMetricsForFrame(aFrame, getter_AddRefs(metrics));
 +  nsIFontMetrics* metrics = nsnull;
 +  nsLayoutUtils::GetFontMetricsForFrame(aFrame, &metrics);
  
    if (!metrics)
      return nsnull;
-@@ -1282,20 +1281,19 @@ GetFontGroupForFrame(nsIFrame* aFrame)
+@@ -1283,19 +1282,18 @@ GetFontGroupForFrame(nsIFrame* aFrame)
    return fm->GetThebesFontGroup();
  }
  
 -static already_AddRefed<gfxContext>
 +static gfxContext*
  GetReferenceRenderingContext(nsTextFrame* aTextFrame, nsIRenderingContext* aRC)
  {
 -  nsCOMPtr<nsIRenderingContext> tmp = aRC;
@@ -2094,18 +2119,17 @@ diff --git a/layout/generic/nsTextFrameT
    if (!tmp) {
      nsresult rv = aTextFrame->PresContext()->PresShell()->
 -      CreateRenderingContext(aTextFrame, getter_AddRefs(tmp));
 +      CreateRenderingContext(aTextFrame, &tmp);
      if (NS_FAILED(rv))
        return nsnull;
    }
  
-   gfxContext* ctx = static_cast<gfxContext*>
-           (tmp->GetNativeGraphicData(nsIRenderingContext::NATIVE_THEBES_CONTEXT));
+   gfxContext* ctx = tmp->ThebesContext();
 -  NS_ADDREF(ctx);
    return ctx;
  }
  
 @@ -1306,7 +1304,7 @@ static gfxTextRun*
  static gfxTextRun*
  GetHyphenTextRun(gfxTextRun* aTextRun, gfxContext* aContext, nsTextFrame* aTextFrame)
  {
@@ -2144,38 +2168,38 @@ diff --git a/layout/generic/nsTextFrameT
  
    if (selectionContent &&
        selectionStatus == nsISelectionController::SELECTION_ON) {
 -    nsRefPtr<nsStyleContext> sc = nsnull;
 +    nsStyleContext* sc = nsnull;
      sc = mPresContext->StyleSet()->
        ProbePseudoStyleFor(selectionContent, nsCSSPseudoElements::mozSelection,
                            mFrame->GetStyleContext());
-@@ -3055,7 +3052,7 @@ NS_IMETHODIMP nsTextFrame::GetAccessible
- {
-   if (!IsEmpty() || GetNextInFlow()) {
- 
--    nsCOMPtr<nsIAccessibilityService> accService = do_GetService("@mozilla.org/accessibilityService;1");
-+    nsIAccessibilityService* accService = do_GetService("@mozilla.org/accessibilityService;1");
- 
-     if (accService) {
-       return accService->CreateHTMLTextAccessible(static_cast<nsIFrame*>(this), aAccessible);
-@@ -4148,9 +4145,9 @@ nsTextFrame::GetSelectionStatus(PRInt16*
+@@ -3061,7 +3058,7 @@ NS_IMETHODIMP nsTextFrame::GetAccessible
+     }
+   }
+ 
+-  nsCOMPtr<nsIAccessibilityService> accService = do_GetService("@mozilla.org/accessibilityService;1");
++  nsIAccessibilityService* accService = do_GetService("@mozilla.org/accessibilityService;1");
+ 
+   if (accService) {
+     return accService->CreateHTMLTextAccessible(static_cast<nsIFrame*>(this), aAccessible);
+@@ -4166,9 +4163,9 @@ nsTextFrame::GetSelectionStatus(PRInt16*
  nsTextFrame::GetSelectionStatus(PRInt16* aSelectionFlags)
  {
    // get the selection controller
 -  nsCOMPtr<nsISelectionController> selectionController;
 +  nsISelectionController* selectionController = nsnull;
    nsresult rv = GetSelectionController(PresContext(),
 -                                       getter_AddRefs(selectionController));
 +                                       &selectionController);
    if (NS_FAILED(rv) || !selectionController)
      return nsISelectionController::SELECTION_OFF;
  
-@@ -4292,15 +4289,15 @@ nsTextFrame::SetSelected(nsPresContext* 
+@@ -4310,15 +4307,15 @@ nsTextFrame::SetSelected(nsPresContext* 
    PRBool found = PR_FALSE;
    if (aRange) {
      //lets see if the range contains us, if so we must redraw!
 -    nsCOMPtr<nsIDOMNode> endNode;
 +    nsIDOMNode* endNode = nsnull;
      PRInt32 endOffset;
 -    nsCOMPtr<nsIDOMNode> startNode;
 +    nsIDOMNode* startNode = nsnull;
@@ -2189,33 +2213,33 @@ diff --git a/layout/generic/nsTextFrameT
 -    nsCOMPtr<nsIDOMNode> thisNode = do_QueryInterface(GetContent());
 +    nsIDOMNode* thisNode = do_QueryInterface(GetContent());
  
      if (thisNode == startNode)
      {
 diff --git a/layout/mathml/base/src/nsMathMLChar.cpp b/layout/mathml/base/src/nsMathMLChar.cpp
 --- a/layout/mathml/base/src/nsMathMLChar.cpp
 +++ b/layout/mathml/base/src/nsMathMLChar.cpp
-@@ -155,12 +155,12 @@ static void
+@@ -154,12 +154,12 @@ static void
  static void
  AlertMissingFonts(nsString& aMissingFonts)
  {
 -  nsCOMPtr<nsIStringBundleService> sbs(do_GetService(NS_STRINGBUNDLE_CONTRACTID));
 +  nsIStringBundleService* sbs(do_GetService(NS_STRINGBUNDLE_CONTRACTID));
    if (!sbs)
      return;
  
 -  nsCOMPtr<nsIStringBundle> sb;
 -  sbs->CreateBundle("resource://gre/res/fonts/mathfont.properties", getter_AddRefs(sb));
 +  nsIStringBundle* sb = nsnull;
 +  sbs->CreateBundle("resource://gre/res/fonts/mathfont.properties", &sb);
    if (!sb)
      return;
  
-@@ -170,14 +170,14 @@ AlertMissingFonts(nsString& aMissingFont
+@@ -169,14 +169,14 @@ AlertMissingFonts(nsString& aMissingFont
    sb->FormatStringFromName(NS_LITERAL_STRING("mathfont_missing_dialog_message").get(),
                             strings, 1, getter_Copies(message));
  
 -  nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID));
 +  nsIWindowWatcher* wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID));
    if (!wwatch)
      return;
  
@@ -2255,226 +2279,226 @@ diff --git a/layout/mathml/base/src/nsMa
    nsCAutoString key;
    nsAutoString value;
    nsIPersistentProperties* mathfontProp = nsnull;
 -  nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID));
 +  nsIPrefBranch* prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID));
  
    // Add the math fonts in the gGlyphTableList in order of preference ...
    // Note: we only load font-names at this stage. The actual glyph tables will
-@@ -2191,8 +2191,8 @@ nsMathMLChar::PaintVertically(nsPresCont
-   }
-   else { // glue is present
+@@ -2215,8 +2215,8 @@ nsMathMLChar::PaintVertically(nsPresCont
+   else if (bmdata[3].ascent + bmdata[3].descent > 0) {
+     // glue is present
      nscoord overlap;
 -    nsCOMPtr<nsIFontMetrics> fm;
 -    aRenderingContext.GetFontMetrics(*getter_AddRefs(fm));
 +    nsIFontMetrics* fm = nsnull;
 +    aRenderingContext.GetFontMetrics(*&fm);
      nsMathMLFrame::GetRuleThickness(fm, overlap);
      overlap = 2 * PR_MAX(overlap, onePixel);
-     while (overlap > 0 && bmdata[3].ascent + bmdata[3].descent <= 2*overlap + onePixel)
-@@ -2387,8 +2387,8 @@ nsMathMLChar::PaintHorizontally(nsPresCo
-   }
-   else { // glue is present
+     // Ensure the stride for the glue is not reduced to less than onePixel
+@@ -2418,8 +2418,8 @@ nsMathMLChar::PaintHorizontally(nsPresCo
+   else if (bmdata[3].rightBearing - bmdata[3].leftBearing > 0) {
+     // glue is present
      nscoord overlap;
 -    nsCOMPtr<nsIFontMetrics> fm;
 -    aRenderingContext.GetFontMetrics(*getter_AddRefs(fm));
 +    nsIFontMetrics* fm = nsnull;
 +    aRenderingContext.GetFontMetrics(*&fm);
      nsMathMLFrame::GetRuleThickness(fm, overlap);
      overlap = 2 * PR_MAX(overlap, onePixel);
-     while (overlap > 0 && bmdata[3].rightBearing - bmdata[3].leftBearing <= 2*overlap + onePixel)
+     // Ensure the stride for the glue is not reduced to less than onePixel
 diff --git a/modules/plugin/base/src/ns4xPlugin.cpp b/modules/plugin/base/src/ns4xPlugin.cpp
 --- a/modules/plugin/base/src/ns4xPlugin.cpp
 +++ b/modules/plugin/base/src/ns4xPlugin.cpp
-@@ -591,7 +591,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
+@@ -592,7 +592,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
    if (*aResult == NULL)
      return NS_ERROR_OUT_OF_MEMORY;
  
 -  NS_ADDREF(*aResult);
  
    if (!aFileName) //do not call NP_Initialize in this case, bug 74938
      return NS_OK;
-@@ -623,7 +622,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
+@@ -624,7 +623,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
    if (*aResult == NULL)
      return NS_ERROR_OUT_OF_MEMORY;
  
 -  NS_ADDREF(*aResult);
  
    // we must init here because the plugin may call NPN functions
    // when we call into the NP_Initialize entry point - NPN functions
-@@ -659,7 +657,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
+@@ -660,7 +658,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
    if (*aResult == NULL)
      return NS_ERROR_OUT_OF_MEMORY;
  
 -  NS_ADDREF(*aResult);
  
    // we must init here because the plugin may call NPN functions
    // when we call into the NP_Initialize entry point - NPN functions
-@@ -762,7 +759,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
+@@ -763,7 +760,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
    ::UseResFile(appRefNum);
    *aResult = plugin;
  
 -  NS_ADDREF(*aResult);
    if (NS_FAILED((*aResult)->Initialize())) {
      NS_RELEASE(*aResult);
      return NS_ERROR_FAILURE;
-@@ -791,7 +787,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
+@@ -792,7 +788,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
    if (*aResult == NULL)
      return NS_ERROR_OUT_OF_MEMORY;
  
 -  NS_ADDREF(*aResult);
  
    // we must init here because the plugin may call NPN functions
    // when we call into the NP_Initialize entry point - NPN functions
-@@ -830,7 +825,7 @@ ns4xPlugin::CreateInstance(nsISupports *
+@@ -831,7 +826,7 @@ ns4xPlugin::CreateInstance(nsISupports *
    *aResult = NULL;
  
    // XXX This is suspicuous!
 -  nsRefPtr<ns4xPluginInstance> inst =
 +  ns4xPluginInstance* inst =
      new ns4xPluginInstance(&fCallbacks, fLibrary);
  
    if (!inst)
-@@ -949,13 +944,13 @@ MakeNew4xStreamInternal(NPP npp, const c
+@@ -950,13 +945,13 @@ MakeNew4xStreamInternal(NPP npp, const c
    if (inst == NULL)
      return NPERR_INVALID_INSTANCE_ERROR;
  
 -  nsCOMPtr<nsIPluginManager> pm = do_GetService(kPluginManagerCID);
 +  nsIPluginManager* pm = do_GetService(kPluginManagerCID);
    NS_ASSERTION(pm, "failed to get plugin manager");
    if (!pm) return NPERR_GENERIC_ERROR;
  
 -  nsCOMPtr<nsIPluginStreamListener> listener;
 +  nsIPluginStreamListener* listener = nsnull;
    if (target == nsnull)
 -    ((ns4xPluginInstance*)inst)->NewNotifyStream(getter_AddRefs(listener),
 +    ((ns4xPluginInstance*)inst)->NewNotifyStream(&listener,
                                                   notifyData,
                                                   bDoNotify, relativeURL);
  
-@@ -1064,7 +1059,7 @@ _posturl(NPP npp, const char *relativeUR
+@@ -1065,7 +1060,7 @@ _posturl(NPP npp, const char *relativeUR
  // A little helper class used to wrap up plugin manager streams (that is,
  // streams from the plugin to the browser).
  
 -class ns4xStreamWrapper : nsISupports
 +class ns4xStreamWrapper : public XPCOMGCFinalizedObject, private nsISupports
  {
  public:
    NS_DECL_ISUPPORTS
-@@ -1089,7 +1084,6 @@ ns4xStreamWrapper::ns4xStreamWrapper(nsI
+@@ -1090,7 +1085,6 @@ ns4xStreamWrapper::ns4xStreamWrapper(nsI
    NS_ASSERTION(stream != NULL, "bad stream");
  
    fStream = stream;
 -  NS_ADDREF(fStream);
  
    memset(&fNPStream, 0, sizeof(fNPStream));
    fNPStream.ndata = (void*) this;
-@@ -1105,7 +1099,6 @@ ns4xStreamWrapper::GetStream(nsIOutputSt
+@@ -1106,7 +1100,6 @@ ns4xStreamWrapper::GetStream(nsIOutputSt
  ns4xStreamWrapper::GetStream(nsIOutputStream* &result)
  {
    result = fStream;
 -  NS_IF_ADDREF(fStream);
  }
  
  
-@@ -1120,12 +1113,12 @@ _newstream(NPP npp, NPMIMEType type, con
+@@ -1121,12 +1114,12 @@ _newstream(NPP npp, NPMIMEType type, con
    NPError err = NPERR_INVALID_INSTANCE_ERROR;
    if (npp && npp->ndata) {
      nsIPluginInstance *inst = (nsIPluginInstance *) npp->ndata;
 -    nsCOMPtr<nsIOutputStream> stream;
 -    nsCOMPtr<nsIPluginInstancePeer> peer;
 -    if (NS_SUCCEEDED(inst->GetPeer(getter_AddRefs(peer))) &&
 +    nsIOutputStream* stream = nsnull;
 +    nsIPluginInstancePeer* peer = nsnull;
 +    if (NS_SUCCEEDED(inst->GetPeer(&peer)) &&
        peer &&
        NS_SUCCEEDED(peer->NewStream((const char*) type, target,
 -                                   getter_AddRefs(stream)))) {
 +                                   &stream))) {
        ns4xStreamWrapper* wrapper = new ns4xStreamWrapper(stream);
        if (wrapper) {
          (*result) = wrapper->GetNPStream();
-@@ -1184,7 +1177,7 @@ _destroystream(NPP npp, NPStream *pstrea
+@@ -1185,7 +1178,7 @@ _destroystream(NPP npp, NPStream *pstrea
    if (!npp)
      return NPERR_INVALID_INSTANCE_ERROR;
  
 -  nsCOMPtr<nsIPluginStreamListener> listener =
 +  nsIPluginStreamListener* listener =
      do_QueryInterface((nsISupports *)pstream->ndata);
  
    // DestroyStream can kill two kinds of streams: NPP derived and NPN derived.
-@@ -1206,7 +1199,6 @@ _destroystream(NPP npp, NPStream *pstrea
+@@ -1207,7 +1200,6 @@ _destroystream(NPP npp, NPStream *pstrea
        return NPERR_INVALID_PARAM;
  
      // This will release the wrapped nsIOutputStream.
 -    delete wrapper;
      pstream->ndata = nsnull;
    }
  
-@@ -1228,8 +1220,8 @@ _status(NPP npp, const char *message)
+@@ -1229,8 +1221,8 @@ _status(NPP npp, const char *message)
  
    nsIPluginInstance *inst = (nsIPluginInstance *) npp->ndata;
  
 -  nsCOMPtr<nsIPluginInstancePeer> peer;
 -  if (NS_SUCCEEDED(inst->GetPeer(getter_AddRefs(peer))) && peer) {
 +  nsIPluginInstancePeer* peer = nsnull;
 +  if (NS_SUCCEEDED(inst->GetPeer(&peer)) && peer) {
      peer->ShowStatus(message);
    }
  }
-@@ -1264,7 +1256,7 @@ _reloadplugins(NPBool reloadPages)
+@@ -1265,7 +1257,7 @@ _reloadplugins(NPBool reloadPages)
    NPN_PLUGIN_LOG(PLUGIN_LOG_NORMAL,
                   ("NPN_ReloadPlugins: reloadPages=%d\n", reloadPages));
  
 -  nsCOMPtr<nsIPluginManager> pm(do_GetService(kPluginManagerCID));
 +  nsIPluginManager* pm(do_GetService(kPluginManagerCID));
  
    pm->ReloadPlugins(reloadPages);
  }
-@@ -1286,9 +1278,9 @@ _invalidaterect(NPP npp, NPRect *invalid
+@@ -1287,9 +1279,9 @@ _invalidaterect(NPP npp, NPRect *invalid
  
    nsIPluginInstance *inst = (nsIPluginInstance *) npp->ndata;
  
 -  nsCOMPtr<nsIPluginInstancePeer> peer;
 -  if (NS_SUCCEEDED(inst->GetPeer(getter_AddRefs(peer))) && peer) {
 -    nsCOMPtr<nsIWindowlessPluginInstancePeer> wpeer(do_QueryInterface(peer));
 +  nsIPluginInstancePeer* peer = nsnull;
 +  if (NS_SUCCEEDED(inst->GetPeer(&peer)) && peer) {
 +    nsIWindowlessPluginInstancePeer* wpeer(do_QueryInterface(peer));
      if (wpeer) {
        // XXX nsRect & NPRect are structurally equivalent
        wpeer->InvalidateRect((nsPluginRect *)invalidRect);
-@@ -1312,9 +1304,9 @@ _invalidateregion(NPP npp, NPRegion inva
+@@ -1313,9 +1305,9 @@ _invalidateregion(NPP npp, NPRegion inva
  
    nsIPluginInstance *inst = (nsIPluginInstance *) npp->ndata;
  
 -  nsCOMPtr<nsIPluginInstancePeer> peer;
 -  if (NS_SUCCEEDED(inst->GetPeer(getter_AddRefs(peer))) && peer) {
 -    nsCOMPtr<nsIWindowlessPluginInstancePeer> wpeer(do_QueryInterface(peer));
 +  nsIPluginInstancePeer* peer = nsnull;
 +  if (NS_SUCCEEDED(inst->GetPeer(&peer)) && peer) {
 +    nsIWindowlessPluginInstancePeer* wpeer(do_QueryInterface(peer));
      if (wpeer) {
        // nsPluginRegion & NPRegion are typedef'd to the same thing
        wpeer->InvalidateRegion((nsPluginRegion)invalidRegion);
-@@ -1336,9 +1328,9 @@ _forceredraw(NPP npp)
+@@ -1337,9 +1329,9 @@ _forceredraw(NPP npp)
  
    nsIPluginInstance *inst = (nsIPluginInstance *) npp->ndata;
  
 -  nsCOMPtr<nsIPluginInstancePeer> peer;
 -  if (NS_SUCCEEDED(inst->GetPeer(getter_AddRefs(peer))) && peer) {
 -    nsCOMPtr<nsIWindowlessPluginInstancePeer> wpeer(do_QueryInterface(peer));
 +  nsIPluginInstancePeer* peer = nsnull;
 +  if (NS_SUCCEEDED(inst->GetPeer(&peer)) && peer) {
 +    nsIWindowlessPluginInstancePeer* wpeer(do_QueryInterface(peer));
      if (wpeer) {
        wpeer->ForceRedraw();
      }
-@@ -1353,17 +1345,17 @@ GetJSContextFromNPP(NPP npp)
+@@ -1354,17 +1346,17 @@ GetDocumentFromNPP(NPP npp)
    ns4xPluginInstance *inst = (ns4xPluginInstance *)npp->ndata;
    NS_ENSURE_TRUE(inst, nsnull);
  
 -  nsCOMPtr<nsIPluginInstancePeer> pip;
 -  inst->GetPeer(getter_AddRefs(pip));
 -  nsCOMPtr<nsPIPluginInstancePeer> pp(do_QueryInterface(pip));
 +  nsIPluginInstancePeer* pip = nsnull;
 +  inst->GetPeer(&pip);
@@ -2486,20 +2510,20 @@ diff --git a/modules/plugin/base/src/ns4
 +  nsIPluginInstanceOwner* owner = nsnull;
 +  pp->GetOwner(&owner);
    NS_ENSURE_TRUE(owner, nsnull);
  
 -  nsCOMPtr<nsIDocument> doc;
 -  owner->GetDocument(getter_AddRefs(doc));
 +  nsIDocument* doc = nsnull;
 +  owner->GetDocument(&doc);
-   NS_ENSURE_TRUE(doc, nsnull);
- 
-   nsIScriptGlobalObject *sgo = doc->GetScriptGlobalObject();
-@@ -1398,19 +1390,19 @@ _getpluginelement(NPP npp)
+ 
+   return doc;
+ }
+@@ -1413,19 +1405,19 @@ _getpluginelement(NPP npp)
    }
  
    // Pass ownership of elementp to element
 -  nsCOMPtr<nsIDOMElement> element;
 -  element.swap(elementp);
 +  nsIDOMElement* element = nsnull;
 +  swap(element, elementp);
  
@@ -2514,73 +2538,73 @@ diff --git a/modules/plugin/base/src/ns4
 +  nsIXPConnectJSObjectHolder* holder = nsnull;
    xpc->WrapNative(cx, ::JS_GetGlobalObject(cx), element,
                    NS_GET_IID(nsIDOMElement),
 -                  getter_AddRefs(holder));
 +                  &holder);
    NS_ENSURE_TRUE(holder, nsnull);
  
    JSObject* obj = nsnull;
-@@ -1437,7 +1429,7 @@ NPIdentifier NP_CALLBACK
+@@ -1452,7 +1444,7 @@ NPIdentifier NP_CALLBACK
  NPIdentifier NP_CALLBACK
  _getstringidentifier(const NPUTF8* name)
  {
 -  nsCOMPtr<nsIThreadJSContextStack> stack =
 +  nsIThreadJSContextStack* stack =
      do_GetService("@mozilla.org/js/xpc/ContextStack;1");
    if (!stack)
      return NULL;
-@@ -1455,7 +1447,7 @@ _getstringidentifiers(const NPUTF8** nam
+@@ -1470,7 +1462,7 @@ _getstringidentifiers(const NPUTF8** nam
  _getstringidentifiers(const NPUTF8** names, int32_t nameCount,
                        NPIdentifier *identifiers)
  {
 -  nsCOMPtr<nsIThreadJSContextStack> stack =
 +  nsIThreadJSContextStack* stack =
      do_GetService("@mozilla.org/js/xpc/ContextStack;1");
    if (!stack)
      return;
-@@ -1639,7 +1631,7 @@ _evaluate(NPP npp, NPObject* npobj, NPSt
+@@ -1657,7 +1649,7 @@ _evaluate(NPP npp, NPObject* npobj, NPSt
    NS_ConvertUTF8toUTF16 utf16script(script->utf8characters,
                                      script->utf8length);
  
 -  nsCOMPtr<nsIScriptContext> scx = GetScriptContextFromJSContext(cx);
 +  nsIScriptContext* scx = GetScriptContextFromJSContext(cx);
    NS_ENSURE_TRUE(scx, false);
  
-   nsIPrincipal *principal = nsnull;
-@@ -1886,8 +1878,8 @@ _getvalue(NPP npp, NPNVariable variable,
+   nsIPrincipal *principal = doc->NodePrincipal();
+@@ -1932,8 +1924,8 @@ _getvalue(NPP npp, NPNVariable variable,
  
      ns4xPluginInstance *inst = (ns4xPluginInstance *) npp->ndata;
  
 -    nsCOMPtr<nsIPluginInstancePeer> peer;
 -    if (NS_SUCCEEDED(inst->GetPeer(getter_AddRefs(peer))) &&
 +    nsIPluginInstancePeer* peer = nsnull;
 +    if (NS_SUCCEEDED(inst->GetPeer(&peer)) &&
          peer &&
          NS_SUCCEEDED(peer->GetValue(nsPluginInstancePeerVariable_NetscapeWindow,
                                      result))) {
-@@ -1899,7 +1891,7 @@ _getvalue(NPP npp, NPNVariable variable,
+@@ -1945,7 +1937,7 @@ _getvalue(NPP npp, NPNVariable variable,
  
    case NPNVjavascriptEnabledBool: {
      *(NPBool*)result = PR_FALSE;
 -    nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
 +    nsIPrefBranch* prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
      if (prefs) {
        PRBool js = PR_FALSE;;
        res = prefs->GetBoolPref("javascript.enabled", &js);
-@@ -1915,7 +1907,7 @@ _getvalue(NPP npp, NPNVariable variable,
+@@ -1961,7 +1953,7 @@ _getvalue(NPP npp, NPNVariable variable,
  
    case NPNVisOfflineBool: {
      PRBool offline = PR_FALSE;
 -    nsCOMPtr<nsIIOService> ioservice =
 +    nsIIOService* ioservice =
        do_GetService(NS_IOSERVICE_CONTRACTID, &res);
      if (NS_SUCCEEDED(res))
        res = ioservice->GetOffline(&offline);
-@@ -1940,14 +1932,14 @@ _getvalue(NPP npp, NPNVariable variable,
+@@ -1986,14 +1978,14 @@ _getvalue(NPP npp, NPNVariable variable,
      ns4xPluginInstance *inst = (ns4xPluginInstance *) npp->ndata;
      NS_ENSURE_TRUE(inst, NPERR_GENERIC_ERROR);
  
 -    nsCOMPtr<nsIPluginInstancePeer> pip;
 -    inst->GetPeer(getter_AddRefs(pip));
 -    nsCOMPtr<nsIPluginTagInfo2> pti2 (do_QueryInterface(pip));
 +    nsIPluginInstancePeer* pip = nsnull;
 +    inst->GetPeer(&pip);
@@ -2591,57 +2615,57 @@ diff --git a/modules/plugin/base/src/ns4
 +      nsIDOMElement* e = nsnull;
 +      pti2->GetDOMElement(&e);
        if (e) {
 -        NS_ADDREF(*(nsIDOMElement**)result = e.get());
 +        *(nsIDOMElement**)result = e;
          return NPERR_NO_ERROR;
        }
      }
-@@ -1958,7 +1950,7 @@ _getvalue(NPP npp, NPNVariable variable,
+@@ -2004,7 +1996,7 @@ _getvalue(NPP npp, NPNVariable variable,
      ns4xPluginInstance *inst = (ns4xPluginInstance *)npp->ndata;
      NS_ENSURE_TRUE(inst, NPERR_GENERIC_ERROR);
  
 -    nsIDOMWindow *domWindow = inst->GetDOMWindow().get();
 +    nsIDOMWindow *domWindow = inst->GetDOMWindow();
  
      if (domWindow) {
        // Pass over ownership of domWindow to the caller.
-@@ -2079,7 +2071,7 @@ _setvalue(NPP npp, NPPVariable variable,
+@@ -2125,7 +2117,7 @@ _setvalue(NPP npp, NPPVariable variable,
      case NPPVjavascriptPushCallerBool:
        {
          nsresult rv;
 -        nsCOMPtr<nsIJSContextStack> contextStack =
 +        nsIJSContextStack* contextStack =
            do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
          if (NS_SUCCEEDED(rv)) {
            NPBool bPushCaller = (result != nsnull);
-@@ -2087,9 +2079,9 @@ _setvalue(NPP npp, NPPVariable variable,
+@@ -2133,9 +2125,9 @@ _setvalue(NPP npp, NPPVariable variable,
            if (bPushCaller) {
              rv = NS_ERROR_FAILURE;
  
 -            nsCOMPtr<nsIPluginInstancePeer> peer;
 -            if (NS_SUCCEEDED(inst->GetPeer(getter_AddRefs(peer))) && peer) {
 -              nsCOMPtr<nsIPluginInstancePeer2> peer2 =
 +            nsIPluginInstancePeer* peer = nsnull;
 +            if (NS_SUCCEEDED(inst->GetPeer(&peer)) && peer) {
 +              nsIPluginInstancePeer2* peer2 =
                  do_QueryInterface(peer);
  
                if (peer2) {
-@@ -2184,7 +2176,7 @@ _useragent(NPP npp)
+@@ -2230,7 +2222,7 @@ _useragent(NPP npp)
  
    char *retstr;
  
 -  nsCOMPtr<nsIPluginManager> pm(do_GetService(kPluginManagerCID));
 +  nsIPluginManager* pm(do_GetService(kPluginManagerCID));
  
    pm->UserAgent((const char **)&retstr);
  
-@@ -2317,7 +2309,7 @@ void NP_CALLBACK
+@@ -2363,7 +2355,7 @@ void NP_CALLBACK
  void NP_CALLBACK
  _pluginthreadasynccall(NPP instance, PluginThreadCallback func, void *userData)
  {
 -  nsRefPtr<nsPluginThreadRunnable> evt =
 +  nsPluginThreadRunnable* evt =
      new nsPluginThreadRunnable(instance, func, userData);
  
    if (evt && evt->IsValid()) {
@@ -2786,39 +2810,39 @@ diff --git a/view/src/nsView.cpp b/view/
 +    nsIDeviceContext* dx = nsnull;
 +    mViewManager->GetDeviceContext(*&dx);
      PRInt32 p2a = dx->AppUnitsPerDevPixel();
      nsIntRect ourRect(NSAppUnitsToIntPixels(toWidgetOffset.x, p2a),
                        NSAppUnitsToIntPixels(toWidgetOffset.y, p2a),
 diff --git a/xpcom/base/nsAgg.h b/xpcom/base/nsAgg.h
 --- a/xpcom/base/nsAgg.h
 +++ b/xpcom/base/nsAgg.h
-@@ -170,10 +170,6 @@ _InstanceClass##Constructor(nsISupports 
+@@ -171,10 +171,6 @@ _InstanceClass##Constructor(nsISupports 
                                                                              \
      nsISupports* inner = inst->InnerObject();                               \
      nsresult rv = inner->QueryInterface(aIID, aResult);                     \
 -    if (NS_FAILED(rv)) {                                                    \
 -        delete inst;                                                        \
 -    }                                                                       \
 -                                                                            \
      return rv;                                                              \
  }                                                                           \
  
-@@ -192,7 +188,6 @@ _InstanceClass##Constructor(nsISupports 
+@@ -193,7 +189,6 @@ _InstanceClass##Constructor(nsISupports 
      }                                                                       \
                                                                              \
      nsISupports* inner = inst->InnerObject();                               \
 -    NS_ADDREF(inner);                                                       \
      nsresult rv = inst->_InitMethod();                                      \
      if (NS_SUCCEEDED(rv)) {                                                 \
          rv = inner->QueryInterface(aIID, aResult);                          \
 diff --git a/xpcom/components/nsComponentManager.cpp b/xpcom/components/nsComponentManager.cpp
 --- a/xpcom/components/nsComponentManager.cpp
 +++ b/xpcom/components/nsComponentManager.cpp
-@@ -2040,7 +2040,6 @@ nsComponentManagerImpl::RegisterService(
+@@ -1992,7 +1992,6 @@ nsComponentManagerImpl::RegisterService(
                         (PL_DHashTableOperate(&mContractIDs, aContractID,
                                                  PL_DHASH_ADD));
          if (!contractIDTableEntry) {
 -            delete entry;
              return NS_ERROR_OUT_OF_MEMORY;
          }
  
 diff --git a/xpcom/glue/nsGenericFactory.cpp b/xpcom/glue/nsGenericFactory.cpp
--- a/hashentry-fixups.patch
+++ b/hashentry-fixups.patch
@@ -25,17 +25,17 @@ diff --git a/caps/include/nsScriptSecuri
 -
 -    enum { ALLOW_MEMMOVE = PR_TRUE };
  
  private:
      nsCOMPtr<nsIPrincipal> mKey;
 diff --git a/chrome/src/nsChromeRegistry.h b/chrome/src/nsChromeRegistry.h
 --- a/chrome/src/nsChromeRegistry.h
 +++ b/chrome/src/nsChromeRegistry.h
-@@ -213,9 +213,8 @@ public:
+@@ -212,9 +212,8 @@ public:
      typedef nsURIHashKey::KeyType        KeyType;
      typedef nsURIHashKey::KeyTypePointer KeyTypePointer;
  
 -    OverlayListEntry(KeyTypePointer aKey) : nsURIHashKey(aKey) { }
 -    OverlayListEntry(OverlayListEntry& toCopy) : nsURIHashKey(toCopy),
 -                                                 mArray(toCopy.mArray) { }
 +    OverlayListEntry(KeyTypePointer aKey, const void *entryStore)
 +      : nsURIHashKey(aKey, entryStore) { }
@@ -92,29 +92,29 @@ diff --git a/content/base/src/nsDocument
      static PLDHashNumber HashKey(KeyTypePointer aKey) { return *aKey; }
 -    enum { ALLOW_MEMMOVE = PR_TRUE };
  
      // Content set methods
      nsresult PutContent(nsIContent* aContent);
 diff --git a/content/base/src/nsNameSpaceManager.cpp b/content/base/src/nsNameSpaceManager.cpp
 --- a/content/base/src/nsNameSpaceManager.cpp
 +++ b/content/base/src/nsNameSpaceManager.cpp
-@@ -81,10 +81,7 @@ public:
+@@ -78,10 +78,7 @@ public:
    typedef const nsAString* KeyType;
    typedef const nsAString* KeyTypePointer;
  
 -  nsNameSpaceKey(KeyTypePointer aKey) : mKey(aKey)
 -  {
 -  }
 -  nsNameSpaceKey(const nsNameSpaceKey& toCopy) : mKey(toCopy.mKey)
 +  nsNameSpaceKey(KeyTypePointer aKey, const void *entryStore) : mKey(aKey)
    {
    }
  
-@@ -104,10 +101,6 @@ public:
+@@ -101,10 +98,6 @@ public:
    static PLDHashNumber HashKey(KeyTypePointer aKey) {
      return HashString(*aKey);
    }
 -
 -  enum { 
 -    ALLOW_MEMMOVE = PR_TRUE
 -  };
  
@@ -196,17 +196,17 @@ diff --git a/dom/src/storage/nsDOMStorag
 -
 -nsSessionStorageEntry::~nsSessionStorageEntry()
 +nsSessionStorageEntry::nsSessionStorageEntry(KeyTypePointer aStr,
 +                                             const void *entryStore)
 +  : nsStringHashKey(aStr, entryStore), mItem(nsnull)
  {
  }
  
-@@ -239,18 +230,9 @@ nsDOMStorageDB* nsDOMStorage::gStorageDB
+@@ -241,18 +232,9 @@ nsDOMStorageDB* nsDOMStorage::gStorageDB
  nsDOMStorageDB* nsDOMStorage::gStorageDB = nsnull;
  #endif
  
 -nsDOMStorageEntry::nsDOMStorageEntry(KeyTypePointer aStr)
 -  : nsVoidPtrHashKey(aStr), mStorage(nsnull)
 -{
 -}
 -
@@ -248,29 +248,29 @@ diff --git a/dom/src/storage/nsDOMStorag
 +  nsSessionStorageEntry(KeyTypePointer aStr, const void *entryStore);
 +  ~nsSessionStorageEntry() { }
  
    nsRefPtr<nsDOMStorageItem> mItem;
  };
 diff --git a/extensions/cookie/nsPermissionManager.cpp b/extensions/cookie/nsPermissionManager.cpp
 --- a/extensions/cookie/nsPermissionManager.cpp
 +++ b/extensions/cookie/nsPermissionManager.cpp
-@@ -69,7 +69,7 @@ ArenaStrDup(const char* str, PLArenaPool
+@@ -77,7 +77,7 @@ ArenaStrDup(const char* str, PLArenaPool
    return static_cast<char*>(mem);
  }
  
 -nsHostEntry::nsHostEntry(const char* aHost)
 +nsHostEntry::nsHostEntry(const char* aHost, const void*)
  {
    mHost = ArenaStrDup(aHost, gHostArena);
-   mPermissions[0] = mPermissions[1] = 0;
+ }
 diff --git a/extensions/cookie/nsPermissionManager.h b/extensions/cookie/nsPermissionManager.h
 --- a/extensions/cookie/nsPermissionManager.h
 +++ b/extensions/cookie/nsPermissionManager.h
-@@ -71,7 +71,7 @@ public:
+@@ -77,7 +77,7 @@ public:
    typedef const char* KeyType;
    typedef const char* KeyTypePointer;
  
 -  nsHostEntry(const char* aHost);
 +  nsHostEntry(const char* aHost, const void *entryStore);
    nsHostEntry(const nsHostEntry& toCopy);
  
    ~nsHostEntry()
@@ -298,28 +298,28 @@ diff --git a/extensions/spellcheck/src/m
 -
 -  enum { ALLOW_MEMMOVE = PR_TRUE };
  
  private:
    PRUnichar *mKey;
 diff --git a/gfx/thebes/public/gfxFont.h b/gfx/thebes/public/gfxFont.h
 --- a/gfx/thebes/public/gfxFont.h
 +++ b/gfx/thebes/public/gfxFont.h
-@@ -212,8 +212,8 @@ protected:
+@@ -213,8 +213,8 @@ protected:
  
          // When constructing a new entry in the hashtable, we'll leave this
          // blank. The caller of Put() will fill this in.
 -        HashEntry(KeyTypePointer aStr) : mFont(nsnull) { }
 -        HashEntry(const HashEntry& toCopy) : mFont(toCopy.mFont) { }
 +        HashEntry(KeyTypePointer aStr, const void *entryStore)
 +            : mFont(nsnull) { }
          ~HashEntry() { }
  
          PRBool KeyEquals(const KeyTypePointer aKey) const;
-@@ -285,10 +285,8 @@ private:
+@@ -289,10 +289,8 @@ private:
      public:
          // When constructing a new entry in the hashtable, we'll leave this
          // blank. The caller of Put() will fill this in.
 -        HashEntry(KeyTypePointer aPtr) : nsUint32HashKey(aPtr) {}
 -        HashEntry(const HashEntry& toCopy) : nsUint32HashKey(toCopy) {
 -          x = toCopy.x; y = toCopy.y; width = toCopy.width; height = toCopy.height;
 -        }
 +        HashEntry(KeyTypePointer aPtr, const void *entryStore)
@@ -361,17 +361,17 @@ diff --git a/layout/base/nsBidiPresUtils
 +  nsFrameContinuationState(const void *aFrame, const void *entryStore) :
 +    nsVoidPtrHashKey(aFrame, entryStore) {}
  
    /**
     * The first visual frame in the continuation chain containing this frame, or
 diff --git a/layout/style/nsCSSLoader.h b/layout/style/nsCSSLoader.h
 --- a/layout/style/nsCSSLoader.h
 +++ b/layout/style/nsCSSLoader.h
-@@ -226,18 +226,14 @@ public:
+@@ -225,18 +225,14 @@ public:
    typedef nsURIAndPrincipalHashKey* KeyType;
    typedef const nsURIAndPrincipalHashKey* KeyTypePointer;
  
 -  nsURIAndPrincipalHashKey(const nsURIAndPrincipalHashKey* aKey)
 -    : nsURIHashKey(aKey->mKey), mPrincipal(aKey->mPrincipal)
 +  nsURIAndPrincipalHashKey(const nsURIAndPrincipalHashKey* aKey,
 +                           const void *entryStore)
 +    : nsURIHashKey(aKey->mKey, entryStore), mPrincipal(aKey->mPrincipal)
@@ -384,17 +384,17 @@ diff --git a/layout/style/nsCSSLoader.h 
 -    MOZ_COUNT_CTOR(nsURIAndPrincipalHashKey);
 -  }
 -  nsURIAndPrincipalHashKey(const nsURIAndPrincipalHashKey& toCopy)
 -    : nsURIHashKey(toCopy), mPrincipal(toCopy.mPrincipal)
 +    : nsURIHashKey(aURI, NULL), mPrincipal(aPrincipal)
    {
      MOZ_COUNT_CTOR(nsURIAndPrincipalHashKey);
    }
-@@ -272,8 +268,6 @@ public:
+@@ -271,8 +267,6 @@ public:
      return nsURIHashKey::HashKey(aKey->mKey);
    }
       
 -  enum { ALLOW_MEMMOVE = PR_TRUE };
 - 
  protected:
    nsCOMPtr<nsIPrincipal> mPrincipal;
  };
@@ -411,17 +411,17 @@ diff --git a/netwerk/base/public/nsURIHa
 -    nsURIHashKey(const nsURIHashKey& toCopy) :
 -        mKey(toCopy.mKey) { MOZ_COUNT_CTOR(nsURIHashKey); }
      ~nsURIHashKey() { MOZ_COUNT_DTOR(nsURIHashKey); }
  
      nsIURI* GetKey() const { return mKey; }
 diff --git a/netwerk/cookie/src/nsCookieService.h b/netwerk/cookie/src/nsCookieService.h
 --- a/netwerk/cookie/src/nsCookieService.h
 +++ b/netwerk/cookie/src/nsCookieService.h
-@@ -72,16 +72,9 @@ class nsCookieEntry : public PLDHashEntr
+@@ -73,16 +73,9 @@ class nsCookieEntry : public PLDHashEntr
      typedef const char* KeyTypePointer;
  
      // do nothing with aHost - we require mHead to be set before we're live!
 -    nsCookieEntry(KeyTypePointer aHost)
 +    nsCookieEntry(KeyTypePointer aHost, const void *entryStore)
       : mHead(nsnull)
      {
 -    }
@@ -429,108 +429,108 @@ diff --git a/netwerk/cookie/src/nsCookie
 -    nsCookieEntry(const nsCookieEntry& toCopy)
 -    {
 -      // if we end up here, things will break. nsTHashtable shouldn't
 -      // allow this, since we set ALLOW_MEMMOVE to true.
 -      NS_NOTREACHED("nsCookieEntry copy constructor is forbidden!");
      }
  
      ~nsCookieEntry()
-@@ -119,8 +112,6 @@ class nsCookieEntry : public PLDHashEntr
+@@ -120,8 +113,6 @@ class nsCookieEntry : public PLDHashEntr
        // pass nsnull
        return PL_DHashStringKey(nsnull, aKey);
      }
 -
 -    enum { ALLOW_MEMMOVE = PR_TRUE };
  
      // get methods
      inline const nsDependentCString Host() const { return mHead->Host(); }
 diff --git a/netwerk/dns/src/nsEffectiveTLDService.cpp b/netwerk/dns/src/nsEffectiveTLDService.cpp
 --- a/netwerk/dns/src/nsEffectiveTLDService.cpp
 +++ b/netwerk/dns/src/nsEffectiveTLDService.cpp
-@@ -80,7 +80,7 @@ ArenaStrDup(const char* str, PLArenaPool
+@@ -81,7 +81,7 @@ ArenaStrDup(const char* str, PLArenaPool
    return static_cast<char*>(mem);
  }
  
 -nsDomainEntry::nsDomainEntry(const char *aDomain)
 +nsDomainEntry::nsDomainEntry(const char *aDomain, const void *entryStore)
   : mDomain(ArenaStrDup(aDomain, gArena))
   , mIsNormal(PR_FALSE)
   , mIsException(PR_FALSE)
 diff --git a/netwerk/dns/src/nsEffectiveTLDService.h b/netwerk/dns/src/nsEffectiveTLDService.h
 --- a/netwerk/dns/src/nsEffectiveTLDService.h
 +++ b/netwerk/dns/src/nsEffectiveTLDService.h
-@@ -53,14 +53,7 @@ public:
+@@ -54,14 +54,7 @@ public:
    typedef const char* KeyType;
    typedef const char* KeyTypePointer;
  
 -  nsDomainEntry(const char* aDomain);
 -
 -  nsDomainEntry(const nsDomainEntry& toCopy)
 -  {
 -    // if we end up here, things will break. nsTHashtable shouldn't
 -    // allow this, since we set ALLOW_MEMMOVE to true.
 -    NS_NOTREACHED("nsDomainEntry copy constructor is forbidden!");
 -  }
 +  nsDomainEntry(const char* aDomain, const void *entryStore);
  
    ~nsDomainEntry()
    {
-@@ -87,8 +80,6 @@ public:
+@@ -88,8 +81,6 @@ public:
      // pass nsnull
      return PL_DHashStringKey(nsnull, aKey);
    }
 -
 -  enum { ALLOW_MEMMOVE = PR_TRUE };
  
    PRPackedBool& IsNormal()    { return mIsNormal; }
    PRPackedBool& IsException() { return mIsException; }
 diff --git a/security/manager/ssl/src/nsCertOverrideService.h b/security/manager/ssl/src/nsCertOverrideService.h
 --- a/security/manager/ssl/src/nsCertOverrideService.h
 +++ b/security/manager/ssl/src/nsCertOverrideService.h
-@@ -95,13 +95,9 @@ class nsCertOverrideEntry : public PLDHa
+@@ -97,13 +97,9 @@ class nsCertOverrideEntry : public PLDHa
      typedef const char* KeyTypePointer;
  
      // do nothing with aHost - we require mHead to be set before we're live!
 -    nsCertOverrideEntry(KeyTypePointer aHostWithPortUTF8)
 +    nsCertOverrideEntry(KeyTypePointer aHostWithPortUTF8,
 +                        const void *entryStore)
      {
 -    }
 -
 -    nsCertOverrideEntry(const nsCertOverrideEntry& toCopy)
 -    {
 -      mSettings = toCopy.mSettings;
      }
  
      ~nsCertOverrideEntry()
-@@ -134,8 +130,6 @@ class nsCertOverrideEntry : public PLDHa
+@@ -136,8 +132,6 @@ class nsCertOverrideEntry : public PLDHa
        // pass nsnull
        return PL_DHashStringKey(nsnull, aKey);
      }
 -
 -    enum { ALLOW_MEMMOVE = PR_FALSE };
  
      // get methods
      inline const nsCString &HostWithPort() const { return mSettings.mHostWithPortUTF8; }
 diff --git a/toolkit/components/places/src/nsNavHistoryResult.h b/toolkit/components/places/src/nsNavHistoryResult.h
 --- a/toolkit/components/places/src/nsNavHistoryResult.h
 +++ b/toolkit/components/places/src/nsNavHistoryResult.h
-@@ -74,8 +74,8 @@ public:
+@@ -75,8 +75,8 @@ public:
    typedef const PRInt64& KeyType;
    typedef const PRInt64* KeyTypePointer;
  
 -  nsTrimInt64HashKey(KeyTypePointer aKey) : mValue(*aKey) { }
 -  nsTrimInt64HashKey(const nsTrimInt64HashKey& toCopy) : mValue(toCopy.mValue) { }
 +  nsTrimInt64HashKey(KeyTypePointer aKey, const void *entryStore)
 +    : mValue(*aKey) { }
    ~nsTrimInt64HashKey() { }
  
    KeyType GetKey() const { return mValue; }
-@@ -84,7 +84,6 @@ public:
+@@ -85,7 +85,6 @@ public:
    static KeyTypePointer KeyToPointer(KeyType aKey) { return &aKey; }
    static PLDHashNumber HashKey(KeyTypePointer aKey)
      { return static_cast<PRUint32>((*aKey) & PR_UINT32_MAX); }
 -  enum { ALLOW_MEMMOVE = PR_TRUE };
  
  private:
    const PRInt64 mValue;
 diff --git a/xpcom/glue/nsHashKeys.h b/xpcom/glue/nsHashKeys.h
--- a/js-shell-threading
+++ b/js-shell-threading
@@ -1,40 +1,54 @@
+* * *
+
 diff --git a/js/src/js.cpp b/js/src/js.cpp
 --- a/js/src/js.cpp
 +++ b/js/src/js.cpp
-@@ -188,8 +188,12 @@ my_BranchCallback(JSContext *cx, JSScrip
+@@ -102,6 +102,7 @@ static jsuword gStackBase;
+ 
+ static size_t gScriptStackQuota = JS_DEFAULT_SCRIPT_STACK_QUOTA;
+ 
++static JSBool gEnableBranchCallback = JS_FALSE;
+ static uint32 gBranchCount;
+ static uint32 gBranchLimit;
+ 
+@@ -188,8 +189,12 @@ my_BranchCallback(JSContext *cx, JSScrip
          gBranchCount = 0;
          return JS_FALSE;
      }
 -    if ((gBranchCount & 0x3fff) == 1)
 -        JS_MaybeGC(cx);
 +    if ((gBranchCount & 0xff) == 1) {
 +        if ((gBranchCount & 0x3fff) == 1)
 +            JS_MaybeGC(cx);
 +        else
 +            JS_YieldRequest(cx);
 +    }
      return JS_TRUE;
  }
  
-@@ -212,10 +216,8 @@ SetContextOptions(JSContext *cx)
+@@ -212,7 +217,7 @@ SetContextOptions(JSContext *cx)
      }
      JS_SetThreadStackLimit(cx, stackLimit);
      JS_SetScriptStackQuota(cx, gScriptStackQuota);
 -    if (gBranchLimit != 0) {
--        JS_SetBranchCallback(cx, my_BranchCallback);
--        JS_ToggleOptions(cx, JSOPTION_NATIVE_BRANCH_CALLBACK);
--    }
-+    JS_SetBranchCallback(cx, my_BranchCallback);
-+    JS_ToggleOptions(cx, JSOPTION_NATIVE_BRANCH_CALLBACK);
- }
++    if (gEnableBranchCallback) {
+         JS_SetBranchCallback(cx, my_BranchCallback);
+         JS_ToggleOptions(cx, JSOPTION_NATIVE_BRANCH_CALLBACK);
+     }
+@@ -466,6 +471,7 @@ ProcessArgs(JSContext *cx, JSObject *obj
  
- static void
-@@ -2457,6 +2459,252 @@ out:
+         case 'b':
+             gBranchLimit = atoi(argv[++i]);
++            gEnableBranchCallback = (gBranchLimit != 0);
+             break;
+ 
+         case 'c':
+@@ -2467,6 +2473,259 @@ out:
      return ok;
  }
  
 +#ifdef JS_THREADSAFE
 +
 +static JSBool
 +Sleep(JSContext *cx, uintN argc, jsval *vp)
 +{
@@ -59,29 +73,29 @@ diff --git a/js/src/js.cpp b/js/src/js.c
 +    SCATTER_WAIT,
 +    SCATTER_GO,
 +    SCATTER_CANCEL
 +};
 +
 +struct ScatterThreadData;
 +
 +struct ScatterData {
-+    ScatterThreadData *threads;
-+    jsval *results;
-+    PRLock *lock;
-+    PRCondVar *cvar;
-+    ScatterStatus status;
++    ScatterThreadData   *threads;
++    jsval               *results;
++    PRLock              *lock;
++    PRCondVar           *cvar;
++    ScatterStatus       status;
 +};
 +
 +struct ScatterThreadData {
-+    jsint index;
-+    ScatterData *shared;
-+    PRThread *thr;
-+    JSContext *cx;
-+    jsval fn;
++    jsint               index;
++    ScatterData         *shared;
++    PRThread            *thr;
++    JSContext           *cx;
++    jsval               fn;
 +};
 +
 +static void
 +DoScatteredWork(JSContext *cx, ScatterThreadData *td)
 +{
 +    jsval *rval = &td->shared->results[td->index];
 +
 +    if (!JS_CallFunctionValue(cx, NULL, td->fn, 0, NULL, rval)) {
@@ -114,33 +128,41 @@ diff --git a/js/src/js.cpp b/js/src/js.c
 +    JS_SetContextThread(cx);
 +    JS_SetThreadStackLimit(cx, 0);
 +    JS_BeginRequest(cx);
 +    DoScatteredWork(cx, td);
 +    JS_EndRequest(cx);
 +    JS_ClearContextThread(cx);
 +}
 +
-+/* scatter(fnArray) - Call each function in `fnArray` without arguments, each
-+ * in a different thread.  When all threads have finished, return an array:
-+ * the return values.  Errors are not propagated; if any of the function calls
-+ * fails with an exception, the corresponding slot in the results array gets
-+ * (undefined).
++/*
++ * scatter(fnArray) - Call each function in `fnArray` without arguments, each
++ * in a different thread. When all threads have finished, return an array: the
++ * return values. Errors are not propagated; if any of the function calls
++ * fails, the corresponding element in the results array gets the exception
++ * object, if any, else (undefined).
 + */
 +static JSBool
 +Scatter(JSContext *cx, uintN argc, jsval *vp)
 +{
 +    jsuint i;
-+    jsuint n; // number of threads
++    jsuint n;  /* number of threads */
 +    JSObject *inArr;
 +    JSObject *arr;
 +    ScatterData sd;
 +    JSBool ok;
 +    jsrefcount rc;
 +
++    if (!gEnableBranchCallback) {
++        /* Enable the branch callback, for periodic scope-sharing. */
++        gEnableBranchCallback = JS_TRUE;
++        JS_SetBranchCallback(cx, my_BranchCallback);
++        JS_ToggleOptions(cx, JSOPTION_NATIVE_BRANCH_CALLBACK);
++    }
++
 +    sd.lock = NULL;
 +    sd.cvar = NULL;
 +    sd.results = NULL;
 +    sd.threads = NULL;
 +    sd.status = SCATTER_WAIT;
 +
 +    if (!JSVAL_IS_OBJECT(JS_ARGV(cx, vp)[0]))
 +        goto fail;
@@ -195,30 +217,29 @@ diff --git a/js/src/js.cpp b/js/src/js.c
 +    }
 +
 +    for (i = 1; i < n; i++) {
 +        JSContext *newcx = JS_NewContext(JS_GetRuntime(cx), 8192);
 +        if (newcx == NULL)
 +            goto fail;
 +        JS_SetGlobalObject(newcx, JS_GetGlobalObject(cx));
 +        JS_ClearContextThread(newcx);
-+        // TODO - make sure JSContexts are actually correctly set up
 +        sd.threads[i].cx = newcx;
 +    }
 +
 +    for (i = 1; i < n; i++) {
 +        PRThread *t = PR_CreateThread(PR_USER_THREAD,
 +                                      RunScatterThread,
 +                                      &sd.threads[i],
 +                                      PR_PRIORITY_NORMAL,
 +                                      PR_LOCAL_THREAD,
 +                                      PR_JOINABLE_THREAD,
 +                                      0);
 +        if (t == NULL) {
-+            // Failed to start thread!
++            /* Failed to start thread! */
 +            PR_Lock(sd.lock);
 +            sd.status = SCATTER_CANCEL;
 +            PR_NotifyAllCondVar(sd.cvar);
 +            PR_Unlock(sd.lock);
 +            while (i-- > 1)
 +                PR_JoinThread(sd.threads[i].thr);
 +            goto fail;
 +        }
@@ -277,30 +298,30 @@ diff --git a/js/src/js.cpp b/js/src/js.c
 +}
 +
 +#endif
 +
 +
  /* We use a mix of JS_FS and JS_FN to test both kinds of natives. */
  static JSFunctionSpec shell_functions[] = {
      JS_FS("version",        Version,        0,0,0),
-@@ -2503,6 +2751,10 @@ static JSFunctionSpec shell_functions[] 
+@@ -2513,6 +2772,10 @@ static JSFunctionSpec shell_functions[] 
      JS_FN("getslx",         GetSLX,         1,1,0),
      JS_FN("toint32",        ToInt32,        1,1,0),
      JS_FS("evalcx",         EvalInContext,  1,0,0),
 +#ifdef JS_THREADSAFE
 +    JS_FN("sleep",          Sleep,          1,1,0),
 +    JS_FN("scatter",        Scatter,        1,1,0),
 +#endif
-     JS_FS_END
- };
- 
-@@ -2565,6 +2817,10 @@ static const char *const shell_help_mess
+ #ifdef MOZ_SHARK
+     JS_FS("startShark",      StartShark,      0,0,0),
+     JS_FS("stopShark",       StopShark,       0,0,0),
+@@ -2581,6 +2844,10 @@ static const char *const shell_help_mess
  "  Evaluate s in optional sandbox object o\n"
  "  if (s == '' && !o) return new o with eager standard classes\n"
  "  if (s == 'lazy' && !o) return new o with lazy standard classes",
 +#ifdef JS_THREADSAFE
 +"sleep(dt)                Sleep for dt seconds",
 +"scatter(fns)             Call functions concurrently (ignoring errors)",
 +#endif
- };
- 
- /* Help messages must match shell functions. */
+ #ifdef MOZ_SHARK
+ "startShark()             Start a Shark session.\n"
+ "                         Shark must be running with programatic sampling.",
deleted file mode 100644
--- a/jsref-with-threadsafe-mmgc
+++ /dev/null
@@ -1,1650 +0,0 @@
-* * *
-* * *
-* * *
-
-diff --git a/js/src/Makefile.ref b/js/src/Makefile.ref
---- a/js/src/Makefile.ref
-+++ b/js/src/Makefile.ref
-@@ -62,13 +62,15 @@ INCLUDES   += -I$(OBJDIR)
- INCLUDES   += -I$(OBJDIR)
- 
- ifdef JS_THREADSAFE
--DEFINES += -DJS_THREADSAFE
--INCLUDES += -I$(DIST)/include/nspr
--ifdef USE_MSVC
--OTHER_LIBS += $(DIST)/lib/libnspr$(NSPR_LIBSUFFIX).lib
--else
--OTHER_LIBS += -L$(DIST)/lib -lnspr$(NSPR_LIBSUFFIX)
--endif
-+DEFINES += -DJS_THREADSAFE -DMMGC_THREADSAFE
-+NSPR_INCLUDES = -I$(DIST_ABS)/include/nspr
-+INCLUDES += $(NSPR_INCLUDES)
-+ifdef USE_MSVC
-+NSPR_LDOPTS = $(DIST_ABS)/lib/libnspr$(NSPR_LIBSUFFIX).lib
-+else
-+NSPR_LDOPTS = -L$(DIST_ABS)/lib -lnspr$(NSPR_LIBSUFFIX)
-+endif
-+OTHER_LIBS += $(NSPR_LDOPTS)
- endif
- 
- ifdef JS_NO_THIN_LOCKS
-@@ -283,6 +285,9 @@ else
- else
- TAMARIN_CONFIGURE_FLAGS = --enable-debug
- endif
-+ifdef JS_THREADSAFE
-+TAMARIN_CONFIGURE_FLAGS += --with-threadsafe-mmgc --with-nspr-ldopts="$(NSPR_LDOPTS)" --with-nspr-includes="$(NSPR_INCLUDES)"
-+endif
- 
- include rules.mk
- 
-diff --git a/js/src/config.mk b/js/src/config.mk
---- a/js/src/config.mk
-+++ b/js/src/config.mk
-@@ -42,6 +42,7 @@ else
- else
- DIST = $(DEPTH)/../../dist
- endif
-+DIST_ABS = $(shell cd $(DIST) && pwd || echo "Error: JS_DIST directory '$(DIST)' does not exist")
- 
- # Set os+release dependent make variables
- OS_ARCH         := $(subst /,_,$(shell uname -s | sed /\ /s//_/))
-diff --git a/js/src/jsapi.cpp b/js/src/jsapi.cpp
---- a/js/src/jsapi.cpp
-+++ b/js/src/jsapi.cpp
-@@ -713,22 +713,17 @@ JS_NewRuntime(uint32 maxbytes)
- #ifdef JS_THREADSAFE
-     if (!js_InitThreadPrivateIndex(js_ThreadDestructorCB))
-         goto bad;
--    rt->gcLock = JS_NEW_LOCK();
--    if (!rt->gcLock)
-+#endif
-+    if (!js_InitGC(rt, maxbytes))
-         goto bad;
--    rt->gcDone = JS_NEW_CONDVAR(rt->gcLock);
--    if (!rt->gcDone)
--        goto bad;
--    rt->requestDone = JS_NEW_CONDVAR(rt->gcLock);
--    if (!rt->requestDone)
--        goto bad;
-+#ifdef JS_THREADSAFE
-     /* this is asymmetric with JS_ShutDown: */
-     if (!js_SetupLocks(8, 16))
-         goto bad;
-     rt->rtLock = JS_NEW_LOCK();
-     if (!rt->rtLock)
-         goto bad;
--    rt->stateChange = JS_NEW_CONDVAR(rt->gcLock);
-+    rt->stateChange = new MMgc::GCCondition(rt->gc->m_lock);
-     if (!rt->stateChange)
-         goto bad;
-     rt->setSlotLock = JS_NEW_LOCK();
-@@ -737,7 +732,7 @@ JS_NewRuntime(uint32 maxbytes)
-     rt->setSlotDone = JS_NEW_CONDVAR(rt->setSlotLock);
-     if (!rt->setSlotDone)
-         goto bad;
--    rt->scopeSharingDone = JS_NEW_CONDVAR(rt->gcLock);
-+    rt->scopeSharingDone = new MMgc::GCCondition(rt->gc->m_lock);
-     if (!rt->scopeSharingDone)
-         goto bad;
-     rt->scopeSharingTodo = NO_SCOPE_SHARING_TODO;
-@@ -745,8 +740,6 @@ JS_NewRuntime(uint32 maxbytes)
-     if (!rt->debuggerLock)
-         goto bad;
- #endif
--    if (!js_InitGC(rt, maxbytes))
--        goto bad;
-     if (!js_InitPropertyTree(rt))
-         goto bad;
-     return rt;
-@@ -789,27 +782,20 @@ JS_DestroyRuntime(JSRuntime *rt)
-      */
-     js_FinishDeflatedStringCache(rt);
- #ifdef JS_THREADSAFE
--    if (rt->gcLock)
--        JS_DESTROY_LOCK(rt->gcLock);
--    if (rt->gcDone)
--        JS_DESTROY_CONDVAR(rt->gcDone);
--    if (rt->requestDone)
--        JS_DESTROY_CONDVAR(rt->requestDone);
-     if (rt->rtLock)
-         JS_DESTROY_LOCK(rt->rtLock);
--    if (rt->stateChange)
--        JS_DESTROY_CONDVAR(rt->stateChange);
-+    delete rt->stateChange;
-     if (rt->setSlotLock)
-         JS_DESTROY_LOCK(rt->setSlotLock);
-     if (rt->setSlotDone)
-         JS_DESTROY_CONDVAR(rt->setSlotDone);
--    if (rt->scopeSharingDone)
--        JS_DESTROY_CONDVAR(rt->scopeSharingDone);
-+    delete rt->scopeSharingDone;
-     if (rt->debuggerLock)
-         JS_DESTROY_LOCK(rt->debuggerLock);
- #else
-     GSN_CACHE_CLEAR(&rt->gsnCache);
- #endif
-+    js_FinishGC(rt);
-     js_FinishPropertyTree(rt);
-     delete rt;
- }
-@@ -856,15 +842,15 @@ JS_BeginRequest(JSContext *cx)
-         JS_LOCK_GC(rt);
- 
-         /* NB: we use cx->thread here, not js_GetCurrentThread(). */
--        if (rt->gcThread != cx->thread) {
--            while (rt->gcLevel > 0)
--                JS_AWAIT_GC_DONE(rt);
--        }
-+        if (rt->gcThread != cx->thread && cx->thread->requestCount == 0)
-+            rt->gc->WaitForGCDone();
- 
-         /* Indicate that a request is running. */
--        rt->requestCount++;
-         cx->requestDepth = 1;
-         cx->outstandingRequests++;
-+        cx->thread->requestCount++;
-+        if (cx->thread->requestCount == 1)
-+            rt->gc->OnEnterRequestAlreadyLocked();
-         JS_UNLOCK_GC(rt);
-         return;
-     }
-@@ -880,6 +866,7 @@ JS_EndRequest(JSContext *cx)
-     uintN nshares;
- 
-     CHECK_REQUEST(cx);
-+    JS_ASSERT(cx->thread->id == js_CurrentThreadId());
-     JS_ASSERT(cx->requestDepth > 0);
-     JS_ASSERT(cx->outstandingRequests > 0);
-     if (cx->requestDepth == 1) {
-@@ -915,13 +902,12 @@ JS_EndRequest(JSContext *cx)
-             }
-         }
-         if (nshares)
--            JS_NOTIFY_ALL_CONDVAR(rt->scopeSharingDone);
-+            rt->scopeSharingDone->NotifyAll();
- 
-         /* Give the GC a chance to run if this was the last request running. */
--        JS_ASSERT(rt->requestCount > 0);
--        rt->requestCount--;
--        if (rt->requestCount == 0)
--            JS_NOTIFY_REQUEST_DONE(rt);
-+        cx->thread->requestCount--;
-+        if (cx->thread->requestCount == 0)
-+            rt->gc->OnLeaveRequestAlreadyLocked();
- 
-         JS_UNLOCK_GC(rt);
-         return;
-@@ -942,19 +928,19 @@ JS_YieldRequest(JSContext *cx)
- 
-     rt = cx->runtime;
-     JS_LOCK_GC(rt);
--    JS_ASSERT(rt->requestCount > 0);
--    rt->requestCount--;
--    if (rt->requestCount == 0)
--        JS_NOTIFY_REQUEST_DONE(rt);
-+    JS_ASSERT(cx->thread->requestCount > 0);
-+    cx->thread->requestCount--;
-+    if (cx->thread->requestCount == 0)
-+        rt->gc->OnLeaveRequestAlreadyLocked();
-     JS_UNLOCK_GC(rt);
-     /* XXXbe give the GC or another request calling it a chance to run here?
-              Assumes FIFO scheduling */
-     JS_LOCK_GC(rt);
--    if (rt->gcThread != cx->thread) {
--        while (rt->gcLevel > 0)
--            JS_AWAIT_GC_DONE(rt);
--    }
--    rt->requestCount++;
-+    if (rt->gc->m_exclusiveGCThread != MMgc::GCThread::GetCurrentThread())
-+        rt->gc->WaitForGCDone();
-+    cx->thread->requestCount++;
-+    if (cx->thread->requestCount == 1)
-+        rt->gc->OnEnterRequestAlreadyLocked();
-     JS_UNLOCK_GC(rt);
- }
- 
-@@ -962,6 +948,8 @@ JS_SuspendRequest(JSContext *cx)
- JS_SuspendRequest(JSContext *cx)
- {
-     jsrefcount saveDepth = cx->requestDepth;
-+
-+    //XXX HORRIBLE BUG;  // stack isn't rooted here
- 
-     while (cx->requestDepth)
-         JS_EndRequest(cx);
-@@ -2367,9 +2355,9 @@ JS_MarkGCThing(JSContext *cx, void *thin
- 
-     trc = (JSTracer *)arg;
-     if (!trc)
--        trc = cx->runtime->gcMarkingTracer;
-+        trc = cx->runtime->gc->GetTracer();
-     else
--        JS_ASSERT(trc == cx->runtime->gcMarkingTracer);
-+        JS_ASSERT(trc == cx->runtime->gc->GetTracer());
- 
- #ifdef JS_THREADSAFE
-     JS_ASSERT(cx->runtime->gcThread == trc->context->thread);
-@@ -2399,8 +2387,8 @@ JS_MaybeGC(JSContext *cx)
- JS_MaybeGC(JSContext *cx)
- {
- #ifdef JS_GC_ZEAL
--    if (cx->runtime->gcZeal > 0) {
--        JS_GC(cx);
-+    if (cx->runtime->gc->greedy) {
-+        js_GC(cx, GC_NORMAL);
-         return;
-     }
- #endif
-@@ -5518,7 +5506,7 @@ JS_PUBLIC_API(void)
- JS_PUBLIC_API(void)
- JS_SetGCZeal(JSContext *cx, uint8 zeal)
- {
--    cx->runtime->gcZeal = zeal;
-+    cx->runtime->gc->greedy = (zeal != 0);
- }
- #endif
- 
-diff --git a/js/src/jsapi.h b/js/src/jsapi.h
---- a/js/src/jsapi.h
-+++ b/js/src/jsapi.h
-@@ -907,16 +907,6 @@ JS_STATIC_ASSERT(JSVAL_TRACE_KIND(JSVAL_
- JS_STATIC_ASSERT(JSVAL_TRACE_KIND(JSVAL_DOUBLE) == JSTRACE_DOUBLE);
- JS_STATIC_ASSERT(JSVAL_TRACE_KIND(JSVAL_STRING) == JSTRACE_STRING);
- 
--struct JSTracer {
--    JSContext           *context;
--    JSTraceCallback     callback;
--#ifdef DEBUG
--    JSTraceNamePrinter  debugPrinter;
--    const void          *debugPrintArg;
--    size_t              debugPrintIndex;
--#endif
--};
--
- /*
-  * The method to call on each reference to a traceable thing stored in a
-  * particular JSObject or other runtime structure. With DEBUG defined the
-diff --git a/js/src/jscntxt.cpp b/js/src/jscntxt.cpp
---- a/js/src/jscntxt.cpp
-+++ b/js/src/jscntxt.cpp
-@@ -84,6 +84,7 @@ js_InitThreadPrivateIndex(void (JS_DLL_C
-     if (tpIndexInited)
-         return JS_TRUE;
- 
-+    MMgc::GCThread::Init();
-     status = PR_NewThreadPrivateIndex(&threadTPIndex, ptr);
- 
-     if (status == PR_SUCCESS)
-@@ -102,6 +103,7 @@ js_ThreadDestructorCB(void *ptr)
- 
-     if (!thread)
-         return;
-+    JS_ASSERT(thread->requestCount == 0);
-     JS_ASSERT(JS_CLIST_IS_EMPTY(&thread->contextList));
-     GSN_CACHE_CLEAR(&thread->gsnCache);
-     free(thread);
-@@ -136,6 +138,9 @@ js_GetCurrentThread(JSRuntime *rt)
- 
-         JS_INIT_CLIST(&thread->contextList);
-         thread->id = js_CurrentThreadId();
-+        thread->requestCount = 0;
-+        thread->pendingGCContext = NULL;
-+        thread->pendingGCKind = GC_NOT_RUNNING;
-     }
-     return thread;
- }
-@@ -224,7 +229,7 @@ js_NewContext(JSRuntime *rt, size_t stac
-             rt->state = JSRTS_LAUNCHING;
-             break;
-         }
--        JS_WAIT_CONDVAR(rt->stateChange, JS_NO_TIMEOUT);
-+        JS_WAIT_GCCONDITION(rt->stateChange);
-     }
-     JS_APPEND_LINK(&cx->links, &rt->contextList);
-     JS_UNLOCK_GC(rt);
-@@ -282,7 +287,7 @@ js_NewContext(JSRuntime *rt, size_t stac
- 
-         JS_LOCK_GC(rt);
-         rt->state = JSRTS_UP;
--        JS_NOTIFY_ALL_CONDVAR(rt->stateChange);
-+        JS_NOTIFY_ALL_GCCONDITION(rt->stateChange);
-         JS_UNLOCK_GC(rt);
-     }
- 
-@@ -392,7 +397,7 @@ js_DestroyContext(JSContext *cx, JSDestr
-         /* Take the runtime down, now that it has no contexts or atoms. */
-         JS_LOCK_GC(rt);
-         rt->state = JSRTS_DOWN;
--        JS_NOTIFY_ALL_CONDVAR(rt->stateChange);
-+        JS_NOTIFY_ALL_GCCONDITION(rt->stateChange);
-         JS_UNLOCK_GC(rt);
-     } else {
-         if (mode == JSDCM_FORCE_GC)
-@@ -629,7 +634,7 @@ js_LeaveLocalRootScopeWithResult(JSConte
- 
-     /*
-      * Pop the scope, restoring lrs->scopeMark.  If rval is a GC-thing, push
--     * it on the caller's scope, or store it in lastInternalResult if we are
-+     * it on the caller's scope, or trust to the conservative GC if we are
-      * leaving the outermost scope.  We don't need to allocate a new lrc
-      * because we can overwrite the old mark's slot with rval.
-      */
-diff --git a/js/src/jscntxt.h b/js/src/jscntxt.h
---- a/js/src/jscntxt.h
-+++ b/js/src/jscntxt.h
-@@ -112,6 +112,25 @@ struct JSThread {
-     uint32              gcMallocBytes;
- 
-     /*
-+     * Per-thread garbage collection parameters.
-+     *
-+     * js_GC stashes garbage collection parameters here before calling
-+     * JSGC::Collect.  If MMgc decides to collect on this thread, then
-+     * JSGC::enterExclusiveGC moves these parameters to rt->gcContext and
-+     * rt->gcKind.  These fields are cleared at that time.  If GC does not
-+     * happen on this thread, then js_GC clears these fields before exiting.
-+     *
-+     * js_NewGCThing uses these fields for exactly the same purpose, though in
-+     * that case GC usually does not happen.
-+     *
-+     * Invariant: A call to js_GC or js_NewGCThing may change these values
-+     * while it's running, but it will always restore the previous values
-+     * before returning.
-+     */
-+    JSContext           *pendingGCContext;
-+    JSGCInvocationKind  pendingGCKind;
-+
-+    /*
-      * Store the GSN cache in struct JSThread, not struct JSContext, both to
-      * save space and to simplify cleanup in js_GC.  Any embedding (Firefox
-      * or another Gecko application) that uses many contexts per thread is
-@@ -119,6 +138,9 @@ struct JSThread {
-      * among two or more contexts running script in one thread.
-      */
-     JSGSNCache          gsnCache;
-+
-+    /* Number of contexts in active requests on this thread. */
-+    jsrefcount          requestCount;
- };
- 
- #define JS_GSN_CACHE(cx) ((cx)->thread->gsnCache)
-@@ -180,7 +202,10 @@ private:
- };
- 
- struct JSRuntime {
--    /* Runtime state, synchronized by the stateChange/gcLock condvar/lock. */
-+    /*
-+     * Runtime state, synchronized by the stateChange/gc->m_lock
-+     * condvar/lock.
-+     */
-     JSRuntimeState      state;
- 
-     /* Context create/destroy callback. */
-@@ -196,23 +221,11 @@ struct JSRuntime {
- 
-     uint32              gcMaxBytes;
-     uint32              gcMaxMallocBytes;
--    uint32              gcLevel;
--    uint32              gcNumber;
--    JSTracer            *gcMarkingTracer;
--
--    /*
--     * NB: do not pack another flag here by claiming gcPadding unless the new
--     * flag is written only by the GC thread.  Atomic updates to packed bytes
--     * are not guaranteed, so stores issued by one thread may be lost due to
--     * unsynchronized read-modify-write cycles on other threads.
--     */
--    JSPackedBool        gcPoke;
--    uint8               gcRunning;  /* JSGCInvocationKind */
--    uint16              gcPadding;
--#ifdef JS_GC_ZEAL
--    jsrefcount          gcZeal;
--#endif
-+
-+    JSBool              gcPoke;
-+
-     JSContext           *gcContext;
-+    JSGCInvocationKind  gcKind;
- 
-     JSGCCallback        gcCallback;
-     uint32              gcMallocBytes;
-@@ -259,7 +272,7 @@ struct JSRuntime {
-     JSString            *emptyString;
-     JSString            **unitStrings;
- 
--    /* List of active contexts sharing this runtime; protected by gcLock. */
-+    /* List of active contexts sharing this runtime; protected by gc->m_lock. */
-     JSCList             contextList;
- 
-     /* Per runtime debug hooks -- see jsprvtd.h and jsdbgapi.h. */
-@@ -273,11 +286,6 @@ struct JSRuntime {
-     void                *data;
- 
- #ifdef JS_THREADSAFE
--    /* These combine to interlock the GC and new requests. */
--    PRLock              *gcLock;
--    PRCondVar           *gcDone;
--    PRCondVar           *requestDone;
--    uint32              requestCount;
-     JSThread            *gcThread;
- 
-     /* Lock and owning thread pointer for JS_LOCK_RUNTIME. */
-@@ -286,8 +294,8 @@ struct JSRuntime {
-     jsword              rtLockOwner;
- #endif
- 
--    /* Used to synchronize down/up state change; protected by gcLock. */
--    PRCondVar           *stateChange;
-+    /* Used to synchronize down/up state change; protected by gc->m_lock. */
-+    MMgc::GCCondition   *stateChange;
- 
-     /* Used to serialize cycle checks when setting __proto__ or __parent__. */
-     PRLock              *setSlotLock;
-@@ -297,15 +305,15 @@ struct JSRuntime {
- 
-     /*
-      * State for sharing single-threaded scopes, once a second thread tries to
--     * lock a scope.  The scopeSharingDone condvar is protected by rt->gcLock,
--     * to minimize number of locks taken in JS_EndRequest.
-+     * lock a scope.  The scopeSharingDone condvar is protected by
-+     * rt->gc->m_lock, to minimize number of locks taken in JS_EndRequest.
-      *
-      * The scopeSharingTodo linked list is likewise "global" per runtime, not
-      * one-list-per-context, to conserve space over all contexts, optimizing
-      * for the likely case that scopes become shared rarely, and among a very
-      * small set of threads (contexts).
-      */
--    PRCondVar           *scopeSharingDone;
-+    MMgc::GCCondition   *scopeSharingDone;
-     JSScope             *scopeSharingTodo;
- 
- /*
-@@ -682,6 +690,10 @@ struct JSContext {
-     JSStackFrame        *dormantFrameChain; /* dormant stack frame to scan */
- #ifdef JS_THREADSAFE
-     JSThread            *thread;
-+
-+    /* @access ReadWrite(gc->m_lock || cxThreadIsCurrentThread,
-+     *                   gc->m_lock && cxThreadIsCurrentThread)
-+     */
-     jsrefcount          requestDepth;
-     /* Same as requestDepth but ignoring JS_SuspendRequest/JS_ResumeRequest */
-     jsrefcount          outstandingRequests;
-@@ -708,7 +720,12 @@ struct JSContext {
- };
- 
- #ifdef JS_THREADSAFE
--# define JS_THREAD_ID(cx)       ((cx)->thread ? (cx)->thread->id : 0)
-+# define JS_THREAD_ID(cx)         ((cx)->thread ? (cx)->thread->id : 0)
-+# define JS_IS_IN_REQUEST(cx)     ((cx)->requestDepth > 0)
-+# define THREAD_IS_IN_REQUEST(cx) ((cx)->thread->requestCount > 0)
-+#else
-+# define JS_IS_IN_REQUEST(cx)     false
-+# define THREAD_IS_IN_REQUEST(cx) false
- #endif
- 
- /*
-@@ -789,14 +806,14 @@ js_DestroyContext(JSContext *cx, JSDestr
- 
- /*
-  * Return true if cx points to a context in rt->contextList, else return false.
-- * NB: the caller (see jslock.c:ClaimScope) must hold rt->gcLock.
-+ * NB: the caller (see jslock.c:ClaimScope) must hold rt->gc->m_lock.
-  */
- extern JSBool
- js_ValidContextPointer(JSRuntime *rt, JSContext *cx);
- 
- /*
-- * If unlocked, acquire and release rt->gcLock around *iterp update; otherwise
-- * the caller must be holding rt->gcLock.
-+ * If unlocked, acquire and release rt->gc->m_lock around *iterp update;
-+ * otherwise the caller must be holding rt->gc->m_lock.
-  */
- extern JSContext *
- js_ContextIterator(JSRuntime *rt, JSBool unlocked, JSContext **iterp);
-diff --git a/js/src/jsgc.cpp b/js/src/jsgc.cpp
---- a/js/src/jsgc.cpp
-+++ b/js/src/jsgc.cpp
-@@ -73,6 +73,7 @@
- 
- namespace
- {
-+    // XXX TODO - Get rid of static initializer.
-     class Init {
-     public:
-         Init()
-@@ -89,6 +90,20 @@ namespace
- 
-     Init _init;
- }
-+
-+#ifdef JS_THREADSAFE
-+#define PENDING_GC_CONTEXT(thread) ((thread)->pendingGCContext)
-+#define PENDING_GC_KIND(thread)    ((thread)->pendingGCKind)
-+#else
-+/* Single-threaded equivalent of JSThread::gcContext. */
-+static JSContext *g_pendingGCContext = NULL;
-+
-+/* Single-threaded equivalent of JSThread::gcKind. */
-+static JSGCInvocationKind g_pendingGCKind = GC_NOT_RUNNING;
-+
-+#define PENDING_GC_CONTEXT(ignore) g_pendingGCContext
-+#define PENDING_GC_KIND(ignore)    g_pendingGCKind
-+#endif
- 
- JS_STATIC_ASSERT(sizeof(JSStackHeader) >= 2 * sizeof(jsval));
- 
-@@ -356,10 +371,20 @@ js_InitGC(JSRuntime *rt, uint32 maxbytes
-     if (!rt->gc)
-         return JS_FALSE;
- 
-+    /*
-+     * Allocate the object responsible for SpiderMonkey's exact marking.
-+     * We enter an MMgc request, temporarily, around this allocation.
-+     */
-+    rt->gc->OnEnterRequest();
-     rt->gcMarker = new(rt->gc) JSRuntimeGCMarker(rt);
-     if (!rt->gcMarker)
-         return JS_FALSE;
--
-+    rt->gc->OnLeaveRequest();
-+
-+    /*
-+     * Note: This allocation is from a non-threadsafe allocator.  This is only
-+     * threadsafe because the GC hasn't been exposed to any other threads yet.
-+     */
-     rt->gcMarkerRoot =
-         new MMgc::GCRoot(rt->gc, &rt->gcMarker, sizeof(rt->gcMarker));
-     if (!rt->gcMarkerRoot)
-@@ -415,11 +440,12 @@ js_AddRootRT(JSRuntime *rt, void *rp, co
-     JSGCRootHashEntry *rhe;
- 
-     /*
--     * Due to the long-standing, but now removed, use of rt->gcLock across the
--     * bulk of js_GC, API users have come to depend on JS_AddRoot etc. locking
--     * properly with a racing GC, without calling JS_AddRoot from a request.
--     * We have to preserve API compatibility here, now that we avoid holding
--     * rt->gcLock across the mark phase (including the root hashtable mark).
-+     * Due to the long-standing, but now removed, use of rt->gc->m_lock across
-+     * the bulk of js_GC, API users have come to depend on JS_AddRoot
-+     * etc. locking properly with a racing GC, without calling JS_AddRoot from
-+     * a request.  We have to preserve API compatibility here, now that we
-+     * avoid holding rt->gc->m_lock across the mark phase (including the root
-+     * hashtable mark).
-      *
-      * If the GC is running and we're called on another thread, wait for this
-      * GC activation to finish.  We can safely wait here (in the case where we
-@@ -429,12 +455,8 @@ js_AddRootRT(JSRuntime *rt, void *rp, co
-      */
-     JS_LOCK_GC(rt);
- #ifdef JS_THREADSAFE
--    JS_ASSERT(!rt->gcRunning || rt->gcLevel > 0);
--    if (rt->gcRunning && rt->gcThread->id != js_CurrentThreadId()) {
--        do {
--            JS_AWAIT_GC_DONE(rt);
--        } while (rt->gcLevel > 0);
--    }
-+    if (rt->gc->IsGCRunning() && rt->gcThread->id != js_CurrentThreadId())
-+        rt->gc->WaitForGCDone();
- #endif
-     rhe = (JSGCRootHashEntry *)
-           JS_DHashTableOperate(&rt->gcRootsHash, rp, JS_DHASH_ADD);
-@@ -458,12 +480,8 @@ js_RemoveRoot(JSRuntime *rt, void *rp)
-      */
-     JS_LOCK_GC(rt);
- #ifdef JS_THREADSAFE
--    JS_ASSERT(!rt->gcRunning || rt->gcLevel > 0);
--    if (rt->gcRunning && rt->gcThread->id != js_CurrentThreadId()) {
--        do {
--            JS_AWAIT_GC_DONE(rt);
--        } while (rt->gcLevel > 0);
--    }
-+    if (rt->gc->IsGCRunning() && rt->gcThread->id != js_CurrentThreadId())
-+        rt->gc->WaitForGCDone();
- #endif
-     (void) JS_DHashTableOperate(&rt->gcRootsHash, rp, JS_DHASH_REMOVE);
-     rt->gcPoke = JS_TRUE;
-@@ -594,7 +612,9 @@ js_RegisterCloseableIterator(JSContext *
-     JSBool ok;
- 
-     rt = cx->runtime;
--    JS_ASSERT(!rt->gcRunning);
-+#ifdef JS_THREADSAFE
-+    JS_ASSERT(!rt->gc->IsGCRunning());
-+#endif
- 
-     JS_LOCK_GC(rt);
-     ok = AddToPtrTable(cx, &rt->gcIteratorTable, &iteratorTableInfo, obj);
-@@ -630,30 +650,58 @@ JSGC::JSGC(JSRuntime *_rt)
-       GCCallback(this),
-       rt(_rt)
- {
--    /*
--     * By default, any call to Alloc may result in a collection.  The nogc
--     * bit overrides this, allowing SpiderMonkey to control exactly when GC
--     * happens.  This is necessary because GC::Collect() is not the full story
--     * in SpiderMonkey; see js_GC() to see other things that must happen with
--     * each collection.
--     */
--    nogc = true;
--
-     /* Incremental mode requires more work; see MMgc docs. */
-     incremental = false;
- }
- 
-+bool
-+JSGC::precollect()
-+{
-+    JSContext *cx;
-+    JSGCInvocationKind gckind;
-+
-+#ifdef JS_THREADSAFE
-+    /* Avoid deadlock. */
-+    JS_ASSERT(!JS_IS_RUNTIME_LOCKED(rt));
-+
-+    JSThread *thread = js_GetCurrentThread(rt);
-+#endif
-+
-+    cx = PENDING_GC_CONTEXT(thread);
-+    gckind = PENDING_GC_KIND(thread);
-+
-+    /*
-+     * Don't collect garbage if the runtime isn't up, and cx is not the last
-+     * context in the runtime.  The last context must force a GC, and nothing
-+     * should suppress that final collection or there may be shutdown leaks,
-+     * or runtime bloat until the next context is created.
-+     */
-+    if (rt->state != JSRTS_UP && gckind != GC_LAST_CONTEXT)
-+        return false;
-+
-+    /*
-+     * Let the API user decide to defer a GC if it wants to (unless this
-+     * is the last context).  Invoke the callback regardless.
-+     */
-+    if (rt->gcCallback &&
-+        !rt->gcCallback(cx, JSGC_BEGIN) &&
-+        gckind != GC_LAST_CONTEXT) {
-+        return false;
-+    }
-+
-+#ifdef JS_THREADSAFE
-+    /* Assert this after the callback has a chance to veto the collection. */
-+    JS_ASSERT(cx->thread == thread);
-+#endif
-+
-+    return true;
-+}
-+
- void
--JSGC::lastmark(MMgc::GCStack<MMgc::GCWorkItem> &)
-+JSGC::presweep()
- {
-     JSContext *cx = rt->gcContext;
- 
--    /*
--     * These callbacks must be called from the lastmark() hook, even though we
--     * don't use the GCStack parameter, to allow for the future possibility of
--     * using incremental GC.  Otherwise we would have to break JSAPI
--     * compatibility.
--     */
-     JS_ASSERT(!cx->insideGCMarkCallback);
-     if (rt->gcCallback) {
-         cx->insideGCMarkCallback = JS_TRUE;
-@@ -662,41 +710,154 @@ JSGC::lastmark(MMgc::GCStack<MMgc::GCWor
-         cx->insideGCMarkCallback = JS_FALSE;
-     }
-     JS_ASSERT(rt->gcUnscannedStack == NULL);
-+
-+    /*
-+     * We first sweep atom state so we can use js_IsAboutToBeFinalized on
-+     * JSString or jsdouble held in a hashtable to check if the hashtable
-+     * entry can be freed. Note that even after the entry is freed,
-+     * JSObject finalizers can continue to access the corresponding
-+     * jsdouble* and JSString* assuming that they are unique. This works
-+     * since the atomization API must not be called during GC.
-+     */
-+    js_SweepAtomState(cx);
-+
-+    /* Finalize iterator states before the objects they iterate over. */
-+    CloseNativeIterators(cx);
-+
-+    /* Finalize watch points associated with unreachable objects. */
-+    js_SweepWatchPoints(cx);
-+
-+#ifdef DUMP_CALL_TABLE
-+    /*
-+     * Call js_DumpCallTable here so it can meter and then clear weak refs
-+     * to GC-things that are about to be finalized.
-+     */
-+    js_DumpCallTable(cx);
-+#endif
- }
- 
- void
--JSGC::presweep()
-+JSGC::postsweep()
-+{
-+    /*
-+     * Sweep the runtime's property tree after finalizing objects, in case any
-+     * had watchpoints referencing tree nodes.
-+     */
-+    js_SweepScopeProperties(rt->gcContext);
-+
-+    /*
-+     * Sweep script filenames after sweeping functions in the generic loop
-+     * above. In this way when a scripted function's finalizer destroys the
-+     * script and calls rt->destroyScriptHook, the hook can still access the
-+     * script's filename. See bug 323267.
-+     */
-+    js_SweepScriptFilenames(rt);
-+
-+    if (rt->gcCallback)
-+        (void) rt->gcCallback(rt->gcContext, JSGC_FINALIZE_END);
-+#ifdef DEBUG_srcnotesize
-+  { extern void DumpSrcNoteSizeHist();
-+    DumpSrcNoteSizeHist();
-+  }
-+#endif
-+
-+#ifndef JS_THREADSAFE
-+    rt->gcKind = GC_NOT_RUNNING;
-+#endif
-+}
-+
-+void
-+JSGC::enterExclusiveGC()
-+{
-+#ifdef JS_THREADSAFE
-+    JSThread *thread = js_GetCurrentThread(rt);
-+
-+    JS_ASSERT_IF(thread->pendingGCContext,
-+                 thread->pendingGCContext->thread == thread);
-+    rt->gcThread = thread;
-+#endif
-+
-+    rt->gcPoke = JS_FALSE;
-+
-+    rt->gcContext = PENDING_GC_CONTEXT(thread);
-+    rt->gcKind = PENDING_GC_KIND(thread);
-+}
-+
-+void
-+JSGC::enterExclusiveGCNoLock()
- {
-     JSContext *cx = rt->gcContext;
--
--    /* The mark phase is over. */
--    rt->gcMarkingTracer = NULL;
--
--    if (cx) {
--        /*
--         * We first sweep atom state so we can use js_IsAboutToBeFinalized on
--         * JSString or jsdouble held in a hashtable to check if the hashtable
--         * entry can be freed. Note that even after the entry is freed,
--         * JSObject finalizers can continue to access the corresponding
--         * jsdouble* and JSString* assuming that they are unique. This works
--         * since the atomization API must not be called during GC.
--         */
--        js_SweepAtomState(cx);
--
--        /* Finalize iterator states before the objects they iterate over. */
--        CloseNativeIterators(cx);
--
--        /* Finalize watch points associated with unreachable objects. */
--        js_SweepWatchPoints(cx);
--
--#ifdef DUMP_CALL_TABLE
--        /*
--         * Call js_DumpCallTable here so it can meter and then clear weak refs
--         * to GC-things that are about to be finalized.
--         */
--        js_DumpCallTable(cx);
--#endif
--
-+#ifdef JS_THREADSAFE
-+    JSContext *acx, *iter;
-+#endif
-+
-+    /* Reset malloc counter. */
-+    rt->gcMallocBytes = 0;
-+
-+#ifdef DEBUG_scopemeters
-+  { extern void js_DumpScopeMeters(JSRuntime *rt);
-+    js_DumpScopeMeters(rt);
-+  }
-+#endif
-+
-+#ifdef JS_THREADSAFE
-+    /*
-+     * In case a JSScript wrapped within an object was finalized, we null
-+     * acx->thread->gsnCache.script and finish the cache's hashtable.  Note
-+     * that js_DestroyScript, called from script_finalize, will have already
-+     * cleared cx->thread->gsnCache above during finalization, so we don't
-+     * have to here.
-+     */
-+    iter = NULL;
-+    while ((acx = js_ContextIterator(rt, JS_FALSE, &iter)) != NULL) {
-+        if (!acx->thread || acx->thread == cx->thread)
-+            continue;
-+        GSN_CACHE_CLEAR(&acx->thread->gsnCache);
-+    }
-+#else
-+    /* The thread-unsafe case just has to clear the runtime's GSN cache. */
-+    GSN_CACHE_CLEAR(&rt->gsnCache);
-+#endif
-+
-+    JS_ASSERT(rt->gcUnscannedStack == NULL);
-+
-+    /* CustomMark() methods called from GC::Collect() use this tracer. */
-+    JS_TRACER_INIT(&tracer, cx, NULL);
-+    JS_ASSERT(IS_GC_MARKING_TRACER(&tracer));
-+}
-+
-+void
-+JSGC::leaveExclusiveGC()
-+{
-+    rt->gcKind = GC_NOT_RUNNING;
-+    rt->gcContext = NULL;
-+#ifdef MMGC_THREADSAFE
-+    rt->gcThread = NULL;
-+#endif
-+}
-+
-+void
-+JSGC::postcollect()
-+{
-+#ifdef JS_THREADSAFE
-+    JSThread *thread = js_GetCurrentThread(rt);
-+#endif
-+    JSContext *cx = PENDING_GC_CONTEXT(thread);
-+    JSGCInvocationKind gckind = PENDING_GC_KIND(thread);
-+
-+    /* Execute JSGC_END callback outside the lock. */
-+    if (rt->gcCallback) {
-+        if (gckind == GC_LAST_DITCH) {
-+            JS_KEEP_ATOMS(rt);
-+            JS_UNLOCK_GC(rt);
-+        }
-+
-+        (void) rt->gcCallback(cx, JSGC_END);
-+
-+        if (gckind == GC_LAST_DITCH) {
-+            JS_LOCK_GC(rt);
-+            JS_UNKEEP_ATOMS(rt);
-+        }
-     }
- }
- 
-@@ -704,39 +865,13 @@ js_NewGCThing(JSContext *cx, uintN flags
- js_NewGCThing(JSContext *cx, uintN flags, size_t nbytes)
- {
-     JSRuntime *rt;
--    JSBool doGC;
-     void *thing;
-     JSLocalRootStack *lrs;
- #ifdef JS_THREADSAFE
--    uintN localMallocBytes;
--#endif
--
--    rt = cx->runtime;
--
--#ifdef JS_THREADSAFE
--    JS_LOCK_GC(rt);
--
--    /* Transfer thread-local counter to global one. */
--    localMallocBytes = cx->thread->gcMallocBytes;
--    if (localMallocBytes != 0) {
--        cx->thread->gcMallocBytes = 0;
--        if (rt->gcMaxMallocBytes - rt->gcMallocBytes < localMallocBytes)
--            rt->gcMallocBytes = rt->gcMaxMallocBytes;
--        else
--            rt->gcMallocBytes += localMallocBytes;
--    }
--#endif
--
--    JS_ASSERT(!rt->gc->Collecting());
--    if (rt->gc->Collecting()) {
--        JS_UNLOCK_GC(rt);
--        return NULL;
--    }
--
--    doGC = (rt->gcMallocBytes >= rt->gcMaxMallocBytes && rt->gcPoke);
--#ifdef JS_GC_ZEAL
--    doGC = doGC || rt->gcZeal >= 2 || (rt->gcZeal >= 1 && rt->gcPoke);
--#endif
-+    JSThread *thread;
-+#endif
-+    JSContext *savedGCContext;
-+    JSGCInvocationKind savedGCKind;
- 
-     /*
-      * Since we currently store gcThingFlags for a jsdouble at offset 8,
-@@ -745,39 +880,43 @@ js_NewGCThing(JSContext *cx, uintN flags
-     if ((flags & GCF_TYPEMASK) == GCX_DOUBLE)
-         nbytes++;
- 
--    for (;;) {
--        if (doGC) {
--            /*
--             * Keep rt->gcLock across the call into js_GC so we don't starve
--             * and lose to racing threads who deplete the heap just after
--             * js_GC has replenished it (or has synchronized with a racing
--             * GC that collected a bunch of garbage).  This unfair scheduling
--             * can happen on certain operating systems. For the gory details,
--             * see bug 162779 at https://bugzilla.mozilla.org/.
--             */
--            js_GC(cx, GC_LAST_DITCH);
--        }
--
--        thing = rt->gc->Alloc(nbytes,
--                              gc_type_is_finalized[flags & GCF_TYPEMASK]
--                              ? (MMgc::GC::kZero
--                                 | MMgc::GC::kContainsPointers
--                                 | MMgc::GC::kFinalize)
--                              : 0);
--        if (thing)
--            break;
--
--        /* Consider doing a "last ditch" GC unless already tried. */
--        if (doGC)
--            goto fail;
--        doGC = JS_TRUE;
-+    rt = cx->runtime;
-+#ifdef JS_THREADSAFE
-+    JS_ASSERT(!rt->gc->IsGCRunning());
-+    if (rt->gc->IsGCRunning())
-+        return NULL;
-+
-+    JS_ASSERT(cx->thread == js_GetCurrentThread(rt));
-+    thread = cx->thread;
-+#endif
-+
-+    /* Enter possible GC region. */
-+    savedGCContext = PENDING_GC_CONTEXT(thread);
-+    PENDING_GC_CONTEXT(thread) = cx;
-+    savedGCKind = PENDING_GC_KIND(thread);
-+    PENDING_GC_KIND(thread) = GC_LAST_DITCH;
-+
-+    thing = rt->gc->Alloc(nbytes,
-+                          gc_type_is_finalized[flags & GCF_TYPEMASK]
-+                          ? (MMgc::GC::kZero
-+                             | MMgc::GC::kContainsPointers
-+                             | MMgc::GC::kFinalize)
-+                          : 0);
-+
-+    /* Leave possible GC region. */
-+    PENDING_GC_CONTEXT(thread) = savedGCContext;
-+    PENDING_GC_KIND(thread) = savedGCKind;
-+
-+    if (!thing) {
-+        JS_ReportOutOfMemory(cx);
-+        return NULL;
-     }
- 
-     /*
-      * We successfully allocated the thing.
-      *
-      * Check for local root scope.  See JS_EnterLocalRootScope() and related
--     * APIs.  FIXME - This should be deleted.
-+     * APIs.
-      */
-     lrs = cx->localRootStack;
-     if (lrs)
-@@ -786,18 +925,8 @@ js_NewGCThing(JSContext *cx, uintN flags
-     /* We can't fail now, so update flags. */
-     *GetGCThingFlags(thing) = (uint8)flags;
- 
--#ifdef JS_THREADSAFE
--    JS_UNLOCK_GC(rt);
--#endif
-     JS_COUNT_OPERATION(cx, JSOW_ALLOCATION);
-     return thing;
--
--fail:
--#ifdef JS_THREADSAFE
--    JS_UNLOCK_GC(rt);
--#endif
--    JS_ReportOutOfMemory(cx);
--    return NULL;
- }
- 
- JSBool
-@@ -950,8 +1079,10 @@ JS_CallTracer(JSTracer *trc, void *thing
- 
-     cx = trc->context;
-     rt = cx->runtime;
--    JS_ASSERT(rt->gcMarkingTracer == trc);
--    JS_ASSERT(rt->gcLevel > 0);
-+    JS_ASSERT(rt->gc->GetTracer() == trc);
-+#ifdef JS_THREADSAFE
-+    JS_ASSERT(rt->gc->m_exclusiveGCThread != NULL);
-+#endif
- 
-     /* Optimize for strings as their tracing is not recursive. */
-     if (kind == JSTRACE_STRING) {
-@@ -1268,268 +1399,23 @@ js_TraceRuntime(JSTracer *trc)
-         rt->gcExtraRootsTraceOp(trc, rt->gcExtraRootsData);
- }
- 
--/* Make sure clearing weak roots with 0s gets us null */
--JS_STATIC_ASSERT(JSVAL_NULL == 0);
--
--/*
-- * When gckind is GC_LAST_DITCH, it indicates a call from js_NewGCThing with
-- * rt->gcLock already held and when the lock should be kept on return.
-- */
- void
- js_GC(JSContext *cx, JSGCInvocationKind gckind)
- {
--    JSRuntime *rt;
--    JSTracer trc;
--#ifdef JS_THREADSAFE
--    uint32 requestDebit;
--    JSContext *acx, *iter;
--#endif
--
--    rt = cx->runtime;
--#ifdef JS_THREADSAFE
--    /* Avoid deadlock. */
--    JS_ASSERT(!JS_IS_RUNTIME_LOCKED(rt));
--#endif
--
--    /*
--     * Don't collect garbage if the runtime isn't up, and cx is not the last
--     * context in the runtime.  The last context must force a GC, and nothing
--     * should suppress that final collection or there may be shutdown leaks,
--     * or runtime bloat until the next context is created.
--     */
--    if (rt->state != JSRTS_UP && gckind != GC_LAST_CONTEXT)
--        return;
--
--  restart_after_callback:
--    /*
--     * Let the API user decide to defer a GC if it wants to (unless this
--     * is the last context).  Invoke the callback regardless.
--     */
--    if (rt->gcCallback &&
--        !rt->gcCallback(cx, JSGC_BEGIN) &&
--        gckind != GC_LAST_CONTEXT) {
--        return;
--    }
--
--    /* Lock out other GC allocator and collector invocations. */
--    if (gckind != GC_LAST_DITCH)
--        JS_LOCK_GC(rt);
--
--    rt->gcPoke = JS_FALSE;
--
--#ifdef JS_THREADSAFE
--    JS_ASSERT(cx->thread->id == js_CurrentThreadId());
--
--    /* Bump gcLevel and return rather than nest on this thread. */
--    if (rt->gcThread == cx->thread) {
--        JS_ASSERT(rt->gcLevel > 0);
--        rt->gcLevel++;
--        if (gckind != GC_LAST_DITCH)
--            JS_UNLOCK_GC(rt);
--        return;
--    }
--
--    /*
--     * If we're in one or more requests (possibly on more than one context)
--     * running on the current thread, indicate, temporarily, that all these
--     * requests are inactive.  If cx->thread is NULL, then cx is not using
--     * the request model, and does not contribute to rt->requestCount.
--     */
--    requestDebit = 0;
--    if (cx->thread) {
--        JSCList *head, *link;
--
--        /*
--         * Check all contexts on cx->thread->contextList for active requests,
--         * counting each such context against requestDebit.
--         */
--        head = &cx->thread->contextList;
--        for (link = head->next; link != head; link = link->next) {
--            acx = CX_FROM_THREAD_LINKS(link);
--            JS_ASSERT(acx->thread == cx->thread);
--            if (acx->requestDepth)
--                requestDebit++;
--        }
--    } else {
--        /*
--         * We assert, but check anyway, in case someone is misusing the API.
--         * Avoiding the loop over all of rt's contexts is a win in the event
--         * that the GC runs only on request-less contexts with null threads,
--         * in a special thread such as might be used by the UI/DOM/Layout
--         * "mozilla" or "main" thread in Mozilla-the-browser.
--         */
--        JS_ASSERT(cx->requestDepth == 0);
--        if (cx->requestDepth)
--            requestDebit = 1;
--    }
--    if (requestDebit) {
--        JS_ASSERT(requestDebit <= rt->requestCount);
--        rt->requestCount -= requestDebit;
--        if (rt->requestCount == 0)
--            JS_NOTIFY_REQUEST_DONE(rt);
--    }
--
--    /* If another thread is already in GC, don't attempt GC; wait instead. */
--    if (rt->gcLevel > 0) {
--        /* Bump gcLevel to restart the current GC, so it finds new garbage. */
--        rt->gcLevel++;
--
--        /* Wait for the other thread to finish, then resume our request. */
--        while (rt->gcLevel > 0)
--            JS_AWAIT_GC_DONE(rt);
--        if (requestDebit)
--            rt->requestCount += requestDebit;
--        if (gckind != GC_LAST_DITCH)
--            JS_UNLOCK_GC(rt);
--        return;
--    }
--
--    /* No other thread is in GC, so indicate that we're now in GC. */
--    rt->gcLevel = 1;
--    rt->gcThread = cx->thread;
--
--    /* Wait for all other requests to finish. */
--    while (rt->requestCount > 0)
--        JS_AWAIT_REQUEST_DONE(rt);
--
--#else  /* !JS_THREADSAFE */
--
--    /* Bump gcLevel and return rather than nest; the outer gc will restart. */
--    rt->gcLevel++;
--    if (rt->gcLevel > 1)
--        return;
--
--#endif /* !JS_THREADSAFE */
--
--    /*
--     * Set rt->gcRunning here within the GC lock, and after waiting for any
--     * active requests to end, so that new requests that try to JS_AddRoot,
--     * JS_RemoveRoot, or JS_RemoveRootRT block in JS_BeginRequest waiting for
--     * rt->gcLevel to drop to zero, while request-less calls to the *Root*
--     * APIs block in js_AddRoot or js_RemoveRoot (see above in this file),
--     * waiting for GC to finish.
--     */
--    rt->gcRunning = gckind;
--    rt->gcContext = cx;
--    JS_UNLOCK_GC(rt);
--
--    /* Reset malloc counter. */
--    rt->gcMallocBytes = 0;
--
--#ifdef DEBUG_scopemeters
--  { extern void js_DumpScopeMeters(JSRuntime *rt);
--    js_DumpScopeMeters(rt);
--  }
--#endif
--
--#ifdef JS_THREADSAFE
--    /*
--     * Set all thread local freelists to NULL. We may visit a thread's
--     * freelist more than once. To avoid redundant clearing we unroll the
--     * current thread's step.
--     *
--     * Also, in case a JSScript wrapped within an object was finalized, we
--     * null acx->thread->gsnCache.script and finish the cache's hashtable.
--     * Note that js_DestroyScript, called from script_finalize, will have
--     * already cleared cx->thread->gsnCache above during finalization, so we
--     * don't have to here.
--     */
--    iter = NULL;
--    while ((acx = js_ContextIterator(rt, JS_FALSE, &iter)) != NULL) {
--        if (!acx->thread || acx->thread == cx->thread)
--            continue;
--        GSN_CACHE_CLEAR(&acx->thread->gsnCache);
--    }
--#else
--    /* The thread-unsafe case just has to clear the runtime's GSN cache. */
--    GSN_CACHE_CLEAR(&rt->gsnCache);
--#endif
--
--restart:
--    rt->gcNumber++;
--    JS_ASSERT(rt->gcUnscannedStack == NULL);
--
--    /* CustomMark() methods called from GC::Collect() use this tracer. */
--    JS_TRACER_INIT(&trc, cx, NULL);
--    rt->gcMarkingTracer = &trc;
--    JS_ASSERT(IS_GC_MARKING_TRACER(&trc));
--
--    rt->gc->nogc = false;
--    rt->gc->Collect();
--    rt->gc->nogc = true;
--
--    /*
--     * Sweep the runtime's property tree after finalizing objects, in case any
--     * had watchpoints referencing tree nodes.
--     */
--    js_SweepScopeProperties(cx);
--
--    /*
--     * Sweep script filenames after sweeping functions in the generic loop
--     * above. In this way when a scripted function's finalizer destroys the
--     * script and calls rt->destroyScriptHook, the hook can still access the
--     * script's filename. See bug 323267.
--     */
--    js_SweepScriptFilenames(rt);
--
--    if (rt->gcCallback)
--        (void) rt->gcCallback(cx, JSGC_FINALIZE_END);
--#ifdef DEBUG_srcnotesize
--  { extern void DumpSrcNoteSizeHist();
--    DumpSrcNoteSizeHist();
--  }
--#endif
--
--    JS_LOCK_GC(rt);
--
--    /*
--     * We want to restart GC if js_GC was called recursively or if any of the
--     * finalizers called js_RemoveRoot or js_UnlockGCThingRT.
--     */
--    if (rt->gcLevel > 1 || rt->gcPoke) {
--        rt->gcLevel = 1;
--        rt->gcPoke = JS_FALSE;
--        JS_UNLOCK_GC(rt);
--        goto restart;
--    }
--    rt->gcLevel = 0;
--    rt->gcContext = NULL;
--    rt->gcRunning = GC_NOT_RUNNING;
--
--#ifdef JS_THREADSAFE
--    /* If we were invoked during a request, pay back the temporary debit. */
--    if (requestDebit)
--        rt->requestCount += requestDebit;
--    rt->gcThread = NULL;
--    JS_NOTIFY_GC_DONE(rt);
--
--    /*
--     * Unlock unless we have GC_LAST_DITCH which requires locked GC on return.
--     */
--    if (gckind != GC_LAST_DITCH)
--        JS_UNLOCK_GC(rt);
--#endif
--
--    /* Execute JSGC_END callback outside the lock. */
--    if (rt->gcCallback) {
--        if (gckind == GC_LAST_DITCH) {
--            JS_KEEP_ATOMS(rt);
--            JS_UNLOCK_GC(rt);
--        }
--
--        (void) rt->gcCallback(cx, JSGC_END);
--
--        if (gckind == GC_LAST_DITCH) {
--            JS_LOCK_GC(rt);
--            JS_UNKEEP_ATOMS(rt);
--        } else if (gckind == GC_LAST_CONTEXT && rt->gcPoke) {
--            /*
--             * On shutdown iterate until JSGC_END callback stops creating
--             * garbage.
--             */
--            goto restart_after_callback;
--        }
--    }
-+    JSContext *savedGCContext;
-+    JSGCInvocationKind savedGCKind;
-+
-+    /* Enter GC region. */
-+    savedGCContext = PENDING_GC_CONTEXT(cx->thread);
-+    PENDING_GC_CONTEXT(cx->thread) = cx;
-+    savedGCKind = PENDING_GC_KIND(cx->thread);
-+    PENDING_GC_KIND(cx->thread) = gckind;
-+
-+    cx->runtime->gc->CollectWithBookkeeping(false, THREAD_IS_IN_REQUEST(cx));
-+
-+    /* Leave GC region. */
-+    PENDING_GC_CONTEXT(cx->thread) = savedGCContext;
-+    PENDING_GC_KIND(cx->thread) = savedGCKind;
- }
- 
- void
-@@ -1569,7 +1455,7 @@ JSFinalizedGCThing::MarkAs(uint32 kind)
-     MMgc::GC::SetMark(this);
-     rt = js_GetGCThingRuntime(this);
-     JS_ASSERT(rt);
--    trc = rt->gcMarkingTracer;
-+    trc = rt->gc->GetTracer();
-     JS_ASSERT(trc);
-     JS_ASSERT(IS_GC_MARKING_TRACER(trc));
-     JS_TraceChildren(trc, this, kind);
-@@ -1582,7 +1468,7 @@ JSRuntimeGCMarker::CustomMark()
-     JSTracer *trc;
- 
-     MMgc::GC::SetMark(this);
--    trc = rt->gcMarkingTracer;
-+    trc = rt->gc->GetTracer();
-     JS_ASSERT(trc);
-     JS_ASSERT(IS_GC_MARKING_TRACER(trc));
-     JS_TraceRuntime(trc);
-diff --git a/js/src/jsgc.h b/js/src/jsgc.h
---- a/js/src/jsgc.h
-+++ b/js/src/jsgc.h
-@@ -60,14 +60,44 @@ public:
-     JSRuntime *
-     GetRuntime() { return rt; }
- 
-+    JSTracer *
-+    GetTracer() { return &tracer; }
-+
-+    /* Make some protected members public.  We're all friends here. */
-+    using GC::CollectWithBookkeeping;
-+#ifdef JS_THREADSAFE
-+    using GC::m_lock;
-+    using GC::m_condDone;
-+    using GC::WaitForGCDone;
-+    using GC::m_exclusiveGCThread;
-+    using GC::OnEnterRequestAlreadyLocked;
-+    using GC::OnLeaveRequestAlreadyLocked;
-+#endif
-+
- private:
--    virtual void
--    lastmark(MMgc::GCStack<MMgc::GCWorkItem> &);
--
-+    virtual bool
-+    precollect();
-+
-+    virtual void
-+    postcollect();
-+
-+    virtual void
-+    enterExclusiveGC();
-+
-+    virtual void
-+    enterExclusiveGCNoLock();
-+
-+    virtual void
-+    leaveExclusiveGC();
-+ 
-     virtual void
-     presweep();
--
-+ 
-+    virtual void
-+    postsweep();
-+ 
-     JSRuntime *rt;
-+    JSTracer tracer;
- };
- 
- JS_BEGIN_EXTERN_C
-@@ -261,10 +291,7 @@ typedef enum JSGCInvocationKind {
-     /* Normal invocation. */
-     GC_NORMAL,
- 
--    /*
--     * Called from js_DestroyContext for last JSContext in a JSRuntime, when
--     * it is imperative that rt->gcPoke gets cleared early in js_GC.
--     */
-+    /* Called from js_DestroyContext for last JSContext in a JSRuntime. */
-     GC_LAST_CONTEXT,
- 
-     /*
-@@ -327,9 +354,10 @@ private:
-     JSFinalizedGCThing & operator=(const JSFinalizedGCThing &);
- };
- 
--/* Tracing routines may use this to determine whether to mark all atoms. */
--#define GC_KEEP_ATOMS(rt) ((rt)->gcRunning == GC_LAST_DITCH ||                \
--                           (rt)->gcKeepAtoms != 0)
-+/* Tracing routines may use this to determine whether to mark all atoms.
-+ * Implicit collections (GC_LAST_DITCH) always keep all atoms.
-+ */
-+#define GC_KEEP_ATOMS(rt) ((rt)->gcKeepAtoms != 0)
- 
- JS_END_EXTERN_C
- 
-diff --git a/js/src/jslock.cpp b/js/src/jslock.cpp
---- a/js/src/jslock.cpp
-+++ b/js/src/jslock.cpp
-@@ -292,7 +292,7 @@ js_unlog_scope(JSScope *scope)
-  * That condition implies deadlock in ClaimScope if cx's thread were to wait
-  * to share scope.
-  *
-- * (i) rt->gcLock held
-+ * (i) rt->gc->m_lock held
-  */
- static JSBool
- WillDeadlock(JSScope *scope, JSContext *cx)
-@@ -316,7 +316,7 @@ WillDeadlock(JSScope *scope, JSContext *
-  * for scope's lock, because its ownercx is waiting on a scope owned by the
-  * calling cx.
-  *
-- * (i) rt->gcLock held
-+ * (i) rt->gc->m_lock held
-  */
- static void
- ShareScope(JSContext *cx, JSScope *scope)
-@@ -332,7 +332,7 @@ ShareScope(JSContext *cx, JSScope *scope
-         }
-         *todop = scope->u.link;
-         scope->u.link = NULL;       /* null u.link for sanity ASAP */
--        JS_NOTIFY_ALL_CONDVAR(rt->scopeSharingDone);
-+        rt->scopeSharingDone->NotifyAll();
-     }
-     js_InitLock(&scope->lock);
-     if (scope == rt->setSlotScope) {
-@@ -343,13 +343,13 @@ ShareScope(JSContext *cx, JSScope *scope
-          * non-null).  See below in ClaimScope, before the ShareScope call,
-          * for more on why this is necessary.
-          *
--         * If NSPR_LOCK is defined, we cannot deadlock holding rt->gcLock and
--         * acquiring scope->lock.fat here, against another thread holding that
--         * fat lock and trying to grab rt->gcLock.  This is because no other
--         * thread can attempt to acquire scope->lock.fat until scope->ownercx
--         * is null *and* our thread has released rt->gcLock, which interlocks
--         * scope->ownercx's transition to null against tests of that member
--         * in ClaimScope.
-+         * If NSPR_LOCK is defined, we cannot deadlock holding rt->gc->m_lock
-+         * and acquiring scope->lock.fat here, against another thread holding
-+         * that fat lock and trying to grab rt->gc->m_lock.  This is because
-+         * no other thread can attempt to acquire scope->lock.fat until
-+         * scope->ownercx is null *and* our thread has released
-+         * rt->gc->m_lock, which interlocks scope->ownercx's transition to
-+         * null against tests of that member in ClaimScope.
-          */
-         scope->lock.owner = CX_THINLOCK_ID(scope->ownercx);
- #ifdef NSPR_LOCK
-@@ -416,7 +416,6 @@ ClaimScope(JSScope *scope, JSContext *cx
-     JSRuntime *rt;
-     JSContext *ownercx;
-     jsrefcount saveDepth;
--    PRStatus stat;
- 
-     rt = cx->runtime;
-     JS_RUNTIME_METER(rt, claimAttempts);
-@@ -501,18 +500,18 @@ ClaimScope(JSScope *scope, JSContext *cx
-          * GC needs to run on ownercx.
-          *
-          * Unlike JS_SuspendRequest and JS_EndRequest, we must take care not
--         * to decrement rt->requestCount if cx is active on the GC's thread,
--         * because the GC has already reduced rt->requestCount to exclude all
--         * such such contexts.
-+         * to call rt->gc->OnLeaveRequest if cx is active on the GC's thread,
-+         * because the GC has already reduced cx->thread->requestCount to 0,
-+         * to exclude all such such contexts.
-          */
-         saveDepth = cx->requestDepth;
-         if (saveDepth) {
-             cx->requestDepth = 0;
-             if (rt->gcThread != cx->thread) {
--                JS_ASSERT(rt->requestCount > 0);
--                rt->requestCount--;
--                if (rt->requestCount == 0)
--                    JS_NOTIFY_REQUEST_DONE(rt);
-+                JS_ASSERT(cx->thread->requestCount > 0);
-+                cx->thread->requestCount--;
-+                if (cx->thread->requestCount == 0)
-+                    rt->gc->OnLeaveRequestAlreadyLocked();
-             }
-         }
- 
-@@ -522,8 +521,7 @@ ClaimScope(JSScope *scope, JSContext *cx
-          * thread's request.  So it is safe to wait on rt->scopeSharingDone.
-          */
-         cx->scopeToShare = scope;
--        stat = PR_WaitCondVar(rt->scopeSharingDone, PR_INTERVAL_NO_TIMEOUT);
--        JS_ASSERT(stat != PR_FAILURE);
-+        rt->scopeSharingDone->Wait();
- 
-         /*
-          * Inline JS_ResumeRequest after waiting on rt->scopeSharingDone,
-@@ -531,19 +529,22 @@ ClaimScope(JSScope *scope, JSContext *cx
-          * specialized JS_SuspendRequest code: beware rt->gcThread.
-          */
-         if (saveDepth) {
-+            if (rt->gcThread != cx->thread)
-+                rt->gc->WaitForGCDone();
-+            cx->requestDepth = saveDepth;
-             if (rt->gcThread != cx->thread) {
--                while (rt->gcLevel > 0)
--                    JS_AWAIT_GC_DONE(rt);
--                rt->requestCount++;
-+                cx->thread->requestCount++;
-+                if (cx->thread->requestCount == 1)
-+                    rt->gc->OnEnterRequestAlreadyLocked();
-             }
--            cx->requestDepth = saveDepth;
-         }
- 
-         /*
-          * Don't clear cx->scopeToShare until after we're through waiting on
--         * all condition variables protected by rt->gcLock -- that includes
--         * rt->scopeSharingDone *and* rt->gcDone (hidden in JS_AWAIT_GC_DONE,
--         * in the inlined JS_ResumeRequest code immediately above).
-+         * all condition variables protected by rt->gc->m_lock -- that
-+         * includes rt->scopeSharingDone *and* rt->gc->m_condDone (hidden in
-+         * rt->gc->WaitForGCDone(), in the inlined JS_ResumeRequest code
-+         * immediately above).
-          *
-          * Otherwise, the GC could easily deadlock with another thread that
-          * owns a scope wanted by a finalizer.  By keeping cx->scopeToShare
-diff --git a/js/src/jslock.h b/js/src/jslock.h
---- a/js/src/jslock.h
-+++ b/js/src/jslock.h
-@@ -103,6 +103,9 @@ typedef struct JSFatLockTable {
- #define JS_NO_TIMEOUT               PR_INTERVAL_NO_TIMEOUT
- #define JS_NOTIFY_CONDVAR(cv)       PR_NotifyCondVar(cv)
- #define JS_NOTIFY_ALL_CONDVAR(cv)   PR_NotifyAllCondVar(cv)
-+
-+#define JS_WAIT_GCCONDITION(cv)     ((cv)->Wait())
-+#define JS_NOTIFY_ALL_GCCONDITION(cv) ((cv)->NotifyAll())
- 
- /*
-  * Include jsscope.h so JS_LOCK_OBJ macro callers don't have to include it.
-@@ -212,6 +215,9 @@ extern JS_INLINE void js_Unlock(JSThinLo
- 
- #endif /* arch-tests */
- 
-+#define JS_LOCK_GC(rt)              ((rt)->gc->m_lock.Acquire())
-+#define JS_UNLOCK_GC(rt)            ((rt)->gc->m_lock.Release())
-+
- #else  /* !JS_THREADSAFE */
- 
- JS_BEGIN_EXTERN_C
-@@ -233,6 +239,9 @@ JS_BEGIN_EXTERN_C
- #define JS_WAIT_CONDVAR(cv,to)      ((void)0)
- #define JS_NOTIFY_CONDVAR(cv)       ((void)0)
- #define JS_NOTIFY_ALL_CONDVAR(cv)   ((void)0)
-+
-+#define JS_WAIT_GCCONDITION(cv)     ((void)0)
-+#define JS_NOTIFY_ALL_GCCONDITION(cv) ((void)0)
- 
- #define JS_LOCK_RUNTIME(rt)         ((void)0)
- #define JS_UNLOCK_RUNTIME(rt)       ((void)0)
-@@ -248,6 +257,9 @@ JS_BEGIN_EXTERN_C
- #define JS_IS_SCOPE_LOCKED(cx,scope)    1
- #define JS_LOCK_VOID(cx, e)             JS_LOCK_RUNTIME_VOID((cx)->runtime, e)
- 
-+#define JS_LOCK_GC(rt)              ((void) 0)
-+#define JS_UNLOCK_GC(rt)            ((void) 0)
-+
- #endif /* !JS_THREADSAFE */
- 
- #define JS_LOCK_RUNTIME_VOID(rt,e)                                            \
-@@ -257,14 +269,7 @@ JS_BEGIN_EXTERN_C
-         JS_UNLOCK_RUNTIME(rt);                                                \
-     JS_END_MACRO
- 
--#define JS_LOCK_GC(rt)              JS_ACQUIRE_LOCK((rt)->gcLock)
--#define JS_UNLOCK_GC(rt)            JS_RELEASE_LOCK((rt)->gcLock)
- #define JS_LOCK_GC_VOID(rt,e)       (JS_LOCK_GC(rt), (e), JS_UNLOCK_GC(rt))
--#define JS_AWAIT_GC_DONE(rt)        JS_WAIT_CONDVAR((rt)->gcDone, JS_NO_TIMEOUT)
--#define JS_NOTIFY_GC_DONE(rt)       JS_NOTIFY_ALL_CONDVAR((rt)->gcDone)
--#define JS_AWAIT_REQUEST_DONE(rt)   JS_WAIT_CONDVAR((rt)->requestDone,        \
--                                                    JS_NO_TIMEOUT)
--#define JS_NOTIFY_REQUEST_DONE(rt)  JS_NOTIFY_CONDVAR((rt)->requestDone)
- 
- #define JS_LOCK(P,CX)               JS_LOCK0(P, CX_THINLOCK_ID(CX))
- #define JS_UNLOCK(P,CX)             JS_UNLOCK0(P, CX_THINLOCK_ID(CX))
-diff --git a/js/src/jsobj.cpp b/js/src/jsobj.cpp
---- a/js/src/jsobj.cpp
-+++ b/js/src/jsobj.cpp
-@@ -307,7 +307,10 @@ js_SetProtoOrParent(JSContext *cx, JSObj
-     while (rt->setSlotBusy) {
-         jsrefcount saveDepth;
- 
--        /* Take pains to avoid nesting rt->gcLock inside rt->setSlotLock! */
-+        /*
-+         * Take pains to avoid nesting rt->gc->m_lock inside
-+         * rt->setSlotLock!
-+         */
-         JS_RELEASE_LOCK(rt->setSlotLock);
-         saveDepth = JS_SuspendRequest(cx);
-         JS_ACQUIRE_LOCK(rt->setSlotLock);
-diff --git a/js/src/jsobj.h b/js/src/jsobj.h
---- a/js/src/jsobj.h
-+++ b/js/src/jsobj.h
-@@ -238,10 +238,10 @@ struct JSObject : public JSFinalizedGCTh
-  *
-  * The GC runs only when all threads except the one on which the GC is active
-  * are suspended at GC-safe points, so calling STOBJ_GET_SLOT from the GC's
-- * thread is safe when rt->gcRunning is set. See jsgc.c for details.
-+ * thread is safe when (rt)->gc->IsGCRunning(). See MMgc/GC.h for details.
-  */
- #define THREAD_IS_RUNNING_GC(rt, thread)                                      \
--    ((rt)->gcRunning && (rt)->gcThread == (thread))
-+    ((rt)->gc->IsGCRunning() && (rt)->gcThread == (thread))
- 
- #define CX_THREAD_IS_RUNNING_GC(cx)                                           \
-     THREAD_IS_RUNNING_GC((cx)->runtime, (cx)->thread)
-diff --git a/js/src/jspubtd.h b/js/src/jspubtd.h
---- a/js/src/jspubtd.h
-+++ b/js/src/jspubtd.h
-@@ -739,6 +739,16 @@ typedef intN
- typedef intN
- (* JS_DLL_CALLBACK JSGCRootMapFun)(void *rp, const char *name, void *data);
- 
-+struct JSTracer {
-+    JSContext           *context;
-+    JSTraceCallback     callback;
-+#ifdef DEBUG
-+    JSTraceNamePrinter  debugPrinter;
-+    const void          *debugPrintArg;
-+    size_t              debugPrintIndex;
-+#endif
-+};
-+
- JS_END_EXTERN_C
- 
- #endif /* jspubtd_h___ */
-diff --git a/js/src/xpconnect/src/nsXPConnect.cpp b/js/src/xpconnect/src/nsXPConnect.cpp
---- a/js/src/xpconnect/src/nsXPConnect.cpp
-+++ b/js/src/xpconnect/src/nsXPConnect.cpp
-@@ -438,7 +438,7 @@ XPCCycleCollectGCCallback(JSContext *cx,
-         // Mark JS objects that are held by XPCOM objects that are in cycles
-         // that will not be collected.
-         nsXPConnect::GetRuntime()->
--            TraceXPConnectRoots(cx->runtime->gcMarkingTracer);
-+            TraceXPConnectRoots(cx->runtime->gc->GetTracer());
-     }
-     else if(status == JSGC_END)
-         nsXPConnect::GetRuntime()->RestoreContextGlobals();
deleted file mode 100644
--- a/jstrace-function
+++ /dev/null
@@ -1,29 +0,0 @@
-diff --git a/js/src/jsfun.cpp b/js/src/jsfun.cpp
---- a/js/src/jsfun.cpp
-+++ b/js/src/jsfun.cpp
-@@ -2033,6 +2033,13 @@ JSFunction::~JSFunction()
-     }
- }
- 
-+bool
-+JSFunction::CustomMark()
-+{
-+    MarkAs(JSTRACE_FUNCTION);
-+    return true;
-+}
-+
- JSObject *
- js_CloneFunctionObject(JSContext *cx, JSObject *funobj, JSObject *parent)
- {
-diff --git a/js/src/jsfun.h b/js/src/jsfun.h
---- a/js/src/jsfun.h
-+++ b/js/src/jsfun.h
-@@ -65,6 +65,8 @@ typedef union JSLocalNames {
- 
- struct JSFunction : public JSFinalizedGCThing {
-     virtual ~JSFunction();
-+
-+    virtual bool CustomMark();
- 
-     JSObject        *object;    /* back-pointer to GC'ed object header */
-     uint16          nargs;      /* maximum number of specified arguments,
deleted file mode 100644
--- a/maybegc
+++ /dev/null
@@ -1,19 +0,0 @@
-diff --git a/js/src/jsapi.cpp b/js/src/jsapi.cpp
---- a/js/src/jsapi.cpp
-+++ b/js/src/jsapi.cpp
-@@ -2388,14 +2388,7 @@ JS_PUBLIC_API(void)
- JS_PUBLIC_API(void)
- JS_MaybeGC(JSContext *cx)
- {
--#ifdef JS_GC_ZEAL
--    if (cx->runtime->gc->greedy) {
--        js_GC(cx, GC_NORMAL);
--        return;
--    }
--#endif
--
--    /* FIXME bug 392602 - Find new heuristic to determine when to GC. */
-+    cx->runtime->gc->MaybeGC(THREAD_IS_IN_REQUEST(cx));
- }
- 
- JS_PUBLIC_API(JSGCCallback)
--- a/necko-deadlocks
+++ b/necko-deadlocks
@@ -124,19 +124,20 @@ diff --git a/netwerk/base/src/nsIOServic
      if (NS_FAILED(rv)) return rv;
  
      return handler->NewURI(aSpec, aCharset, aBaseURI, result);
 @@ -507,12 +504,12 @@ nsIOService::NewFileURI(nsIFile *file, n
      nsresult rv;
      NS_ENSURE_ARG_POINTER(file);
  
 -    nsCOMPtr<nsIProtocolHandler> handler;
+-
+-    rv = GetProtocolHandler("file", getter_AddRefs(handler));
 +    nsIProtocolHandler* handler = nsnull;
- 
--    rv = GetProtocolHandler("file", getter_AddRefs(handler));
++
 +    rv = GetProtocolHandler("file", &handler);
      if (NS_FAILED(rv)) return rv;
  
 -    nsCOMPtr<nsIFileProtocolHandler> fileHandler( do_QueryInterface(handler, &rv) );
 +    nsIFileProtocolHandler* fileHandler( do_QueryInterface(handler, &rv) );
      if (NS_FAILED(rv)) return rv;
      
      return fileHandler->NewFileURI(file, result);
@@ -871,25 +872,27 @@ diff --git a/netwerk/cache/src/nsCacheRe
      }
      
      ~nsCacheRequest()
 @@ -83,12 +84,13 @@ private:
          delete mKey;
          if (mLock)    PR_DestroyLock(mLock);
          if (mCondVar) PR_DestroyCondVar(mCondVar);
 -        NS_ASSERTION(PR_CLIST_IS_EMPTY(this), "request still on a list");
-+    }
- 
+-
 -        if (mListener)
 -            nsCacheService::ReleaseObject_Locked(mListener, mThread);
+-    }
+-    
++    }
++
 +    static void operator delete(void *obj)
 +    {
 +        NS_GetGC()->Free(obj);
-     }
--    
++    }
 +
      /**
       * Simple Accessors
       */
 diff --git a/netwerk/cache/src/nsCacheService.cpp b/netwerk/cache/src/nsCacheService.cpp
 --- a/netwerk/cache/src/nsCacheService.cpp
 +++ b/netwerk/cache/src/nsCacheService.cpp
 @@ -92,7 +92,7 @@
@@ -1194,111 +1197,112 @@ diff --git a/netwerk/cache/src/nsDeleteD
   */
 -NS_HIDDEN_(nsresult) GetTrashDir(nsIFile *dir, nsCOMPtr<nsIFile> *result);
 +NS_HIDDEN_(nsresult) GetTrashDir(nsIFile *dir, nsIFile **result);
  
  #endif  // nsDeleteDir_h__
 diff --git a/netwerk/cache/src/nsDiskCacheDevice.cpp b/netwerk/cache/src/nsDiskCacheDevice.cpp
 --- a/netwerk/cache/src/nsDiskCacheDevice.cpp
 +++ b/netwerk/cache/src/nsDiskCacheDevice.cpp
-@@ -158,7 +158,7 @@ nsDiskCacheEvictor::VisitRecord(nsDiskCa
+@@ -155,7 +155,7 @@ nsDiskCacheEvictor::VisitRecord(nsDiskCa
   *  nsDiskCacheDeviceInfo
   *****************************************************************************/
  
 -class nsDiskCacheDeviceInfo : public nsICacheDeviceInfo {
 +class nsDiskCacheDeviceInfo : public XPCOMGCFinalizedObject, public nsICacheDeviceInfo {
  public:
      NS_DECL_ISUPPORTS
      NS_DECL_NSICACHEDEVICEINFO
-@@ -191,9 +191,9 @@ NS_IMETHODIMP nsDiskCacheDeviceInfo::Get
+@@ -188,9 +188,9 @@ NS_IMETHODIMP nsDiskCacheDeviceInfo::Get
      nsCString buffer;
      
      buffer.AssignLiteral("\n<tr>\n<td><b>Cache Directory:</b></td>\n<td><tt> ");
 -    nsCOMPtr<nsILocalFile> cacheDir;
 +    nsILocalFile* cacheDir = nsnull;
      nsAutoString           path;
 -    mDevice->getCacheDirectory(getter_AddRefs(cacheDir)); 
 +    mDevice->getCacheDirectory(&cacheDir); 
      nsresult rv = cacheDir->GetPath(path);
      if (NS_SUCCEEDED(rv)) {
          AppendUTF16toUTF8(path, buffer);
-@@ -345,7 +345,7 @@ nsDiskCacheDevice::Shutdown()
+@@ -342,7 +342,7 @@ nsDiskCacheDevice::Shutdown()
  
      if (mCacheDirectory) {
          // delete any trash files left-over before shutting down.
 -        nsCOMPtr<nsIFile> trashDir;
 +        nsIFile* trashDir = nsnull;
          GetTrashDir(mCacheDirectory, &trashDir);
          if (trashDir) {
              PRBool exists;
-@@ -473,7 +473,6 @@ nsDiskCacheDevice::DeactivateEntry(nsCac
+@@ -465,7 +465,6 @@ nsDiskCacheDevice::DeactivateEntry(nsCac
      }
  
      mBindery.RemoveBinding(binding); // extract binding from collision detection stuff
 -    delete entry;   // which will release binding
      return rv;
  }
  
-@@ -654,13 +653,13 @@ nsDiskCacheDevice::GetFileForEntry(nsCac
+@@ -646,13 +645,13 @@ nsDiskCacheDevice::GetFileForEntry(nsCac
          }
      }
      
 -    nsCOMPtr<nsIFile>  file;
 +    nsIFile*  file = nsnull;
      rv = mCacheMap.GetFileForDiskCacheRecord(&binding->mRecord,
                                               nsDiskCache::kData,
 -                                             getter_AddRefs(file));
 +                                             &file);
      if (NS_FAILED(rv))  return rv;
      
 -    NS_IF_ADDREF(*result = file);
 +    *result = file;
      return NS_OK;
  }
  
-@@ -740,7 +739,7 @@ public:
+@@ -731,7 +730,7 @@ public:
          if (!entryInfo) {
              return kStopVisitingRecords;
          }
 -        nsCOMPtr<nsICacheEntryInfo> ref(entryInfo);
 +        nsICacheEntryInfo* ref(entryInfo);
          
          PRBool  keepGoing;
-         rv = mVisitor->VisitEntry(DISK_CACHE_DEVICE_ID, entryInfo, &keepGoing);
-@@ -759,7 +758,7 @@ nsDiskCacheDevice::Visit(nsICacheVisitor
+         (void)mVisitor->VisitEntry(DISK_CACHE_DEVICE_ID, entryInfo, &keepGoing);
+@@ -749,7 +748,7 @@ nsDiskCacheDevice::Visit(nsICacheVisitor
  {
      if (!Initialized())  return NS_ERROR_NOT_INITIALIZED;
      nsDiskCacheDeviceInfo* deviceInfo = new nsDiskCacheDeviceInfo(this);
 -    nsCOMPtr<nsICacheDeviceInfo> ref(deviceInfo);
 +    nsICacheDeviceInfo* ref(deviceInfo);
      
      PRBool keepGoing;
      nsresult rv = visitor->VisitDevice(DISK_CACHE_DEVICE_ID, deviceInfo, &keepGoing);
-@@ -843,7 +842,7 @@ nsDiskCacheDevice::OpenDiskCache()
+@@ -833,7 +832,7 @@ nsDiskCacheDevice::OpenDiskCache()
  
      if (!trashing) {
          // delete any trash files leftover from a previous run
 -        nsCOMPtr<nsIFile> trashDir;
 +        nsIFile* trashDir = nsnull;
          GetTrashDir(mCacheDirectory, &trashDir);
          if (trashDir) {
              PRBool exists;
-@@ -920,9 +919,9 @@ nsDiskCacheDevice::SetCacheParentDirecto
+@@ -910,9 +909,9 @@ nsDiskCacheDevice::SetCacheParentDirecto
      if (NS_FAILED(rv))  return;
  
      // ensure cache directory exists
 -    nsCOMPtr<nsIFile> directory;
+-    
+-    rv = parentDir->Clone(getter_AddRefs(directory));
 +    nsIFile* directory = nsnull;
-     
--    rv = parentDir->Clone(getter_AddRefs(directory));
++    
 +    rv = parentDir->Clone(&directory);
      if (NS_FAILED(rv))  return;
      rv = directory->AppendNative(NS_LITERAL_CSTRING("Cache"));
      if (NS_FAILED(rv))  return;
-@@ -935,7 +934,6 @@ nsDiskCacheDevice::getCacheDirectory(nsI
+@@ -925,7 +924,6 @@ nsDiskCacheDevice::getCacheDirectory(nsI
  nsDiskCacheDevice::getCacheDirectory(nsILocalFile ** result)
  {
      *result = mCacheDirectory;
 -    NS_IF_ADDREF(*result);
  }
  
  
 diff --git a/netwerk/cache/src/nsDiskCacheStreams.cpp b/netwerk/cache/src/nsDiskCacheStreams.cpp
@@ -1559,43 +1563,46 @@ diff --git a/netwerk/dns/src/nsDNSServic
 -    PRMonitor *mon = PR_NewMonitor();
 +
 +    PRMonitor *mon = nsAutoMonitor::NewMonitor("nsDNSMonitor");
      if (!mon)
          return NS_ERROR_OUT_OF_MEMORY;
  
 -    PR_EnterMonitor(mon);
 -    nsDNSSyncRequest syncReq(mon);
-+    {
-+        nsAutoMonitor automon(mon);
-+        nsDNSSyncRequest syncReq(mon);
- 
+-
 -    PRUint16 af = GetAFForLookup(*hostPtr);
-+        PRUint16 af = GetAFForLookup(*hostPtr);
- 
+-
 -    rv = res->ResolveHost(PromiseFlatCString(*hostPtr).get(), flags, af, &syncReq);
 -    if (NS_SUCCEEDED(rv)) {
 -        // wait for result
 -        while (!syncReq.mDone)
 -            PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT);
-+        rv = res->ResolveHost(PromiseFlatCString(*hostPtr).get(), flags, af, &syncReq);
-+        if (NS_SUCCEEDED(rv)) {
-+            // wait for result
-+            while (!syncReq.mDone)
-+                automon.Wait(PR_INTERVAL_NO_TIMEOUT);
- 
+-
 -        if (NS_FAILED(syncReq.mStatus))
 -            rv = syncReq.mStatus;
 -        else {
 -            NS_ASSERTION(syncReq.mHostRecord, "no host record");
 -            nsDNSRecord *rec = new nsDNSRecord(syncReq.mHostRecord);
 -            if (!rec)
 -                rv = NS_ERROR_OUT_OF_MEMORY;
 -            else
 -                NS_ADDREF(*result = rec);
++    {
++        nsAutoMonitor automon(mon);
++        nsDNSSyncRequest syncReq(mon);
++
++        PRUint16 af = GetAFForLookup(*hostPtr);
++
++        rv = res->ResolveHost(PromiseFlatCString(*hostPtr).get(), flags, af, &syncReq);
++        if (NS_SUCCEEDED(rv)) {
++            // wait for result
++            while (!syncReq.mDone)
++                automon.Wait(PR_INTERVAL_NO_TIMEOUT);
++
 +            if (NS_FAILED(syncReq.mStatus))
 +                rv = syncReq.mStatus;
 +            else {
 +                NS_ASSERTION(syncReq.mHostRecord, "no host record");
 +                nsDNSRecord *rec = new nsDNSRecord(syncReq.mHostRecord);
 +                if (!rec)
 +                    rv = NS_ERROR_OUT_OF_MEMORY;
 +                else
@@ -1731,53 +1738,58 @@ diff --git a/netwerk/protocol/http/src/n
 @@ -250,14 +249,11 @@ nsHttpAuthCache::FreeEntry(void *self, P
          NS_NOTREACHED("should never happen");
      }
      else if (flag == HT_FREE_ENTRY) {
 -        // three wonderful flavors of freeing memory ;-)
 -        delete (nsHttpAuthNode *) he->value;
          nsCRT::free((char *) he->key);
 -        free(he);
-     }
- }
- 
+-    }
+-}
+-
 -PLHashAllocOps nsHttpAuthCache::gHashAllocOps =
++    }
++}
++
 +const PLHashAllocOps nsHttpAuthCache::gHashAllocOps =
  {
      nsHttpAuthCache::AllocTable,
      nsHttpAuthCache::FreeTable,
-@@ -444,21 +440,6 @@ nsHttpAuthEntry::Set(const char *path,
+@@ -443,21 +439,6 @@ nsHttpAuthEntry::Set(const char *path,
+ //-----------------------------------------------------------------------------
  // nsHttpAuthNode
  //-----------------------------------------------------------------------------
- 
+-
 -nsHttpAuthNode::nsHttpAuthNode()
 -{
 -    LOG(("Creating nsHttpAuthNode @%x\n", this));
 -}
 -
 -nsHttpAuthNode::~nsHttpAuthNode()
 -{
 -    LOG(("Destroying nsHttpAuthNode @%x\n", this));
 -
 -    PRInt32 i;
 -    for (i=0; i<mList.Count(); ++i)
 -        delete (nsHttpAuthEntry *) mList[i];
 -    mList.Clear();
 -}
--
+ 
  nsHttpAuthEntry *
  nsHttpAuthNode::LookupEntryByPath(const char *path)
- {
 @@ -540,6 +521,5 @@ nsHttpAuthNode::ClearAuthEntry(const cha
      nsHttpAuthEntry *entry = LookupEntryByRealm(realm);
      if (entry) {
          mList.RemoveElement(entry); // double search OK
 -        delete entry;
-     }
- }
+-    }
+-}
++    }
++}
 diff --git a/netwerk/protocol/http/src/nsHttpAuthCache.h b/netwerk/protocol/http/src/nsHttpAuthCache.h
 --- a/netwerk/protocol/http/src/nsHttpAuthCache.h
 +++ b/netwerk/protocol/http/src/nsHttpAuthCache.h
 @@ -104,7 +104,7 @@ private:
  // nsHttpAuthEntry
  //-----------------------------------------------------------------------------
  
 -class nsHttpAuthEntry
@@ -1785,21 +1797,23 @@ diff --git a/netwerk/protocol/http/src/n
  {
  public:
      const char *Realm()       const { return mRealm; }
 @@ -161,11 +161,10 @@ private:
  // nsHttpAuthNode
  //-----------------------------------------------------------------------------
  
 -class nsHttpAuthNode
-+class nsHttpAuthNode : public XPCOMGCObject
- {
- private:
+-{
+-private:
 -    nsHttpAuthNode();
 -   ~nsHttpAuthNode();
++class nsHttpAuthNode : public XPCOMGCObject
++{
++private:
 +    nsHttpAuthNode() { }
  
      // path can be null, in which case we'll search for an entry
      // with a null path.
 @@ -187,7 +186,7 @@ private:
      PRUint32 EntryCount() { return (PRUint32) mList.Count(); }
  
  private:
@@ -1891,49 +1905,49 @@ diff --git a/netwerk/protocol/http/src/n
 +    }
 +
      nsCString              mHashKey;
      nsCString              mHost;
      PRInt32                mPort;
 diff --git a/netwerk/protocol/http/src/nsHttpConnectionMgr.h b/netwerk/protocol/http/src/nsHttpConnectionMgr.h
 --- a/netwerk/protocol/http/src/nsHttpConnectionMgr.h
 +++ b/netwerk/protocol/http/src/nsHttpConnectionMgr.h
-@@ -86,16 +86,6 @@ public:
-     //-------------------------------------------------------------------------
+@@ -87,16 +87,6 @@ public:
      // NOTE: functions below may be called on any thread.
      //-------------------------------------------------------------------------
--
+ 
 -    void AddRef()
 -    {
 -	NS_WARNING("Don't call me");
 -    }
 -
 -    void Release()
 -    {
 -	NS_WARNING("Don't call me");
 -    }
- 
+-
      // adds a transaction to the list of managed transactions.
      nsresult AddTransaction(nsHttpTransaction *, PRInt32 priority);
+ 
 diff --git a/netwerk/protocol/http/src/nsHttpHandler.cpp b/netwerk/protocol/http/src/nsHttpHandler.cpp
 --- a/netwerk/protocol/http/src/nsHttpHandler.cpp
 +++ b/netwerk/protocol/http/src/nsHttpHandler.cpp
-@@ -192,12 +192,6 @@ nsHttpHandler::~nsHttpHandler()
-     // it is taken care of in xpcom shutdown event in the Observe method.
+@@ -193,12 +193,6 @@ nsHttpHandler::~nsHttpHandler()
  
      LOG(("Deleting nsHttpHandler [this=%x]\n", this));
--
+ 
 -    // make sure the connection manager is shutdown
 -    if (mConnMgr) {
 -        mConnMgr->Shutdown();
 -        NS_RELEASE(mConnMgr);
 -    }
- 
+-
      nsHttp::DestroyAtomTable();
  
+     gHttpHandler = nsnull;
 diff --git a/netwerk/test/httpserver/Makefile.in b/netwerk/test/httpserver/Makefile.in
 --- a/netwerk/test/httpserver/Makefile.in
 +++ b/netwerk/test/httpserver/Makefile.in
 @@ -43,7 +43,7 @@ VPATH		= @srcdir@
  
  include $(DEPTH)/config/autoconf.mk
  
 -MODULE          = test_necko
--- a/no-attributes-configure-check
+++ b/no-attributes-configure-check
@@ -1,23 +1,21 @@
 diff --git a/configure.in b/configure.in
 --- a/configure.in
 +++ b/configure.in
-@@ -1255,7 +1255,18 @@ if test "$GNU_CC"; then
-     # -Wbad-function-cast - warns when casting a function to a new return type
-     # -Wconversion - complained when char's or short's were used a function args
-     # -Wshadow - removed because it generates more noise than help --pete
--    _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wall -W -Wno-unused -Wpointer-arith -Wcast-align -Wno-attributes"
-+    _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wall -W -Wno-unused -Wpointer-arith -Wcast-align"
+@@ -1259,6 +1259,17 @@ if test "$GNU_CC"; then
+     if test "$CPU_ARCH" != "ia64"; then
+         # only use -Wcast-align for non-ia64, it's noisy on that platform
+         _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wcast-align"
++    fi
 +
 +    _SAVE_CFLAGS=$CFLAGS
 +    CFLAGS="$CFLAGS -Wno-attributes"
 +    AC_TRY_COMPILE([$no_attributes_flag],
 +                   [void test();],
 +                   ac_cv_no_attributes_flag="yes",
 +                   ac_cv_no_attributes_flag="no")
 +    CFLAGS=$_SAVE_CFLAGS
 +    if test "$ac_cv_no_attributes_flag" = "yes"; then
 +        _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wno-attributes"
-+    fi
+     fi
  
      dnl Turn pedantic on but disable the warnings for long long
-     _PEDANTIC=1
--- a/nsAttrAndChildArray
+++ b/nsAttrAndChildArray
@@ -1,67 +1,47 @@
 diff --git a/content/base/src/nsAttrAndChildArray.cpp b/content/base/src/nsAttrAndChildArray.cpp
 --- a/content/base/src/nsAttrAndChildArray.cpp
 +++ b/content/base/src/nsAttrAndChildArray.cpp
-@@ -119,22 +119,6 @@ GetIndexFromCache(const nsAttrAndChildAr
+@@ -118,18 +118,6 @@ GetIndexFromCache(const nsAttrAndChildAr
+ 
  #define NS_IMPL_EXTRA_SIZE \
    ((sizeof(Impl) - sizeof(mImpl->mBuffer)) / sizeof(void*))
- 
+-
 -nsAttrAndChildArray::nsAttrAndChildArray()
 -  : mImpl(nsnull)
 -{
 -}
 -
 -nsAttrAndChildArray::~nsAttrAndChildArray()
 -{
--  if (!mImpl) {
--    return;
+-  if (mImpl) {
+-    Clear();
 -  }
--
--  Clear();
--
--  PR_Free(mImpl);
 -}
--
+ 
  nsIContent*
  nsAttrAndChildArray::GetSafeChildAt(PRUint32 aPos) const
- {
-@@ -612,14 +596,11 @@ nsAttrAndChildArray::Compact()
-   // Then resize or free buffer
-   PRUint32 newSize = attrCount * ATTRSIZE + childCount;
-   if (!newSize && !mImpl->mMappedAttrs) {
--    PR_Free(mImpl);
-+    NS_GetGC()->Free(mImpl);
-     mImpl = nsnull;
-   }
-   else if (newSize < mImpl->mBufferSize) {
--    mImpl = static_cast<Impl*>(PR_Realloc(mImpl, (newSize + NS_IMPL_EXTRA_SIZE) * sizeof(nsIContent*)));
--    NS_ASSERTION(mImpl, "failed to reallocate to smaller buffer");
--
--    mImpl->mBufferSize = newSize;
-+    // XXXbsmedberg: is compacting this worthwhile?
-   }
- }
- 
-@@ -750,16 +731,18 @@ nsAttrAndChildArray::GrowBy(PRUint32 aGr
+@@ -718,16 +706,17 @@ nsAttrAndChildArray::GrowBy(PRUint32 aGr
      size = PR_BIT(PR_CeilingLog2(minSize));
    }
  
--  Impl* newImpl = static_cast<Impl*>
--                             (mImpl ? PR_Realloc(mImpl, size * sizeof(void*)) :
--              PR_Malloc(size * sizeof(void*)));
+-  Impl* newImpl = static_cast<Impl*>(malloc(size * sizeof(void*)));
 +  Impl* newImpl = new(size * sizeof(void*)) Impl;
    NS_ENSURE_TRUE(newImpl, PR_FALSE);
- 
    Impl* oldImpl = mImpl;
    mImpl = newImpl;
- 
-   // Set initial counts if we didn't have a buffer before
--  if (!oldImpl) {
-+  if (oldImpl) {
++
++  // Set initial counts if we didn't have a buffer before
+   if (oldImpl) {
+-    PRUint32 oldSize =
+-      (oldImpl->mBufferSize + NS_IMPL_EXTRA_SIZE) * sizeof(void*);
+-    memcpy(newImpl, oldImpl, oldSize);
+-  } else {
+-    // Set initial counts if we didn't have a buffer before
 +    memcpy(mImpl, oldImpl,
 +           (NS_IMPL_EXTRA_SIZE + oldImpl->mBufferSize) * sizeof(void*));
 +  }
 +  else {
      mImpl->mMappedAttrs = nsnull;
      SetAttrSlotAndChildCount(0, 0);
    }
 diff --git a/content/base/src/nsAttrAndChildArray.h b/content/base/src/nsAttrAndChildArray.h
@@ -73,17 +53,17 @@ diff --git a/content/base/src/nsAttrAndC
  public:
 -  nsAttrAndChildArray();
 -  ~nsAttrAndChildArray();
 +  nsAttrAndChildArray() : mImpl(nsnull) { }
 +  ~nsAttrAndChildArray() { }
  
    PRUint32 ChildCount() const
    {
-@@ -179,11 +179,18 @@ private:
+@@ -177,11 +177,18 @@ private:
      nsAttrValue mValue;
    };
  
 -  struct Impl {
 +  struct Impl : public XPCOMGCObject
 +  {
      PRUint32 mAttrAndChildCount;
      PRUint32 mBufferSize;
@@ -92,33 +72,33 @@ diff --git a/content/base/src/nsAttrAndC
 +
 +    // Ignore "size" and operate only on realSize
 +    static void* operator new(size_t size, size_t realSize)
 +    {
 +      return XPCOMGCObject::operator new(realSize);
 +    }
    };
  
-   Impl* mImpl;
+   Impl*               mImpl;
 diff --git a/content/base/src/nsGenericDOMDataNode.cpp b/content/base/src/nsGenericDOMDataNode.cpp
 --- a/content/base/src/nsGenericDOMDataNode.cpp
 +++ b/content/base/src/nsGenericDOMDataNode.cpp
 @@ -72,8 +72,6 @@ nsGenericDOMDataNode::nsGenericDOMDataNo
  
  nsGenericDOMDataNode::~nsGenericDOMDataNode()
  {
 -  NS_PRECONDITION(!IsInDoc(),
 -                  "Please remove this from the document properly");
  }
  
  NS_IMPL_CYCLE_COLLECTION_CLASS(nsGenericDOMDataNode)
 diff --git a/content/base/src/nsGenericElement.cpp b/content/base/src/nsGenericElement.cpp
 --- a/content/base/src/nsGenericElement.cpp
 +++ b/content/base/src/nsGenericElement.cpp
-@@ -999,8 +999,6 @@ nsGenericElement::nsGenericElement(nsINo
+@@ -988,8 +988,6 @@ nsGenericElement::nsGenericElement(nsINo
  
  nsGenericElement::~nsGenericElement()
  {
 -  NS_PRECONDITION(!IsInDoc(),
 -                  "Please remove this from the document properly");
  }
  
  NS_IMETHODIMP
--- a/nsListenerStruct
+++ b/nsListenerStruct
@@ -1,167 +1,36 @@
 diff --git a/content/events/src/nsEventListenerManager.cpp b/content/events/src/nsEventListenerManager.cpp
 --- a/content/events/src/nsEventListenerManager.cpp
 +++ b/content/events/src/nsEventListenerManager.cpp
-@@ -373,9 +373,9 @@ nsEventListenerManager::RemoveAllListene
- nsEventListenerManager::RemoveAllListeners()
- {
-   mListenersRemoved = PR_TRUE;
--  PRInt32 count = mListeners.Count();
-+  PRInt32 count = mListeners.Length();
-   for (PRInt32 i = 0; i < count; i++) {
--    delete static_cast<nsListenerStruct*>(mListeners.ElementAt(i));
-+    NS_GetGC()->Free(mListeners.ElementAt(i));
-   }
-   mListeners.Clear();
-   return NS_OK;
-@@ -469,9 +469,9 @@ nsEventListenerManager::AddEventListener
-   }
- 
-   nsListenerStruct* ls = nsnull;
--  PRInt32 count = mListeners.Count();
-+  PRInt32 count = mListeners.Length();
-   for (PRInt32 i = 0; i < count; i++) {
--    ls = static_cast<nsListenerStruct*>(mListeners.ElementAt(i));
-+    ls = mListeners.ElementAt(i);
-     if (ls->mListener == aListener && ls->mFlags == aFlags &&
-         ls->mGroupFlags == group &&
-         (EVENT_TYPE_EQUALS(ls, aType, aTypeAtom) ||
-@@ -493,7 +493,7 @@ nsEventListenerManager::AddEventListener
-   ls->mGroupFlags = group;
-   ls->mHandlerIsString = PR_FALSE;
-   ls->mTypeData = aTypeData;
--  mListeners.AppendElement((void*)ls);
-+  mListeners.AppendElement(ls);
- 
-   // For mutation listeners, we need to update the global bit on the DOM window.
-   // Otherwise we won't actually fire the mutation event.
-@@ -555,9 +555,9 @@ nsEventListenerManager::RemoveEventListe
-   nsListenerStruct* ls = nsnull;
-   aFlags &= ~NS_PRIV_EVENT_UNTRUSTED_PERMITTED;
- 
--  PRInt32 count = mListeners.Count();
-+  PRInt32 count = mListeners.Length();
-   for (PRInt32 i = 0; i < count; ++i) {
--    ls = static_cast<nsListenerStruct*>(mListeners.ElementAt(i));
-+    ls = mListeners.ElementAt(i);
-     if (ls->mListener == aListener &&
-         ls->mGroupFlags == group &&
-         ((ls->mFlags & ~NS_PRIV_EVENT_UNTRUSTED_PERMITTED) == aFlags) &&
-@@ -565,7 +565,7 @@ nsEventListenerManager::RemoveEventListe
+@@ -557,6 +557,7 @@ nsEventListenerManager::RemoveEventListe
           (!(ls->mEventType) &&
            EVENT_TYPE_DATA_EQUALS(ls->mTypeData, aTypeData)))) {
        mListeners.RemoveElementAt(i);
--      delete ls;
 +      NS_GetGC()->Free(ls);
        mNoListenerForEvent = NS_EVENT_TYPE_NULL;
        mNoListenerForEventAtom = nsnull;
-       mListenerRemoved = PR_TRUE;
-@@ -638,9 +638,9 @@ nsEventListenerManager::FindJSEventListe
-   // Run through the listeners for this type and see if a script
-   // listener is registered
-   nsListenerStruct *ls;
--  PRInt32 count = mListeners.Count();
-+  PRInt32 count = mListeners.Length();
-   for (PRInt32 i = 0; i < count; ++i) {
--    ls = static_cast<nsListenerStruct*>(mListeners.ElementAt(i));
-+    ls = mListeners.ElementAt(i);
-     if (EVENT_TYPE_EQUALS(ls, aEventType, aTypeAtom) &&
-         ls->mFlags & NS_PRIV_EVENT_FLAG_SCRIPT) {
-       return ls;
-@@ -836,8 +836,8 @@ nsEventListenerManager::RemoveScriptEven
-   nsListenerStruct* ls = FindJSEventListener(eventType, aName);
+       break;
+@@ -827,6 +828,7 @@ nsEventListenerManager::RemoveScriptEven
  
    if (ls) {
--    mListeners.RemoveElement((void*)ls);
--    delete ls;
-+    mListeners.RemoveElement(ls);
+     mListeners.RemoveElement(ls);
 +    NS_GetGC()->Free(ls);
      mNoListenerForEvent = NS_EVENT_TYPE_NULL;
      mNoListenerForEventAtom = nsnull;
-     mListenerRemoved = PR_TRUE;
-@@ -1100,7 +1100,7 @@ nsEventListenerManager::HandleEvent(nsPr
-                                     PRUint32 aFlags,
-                                     nsEventStatus* aEventStatus)
- {
--  if (mListeners.Count() <= 0 || aEvent->flags & NS_EVENT_FLAG_STOP_DISPATCH) {
-+  if (mListeners.Length() <= 0 || aEvent->flags & NS_EVENT_FLAG_STOP_DISPATCH) {
-     return NS_OK;
    }
+@@ -1139,7 +1141,7 @@ nsEventListenerManager::HandleEvent(nsPr
  
-@@ -1157,14 +1157,12 @@ found:
-     mListenerRemoved = PR_FALSE;
-   }
+ found:
  
--  PRInt32 count = mListeners.Count();
--  nsVoidArray originalListeners(count);
--  originalListeners = mListeners;
-+  PRInt32 count = mListeners.Length();
-+  nsTArray<nsListenerStruct*, GCAllocator> originalListeners(mListeners);
+-  nsAutoTObserverArray<nsAutoPtr<nsListenerStruct>, 2>::EndLimitedIterator iter(mListeners);
++  nsAutoTObserverArray<nsListenerStruct*, 2>::EndLimitedIterator iter(mListeners);
    nsAutoPopupStatePusher popupStatePusher(nsDOMEvent::GetEventPopupControlState(aEvent));
    PRBool hasListener = PR_FALSE;
-   for (PRInt32 k = 0; !mListenersRemoved && k < count; ++k) {
--    nsListenerStruct* ls =
--      static_cast<nsListenerStruct*>(originalListeners.FastElementAt(k));
-+    nsListenerStruct* ls = originalListeners[k];
-     if (!ls || (mListenerRemoved && mListeners.IndexOf(ls) == -1)) {
-       continue;
-     }
-@@ -1688,10 +1686,9 @@ nsEventListenerManager::HasMutationListe
- {
-   *aListener = PR_FALSE;
-   if (mMayHaveMutationListeners) {
--    PRInt32 count = mListeners.Count();
-+    PRInt32 count = mListeners.Length();
-     for (PRInt32 i = 0; i < count; ++i) {
--      nsListenerStruct* ls = static_cast<nsListenerStruct*>
--                                        (mListeners.FastElementAt(i));
-+      nsListenerStruct* ls = mListeners[i];
-       if (ls &&
-           ls->mEventType >= NS_MUTATION_START &&
-           ls->mEventType <= NS_MUTATION_END) {
-@@ -1709,10 +1706,9 @@ nsEventListenerManager::MutationListener
- {
-   PRUint32 bits = 0;
-   if (mMayHaveMutationListeners) {
--    PRInt32 i, count = mListeners.Count();
-+    PRInt32 i, count = mListeners.Length();
-     for (i = 0; i < count; ++i) {
--      nsListenerStruct* ls = static_cast<nsListenerStruct*>
--                                        (mListeners.FastElementAt(i));
-+      nsListenerStruct* ls = mListeners[i];
-       if (ls &&
-           (ls->mEventType >= NS_MUTATION_START &&
-            ls->mEventType <= NS_MUTATION_END)) {
-@@ -1749,10 +1745,9 @@ nsEventListenerManager::HasListenersFor(
-   }
- found:
- 
--  PRInt32 i, count = mListeners.Count();
-+  PRInt32 i, count = mListeners.Length();
-   for (i = 0; i < count; ++i) {
--    nsListenerStruct* ls = static_cast<nsListenerStruct*>
--                                      (mListeners.FastElementAt(i));
-+    nsListenerStruct* ls = mListeners[i];
-     if (ls &&
-         (ls->mTypeAtom == atom ||
-          EVENT_TYPE_DATA_EQUALS(ls->mTypeData, typeData))) {
-@@ -1765,10 +1760,9 @@ PRBool
- PRBool
- nsEventListenerManager::HasUnloadListeners()
- {
--  PRInt32 count = mListeners.Count();
-+  PRInt32 count = mListeners.Length();
-   for (PRInt32 i = 0; i < count; ++i) {
--    nsListenerStruct* ls = static_cast<nsListenerStruct*>
--                                      (mListeners.FastElementAt(i));
-+    nsListenerStruct* ls = mListeners[i];
-     if (ls &&
-         (ls->mEventType == NS_PAGE_UNLOAD ||
-          ls->mEventType == NS_BEFORE_PAGE_UNLOAD) ||
+   while (iter.HasMore()) {
 diff --git a/content/events/src/nsEventListenerManager.h b/content/events/src/nsEventListenerManager.h
 --- a/content/events/src/nsEventListenerManager.h
 +++ b/content/events/src/nsEventListenerManager.h
 @@ -47,12 +47,14 @@
  #include "nsHashtable.h"
  #include "nsIScriptContext.h"
  #include "nsCycleCollectionParticipant.h"
 +#include "nsTArray.h"
@@ -180,17 +49,57 @@ diff --git a/content/events/src/nsEventL
    PRUint16                      mGroupFlags;
    PRBool                        mHandlerIsString;
    const EventTypeData*          mTypeData;
 -} nsListenerStruct;
 +};
  
  /*
   * Event listener manager
-@@ -189,7 +191,7 @@ protected:
+@@ -188,7 +190,7 @@ protected:
    nsresult GetDOM2EventGroup(nsIDOMEventGroup** aGroup);
    PRBool ListenerCanHandle(nsListenerStruct* aLs, nsEvent* aEvent);
  
--  nsVoidArray       mListeners;
-+  nsTArray<nsListenerStruct*, GCAllocator> mListeners;
-   nsISupports*      mTarget;  //WEAK
-   PRPackedBool      mListenersRemoved;
-   PRPackedBool      mListenerRemoved;
+-  nsAutoTObserverArray<nsAutoPtr<nsListenerStruct>, 2> mListeners;
++  nsAutoTObserverArray<nsListenerStruct*, 2>           mListeners;
+   nsISupports*                                         mTarget;  //WEAK
+   PRUint32                                             mMayHaveMutationListeners : 1;
+   // These two member variables are used to cache the information
+diff --git a/xpcom/glue/nsTArray.h b/xpcom/glue/nsTArray.h
+--- a/xpcom/glue/nsTArray.h
++++ b/xpcom/glue/nsTArray.h
+@@ -748,10 +748,10 @@ class nsTArray : public nsTArray_base<Al
+     }
+ };
+ 
+-template<class E, PRUint32 N>
+-class nsAutoTArray : public nsTArray<E> {
++template<class E, PRUint32 N, class Allocator=CAllocator>
++class nsAutoTArray : public nsTArray<E, Allocator> {
+   public:
+-    typedef nsTArray<E> base_type;
++    typedef nsTArray<E, Allocator> base_type;
+     typedef typename base_type::Header Header;
+     typedef typename base_type::elem_type elem_type;
+ 
+@@ -772,8 +772,8 @@ class nsAutoTArray : public nsTArray<E> 
+ 
+ // specialization for N = 0. this makes the inheritance model easier for
+ // templated users of nsAutoTArray.
+-template<class E>
+-class nsAutoTArray<E, 0> : public nsTArray<E> {
++template<class E, class Allocator>
++class nsAutoTArray<E, 0, Allocator> : public nsTArray<E, Allocator> {
+   public:
+     nsAutoTArray() {}
+ };
+diff --git a/xpcom/glue/nsTObserverArray.h b/xpcom/glue/nsTObserverArray.h
+--- a/xpcom/glue/nsTObserverArray.h
++++ b/xpcom/glue/nsTObserverArray.h
+@@ -104,7 +104,7 @@ class nsAutoTObserverArray : protected n
+ class nsAutoTObserverArray : protected nsTObserverArray_base {
+   public:
+     typedef T           elem_type;
+-    typedef nsTArray<T> array_type;
++    typedef nsTArray<T, GCAllocator> array_type;
+ 
+     nsAutoTObserverArray() {
+     }
--- a/nsPresShellIterator
+++ b/nsPresShellIterator
@@ -1,26 +1,26 @@
 diff --git a/content/base/public/nsPresShellIterator.h b/content/base/public/nsPresShellIterator.h
 --- a/content/base/public/nsPresShellIterator.h
 +++ b/content/base/public/nsPresShellIterator.h
 @@ -47,22 +47,21 @@ public:
  public:
    nsPresShellIterator(nsIDocument* aDoc)
-   : nsTObserverArray<nsIPresShell>::ForwardIterator(aDoc->mPresShells),
+   : nsTObserverArray<nsIPresShell*>::ForwardIterator(aDoc->mPresShells),
 -    mDoc(aDoc) {}
 +    mDoc(aDoc)
 +  {
 +    ASSERT_StackObject(this);
 +  }
  
 -  already_AddRefed<nsIPresShell> GetNextShell()
 +  nsIPresShell* GetNextShell()
    {
      nsIPresShell* shell = nsnull;
-     if (!mDoc->ShellsAreHidden()) {
+     if (!mDoc->ShellsAreHidden() && HasMore()) {
        shell = GetNext();
 -      NS_IF_ADDREF(shell);
      }
      return shell;
    }
  private:
 -  static void* operator new(size_t) CPP_THROW_NEW { return 0; }
 -  static void operator delete(void*, size_t) {}
--- a/nsSlots
+++ b/nsSlots
@@ -1,23 +1,23 @@
 * * *
 
 diff --git a/content/base/public/nsINode.h b/content/base/public/nsINode.h
 --- a/content/base/public/nsINode.h
 +++ b/content/base/public/nsINode.h
-@@ -538,7 +538,7 @@ public:
+@@ -532,7 +532,7 @@ public:
  
    // This class can be extended by subclasses that wish to store more
    // information in the slots.
 -  class nsSlots
 +  class nsSlots : public XPCOMGCObject
    {
    public:
      nsSlots(PtrBits aFlags)
-@@ -547,10 +547,6 @@ public:
+@@ -541,10 +541,6 @@ public:
          mWeakReference(nsnull)
      {
      }
 -
 -    // If needed we could remove the vtable pointer this dtor causes by
 -    // putting a DestroySlots function on nsINode
 -    virtual ~nsSlots();
  
@@ -75,120 +75,120 @@ diff --git a/content/base/src/nsGenericE
  {
 -  nsCOMPtr<nsIEventListenerManager> elm;
 -  nsresult rv = GetListenerManager(PR_TRUE, getter_AddRefs(elm));
 +  nsIEventListenerManager* elm = nsnull;
 +  nsresult rv = GetListenerManager(PR_TRUE, &elm);
    if (elm) {
      return elm->GetSystemEventGroupLM(aGroup);
    }
-@@ -383,7 +369,7 @@ NS_IMETHODIMP
+@@ -371,7 +357,7 @@ NS_IMETHODIMP
  NS_IMETHODIMP
  nsNode3Tearoff::GetBaseURI(nsAString& aURI)
  {
 -  nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI();
 +  nsIURI* baseURI = mContent->GetBaseURI();
    nsCAutoString spec;
  
    if (baseURI) {
-@@ -398,7 +384,7 @@ NS_IMETHODIMP
+@@ -386,7 +372,7 @@ NS_IMETHODIMP
  NS_IMETHODIMP
  nsNode3Tearoff::GetTextContent(nsAString &aTextContent)
  {
 -  nsCOMPtr<nsIDOMNode> node(do_QueryInterface(mContent));
 +  nsIDOMNode* node(do_QueryInterface(mContent));
    NS_ASSERTION(node, "We have an nsIContent which doesn't support nsIDOMNode");
  
    PRUint16 nodeType;
-@@ -428,7 +414,7 @@ nsNode3Tearoff::SetTextContent(const nsA
+@@ -416,7 +402,7 @@ nsNode3Tearoff::SetTextContent(const nsA
    // Batch possible DOMSubtreeModified events.
    mozAutoSubtreeModified subtree(mContent->GetOwnerDoc(), nsnull);
  
 -  nsCOMPtr<nsIDOMNode> node(do_QueryInterface(mContent));
 +  nsIDOMNode* node(do_QueryInterface(mContent));
    NS_ASSERTION(node, "We have an nsIContent which doesn't support nsIDOMNode");
  
    PRUint16 nodeType;
-@@ -454,7 +440,7 @@ nsNode3Tearoff::CompareDocumentPosition(
+@@ -442,7 +428,7 @@ nsNode3Tearoff::CompareDocumentPosition(
  {
    NS_ENSURE_ARG_POINTER(aOther);
  
 -  nsCOMPtr<nsINode> other = do_QueryInterface(aOther);
 +  nsINode* other = do_QueryInterface(aOther);
    NS_ENSURE_TRUE(other, NS_ERROR_DOM_NOT_SUPPORTED_ERR);
  
    *aReturn = nsContentUtils::ComparePosition(other, mContent);
-@@ -465,7 +451,7 @@ nsNode3Tearoff::IsSameNode(nsIDOMNode* a
+@@ -453,7 +439,7 @@ nsNode3Tearoff::IsSameNode(nsIDOMNode* a
  nsNode3Tearoff::IsSameNode(nsIDOMNode* aOther,
                             PRBool* aReturn)
  {
 -  nsCOMPtr<nsIContent> other(do_QueryInterface(aOther));
 +  nsIContent* other(do_QueryInterface(aOther));
    *aReturn = mContent == other;
  
    return NS_OK;
-@@ -487,8 +473,8 @@ nsNode3Tearoff::AreNodesEqual(nsIContent
+@@ -475,8 +461,8 @@ nsNode3Tearoff::AreNodesEqual(nsIContent
    }
  
    if (aContent1->Tag() == nsGkAtoms::documentTypeNodeName) {
 -    nsCOMPtr<nsIDOMDocumentType> docType1 = do_QueryInterface(aContent1);
 -    nsCOMPtr<nsIDOMDocumentType> docType2 = do_QueryInterface(aContent2);
 +    nsIDOMDocumentType* docType1 = do_QueryInterface(aContent1);
 +    nsIDOMDocumentType* docType2 = do_QueryInterface(aContent2);
  
      NS_ASSERTION(docType1 && docType2, "Why don't we have a document type node?");
  
-@@ -544,8 +530,8 @@ nsNode3Tearoff::AreNodesEqual(nsIContent
+@@ -532,8 +518,8 @@ nsNode3Tearoff::AreNodesEqual(nsIContent
      }
    } else {
      // aContent1 is not an element.  Node value check.
 -    nsCOMPtr<nsIDOMNode> domNode1 = do_QueryInterface(aContent1);
 -    nsCOMPtr<nsIDOMNode> domNode2 = do_QueryInterface(aContent2);
 +    nsIDOMNode* domNode1 = do_QueryInterface(aContent1);
 +    nsIDOMNode* domNode2 = do_QueryInterface(aContent2);
      NS_ASSERTION(domNode1 && domNode2, "How'd we get nsIContent without nsIDOMNode?");
      domNode1->GetNodeValue(string1);
      domNode2->GetNodeValue(string2);
-@@ -580,7 +566,7 @@ nsNode3Tearoff::IsEqualNode(nsIDOMNode* 
+@@ -568,7 +554,7 @@ nsNode3Tearoff::IsEqualNode(nsIDOMNode* 
    *aReturn = PR_FALSE;
  
    // Since we implement nsIContent, aOther must as well.
 -  nsCOMPtr<nsIContent> aOtherContent = do_QueryInterface(aOther);
 +  nsIContent* aOtherContent = do_QueryInterface(aOther);
    // Documents and attributes don't implement nsIContent.
    if (!aOtherContent) {
      return NS_OK;
-@@ -754,7 +740,7 @@ nsNSElementTearoff::GetBoundingClientRec
+@@ -743,7 +729,7 @@ nsNSElementTearoff::GetBoundingClientRec
    if (!rect)
      return NS_ERROR_OUT_OF_MEMORY;
  
 -  NS_ADDREF(*aResult = rect);
 +  *aResult = rect;
    
    nsIFrame* frame = mContent->GetPrimaryFrame(Flush_Layout);  
    if (!frame) {
-@@ -793,7 +779,7 @@ nsNSElementTearoff::GetClientRects(nsIDO
+@@ -780,7 +766,7 @@ nsNSElementTearoff::GetClientRects(nsIDO
    if (!rectList)
      return NS_ERROR_OUT_OF_MEMORY;
    
 -  NS_ADDREF(*aResult = rectList);
 +  *aResult = rectList;
    
    nsIFrame* frame = mContent->GetPrimaryFrame(Flush_Layout);
    if (!frame) {
-@@ -803,7 +789,7 @@ nsNSElementTearoff::GetClientRects(nsIDO
-   
+@@ -791,7 +777,7 @@ nsNSElementTearoff::GetClientRects(nsIDO
    nsPresContext* presContext = frame->PresContext();
-   for (nsIFrame* f = frame; f; f = f->GetNextContinuation()) {
+   for (nsIFrame* f = frame; f;
+        f = nsLayoutUtils::GetNextContinuationOrSpecialSibling(f)) {
 -    nsRefPtr<nsTextRectangle> rect = new nsTextRectangle();
 +    nsTextRectangle* rect = new nsTextRectangle();
      if (!rect)
        return NS_ERROR_OUT_OF_MEMORY;
      
-@@ -823,21 +809,16 @@ NS_IMPL_ISUPPORTS1(nsNodeWeakReference,
+@@ -811,21 +797,16 @@ NS_IMPL_ISUPPORTS1(nsNodeWeakReference,
  NS_IMPL_ISUPPORTS1(nsNodeWeakReference,
                     nsIWeakReference)
  
 -nsNodeWeakReference::~nsNodeWeakReference()
 -{
 -  if (mNode) {
 -    NS_ASSERTION(mNode->GetSlots() &&
 -                 mNode->GetSlots()->mWeakReference == this,
@@ -207,223 +207,218 @@ diff --git a/content/base/src/nsGenericE
 +    *aInstancePtr = nsnull;
 +    return NS_ERROR_NULL_POINTER;
 +  }
 +
 +  return node->QueryInterface(aIID, aInstancePtr);
  }
  
  
-@@ -861,7 +842,7 @@ nsNodeSupportsWeakRefTearoff::GetWeakRef
+@@ -849,7 +830,7 @@ nsNodeSupportsWeakRefTearoff::GetWeakRef
      NS_ENSURE_TRUE(slots->mWeakReference, NS_ERROR_OUT_OF_MEMORY);
    }
  
 -  NS_ADDREF(*aInstancePtr = slots->mWeakReference);
 +  *aInstancePtr = slots->mWeakReference;
  
    return NS_OK;
  }
-@@ -882,9 +863,9 @@ nsresult
+@@ -870,9 +851,9 @@ nsresult
  nsresult
  nsDOMEventRTTearoff::GetDOM3EventTarget(nsIDOM3EventTarget **aTarget)
  {
 -  nsCOMPtr<nsIEventListenerManager> listener_manager;
 +  nsIEventListenerManager* listener_manager = nsnull;
    nsresult rv =
 -    mContent->GetListenerManager(PR_TRUE, getter_AddRefs(listener_manager));
 +    mContent->GetListenerManager(PR_TRUE, &listener_manager);
    NS_ENSURE_SUCCESS(rv, rv);
  
    return CallQueryInterface(listener_manager, aTarget);
-@@ -926,11 +907,11 @@ NS_IMETHODIMP
+@@ -914,11 +895,11 @@ NS_IMETHODIMP
  NS_IMETHODIMP
  nsDOMEventRTTearoff::DispatchEvent(nsIDOMEvent *aEvt, PRBool* _retval)
  {
 -  nsCOMPtr<nsIEventListenerManager> listener_manager;
 +  nsIEventListenerManager* listener_manager = nsnull;
    nsresult rv =
 -    mContent->GetListenerManager(PR_TRUE, getter_AddRefs(listener_manager));
--  NS_ENSURE_SUCCESS(rv, rv);
++    mContent->GetListenerManager(PR_TRUE, &listener_manager);
+   NS_ENSURE_SUCCESS(rv, rv);
 -  nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(listener_manager);
-+    mContent->GetListenerManager(PR_TRUE, &listener_manager);
-+  NS_ENSURE_SUCCESS(rv, rv);
 +  nsIDOMEventTarget* target = do_QueryInterface(listener_manager);
    NS_ENSURE_STATE(target);
    return target->DispatchEvent(aEvt, _retval);
  }
-@@ -942,8 +923,8 @@ nsDOMEventRTTearoff::AddGroupedEventList
+@@ -930,8 +911,8 @@ nsDOMEventRTTearoff::AddGroupedEventList
                                               PRBool aUseCapture,
                                               nsIDOMEventGroup *aEvtGrp)
  {
 -  nsCOMPtr<nsIDOM3EventTarget> event_target;
 -  nsresult rv = GetDOM3EventTarget(getter_AddRefs(event_target));
 +  nsIDOM3EventTarget* event_target = nsnull;
 +  nsresult rv = GetDOM3EventTarget(&event_target);
    NS_ENSURE_SUCCESS(rv, rv);
  
    return event_target->AddGroupedEventListener(aType, aListener, aUseCapture,
-@@ -956,8 +937,8 @@ nsDOMEventRTTearoff::RemoveGroupedEventL
+@@ -944,8 +925,8 @@ nsDOMEventRTTearoff::RemoveGroupedEventL
                                                  PRBool aUseCapture,
                                                  nsIDOMEventGroup *aEvtGrp)
  {
 -  nsCOMPtr<nsIDOM3EventTarget> event_target;
 -  nsresult rv = GetDOM3EventTarget(getter_AddRefs(event_target));
 +  nsIDOM3EventTarget* event_target = nsnull;
 +  nsresult rv = GetDOM3EventTarget(&event_target);
    NS_ENSURE_SUCCESS(rv, rv);
  
    return event_target->RemoveGroupedEventListener(aType, aListener,
-@@ -983,9 +964,9 @@ nsDOMEventRTTearoff::AddEventListener(co
+@@ -971,9 +952,9 @@ nsDOMEventRTTearoff::AddEventListener(co
                                        PRBool aUseCapture,
                                        PRBool aWantsUntrusted)
  {
 -  nsCOMPtr<nsIEventListenerManager> listener_manager;
 +  nsIEventListenerManager* listener_manager = nsnull;
    nsresult rv =
 -    mContent->GetListenerManager(PR_TRUE, getter_AddRefs(listener_manager));
 +    mContent->GetListenerManager(PR_TRUE, &listener_manager);
    NS_ENSURE_SUCCESS(rv, rv);
  
    PRInt32 flags = aUseCapture ? NS_EVENT_FLAG_CAPTURE : NS_EVENT_FLAG_BUBBLE;
-@@ -1008,10 +989,6 @@ nsGenericElement::nsDOMSlots::nsDOMSlots
+@@ -996,10 +977,6 @@ nsGenericElement::nsDOMSlots::nsDOMSlots
  {
  }
  
 -nsGenericElement::nsDOMSlots::~nsDOMSlots()
 -{
 -}
 -
  nsGenericElement::nsGenericElement(nsINodeInfo *aNodeInfo)
-   : nsIContent(aNodeInfo)
- {
-@@ -1135,7 +1112,7 @@ nsGenericElement::SetPrefix(const nsAStr
+   : nsIContent(aNodeInfo),
+     mAttrsAndChildren()
+@@ -1124,7 +1101,7 @@ nsGenericElement::SetPrefix(const nsAStr
  {
    // XXX: Validate the prefix string!
  
 -  nsCOMPtr<nsIAtom> prefix;
 +  nsIAtom* prefix = nsnull;
  
    if (!aPrefix.IsEmpty()) {
      prefix = do_GetAtom(aPrefix);
-@@ -1147,9 +1124,9 @@ nsGenericElement::SetPrefix(const nsAStr
+@@ -1136,9 +1113,9 @@ nsGenericElement::SetPrefix(const nsAStr
      return NS_ERROR_DOM_NAMESPACE_ERR;
    }
  
 -  nsCOMPtr<nsINodeInfo> newNodeInfo;
 +  nsINodeInfo* newNodeInfo = nsnull;
    nsresult rv = nsContentUtils::PrefixChanged(mNodeInfo, prefix,
 -                                              getter_AddRefs(newNodeInfo));
 +                                              &newNodeInfo);
    NS_ENSURE_SUCCESS(rv, rv);
  
    mNodeInfo = newNodeInfo;
-@@ -1216,7 +1193,7 @@ nsGenericElement::InternalIsSupported(ns
+@@ -1205,7 +1182,7 @@ nsGenericElement::InternalIsSupported(ns
    }
  #endif /* MOZ_SVG */
    else {
 -    nsCOMPtr<nsIDOMNSFeatureFactory> factory =
 +    nsIDOMNSFeatureFactory* factory =
        GetDOMFeatureFactory(aFeature, aVersion);
  
      if (factory) {
-@@ -1233,7 +1210,7 @@ nsGenericElement::InternalGetFeature(nsI
+@@ -1222,7 +1199,7 @@ nsGenericElement::InternalGetFeature(nsI
                                      nsISupports** aReturn)
  {
    *aReturn = nsnull;
 -  nsCOMPtr<nsIDOMNSFeatureFactory> factory =
 +  nsIDOMNSFeatureFactory* factory =
      GetDOMFeatureFactory(aFeature, aVersion);
  
    if (factory) {
-@@ -1243,12 +1220,12 @@ nsGenericElement::InternalGetFeature(nsI
+@@ -1232,12 +1209,12 @@ nsGenericElement::InternalGetFeature(nsI
    return NS_OK;
  }
  
 -already_AddRefed<nsIDOMNSFeatureFactory>
 +nsIDOMNSFeatureFactory*
  nsGenericElement::GetDOMFeatureFactory(const nsAString& aFeature,
                                         const nsAString& aVersion)
  {
    nsIDOMNSFeatureFactory *factory = nsnull;
 -  nsCOMPtr<nsICategoryManager> categoryManager =
 +  nsICategoryManager* categoryManager =
      do_GetService(NS_CATEGORYMANAGER_CONTRACTID);
    if (categoryManager) {
      nsCAutoString featureCategory(NS_DOMNS_FEATURE_PREFIX);
-@@ -1303,7 +1280,7 @@ nsGenericElement::GetAttributes(nsIDOMNa
+@@ -1292,7 +1269,7 @@ nsGenericElement::GetAttributes(nsIDOMNa
      }
    }
  
 -  NS_ADDREF(*aAttributes = slots->mAttributeMap);
 +  *aAttributes = slots->mAttributeMap;
  
    return NS_OK;
  }
-@@ -1322,10 +1299,9 @@ nsGenericElement::GetChildNodes(nsIDOMNo
+@@ -1311,10 +1288,9 @@ nsGenericElement::GetChildNodes(nsIDOMNo
      if (!slots->mChildNodes) {
        return NS_ERROR_OUT_OF_MEMORY;
      }
 -    NS_ADDREF(slots->mChildNodes);
 -  }
 -
 -  NS_ADDREF(*aChildNodes = slots->mChildNodes);
 +  }
 +
 +  *aChildNodes = slots->mChildNodes;
  
    return NS_OK;
  }
-@@ -1406,7 +1382,7 @@ nsGenericElement::SetAttribute(const nsA
+@@ -1395,7 +1371,7 @@ nsGenericElement::SetAttribute(const nsA
      nsresult rv = nsContentUtils::CheckQName(aName, PR_FALSE);
      NS_ENSURE_SUCCESS(rv, rv);
  
 -    nsCOMPtr<nsIAtom> nameAtom = do_GetAtom(aName);
 +    nsIAtom* nameAtom = do_GetAtom(aName);
      NS_ENSURE_TRUE(nameAtom, NS_ERROR_OUT_OF_MEMORY);
  
      return SetAttr(kNameSpaceID_None, nameAtom, aValue, PR_TRUE);
-@@ -1440,12 +1416,12 @@ nsGenericElement::GetAttributeNode(const
+@@ -1429,12 +1405,12 @@ nsGenericElement::GetAttributeNode(const
    NS_ENSURE_ARG_POINTER(aReturn);
    *aReturn = nsnull;
  
 -  nsCOMPtr<nsIDOMNamedNodeMap> map;
 -  nsresult rv = GetAttributes(getter_AddRefs(map));
--  NS_ENSURE_SUCCESS(rv, rv);
--
++  nsIDOMNamedNodeMap* map = nsnull;
++  nsresult rv = GetAttributes(&map);
+   NS_ENSURE_SUCCESS(rv, rv);
+ 
 -  nsCOMPtr<nsIDOMNode> node;
 -  rv = map->GetNamedItem(aName, getter_AddRefs(node));
-+  nsIDOMNamedNodeMap* map = nsnull;
-+  nsresult rv = GetAttributes(&map);
-+  NS_ENSURE_SUCCESS(rv, rv);
-+
 +  nsIDOMNode* node = nsnull;
 +  rv = map->GetNamedItem(aName, &node);
  
    if (NS_SUCCEEDED(rv) && node) {
      rv = CallQueryInterface(node, aReturn);
-@@ -1463,12 +1439,12 @@ nsGenericElement::SetAttributeNode(nsIDO
+@@ -1452,12 +1428,12 @@ nsGenericElement::SetAttributeNode(nsIDO
  
    *aReturn = nsnull;
  
 -  nsCOMPtr<nsIDOMNamedNodeMap> map;
 -  nsresult rv = GetAttributes(getter_AddRefs(map));
--  NS_ENSURE_SUCCESS(rv, rv);
--
++  nsIDOMNamedNodeMap* map = nsnull;
++  nsresult rv = GetAttributes(&map);
+   NS_ENSURE_SUCCESS(rv, rv);
+ 
 -  nsCOMPtr<nsIDOMNode> returnNode;
 -  rv = map->SetNamedItem(aAttribute, getter_AddRefs(returnNode));
-+  nsIDOMNamedNodeMap* map = nsnull;
-+  nsresult rv = GetAttributes(&map);
-+  NS_ENSURE_SUCCESS(rv, rv);
-+
 +  nsIDOMNode* returnNode = nsnull;
 +  rv = map->SetNamedItem(aAttribute, &returnNode);
    NS_ENSURE_SUCCESS(rv, rv);
  
    if (returnNode) {
-@@ -1487,16 +1463,16 @@ nsGenericElement::RemoveAttributeNode(ns
+@@ -1476,16 +1452,16 @@ nsGenericElement::RemoveAttributeNode(ns
  
    *aReturn = nsnull;
  
 -  nsCOMPtr<nsIDOMNamedNodeMap> map;
 -  nsresult rv = GetAttributes(getter_AddRefs(map));
 +  nsIDOMNamedNodeMap* map = nsnull;
 +  nsresult rv = GetAttributes(&map);
    NS_ENSURE_SUCCESS(rv, rv);
@@ -434,165 +429,159 @@ diff --git a/content/base/src/nsGenericE
    if (NS_SUCCEEDED(rv)) {
 -    nsCOMPtr<nsIDOMNode> node;
 -    rv = map->RemoveNamedItem(name, getter_AddRefs(node));
 +    nsIDOMNode* node = nsnull;
 +    rv = map->RemoveNamedItem(name, &node);
  
      if (NS_SUCCEEDED(rv) && node) {
        rv = CallQueryInterface(node, aReturn);
-@@ -1510,11 +1486,11 @@ nsGenericElement::GetElementsByTagName(c
+@@ -1499,11 +1475,11 @@ nsGenericElement::GetElementsByTagName(c
  nsGenericElement::GetElementsByTagName(const nsAString& aTagname,
                                         nsIDOMNodeList** aReturn)
  {
 -  nsCOMPtr<nsIAtom> nameAtom = do_GetAtom(aTagname);
 +  nsIAtom* nameAtom = do_GetAtom(aTagname);
    NS_ENSURE_TRUE(nameAtom, NS_ERROR_OUT_OF_MEMORY);
  
    nsContentList *list = NS_GetContentList(this, nameAtom,
 -                                          kNameSpaceID_Unknown).get();
 +                                          kNameSpaceID_Unknown);
    NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY);
  
    // transfer ref to aReturn
-@@ -1538,7 +1514,7 @@ nsGenericElement::GetAttributeNS(const n
+@@ -1527,7 +1503,7 @@ nsGenericElement::GetAttributeNS(const n
      return NS_OK;
    }
  
 -  nsCOMPtr<nsIAtom> name = do_GetAtom(aLocalName);
 +  nsIAtom* name = do_GetAtom(aLocalName);
    GetAttr(nsid, name, aReturn);
  
    return NS_OK;
-@@ -1549,11 +1525,11 @@ nsGenericElement::SetAttributeNS(const n
+@@ -1538,11 +1514,11 @@ nsGenericElement::SetAttributeNS(const n
                                   const nsAString& aQualifiedName,
                                   const nsAString& aValue)
  {
 -  nsCOMPtr<nsINodeInfo> ni;
 +  nsINodeInfo* ni = nsnull;
    nsresult rv =
      nsContentUtils::GetNodeInfoFromQName(aNamespaceURI, aQualifiedName,
                                           mNodeInfo->NodeInfoManager(),
 -                                         getter_AddRefs(ni));
 +                                         &ni);
    NS_ENSURE_SUCCESS(rv, rv);
  
    return SetAttr(ni->NamespaceID(), ni->NameAtom(), ni->GetPrefixAtom(),
-@@ -1564,7 +1540,7 @@ nsGenericElement::RemoveAttributeNS(cons
+@@ -1553,7 +1529,7 @@ nsGenericElement::RemoveAttributeNS(cons
  nsGenericElement::RemoveAttributeNS(const nsAString& aNamespaceURI,
                                      const nsAString& aLocalName)
  {
 -  nsCOMPtr<nsIAtom> name = do_GetAtom(aLocalName);
 +  nsIAtom* name = do_GetAtom(aLocalName);
    PRInt32 nsid =
      nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI);
  
-@@ -1589,12 +1565,12 @@ nsGenericElement::GetAttributeNodeNS(con
+@@ -1578,12 +1554,12 @@ nsGenericElement::GetAttributeNodeNS(con
  
    *aReturn = nsnull;
  
 -  nsCOMPtr<nsIDOMNamedNodeMap> map;
 -  nsresult rv = GetAttributes(getter_AddRefs(map));
--  NS_ENSURE_SUCCESS(rv, rv);
--
++  nsIDOMNamedNodeMap* map = nsnull;
++  nsresult rv = GetAttributes(&map);
+   NS_ENSURE_SUCCESS(rv, rv);
+ 
 -  nsCOMPtr<nsIDOMNode> node;
 -  rv = map->GetNamedItemNS(aNamespaceURI, aLocalName, getter_AddRefs(node));
-+  nsIDOMNamedNodeMap* map = nsnull;
-+  nsresult rv = GetAttributes(&map);
-+  NS_ENSURE_SUCCESS(rv, rv);
-+
 +  nsIDOMNode* node = nsnull;
 +  rv = map->GetNamedItemNS(aNamespaceURI, aLocalName, &node);
  
    if (NS_SUCCEEDED(rv) && node) {
      rv = CallQueryInterface(node, aReturn);
-@@ -1612,12 +1588,12 @@ nsGenericElement::SetAttributeNodeNS(nsI
+@@ -1601,12 +1577,12 @@ nsGenericElement::SetAttributeNodeNS(nsI
  
    *aReturn = nsnull;
  
 -  nsCOMPtr<nsIDOMNamedNodeMap> map;
 -  nsresult rv = GetAttributes(getter_AddRefs(map));
--  NS_ENSURE_SUCCESS(rv, rv);
--
++  nsIDOMNamedNodeMap* map = nsnull;
++  nsresult rv = GetAttributes(&map);
+   NS_ENSURE_SUCCESS(rv, rv);
+ 
 -  nsCOMPtr<nsIDOMNode> returnNode;
 -  rv = map->SetNamedItemNS(aNewAttr, getter_AddRefs(returnNode));
-+  nsIDOMNamedNodeMap* map = nsnull;
-+  nsresult rv = GetAttributes(&map);
-+  NS_ENSURE_SUCCESS(rv, rv);
-+
 +  nsIDOMNode* returnNode = nsnull;
 +  rv = map->SetNamedItemNS(aNewAttr, &returnNode);
    NS_ENSURE_SUCCESS(rv, rv);
  
    if (returnNode) {
-@@ -1641,10 +1617,10 @@ nsGenericElement::GetElementsByTagNameNS
+@@ -1630,10 +1606,10 @@ nsGenericElement::GetElementsByTagNameNS
      NS_ENSURE_SUCCESS(rv, rv);
    }
  
 -  nsCOMPtr<nsIAtom> nameAtom = do_GetAtom(aLocalName);
 +  nsIAtom* nameAtom = do_GetAtom(aLocalName);
    NS_ENSURE_TRUE(nameAtom, NS_ERROR_OUT_OF_MEMORY);
  
 -  nsContentList *list = NS_GetContentList(this, nameAtom, nameSpaceId).get();
 +  nsContentList *list = NS_GetContentList(this, nameAtom, nameSpaceId);
    NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY);
  
    // transfer ref to aReturn
-@@ -1681,7 +1657,7 @@ nsGenericElement::HasAttributeNS(const n
+@@ -1670,7 +1646,7 @@ nsGenericElement::HasAttributeNS(const n
      return NS_OK;
    }
  
 -  nsCOMPtr<nsIAtom> name = do_GetAtom(aLocalName);
 +  nsIAtom* name = do_GetAtom(aLocalName);
    *aReturn = HasAttr(nsid, name);
  
    return NS_OK;
-@@ -1692,10 +1668,10 @@ nsGenericElement::JoinTextNodes(nsIConte
+@@ -1681,10 +1657,10 @@ nsGenericElement::JoinTextNodes(nsIConte
                                  nsIContent* aSecond)
  {
    nsresult rv = NS_OK;
 -  nsCOMPtr<nsIDOMText> firstText(do_QueryInterface(aFirst, &rv));
--
--  if (NS_SUCCEEDED(rv)) {
++  nsIDOMText* firstText(do_QueryInterface(aFirst, &rv));
+ 
+   if (NS_SUCCEEDED(rv)) {
 -    nsCOMPtr<nsIDOMText> secondText(do_QueryInterface(aSecond, &rv));
-+  nsIDOMText* firstText(do_QueryInterface(aFirst, &rv));
-+
-+  if (NS_SUCCEEDED(rv)) {
 +    nsIDOMText* secondText(do_QueryInterface(aSecond, &rv));
  
      if (NS_SUCCEEDED(rv)) {
        nsAutoString str;
-@@ -1722,7 +1698,7 @@ nsGenericElement::Normalize()
+@@ -1711,7 +1687,7 @@ nsGenericElement::Normalize()
    for (index = 0; (index < count) && (NS_OK == result); index++) {
      nsIContent *child = GetChildAt(index);
  
 -    nsCOMPtr<nsIDOMNode> node = do_QueryInterface(child);
 +    nsIDOMNode* node = do_QueryInterface(child);
      if (node) {
        PRUint16 nodeType;
        node->GetNodeType(&nodeType);
-@@ -1748,7 +1724,7 @@ nsGenericElement::Normalize()
+@@ -1737,7 +1713,7 @@ nsGenericElement::Normalize()
              // nodes.
              nsIContent *sibling = GetChildAt(index + 1);
  
 -            nsCOMPtr<nsIDOMNode> siblingNode = do_QueryInterface(sibling);
 +            nsIDOMNode* siblingNode = do_QueryInterface(sibling);
  
              if (siblingNode) {
                PRUint16 siblingNodeType;
-@@ -1772,7 +1748,7 @@ nsGenericElement::Normalize()
+@@ -1761,7 +1737,7 @@ nsGenericElement::Normalize()
            break;
  
          case nsIDOMNode::ELEMENT_NODE:
 -          nsCOMPtr<nsIDOMElement> element = do_QueryInterface(child);
 +          nsIDOMElement* element = do_QueryInterface(child);
  
            if (element) {
              result = element->Normalize();
-@@ -1812,16 +1788,16 @@ BindNodesInInsertPoints(nsXBLBinding* aB
+@@ -1801,16 +1777,16 @@ BindNodesInInsertPoints(nsXBLBinding* aB
    if (inserts) {
      PRBool allowScripts = aBinding->AllowScripts();
  #ifdef MOZ_XUL
 -    nsCOMPtr<nsIXULDocument> xulDoc = do_QueryInterface(aDocument);
 +    nsIXULDocument* xulDoc = do_QueryInterface(aDocument);
  #endif
      PRUint32 i;
      for (i = 0; i < inserts->Length(); ++i) {
@@ -602,130 +591,130 @@ diff --git a/content/base/src/nsGenericE
        if (insertRoot) {
          PRUint32 j;
          for (j = 0; j < insertRoot->GetChildCount(); ++j) {
 -          nsCOMPtr<nsIContent> child = insertRoot->GetChildAt(j);
 +          nsIContent* child = insertRoot->GetChildAt(j);
            rv = child->BindToTree(aDocument, aInsertParent,
                                   aBinding->GetBoundElement(), allowScripts);
            NS_ENSURE_SUCCESS(rv, rv);
-@@ -1939,11 +1915,11 @@ nsGenericElement::BindToTree(nsIDocument
+@@ -1928,11 +1904,11 @@ nsGenericElement::BindToTree(nsIDocument
        nsXBLBinding* contBinding =
          GetFirstBindingWithContent(bmgr, this);
        if (contBinding) {
 -        nsCOMPtr<nsIContent> anonRoot = contBinding->GetAnonymousContent();
 +        nsIContent* anonRoot = contBinding->GetAnonymousContent();
          PRBool allowScripts = contBinding->AllowScripts();
          PRUint32 i;
          for (i = 0; i < anonRoot->GetChildCount(); ++i) {
 -          nsCOMPtr<nsIContent> child = anonRoot->GetChildAt(i);
 +          nsIContent* child = anonRoot->GetChildAt(i);
            rv = child->BindToTree(aDocument, this, this, allowScripts);
            NS_ENSURE_SUCCESS(rv, rv);
          }
-@@ -1975,7 +1951,7 @@ nsGenericElement::BindToTree(nsIDocument
+@@ -1964,7 +1940,7 @@ nsGenericElement::BindToTree(nsIDocument
    // Additionally, there's not really a need to generate the children here.
    for (i = 0; i < mAttrsAndChildren.ChildCount(); ++i) {
      // The child can remove itself from the parent in BindToTree.
 -    nsCOMPtr<nsIContent> child = mAttrsAndChildren.ChildAt(i);
 +    nsIContent* child = mAttrsAndChildren.ChildAt(i);
      rv = child->BindToTree(aDocument, this, aBindingParent,
                             aCompileEventHandlers);
      NS_ENSURE_SUCCESS(rv, rv);
-@@ -2088,7 +2064,7 @@ nsGenericElement::doPreHandleEvent(nsICo
-   PRBool isAnonForEvents = aContent->IsAnonymousForEvents();
+@@ -2077,7 +2053,7 @@ nsGenericElement::doPreHandleEvent(nsICo
+   PRBool isAnonForEvents = aContent->IsNativeAnonymous();
    if (aVisitor.mEvent->message == NS_MOUSE_ENTER_SYNTH ||
        aVisitor.mEvent->message == NS_MOUSE_EXIT_SYNTH) {
 -     nsCOMPtr<nsIContent> relatedTarget =
 +     nsIContent* relatedTarget =
         do_QueryInterface(static_cast<nsMouseEvent*>
                                      (aVisitor.mEvent)->relatedTarget);
      if (relatedTarget &&
-@@ -2119,7 +2095,7 @@ nsGenericElement::doPreHandleEvent(nsICo
+@@ -2108,7 +2084,7 @@ nsGenericElement::doPreHandleEvent(nsICo
      }
    }
  
 -  nsCOMPtr<nsIContent> parent = aContent->GetParent();
 +  nsIContent* parent = aContent->GetParent();
    if (isAnonForEvents) {
      // Don't propagate mutation events which are dispatched somewhere inside
      // native anonymous content.
-@@ -2130,7 +2106,7 @@ nsGenericElement::doPreHandleEvent(nsICo
+@@ -2119,7 +2095,7 @@ nsGenericElement::doPreHandleEvent(nsICo
  
      aVisitor.mEventTargetAtParent = parent;
    } else if (parent) {
 -    nsCOMPtr<nsIContent> content(do_QueryInterface(aVisitor.mEvent->target));
 +    nsIContent* content(do_QueryInterface(aVisitor.mEvent->target));
      if (content && content->GetBindingParent() == parent) {
        aVisitor.mEventTargetAtParent = parent;
      }
-@@ -2289,7 +2265,7 @@ nsGenericElement::GetExistingAttrNameFro
+@@ -2278,7 +2254,7 @@ nsGenericElement::GetExistingAttrNameFro
                                                kNameSpaceID_None, &nodeInfo);
    }
    else {
 -    NS_ADDREF(nodeInfo = name->NodeInfo());
 +    nodeInfo = name->NodeInfo();
    }
  
    return nodeInfo;
-@@ -2308,7 +2284,7 @@ nsGenericElement::GetBaseURI() const
+@@ -2297,7 +2273,7 @@ nsGenericElement::GetBaseURI() const
  
    // Our base URL depends on whether we have an xml:base attribute, as
    // well as on whether any of our ancestors do.
 -  nsCOMPtr<nsIURI> parentBase;
 +  nsIURI* parentBase = nsnull;
  
    nsIContent *parent = GetParent();
    if (parent) {
-@@ -2325,13 +2301,13 @@ nsGenericElement::GetBaseURI() const
+@@ -2314,13 +2290,13 @@ nsGenericElement::GetBaseURI() const
    if (value.IsEmpty()) {
      // No xml:base, so we just use the parent's base URL
      nsIURI *base = nsnull;
 -    parentBase.swap(base);
 +    swap(parentBase, base);
  
      return base;
    }
  
 -  nsCOMPtr<nsIURI> ourBase;
 -  nsresult rv = NS_NewURI(getter_AddRefs(ourBase), value,
 +  nsIURI* ourBase = nsnull;
 +  nsresult rv = NS_NewURI(&ourBase, value,
                            doc->GetDocumentCharacterSet().get(), parentBase);
    if (NS_SUCCEEDED(rv)) {
      // do a security check, almost the same as nsDocument::SetBaseURL()
-@@ -2347,7 +2323,6 @@ nsGenericElement::GetBaseURI() const
+@@ -2336,7 +2312,6 @@ nsGenericElement::GetBaseURI() const
      base = ourBase;
    }
  
 -  NS_IF_ADDREF(base);
  
    return base;    
  }
-@@ -2365,7 +2340,7 @@ nsGenericElement::SetFocus(nsPresContext
+@@ -2354,7 +2329,7 @@ nsGenericElement::SetFocus(nsPresContext
    // Traditionally focusable elements can take focus as long as they don't set
    // the disabled attribute
  
 -  nsCOMPtr<nsIPresShell> presShell = aPresContext->PresShell();
 +  nsIPresShell* presShell = aPresContext->PresShell();
    if (!presShell) {
      return;
    }
-@@ -2396,8 +2371,8 @@ nsGenericElement::ShouldFocus(nsIContent
+@@ -2385,8 +2360,8 @@ nsGenericElement::ShouldFocus(nsIContent
      nsIScriptGlobalObject *sgo = document->GetScriptGlobalObject();
  
      if (sgo) {
 -      nsCOMPtr<nsIWebNavigation> webNav(do_GetInterface(sgo));
 -      nsCOMPtr<nsIBaseWindow> baseWin(do_QueryInterface(webNav));
 +      nsIWebNavigation* webNav(do_GetInterface(sgo));
 +      nsIBaseWindow* baseWin(do_QueryInterface(webNav));
  
        if (baseWin) {
          baseWin->GetVisibility(&visible);
-@@ -2422,13 +2397,13 @@ nsGenericElement::ShouldBlur(nsIContent 
+@@ -2411,13 +2386,13 @@ nsGenericElement::ShouldBlur(nsIContent 
      nsPIDOMWindow *win = document->GetWindow();
  
      if (win) {
 -      nsCOMPtr<nsIFocusController> focusController =
 +      nsIFocusController* focusController =
             win->GetRootFocusController();
  
        if (focusController) {
@@ -733,169 +722,169 @@ diff --git a/content/base/src/nsGenericE
 -        focusController->GetFocusedElement(getter_AddRefs(focusedElement));    
 -        nsCOMPtr<nsIDOMElement> domElement = do_QueryInterface(aContent);
 +        nsIDOMElement* focusedElement = nsnull;
 +        focusController->GetFocusedElement(&focusedElement);    
 +        nsIDOMElement* domElement = do_QueryInterface(aContent);
          //when the element is the same as the focused element, blur it
          if (domElement == focusedElement)
            isFocused = PR_TRUE;
-@@ -2529,7 +2504,7 @@ nsGenericElement::doInsertChildAt(nsICon
+@@ -2518,7 +2493,7 @@ nsGenericElement::doInsertChildAt(nsICon
        return NS_ERROR_DOM_WRONG_DOCUMENT_ERR;
      }
  
 -    nsCOMPtr<nsIDOMNode> kid = do_QueryInterface(aKid, &rv);
 +    nsIDOMNode* kid = do_QueryInterface(aKid, &rv);
      NS_ENSURE_SUCCESS(rv, rv);
  
      PRUint16 nodeType = 0;
-@@ -2594,7 +2569,7 @@ nsresult
+@@ -2583,7 +2558,7 @@ nsresult
  nsresult
  nsGenericElement::RemoveChildAt(PRUint32 aIndex, PRBool aNotify)
  {
 -  nsCOMPtr<nsIContent> oldKid = mAttrsAndChildren.GetSafeChildAt(aIndex);
 +  nsIContent* oldKid = mAttrsAndChildren.GetSafeChildAt(aIndex);
    NS_ASSERTION(oldKid == GetChildAt(aIndex), "Unexpected child in RemoveChildAt");
  
    if (oldKid) {
-@@ -2622,7 +2597,7 @@ nsGenericElement::doRemoveChildAt(PRUint
+@@ -2611,7 +2586,7 @@ nsGenericElement::doRemoveChildAt(PRUint
    if (aNotify && aDocument) {
      nsIPresShell *presShell = aDocument->GetPrimaryShell();
      if (presShell && presShell->IsAccessibilityActive()) {
 -      nsCOMPtr<nsIAccessibilityService> accService = 
 +      nsIAccessibilityService* accService = 
          do_GetService("@mozilla.org/accessibilityService;1");
        if (accService) {
          accService->InvalidateSubtreeFor(presShell, aKid,
-@@ -2690,7 +2665,7 @@ nsGenericElement::DispatchEvent(nsPresCo
+@@ -2679,7 +2654,7 @@ nsGenericElement::DispatchEvent(nsPresCo
      return NS_OK;
    }
  
 -  nsCOMPtr<nsIPresShell> shell = aPresContext->GetPresShell();
 +  nsIPresShell* shell = aPresContext->GetPresShell();
    if (!shell) {
      return NS_OK;
    }
-@@ -2831,7 +2806,7 @@ PRBool IsAllowedAsChild(nsIContent* aNew
+@@ -2820,7 +2795,7 @@ PRBool IsAllowedAsChild(nsIContent* aNew
                    "Must have ref content for replace");
  #ifdef DEBUG
    PRUint16 debugNodeType = 0;
 -  nsCOMPtr<nsIDOMNode> debugNode(do_QueryInterface(aNewChild));
 +  nsIDOMNode* debugNode(do_QueryInterface(aNewChild));
    nsresult debugRv = debugNode->GetNodeType(&debugNodeType);
  
    NS_PRECONDITION(NS_SUCCEEDED(debugRv) && debugNodeType == aNewNodeType,
-@@ -2875,11 +2850,11 @@ PRBool IsAllowedAsChild(nsIContent* aNew
+@@ -2864,11 +2839,11 @@ PRBool IsAllowedAsChild(nsIContent* aNew
        }
  
        // Now grovel for a doctype
 -      nsCOMPtr<nsIDOMDocument> doc = do_QueryInterface(aDocument);
 +      nsIDOMDocument* doc = do_QueryInterface(aDocument);
        NS_ASSERTION(doc, "Shouldn't happen");
 -      nsCOMPtr<nsIDOMDocumentType> docType;
 -      doc->GetDoctype(getter_AddRefs(docType));
 -      nsCOMPtr<nsIContent> docTypeContent = do_QueryInterface(docType);
 +      nsIDOMDocumentType* docType = nsnull;
 +      doc->GetDoctype(&docType);
 +      nsIContent* docTypeContent = do_QueryInterface(docType);
        
        if (!docTypeContent) {
          // It's all good.
-@@ -2902,11 +2877,11 @@ PRBool IsAllowedAsChild(nsIContent* aNew
+@@ -2891,11 +2866,11 @@ PRBool IsAllowedAsChild(nsIContent* aNew
          return PR_FALSE;
        }
  
 -      nsCOMPtr<nsIDOMDocument> doc = do_QueryInterface(aDocument);
 +      nsIDOMDocument* doc = do_QueryInterface(aDocument);
        NS_ASSERTION(doc, "Shouldn't happen");
 -      nsCOMPtr<nsIDOMDocumentType> docType;
 -      doc->GetDoctype(getter_AddRefs(docType));
 -      nsCOMPtr<nsIContent> docTypeContent = do_QueryInterface(docType);
 +      nsIDOMDocumentType* docType = nsnull;
 +      doc->GetDoctype(&docType);
 +      nsIContent* docTypeContent = do_QueryInterface(docType);
        if (docTypeContent) {
          // Already have a doctype, so this is only OK if we're replacing it
          return aIsReplace && docTypeContent == aRefContent;
-@@ -2957,7 +2932,7 @@ PRBool IsAllowedAsChild(nsIContent* aNew
+@@ -2946,7 +2921,7 @@ PRBool IsAllowedAsChild(nsIContent* aNew
          }
          // If we can put this content at the the right place, we might be ok;
          // if not, we bail out.
 -        nsCOMPtr<nsIDOMNode> childNode(do_QueryInterface(childContent));
 +        nsIDOMNode* childNode(do_QueryInterface(childContent));
          PRUint16 type;
          childNode->GetNodeType(&type);
          if (!IsAllowedAsChild(childContent, type, aParent, aDocument,
-@@ -3000,9 +2975,9 @@ nsGenericElement::doReplaceOrInsertBefor
+@@ -2989,9 +2964,9 @@ nsGenericElement::doReplaceOrInsertBefor
  
    // Keep a strong reference to the node that we'll return to ensure it
    // doesn't go away.
 -  nsCOMPtr<nsIDOMNode> returnVal = aReplace ? aRefChild : aNewChild;
 -
 -  nsCOMPtr<nsIContent> refContent;
 +  nsIDOMNode* returnVal = aReplace ? aRefChild : aNewChild;
 +
 +  nsIContent* refContent = nsnull;
    nsresult res = NS_OK;
    PRInt32 insPos;
  
-@@ -3017,7 +2992,7 @@ nsGenericElement::doReplaceOrInsertBefor
+@@ -3006,7 +2981,7 @@ nsGenericElement::doReplaceOrInsertBefor
      }
  
      if (aRefChild == aNewChild) {
 -      NS_ADDREF(*aReturn = aNewChild);
 +      *aReturn = aNewChild;
  
        return NS_OK;
      }
-@@ -3025,7 +3000,7 @@ nsGenericElement::doReplaceOrInsertBefor
+@@ -3014,7 +2989,7 @@ nsGenericElement::doReplaceOrInsertBefor
      insPos = container->GetChildCount();
    }
  
 -  nsCOMPtr<nsIContent> newContent = do_QueryInterface(aNewChild);
 +  nsIContent* newContent = do_QueryInterface(aNewChild);
    if (!newContent) {
      return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
    }
-@@ -3138,7 +3113,7 @@ nsGenericElement::doReplaceOrInsertBefor
+@@ -3127,7 +3102,7 @@ nsGenericElement::doReplaceOrInsertBefor
            return NS_ERROR_DOM_NOT_FOUND_ERR;
          }
  
 -        nsCOMPtr<nsIDOMNode> tmpNode = do_QueryInterface(childContent);
 +        nsIDOMNode* tmpNode = do_QueryInterface(childContent);
          PRUint16 tmpType = 0;
          tmpNode->GetNodeType(&tmpType);
  
-@@ -3218,7 +3193,7 @@ nsGenericElement::doReplaceOrInsertBefor
+@@ -3207,7 +3182,7 @@ nsGenericElement::doReplaceOrInsertBefor
      NS_ENSURE_SUCCESS(res, res);
    }
  
 -  returnVal.swap(*aReturn);
 +  swap(returnVal, *aReturn);
  
    return res;
  }
-@@ -3237,7 +3212,7 @@ nsGenericElement::doRemoveChild(nsIDOMNo
+@@ -3226,7 +3201,7 @@ nsGenericElement::doRemoveChild(nsIDOMNo
  
    nsINode* container = NODE_FROM(aParent, aDocument);
  
 -  nsCOMPtr<nsIContent> content = do_QueryInterface(aOldChild);
 +  nsIContent* content = do_QueryInterface(aOldChild);
    // fix children to be a passed argument
    PRInt32 index = container->IndexOf(content);
    if (index == -1) {
-@@ -3248,7 +3223,6 @@ nsGenericElement::doRemoveChild(nsIDOMNo
+@@ -3237,7 +3212,6 @@ nsGenericElement::doRemoveChild(nsIDOMNo
    nsresult rv = container->RemoveChildAt(index, PR_TRUE);
  
    *aReturn = aOldChild;
 -  NS_ADDREF(aOldChild);
  
    return rv;
  }
-@@ -3323,12 +3297,12 @@ nsGenericElement::AddScriptEventListener
+@@ -3312,12 +3286,12 @@ nsGenericElement::AddScriptEventListener
    }
  
    NS_PRECONDITION(aEventName, "Must have event name!");
 -  nsCOMPtr<nsISupports> target;
 +  nsISupports* target = nsnull;
    PRBool defer = PR_TRUE;
 -  nsCOMPtr<nsIEventListenerManager> manager;
 -
@@ -903,176 +892,176 @@ diff --git a/content/base/src/nsGenericE
 -                                               getter_AddRefs(target),
 +  nsIEventListenerManager* manager = nsnull;
 +
 +  nsresult rv = GetEventListenerManagerForAttr(&manager,
 +                                               &target,
                                                 &defer);
    NS_ENSURE_SUCCESS(rv, rv);
  
-@@ -3479,10 +3453,10 @@ nsGenericElement::SetAttrAndNotify(PRInt
+@@ -3468,10 +3442,10 @@ nsGenericElement::SetAttrAndNotify(PRInt
      }
    }
    else {
 -    nsCOMPtr<nsINodeInfo> ni;
 +    nsINodeInfo* ni = nsnull;
      rv = mNodeInfo->NodeInfoManager()->GetNodeInfo(aName, aPrefix,
                                                     aNamespaceID,
 -                                                   getter_AddRefs(ni));
 +                                                   &ni);
      NS_ENSURE_SUCCESS(rv, rv);
  
      rv = mAttrsAndChildren.SetAndTakeAttr(ni, aParsedValue);
-@@ -3490,7 +3464,7 @@ nsGenericElement::SetAttrAndNotify(PRInt
+@@ -3479,7 +3453,7 @@ nsGenericElement::SetAttrAndNotify(PRInt
    NS_ENSURE_SUCCESS(rv, rv);
  
    if (document) {
 -    nsRefPtr<nsXBLBinding> binding =
 +    nsXBLBinding* binding =
        document->BindingManager()->GetBinding(this);
      if (binding) {
        binding->AttributeChanged(aName, aNamespaceID, PR_FALSE, aNotify);
-@@ -3512,10 +3486,10 @@ nsGenericElement::SetAttrAndNotify(PRInt
+@@ -3501,10 +3475,10 @@ nsGenericElement::SetAttrAndNotify(PRInt
  
      nsAutoString attrName;
      aName->ToString(attrName);
 -    nsCOMPtr<nsIDOMAttr> attrNode;
 +    nsIDOMAttr* attrNode = nsnull;
      nsAutoString ns;
      nsContentUtils::NameSpaceManager()->GetNameSpaceURI(aNamespaceID, ns);
 -    GetAttributeNodeNS(ns, attrName, getter_AddRefs(attrNode));
 +    GetAttributeNodeNS(ns, attrName, &attrNode);
      mutation.mRelatedNode = attrNode;
  
      mutation.mAttrName = aName;
-@@ -3575,7 +3549,7 @@ nsGenericElement::GetEventListenerManage
+@@ -3564,7 +3538,7 @@ nsGenericElement::GetEventListenerManage
  {
    nsresult rv = GetListenerManager(PR_TRUE, aManager);
    if (NS_SUCCEEDED(rv)) {
 -    NS_ADDREF(*aTarget = static_cast<nsIContent*>(this));
 +    *aTarget = static_cast<nsIContent*>(this);
    }
    *aDefer = PR_TRUE;
    return rv;
-@@ -3720,13 +3694,13 @@ nsGenericElement::UnsetAttr(PRInt32 aNam
+@@ -3709,13 +3683,13 @@ nsGenericElement::UnsetAttr(PRInt32 aNam
                                           this);
  
    // Grab the attr node if needed before we remove it from the attr map
 -  nsCOMPtr<nsIDOMAttr> attrNode;
 +  nsIDOMAttr* attrNode = nsnull;
    if (hasMutationListeners) {
      nsAutoString attrName;
      aName->ToString(attrName);
      nsAutoString ns;
      nsContentUtils::NameSpaceManager()->GetNameSpaceURI(aNameSpaceID, ns);
 -    GetAttributeNodeNS(ns, attrName, getter_AddRefs(attrNode));
 +    GetAttributeNodeNS(ns, attrName, &attrNode);
    }
  
    // Clear binding to nsIDOMNamedNodeMap
-@@ -3740,7 +3714,7 @@ nsGenericElement::UnsetAttr(PRInt32 aNam
+@@ -3729,7 +3703,7 @@ nsGenericElement::UnsetAttr(PRInt32 aNam
    NS_ENSURE_SUCCESS(rv, rv);
  
    if (document) {
 -    nsRefPtr<nsXBLBinding> binding =
 +    nsXBLBinding* binding =
        document->BindingManager()->GetBinding(this);
      if (binding)
        binding->AttributeChanged(aName, aNameSpaceID, PR_TRUE, aNotify);
-@@ -3758,7 +3732,7 @@ nsGenericElement::UnsetAttr(PRInt32 aNam
+@@ -3747,7 +3721,7 @@ nsGenericElement::UnsetAttr(PRInt32 aNam
    }
  
    if (hasMutationListeners) {
 -    nsCOMPtr<nsIDOMEventTarget> node =
 +    nsIDOMEventTarget* node =
        do_QueryInterface(static_cast<nsIContent *>(this));
      nsMutationEvent mutation(PR_TRUE, NS_MUTATION_ATTRMODIFIED);
  
-@@ -3906,9 +3880,9 @@ nsGenericElement::List(FILE* out, PRInt3
+@@ -3895,9 +3869,9 @@ nsGenericElement::List(FILE* out, PRInt3
      // Note: not listing nsIAnonymousContentCreator-created content...
  
      nsBindingManager* bindingManager = document->BindingManager();
 -    nsCOMPtr<nsIDOMNodeList> anonymousChildren;
 +    nsIDOMNodeList* anonymousChildren = nsnull;
      bindingManager->GetAnonymousNodesFor(nonConstThis,
 -                                         getter_AddRefs(anonymousChildren));
 +                                         &anonymousChildren);
  
      if (anonymousChildren) {
        anonymousChildren->GetLength(&length);
-@@ -3917,9 +3891,9 @@ nsGenericElement::List(FILE* out, PRInt3
+@@ -3906,9 +3880,9 @@ nsGenericElement::List(FILE* out, PRInt3
          fputs("anonymous-children<\n", out);
  
          for (i = 0; i < length; ++i) {
 -          nsCOMPtr<nsIDOMNode> node;
 -          anonymousChildren->Item(i, getter_AddRefs(node));
 -          nsCOMPtr<nsIContent> child = do_QueryInterface(node);
 +          nsIDOMNode* node = nsnull;
 +          anonymousChildren->Item(i, &node);
 +          nsIContent* child = do_QueryInterface(node);
            child->List(out, aIndent + 1);
          }
  
-@@ -3929,9 +3903,9 @@ nsGenericElement::List(FILE* out, PRInt3
+@@ -3918,9 +3892,9 @@ nsGenericElement::List(FILE* out, PRInt3
      }
  
      if (bindingManager->HasContentListFor(nonConstThis)) {
 -      nsCOMPtr<nsIDOMNodeList> contentList;
 +      nsIDOMNodeList* contentList = nsnull;
        bindingManager->GetContentListFor(nonConstThis,
 -                                        getter_AddRefs(contentList));
 +                                        &contentList);
  
        NS_ASSERTION(contentList != nsnull, "oops, binding manager lied");
  
-@@ -3941,9 +3915,9 @@ nsGenericElement::List(FILE* out, PRInt3
+@@ -3930,9 +3904,9 @@ nsGenericElement::List(FILE* out, PRInt3
          fputs("content-list<\n", out);
  
          for (i = 0; i < length; ++i) {
 -          nsCOMPtr<nsIDOMNode> node;
 -          contentList->Item(i, getter_AddRefs(node));
 -          nsCOMPtr<nsIContent> child = do_QueryInterface(node);
 +          nsIDOMNode* node = nsnull;
 +          contentList->Item(i, &node);
 +          nsIContent* child = do_QueryInterface(node);
            child->List(out, aIndent + 1);
          }
  
-@@ -4041,8 +4015,8 @@ nsGenericElement::PreHandleEventForLinks
+@@ -4030,8 +4004,8 @@ nsGenericElement::PreHandleEventForLinks
    }
  
    // Make sure we meet the preconditions before continuing
 -  nsCOMPtr<nsIURI> absURI;
 -  if (!CheckHandleEventForLinksPrecondition(aVisitor, getter_AddRefs(absURI))) {
 +  nsIURI* absURI = nsnull;
 +  if (!CheckHandleEventForLinksPrecondition(aVisitor, &absURI)) {
      return NS_OK;
    }
  
-@@ -4096,8 +4070,8 @@ nsGenericElement::PostHandleEventForLink
+@@ -4085,8 +4059,8 @@ nsGenericElement::PostHandleEventForLink
    }
  
    // Make sure we meet the preconditions before continuing
 -  nsCOMPtr<nsIURI> absURI;
 -  if (!CheckHandleEventForLinksPrecondition(aVisitor, getter_AddRefs(absURI))) {
 +  nsIURI* absURI = nsnull;
 +  if (!CheckHandleEventForLinksPrecondition(aVisitor, &absURI)) {
      return NS_OK;
    }
  
-@@ -4124,7 +4098,7 @@ nsGenericElement::PostHandleEventForLink
+@@ -4113,7 +4087,7 @@ nsGenericElement::PostHandleEventForLink
                PRBool isActive = PR_FALSE;
                focusController->GetActive(&isActive);
                if (!isActive) {
 -                nsCOMPtr<nsIDOMElement> domElement = do_QueryInterface(this);
 +                nsIDOMElement* domElement = do_QueryInterface(this);
                  if(domElement)
                    focusController->SetFocusedElement(domElement);
                  break;
-@@ -4148,7 +4122,7 @@ nsGenericElement::PostHandleEventForLink
+@@ -4137,7 +4111,7 @@ nsGenericElement::PostHandleEventForLink
        }
  
        // The default action is simply to dispatch DOMActivate
 -      nsCOMPtr<nsIPresShell> shell = aVisitor.mPresContext->GetPresShell();
 +      nsIPresShell* shell = aVisitor.mPresContext->GetPresShell();
        if (shell) {
          // single-click
          nsEventStatus status = nsEventStatus_eIgnore;
@@ -1102,21 +1091,24 @@ diff --git a/content/base/src/nsGenericE
   */
  
 -class nsNodeWeakReference : public nsIWeakReference
 +class nsNodeWeakReference : public XPCOMGCFinalizedObject, public nsIWeakReference
  {
  public:
    nsNodeWeakReference(nsINode* aNode)
 -    : mNode(aNode)
+-  {
+-  }
+-
+-  ~nsNodeWeakReference();
 +    : mRef(NS_GetGC()->GetWeakRef(aNode))
-   {
-   }
- 
--  ~nsNodeWeakReference();
++  {
++  }
++
 +  ~nsNodeWeakReference()
 +  {
 +  }
  
    // nsISupports
    NS_DECL_ISUPPORTS
 @@ -161,19 +163,14 @@ public:
    // nsIWeakReference
@@ -1176,33 +1168,34 @@ diff --git a/content/base/src/nsGenericE
 -class nsNSElementTearoff : public nsIDOMNSElement
 +class nsNSElementTearoff : public XPCOMGCFinalizedObject, public nsIDOMNSElement
  {
  public:
    NS_DECL_CYCLE_COLLECTING_ISUPPORTS
 diff --git a/content/base/src/nsNodeUtils.cpp b/content/base/src/nsNodeUtils.cpp
 --- a/content/base/src/nsNodeUtils.cpp
 +++ b/content/base/src/nsNodeUtils.cpp
-@@ -184,60 +184,6 @@ nsNodeUtils::ParentChainChanged(nsIConte
+@@ -184,61 +184,6 @@ nsNodeUtils::ParentChainChanged(nsIConte
    }
  }
  
 -void
 -nsNodeUtils::LastRelease(nsINode* aNode)
 -{
 -  nsINode::nsSlots* slots = aNode->GetExistingSlots();
 -  if (slots) {
 -    if (!slots->mMutationObservers.IsEmpty()) {
 -      NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS(slots->mMutationObservers,
 -                                         nsIMutationObserver,
 -                                         NodeWillBeDestroyed, (aNode));
 -    }
 -
 -    PtrBits flags = slots->mFlags | NODE_DOESNT_HAVE_SLOTS;
--    delete slots;
+-    delete slots; // Calls destructor and sets size to *slots.
+-    size_t* sz = reinterpret_cast<size_t*>(slots);
 -    aNode->mFlagsOrSlots = flags;
 -  }
 -
 -  // Kill properties first since that may run external code, so we want to
 -  // be in as complete state as possible at that time.
 -  if (aNode->IsNodeOfType(nsINode::eDOCUMENT)) {
 -    // Delete all properties before tearing down the document. Some of the
 -    // properties are bound to nsINode objects and the destructor functions of
@@ -1237,128 +1230,128 @@ diff --git a/content/base/src/nsNodeUtil
 -  }
 -
 -  delete aNode;
 -}
 -
  static nsresult
  SetUserDataProperty(PRUint16 aCategory, nsINode *aNode, nsIAtom *aKey,
                      nsISupports* aValue, void** aOldValue)
-@@ -248,7 +194,6 @@ SetUserDataProperty(PRUint16 aCategory, 
+@@ -249,7 +194,6 @@ SetUserDataProperty(PRUint16 aCategory, 
    NS_ENSURE_SUCCESS(rv, rv);
  
    // Property table owns it now.
 -  NS_ADDREF(aValue);
  
    return NS_OK;
  }
-@@ -261,7 +206,7 @@ nsNodeUtils::SetUserData(nsINode *aNode,
+@@ -262,7 +206,7 @@ nsNodeUtils::SetUserData(nsINode *aNode,
  {
    *aResult = nsnull;
  
 -  nsCOMPtr<nsIAtom> key = do_GetAtom(aKey);
 +  nsIAtom* key = do_GetAtom(aKey);
    if (!key) {
      return NS_ERROR_OUT_OF_MEMORY;
    }
-@@ -277,12 +222,12 @@ nsNodeUtils::SetUserData(nsINode *aNode,
+@@ -278,12 +222,12 @@ nsNodeUtils::SetUserData(nsINode *aNode,
    }
  
    // Take over ownership of the old data from the property table.
 -  nsCOMPtr<nsIVariant> oldData = dont_AddRef(static_cast<nsIVariant*>(data));
 +  nsIVariant* oldData = dont_AddRef(static_cast<nsIVariant*>(data));
  
    if (aData && aHandler) {
 -    nsCOMPtr<nsIDOMUserDataHandler> oldHandler;
 +    nsIDOMUserDataHandler* oldHandler = nsnull;
      rv = SetUserDataProperty(DOM_USER_DATA_HANDLER, aNode, key, aHandler,
 -                             getter_AddRefs(oldHandler));
 +                             (void**)&oldHandler);
      if (NS_FAILED(rv)) {
        // We failed to set the handler, remove the data.
        aNode->DeleteProperty(DOM_USER_DATA, key);
-@@ -294,7 +239,7 @@ nsNodeUtils::SetUserData(nsINode *aNode,
+@@ -295,7 +239,7 @@ nsNodeUtils::SetUserData(nsINode *aNode,
      aNode->DeleteProperty(DOM_USER_DATA_HANDLER, key);
    }
  
 -  oldData.swap(*aResult);
 +  swap(oldData, *aResult);
  
    return NS_OK;
  }
-@@ -304,14 +249,13 @@ nsNodeUtils::GetUserData(nsINode *aNode,
+@@ -305,14 +249,13 @@ nsNodeUtils::GetUserData(nsINode *aNode,
  nsNodeUtils::GetUserData(nsINode *aNode, const nsAString &aKey,
                           nsIVariant **aResult)
  {
 -  nsCOMPtr<nsIAtom> key = do_GetAtom(aKey);
 +  nsIAtom* key = do_GetAtom(aKey);
    if (!key) {
      return NS_ERROR_OUT_OF_MEMORY;
    }
  
    *aResult = static_cast<nsIVariant*>
                          (aNode->GetProperty(DOM_USER_DATA, key));
 -  NS_IF_ADDREF(*aResult);
  
    return NS_OK;
  }
-@@ -326,10 +270,10 @@ CallHandler(void *aObject, nsIAtom *aKey
+@@ -327,10 +270,10 @@ CallHandler(void *aObject, nsIAtom *aKey
  CallHandler(void *aObject, nsIAtom *aKey, void *aHandler, void *aData)
  {
    nsHandlerData *handlerData = static_cast<nsHandlerData*>(aData);
 -  nsCOMPtr<nsIDOMUserDataHandler> handler =
 +  nsIDOMUserDataHandler* handler =
      static_cast<nsIDOMUserDataHandler*>(aHandler);
    nsINode *node = static_cast<nsINode*>(aObject);
 -  nsCOMPtr<nsIVariant> data =
 +  nsIVariant* data =
      static_cast<nsIVariant*>(node->GetProperty(DOM_USER_DATA, aKey));
    NS_ASSERTION(data, "Handler without data?");
  
-@@ -353,7 +297,7 @@ nsNodeUtils::CallUserDataHandlers(nsCOMA
+@@ -354,7 +297,7 @@ nsNodeUtils::CallUserDataHandlers(nsCOMA
  
    // Keep the document alive, just in case one of the handlers causes it to go
    // away.
 -  nsCOMPtr<nsIDocument> ownerDoc = aOwnerDocument;
 +  nsIDocument* ownerDoc = aOwnerDocument;
  
    nsHandlerData handlerData;
    handlerData.mOperation = aOperation;
-@@ -384,10 +328,10 @@ nsNodeUtils::CloneNodeImpl(nsINode *aNod
+@@ -385,10 +328,10 @@ nsNodeUtils::CloneNodeImpl(nsINode *aNod
  {
    *aResult = nsnull;
  
 -  nsCOMPtr<nsIDOMNode> newNode;
 +  nsIDOMNode* newNode = nsnull;
    nsCOMArray<nsINode> nodesWithProperties;
    nsresult rv = Clone(aNode, aDeep, nsnull, nodesWithProperties,
 -                      getter_AddRefs(newNode));
 +                      &newNode);
    NS_ENSURE_SUCCESS(rv, rv);
  
    nsIDocument *ownerDoc = aNode->GetOwnerDoc();
-@@ -397,7 +341,7 @@ nsNodeUtils::CloneNodeImpl(nsINode *aNod
+@@ -398,7 +341,7 @@ nsNodeUtils::CloneNodeImpl(nsINode *aNod
      NS_ENSURE_SUCCESS(rv, rv);
    }
  
 -  newNode.swap(*aResult);
 +  swap(newNode, *aResult);
  
    return NS_OK;
  }
-@@ -427,7 +371,7 @@ PLDHashOperator PR_CALLBACK
+@@ -428,7 +371,7 @@ PLDHashOperator PR_CALLBACK
  PLDHashOperator PR_CALLBACK
  AdoptFunc(nsAttrHashKey::KeyType aKey, nsIDOMNode *aData, void* aUserArg)
  {
 -  nsCOMPtr<nsIAttribute> attr = do_QueryInterface(aData);
 +  nsIAttribute* attr = do_QueryInterface(aData);
    NS_ASSERTION(attr, "non-nsIAttribute somehow made it into the hashmap?!");
  
    AdoptFuncData *data = static_cast<AdoptFuncData*>(aUserArg);
-@@ -435,18 +379,18 @@ AdoptFunc(nsAttrHashKey::KeyType aKey, n
+@@ -436,18 +379,18 @@ AdoptFunc(nsAttrHashKey::KeyType aKey, n
    // If we were passed an element we need to clone the attribute nodes and
    // insert them into the element.
    PRBool clone = data->mElement != nsnull;
 -  nsCOMPtr<nsIDOMNode> node;
 +  nsIDOMNode* node = nsnull;
    nsresult rv = nsNodeUtils::CloneAndAdopt(attr, clone, PR_TRUE,
                                             data->mNewNodeInfoManager,
                                             data->mCx, data->mOldScope,
@@ -1371,32 +1364,32 @@ diff --git a/content/base/src/nsNodeUtil
 -    nsCOMPtr<nsIDOMAttr> dummy, attribute = do_QueryInterface(node, &rv);
 +    nsIDOMAttr* dummy = nsnull, *attribute = do_QueryInterface(node, &rv);
      if (NS_SUCCEEDED(rv)) {
 -      rv = data->mElement->SetAttributeNode(attribute, getter_AddRefs(dummy));
 +      rv = data->mElement->SetAttributeNode(attribute, &dummy);
      }
    }
  
-@@ -480,12 +424,12 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -481,12 +424,12 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
  
    // aNode.
    nsINodeInfo *nodeInfo = aNode->mNodeInfo;
 -  nsCOMPtr<nsINodeInfo> newNodeInfo;
 +  nsINodeInfo* newNodeInfo = nsnull;
    if (nodeInfoManager) {
      rv = nodeInfoManager->GetNodeInfo(nodeInfo->NameAtom(),
                                        nodeInfo->GetPrefixAtom(),
                                        nodeInfo->NamespaceID(),
 -                                      getter_AddRefs(newNodeInfo));
 +                                      &newNodeInfo);
      NS_ENSURE_SUCCESS(rv, rv);
  
      nodeInfo = newNodeInfo;
-@@ -495,15 +439,15 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -496,15 +439,15 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
                             static_cast<nsGenericElement*>(aNode) :
                             nsnull;
  
 -  nsCOMPtr<nsINode> clone;
 +  nsINode* clone = nsnull;
    if (aClone) {
 -    rv = aNode->Clone(nodeInfo, getter_AddRefs(clone));
 +    rv = aNode->Clone(nodeInfo, &clone);
@@ -1405,85 +1398,85 @@ diff --git a/content/base/src/nsNodeUtil
      if (aParent) {
        // If we're cloning we need to insert the cloned children into the cloned
        // parent.
 -      nsCOMPtr<nsIContent> cloneContent = do_QueryInterface(clone, &rv);
 +      nsIContent* cloneContent = do_QueryInterface(clone, &rv);
        NS_ENSURE_SUCCESS(rv, rv);
  
        rv = aParent->AppendChildTo(cloneContent, PR_FALSE);
-@@ -517,7 +461,7 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -518,7 +461,7 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
      }
    }
    else if (nodeInfoManager) {
 -    nsCOMPtr<nsISupports> oldRef;
 +    nsISupports* oldRef = nsnull;
      nsIDocument* oldDoc = aNode->GetOwnerDoc();
      if (oldDoc) {
        oldRef = oldDoc->GetReference(aNode);
-@@ -536,8 +480,8 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -537,8 +480,8 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
  
        nsPIDOMWindow* window = newDoc->GetInnerWindow();
        if (window) {
 -        nsCOMPtr<nsIEventListenerManager> elm;
 -        aNode->GetListenerManager(PR_FALSE, getter_AddRefs(elm));
 +        nsIEventListenerManager* elm = nsnull;
 +        aNode->GetListenerManager(PR_FALSE, &elm);
          if (elm) {
            window->SetMutationListeners(elm->MutationListenerBits());
          }
-@@ -551,9 +495,9 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -552,9 +495,9 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
      if (aCx) {
        nsIXPConnect *xpc = nsContentUtils::XPConnect();
        if (xpc) {
 -        nsCOMPtr<nsIXPConnectJSObjectHolder> oldWrapper;
 +        nsIXPConnectJSObjectHolder* oldWrapper = nsnull;
          rv = xpc->ReparentWrappedNativeIfFound(aCx, aOldScope, aNewScope, aNode,
 -                                               getter_AddRefs(oldWrapper));
 +                                               &oldWrapper);
          if (NS_FAILED(rv)) {
            aNode->mNodeInfo.swap(nodeInfo);
  
-@@ -567,7 +511,7 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -568,7 +511,7 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
      // aNode's attributes.
      const nsDOMAttributeMap *map = elem->GetAttributeMap();
      if (map) {
 -      nsCOMPtr<nsIDOMElement> element;
 +      nsIDOMElement* element = nsnull;
        if (aClone) {
          // If we're cloning we need to insert the cloned attribute nodes into
          // the cloned element.
-@@ -591,11 +535,11 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -592,11 +535,11 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
    //     GetChildAt(0). We can remove this when
    //     https://bugzilla.mozilla.org/show_bug.cgi?id=56758 is fixed.
    if (aClone && aNode->IsNodeOfType(nsINode::eATTRIBUTE)) {
 -    nsCOMPtr<nsINode> attrChildNode = aNode->GetChildAt(0);
 +    nsINode* attrChildNode = aNode->GetChildAt(0);
      // We only need to do this if the child node has properties (because we
      // might need to call a userdata handler).
      if (attrChildNode && attrChildNode->HasProperties()) {
 -      nsCOMPtr<nsINode> clonedAttrChildNode = clone->GetChildAt(0);
 +      nsINode* clonedAttrChildNode = clone->GetChildAt(0);
        if (clonedAttrChildNode) {
          PRBool ok = aNodesWithProperties.AppendObject(attrChildNode) &&
                      aNodesWithProperties.AppendObject(clonedAttrChildNode);
-@@ -608,10 +552,10 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -609,10 +552,10 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
      // aNode's children.
      PRUint32 i, length = aNode->GetChildCount();
      for (i = 0; i < length; ++i) {
 -      nsCOMPtr<nsIDOMNode> child;
 +      nsIDOMNode* child = nsnull;
        rv = CloneAndAdopt(aNode->GetChildAt(i), aClone, PR_TRUE, nodeInfoManager,
                           aCx, aOldScope, aNewScope, aNodesWithProperties,
 -                         clone, getter_AddRefs(child));
 +                         clone, &child);
        NS_ENSURE_SUCCESS(rv, rv);
      }
    }
-@@ -657,7 +601,7 @@ nsNodeUtils::UnlinkUserData(nsINode *aNo
+@@ -658,7 +601,7 @@ nsNodeUtils::UnlinkUserData(nsINode *aNo
  
    // Strong reference to the document so that deleting properties can't
    // delete the document.
 -  nsCOMPtr<nsIDocument> document = aNode->GetOwnerDoc();
 +  nsIDocument* document = aNode->GetOwnerDoc();
    if (document) {
      document->PropertyTable()->DeleteAllPropertiesFor(aNode, DOM_USER_DATA);
      document->PropertyTable()->DeleteAllPropertiesFor(aNode,
--- a/nscore-class-annotation-types
+++ b/nscore-class-annotation-types
@@ -1,20 +1,8 @@
-diff --git a/configure.in b/configure.in
---- a/configure.in
-+++ b/configure.in
-@@ -1230,7 +1230,7 @@ if test "$GNU_CC"; then
-     # -Wbad-function-cast - warns when casting a function to a new return type
-     # -Wconversion - complained when char's or short's were used a function args
-     # -Wshadow - removed because it generates more noise than help --pete
--    _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wall -W -Wno-unused -Wpointer-arith -Wcast-align"
-+    _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wall -W -Wno-unused -Wpointer-arith -Wcast-align -Wno-attributes"
- 
-     dnl Turn pedantic on but disable the warnings for long long
-     _PEDANTIC=1
 diff --git a/xpcom/base/nscore.h b/xpcom/base/nscore.h
 --- a/xpcom/base/nscore.h
 +++ b/xpcom/base/nscore.h
 @@ -471,4 +471,29 @@ typedef PRUint32 nsrefcnt;
  #define XPCOM_GLUE_AVOID_NSPR
  #endif
  
 +/**
--- a/prerewrite_fixes.patch
+++ b/prerewrite_fixes.patch
@@ -83,17 +83,17 @@ diff --git a/content/html/content/src/ns
 +        nsCOMPtr<nsIDOMNode> retNode;
 +        nsCOMPtr<nsIDOMNode> newRowNode(do_QueryInterface(newRow));
  
          rowGroup->InsertBefore(newRowNode, firstRow, getter_AddRefs(retNode));
  
 diff --git a/content/svg/content/src/nsSVGSVGElement.cpp b/content/svg/content/src/nsSVGSVGElement.cpp
 --- a/content/svg/content/src/nsSVGSVGElement.cpp
 +++ b/content/svg/content/src/nsSVGSVGElement.cpp
-@@ -733,7 +733,10 @@ nsSVGSVGElement::GetCTM(nsIDOMSVGMatrix 
+@@ -737,7 +737,10 @@ nsSVGSVGElement::GetCTM(nsIDOMSVGMatrix 
        break;
      }
  
 -    nsSVGSVGElement *viewportElement = QI_AND_CAST_TO_NSSVGSVGELEMENT(ancestor);
 +    nsSVGSVGElement *viewportElement = 
 +      nsCOMPtr<nsIDOMSVGSVGElement>(do_QueryInterface(ancestor)) 
 +      ? static_cast<nsSVGSVGElement*>(ancestor.get()) 
 +      : nsnull;
@@ -221,61 +221,61 @@ diff --git a/docshell/base/nsDocShell.cp
 +        GetLoadGroup(getter_AddRefs(currentLoadGroup));
 +    NS_ENSURE_SUCCESS(res, NS_ERROR_FAILURE);
  
      if (currentLoadGroup != mLoadGroup) {
          nsLoadFlags loadFlags = 0;
 diff --git a/dom/src/base/nsGlobalWindow.cpp b/dom/src/base/nsGlobalWindow.cpp
 --- a/dom/src/base/nsGlobalWindow.cpp
 +++ b/dom/src/base/nsGlobalWindow.cpp
-@@ -1061,6 +1061,8 @@ nsGlobalWindow::SetScriptContext(PRUint3
+@@ -1067,6 +1067,8 @@ nsGlobalWindow::SetScriptContext(PRUint3
    return NS_OK;
  }
  
 +typedef nsCOMPtr<nsISupports> nsISupportsCOMPtrArray;
 +
  nsresult
  nsGlobalWindow::EnsureScriptEnvironment(PRUint32 aLangID)
  {
-@@ -1090,12 +1092,14 @@ nsGlobalWindow::EnsureScriptEnvironment(
+@@ -1096,12 +1098,14 @@ nsGlobalWindow::EnsureScriptEnvironment(
      // We are being initialized after the document has been setup.
      // Do what would have been done in SetNewDocument had we been around then.
      NS_ASSERTION(!mInnerWindowHolders[lang_ndx], "already have a holder?");
 -    nsCOMPtr<nsISupports> &holder = mInnerWindowHolders[lang_ndx];
 +    nsISupportsCOMPtrArray &holder = mInnerWindowHolders[lang_ndx];
      PRBool isChrome = PR_FALSE; // xxxmarkh - what about this??
      void *&innerGlob = currentInner->mScriptGlobals[lang_ndx];
 +    //hack to avoid rewriting
 +#define GETTER_ADDREFS(x) (getter_AddRefs(x))
      rv = context->CreateNativeGlobalForInner(this, isChrome,
                                               &innerGlob,
 -                                             getter_AddRefs(holder));
 +                                             GETTER_ADDREFS(holder));
      NS_ENSURE_SUCCESS(rv, rv);
      NS_ASSERTION(innerGlob && holder, "Failed to get global and holder");
      rv = context->ConnectToInner(currentInner, mScriptGlobals[lang_ndx]);
-@@ -1306,7 +1310,7 @@ public:
+@@ -1312,7 +1316,7 @@ public:
    NS_DECL_ISUPPORTS
  
    WindowStateHolder(nsGlobalWindow *aWindow,
 -                    nsCOMPtr<nsISupports> aHolders[],
 +                    nsISupportsCOMPtrArray aHolders[],
                      nsNavigator *aNavigator,
                      nsLocation *aLocation,
                      nsIXPConnectJSObjectHolder *aOuterProto);
-@@ -1354,7 +1358,7 @@ NS_DEFINE_STATIC_IID_ACCESSOR(WindowStat
+@@ -1360,7 +1364,7 @@ NS_DEFINE_STATIC_IID_ACCESSOR(WindowStat
  NS_DEFINE_STATIC_IID_ACCESSOR(WindowStateHolder, WINDOWSTATEHOLDER_IID)
  
  WindowStateHolder::WindowStateHolder(nsGlobalWindow *aWindow,
 -                                     nsCOMPtr<nsISupports> aHolders[],
 +                                     nsISupportsCOMPtrArray aHolders[],
                                       nsNavigator *aNavigator,
                                       nsLocation *aLocation,
                                       nsIXPConnectJSObjectHolder *aOuterProto)
-@@ -1672,10 +1676,11 @@ nsGlobalWindow::SetNewDocument(nsIDocume
+@@ -1678,10 +1682,11 @@ nsGlobalWindow::SetNewDocument(nsIDocume
            nsIScriptContext *this_ctx = GetScriptContextInternal(st_id);
            if (this_ctx) {
              void *&newGlobal = newInnerWindow->mScriptGlobals[st_ndx];
 -            nsCOMPtr<nsISupports> &holder = mInnerWindowHolders[st_ndx];
 +            nsISupportsCOMPtrArray &holder = mInnerWindowHolders[st_ndx];
              rv |= this_ctx->CreateNativeGlobalForInner(sgo, isChrome,
                                                         &newGlobal,
 -                                                       getter_AddRefs(holder));
@@ -311,44 +311,44 @@ diff --git a/editor/libeditor/html/nsHTM
 -      nsAutoTrackDOMPoint tracker(mRangeUpdater, &targetNode, &targetOffset);
 +      nsAutoTrackDOMPoint tracker(mRangeUpdater, getter_AddRefs(targetNode), &targetOffset);
        res = DeleteSelection(eNone);
        NS_ENSURE_SUCCESS(res, res);
      }
 diff --git a/editor/libeditor/html/nsHTMLEditRules.cpp b/editor/libeditor/html/nsHTMLEditRules.cpp
 --- a/editor/libeditor/html/nsHTMLEditRules.cpp
 +++ b/editor/libeditor/html/nsHTMLEditRules.cpp
-@@ -2209,7 +2209,7 @@ nsHTMLEditRules::WillDeleteSelection(nsI
+@@ -2216,7 +2216,7 @@ nsHTMLEditRules::WillDeleteSelection(nsI
        nsCOMPtr<nsIDOMNode> selPointNode = startNode;
        PRInt32 selPointOffset = startOffset;
        {
 -        nsAutoTrackDOMPoint tracker(mHTMLEditor->mRangeUpdater, address_of(selPointNode), &selPointOffset);
 +        nsAutoTrackDOMPoint tracker(mHTMLEditor->mRangeUpdater, getter_AddRefs(selPointNode), &selPointOffset);
          res = JoinBlocks(address_of(leftParent), address_of(rightParent), aCancel);
          *aHandled = PR_TRUE;
        }
-@@ -2275,7 +2275,7 @@ nsHTMLEditRules::WillDeleteSelection(nsI
+@@ -2282,7 +2282,7 @@ nsHTMLEditRules::WillDeleteSelection(nsI
        nsCOMPtr<nsIDOMNode> selPointNode = startNode;
        PRInt32 selPointOffset = startOffset;
        {
 -        nsAutoTrackDOMPoint tracker(mHTMLEditor->mRangeUpdater, address_of(selPointNode), &selPointOffset);
 +        nsAutoTrackDOMPoint tracker(mHTMLEditor->mRangeUpdater, getter_AddRefs(selPointNode), &selPointOffset);
          res = JoinBlocks(address_of(leftParent), address_of(rightParent), aCancel);
          *aHandled = PR_TRUE;
        }
-@@ -2316,7 +2316,7 @@ nsHTMLEditRules::WillDeleteSelection(nsI
+@@ -2323,7 +2323,7 @@ nsHTMLEditRules::WillDeleteSelection(nsI
    
    {
      // track end location of where we are deleting
 -    nsAutoTrackDOMPoint tracker(mHTMLEditor->mRangeUpdater, address_of(endNode), &endOffset);
 +    nsAutoTrackDOMPoint tracker(mHTMLEditor->mRangeUpdater, getter_AddRefs(endNode), &endOffset);
      // we are handling all ranged deletions directly now.
      *aHandled = PR_TRUE;
      
-@@ -4420,7 +4420,7 @@ nsHTMLEditRules::CreateStyleForInsertTex
+@@ -4427,7 +4427,7 @@ nsHTMLEditRules::CreateStyleForInsertTex
          // This is so we can know where to put the selection after we call
          // RemoveStyleInside().  RemoveStyleInside() could remove any and all of those nodes,
          // so I have to use the range tracking system to find the right spot to put selection.
 -        nsAutoTrackDOMPoint tracker(mHTMLEditor->mRangeUpdater, address_of(newSelParent), &newSelOffset);
 +        nsAutoTrackDOMPoint tracker(mHTMLEditor->mRangeUpdater, getter_AddRefs(newSelParent), &newSelOffset);
          res = mHTMLEditor->RemoveStyleInside(leftNode, item->tag, &(item->attr));
          NS_ENSURE_SUCCESS(res, res);
        }
@@ -468,64 +468,53 @@ diff --git a/js/src/xpconnect/src/xpclog
 +
 +#endif
  JS_BEGIN_EXTERN_C
  
  void   XPC_Log_print(const char *fmt, ...);
 diff --git a/layout/style/nsCSSLoader.cpp b/layout/style/nsCSSLoader.cpp
 --- a/layout/style/nsCSSLoader.cpp
 +++ b/layout/style/nsCSSLoader.cpp
-@@ -1008,7 +1008,7 @@ CSSLoaderImpl::CreateSheet(nsIURI* aURI,
+@@ -993,7 +993,7 @@ CSSLoaderImpl::CreateSheet(nsIURI* aURI,
        if (cache) {
          if (cache->IsEnabled()) {
            sheet = cache->GetStyleSheet(aURI);
 -          LOG(("  From XUL cache: %p", sheet.get()));
 +          //LOG(("  From XUL cache: %p", sheet.get()));
          }
        }
      }
-@@ -1019,7 +1019,7 @@ CSSLoaderImpl::CreateSheet(nsIURI* aURI,
+@@ -1004,7 +1004,7 @@ CSSLoaderImpl::CreateSheet(nsIURI* aURI,
        nsURIAndPrincipalHashKey key(aURI, aLoaderPrincipal);
        
        mCompleteSheets.Get(&key, getter_AddRefs(sheet));
 -      LOG(("  From completed: %p", sheet.get()));
 +      //LOG(("  From completed: %p", sheet.get()));
      
        // Then loading sheets
        if (!sheet && !aSyncLoad) {
-@@ -1028,7 +1028,7 @@ CSSLoaderImpl::CreateSheet(nsIURI* aURI,
+@@ -1013,7 +1013,7 @@ CSSLoaderImpl::CreateSheet(nsIURI* aURI,
          mLoadingDatas.Get(&key, &loadData);
          if (loadData) {
            sheet = loadData->mSheet;
 -          LOG(("  From loading: %p", sheet.get()));
 +          //LOG(("  From loading: %p", sheet.get()));
  
  #ifdef DEBUG
            PRBool debugEqual;
-@@ -1048,7 +1048,7 @@ CSSLoaderImpl::CreateSheet(nsIURI* aURI,
+@@ -1033,7 +1033,7 @@ CSSLoaderImpl::CreateSheet(nsIURI* aURI,
            mPendingDatas.Get(&key, &loadData);
            if (loadData) {
              sheet = loadData->mSheet;
 -            LOG(("  From pending: %p", sheet.get()));
 +            //LOG(("  From pending: %p", sheet.get()));
  
  #ifdef DEBUG
              PRBool debugEqual;
-@@ -1578,8 +1578,8 @@ CSSLoaderImpl::SheetComplete(SheetLoadDa
-     nsTObserverArray<nsICSSLoaderObserver>::ForwardIterator iter(mObservers);
-     nsCOMPtr<nsICSSLoaderObserver> obs;
-     while ((obs = iter.GetNext())) {
--      LOG(("  Notifying global observer 0x%x for data 0x%s.  wasAlternate: %d",
--           obs.get(), data, data->mWasAlternate));
-+      /*LOG(("  Notifying global observer 0x%x for data 0x%s.  wasAlternate: %d",
-+        obs.get(), data, data->mWasAlternate));*/
-       obs->StyleSheetLoaded(data->mSheet, data->mWasAlternate, aStatus);
-     }
-   }
-@@ -1802,8 +1802,8 @@ CSSLoaderImpl::LoadStyleLink(nsIContent*
+@@ -1788,8 +1788,8 @@ CSSLoaderImpl::LoadStyleLink(nsIContent*
    NS_ENSURE_SUCCESS(rv, rv);
  
    if (state == eSheetComplete) {
 -    LOG(("  Sheet already complete: 0x%p",
 -         static_cast<void*>(sheet.get())));
 +    /*LOG(("  Sheet already complete: 0x%p",
 +      static_cast<void*>(sheet.get())));*/
      if (aObserver) {
@@ -552,133 +541,133 @@ diff --git a/layout/style/nsCSSStyleShee
 +#define END_MEDIA_CHANGE(sheet, doc)                           
 +#endif
  
  NS_IMETHODIMP
  nsMediaList::SetMediaText(const nsAString& aMediaText)
 diff --git a/netwerk/cookie/src/nsCookieService.cpp b/netwerk/cookie/src/nsCookieService.cpp
 --- a/netwerk/cookie/src/nsCookieService.cpp
 +++ b/netwerk/cookie/src/nsCookieService.cpp
-@@ -533,7 +533,8 @@ nsCookieService::InitDB()
+@@ -532,7 +532,8 @@ nsCookieService::InitDB()
          nsCOMPtr<mozIStorageStatement> stmt;
          rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
            "SELECT id, name, value, host, path, expiry, isSecure, isHttpOnly "
 -          "FROM moz_cookies"), getter_AddRefs(stmt));
 +          "FROM moz_cookies"),
 +				      getter_AddRefs(stmt));
          if (NS_SUCCEEDED(rv))
            break;
  
-@@ -908,7 +909,8 @@ nsCookieService::Read()
+@@ -907,7 +908,8 @@ nsCookieService::Read()
    nsCOMPtr<mozIStorageStatement> stmt;
    rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
      "SELECT id, name, value, host, path, expiry, lastAccessed, isSecure, isHttpOnly "
 -    "FROM moz_cookies"), getter_AddRefs(stmt));
 +    "FROM moz_cookies"),
 +				getter_AddRefs(stmt));
    NS_ENSURE_SUCCESS(rv, rv);
  
    nsCAutoString name, value, host, path;
 diff --git a/storage/src/mozStorageConnection.cpp b/storage/src/mozStorageConnection.cpp
 --- a/storage/src/mozStorageConnection.cpp
 +++ b/storage/src/mozStorageConnection.cpp
-@@ -249,7 +249,8 @@ mozStorageConnection::GetSchemaVersion(P
+@@ -243,7 +243,8 @@ mozStorageConnection::GetSchemaVersion(P
  
      nsCOMPtr<mozIStorageStatement> stmt;
      nsresult rv = CreateStatement(NS_LITERAL_CSTRING(
 -        "PRAGMA user_version"), getter_AddRefs(stmt));
 +        "PRAGMA user_version"), 
 +                                  getter_AddRefs(stmt));
      if (NS_FAILED(rv)) return rv;
  
      *version = 0;
 diff --git a/toolkit/components/downloads/src/nsDownloadManager.cpp b/toolkit/components/downloads/src/nsDownloadManager.cpp
 --- a/toolkit/components/downloads/src/nsDownloadManager.cpp
 +++ b/toolkit/components/downloads/src/nsDownloadManager.cpp
-@@ -468,7 +468,8 @@ nsDownloadManager::InitDB(PRBool *aDoImp
+@@ -470,7 +470,8 @@ nsDownloadManager::InitDB(PRBool *aDoImp
          "SELECT id, name, source, target, tempPath, startTime, endTime, state, "
                 "referrer, entityID, currBytes, maxBytes, mimeType, "
                 "preferredApplication, preferredAction, autoResume "
 -        "FROM moz_downloads"), getter_AddRefs(stmt));
 +        "FROM moz_downloads"),
 +                                    getter_AddRefs(stmt));
        if (NS_SUCCEEDED(rv))
          break;
  
-@@ -670,7 +671,8 @@ nsDownloadManager::RestoreDatabaseState(
+@@ -689,7 +690,8 @@ nsDownloadManager::RestoreDatabaseState(
      "SET autoResume = ?1 "
      "WHERE state = ?2 "
        "OR state = ?3 "
 -      "OR state = ?4"), getter_AddRefs(stmt));
 +      "OR state = ?4"),
 +                                getter_AddRefs(stmt));
    NS_ENSURE_SUCCESS(rv, rv);
  
-   PRInt32 i = 0;
-@@ -697,7 +699,8 @@ nsDownloadManager::RestoreActiveDownload
+   i = 0;
+@@ -716,7 +718,8 @@ nsDownloadManager::RestoreActiveDownload
      "SELECT id "
      "FROM moz_downloads "
      "WHERE (state = ?1 AND LENGTH(entityID) > 0) "
 -      "OR autoResume != ?2"), getter_AddRefs(stmt));
 +    "OR autoResume != ?2"),
 +                                         getter_AddRefs(stmt));
    NS_ENSURE_SUCCESS(rv, rv);
  
    rv = stmt->BindInt32Parameter(0, nsIDownloadManager::DOWNLOAD_PAUSED);
-@@ -741,7 +744,8 @@ nsDownloadManager::AddDownloadToDB(const
+@@ -760,7 +763,8 @@ nsDownloadManager::AddDownloadToDB(const
      "INSERT INTO moz_downloads "
      "(name, source, target, tempPath, startTime, endTime, state, "
       "mimeType, preferredApplication, preferredAction) "
 -    "VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)"), getter_AddRefs(stmt));
 +    "VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)"),
 +                                         getter_AddRefs(stmt));
    NS_ENSURE_SUCCESS(rv, 0);
  
    PRInt32 i = 0;
-@@ -835,7 +839,8 @@ nsDownloadManager::Init()
+@@ -854,7 +858,8 @@ nsDownloadManager::Init()
      "SET tempPath = ?1, startTime = ?2, endTime = ?3, state = ?4, "
          "referrer = ?5, entityID = ?6, currBytes = ?7, maxBytes = ?8, "
          "autoResume = ?9 "
 -    "WHERE id = ?10"), getter_AddRefs(mUpdateDownloadStatement));
 +    "WHERE id = ?10"),
 +                                getter_AddRefs(mUpdateDownloadStatement));
    NS_ENSURE_SUCCESS(rv, rv);
  
    // Do things *after* initializing various download manager properties such as
-@@ -890,7 +895,8 @@ nsDownloadManager::GetDownloadFromDB(PRU
+@@ -909,7 +914,8 @@ nsDownloadManager::GetDownloadFromDB(PRU
             "entityID, currBytes, maxBytes, mimeType, preferredAction, "
             "preferredApplication, autoResume "
      "FROM moz_downloads "
 -    "WHERE id = ?1"), getter_AddRefs(stmt));
 +    "WHERE id = ?1"), 
 +                                         getter_AddRefs(stmt));
    NS_ENSURE_SUCCESS(rv, rv);
  
    rv = stmt->BindInt64Parameter(0, aID);
-@@ -1418,7 +1424,8 @@ nsDownloadManager::RemoveDownload(PRUint
+@@ -1437,7 +1443,8 @@ nsDownloadManager::RemoveDownload(PRUint
    nsCOMPtr<mozIStorageStatement> stmt;
    nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
      "DELETE FROM moz_downloads "
 -    "WHERE id = ?1"), getter_AddRefs(stmt));
 +    "WHERE id = ?1"), 
 +                                         getter_AddRefs(stmt));
    NS_ENSURE_SUCCESS(rv, rv);
  
    rv = stmt->BindInt64Parameter(0, aID); // unsigned; 64-bit to prevent overflow
-@@ -1455,7 +1462,8 @@ nsDownloadManager::CleanUp()
+@@ -1474,7 +1481,8 @@ nsDownloadManager::CleanUp()
        "OR state = ?2 "
        "OR state = ?3 "
        "OR state = ?4 "
 -      "OR state = ?5"), getter_AddRefs(stmt));
 +      "OR state = ?5"),
 +                                         getter_AddRefs(stmt));
    NS_ENSURE_SUCCESS(rv, rv);
    for (PRUint32 i = 0; i < NS_ARRAY_LENGTH(states); ++i) {
      rv = stmt->BindInt32Parameter(i, states[i]);
-@@ -1490,7 +1498,8 @@ nsDownloadManager::GetCanCleanUp(PRBool 
+@@ -1509,7 +1517,8 @@ nsDownloadManager::GetCanCleanUp(PRBool 
        "OR state = ?2 "
        "OR state = ?3 "
        "OR state = ?4 "
 -      "OR state = ?5"), getter_AddRefs(stmt));
 +      "OR state = ?5"),
 +                                         getter_AddRefs(stmt));
    NS_ENSURE_SUCCESS(rv, rv);
    for (PRUint32 i = 0; i < NS_ARRAY_LENGTH(states); ++i) {
@@ -710,51 +699,41 @@ diff --git a/toolkit/components/places/s
 -    if (e)                                                                 \
 -      e->method;                                                           \
    }
  
  #endif
 diff --git a/toolkit/components/places/src/nsNavHistory.cpp b/toolkit/components/places/src/nsNavHistory.cpp
 --- a/toolkit/components/places/src/nsNavHistory.cpp
 +++ b/toolkit/components/places/src/nsNavHistory.cpp
-@@ -999,7 +999,8 @@ nsNavHistory::MigrateV6Up(mozIStorageCon
-   nsCOMPtr<mozIStorageStatement> statement;
-   nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-     "SELECT a.dateAdded, a.lastModified, b.dateAdded, b.lastModified "
--    "FROM moz_annos a, moz_items_annos b"), getter_AddRefs(statement));
-+    "FROM moz_annos a, moz_items_annos b"), 
-+                                         getter_AddRefs(statement));
-   if (NS_FAILED(rv)) {
-     // add dateAdded and lastModified columns to moz_annos
-     rv = aDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-@@ -1039,7 +1040,8 @@ nsNavHistory::CleanUpOnQuit()
+@@ -1072,7 +1072,8 @@ nsNavHistory::CleanUpOnQuit()
    // test for moz_places.user_title
    nsCOMPtr<mozIStorageStatement> statement2;
    nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
 -    "SELECT user_title FROM moz_places"), getter_AddRefs(statement2));
 +    "SELECT user_title FROM moz_places"), 
 +                                         getter_AddRefs(statement2));
    if (NS_SUCCEEDED(rv)) {
      mozStorageTransaction transaction(mDBConn, PR_FALSE);
      // 1. Indexes are moved along with the renamed table. Since we're dropping
-@@ -2905,11 +2907,12 @@ nsNavHistory::RemovePagesFromHost(const 
+@@ -2958,11 +2959,12 @@ nsNavHistory::RemovePagesFromHost(const 
  
    // notify observers
    UpdateBatchScoper batch(*this); // sends Begin/EndUpdateBatch to obsrvrs.
 +  GARBURATOR_HATES_THIS (
    if (deletedURIs.Count()) {
      nsCOMPtr<nsIURI> thisURI;
      for (PRUint32 observerIndex = 0; observerIndex < mObservers.Length();
           observerIndex ++) {
 -      const nsCOMPtr<nsINavHistoryObserver> &obs = mObservers.ElementAt(observerIndex);
 +      const nsCOMPtr<nsINavHistoryObserver> obs = mObservers.ElementAt(observerIndex);
        if (! obs)
          continue;
  
-@@ -2922,6 +2925,7 @@ nsNavHistory::RemovePagesFromHost(const 
+@@ -2975,6 +2977,7 @@ nsNavHistory::RemovePagesFromHost(const 
        }
      }
    }
 +                         )
    return NS_OK;
  }
  
 diff --git a/toolkit/crashreporter/test/TestCrashReporterAPI.cpp b/toolkit/crashreporter/test/TestCrashReporterAPI.cpp
--- a/remove-cyclec.patch
+++ b/remove-cyclec.patch
@@ -2,17 +2,17 @@
 * * *
 * * *
 * * *
 * * *
 
 diff --git a/content/base/public/nsContentUtils.h b/content/base/public/nsContentUtils.h
 --- a/content/base/public/nsContentUtils.h
 +++ b/content/base/public/nsContentUtils.h
-@@ -822,20 +822,6 @@ public:
+@@ -838,20 +838,6 @@ public:
    static PRUint32 GetEventId(nsIAtom* aName);
  
    /**
 -   * Used only during traversal of the XPCOM graph by the cycle
 -   * collector: push a pointer to the listener manager onto the
 -   * children deque, if it exists. Do nothing if there is no listener
 -   * manager.
 -   *
@@ -23,17 +23,17 @@ diff --git a/content/base/public/nsConte
 -   */
 -  static void TraverseListenerManager(nsINode *aNode,
 -                                      nsCycleCollectionTraversalCallback &cb);
 -
 -  /**
     * Get the eventlistener manager for aNode. If a new eventlistener manager
     * was created, aCreated is set to PR_TRUE.
     *
-@@ -978,66 +964,6 @@ public:
+@@ -994,66 +980,6 @@ public:
     * Unbinds the content from the tree and nulls it out if it's not null.
     */
    static void DestroyAnonymousContent(nsCOMPtr<nsIContent>* aContent);
 -
 -  /**
 -   * Keep script object aNewObject, held by aScriptObjectHolder, alive.
 -   *
 -   * NOTE: This currently only supports objects that hold script objects of one
@@ -90,36 +90,36 @@ diff --git a/content/base/public/nsConte
 -   *                            keep alive
 -   * @param aTracer the tracer for aScriptObject
 -   */
 -  static nsresult HoldJSObjects(void* aScriptObjectHolder,
 -                                nsScriptObjectTracer* aTracer);
  
    /**
     * Drop the JS objects held by aScriptObjectHolder.
-@@ -1198,13 +1124,8 @@ private:
+@@ -1238,13 +1164,8 @@ private:
+   static PRBool sInitialized;
  };
  
- 
 -#define NS_HOLD_JS_OBJECTS(obj, clazz)                                         \
 -  nsContentUtils::HoldJSObjects(NS_CYCLE_COLLECTION_UPCAST(obj, clazz),        \
 -                                &NS_CYCLE_COLLECTION_NAME(clazz))
 -
 -#define NS_DROP_JS_OBJECTS(obj, clazz)                                         \
 -  nsContentUtils::DropJSObjects(NS_CYCLE_COLLECTION_UPCAST(obj, clazz))
 -
 +#define NS_HOLD_JS_OBJECTS(obj, clazz) NS_OK
 +#define NS_DROP_JS_OBJECTS(obj, clazz) NS_OK
  
  class nsCxPusher
  {
 diff --git a/content/base/public/nsIContent.h b/content/base/public/nsIContent.h
 --- a/content/base/public/nsIContent.h
 +++ b/content/base/public/nsIContent.h
-@@ -833,38 +833,11 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsIContent
+@@ -812,38 +812,11 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsIContent
  
  // Some cycle-collecting helper macros for nsIContent subclasses
  
 -#define NS_IMPL_CYCLE_COLLECTION_TRAVERSE_LISTENERMANAGER \
 -  if (tmp->HasFlag(NODE_HAS_LISTENERMANAGER)) {           \
 -    nsContentUtils::TraverseListenerManager(tmp, cb);     \
 -  }
 -
@@ -157,17 +157,17 @@ diff --git a/content/base/public/nsICont
 +#define NS_IMPL_CYCLE_COLLECTION_UNLINK_LISTENERMANAGER
 +#define NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
 +#define NS_IMPL_CYCLE_COLLECTION_UNLINK_USERDATA
  
  #endif /* nsIContent_h___ */
 diff --git a/content/base/src/nsContentUtils.cpp b/content/base/src/nsContentUtils.cpp
 --- a/content/base/src/nsContentUtils.cpp
 +++ b/content/base/src/nsContentUtils.cpp
-@@ -3059,25 +3059,6 @@ nsContentUtils::HasMutationListeners(nsI
+@@ -3180,25 +3180,6 @@ nsContentUtils::HasMutationListeners(nsI
    return PR_FALSE;
  }
  
 -/* static */
 -void
 -nsContentUtils::TraverseListenerManager(nsINode *aNode,
 -                                        nsCycleCollectionTraversalCallback &cb)
 -{
@@ -183,17 +183,17 @@ diff --git a/content/base/src/nsContentU
 -  if (PL_DHASH_ENTRY_IS_BUSY(entry)) {
 -    cb.NoteXPCOMChild(entry->mListenerManager);
 -  }
 -}
 -
  nsresult
  nsContentUtils::GetListenerManager(nsINode *aNode,
                                     PRBool aCreateIfNotFound,
-@@ -3540,33 +3521,6 @@ nsContentUtils::DropScriptObject(PRUint3
+@@ -3665,33 +3646,6 @@ nsContentUtils::DropScriptObject(PRUint3
  }
  
  /* static */
 -nsresult
 -nsContentUtils::HoldJSObjects(void* aScriptObjectHolder,
 -                              nsScriptObjectTracer* aTracer)
 -{
 -  nsresult rv = sXPConnect->AddJSHolder(aScriptObjectHolder, aTracer);
@@ -280,28 +280,28 @@ diff --git a/content/base/src/nsDocument
 @@ -155,7 +155,6 @@ static NS_DEFINE_CID(kDOMEventGroupCID, 
  #include "nsLayoutStatics.h"
  #include "nsIJSContextStack.h"
  #include "nsIXPConnect.h"
 -#include "nsCycleCollector.h"
  #include "nsCCUncollectableMarker.h"
  #include "nsIContentPolicy.h"
  
-@@ -793,10 +792,6 @@ nsDocument::~nsDocument()
+@@ -794,10 +793,6 @@ nsDocument::~nsDocument()
    if (gDocumentLeakPRLog)
      PR_LOG(gDocumentLeakPRLog, PR_LOG_DEBUG,
             ("DOCUMENT %p destroyed", this));
 -#endif
 -
 -#ifdef DEBUG
 -  nsCycleCollector_DEBUG_wasFreed(static_cast<nsIDocument*>(this));
  #endif
  
    mInDestructor = PR_TRUE;
-@@ -935,158 +930,6 @@ NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUO
+@@ -939,158 +934,6 @@ NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUO
                                                          nsIDocument,
                                                          nsNodeUtils::LastRelease(this))
  
 -
 -PR_STATIC_CALLBACK(PLDHashOperator)
 -SubDocTraverser(PLDHashTable *table, PLDHashEntryHdr *hdr, PRUint32 number,
 -                void *arg)
 -{
@@ -461,60 +461,65 @@ diff --git a/content/base/src/nsGenericE
 @@ -133,7 +133,6 @@
  
  #include "nsCycleCollectionParticipant.h"
  #include "nsCCUncollectableMarker.h"
 -#include "nsCycleCollector.h"
  
  #ifdef MOZ_SVG
  PRBool NS_SVG_TestFeature(const nsAString &fstr);
-@@ -1084,13 +1083,6 @@ nsGenericElement::nsDOMSlots::nsDOMSlots
+@@ -1108,13 +1107,6 @@ nsGenericElement::nsDOMSlots::nsDOMSlots
  
  nsGenericElement::nsDOMSlots::~nsDOMSlots()
  {
 -  if (mStyle) {
 -    mStyle->DropReference();
 -  }
 -
 -  if (mAttributeMap) {
 -    mAttributeMap->DropReference();
 -  }
  }
  
  nsGenericElement::nsGenericElement(nsINodeInfo *aNodeInfo)
-@@ -1105,9 +1097,6 @@ nsGenericElement::~nsGenericElement()
+@@ -1130,9 +1122,6 @@ nsGenericElement::~nsGenericElement()
  {
    NS_PRECONDITION(!IsInDoc(),
                    "Please remove this from the document properly");
 -#ifdef DEBUG
 -  nsCycleCollector_DEBUG_wasFreed(static_cast<nsINode*>(this));
 -#endif
  }
  
  NS_IMETHODIMP
-@@ -2134,9 +2123,6 @@ nsGenericElement::UnbindFromTree(PRBool 
+@@ -2159,9 +2148,6 @@ nsGenericElement::UnbindFromTree(PRBool 
    }
  
    nsNodeUtils::ParentChainChanged(this);
 -#ifdef DEBUG
 -  nsCycleCollector_DEBUG_shouldBeFreed(static_cast<nsINode*>(this));
 -#endif
  }
  
  nsresult
-@@ -3345,80 +3331,6 @@ nsGenericElement::doRemoveChild(nsIDOMNo
+@@ -3370,85 +3356,6 @@ nsGenericElement::doRemoveChild(nsIDOMNo
  // nsISupports implementation
  
  NS_IMPL_CYCLE_COLLECTION_CLASS(nsGenericElement)
 -
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsGenericElement)
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_LISTENERMANAGER
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_USERDATA
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
 -
+-  if (tmp->HasProperties() && tmp->IsNodeOfType(nsINode::eXUL)) {
+-    tmp->DeleteProperty(nsGkAtoms::contextmenulistener);
+-    tmp->DeleteProperty(nsGkAtoms::popuplistener);
+-  }
+-
 -  // Unlink child content (and unbind our subtree).
 -  {
 -    PRUint32 i;
 -    PRUint32 kids = tmp->mAttrsAndChildren.ChildCount();
 -    for (i = kids; i > 0; i--) {
 -      // We could probably do a non-deep unbind here when IsInDoc is false
 -      // for better performance.
 -      tmp->mAttrsAndChildren.ChildAt(i-1)->UnbindFromTree();
@@ -579,17 +584,17 @@ diff --git a/content/base/src/nsGenericE
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 -
  
  NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsGenericElement)
    NS_INTERFACE_MAP_ENTRY(nsIContent)
 diff --git a/content/base/src/nsNodeUtils.cpp b/content/base/src/nsNodeUtils.cpp
 --- a/content/base/src/nsNodeUtils.cpp
 +++ b/content/base/src/nsNodeUtils.cpp
-@@ -378,30 +378,6 @@ nsNodeUtils::CallUserDataHandlers(nsCOMA
+@@ -395,30 +395,6 @@ nsNodeUtils::CallUserDataHandlers(nsCOMA
    return NS_OK;
  }
  
 -static void
 -NoteUserData(void *aObject, nsIAtom *aKey, void *aXPCOMChild, void *aData)
 -{
 -  nsCycleCollectionTraversalCallback* cb =
 -    static_cast<nsCycleCollectionTraversalCallback*>(aData);
@@ -613,37 +618,37 @@ diff --git a/content/base/src/nsNodeUtil
 -}
 -
  /* static */
  nsresult
  nsNodeUtils::CloneNodeImpl(nsINode *aNode, PRBool aDeep, nsIDOMNode **aResult)
 diff --git a/content/base/src/nsNodeUtils.h b/content/base/src/nsNodeUtils.h
 --- a/content/base/src/nsNodeUtils.h
 +++ b/content/base/src/nsNodeUtils.h
-@@ -242,16 +242,6 @@ public:
+@@ -240,16 +240,6 @@ public:
+   static nsresult CallUserDataHandlers(nsCOMArray<nsINode> &aNodesWithProperties,
+                                        nsIDocument *aOwnerDocument,
                                         PRUint16 aOperation, PRBool aCloned);
- 
-   /**
+-
+-  /**
 -   * Helper for the cycle collector to traverse the DOM UserData and
 -   * UserDataHandlers for aNode.
 -   *
 -   * @param aNode the node to traverse UserData and UserDataHandlers for
 -   * @param aCb the cycle collection callback
 -   */
 -  static void TraverseUserData(nsINode* aNode,
 -                               nsCycleCollectionTraversalCallback &aCb);
--
--  /**
+ 
+   /**
     * A basic implementation of the DOM cloneNode method. Calls nsINode::Clone to
-    * do the actual cloning of the node.
-    *
 diff --git a/content/base/src/nsObjectLoadingContent.cpp b/content/base/src/nsObjectLoadingContent.cpp
 --- a/content/base/src/nsObjectLoadingContent.cpp
 +++ b/content/base/src/nsObjectLoadingContent.cpp
-@@ -1223,12 +1223,6 @@ nsObjectLoadingContent::RemovedFromDocum
+@@ -1225,12 +1225,6 @@ nsObjectLoadingContent::RemovedFromDocum
    }
  }
  
 -void
 -nsObjectLoadingContent::Traverse(nsCycleCollectionTraversalCallback &cb)
 -{
 -  cb.NoteXPCOMChild(mFrameLoader);
 -}
@@ -762,39 +767,35 @@ diff --git a/content/events/src/nsDOMEve
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mExplicitOriginalTarget)
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  
  // nsIDOMEventInterface
  NS_METHOD nsDOMEvent::GetType(nsAString& aType)
 diff --git a/content/events/src/nsEventListenerManager.cpp b/content/events/src/nsEventListenerManager.cpp
 --- a/content/events/src/nsEventListenerManager.cpp
 +++ b/content/events/src/nsEventListenerManager.cpp
-@@ -399,22 +399,6 @@ NS_INTERFACE_MAP_END
- 
+@@ -392,18 +392,6 @@ NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOU
  NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsEventListenerManager, nsIEventListenerManager)
  NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsEventListenerManager, nsIEventListenerManager)
--
+ 
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsEventListenerManager)
--  PRInt32 i, count = tmp->mListeners.Count();
--  nsListenerStruct *ls;
+-  PRInt32 i, count = tmp->mListeners.Length();
 -  for (i = 0; i < count; i++) {
--    ls = static_cast<nsListenerStruct*>(tmp->mListeners.ElementAt(i));
--    if (ls) {
--      cb.NoteXPCOMChild(ls->mListener.get());
--    }
+-    cb.NoteXPCOMChild(tmp->mListeners.ElementAt(i)->mListener.get());
 -  }  
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 -
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsEventListenerManager)
 -  tmp->Disconnect();
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -
- 
+-
  const EventTypeData*
  nsEventListenerManager::GetTypeDataForIID(const nsIID& aIID)
+ {
 diff --git a/content/events/src/nsEventStateManager.cpp b/content/events/src/nsEventStateManager.cpp
 --- a/content/events/src/nsEventStateManager.cpp
 +++ b/content/events/src/nsEventStateManager.cpp
 @@ -675,66 +675,6 @@ NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOU
  NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsEventStateManager, nsIEventStateManager)
  NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsEventStateManager, nsIEventStateManager)
  
 -PR_STATIC_CALLBACK(PRBool)
@@ -858,21 +859,20 @@ diff --git a/content/events/src/nsEventS
 -
 -
  NS_IMETHODIMP
  nsEventStateManager::PreHandleEvent(nsPresContext* aPresContext,
                                      nsEvent *aEvent,
 diff --git a/content/html/content/src/nsHTMLFormElement.cpp b/content/html/content/src/nsHTMLFormElement.cpp
 --- a/content/html/content/src/nsHTMLFormElement.cpp
 +++ b/content/html/content/src/nsHTMLFormElement.cpp
-@@ -525,25 +525,6 @@ nsHTMLFormElement::Init()
- 
+@@ -526,25 +526,6 @@ nsHTMLFormElement::Init()
  
  // nsISupports
--
+ 
 -PR_STATIC_CALLBACK(PLDHashOperator)
 -ElementTraverser(const nsAString& key, nsIDOMHTMLInputElement* element,
 -                 void* userArg)
 -{
 -  nsCycleCollectionTraversalCallback *cb = 
 -    static_cast<nsCycleCollectionTraversalCallback*>(userArg);
 - 
 -  cb->NoteXPCOMChild(element);
@@ -881,19 +881,20 @@ diff --git a/content/html/content/src/ns
 -
 -NS_IMPL_CYCLE_COLLECTION_CLASS(nsHTMLFormElement)
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsHTMLFormElement,
 -                                                  nsGenericHTMLElement)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mControls,
 -                                                       nsIDOMHTMLCollection)
 -  tmp->mSelectedRadioButtons.EnumerateRead(ElementTraverser, &cb);
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
- 
+-
  NS_IMPL_ADDREF_INHERITED(nsHTMLFormElement, nsGenericElement) 
  NS_IMPL_RELEASE_INHERITED(nsHTMLFormElement, nsGenericElement) 
+ 
 @@ -2076,23 +2057,7 @@ nsFormControlList::FlushPendingNotificat
    }
  }
  
 -PR_STATIC_CALLBACK(PLDHashOperator)
 -ControlTraverser(const nsAString& key, nsISupports* control, void* userArg)
 -{
 -  nsCycleCollectionTraversalCallback *cb = 
@@ -939,17 +940,17 @@ diff --git a/content/html/content/src/ns
 -  tmp->Traverse(cb);
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  
  NS_IMPL_ADDREF_INHERITED(nsHTMLSharedObjectElement, nsGenericElement) 
  NS_IMPL_RELEASE_INHERITED(nsHTMLSharedObjectElement, nsGenericElement) 
 diff --git a/content/html/document/src/nsHTMLDocument.cpp b/content/html/document/src/nsHTMLDocument.cpp
 --- a/content/html/document/src/nsHTMLDocument.cpp
 +++ b/content/html/document/src/nsHTMLDocument.cpp
-@@ -364,39 +364,6 @@ nsHTMLDocument::~nsHTMLDocument()
+@@ -379,39 +379,6 @@ nsHTMLDocument::~nsHTMLDocument()
  }
  
  NS_IMPL_CYCLE_COLLECTION_CLASS(nsHTMLDocument)
 -
 -PR_STATIC_CALLBACK(PLDHashOperator)
 -IdAndNameMapEntryTraverse(PLDHashTable *table, PLDHashEntryHdr *hdr,
 -                          PRUint32 number, void *arg)
 -{
@@ -1095,20 +1096,23 @@ diff --git a/content/xbl/src/nsBindingMa
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSTARRAY_MEMBER(mAttachedStack,
 -                                                    nsXBLBinding)
 -  // No need to traverse mProcessAttachedQueueEvent, since it'll just
 -  // fire at some point.
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  
  NS_IMPL_CYCLE_COLLECTION_CLASS(nsBindingManager)
  
-@@ -1466,42 +1391,6 @@ nsBindingManager::DropDocumentReference(
- }
- 
- void
+@@ -1463,42 +1388,6 @@ nsBindingManager::DropDocumentReference(
+   // Make sure to not run any more XBL constructors
+   mProcessingAttachedStack = PR_TRUE;
+   mDocument = nsnull;
+-}
+-
+-void
 -nsBindingManager::Traverse(nsIContent *aContent,
 -                           nsCycleCollectionTraversalCallback &cb)
 -{
 -  if (!aContent->HasFlag(NODE_MAY_BE_IN_BINDING_MNGR)) {
 -    return;
 -  }
 -
 -  nsXBLBinding *binding = GetBinding(aContent);
@@ -1132,22 +1136,19 @@ diff --git a/content/xbl/src/nsBindingMa
 -    cb.NoteXPCOMChild(aContent);
 -    cb.NoteXPCOMChild(value);
 -  }
 -  if (mWrapperTable.ops &&
 -      (value = LookupObject(mWrapperTable, aContent))) {
 -    cb.NoteXPCOMChild(aContent);
 -    cb.NoteXPCOMChild(value);
 -  }
--}
--
--void
- nsBindingManager::BeginOutermostUpdate()
- {
-   mAttachedStackSizeOnOutermost = mAttachedStack.Length();
+ }
+ 
+ void
 diff --git a/content/xbl/src/nsBindingManager.h b/content/xbl/src/nsBindingManager.h
 --- a/content/xbl/src/nsBindingManager.h
 +++ b/content/xbl/src/nsBindingManager.h
 @@ -189,9 +189,6 @@ public:
                       RuleProcessorData* aData,
                       PRBool* aCutOffInheritance);
  
 -  NS_HIDDEN_(void) Traverse(nsIContent *aContent,
@@ -1553,40 +1554,40 @@ diff --git a/content/xslt/src/xpath/nsXP
 -    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mResultNodes)
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  
  NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsXPathResult, nsIDOMXPathResult)
  NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsXPathResult, nsIDOMXPathResult)
 diff --git a/content/xslt/src/xslt/txMozillaXSLTProcessor.cpp b/content/xslt/src/xslt/txMozillaXSLTProcessor.cpp
 --- a/content/xslt/src/xslt/txMozillaXSLTProcessor.cpp
 +++ b/content/xslt/src/xslt/txMozillaXSLTProcessor.cpp
-@@ -291,23 +291,6 @@ private:
- /**
+@@ -292,23 +292,6 @@ private:
   * txMozillaXSLTProcessor
   */
--
+ 
 -NS_IMPL_CYCLE_COLLECTION_CLASS(txMozillaXSLTProcessor)
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(txMozillaXSLTProcessor)
 -    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mEmbeddedStylesheetRoot)
 -    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mSource)
 -    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mPrincipal)
 -    tmp->mVariables.clear();
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(txMozillaXSLTProcessor)
 -    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mEmbeddedStylesheetRoot)
 -    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mSource)
 -    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mPrincipal)
 -    txOwningExpandedNameMap<txIGlobalParameter>::iterator iter(tmp->mVariables);
 -    while (iter.next()) {
 -        cb.NoteXPCOMChild(static_cast<txVariable*>(iter.value())->getValue());
 -    }
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
- 
+-
  NS_IMPL_CYCLE_COLLECTING_ADDREF(txMozillaXSLTProcessor)
  NS_IMPL_CYCLE_COLLECTING_RELEASE(txMozillaXSLTProcessor)
+ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(txMozillaXSLTProcessor)
 diff --git a/content/xul/content/src/nsXULElement.cpp b/content/xul/content/src/nsXULElement.cpp
 --- a/content/xul/content/src/nsXULElement.cpp
 +++ b/content/xul/content/src/nsXULElement.cpp
 @@ -377,11 +377,6 @@ nsXULElement::QueryInterface(REFNSIID aI
  {
      NS_PRECONDITION(aInstancePtr, "null out param");
  
 -    if (aIID.Equals(NS_GET_IID(nsXPCOMCycleCollectionParticipant))) {
@@ -1621,17 +1622,17 @@ diff --git a/content/xul/content/src/nsX
 -                                                  aHandler,
 -                                                  elem->mHoldsScriptObject);
 -            if (NS_FAILED(rv)) return rv;
 -
 -            elem->mHoldsScriptObject = PR_TRUE;
          }
          attr->mEventHandler = (void *)aHandler;
      }
-@@ -2409,47 +2389,6 @@ nsXULElement::RecompileScriptEventListen
+@@ -2393,47 +2373,6 @@ nsXULElement::RecompileScriptEventListen
      }
  }
  
 -NS_IMPL_CYCLE_COLLECTION_CLASS(nsXULPrototypeNode)
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_NATIVE(nsXULPrototypeNode)
 -    if (tmp->mType == nsXULPrototypeNode::eType_Element) {
 -        static_cast<nsXULPrototypeElement*>(tmp)->Unlink();
 -    }
@@ -1669,29 +1670,29 @@ diff --git a/content/xul/content/src/nsX
 -            static_cast<nsXULPrototypeScript*>(tmp);
 -        NS_IMPL_CYCLE_COLLECTION_TRACE_CALLBACK(script->mScriptObject.mLangID,
 -                                                script->mScriptObject.mObject)
 -    }
 -NS_IMPL_CYCLE_COLLECTION_TRACE_END
  NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(nsXULPrototypeNode, AddRef)
  NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(nsXULPrototypeNode, Release)
  
-@@ -2750,11 +2689,6 @@ void
+@@ -2734,11 +2673,6 @@ void
  void
  nsXULPrototypeElement::Unlink()
  {
 -    if (mHoldsScriptObject) {
 -        nsContentUtils::DropScriptObjects(mScriptTypeID, this,
 -                                          &NS_CYCLE_COLLECTION_NAME(nsXULPrototypeNode));
 -        mHoldsScriptObject = PR_FALSE;
 -    }
      mNumAttributes = 0;
      delete[] mAttributes;
      mAttributes = nsnull;
-@@ -2782,7 +2716,6 @@ nsXULPrototypeScript::nsXULPrototypeScri
+@@ -2766,7 +2700,6 @@ nsXULPrototypeScript::nsXULPrototypeScri
  
  nsXULPrototypeScript::~nsXULPrototypeScript()
  {
 -    Unlink();
  }
  
  nsresult
 diff --git a/content/xul/content/src/nsXULElement.h b/content/xul/content/src/nsXULElement.h
@@ -1742,36 +1743,36 @@ diff --git a/content/xul/content/src/nsX
 -        }
 +        mScriptObject.mObject = aObject;
      }
  
      struct ScriptObjectHolder
 diff --git a/content/xul/document/src/nsXULCommandDispatcher.cpp b/content/xul/document/src/nsXULCommandDispatcher.cpp
 --- a/content/xul/document/src/nsXULCommandDispatcher.cpp
 +++ b/content/xul/document/src/nsXULCommandDispatcher.cpp
-@@ -104,19 +104,6 @@ NS_INTERFACE_MAP_END
- 
+@@ -105,19 +105,6 @@ NS_IMPL_CYCLE_COLLECTING_ADDREF(nsXULCom
  NS_IMPL_CYCLE_COLLECTING_ADDREF(nsXULCommandDispatcher)
  NS_IMPL_CYCLE_COLLECTING_RELEASE(nsXULCommandDispatcher)
--
+ 
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsXULCommandDispatcher)
 -  tmp->Disconnect();
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsXULCommandDispatcher)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDocument)
 -  Updater* updater = tmp->mUpdaters;
 -  while (updater) {
 -    cb.NoteXPCOMChild(updater->mElement);
 -    updater = updater->mNext;
 -  }
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
- 
+-
  void
  nsXULCommandDispatcher::Disconnect()
+ {
 diff --git a/content/xul/document/src/nsXULControllers.cpp b/content/xul/document/src/nsXULControllers.cpp
 --- a/content/xul/document/src/nsXULControllers.cpp
 +++ b/content/xul/document/src/nsXULControllers.cpp
 @@ -98,21 +98,6 @@ NS_NewXULControllers(nsISupports* aOuter
  }
  
  NS_IMPL_CYCLE_COLLECTION_CLASS(nsXULControllers)
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsXULControllers)
@@ -1927,28 +1928,28 @@ diff --git a/content/xul/templates/src/n
 -        mSortState.Traverse(cb);
 -    }
  
      virtual void Uninit(PRBool aIsFinal);
  
 diff --git a/content/xul/templates/src/nsXULSortService.h b/content/xul/templates/src/nsXULSortService.h
 --- a/content/xul/templates/src/nsXULSortService.h
 +++ b/content/xul/templates/src/nsXULSortService.h
-@@ -91,11 +91,6 @@ struct nsSortState
-   nsSortState()
+@@ -92,11 +92,6 @@ struct nsSortState
      : initialized(PR_FALSE)
    {
--  }
+   }
 -  void Traverse(nsCycleCollectionTraversalCallback &cb) const
 -  {
 -    cb.NoteXPCOMChild(processor);
 -    cb.NoteXPCOMChild(lastContainer);
-   }
+-  }
  };
  
+ // information about a particular item to be sorted
 diff --git a/content/xul/templates/src/nsXULTemplateBuilder.cpp b/content/xul/templates/src/nsXULTemplateBuilder.cpp
 --- a/content/xul/templates/src/nsXULTemplateBuilder.cpp
 +++ b/content/xul/templates/src/nsXULTemplateBuilder.cpp
 @@ -229,53 +229,12 @@ nsXULTemplateBuilder::Uninit(PRBool aIsF
      mQueriesCompiled = PR_FALSE;
  }
  
 -static PLDHashOperator
@@ -1999,21 +2000,20 @@ diff --git a/content/xul/templates/src/n
 -    tmp->Traverse(cb);
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  
  NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsXULTemplateBuilder,
                                            nsIXULTemplateBuilder)
 diff --git a/content/xul/templates/src/nsXULTemplateQueryProcessorRDF.cpp b/content/xul/templates/src/nsXULTemplateQueryProcessorRDF.cpp
 --- a/content/xul/templates/src/nsXULTemplateQueryProcessorRDF.cpp
 +++ b/content/xul/templates/src/nsXULTemplateQueryProcessorRDF.cpp
-@@ -87,66 +87,6 @@ nsIRDFResource*           nsXULTemplateQ
- 
+@@ -88,66 +88,6 @@ NS_IMPL_CYCLE_COLLECTION_CLASS(nsXULTemp
  NS_IMPL_CYCLE_COLLECTION_CLASS(nsXULTemplateQueryProcessorRDF)
  NS_IMPL_CYCLE_COLLECTION_UNLINK_0(nsXULTemplateQueryProcessorRDF)
--
+ 
 -PR_STATIC_CALLBACK(PLDHashOperator)
 -BindingDependenciesTraverser(nsISupports* key,
 -                             nsCOMArray<nsXULTemplateResultRDF>* array,
 -                             void* userArg)
 -{
 -    nsCycleCollectionTraversalCallback *cb = 
 -        static_cast<nsCycleCollectionTraversalCallback*>(userArg);
 -
@@ -2063,31 +2063,32 @@ diff --git a/content/xul/templates/src/n
 -        tmp->mMemoryElementToResultMap.EnumerateRead(MemoryElementTraverser,
 -                                                     &cb);
 -    }
 -    if (tmp->mRuleToBindingsMap.IsInitialized()) {
 -        tmp->mRuleToBindingsMap.EnumerateRead(RuleToBindingTraverser, &cb);
 -    }
 -    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mQueries)
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
- 
+-
  NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsXULTemplateQueryProcessorRDF,
                                            nsIXULTemplateQueryProcessor)
+ NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsXULTemplateQueryProcessorRDF,
 diff --git a/dom/src/base/nsGlobalWindow.cpp b/dom/src/base/nsGlobalWindow.cpp
 --- a/dom/src/base/nsGlobalWindow.cpp
 +++ b/dom/src/base/nsGlobalWindow.cpp
-@@ -79,7 +79,6 @@
+@@ -78,7 +78,6 @@
  #endif
  #include "nsContentCID.h"
  #include "nsLayoutStatics.h"
 -#include "nsCycleCollector.h"
  #include "nsCCUncollectableMarker.h"
  
  // Interfaces Needed
-@@ -734,10 +733,6 @@ nsGlobalWindow::~nsGlobalWindow()
+@@ -733,10 +732,6 @@ nsGlobalWindow::~nsGlobalWindow()
  
    CleanUp();
  
 -#ifdef DEBUG
 -  nsCycleCollector_DEBUG_wasFreed(static_cast<nsIScriptGlobalObject*>(this));
 -#endif
 -
    delete mPendingStorageEvents;
@@ -2120,30 +2121,31 @@ diff --git a/dom/src/base/nsGlobalWindow
 -
 -#ifdef DEBUG
 -  if (mDocument)
 -    nsCycleCollector_DEBUG_shouldBeFreed(nsCOMPtr<nsISupports>(do_QueryInterface(mDocument)));
 -#endif
  
    // Remove our reference to the document and the document principal.
    mDocument = nsnull;
-@@ -873,9 +857,6 @@ nsGlobalWindow::FreeInnerObjects(PRBool 
+@@ -878,9 +862,6 @@ nsGlobalWindow::FreeInnerObjects(PRBool 
    }
  #endif
  
 -#ifdef DEBUG
 -  nsCycleCollector_DEBUG_shouldBeFreed(static_cast<nsIScriptGlobalObject*>(this));
 -#endif
  }
  
  //*****************************************************************************
-@@ -912,101 +893,6 @@ NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUO
+@@ -916,102 +897,6 @@ NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOU
+ NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsGlobalWindow, nsIScriptGlobalObject)
  NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsGlobalWindow,
                                             nsIScriptGlobalObject)
- 
+-
 -
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsGlobalWindow)
 -  if (tmp->mDoc && nsCCUncollectableMarker::InGeneration(
 -                     tmp->mDoc->GetMarkedCCGeneration())) {
 -    return NS_OK;
 -  }
 -
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mContext)
@@ -2162,16 +2164,17 @@ diff --git a/dom/src/base/nsGlobalWindow
 -
 -  for (PRUint32 i = 0; i < NS_STID_ARRAY_UBOUND; ++i) {      
 -    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mInnerWindowHolders[i])
 -  }
 -
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOpenerScriptPrincipal)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mListenerManager)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mSessionStorage)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mApplicationCache)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDocumentPrincipal)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDoc)
 -
 -  // Traverse any associated preserved wrappers.
 -  {
 -    if (tmp->mDoc) {
 -      cb.NoteXPCOMChild(tmp->mDoc->GetReference(tmp));
 -    }
@@ -2186,18 +2189,17 @@ diff --git a/dom/src/base/nsGlobalWindow
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDummyJavaPluginOwner)
 -#endif
 -
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 -
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsGlobalWindow)
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mContext)
 -
--  // See comment about traversing mOpener above.
--  // NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOpener)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOpener)
 -
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mControllers)
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mArguments)
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mArgumentsLast)
 -
 -  for (PRUint32 i = 0; i < NS_STID_ARRAY_UBOUND; ++i) {      
 -    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mScriptContexts[i])
 -  }
@@ -2206,16 +2208,17 @@ diff --git a/dom/src/base/nsGlobalWindow
 -
 -  for (PRUint32 i = 0; i < NS_STID_ARRAY_UBOUND; ++i) {      
 -    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mInnerWindowHolders[i])
 -  }
 -
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOpenerScriptPrincipal)
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mListenerManager)
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mSessionStorage)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mApplicationCache)
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDocumentPrincipal)
 -
 -  // Unlink any associated preserved wrapper.
 -  if (tmp->mDoc) {
 -    tmp->mDoc->RemoveReference(tmp);
 -    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDoc)
 -  }
 -
@@ -2228,21 +2231,20 @@ diff --git a/dom/src/base/nsGlobalWindow
 -  if (tmp->mDummyJavaPluginOwner) {
 -    tmp->mDummyJavaPluginOwner->Destroy();
 -    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDummyJavaPluginOwner)
 -  }
 -#endif
 -
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -
--
+ 
  //*****************************************************************************
  // nsGlobalWindow::nsIScriptGlobalObject
- //*****************************************************************************
-@@ -2005,10 +1891,6 @@ nsGlobalWindow::SetDocShell(nsIDocShell*
+@@ -2011,10 +1896,6 @@ nsGlobalWindow::SetDocShell(nsIDocShell*
          mScriptContexts[st_ndx] = nsnull;
        }
      }
 -#ifdef DEBUG
 -    nsCycleCollector_DEBUG_shouldBeFreed(mContext);
 -    nsCycleCollector_DEBUG_shouldBeFreed(static_cast<nsIScriptGlobalObject*>(this));
 -#endif
      mContext = nsnull; // we nuked it above also
@@ -2262,44 +2264,44 @@ diff --git a/dom/src/base/nsJSEnvironmen
 @@ -168,7 +167,6 @@ static PRUint32 sCCollectCount;
  static PRUint32 sCCollectCount;
  static PRBool sUserIsActive;
  static PRTime sPreviousCCTime;
 -static PRBool sPreviousCCDidCollect;
  static nsITimer *sGCTimer;
  static PRBool sReadyForGC;
  
-@@ -1137,9 +1135,6 @@ nsJSContext::nsJSContext(JSRuntime *aRun
+@@ -1140,9 +1138,6 @@ nsJSContext::nsJSContext(JSRuntime *aRun
  
  nsJSContext::~nsJSContext()
  {
 -#ifdef DEBUG
 -  nsCycleCollector_DEBUG_wasFreed(static_cast<nsIScriptContext*>(this));
 -#endif
    NS_PRECONDITION(!mTerminations, "Shouldn't have termination funcs by now");
  
    Unlink();
-@@ -1191,16 +1186,6 @@ nsJSContext::Unlink()
+@@ -1194,16 +1189,6 @@ nsJSContext::Unlink()
  }
  
  // QueryInterface implementation for nsJSContext
 -NS_IMPL_CYCLE_COLLECTION_CLASS(nsJSContext)
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsJSContext)
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mGlobalWrapperRef)
 -  tmp->Unlink();
 -  tmp->mIsInitialized = PR_FALSE;
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsJSContext)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mGlobalWrapperRef)
 -  nsContentUtils::XPConnect()->NoteJSContext(tmp->mContext, cb);
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  
  NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsJSContext)
    NS_INTERFACE_MAP_ENTRY(nsIScriptContext)
-@@ -3305,17 +3290,17 @@ nsJSContext::CC()
+@@ -3324,17 +3309,17 @@ nsJSContext::CC()
    sPreviousCCTime = PR_Now();
    sDelayedCCollectCount = 0;
    ++sCCollectCount;
 -#ifdef DEBUG_smaug
 -  printf("Will run cycle collector (%i)\n", sCCollectCount);
 -#endif
 -  // nsCycleCollector_collect() will run a ::JS_GC() indirectly, so
 -  // we do not explicitly call ::JS_GC() here.
@@ -2307,45 +2309,45 @@ diff --git a/dom/src/base/nsJSEnvironmen
 -#ifdef DEBUG_smaug
 -  printf("(1) %s\n", sPreviousCCDidCollect ?
 -                     "Cycle collector did collect nodes" :
 -                     "Cycle collector did not collect nodes");
 -#endif
 +
 +  nsIXPConnect* xpconnect = do_GetService("@mozilla.org/js/xpc/XPConnect;1");
 +  if (xpconnect) {
-+    nsIXPCNativeCallContext* context = nsnull;
++    nsAXPCNativeCallContext* context = nsnull;
 +    xpconnect->GetCurrentNativeCallContext(&context);
 +    if (context) {
 +      JSContext *cx = nsnull;
 +      context->GetJSContext(&cx);
 +      ::JS_GC(cx);
 +    }
 +  }
  }
  
  //static
-@@ -3325,7 +3310,7 @@ nsJSContext::MaybeCC(PRBool aHigherProba
+@@ -3344,7 +3329,7 @@ nsJSContext::MaybeCC(PRBool aHigherProba
    ++sDelayedCCollectCount;
    // Increase the probability also if the previous call to cycle collector
    // collected something.
 -  if (aHigherProbability || sPreviousCCDidCollect) {
 +  if (aHigherProbability) {
      sDelayedCCollectCount *= NS_PROBABILITY_MULTIPLIER;
    }
  
-@@ -3544,7 +3529,6 @@ nsJSRuntime::Startup()
+@@ -3563,7 +3548,6 @@ nsJSRuntime::Startup()
    sCCollectCount = 0;
    sUserIsActive = PR_FALSE;
    sPreviousCCTime = 0;
 -  sPreviousCCDidCollect = PR_FALSE;
    sGCTimer = nsnull;
    sReadyForGC = PR_FALSE;
    sLoadInProgressGCTimer = PR_FALSE;
-@@ -3848,24 +3832,6 @@ nsJSArgArray::ReleaseJSObjects()
+@@ -3867,24 +3851,6 @@ nsJSArgArray::ReleaseJSObjects()
  
  // QueryInterface implementation for nsJSArgArray
  NS_IMPL_CYCLE_COLLECTION_CLASS(nsJSArgArray)
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsJSArgArray)
 -  tmp->ReleaseJSObjects();
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsJSArgArray)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
@@ -2397,21 +2399,20 @@ diff --git a/dom/src/base/nsWindowRoot.c
 -  mRefCnt.decr(static_cast<nsIDOMEventTarget*>(this));
 +  --mRefCnt;
  }
  
  nsWindowRoot::~nsWindowRoot()
 diff --git a/dom/src/events/nsJSEventListener.cpp b/dom/src/events/nsJSEventListener.cpp
 --- a/dom/src/events/nsJSEventListener.cpp
 +++ b/dom/src/events/nsJSEventListener.cpp
-@@ -89,26 +89,6 @@ nsJSEventListener::~nsJSEventListener()
-   if (mContext)
+@@ -90,26 +90,6 @@ nsJSEventListener::~nsJSEventListener()
      NS_DROP_JS_OBJECTS(this, nsJSEventListener);
  }
--
+ 
 -NS_IMPL_CYCLE_COLLECTION_CLASS(nsJSEventListener)
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsJSEventListener)
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mTarget)
 -  if (tmp->mContext) {
 -    tmp->mScopeObject = nsnull;
 -    NS_DROP_JS_OBJECTS(tmp, nsJSEventListener);
 -    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mContext)
 -  }
@@ -2421,27 +2422,97 @@ diff --git a/dom/src/events/nsJSEventLis
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mContext)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 -
 -NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsJSEventListener)
 -  NS_IMPL_CYCLE_COLLECTION_TRACE_MEMBER_CALLBACK(tmp->mContext->GetScriptTypeID(),
 -                                                 mScopeObject)
 -NS_IMPL_CYCLE_COLLECTION_TRACE_END
- 
+-
  NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsJSEventListener)
    NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener)
+   NS_INTERFACE_MAP_ENTRY(nsIJSEventListener)
+diff --git a/dom/src/offline/nsDOMOfflineResourceList.cpp b/dom/src/offline/nsDOMOfflineResourceList.cpp
+--- a/dom/src/offline/nsDOMOfflineResourceList.cpp
++++ b/dom/src/offline/nsDOMOfflineResourceList.cpp
+@@ -81,66 +81,6 @@ static PRUint32 gCachedKeysCount = 0;
+ // nsDOMOfflineResourceList
+ //
+ 
+-NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMOfflineResourceList)
+-
+-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsDOMOfflineResourceList)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mWindow)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mCacheSession)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mCacheUpdate)
+-
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mCheckingListeners)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mErrorListeners)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mNoUpdateListeners)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mDownloadingListeners)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mProgressListeners)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mCachedListeners)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mUpdateReadyListeners)
+-
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOnCheckingListener)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOnErrorListener)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOnNoUpdateListener)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOnDownloadingListener)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOnProgressListener)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOnCachedListener)
+-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOnUpdateReadyListener)
+-
+-  for (PRUint32 i = 0; i < tmp->mPendingEvents.Length(); i++) {
+-    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mPendingEvents[i].event);
+-    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mPendingEvents[i].listener);
+-    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mPendingEvents[i].listeners);
+-  }
+-
+-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+-
+-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDOMOfflineResourceList)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mWindow)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCacheSession)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCacheUpdate)
+-
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mCheckingListeners)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mErrorListeners)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mNoUpdateListeners)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mDownloadingListeners)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mProgressListeners)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mCachedListeners)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mUpdateReadyListeners)
+-
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnCheckingListener)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnErrorListener)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnNoUpdateListener)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnDownloadingListener)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnProgressListener)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnCachedListener)
+-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnUpdateReadyListener)
+-
+-  for (PRUint32 i = 0; i < tmp->mPendingEvents.Length(); i++) {
+-    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mPendingEvents[i].event);
+-    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mPendingEvents[i].listener);
+-    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mPendingEvents[i].listeners);
+-  }
+-
+-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+-
+ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMOfflineResourceList)
+   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMOfflineResourceList)
+   NS_INTERFACE_MAP_ENTRY(nsIDOMOfflineResourceList)
 diff --git a/dom/src/storage/nsDOMStorage.cpp b/dom/src/storage/nsDOMStorage.cpp
 --- a/dom/src/storage/nsDOMStorage.cpp
 +++ b/dom/src/storage/nsDOMStorage.cpp
-@@ -255,29 +255,6 @@ nsDOMStorageEntry::~nsDOMStorageEntry()
- nsDOMStorageEntry::~nsDOMStorageEntry()
+@@ -256,29 +256,6 @@ nsDOMStorageEntry::~nsDOMStorageEntry()
  {
  }
--
+ 
 -PLDHashOperator PR_CALLBACK
 -SessionStorageTraverser(nsSessionStorageEntry* aEntry, void* userArg) {
 -  nsCycleCollectionTraversalCallback *cb = 
 -    static_cast<nsCycleCollectionTraversalCallback*>(userArg);
 -
 -  cb->NoteXPCOMChild((nsIDOMStorageItem *) aEntry->mItem);
 -
 -  return PL_DHASH_NEXT;
@@ -2454,19 +2525,20 @@ diff --git a/dom/src/storage/nsDOMStorag
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsDOMStorage)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mURI)
 -  {
 -    if (tmp->mItems.IsInitialized()) {
 -      tmp->mItems.EnumerateEntries(SessionStorageTraverser, &cb);
 -    }
 -  }
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
- 
+-
  NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsDOMStorage, nsIDOMStorage)
  NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsDOMStorage, nsIDOMStorage)
+ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMStorage)
 @@ -1089,18 +1066,6 @@ NS_NewDOMStorageList(nsIDOMStorageList**
  // nsDOMStorageItem
  //
  
 -NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMStorageItem)
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDOMStorageItem)
 -  {
 -    tmp->mStorage = nsnull;
@@ -2479,21 +2551,20 @@ diff --git a/dom/src/storage/nsDOMStorag
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 -
  NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsDOMStorageItem, nsIDOMStorageItem)
  NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsDOMStorageItem, nsIDOMStorageItem)
  NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMStorageItem)
 diff --git a/embedding/components/commandhandler/src/nsCommandManager.cpp b/embedding/components/commandhandler/src/nsCommandManager.cpp
 --- a/embedding/components/commandhandler/src/nsCommandManager.cpp
 +++ b/embedding/components/commandhandler/src/nsCommandManager.cpp
-@@ -68,30 +68,6 @@ nsCommandManager::~nsCommandManager()
- {
+@@ -69,30 +69,6 @@ nsCommandManager::~nsCommandManager()
    /* destructor code */
  }
--
+ 
 -
 -PR_STATIC_CALLBACK(PLDHashOperator)
 -TraverseCommandObservers(const char* aKey, nsCOMArray<nsIObserver>* aObservers,
 -                         void* aClosure)
 -{
 -  nsCycleCollectionTraversalCallback *cb = 
 -    static_cast<nsCycleCollectionTraversalCallback*>(aClosure);
 -
@@ -2507,28 +2578,36 @@ diff --git a/embedding/components/comman
 -
 -NS_IMPL_CYCLE_COLLECTION_CLASS(nsCommandManager)
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsCommandManager)
 -  tmp->mObserversTable.Clear();
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsCommandManager)
 -  tmp->mObserversTable.EnumerateRead(TraverseCommandObservers, &cb);
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
- 
+-
  NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsCommandManager, nsICommandManager)
  NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsCommandManager, nsICommandManager)
+ 
 diff --git a/js/src/xpconnect/idl/nsIXPConnect.idl b/js/src/xpconnect/idl/nsIXPConnect.idl
 --- a/js/src/xpconnect/idl/nsIXPConnect.idl
 +++ b/js/src/xpconnect/idl/nsIXPConnect.idl
-@@ -728,29 +728,6 @@ interface nsIXPConnect : nsISupports
-     [noscript] JSVal getCrossOriginWrapperForObject(in JSContextPtr aJSContext,
-                                                     in JSObjectPtr aParent,
-                                                     in JSObjectPtr aWrappedObj);
--
--    /**
+@@ -405,7 +405,7 @@ interface nsIXPCFunctionThisTranslator :
+     { 0xbd, 0xd6, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74 } }
+ %}
+ 
+-[uuid(20df9082-5b83-416d-ba80-0422af516d57)]
++[uuid(ccc89d14-104a-475e-af6f-eb83acd15bcf)]
+ interface nsIXPConnect : nsISupports
+ {
+ %{ C++
+@@ -709,28 +709,6 @@ interface nsIXPConnect : nsISupports
+                                in PRUint32 aWay);
+ 
+     /**
 -     * Root JS objects held by aHolder.
 -     * @param aHolder The object that hold the JS objects that should be rooted.
 -     * @param aTrace The tracer for aHolder.
 -     */
 -    [noscript] void addJSHolder(in voidPtr aHolder,
 -                                in nsScriptObjectTracerPtr aTracer);
 -
 -    /**
@@ -2540,19 +2619,20 @@ diff --git a/js/src/xpconnect/idl/nsIXPC
 -    /**
 -     * Note aJSContext as a child to the cycle collector.
 -     * @param aJSContext The JSContext to note.
 -     * @param aCb The cycle collection traversal callback.
 -     */
 -    [noscript,notxpcom] void noteJSContext(in JSContextPtr aJSContext,
 -                                           in nsCCTraversalCallbackRef aCb);
 -
-     /**
+-    /**
       * Get the JSClass and JSGetObjectOps pointers to use for
       * identifying JSObjects that hold nsIXPConnectWrappedNative
+      * pointers in their private date. See IS_WRAPPER_CLASS in
 diff --git a/js/src/xpconnect/src/nsXPConnect.cpp b/js/src/xpconnect/src/nsXPConnect.cpp
 --- a/js/src/xpconnect/src/nsXPConnect.cpp
 +++ b/js/src/xpconnect/src/nsXPConnect.cpp
 @@ -80,20 +80,13 @@ nsXPConnect::nsXPConnect()
          mContextStack(nsnull),
          mDefaultSecurityManager(nsnull),
          mDefaultSecurityManagerFlags(0),
 -        mShuttingDown(JS_FALSE),
@@ -2579,60 +2659,68 @@ diff --git a/js/src/xpconnect/src/nsXPCo
  {
 -    NS_ASSERTION(!mCycleCollectionContext,
 -                 "Didn't call FinishCycleCollection?");
 -    nsCycleCollector_forgetRuntime(nsIProgrammingLanguage::JAVASCRIPT);
 -
      JSContext *cx = nsnull;
      if (mRuntime) {
          // Create our own JSContext rather than an XPCCallContext, since
-@@ -412,576 +401,6 @@ nsXPConnect::GetInfoForName(const char *
- {
+@@ -413,590 +402,6 @@ nsXPConnect::GetInfoForName(const char *
      return FindInfo(NameTester, name, mInterfaceInfoManager, info);
  }
--
+ 
 -static JSGCCallback gOldJSGCCallback;
--// Number of collections that have collected nodes.
--static PRUint32 gCollections;
--// Whether to run cycle collection during GC.
--static PRBool gCollect;
+-// Whether cycle collection was run.
+-static PRBool gDidCollection;
+-// Whether starting cycle collection was successful.
+-static PRBool gInCollection;
+-// Whether cycle collection collected anything.
+-static PRBool gCollected;
 -
 -JS_STATIC_DLL_CALLBACK(JSBool)
 -XPCCycleCollectGCCallback(JSContext *cx, JSGCStatus status)
 -{
 -    // Launch the cycle collector.
 -    if(status == JSGC_MARK_END)
 -    {
 -        // This is the hook between marking and sweeping in the JS GC. Do cycle
 -        // collection.
--        if(gCollect && nsCycleCollector_doCollect())
--            ++gCollections;
--        else
--            // If cycle collection didn't collect anything we should stop
--            // collecting until the next call to nsXPConnect::Collect, even if
--            // there are more (nested) JS_GC calls.
--            gCollect = PR_FALSE;
+-        if(!gDidCollection)
+-        {
+-            NS_ASSERTION(!gInCollection, "Recursing?");
+-
+-            gDidCollection = PR_TRUE;
+-            gInCollection = nsCycleCollector_beginCollection();
+-        }
 -
 -        // Mark JS objects that are held by XPCOM objects that are in cycles
 -        // that will not be collected.
 -        nsXPConnect::GetRuntime()->
 -            TraceXPConnectRoots(cx->runtime->gc->GetTracer());
 -    }
 -    else if(status == JSGC_END)
+-    {
+-        if(gInCollection)
+-        {
+-            gInCollection = PR_FALSE;
+-            gCollected = nsCycleCollector_finishCollection();
+-        }
 -        nsXPConnect::GetRuntime()->RestoreContextGlobals();
+-    }
 -
 -    PRBool ok = gOldJSGCCallback ? gOldJSGCCallback(cx, status) : JS_TRUE;
 -
 -    if(status == JSGC_BEGIN)
 -        nsXPConnect::GetRuntime()->UnsetContextGlobals();
 -
 -    return ok;
 -}
 -
--PRUint32
+-PRBool
 -nsXPConnect::Collect()
 -{
 -    // We're dividing JS objects into 2 categories:
 -    //
 -    // 1. "real" roots, held by the JS engine itself or rooted through the root
 -    //    and lock JS APIs. Roots from this category are considered black in the
 -    //    cycle collector, any cycle they participate in is uncollectable.
 -    //
@@ -2679,29 +2767,30 @@ diff --git a/js/src/xpconnect/src/nsXPCo
 -    XPCCallContext cycleCollectionContext(NATIVE_CALLER);
 -    if(!cycleCollectionContext.IsValid())
 -    {
 -        return PR_FALSE;
 -    }
 -
 -    mCycleCollecting = PR_TRUE;
 -    mCycleCollectionContext = &cycleCollectionContext;
--    gCollections = 0;
--    gCollect = PR_TRUE;
+-    gDidCollection = PR_FALSE;
+-    gInCollection = PR_FALSE;
+-    gCollected = PR_FALSE;
 -
 -    JSContext *cx = mCycleCollectionContext->GetJSContext();
 -    gOldJSGCCallback = JS_SetGCCallback(cx, XPCCycleCollectGCCallback);
 -    JS_GC(cx);
 -    JS_SetGCCallback(cx, gOldJSGCCallback);
 -    gOldJSGCCallback = nsnull;
 -
 -    mCycleCollectionContext = nsnull;
 -    mCycleCollecting = PR_FALSE;
 -
--    return gCollections;
+-    return gCollected;
 -}
 -
 -// JSTRACE_FUNCTION can hold on to a lot of objects, adding it to the cycle
 -// collector reduces the number of edges to those objects.
 -// JSTRACE_XML can recursively hold on to more JSTRACE_XML objects, adding it to
 -// the cycle collector avoids stack overflow.
 -#define ADD_TO_CC(_kind) \
 -    ((_kind) == JSTRACE_OBJECT || (_kind) == JSTRACE_FUNCTION || \
@@ -2767,16 +2856,18 @@ diff --git a/js/src/xpconnect/src/nsXPCo
 -        // collection identical for DEBUG_CC and non-DEBUG_CC builds.
 -        if(!PL_DHashTableInit(&mJSRoots, PL_DHashGetStubOps(), nsnull,
 -                              sizeof(PLDHashEntryStub), PL_DHASH_MIN_SIZE)) {
 -            mJSRoots.ops = nsnull;
 -
 -            return NS_ERROR_OUT_OF_MEMORY;
 -        }
 -
+-        nsXPConnect::GetRuntime()->UnsetContextGlobals();
+-
 -        PRBool alreadyCollecting = mCycleCollecting;
 -        mCycleCollecting = PR_TRUE;
 -        NoteJSRootTracer trc(&mJSRoots, cb);
 -        JS_TRACER_INIT(&trc, mCycleCollectionContext->GetJSContext(),
 -                       NoteJSRoot);
 -        JS_TraceRuntime(&trc);
 -        mCycleCollecting = alreadyCollecting;
 -    }
@@ -2811,16 +2902,18 @@ diff --git a/js/src/xpconnect/src/nsXPCo
 -nsresult 
 -nsXPConnect::FinishCycleCollection()
 -{
 -#ifdef DEBUG_CC
 -    if(mExplainCycleCollectionContext)
 -    {
 -        mCycleCollectionContext = nsnull;
 -        mExplainCycleCollectionContext = nsnull;
+-
+-        nsXPConnect::GetRuntime()->RestoreContextGlobals();
 -    }
 -#endif
 -
 -#ifndef XPCONNECT_STANDALONE
 -    mScopes.Clear();
 -#endif
 -
 -#ifdef DEBUG_CC
@@ -3153,20 +3246,21 @@ diff --git a/js/src/xpconnect/src/nsXPCo
 -
 -NS_IMETHODIMP_(void)
 -nsXPConnect::NoteJSContext(JSContext *aJSContext,
 -                           nsCycleCollectionTraversalCallback &aCb)
 -{
 -    aCb.NoteNativeChild(aJSContext, &JSContext_cycleCollectorGlobal);
 -}
 -
- 
+-
  /***************************************************************************/
  /***************************************************************************/
-@@ -2186,18 +1605,6 @@ nsXPConnect::OnDispatchedEvent(nsIThread
+ // nsIXPConnect interface methods...
+@@ -2253,18 +1658,6 @@ nsXPConnect::OnDispatchedEvent(nsIThread
      return NS_ERROR_UNEXPECTED;
  }
  
 -NS_IMETHODIMP
 -nsXPConnect::AddJSHolder(void* aHolder, nsScriptObjectTracer* aTracer)
 -{
 -    return mRuntime->AddJSHolder(aHolder, aTracer);
 -}
@@ -3420,17 +3514,17 @@ diff --git a/js/src/xpconnect/src/xpcjsr
 -        reinterpret_cast<ClearedGlobalObject*>(entry);
 -
 -    return JS_DHASH_ENTRY_IS_BUSY(entry) ?
 -           clearedGlobal->mGlobalObject :
 -           nsnull;
  }
  
  // static
-@@ -1022,17 +810,6 @@ XPCJSRuntime::~XPCJSRuntime()
+@@ -1019,17 +807,6 @@ XPCJSRuntime::~XPCJSRuntime()
  
      gOldJSGCCallback = NULL;
      gOldJSContextCallback = NULL;
 -
 -    if(mJSHolders.ops)
 -    {
 -        JS_DHashTableFinish(&mJSHolders);
 -        mJSHolders.ops = nsnull;
@@ -3438,68 +3532,69 @@ diff --git a/js/src/xpconnect/src/xpcjsr
 -    if(mClearedGlobalObjects.ops)
 -    {
 -        JS_DHashTableFinish(&mClearedGlobalObjects);
 -        mClearedGlobalObjects.ops = nsnull;
 -    }
  }
  
  XPCJSRuntime::XPCJSRuntime(nsXPConnect* aXPConnect,
-@@ -1084,13 +861,6 @@ XPCJSRuntime::XPCJSRuntime(nsXPConnect* 
-         gOldJSGCCallback = JS_SetGCCallbackRT(mJSRuntime, GCCallback);
+@@ -1081,13 +858,6 @@ XPCJSRuntime::XPCJSRuntime(nsXPConnect* 
          JS_SetExtraGCRoots(mJSRuntime, TraceJS, this);
      }
--
+ 
 -    if(!JS_DHashTableInit(&mJSHolders, JS_DHashGetStubOps(), nsnull,
 -                          sizeof(ObjectHolder), 512))
 -        mJSHolders.ops = nsnull;
 -    if(!JS_DHashTableInit(&mClearedGlobalObjects, JS_DHashGetStubOps(), nsnull,
 -                          sizeof(ClearedGlobalObject), JS_DHASH_MIN_SIZE))
 -        mClearedGlobalObjects.ops = nsnull;
- 
+-
      // Install a JavaScript 'debugger' keyword handler in debug builds only
  #ifdef DEBUG
+     if(mJSRuntime && !JS_GetGlobalDebugHooks(mJSRuntime)->debuggerHandler)
 diff --git a/js/src/xpconnect/src/xpcprivate.h b/js/src/xpconnect/src/xpcprivate.h
 --- a/js/src/xpconnect/src/xpcprivate.h
 +++ b/js/src/xpconnect/src/xpcprivate.h
 @@ -54,7 +54,6 @@
  #include "nsXPCOM.h"
  #include "nsAutoPtr.h"
  #include "nsCycleCollectionParticipant.h"
 -#include "nsCycleCollector.h"
  #include "nsISupports.h"
  #include "nsIServiceManager.h"
  #include "nsIClassInfoImpl.h"
-@@ -443,9 +442,7 @@ const PRBool OBJ_IS_NOT_GLOBAL = PR_FALS
+@@ -444,9 +443,7 @@ const PRBool OBJ_IS_NOT_GLOBAL = PR_FALS
  
  class nsXPConnect : public nsIXPConnect,
                      public nsIThreadObserver,
 -                    public nsSupportsWeakReference,
 -                    public nsCycleCollectionJSRuntime,
 -                    public nsCycleCollectionParticipant
 +                    public nsSupportsWeakReference
  {
  public:
      // all the interface method declarations...
 @@ -494,44 +491,6 @@ public:
+ 
      nsresult GetInfoForIID(const nsIID * aIID, nsIInterfaceInfo** info);
      nsresult GetInfoForName(const char * name, nsIInterfaceInfo** info);
- 
+-
 -    // nsCycleCollectionParticipant
 -    NS_IMETHOD Root(void *p);
 -    NS_IMETHOD Unlink(void *p);
 -    NS_IMETHOD Unroot(void *p);
 -    NS_IMETHOD Traverse(void *p,
 -                        nsCycleCollectionTraversalCallback &cb);
 -    
 -    // nsCycleCollectionLanguageRuntime
 -    virtual nsresult BeginCycleCollection(nsCycleCollectionTraversalCallback &cb);
 -    virtual nsresult FinishCycleCollection();
 -    virtual nsCycleCollectionParticipant *ToParticipant(void *p);
--    virtual PRUint32 Collect();
+-    virtual PRBool Collect();
 -#ifdef DEBUG_CC
 -    virtual void PrintAllReferencesTo(void *p);
 -#endif
 -
 -    // We should not trace XPConnect JS roots when tracing the graph for the
 -    // cycle collector. Those should be traced from the XPCOM objects that hold
 -    // them when we know that they won't be collected by the cycle collector.
 -    PRBool ShouldTraceRoots()
@@ -3515,34 +3610,33 @@ diff --git a/js/src/xpconnect/src/xpcpri
 -    PRInt32 GetRequestDepth(JSContext* cx);
 -
 -    // This returns the singleton nsCycleCollectionParticipant for JSContexts.
 -    static nsCycleCollectionParticipant *JSContextParticipant();
 -
 -#ifndef XPCONNECT_STANDALONE
 -    void RecordTraversal(void *p, nsISupports *s);
 -#endif
--
+ 
  #ifdef XPC_IDISPATCH_SUPPORT
  public:
-     static PRBool IsIDispatchEnabled();
-@@ -556,12 +515,6 @@ private:
+@@ -557,12 +516,6 @@ private:
      nsIXPCSecurityManager*   mDefaultSecurityManager;
      PRUint16                 mDefaultSecurityManagerFlags;
      JSBool                   mShuttingDown;
 -    XPCCallContext*          mCycleCollectionContext;
 -#ifdef DEBUG_CC
 -    nsAutoPtr<XPCCallContext> mExplainCycleCollectionContext;
 -    PLDHashTable             mJSRoots;
 -#endif
 -    PRBool                   mCycleCollecting;
  
  #ifdef XPC_TOOLS_SUPPORT
      nsCOMPtr<nsIXPCToolsProfiler> mProfiler;
-@@ -712,21 +665,12 @@ public:
+@@ -706,21 +659,12 @@ public:
  
      static void JS_DLL_CALLBACK TraceJS(JSTracer* trc, void* data);
      void TraceXPConnectRoots(JSTracer *trc);
 -    void AddXPConnectRoots(JSContext* cx,
 -                           nsCycleCollectionTraversalCallback& cb);
  
      static JSBool JS_DLL_CALLBACK GCCallback(JSContext *cx, JSGCStatus status);
  
@@ -3554,83 +3648,95 @@ diff --git a/js/src/xpconnect/src/xpcpri
 -    nsresult RemoveJSHolder(void* aHolder);
 -
 -    void UnsetContextGlobals();
 -    void RestoreContextGlobals();
 -    JSObject* GetUnsetContextGlobal(JSContext* cx);
  
      void DebugDump(PRInt16 depth);
  
-@@ -790,8 +734,6 @@ private:
+@@ -785,8 +729,6 @@ private:
      XPCRootSetElem *mVariantRoots;
      XPCRootSetElem *mWrappedJSRoots;
      XPCRootSetElem *mObjectHolderRoots;
 -    JSDHashTable mJSHolders;
 -    JSDHashTable mClearedGlobalObjects;
  };
  
  /***************************************************************************/
-@@ -1196,10 +1138,6 @@ public:
+@@ -1253,10 +1195,6 @@ public:
  
      static void
      TraceJS(JSTracer* trc, XPCJSRuntime* rt);
 -
 -    static void
 -    SuspectAllWrappers(XPCJSRuntime* rt, JSContext* cx,
 -                       nsCycleCollectionTraversalCallback &cb);
  
      static void
      FinishedMarkPhaseOfGC(JSContext* cx, XPCJSRuntime* rt);
-@@ -1979,8 +1917,6 @@ public:
+@@ -2040,16 +1978,6 @@ public:
      NS_DECL_ISUPPORTS
      NS_DECL_NSIXPCONNECTJSOBJECTHOLDER
      NS_DECL_NSIXPCONNECTWRAPPEDNATIVE
--    NS_DECL_CYCLE_COLLECTION_CLASS(XPCWrappedNative)
+-    // No need to unlink the JS objects, if the XPCWrappedNative will be cycle
+-    // collected then its mFlatJSObject will be cycle collected too and
+-    // finalization of the mFlatJSObject will unlink the js objects (see
+-    // XPC_WN_NoHelper_Finalize and FlatJSObjectFinalized).
+-    // We also rely on NS_DECL_CYCLE_COLLECTION_CLASS_NO_UNLINK having empty
+-    // Root/Unroot methods, to avoid root/unrooting the JS objects from
+-    // addrefing/releasing the XPCWrappedNative during unlinking, which would
+-    // make the JS objects uncollectable to the JS GC.
+-    NS_DECL_CYCLE_COLLECTION_CLASS_NO_UNLINK(XPCWrappedNative)
 -    NS_DECL_CYCLE_COLLECTION_UNMARK_PURPLE_STUB(XPCWrappedNative)
  
  #ifndef XPCONNECT_STANDALONE
      virtual nsIPrincipal* GetObjectPrincipal() const;
-@@ -2192,8 +2128,6 @@ public:
+@@ -2261,8 +2189,6 @@ public:
  
      JSObject* GetWrapper()              { return mWrapper; }
      void      SetWrapper(JSObject *obj) { mWrapper = obj; }
 -
 -    void NoteTearoffs(nsCycleCollectionTraversalCallback& cb);
  
      // Make ctor and dtor protected (rather than private) to placate nsCOMPtr.
  protected:
 diff --git a/js/src/xpconnect/src/xpcvariant.cpp b/js/src/xpconnect/src/xpcvariant.cpp
 --- a/js/src/xpconnect/src/xpcvariant.cpp
 +++ b/js/src/xpconnect/src/xpcvariant.cpp
-@@ -89,25 +89,6 @@ XPCTraceableVariant::PrintTraceName(JSTr
-     JS_snprintf(buf, bufsize, "XPCVariant[0x%p].mJSVal", trc->debugPrintArg);
+@@ -90,29 +90,6 @@ XPCTraceableVariant::PrintTraceName(JSTr
  }
  #endif
--
+ 
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(XPCVariant)
 -    if(JSVAL_IS_OBJECT(tmp->mJSVal))
 -        cb.NoteScriptChild(nsIProgrammingLanguage::JAVASCRIPT,
 -                           JSVAL_TO_OBJECT(tmp->mJSVal));
 -
 -    nsVariant::Traverse(tmp->mData, cb);
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 -
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(XPCVariant)
--    if(!JSVAL_IS_STRING(tmp->mJSVal))
--        nsVariant::Cleanup(&tmp->mData);
+-    // We're sharing mJSVal's buffer, clear the pointer to it
+-    // so Cleanup() won't try to delete it
+-    if(JSVAL_IS_STRING(tmp->mJSVal))
+-        tmp->mData.u.wstr.mWStringValue = nsnull;
+-    nsVariant::Cleanup(&tmp->mData);
+-
 -    if(JSVAL_IS_TRACEABLE(tmp->mJSVal))
 -    {
 -        XPCTraceableVariant *v = static_cast<XPCTraceableVariant*>(tmp);
 -        v->RemoveFromRootSet(nsXPConnect::GetRuntime()->GetJSRuntime());
 -    }
 -    tmp->mJSVal = JSVAL_NULL;
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
- 
+-
  // static 
  XPCVariant* XPCVariant::newVariant(XPCCallContext& ccx, jsval aJSVal)
+ {
 diff --git a/js/src/xpconnect/src/xpcwrappedjs.cpp b/js/src/xpconnect/src/xpcwrappedjs.cpp
 --- a/js/src/xpconnect/src/xpcwrappedjs.cpp
 +++ b/js/src/xpconnect/src/xpcwrappedjs.cpp
 @@ -45,87 +45,6 @@
  
  // NOTE: much of the fancy footwork is done in xpcstubs.cpp
  
 -NS_IMPL_CYCLE_COLLECTION_CLASS(nsXPCWrappedJS)
@@ -3735,17 +3841,17 @@ diff --git a/js/src/xpconnect/src/xpcwra
 -            NS_CYCLE_COLLECTION_CLASSNAME(nsXPCWrappedJS)::Upcast(this);
 -        return NS_OK;
      }
  
      // Always check for this first so that our 'outer' can get this interface
 diff --git a/js/src/xpconnect/src/xpcwrappednative.cpp b/js/src/xpconnect/src/xpcwrappednative.cpp
 --- a/js/src/xpconnect/src/xpcwrappednative.cpp
 +++ b/js/src/xpconnect/src/xpcwrappednative.cpp
-@@ -47,86 +47,6 @@
+@@ -47,80 +47,6 @@
  #include "XPCWrapper.h"
  
  /***************************************************************************/
 -
 -NS_IMPL_CYCLE_COLLECTION_CLASS(XPCWrappedNative)
 -
 -NS_IMETHODIMP
 -NS_CYCLE_COLLECTION_CLASSNAME(XPCWrappedNative)::Traverse(void *p,
@@ -3813,29 +3919,23 @@ diff --git a/js/src/xpconnect/src/xpcwra
 -            JSObject* jso = to->GetJSObject();
 -            if(!jso)
 -            {
 -                cb.NoteXPCOMChild(to->GetNative());
 -            }
 -        }
 -    }
 -}
--
--// No need to unlink the JS objects, if the XPCWrappedNative will be cycle
--// collected then its mFlatJSObject will be cycle collected too and finalization
--// of the mFlatJSObject will unlink the js objects (see
--// XPC_WN_NoHelper_Finalize and FlatJSObjectFinalized).
--NS_IMPL_CYCLE_COLLECTION_UNLINK_0(XPCWrappedNative)
  
  #ifdef XPC_CHECK_CLASSINFO_CLAIMS
  static void DEBUG_CheckClassInfoClaims(XPCWrappedNative* wrapper);
 diff --git a/js/src/xpconnect/src/xpcwrappednativescope.cpp b/js/src/xpconnect/src/xpcwrappednativescope.cpp
 --- a/js/src/xpconnect/src/xpcwrappednativescope.cpp
 +++ b/js/src/xpconnect/src/xpcwrappednativescope.cpp
-@@ -309,57 +309,6 @@ XPCWrappedNativeScope::TraceJS(JSTracer*
+@@ -319,57 +319,6 @@ XPCWrappedNativeScope::TraceJS(JSTracer*
      }
  }
  
 -struct SuspectClosure
 -{
 -    SuspectClosure(JSContext *aCx, nsCycleCollectionTraversalCallback& aCb)
 -        : cx(aCx), cb(aCb)
 -    {
@@ -3883,17 +3983,17 @@ diff --git a/js/src/xpconnect/src/xpcwra
 -    {
 -        cur->mWrappedNativeMap->Enumerate(WrappedNativeSuspecter, &closure);
 -    }
 -}
 -
  // static
  void
  XPCWrappedNativeScope::FinishedMarkPhaseOfGC(JSContext* cx, XPCJSRuntime* rt)
-@@ -885,20 +834,3 @@ XPCWrappedNativeScope::DebugDump(PRInt16
+@@ -895,20 +844,3 @@ XPCWrappedNativeScope::DebugDump(PRInt16
      XPC_LOG_OUTDENT();
  #endif
  }
 -
 -#ifndef XPCONNECT_STANDALONE
 -// static
 -void
 -XPCWrappedNativeScope::TraverseScopes(XPCCallContext& ccx)
@@ -3907,21 +4007,20 @@ diff --git a/js/src/xpconnect/src/xpcwra
 -            ccx.GetXPConnect()->RecordTraversal(cur->mGlobalJSObject,
 -                                                cur->mScriptObjectPrincipal);
 -        }
 -}
 -#endif
 diff --git a/layout/base/nsPresContext.cpp b/layout/base/nsPresContext.cpp
 --- a/layout/base/nsPresContext.cpp
 +++ b/layout/base/nsPresContext.cpp
-@@ -291,61 +291,6 @@ NS_INTERFACE_MAP_END
- 
+@@ -292,61 +292,6 @@ NS_IMPL_CYCLE_COLLECTING_ADDREF(nsPresCo
  NS_IMPL_CYCLE_COLLECTING_ADDREF(nsPresContext)
  NS_IMPL_CYCLE_COLLECTING_RELEASE(nsPresContext)
--
+ 
 -PR_STATIC_CALLBACK(PLDHashOperator)
 -TraverseImageLoader(const void * aKey, nsCOMPtr<nsImageLoader>& aData,
 -                    void* aClosure)
 -{
 -  nsCycleCollectionTraversalCallback *cb =
 -    static_cast<nsCycleCollectionTraversalCallback*>(aClosure);
 -
 -  cb->NoteXPCOMChild(aData);
@@ -3966,44 +4065,45 @@ diff --git a/layout/base/nsPresContext.c
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mPrintSettings);
 -  if (tmp->mPrefChangedTimer)
 -  {
 -    tmp->mPrefChangedTimer->Cancel();
 -    tmp->mPrefChangedTimer = nsnull;
 -  }
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -
- 
+-
  #define MAKE_FONT_PREF_KEY(_pref, _s0, _s1) \
   _pref.Assign(_s0); \
+  _pref.Append(_s1);
 diff --git a/rdf/base/src/nsCompositeDataSource.cpp b/rdf/base/src/nsCompositeDataSource.cpp
 --- a/rdf/base/src/nsCompositeDataSource.cpp
 +++ b/rdf/base/src/nsCompositeDataSource.cpp
-@@ -648,21 +648,6 @@ CompositeDataSourceImpl::CompositeDataSo
- //
+@@ -649,21 +649,6 @@ CompositeDataSourceImpl::CompositeDataSo
  // nsISupports interface
  //
--
+ 
 -NS_IMPL_CYCLE_COLLECTION_CLASS(CompositeDataSourceImpl)
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(CompositeDataSourceImpl)
 -    PRUint32 i, count = tmp->mDataSources.Count();
 -    for (i = count; i > 0; --i) {
 -        tmp->mDataSources[i - 1]->RemoveObserver(tmp);
 -        tmp->mDataSources.RemoveObjectAt(i - 1);
 -    }
 -    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mObservers);
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(CompositeDataSourceImpl)
 -    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mObservers)
 -    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mDataSources)
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 -
- 
+-
  NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(CompositeDataSourceImpl,
                                            nsIRDFCompositeDataSource)
+ NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(CompositeDataSourceImpl,
 diff --git a/xpcom/base/Makefile.in b/xpcom/base/Makefile.in
 --- a/xpcom/base/Makefile.in
 +++ b/xpcom/base/Makefile.in
 @@ -108,12 +108,13 @@ SDK_XPIDLSRCS   = \
  		nsITraceRefcnt.idl         \
  		nsIWeakReference.idl	   \
  		nsrootidl.idl		   \
 +		$(NULL)
@@ -4015,17 +4115,17 @@ diff --git a/xpcom/base/Makefile.in b/xp
 -		nsCycleCollector.h \
 +		$(NULL)
  
  XPIDLSRCS	= \
  		nsIConsoleListener.idl \
 diff --git a/xpcom/base/nsAgg.h b/xpcom/base/nsAgg.h
 --- a/xpcom/base/nsAgg.h
 +++ b/xpcom/base/nsAgg.h
-@@ -98,28 +98,7 @@ private:                                
+@@ -99,28 +99,7 @@ private:                                
                                                                              \
  public:                                                                     \
  
 -#define NS_DECL_AGGREGATED_CYCLE_COLLECTION_CLASS(_class)                   \
 -class NS_CYCLE_COLLECTION_INNERCLASS                                        \
 - : public nsXPCOMCycleCollectionParticipant                                 \
 -{                                                                           \
 -public:                                                                     \
@@ -4045,17 +4145,17 @@ diff --git a/xpcom/base/nsAgg.h b/xpcom/
 -    return p->InnerObject();                                                \
 -  }                                                                         \
 -};                                                                          \
 -NS_CYCLE_COLLECTION_PARTICIPANT_INSTANCE
 +#define NS_DECL_AGGREGATED_CYCLE_COLLECTION_CLASS(_class)
  
  // Put this in your class's constructor:
  #define NS_INIT_AGGREGATED(outer)                                           \
-@@ -159,37 +138,7 @@ _class::Internal::Release(void)         
+@@ -162,37 +141,7 @@ _class::Internal::Release(void)         
  }                                                                           \
  
  #define NS_IMPL_CYCLE_COLLECTING_AGGREGATED(_class)                         \
 -                                                                            \
 -NS_IMPL_AGGREGATED_HELPER(_class)                                           \
 -                                                                            \
 -NS_IMETHODIMP_(nsrefcnt)                                                    \
 -_class::Internal::AddRef(void)                                              \
@@ -4084,20 +4184,21 @@ diff --git a/xpcom/base/nsAgg.h b/xpcom/
 -        return 0;                                                           \
 -    }                                                                       \
 -    return count;                                                           \
 -}
 +  NS_IMPL_AGGREGATED(_class)
  
  #define NS_IMPL_AGGREGATED_HELPER(_class)                                   \
  NS_IMETHODIMP                                                               \
-@@ -217,52 +166,6 @@ _class::Internal::QueryInterface(const n
+@@ -219,52 +168,6 @@ _class::Internal::QueryInterface(const n
+     _class* agg = (_class*)((char*)(this) - offsetof(_class, fAggregated)); \
      return agg->AggregatedQueryInterface(aIID, aInstancePtr);               \
  }                                                                           \
- 
+-
 -/**
 - * To make aggregated objects participate in cycle collection we need to enable
 - * the outer object (aggregator) to traverse/unlink the objects held by the
 - * inner object (the aggregatee). We can't just make the inner object QI'able to
 - * NS_CYCLECOLLECTIONPARTICIPANT_IID, we don't want to return the inner object's
 - * nsCycleCollectionParticipant for the outer object (which will happen if the
 - * outer object doesn't participate in cycle collection itself).
 - * NS_AGGREGATED_CYCLECOLLECTIONPARTICIPANT_IID enables the outer object to get
@@ -4133,21 +4234,20 @@ diff --git a/xpcom/base/nsAgg.h b/xpcom/
 -class nsAggregatedCycleCollectionParticipant
 -{
 -public:
 -    NS_DECLARE_STATIC_IID_ACCESSOR(NS_AGGREGATED_CYCLECOLLECTIONPARTICIPANT_IID)
 -};
 -
 -NS_DEFINE_STATIC_IID_ACCESSOR(nsAggregatedCycleCollectionParticipant, 
 -                              NS_AGGREGATED_CYCLECOLLECTIONPARTICIPANT_IID)
--
+ 
  // for use with QI macros in nsISupportsUtils.h:
  
- #define NS_INTERFACE_MAP_BEGIN_AGGREGATED(_class)                           \
-@@ -288,25 +191,8 @@ _class::AggregatedQueryInterface(REFNSII
+@@ -291,25 +194,8 @@ _class::AggregatedQueryInterface(REFNSII
      foundInterface = InnerObject();                                         \
    else
  
 -#define NS_IMPL_AGGREGATED_QUERY_CYCLE_COLLECTION(_class)                   \
 -  if (aIID.Equals(IsPartOfAggregated() ?                                    \
 -                  NS_GET_IID(nsCycleCollectionParticipant) :                \
 -                  NS_GET_IID(nsAggregatedCycleCollectionParticipant)))      \
 -    foundInterface = & NS_CYCLE_COLLECTION_NAME(_class);                    \
@@ -4168,17 +4268,17 @@ diff --git a/xpcom/base/nsAgg.h b/xpcom/
 +#define NS_IMPL_AGGREGATED_QUERY_CYCLE_COLLECTION(_class)
 +#define NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_AGGREGATED(_class)
  
  #define NS_GENERIC_AGGREGATED_CONSTRUCTOR(_InstanceClass)                   \
  static NS_METHOD                                                            \
 diff --git a/xpcom/base/nsCycleCollector.cpp b/xpcom/base/nsCycleCollector.cpp
 --- a/xpcom/base/nsCycleCollector.cpp
 +++ b/xpcom/base/nsCycleCollector.cpp
-@@ -38,2654 +38,21 @@
+@@ -38,2744 +38,21 @@
   * ***** END LICENSE BLOCK ***** */
  
  //
 -// This file implements a garbage-cycle collector based on the paper
 -// 
 -//   Concurrent Cycle Collection in Reference Counted Systems
 -//   Bacon & Rajan (2001), ECOOP 2001 / Springer LNCS vol 2072
 -//
@@ -4274,17 +4374,19 @@ diff --git a/xpcom/base/nsCycleCollector
 -#include "nsThreadUtils.h"
 -#include "prenv.h"
 -#include "prprf.h"
 -#include "plstr.h"
 -#include "prtime.h"
 -#include "nsPrintfCString.h"
 -#include "nsTArray.h"
 -#include "nsIObserverService.h"
+-#include "nsIConsoleService.h"
 -#include "nsServiceManagerUtils.h"
+-#include "nsThreadUtils.h"
 -
 -#include <stdio.h>
 -#ifdef WIN32
 -#include <io.h>
 -#include <process.h>
 -#endif
 -
 -#define DEFAULT_SHUTDOWN_COLLECTIONS 5
@@ -4413,18 +4515,18 @@ diff --git a/xpcom/base/nsCycleCollector
 -    
 -        DUMP(mCollection);
 -#undef DUMP
 -    }
 -};
 -#endif
 -
 -#ifdef DEBUG_CC
--static PRBool
--nsCycleCollector_shouldSuppress(nsISupports *s);
+-static PRBool nsCycleCollector_shouldSuppress(nsISupports *s);
+-static void InitMemHook(void);
 -#endif
 -
 -////////////////////////////////////////////////////////////////////////
 -// Base types
 -////////////////////////////////////////////////////////////////////////
 -
 -struct PtrInfo;
 -
@@ -4440,22 +4542,32 @@ diff --git a/xpcom/base/nsCycleCollector
 -    EdgePool()
 -    {
 -        mSentinelAndBlocks[0].block = nsnull;
 -        mSentinelAndBlocks[1].block = nsnull;
 -    }
 -
 -    ~EdgePool()
 -    {
+-        NS_ASSERTION(!mSentinelAndBlocks[0].block &&
+-                     !mSentinelAndBlocks[1].block,
+-                     "Didn't call Clear()?");
+-    }
+-
+-    void Clear()
+-    {
 -        Block *b = Blocks();
 -        while (b) {
 -            Block *next = b->Next();
 -            delete b;
 -            b = next;
 -        }
+-
+-        mSentinelAndBlocks[0].block = nsnull;
+-        mSentinelAndBlocks[1].block = nsnull;
 -    }
 -
 -private:
 -    struct Block;
 -    union PtrInfoOrBlock {
 -        // Use a union to avoid reinterpret_cast and the ensuing
 -        // potential aliasing bugs.
 -        PtrInfo *ptrInfo;
@@ -4640,30 +4752,38 @@ diff --git a/xpcom/base/nsCycleCollector
 -    NodePool()
 -        : mBlocks(nsnull),
 -          mLast(nsnull)
 -    {
 -    }
 -
 -    ~NodePool()
 -    {
+-        NS_ASSERTION(!mBlocks, "Didn't call Clear()?");
+-    }
+-
+-    void Clear()
+-    {
 -#ifdef DEBUG_CC
 -        {
 -            Enumerator queue(*this);
 -            while (!queue.IsDone()) {
 -                PL_strfree(queue.GetNext()->mName);
 -            }
 -        }
 -#endif
 -        Block *b = mBlocks;
 -        while (b) {
 -            Block *n = b->mNext;
 -            delete b;
 -            b = n;
 -        }
+-
+-        mBlocks = nsnull;
+-        mLast = nsnull;
 -    }
 -
 -    class Builder;
 -    friend class Builder;
 -    class Builder {
 -    public:
 -        Builder(NodePool& aPool)
 -            : mNextBlock(&aPool.mBlocks),
@@ -4732,35 +4852,30 @@ diff --git a/xpcom/base/nsCycleCollector
 -    };
 -
 -private:
 -    Block *mBlocks;
 -    PtrInfo *mLast;
 -};
 -
 -
--struct GCGraph;
 -class GCGraphBuilder;
 -
--static GCGraph *sCurrGraph = nsnull;
--
 -struct GCGraph
 -{
 -    NodePool mNodes;
 -    EdgePool mEdges;
 -    PRUint32 mRootCount;
 -#ifdef DEBUG_CC
 -    ReversedEdge *mReversedEdges;
 -#endif
 -
 -    GCGraph() : mRootCount(0) {
--        sCurrGraph = this;
 -    }
 -    ~GCGraph() { 
--        sCurrGraph = nsnull;
 -    }
 -};
 -
 -// XXX Would be nice to have an nsHashSet<KeyType> API that has
 -// Add/Remove/Has rather than PutEntry/RemoveEntry/GetEntry.
 -typedef nsTHashtable<nsVoidPtrHashKey> PointerSet;
 -typedef nsBaseHashtable<nsVoidPtrHashKey, PRUint32, PRUint32>
 -    PointerSetWithGeneration;
@@ -4979,56 +5094,67 @@ diff --git a/xpcom/base/nsCycleCollector
 -{
 -    PRBool mCollectionInProgress;
 -    PRBool mScanInProgress;
 -    PRBool mFollowupCollection;
 -
 -    nsCycleCollectionLanguageRuntime *mRuntimes[nsIProgrammingLanguage::MAX+1];
 -    nsCycleCollectionXPCOMRuntime mXPCOMRuntime;
 -
+-    GCGraph mGraph;
+-
 -    // The buffer |mBuf| serves a variety of purposes; mostly involving the
 -    // transfer of pointers from a hashtable iterator routine to some outer
 -    // logic that might also need to mutate the hashtable.
 -
 -    nsDeque mBuf;
 -    
 -    nsCycleCollectorParams mParams;
 -
 -    nsPurpleBuffer mPurpleBuf;
 -
 -    void RegisterRuntime(PRUint32 langID, 
 -                         nsCycleCollectionLanguageRuntime *rt);
 -    void ForgetRuntime(PRUint32 langID);
 -
 -    void SelectPurple();
--    void MarkRoots(GCGraph &graph, GCGraphBuilder &builder);
--    void ScanRoots(GCGraph &graph);
--    PRBool CollectWhite(GCGraph &graph); // returns whether anything collected
+-    void MarkRoots(GCGraphBuilder &builder);
+-    void ScanRoots();
+-    void CollectWhite();
+-    PRBool UnrootWhite(); // returns whether anything was collected
 -
 -    nsCycleCollector();
 -    ~nsCycleCollector();
 -
 -    PRBool Suspect(nsISupports *n);
 -    PRBool Forget(nsISupports *n);
 -    PRBool Collect(PRUint32 aTryCollections = 1);
--    PRBool DoCollect();
+-    PRBool BeginCollection();
+-    PRBool FinishCollection();
 -    void Shutdown();
 -
+-    void ClearGraph()
+-    {
+-        mGraph.mNodes.Clear();
+-        mGraph.mEdges.Clear();
+-        mGraph.mRootCount = 0;
+-    }
+-
 -#ifdef DEBUG_CC
 -    nsCycleCollectorStats mStats;    
 -
 -    FILE *mPtrLog;
 -
--    void MaybeDrawGraphs(GCGraph &graph);
+-    void MaybeDrawGraphs();
 -    void Allocated(void *n, size_t sz);
 -    void Freed(void *n);
 -
 -    void ExplainLiveExpectedGarbage();
--    PRBool CreateReversedEdges(GCGraph &graph);
--    void DestroyReversedEdges(GCGraph &graph);
+-    PRBool CreateReversedEdges();
+-    void DestroyReversedEdges();
 -    void ShouldBeFreed(nsISupports *n);
 -    void WasFreed(nsISupports *n);
 -    PointerSet mExpectedGarbage;
 -#endif
 -};
 -
 -
 -class GraphWalker
@@ -5053,73 +5179,105 @@ diff --git a/xpcom/base/nsCycleCollector
 -
 -static nsCycleCollector *sCollector = nsnull;
 -
 -
 -////////////////////////////////////////////////////////////////////////
 -// Utility functions
 -////////////////////////////////////////////////////////////////////////
 -
+-class CCRunnableFaultReport : public nsRunnable {
+-public:
+-    CCRunnableFaultReport(const nsCString& report)
+-    {
+-        CopyUTF8toUTF16(report, mReport);
+-    }
+-    
+-    NS_IMETHOD Run() {
+-        nsCOMPtr<nsIObserverService> obs =
+-            do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
+-        if (obs) {
+-            obs->NotifyObservers(nsnull, "cycle-collector-fault",
+-                                 mReport.get());
+-        }
+-
+-        nsCOMPtr<nsIConsoleService> cons =
+-            do_GetService(NS_CONSOLESERVICE_CONTRACTID);
+-        if (cons) {
+-            cons->LogStringMessage(mReport.get());
+-        }
+-        return NS_OK;
+-    }
+-
+-private:
+-    nsString mReport;
+-};
+-
 -static void
 -Fault(const char *msg, const void *ptr=nsnull)
 -{
 -#ifdef DEBUG_CC
 -    // This should be nearly impossible, but just in case.
 -    if (!sCollector)
 -        return;
 -
 -    if (sCollector->mParams.mFaultIsFatal) {
 -
 -        if (ptr)
 -            printf("Fatal fault in cycle collector: %s (ptr: %p)\n", msg, ptr);
 -        else
 -            printf("Fatal fault in cycle collector: %s\n", msg);
 -
 -     
--        if (sCurrGraph) {
+-        if (sCollector->mGraph.mRootCount > 0) {
 -            FILE *stream;
 -#ifdef WIN32
 -            const char fname[] = "c:\\fault-graph.dot";
 -#else
 -            const char fname[] = "/tmp/fault-graph.dot";
 -#endif
 -            printf("depositing faulting cycle-collection graph in %s\n", fname);
 -            stream = fopen(fname, "w+");
--            WriteGraph(stream, *sCurrGraph, ptr);
+-            WriteGraph(stream, sCollector->mGraph, ptr);
 -            fclose(stream);
 -        } 
 -
 -        exit(1);
 -    }
 -#endif
 -
--    NS_NOTREACHED(nsPrintfCString(256,
--                  "Fault in cycle collector: %s (ptr: %p)\n",
--                  msg, ptr).get());
+-    nsPrintfCString str(256, "Fault in cycle collector: %s (ptr: %p)\n",
+-                        msg, ptr);
+-    NS_NOTREACHED(str.get());
 -
 -    // When faults are not fatal, we assume we're running in a
 -    // production environment and we therefore want to disable the
 -    // collector on a fault. This will unfortunately cause the browser
 -    // to leak pretty fast wherever creates cyclical garbage, but it's
 -    // probably a better user experience than crashing. Besides, we
 -    // *should* never hit a fault.
 -
 -    sCollector->mParams.mDoNothing = PR_TRUE;
+-
+-    // Report to observers off an event so we don't run JS under GC
+-    // (which is where we might be right now).
+-    nsCOMPtr<nsIRunnable> ev = new CCRunnableFaultReport(str);
+-    NS_DispatchToCurrentThread(ev);
 -}
 -
 -#ifdef DEBUG_CC
 -static void
 -Fault(const char *msg, PtrInfo *pi)
 -{
 -    printf("Fault in cycle collector: %s\n"
 -           "  while operating on pointer %p %s\n",
 -           msg, pi->mPointer, pi->mName);
 -    if (pi->mInternalRefs) {
 -        printf("  which has internal references from:\n");
--        NodePool::Enumerator queue(sCurrGraph->mNodes);
+-        NodePool::Enumerator queue(sCollector->mGraph.mNodes);
 -        while (!queue.IsDone()) {
 -            PtrInfo *ppi = queue.GetNext();
 -            for (EdgePool::Iterator e = ppi->mFirstChild, e_end = ppi->mLastChild;
 -                 e != e_end; ++e) {
 -                if (*e == pi) {
 -                    printf("    %p %s\n", ppi->mPointer, ppi->mName);
 -                }
 -            }
@@ -5478,18 +5636,22 @@ diff --git a/xpcom/base/nsCycleCollector
 -
 -void 
 -nsCycleCollector::SelectPurple()
 -{
 -    mPurpleBuf.BumpGeneration();
 -    mPurpleBuf.SelectAgedPointers(&mBuf);
 -}
 -
+-#ifdef DEBUG_CC
+-static void InitMemHook(void);
+-#endif
+-
 -void
--nsCycleCollector::MarkRoots(GCGraph &graph, GCGraphBuilder &builder)
+-nsCycleCollector::MarkRoots(GCGraphBuilder &builder)
 -{
 -    int i;
 -    for (i = 0; i < mBuf.GetSize(); ++i) {
 -        nsISupports *s = static_cast<nsISupports *>(mBuf.ObjectAt(i));
 -        nsXPCOMCycleCollectionParticipant *cp;
 -        ToParticipant(s, &cp);
 -        if (cp) {
 -            PtrInfo *pinfo = builder.AddNode(canonicalize(s), cp,
@@ -5512,20 +5674,20 @@ diff --git a/xpcom/base/nsCycleCollector
 -                }
 -#endif
 -
 -                mPurpleBuf.Remove(s);
 -            }
 -        }
 -    }
 -
--    graph.mRootCount = builder.Count();
+-    mGraph.mRootCount = builder.Count();
 -
 -    // read the PtrInfo out of the graph that we are building
--    NodePool::Enumerator queue(graph.mNodes);
+-    NodePool::Enumerator queue(mGraph.mNodes);
 -    while (!queue.IsDone()) {
 -        PtrInfo *pi = queue.GetNext();
 -        builder.Traverse(pi);
 -    }
 -}
 -
 -
 -////////////////////////////////////////////////////////////////////////
@@ -5571,44 +5733,44 @@ diff --git a/xpcom/base/nsCycleCollector
 -            ScanBlackWalker().Walk(pi);
 -            NS_ASSERTION(pi->mColor == black,
 -                         "Why didn't ScanBlackWalker make pi black?");
 -        }
 -    }
 -};
 -
 -void
--nsCycleCollector::ScanRoots(GCGraph &graph)
+-nsCycleCollector::ScanRoots()
 -{
 -    // On the assumption that most nodes will be black, it's
 -    // probably faster to use a GraphWalker than a
 -    // NodePool::Enumerator.
--    scanWalker().WalkFromRoots(graph); 
+-    scanWalker().WalkFromRoots(mGraph); 
 -
 -#ifdef DEBUG_CC
 -    // Sanity check: scan should have colored all grey nodes black or
 -    // white. So we ensure we have no grey nodes at this point.
--    NodePool::Enumerator etor(graph.mNodes);
+-    NodePool::Enumerator etor(mGraph.mNodes);
 -    while (!etor.IsDone())
 -    {
 -        PtrInfo *pinfo = etor.GetNext();
 -        if (pinfo->mColor == grey) {
 -            Fault("valid grey node after scanning", pinfo);
 -        }
 -    }
 -#endif
 -}
 -
 -
 -////////////////////////////////////////////////////////////////////////
 -// Bacon & Rajan's |CollectWhite| routine, somewhat modified.
 -////////////////////////////////////////////////////////////////////////
 -
--PRBool
--nsCycleCollector::CollectWhite(GCGraph &graph)
+-void
+-nsCycleCollector::CollectWhite()
 -{
 -    // Explanation of "somewhat modified": we have no way to collect the
 -    // set of whites "all at once", we have to ask each of them to drop
 -    // their outgoing links and assume this will cause the garbage cycle
 -    // to *mostly* self-destruct (except for the reference we continue
 -    // to hold). 
 -    // 
 -    // To do this "safely" we must make sure that the white nodes we're
@@ -5623,17 +5785,17 @@ diff --git a/xpcom/base/nsCycleCollector
 -
 -    mBuf.Empty();
 -
 -#if defined(DEBUG_CC) && !defined(__MINGW32__) && defined(WIN32)
 -    struct _CrtMemState ms1, ms2;
 -    _CrtMemCheckpoint(&ms1);
 -#endif
 -
--    NodePool::Enumerator etor(graph.mNodes);
+-    NodePool::Enumerator etor(mGraph.mNodes);
 -    while (!etor.IsDone())
 -    {
 -        PtrInfo *pinfo = etor.GetNext();
 -        if (pinfo->mColor == white) {
 -            mBuf.Push(pinfo);
 -        }
 -    }
 -
@@ -5655,17 +5817,23 @@ diff --git a/xpcom/base/nsCycleCollector
 -#endif
 -        }
 -        else {
 -#ifdef DEBUG_CC
 -            ++mStats.mCollectedNode;
 -#endif
 -        }
 -    }
--
+-}
+-
+-PRBool
+-nsCycleCollector::UnrootWhite()
+-{
+-    nsresult rv;
+-    PRUint32 i, count = mBuf.GetSize();
 -    for (i = 0; i < count; ++i) {
 -        PtrInfo *pinfo = static_cast<PtrInfo*>(mBuf.ObjectAt(i));
 -        rv = pinfo->mParticipant->Unroot(pinfo->mPointer);
 -        if (NS_FAILED(rv))
 -            Fault("Failed unroot call while unlinking", pinfo);
 -    }
 -
 -    mBuf.Empty();
@@ -5970,22 +6138,22 @@ diff --git a/xpcom/base/nsCycleCollector
 -        }
 -    }
 -    
 -    fprintf(stream, "\n}\n");    
 -}
 -
 -
 -void 
--nsCycleCollector::MaybeDrawGraphs(GCGraph &graph)
+-nsCycleCollector::MaybeDrawGraphs()
 -{
 -    if (mParams.mDrawGraphs) {
 -        // We draw graphs only if there were any white nodes.
 -        PRBool anyWhites = PR_FALSE;
--        NodePool::Enumerator fwetor(graph.mNodes);
+-        NodePool::Enumerator fwetor(mGraph.mNodes);
 -        while (!fwetor.IsDone())
 -        {
 -            PtrInfo *pinfo = fwetor.GetNext();
 -            if (pinfo->mColor == white) {
 -                anyWhites = PR_TRUE;
 -                break;
 -            }
 -        }
@@ -5994,17 +6162,17 @@ diff --git a/xpcom/base/nsCycleCollector
 -            // We can't just use _popen here because graphviz-for-windows
 -            // doesn't set up its stdin stream properly, sigh.
 -            FILE *stream;
 -#ifdef WIN32
 -            stream = fopen("c:\\cycle-graph.dot", "w+");
 -#else
 -            stream = popen("dotty -", "w");
 -#endif
--            WriteGraph(stream, graph, nsnull);
+-            WriteGraph(stream, mGraph, nsnull);
 -#ifdef WIN32
 -            fclose(stream);
 -            // Even dotty doesn't work terribly well on windows, since
 -            // they execute lefty asynchronously. So we'll just run 
 -            // lefty ourselves.
 -            _spawnlp(_P_WAIT, 
 -                     "lefty", 
 -                     "lefty",
@@ -6223,56 +6391,62 @@ diff --git a/xpcom/base/nsCycleCollector
 -    if (obs) {
 -        obs->NotifyObservers(nsnull, "cycle-collector-begin", nsnull);
 -    }
 -
 -    mFollowupCollection = PR_FALSE;
 -
 -    PRUint32 totalCollections = 0;
 -    while (aTryCollections > totalCollections) {
--        PRUint32 collections = 0;
+-        PRBool collected;
 -        if (mRuntimes[nsIProgrammingLanguage::JAVASCRIPT]) {
--            collections = static_cast<nsCycleCollectionJSRuntime*>
+-            collected = static_cast<nsCycleCollectionJSRuntime*>
 -                (mRuntimes[nsIProgrammingLanguage::JAVASCRIPT])->Collect();
 -        }
 -        else {
--            collections = DoCollect() ? 1 : 0;
+-            collected = BeginCollection() && FinishCollection();
 -        }
 -
--        if(collections == 0)
+-        if (!collected)
 -            break;
 -        
--        totalCollections += collections;
+-        ++totalCollections;
 -    }
 -
 -    mCollectionInProgress = PR_FALSE;
 -
+-#ifdef XP_OS2
+-    // Now that the cycle collector has freed some memory, we can try to
+-    // force the C library to give back as much memory to the system as
+-    // possible.
+-    _heapmin();
+-#endif
+-
 -#ifdef COLLECT_TIME_DEBUG
 -    printf("cc: Collect() took %lldms\n",
 -           (PR_Now() - start) / PR_USEC_PER_MSEC);
 -#endif
 -#ifdef DEBUG_CC
 -    ExplainLiveExpectedGarbage();
 -#endif
 -    return totalCollections > 0;
 -}
 -
 -PRBool
--nsCycleCollector::DoCollect()
+-nsCycleCollector::BeginCollection()
 -{
 -    if (mParams.mDoNothing)
 -        return PR_FALSE;
 -
 -    // It is also essential to empty mBuf here because starting up
 -    // collection in language runtimes may force some "current" suspects
 -    // into mBuf.
 -    mBuf.Empty();
 -
--    GCGraph graph;
--    GCGraphBuilder builder(graph, mRuntimes);
+-    GCGraphBuilder builder(mGraph, mRuntimes);
 -
 -#ifdef COLLECT_TIME_DEBUG
 -    PRTime now = PR_Now();
 -#endif
 -    for (PRUint32 i = 0; i <= nsIProgrammingLanguage::MAX; ++i) {
 -        if (mRuntimes[i])
 -            mRuntimes[i]->BeginCycleCollection(builder);
 -    }
@@ -6292,55 +6466,53 @@ diff --git a/xpcom/base/nsCycleCollector
 -    PRUint32 purpleEnd = mBuf.GetSize();
 -#endif
 -
 -#ifdef COLLECT_TIME_DEBUG
 -    printf("cc: SelectPurple() took %lldms\n",
 -           (PR_Now() - now) / PR_USEC_PER_MSEC);
 -#endif
 -
--    PRBool didCollect = PR_FALSE;
--
 -    if (builder.Count()  > 0 || mBuf.GetSize() != 0) {
 -        mScanInProgress = PR_TRUE;
 -
 -        // The main Bacon & Rajan collection algorithm.
 -
 -#ifdef COLLECT_TIME_DEBUG
 -        now = PR_Now();
 -#endif
 -
--        MarkRoots(graph, builder);
+-        MarkRoots(builder);
 -
 -#ifdef COLLECT_TIME_DEBUG
 -        {
 -            PRTime then = PR_Now();
 -            printf("cc: MarkRoots() took %lldms\n",
 -                   (then - now) / PR_USEC_PER_MSEC);
 -            now = then;
 -        }
 -#endif
 -
--        ScanRoots(graph);