Rebase to actionmonkey tip
authorBenjamin Smedberg <benjamin@smedbergs.us>
Fri, 11 Jul 2008 18:35:53 -0400
changeset 153 cd96178a2e47
parent 152 4c630a56956e
child 154 7b66eb66ba95
push id30
push userbsmedberg@mozilla.com
push dateSun, 13 Jul 2008 14:45:31 +0000
Rebase to actionmonkey tip
comarray.patch
comptr-rewrite.patch
content-hashtables
content-stack-classes
core-refcounting
core-refcounting2
editor-stack-classes
gc-hashtables.patch
gcobject-nodelete.patch
gfx-refcounting
gfx-refcounting2
hgignore-update
layout-stack-classes
mozStorageStatementScoper-stackclass
no-standaloneglue.patch
nsCanvasRenderingContext2D_ContextState-okonstack
nsMorkReader-stackclass
nsProxiedService-stackclass
nsSlots
propertycache-gc-assert
remove-cycle
root-contentutils
root-layout-stuff
series
stack-comptr-fixup
static-check-gc-attributes
system-metrics-comarray
tamarin-bug-427030-v1.patch
tamarin-bug-427030-v1.patch2
tamarin-debug-print-finalizers
--- a/comarray.patch
+++ b/comarray.patch
@@ -1,12 +1,12 @@
 diff --git a/browser/components/migration/src/nsPhoenixProfileMigrator.h b/browser/components/migration/src/nsPhoenixProfileMigrator.h
 --- a/browser/components/migration/src/nsPhoenixProfileMigrator.h
 +++ b/browser/components/migration/src/nsPhoenixProfileMigrator.h
-@@ -48,7 +48,6 @@
+@@ -48,7 +48,6 @@ class nsIFile;
  class nsIFile;
  class nsIPrefBranch;
  class nsIPrefService;
 -class nsVoidArray;
  
  class nsPhoenixProfileMigrator : public nsNetscapeProfileMigratorBase, 
                                   public nsIBrowserProfileMigrator
 diff --git a/browser/components/migration/src/nsSeamonkeyProfileMigrator.h b/browser/components/migration/src/nsSeamonkeyProfileMigrator.h
@@ -23,50 +23,50 @@ 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
-@@ -93,7 +93,6 @@
+@@ -96,7 +96,6 @@ class nsIRunnable;
  class nsIRunnable;
  template<class E> class nsCOMArray;
  class nsIPref;
 -class nsVoidArray;
  struct JSRuntime;
  class nsICaseConversion;
- class nsIWidget;
+ class nsIUGenCategory;
 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
-@@ -48,7 +48,6 @@
+@@ -48,7 +48,6 @@ class nsIAtom;
  class nsIAtom;
  class nsIDocument;
  class nsPresContext;
 -class nsVoidArray;
  class nsIDOMEvent;
  class nsIContent;
  class nsIEventListenerManager;
 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
-@@ -55,7 +55,6 @@
+@@ -55,7 +55,6 @@ class nsEventChainPostVisitor;
  class nsEventChainPostVisitor;
  class nsIEventListenerManager;
  class nsIPrincipal;
 -class nsVoidArray;
  class nsIMutationObserver;
  class nsChildContentList;
  class nsNodeWeakReference;
 diff --git a/content/base/src/nsGenericElement.h b/content/base/src/nsGenericElement.h
 --- a/content/base/src/nsGenericElement.h
 +++ b/content/base/src/nsGenericElement.h
-@@ -72,7 +72,6 @@
+@@ -72,7 +72,6 @@ class nsDOMCSSDeclaration;
  class nsDOMCSSDeclaration;
  class nsIDOMCSSStyleDeclaration;
  class nsIURI;
 -class nsVoidArray;
  class nsINodeInfo;
  class nsIControllers;
  class nsIDOMNSFeatureFactory;
 diff --git a/content/base/src/nsRange.h b/content/base/src/nsRange.h
@@ -108,39 +108,39 @@ diff --git a/editor/txmgr/src/nsTransact
  class nsTransactionRedoStack;
 -class nsVoidArray;
  
  /** implementation of a transaction manager object.
   *
 diff --git a/layout/base/nsCSSFrameConstructor.h b/layout/base/nsCSSFrameConstructor.h
 --- a/layout/base/nsCSSFrameConstructor.h
 +++ b/layout/base/nsCSSFrameConstructor.h
-@@ -61,7 +61,6 @@
+@@ -61,7 +61,6 @@ struct nsStyleContent;
  struct nsStyleContent;
  struct nsStyleDisplay;
  class nsIPresShell;
 -class nsVoidArray;
  class nsFrameManager;
  class nsIDOMHTMLSelectElement;
  class nsPresContext;
 diff --git a/layout/forms/nsIComboboxControlFrame.h b/layout/forms/nsIComboboxControlFrame.h
 --- a/layout/forms/nsIComboboxControlFrame.h
 +++ b/layout/forms/nsIComboboxControlFrame.h
-@@ -44,7 +44,6 @@
+@@ -44,7 +44,6 @@ class nsPresContext;
  class nsPresContext;
  class nsString;
  class nsIContent;
 -class nsVoidArray;
  class nsCSSFrameConstructor;
  
  
 diff --git a/layout/forms/nsListControlFrame.h b/layout/forms/nsListControlFrame.h
 --- a/layout/forms/nsListControlFrame.h
 +++ b/layout/forms/nsListControlFrame.h
-@@ -63,9 +63,6 @@
+@@ -63,9 +63,6 @@ class nsIDOMHTMLOptionElement;
  class nsIDOMHTMLOptionElement;
  class nsIComboboxControlFrame;
  class nsPresContext;
 -class nsVoidArray;
 -
 -class nsVoidArray;
  class nsListEventListener;
  
@@ -154,17 +154,17 @@ diff --git a/layout/tables/nsTableColFra
  
 -class nsVoidArray;
  class nsTableCellFrame;
  
  enum nsTableColType {
 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
-@@ -54,6 +54,7 @@
+@@ -54,6 +54,7 @@ struct nsListIter;
  struct nsListIter;
  struct nsEnumerationData;
  
 +class nsIPrefBranch;
  class nsICookiePermission;
  class nsIEffectiveTLDService;
  class nsIPrefBranch;
 diff --git a/rdf/datasource/public/nsIRDFFileSystem.h b/rdf/datasource/public/nsIRDFFileSystem.h
@@ -178,17 +178,17 @@ diff --git a/rdf/datasource/public/nsIRD
 -
 -
  #define NS_IRDFFILESYSTEMDATAOURCE_IID \
  { 0x1222e6f0, 0xa5e3, 0x11d2, { 0x8b, 0x7c, 0x00, 0x80, 0x5f, 0x8a, 0x7d, 0xb5 } }
  
 diff --git a/widget/src/windows/nsDataObj.h b/widget/src/windows/nsDataObj.h
 --- a/widget/src/windows/nsDataObj.h
 +++ b/widget/src/windows/nsDataObj.h
-@@ -128,7 +128,6 @@
+@@ -128,7 +128,6 @@ typedef struct _FILEGROUPDESCRIPTORW {
  # endif /*__W32API_MAJOR_VERSION*/
  #endif /*__MINGW32__*/
  
 -class nsVoidArray;
  class CEnumFormatEtc;
  class nsITransferable;
  
 diff --git a/widget/src/xpwidgets/nsTransferable.h b/widget/src/xpwidgets/nsTransferable.h
@@ -206,17 +206,17 @@ diff --git a/widget/src/xpwidgets/nsTran
  class nsDataObj;
 -class nsVoidArray;
  
  
  /**
 diff --git a/xpcom/base/Makefile.in b/xpcom/base/Makefile.in
 --- a/xpcom/base/Makefile.in
 +++ b/xpcom/base/Makefile.in
-@@ -53,7 +53,6 @@
+@@ -53,7 +53,6 @@ REQUIRES	= string \
  		  $(NULL)
  
  CPPSRCS		= \
 -		nsAllocator.cpp \
  		nsVersionComparatorImpl.cpp \
  		nsConsoleMessage.cpp \
  		nsConsoleService.cpp \
 diff --git a/xpcom/base/nsAllocator.cpp b/xpcom/base/nsAllocator.cpp
@@ -318,17 +318,17 @@ deleted file mode 100644
 -#include "prmem.h"
 -#include "nsAgg.h"
 -#include "nsIFactory.h"
 -
 -#endif // nsAllocator_h__
 diff --git a/xpcom/glue/Makefile.in b/xpcom/glue/Makefile.in
 --- a/xpcom/glue/Makefile.in
 +++ b/xpcom/glue/Makefile.in
-@@ -70,6 +70,7 @@
+@@ -74,6 +74,7 @@ CPPSRCS		= \
  
  SDK_HEADERS = \
  		pldhash.h \
 +		nsAllocator.h \
  		nsArrayEnumerator.h \
  		nsArrayUtils.h \
  		nsAutoLock.h \
 diff --git a/xpcom/glue/nsAllocator.cpp b/xpcom/glue/nsAllocator.cpp
@@ -506,17 +506,17 @@ diff --git a/xpcom/glue/nsCOMArray.h b/x
  #ifndef nsCOMArray_h__
  #define nsCOMArray_h__
  
 -#include "nsVoidArray.h"
 +#include "nsVoidArray.h" // for enumerator type declarations
  #include "nsISupports.h"
  
  // See below for the definition of nsCOMArray<T>
-@@ -118,7 +118,7 @@
+@@ -118,7 +118,7 @@ private:
  private:
      
      // the actual storage
 -    nsVoidArray mArray;
 +    nsVoidArrayBase<GCAllocator> mArray;
  
      // don't implement these, defaults will muck with refcounts!
      nsCOMArray_base& operator=(const nsCOMArray_base& other);
@@ -1207,17 +1207,17 @@ diff --git a/xpcom/glue/nsVoidArray.h b/
  #include "nsDebug.h"
 +#include "nsAllocator.h"
 +#include "nsQuickSort.h"
 +#include "prbit.h"
 +#include "nsCRTGlue.h"
  
  // Comparator callback function for sorting array values.
  typedef int (* PR_CALLBACK nsVoidArrayComparatorFunc)
-@@ -50,14 +54,15 @@
+@@ -50,14 +54,15 @@ typedef int (* PR_CALLBACK nsVoidArrayCo
  // Enumerator callback function. Return PR_FALSE to stop
  typedef PRBool (* PR_CALLBACK nsVoidArrayEnumFunc)(void* aElement, void *aData);
  
 -/// A basic zero-based array of void*'s that manages its own memory
 -class NS_COM_GLUE nsVoidArray {
 +/// A basic zero-based array of void*'s that manages its own memory using the C allocator malloc/free
 +template<class Allocator>
 +class nsVoidArrayBase {
@@ -1229,35 +1229,35 @@ diff --git a/xpcom/glue/nsVoidArray.h b/
 +  nsVoidArrayBase(PRInt32 aCount);  // initial count of aCount elements set to nsnull
 +  ~nsVoidArrayBase();
  
 -  nsVoidArray& operator=(const nsVoidArray& other);
 +  nsVoidArrayBase<Allocator>& operator=(const nsVoidArrayBase<Allocator>& other);
  
    inline PRInt32 Count() const {
      return mImpl ? mImpl->mCount : 0;
-@@ -98,7 +103,7 @@
+@@ -98,7 +103,7 @@ public:
    PRInt32 IndexOf(void* aPossibleElement) const;
  
    PRBool InsertElementAt(void* aElement, PRInt32 aIndex);
 -  PRBool InsertElementsAt(const nsVoidArray &other, PRInt32 aIndex);
 +  PRBool InsertElementsAt(const nsVoidArrayBase<Allocator> &other, PRInt32 aIndex);
  
    PRBool ReplaceElementAt(void* aElement, PRInt32 aIndex);
  
-@@ -109,7 +114,7 @@
+@@ -109,7 +114,7 @@ public:
      return InsertElementAt(aElement, Count());
    }
  
 -  PRBool AppendElements(nsVoidArray& aElements) {
 +  PRBool AppendElements(nsVoidArrayBase<Allocator>& aElements) {
      return InsertElementsAt(aElements, Count());
    }
  
-@@ -130,6 +135,19 @@
+@@ -130,6 +135,19 @@ public:
    PRBool EnumerateBackwards(nsVoidArrayEnumFunc aFunc, void* aData);
  
  protected:
 +  /**
 +   * Grow the array by at least this many elements at a time.
 +   */
 +  static const PRInt32 kMinGrowArrayBy = 8;
 +  static const PRInt32 kMaxGrowArrayBy = 1024;
@@ -1267,17 +1267,17 @@ diff --git a/xpcom/glue/nsVoidArray.h b/
 +   * This is the threshold (in bytes) of the mImpl struct, past which
 +   * we'll force the array to grow geometrically
 +   */
 +  static const PRInt32 kLinearThreshold = 24 * sizeof(void *);
 +
    PRBool GrowArrayBy(PRInt32 aGrowBy);
  
    struct Impl {
-@@ -152,6 +170,31 @@
+@@ -152,6 +170,31 @@ protected:
      void*   mArray[1];
    };
  
 +  /**
 +   * Compute the number of bytes requires for the mImpl struct that will
 +   * hold |n| elements.
 +   */
 +  static size_t Sizeof_Impl(int n) {
@@ -1299,17 +1299,17 @@ diff --git a/xpcom/glue/nsVoidArray.h b/
 +    void* mData;
 +  };
 +
 +  static int Comparator(const void* aElement1, const void* aElement2, void* aData);
 +
    Impl* mImpl;
  #if DEBUG_VOIDARRAY
    PRInt32 mMaxCount;
-@@ -179,26 +222,31 @@
+@@ -179,26 +222,31 @@ protected:
  
  private:
    /// Copy constructors are not allowed
 -  nsVoidArray(const nsVoidArray& other);
 +  nsVoidArrayBase(const nsVoidArrayBase<Allocator>& other);
  };
  
 +typedef nsVoidArrayBase<CAllocator> nsVoidArray;
@@ -1337,17 +1337,17 @@ diff --git a/xpcom/glue/nsVoidArray.h b/
 -  char mAutoBuf[sizeof(Impl) + (kAutoBufSize - 1) * sizeof(void*)];
 +  char mAutoBuf[sizeof(typename Base::Impl) + (Base::kAutoBufSize - 1) * sizeof(void*)];
  };
  
 +typedef nsAutoVoidArrayBase<CAllocator> nsAutoVoidArray;
  
  class nsString;
  
-@@ -438,4 +486,536 @@
+@@ -438,4 +486,536 @@ private:
    PRBool EnsureArray();
  };
  
 +template<class Allocator>
 +inline void
 +nsVoidArrayBase<Allocator>::SetArray(Impl *newImpl, PRInt32 aSize, PRInt32 aCount,
 +				     PRBool aOwner, PRBool aHasAuto)
 +{
@@ -1877,16 +1877,16 @@ diff --git a/xpcom/glue/nsVoidArray.h b/
 +  // but we'll clear it at that time if needed to save CPU cycles.
 +  ResetToAutoBuffer();
 +}
 +
  #endif /* nsVoidArray_h___ */
 diff --git a/xpcom/glue/objs.mk b/xpcom/glue/objs.mk
 --- a/xpcom/glue/objs.mk
 +++ b/xpcom/glue/objs.mk
-@@ -41,6 +41,7 @@
+@@ -41,6 +41,7 @@ XPCOM_GLUE_SRC_CSRCS = $(addprefix $(top
  XPCOM_GLUE_SRC_CSRCS = $(addprefix $(topsrcdir)/xpcom/glue/, $(XPCOM_GLUE_SRC_LCSRCS))
  
  XPCOM_GLUE_SRC_LCPPSRCS =        \
 +  nsAllocator.cpp                \
    nsArrayEnumerator.cpp          \
    nsArrayUtils.cpp               \
    nsCategoryCache.cpp            \
--- a/comptr-rewrite.patch
+++ b/comptr-rewrite.patch
@@ -313,17 +313,17 @@ diff --git a/content/base/src/nsGenericE
 -    return;
 -  }
 -
 -  delete this;
 -}
  
  nsresult
  nsDOMEventRTTearoff::GetDOM3EventTarget(nsIDOM3EventTarget **aTarget)
-@@ -4077,8 +4004,7 @@ nsGenericElement::List(FILE* out, PRInt3
+@@ -4100,8 +4027,7 @@ nsGenericElement::List(FILE* out, PRInt3
  
    ListAttributes(out);
  
 -  fprintf(out, " intrinsicstate=[%08x]", IntrinsicState());
 -  fprintf(out, " refcount=%d<", mRefCnt.get());
 +  fprintf(out, " intrinsicstate=[%08x]<", IntrinsicState());
  
    PRUint32 i, length = GetChildCount();
@@ -604,42 +604,42 @@ diff --git a/content/base/src/nsNodeInfo
  
 -  nsAutoRefCnt mRefCnt;
    NS_DECL_OWNINGTHREAD
  
    PLHashTable *mNodeInfoHash;
 diff --git a/content/base/src/nsTextNode.cpp b/content/base/src/nsTextNode.cpp
 --- a/content/base/src/nsTextNode.cpp
 +++ b/content/base/src/nsTextNode.cpp
-@@ -236,8 +236,7 @@ nsTextNode::List(FILE* out, PRInt32 aInd
+@@ -238,8 +238,7 @@ nsTextNode::List(FILE* out, PRInt32 aInd
    for (index = aIndent; --index >= 0; ) fputs("  ", out);
  
    fprintf(out, "Text@%p", this);
 -  fprintf(out, " intrinsicstate=[%08x]", IntrinsicState());
 -  fprintf(out, " refcount=%d<", mRefCnt.get());
 +  fprintf(out, " intrinsicstate=[%08x]<", IntrinsicState());
  
    nsAutoString tmp;
    ToCString(tmp, 0, mText.GetLength());
 diff --git a/content/events/src/nsEventDispatcher.cpp b/content/events/src/nsEventDispatcher.cpp
 --- a/content/events/src/nsEventDispatcher.cpp
 +++ b/content/events/src/nsEventDispatcher.cpp
-@@ -498,8 +498,6 @@ nsEventDispatcher::Dispatch(nsISupports*
+@@ -493,8 +493,6 @@ nsEventDispatcher::Dispatch(nsISupports*
    if (!externalDOMEvent && preVisitor.mDOMEvent) {
      // An nsDOMEvent was created while dispatching the event.
      // Duplicate private data if someone holds a pointer to it.
 -    nsrefcnt rc = 0;
 -    NS_RELEASE2(preVisitor.mDOMEvent, rc);
      nsCOMPtr<nsIPrivateDOMEvent> privateEvent =
        do_QueryInterface(preVisitor.mDOMEvent);
      if (privateEvent) {
 diff --git a/content/html/document/src/nsHTMLDocument.h b/content/html/document/src/nsHTMLDocument.h
 --- a/content/html/document/src/nsHTMLDocument.h
 +++ b/content/html/document/src/nsHTMLDocument.h
-@@ -78,9 +78,6 @@ public:
+@@ -77,9 +77,6 @@ public:
    virtual nsresult Init();
  
    NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr);
 -
 -  NS_IMETHOD_(nsrefcnt) AddRef(void);
 -  NS_IMETHOD_(nsrefcnt) Release(void);
  
    virtual void Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup);
@@ -958,17 +958,17 @@ diff --git a/content/xbl/src/nsXBLProtot
          nsISupportsKey key(atom);
 -        xblIns->AddRef();
          mInsertionPointTable->Put(&key, xblIns);
            
          token = nsCRT::strtok( newStr, "| ", &newStr );
 diff --git a/content/xml/content/src/nsXMLCDATASection.cpp b/content/xml/content/src/nsXMLCDATASection.cpp
 --- a/content/xml/content/src/nsXMLCDATASection.cpp
 +++ b/content/xml/content/src/nsXMLCDATASection.cpp
-@@ -169,7 +169,7 @@ nsXMLCDATASection::List(FILE* out, PRInt
+@@ -171,7 +171,7 @@ nsXMLCDATASection::List(FILE* out, PRInt
    PRInt32 index;
    for (index = aIndent; --index >= 0; ) fputs("  ", out);
  
 -  fprintf(out, "CDATASection refcount=%d<", mRefCnt.get());
 +  fprintf(out, "CDATASection<");
  
    nsAutoString tmp;
    ToCString(tmp, 0, mText.GetLength());
@@ -2331,17 +2331,17 @@ diff --git a/intl/unicharutil/src/nsCate
 -  return nsrefcnt(1);
 -}
  
  nsCategoryImp* nsCategoryImp::GetInstance()
  {
 diff --git a/js/src/xpconnect/shell/xpcshell.cpp b/js/src/xpconnect/shell/xpcshell.cpp
 --- a/js/src/xpconnect/shell/xpcshell.cpp
 +++ b/js/src/xpconnect/shell/xpcshell.cpp
-@@ -899,11 +899,11 @@ ProcessArgs(JSContext *cx, JSObject *obj
+@@ -907,11 +907,11 @@ ProcessArgs(JSContext *cx, JSObject *obj
  
  /***************************************************************************/
  
 -class FullTrustSecMan
 +class FullTrustSecMan : public XPCOMGCFinalizedObject
  #ifndef XPCONNECT_STANDALONE
 -  : public nsIScriptSecurityManager
 +                      , public nsIScriptSecurityManager
@@ -2594,26 +2594,26 @@ diff --git a/js/src/xpconnect/src/xpcpri
      static void
      SystemIsBeingShutDown(JSContext* cx);
 -
 -    static void
 -    TraceJS(JSTracer* trc, XPCJSRuntime* rt);
  
      static void
      FinishedMarkPhaseOfGC(JSContext* cx, XPCJSRuntime* rt);
-@@ -2246,8 +2240,6 @@ public:
+@@ -2239,8 +2233,6 @@ public:
                          nsIClassInfo* classInfo,
                          XPCNativeScriptableCreateInfo* sciProto);
  
 -    JSBool HasExternalReference() const {return mRefCnt > 1;}
 -
      JSObject* GetWrapper()              { return mWrapper; }
      void      SetWrapper(JSObject *obj) { mWrapper = obj; }
  
-@@ -2477,21 +2469,8 @@ public:
+@@ -2470,21 +2462,8 @@ public:
      JSBool IsValid() const {return mJSObj != nsnull;}
      void SystemIsBeingShutDown(JSRuntime* rt);
  
 -    // This is used by XPCJSRuntime::GCCallback to find wrappers that no
 -    // longer root their JSObject and are only still alive because they
 -    // were being used via nsSupportsWeakReference at the time when their
 -    // last (outside) reference was released. Wrappers that fit into that
 -    // category are only deleted when we see that their corresponding JSObject
@@ -2625,25 +2625,25 @@ diff --git a/js/src/xpconnect/src/xpcpri
 -
 -    void TraceJS(JSTracer* trc);
 -#ifdef DEBUG
 -    static void PrintTraceName(JSTracer* trc, char *buf, size_t bufsize);
 -#endif
  
      virtual ~nsXPCWrappedJS();
  protected:
-@@ -3177,7 +3156,6 @@ public:
+@@ -3172,7 +3151,6 @@ public:
      static nsXPCThreadJSContextStackImpl* GetSingleton();
  
      static void InitStatics() { gXPCThreadJSContextStack = nsnull; }
 -    static void FreeSingleton();
  
      nsXPCThreadJSContextStackImpl();
      virtual ~nsXPCThreadJSContextStackImpl();
-@@ -3255,12 +3233,11 @@ class nsJSRuntimeServiceImpl : public ns
+@@ -3250,12 +3228,11 @@ class nsJSRuntimeServiceImpl : public ns
  
      static void FreeSingleton();
  
 -    nsJSRuntimeServiceImpl();
 -    virtual ~nsJSRuntimeServiceImpl();
 +    nsJSRuntimeServiceImpl() {}
 +    ~nsJSRuntimeServiceImpl() {}
  
@@ -2883,17 +2883,17 @@ diff --git a/js/src/xpconnect/src/xpcwra
 -    // This reference will be released when mFlatJSObject is finalized.
 -    // Since this reference will push the refcount to 2 it will also root
 -    // mFlatJSObject;
 -    NS_ASSERTION(1 == mRefCnt, "unexpected refcount value");
 -    NS_ADDREF(this);
  
      if(si && si->GetFlags().WantCreate() &&
         NS_FAILED(si->GetCallback()->Create(this, ccx, mFlatJSObject)))
-@@ -2648,7 +2642,7 @@ NS_IMETHODIMP XPCWrappedNative::DebugDum
+@@ -2654,7 +2648,7 @@ NS_IMETHODIMP XPCWrappedNative::DebugDum
  {
  #ifdef DEBUG
      depth-- ;
 -    XPC_LOG_ALWAYS(("XPCWrappedNative @ %x with mRefCnt = %d", this, mRefCnt.get()));
 +    XPC_LOG_ALWAYS(("XPCWrappedNative @ %x", this));
      XPC_LOG_INDENT();
  
          if(HasProto())
@@ -2967,25 +2967,25 @@ diff --git a/js/src/xpconnect/tests/comp
 -  return mRefCnt;
 -}
  
  NS_IMETHODIMP
  xpctestNoisy::QueryInterface(REFNSIID iid, void** result)
 diff --git a/layout/build/nsLayoutStatics.cpp b/layout/build/nsLayoutStatics.cpp
 --- a/layout/build/nsLayoutStatics.cpp
 +++ b/layout/build/nsLayoutStatics.cpp
-@@ -245,7 +245,6 @@ nsLayoutStatics::Shutdown()
+@@ -258,7 +258,6 @@ nsLayoutStatics::Shutdown()
    nsDOMStorageManager::Shutdown();
    txMozillaXSLTProcessor::Shutdown();
    nsDOMAttribute::Shutdown();
 -  nsDOMEventRTTearoff::Shutdown();
    nsEventListenerManager::Shutdown();
    nsContentList::Shutdown();
    nsComputedDOMStyle::Shutdown();
-@@ -292,7 +291,6 @@ nsLayoutStatics::Shutdown()
+@@ -305,7 +304,6 @@ nsLayoutStatics::Shutdown()
  
    nsAttrValue::Shutdown();
    nsContentUtils::Shutdown();
 -  nsNodeInfo::ClearCache();
    nsLayoutStylesheetCache::Shutdown();
    NS_NameSpaceManagerShutdown();
    nsStyleSet::FreeGlobals();
 diff --git a/layout/generic/nsGfxScrollFrame.cpp b/layout/generic/nsGfxScrollFrame.cpp
@@ -3198,17 +3198,17 @@ diff --git a/layout/style/nsCSSRule.h b/
  protected:
 -  nsAutoRefCnt mRefCnt;
    NS_DECL_OWNINGTHREAD
  public:
  
 diff --git a/layout/style/nsCSSStyleRule.cpp b/layout/style/nsCSSStyleRule.cpp
 --- a/layout/style/nsCSSStyleRule.cpp
 +++ b/layout/style/nsCSSStyleRule.cpp
-@@ -817,11 +817,6 @@ public:
+@@ -864,11 +864,6 @@ public:
                                              nsICSSParser** aCSSParser);
    virtual nsresult DeclarationChanged();
  
 -  // Override |AddRef| and |Release| for being a member of
 -  // |DOMCSSStyleRuleImpl|.
 -  NS_IMETHOD_(nsrefcnt) AddRef(void);
 -  NS_IMETHOD_(nsrefcnt) Release(void);
 -
@@ -3232,17 +3232,17 @@ diff --git a/layout/style/nsCSSStyleShee
    : nsICSSStyleSheet(),
 -    mRefCnt(0),
      mTitle(aCopy.mTitle), 
      mMedia(nsnull),
      mFirstChild(nsnull), 
 diff --git a/layout/style/nsComputedDOMStyle.cpp b/layout/style/nsComputedDOMStyle.cpp
 --- a/layout/style/nsComputedDOMStyle.cpp
 +++ b/layout/style/nsComputedDOMStyle.cpp
-@@ -80,29 +80,15 @@
+@@ -81,29 +81,15 @@
   * returned by the getComputedStyle() function.
   */
  
 -static nsComputedDOMStyle *sCachedComputedDOMStyle;
 -
  nsresult
  NS_NewComputedDOMStyle(nsIComputedDOMStyle** aComputedStyle)
  {
@@ -3265,30 +3265,30 @@ diff --git a/layout/style/nsComputedDOMS
 -  }
 -
 -  NS_ADDREF(*aComputedStyle);
 +  *aComputedStyle = new nsComputedDOMStyle();
 +  NS_ENSURE_TRUE(*aComputedStyle, NS_ERROR_OUT_OF_MEMORY);
  
    return NS_OK;
  }
-@@ -129,12 +115,6 @@ void
+@@ -130,12 +116,6 @@ void
  void
  nsComputedDOMStyle::Shutdown()
  {
 -  // We want to de-allocate without calling the dtor since we
 -  // already did that manually in doDestroyComputedDOMStyle(),
 -  // so cast our cached object to something that doesn't know
 -  // about our dtor.
 -  delete reinterpret_cast<char*>(sCachedComputedDOMStyle);
 -  sCachedComputedDOMStyle = nsnull;
  }
  
  
-@@ -148,26 +128,6 @@ NS_INTERFACE_MAP_BEGIN(nsComputedDOMStyl
+@@ -149,26 +129,6 @@ NS_INTERFACE_MAP_BEGIN(nsComputedDOMStyl
    NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIComputedDOMStyle)
    NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(ComputedCSSStyleDeclaration)
  NS_INTERFACE_MAP_END
 -
 -
 -static void doDestroyComputedDOMStyle(nsComputedDOMStyle *aComputedStyle)
 -{
 -  if (!sCachedComputedDOMStyle) {
@@ -5209,27 +5209,27 @@ diff --git a/rdf/base/src/nsCompositeDat
 +                                             mAllowNegativeAssertions,
 +                                             mCoalesceDuplicateArcs);
  
      if (! result)
          return NS_ERROR_OUT_OF_MEMORY;
 diff --git a/rdf/base/src/nsInMemoryDataSource.cpp b/rdf/base/src/nsInMemoryDataSource.cpp
 --- a/rdf/base/src/nsInMemoryDataSource.cpp
 +++ b/rdf/base/src/nsInMemoryDataSource.cpp
-@@ -427,7 +427,8 @@ public:
+@@ -438,7 +438,8 @@ public:
  /**
   * InMemoryAssertionEnumeratorImpl
   */
 -class InMemoryAssertionEnumeratorImpl : public nsISimpleEnumerator
 +class InMemoryAssertionEnumeratorImpl : public XPCOMGCFinalizedObject
 +                                      , public nsISimpleEnumerator
  {
  private:
      InMemoryDataSource* mDataSource;
-@@ -440,44 +441,14 @@ private:
+@@ -451,44 +452,14 @@ private:
      Assertion*      mNextAssertion;
      nsCOMPtr<nsISupportsArray> mHashArcs;
  
 -    // Hide so that only Create() and Destroy() can be used to
 -    // allocate and deallocate from the heap
 -    static void* operator new(size_t) CPP_THROW_NEW { return 0; }
 -    static void operator delete(void*, size_t) {}
 +    virtual ~InMemoryAssertionEnumeratorImpl();
@@ -5266,48 +5266,48 @@ diff --git a/rdf/base/src/nsInMemoryData
 -        // Grab the pool from the datasource; since we keep the
 -        // datasource alive, this has to be safe.
 -        nsFixedSizeAllocator& pool = aEnumerator->mDataSource->mAllocator;
 -        aEnumerator->~InMemoryAssertionEnumeratorImpl();
 -        pool.Free(aEnumerator, sizeof(*aEnumerator)); }
  
      // nsISupports interface
      NS_DECL_ISUPPORTS
-@@ -548,7 +519,6 @@ InMemoryAssertionEnumeratorImpl::~InMemo
+@@ -559,7 +530,6 @@ InMemoryAssertionEnumeratorImpl::~InMemo
  }
  
  NS_IMPL_ADDREF(InMemoryAssertionEnumeratorImpl)
 -NS_IMPL_RELEASE_WITH_DESTROY(InMemoryAssertionEnumeratorImpl, Destroy(this))
  NS_IMPL_QUERY_INTERFACE1(InMemoryAssertionEnumeratorImpl, nsISimpleEnumerator)
  
  NS_IMETHODIMP
-@@ -631,11 +601,6 @@ class InMemoryArcsEnumeratorImpl : publi
+@@ -642,11 +612,6 @@ class InMemoryArcsEnumeratorImpl : publi
  class InMemoryArcsEnumeratorImpl : public nsISimpleEnumerator
  {
  private:
 -    // Hide so that only Create() and Destroy() can be used to
 -    // allocate and deallocate from the heap
 -    static void* operator new(size_t) CPP_THROW_NEW { return 0; }
 -    static void operator delete(void*, size_t) {}
 -
      InMemoryDataSource* mDataSource;
      nsIRDFResource*     mSource;
      nsIRDFNode*         mTarget;
-@@ -643,10 +608,6 @@ private:
+@@ -654,10 +619,6 @@ private:
      nsIRDFResource*     mCurrent;
      Assertion*          mAssertion;
      nsCOMPtr<nsISupportsArray> mHashArcs;
 -
 -    InMemoryArcsEnumeratorImpl(InMemoryDataSource* aDataSource,
 -                               nsIRDFResource* aSource,
 -                               nsIRDFNode* aTarget);
  
      virtual ~InMemoryArcsEnumeratorImpl();
  
-@@ -661,26 +622,9 @@ public:
+@@ -672,26 +633,9 @@ public:
      // nsISimpleEnumerator interface
      NS_DECL_NSISIMPLEENUMERATOR
  
 -    static InMemoryArcsEnumeratorImpl*
 -    Create(InMemoryDataSource* aDataSource,
 -           nsIRDFResource* aSource,
 -           nsIRDFNode* aTarget) {
 -        void* place = aDataSource->mAllocator.Alloc(sizeof(InMemoryArcsEnumeratorImpl));
@@ -5327,56 +5327,56 @@ diff --git a/rdf/base/src/nsInMemoryData
 -        aEnumerator->~InMemoryArcsEnumeratorImpl();
 -        pool.Free(aEnumerator, sizeof(*aEnumerator)); }
 +    InMemoryArcsEnumeratorImpl(InMemoryDataSource* aDataSource,
 +                               nsIRDFResource* aSource,
 +                               nsIRDFNode* aTarget);
  };
  
  
-@@ -747,7 +691,6 @@ InMemoryArcsEnumeratorImpl::~InMemoryArc
+@@ -758,7 +702,6 @@ InMemoryArcsEnumeratorImpl::~InMemoryArc
  }
  
  NS_IMPL_ADDREF(InMemoryArcsEnumeratorImpl)
 -NS_IMPL_RELEASE_WITH_DESTROY(InMemoryArcsEnumeratorImpl, Destroy(this))
  NS_IMPL_QUERY_INTERFACE1(InMemoryArcsEnumeratorImpl, nsISimpleEnumerator)
  
  NS_IMETHODIMP
-@@ -1207,8 +1150,8 @@ InMemoryDataSource::GetSources(nsIRDFRes
+@@ -1218,8 +1161,8 @@ InMemoryDataSource::GetSources(nsIRDFRes
          return NS_ERROR_NULL_POINTER;
  
      InMemoryAssertionEnumeratorImpl* result =
 -        InMemoryAssertionEnumeratorImpl::Create(this, nsnull, aProperty,
 -                                                  aTarget, aTruthValue);
 +        new InMemoryAssertionEnumeratorImpl(this, nsnull, aProperty,
 +                                            aTarget, aTruthValue);
  
      if (! result)
          return NS_ERROR_OUT_OF_MEMORY;
-@@ -1238,8 +1181,8 @@ InMemoryDataSource::GetTargets(nsIRDFRes
+@@ -1249,8 +1192,8 @@ InMemoryDataSource::GetTargets(nsIRDFRes
          return NS_ERROR_NULL_POINTER;
  
      InMemoryAssertionEnumeratorImpl* result =
 -        InMemoryAssertionEnumeratorImpl::Create(this, aSource, aProperty,
 -                                                nsnull, aTruthValue);
 +        new InMemoryAssertionEnumeratorImpl(this, aSource, aProperty,
 +                                            nsnull, aTruthValue);
  
      if (! result)
          return NS_ERROR_OUT_OF_MEMORY;
-@@ -1744,7 +1687,7 @@ InMemoryDataSource::ArcLabelsIn(nsIRDFNo
+@@ -1755,7 +1698,7 @@ InMemoryDataSource::ArcLabelsIn(nsIRDFNo
          return NS_ERROR_NULL_POINTER;
  
      InMemoryArcsEnumeratorImpl* result =
 -        InMemoryArcsEnumeratorImpl::Create(this, nsnull, aTarget);
 +        new InMemoryArcsEnumeratorImpl(this, nsnull, aTarget);
  
      if (! result)
          return NS_ERROR_OUT_OF_MEMORY;
-@@ -1763,7 +1706,7 @@ InMemoryDataSource::ArcLabelsOut(nsIRDFR
+@@ -1774,7 +1717,7 @@ InMemoryDataSource::ArcLabelsOut(nsIRDFR
          return NS_ERROR_NULL_POINTER;
  
      InMemoryArcsEnumeratorImpl* result =
 -        InMemoryArcsEnumeratorImpl::Create(this, aSource, nsnull);
 +        new InMemoryArcsEnumeratorImpl(this, aSource, nsnull);
  
      if (! result)
          return NS_ERROR_OUT_OF_MEMORY;
@@ -5606,27 +5606,27 @@ diff --git a/toolkit/components/places/s
  
 -  clone->mRefCnt = 0; // the clone doesn't inherit our refcount
    NS_ADDREF(*_retval = clone);
    return NS_OK;
  }
 diff --git a/toolkit/xre/nsAppRunner.cpp b/toolkit/xre/nsAppRunner.cpp
 --- a/toolkit/xre/nsAppRunner.cpp
 +++ b/toolkit/xre/nsAppRunner.cpp
-@@ -562,7 +562,8 @@ PRBool gSafeMode = PR_FALSE;
+@@ -565,7 +565,8 @@ PRBool gSafeMode = PR_FALSE;
   * The nsXULAppInfo object implements nsIFactory so that it can be its own
   * singleton.
   */
 -class nsXULAppInfo : public nsIXULAppInfo,
 +class nsXULAppInfo : public XPCOMGCObject,
 +                     public nsIXULAppInfo,
  #ifdef XP_WIN
                       public nsIWinAppHelper,
  #endif
-@@ -597,18 +598,6 @@ NS_INTERFACE_MAP_BEGIN(nsXULAppInfo)
+@@ -600,18 +601,6 @@ NS_INTERFACE_MAP_BEGIN(nsXULAppInfo)
  #endif
    NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIXULAppInfo, gAppData)
  NS_INTERFACE_MAP_END
 -
 -NS_IMETHODIMP_(nsrefcnt)
 -nsXULAppInfo::AddRef()
 -{
 -  return 1;
@@ -5635,81 +5635,81 @@ diff --git a/toolkit/xre/nsAppRunner.cpp
 -NS_IMETHODIMP_(nsrefcnt)
 -nsXULAppInfo::Release()
 -{
 -  return 1;
 -}
  
  NS_IMETHODIMP
  nsXULAppInfo::GetVendor(nsACString& aResult)
-@@ -844,14 +833,12 @@ nsXULAppInfo::WriteMinidumpForException(
+@@ -847,14 +836,12 @@ nsXULAppInfo::WriteMinidumpForException(
  }
  #endif
  
 -static const nsXULAppInfo kAppInfo;
  static NS_METHOD AppInfoConstructor(nsISupports* aOuter,
                                      REFNSIID aIID, void **aResult)
  {
    NS_ENSURE_NO_AGGREGATION(aOuter);
  
 -  return const_cast<nsXULAppInfo*>(&kAppInfo)->
 -    QueryInterface(aIID, aResult);
 +  return (new nsXULAppInfo())->QueryInterface(aIID, aResult);
  }
  
  PRBool gLogConsoleErrors
-@@ -1108,8 +1095,8 @@ static void DumpArbitraryHelp()
+@@ -1111,8 +1098,8 @@ static void DumpArbitraryHelp()
    ScopedLogging log;
  
    {
 -    nsXREDirProvider dirProvider;
 -    dirProvider.Initialize(nsnull, gAppData->xreDirectory);
 +    nsXREDirProvider *dirProvider = new nsXREDirProvider();
 +    dirProvider->Initialize(nsnull, gAppData->xreDirectory);
  
      ScopedXPCOMStartup xpcom;
      xpcom.Initialize();
-@@ -2617,12 +2604,12 @@ XRE_main(int argc, char* argv[], const n
+@@ -2621,12 +2608,12 @@ XRE_main(int argc, char* argv[], const n
      CrashReporter::SetRestartArgs(argc, argv);
  
      // annotate other data (user id etc)
 -    nsXREDirProvider dirProvider;
 +    nsXREDirProvider *dirProvider = new nsXREDirProvider();
      nsCOMPtr<nsILocalFile> userAppDataDir;
 -    rv = dirProvider.Initialize(gAppData->directory, gAppData->xreDirectory);
 +    rv = dirProvider->Initialize(gAppData->directory, gAppData->xreDirectory);
      if (NS_SUCCEEDED(rv) &&
 -        NS_SUCCEEDED(dirProvider.GetUserAppDataDirectory(
 -                                                         getter_AddRefs(userAppDataDir)))) {
 +        NS_SUCCEEDED(dirProvider->GetUserAppDataDirectory(
 +                                  getter_AddRefs(userAppDataDir)))) {
        CrashReporter::SetupExtraData(userAppDataDir,
                                      nsDependentCString(appData.buildID));
  
-@@ -2630,7 +2617,7 @@ XRE_main(int argc, char* argv[], const n
+@@ -2634,7 +2621,7 @@ XRE_main(int argc, char* argv[], const n
        nsCOMPtr<nsIFile> overrideini;
        PRBool exists;
        static char overrideEnv[MAXPATHLEN];
 -      if (NS_SUCCEEDED(dirProvider.GetAppDir()->Clone(getter_AddRefs(overrideini))) &&
 +      if (NS_SUCCEEDED(dirProvider->GetAppDir()->Clone(getter_AddRefs(overrideini))) &&
            NS_SUCCEEDED(overrideini->AppendNative(NS_LITERAL_CSTRING("crashreporter-override.ini"))) &&
            NS_SUCCEEDED(overrideini->Exists(&exists)) &&
            exists) {
-@@ -2739,8 +2726,8 @@ XRE_main(int argc, char* argv[], const n
+@@ -2743,8 +2730,8 @@ XRE_main(int argc, char* argv[], const n
  #endif
  
    {
 -    nsXREDirProvider dirProvider;
 -    rv = dirProvider.Initialize(gAppData->directory, gAppData->xreDirectory);
 +    nsXREDirProvider *dirProvider = new nsXREDirProvider();
 +    rv = dirProvider->Initialize(gAppData->directory, gAppData->xreDirectory);
      if (NS_FAILED(rv))
        return 1;
  
-@@ -2873,14 +2860,14 @@ XRE_main(int argc, char* argv[], const n
+@@ -2883,14 +2870,14 @@ XRE_main(int argc, char* argv[], const n
    // Check for and process any available updates
    nsCOMPtr<nsIFile> updRoot;
    PRBool persistent;
 -  rv = dirProvider.GetFile(XRE_UPDATE_ROOT_DIR, &persistent,
 -                           getter_AddRefs(updRoot));
 +  rv = dirProvider->GetFile(XRE_UPDATE_ROOT_DIR, &persistent,
 +                            getter_AddRefs(updRoot));
    // XRE_UPDATE_ROOT_DIR may fail. Fallback to appDir if failed
@@ -5719,62 +5719,62 @@ diff --git a/toolkit/xre/nsAppRunner.cpp
  
 -  ProcessUpdates(dirProvider.GetGREDir(),
 -                 dirProvider.GetAppDir(),
 +  ProcessUpdates(dirProvider->GetGREDir(),
 +                 dirProvider->GetAppDir(),
                   updRoot,
                   gRestartArgc,
                   gRestartArgv);
-@@ -2904,7 +2891,7 @@ XRE_main(int argc, char* argv[], const n
+@@ -2914,7 +2901,7 @@ XRE_main(int argc, char* argv[], const n
      rv = profileLock->GetLocalDirectory(getter_AddRefs(profLD));
      NS_ENSURE_SUCCESS(rv, 1);
  
 -    rv = dirProvider.SetProfile(profD, profLD);
 +    rv = dirProvider->SetProfile(profD, profLD);
      NS_ENSURE_SUCCESS(rv, 1);
  
      //////////////////////// NOW WE HAVE A PROFILE ////////////////////////
-@@ -2930,7 +2917,7 @@ XRE_main(int argc, char* argv[], const n
+@@ -2940,7 +2927,7 @@ XRE_main(int argc, char* argv[], const n
      // profile was started with.  The format of the version stamp is defined
      // by the BuildVersion function.
      PRBool versionOK = CheckCompatibility(profD, version, osABI,
 -                                          dirProvider.GetGREDir(),
 +                                          dirProvider->GetGREDir(),
                                            gAppData->directory);
  
      // Every time a profile is loaded by a build with a different version,
-@@ -2943,7 +2930,7 @@ XRE_main(int argc, char* argv[], const n
+@@ -2953,7 +2940,7 @@ XRE_main(int argc, char* argv[], const n
      if (gSafeMode) {
        RemoveComponentRegistries(profD, profLD, PR_FALSE);
        WriteVersion(profD, NS_LITERAL_CSTRING("Safe Mode"), osABI,
 -                   dirProvider.GetGREDir(), gAppData->directory);
 +                   dirProvider->GetGREDir(), gAppData->directory);
      }
      else if (versionOK) {
        if (ComponentsListChanged(profD)) {
-@@ -2967,7 +2954,7 @@ XRE_main(int argc, char* argv[], const n
+@@ -2977,7 +2964,7 @@ XRE_main(int argc, char* argv[], const n
  
        // Write out version
        WriteVersion(profD, version, osABI,
 -                   dirProvider.GetGREDir(), gAppData->directory);
 +                   dirProvider->GetGREDir(), gAppData->directory);
      }
  
      PRBool needsRestart = PR_FALSE;
-@@ -3010,7 +2997,7 @@ XRE_main(int argc, char* argv[], const n
+@@ -3020,7 +3007,7 @@ XRE_main(int argc, char* argv[], const n
  
          if (gDoMigration) {
            nsCOMPtr<nsIFile> file;
 -          dirProvider.GetAppDir()->Clone(getter_AddRefs(file));
 +          dirProvider->GetAppDir()->Clone(getter_AddRefs(file));
            file->AppendNative(NS_LITERAL_CSTRING("override.ini"));
            nsINIParser parser;
            nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(file));
-@@ -3032,9 +3019,9 @@ XRE_main(int argc, char* argv[], const n
+@@ -3042,9 +3029,9 @@ XRE_main(int argc, char* argv[], const n
            nsCOMPtr<nsIProfileMigrator> pm
              (do_CreateInstance(NS_PROFILEMIGRATOR_CONTRACTID));
            if (pm)
 -            pm->Migrate(&dirProvider);
 +            pm->Migrate(dirProvider);
          }
 -        dirProvider.DoStartup();
 +        dirProvider->DoStartup();
@@ -7829,17 +7829,17 @@ diff --git a/xpcom/base/nsTraceRefcntImp
 +{
 +  if (!gJSRuntime)
 +    return NULL;
 +
 +  return gJSRuntime->gc;
  }
  
  EXPORT_XPCOM_API(void)
-@@ -1215,68 +487,3 @@ nsTraceRefcntImpl::SetActivityIsLegal(PR
+@@ -1221,68 +493,3 @@ nsTraceRefcntImpl::SetActivityIsLegal(PR
    PR_SetThreadPrivate(gActivityTLS, NS_INT32_TO_PTR(!aLegal));
  #endif
  }
 -
 -NS_IMPL_QUERY_INTERFACE1(nsTraceRefcntImpl, nsITraceRefcnt)
 -
 -NS_IMETHODIMP_(nsrefcnt) nsTraceRefcntImpl::AddRef(void)
 -{
@@ -7974,25 +7974,25 @@ diff --git a/xpcom/build/Makefile.in b/x
 @@ -71,6 +71,7 @@ MOZILLA_INTERNAL_API = 1
  MOZILLA_INTERNAL_API = 1
  
  REQUIRES	= string \
 +		  js \
  		  $(NULL)
  
  # pull in MoreFiles for MacOSX
-@@ -144,6 +145,7 @@ SDK_HEADERS =  \
+@@ -150,6 +151,7 @@ SDK_HEADERS =  \
  
  EXPORTS	= \
  		nsXPCOMCIDInternal.h \
 +		nsXPCOMPrivate.h \
  		$(NULL)
  
  # Force use of PIC
-@@ -168,7 +170,7 @@ DEFINES		+= \
+@@ -172,7 +174,7 @@ DEFINES		+= \
  		-DEXPORT_XPT_API \
  		-DEXPORT_XPTC_API
  
 -EXTRA_DSO_LDOPTS += $(NSPR_LIBS) $(MMGC_LIBS)
 +EXTRA_DSO_LDOPTS += $(MOZ_JS_LIBS) $(NSPR_LIBS) $(MMGC_LIBS)
  
  ifdef GC_LEAK_DETECTOR
  DEFINES += -DGC_LEAK_DETECTOR
@@ -8143,17 +8143,17 @@ diff --git a/xpcom/components/nsComponen
      }
      if (mErrorPtr)
          *mErrorPtr = rv;
 -    return rv;
 +    return result;
  }
  
  ////////////////////////////////////////////////////////////////////////////////
-@@ -3227,9 +3228,12 @@ nsComponentManagerImpl::AutoRegister(nsI
+@@ -3230,9 +3231,12 @@ nsComponentManagerImpl::AutoRegister(nsI
      nsresult rv;
  
      if (!mCategoryManager) {
 -        mCategoryManager = do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
 +        nsICategoryManager* catMan =
 +            do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
          if (NS_FAILED(rv))
              return rv;
@@ -8306,17 +8306,17 @@ diff --git a/xpcom/glue/Makefile.in b/xp
 +++ b/xpcom/glue/Makefile.in
 @@ -51,6 +51,7 @@ DIST_INSTALL	= 1
  
  REQUIRES = \
  		string \
 +		js \
  		$(NULL)
  
- LOCAL_INCLUDES	= \
+ ifdef NS_TRACE_MALLOC
 diff --git a/xpcom/glue/nsArrayEnumerator.cpp b/xpcom/glue/nsArrayEnumerator.cpp
 --- a/xpcom/glue/nsArrayEnumerator.cpp
 +++ b/xpcom/glue/nsArrayEnumerator.cpp
 @@ -136,14 +136,10 @@ public:
      NS_DECL_NSISIMPLEENUMERATOR
  
      // nsSimpleArrayEnumerator methods
 -    nsCOMArrayEnumerator() : mIndex(0) {
--- a/content-hashtables
+++ b/content-hashtables
@@ -1,34 +1,34 @@
 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
-@@ -1127,7 +1127,7 @@ private:
+@@ -1271,7 +1271,7 @@ private:
  
    static nsIConsoleService* sConsoleService;
  
 -  static nsDataHashtable<nsISupportsHashKey, EventNameMapping>* sEventTable;
 +  static nsDataHashtable<nsISupportsHashKey, EventNameMapping, GCAllocator>* sEventTable;
  
    static nsIStringBundleService* sStringBundleService;
    static nsIStringBundle* sStringBundles[PropertiesFile_COUNT];
 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
-@@ -171,7 +171,7 @@ nsIPref *nsContentUtils::sPref = nsnull;
+@@ -188,7 +188,7 @@ nsIPref *nsContentUtils::sPref = nsnull;
  nsIPref *nsContentUtils::sPref = nsnull;
  imgILoader *nsContentUtils::sImgLoader;
  nsIConsoleService *nsContentUtils::sConsoleService;
 -nsDataHashtable<nsISupportsHashKey, EventNameMapping>* nsContentUtils::sEventTable = nsnull;
 +nsDataHashtable<nsISupportsHashKey, EventNameMapping, GCAllocator>* nsContentUtils::sEventTable = nsnull;
  nsIStringBundleService *nsContentUtils::sStringBundleService;
  nsIStringBundle *nsContentUtils::sStringBundles[PropertiesFile_COUNT];
  nsIContentPolicy *nsContentUtils::sContentPolicyService;
-@@ -417,7 +417,7 @@ nsContentUtils::InitializeEventTable() {
- #endif // MOZ_SVG
+@@ -461,7 +461,7 @@ nsContentUtils::InitializeEventTable() {
+ #endif //MOZ_MEDIA
    };
  
 -  sEventTable = new nsDataHashtable<nsISupportsHashKey, EventNameMapping>;
 +  sEventTable = new nsDataHashtable<nsISupportsHashKey, EventNameMapping, GCAllocator>;
    if (!sEventTable ||
        !sEventTable->Init(int(NS_ARRAY_LENGTH(eventArray) / 0.75) + 1)) {
      delete sEventTable;
 diff --git a/xpcom/ds/nsExpirationTracker.h b/xpcom/ds/nsExpirationTracker.h
--- a/content-stack-classes
+++ b/content-stack-classes
@@ -1,265 +1,2 @@
 Annotate classes in dom/content which only appear on the stack.
 
-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
-@@ -1290,7 +1290,7 @@ private:
- #define NS_HOLD_JS_OBJECTS(obj, clazz) NS_OK
- #define NS_DROP_JS_OBJECTS(obj, clazz) NS_OK
- 
--class nsCxPusher
-+class NS_STACK_CLASS nsCxPusher
- {
- public:
-   nsCxPusher();
-diff --git a/content/base/public/nsIDocument.h b/content/base/public/nsIDocument.h
---- a/content/base/public/nsIDocument.h
-+++ b/content/base/public/nsIDocument.h
-@@ -1075,7 +1075,7 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsIDocumen
-  * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
-  * object is deleted.
-  */
--class mozAutoSubtreeModified
-+class NS_STACK_CLASS mozAutoSubtreeModified
- {
- public:
-   /**
-diff --git a/content/base/src/mozAutoDocUpdate.h b/content/base/src/mozAutoDocUpdate.h
---- a/content/base/src/mozAutoDocUpdate.h
-+++ b/content/base/src/mozAutoDocUpdate.h
-@@ -41,7 +41,7 @@
-  * in which case no updates will be called.  The constructor also takes a
-  * boolean that can be set to false to prevent notifications.
-  */
--class mozAutoDocUpdate
-+class NS_STACK_CLASS mozAutoDocUpdate
- {
- public:
-   mozAutoDocUpdate(nsIDocument* aDocument, nsUpdateType aUpdateType,
-@@ -94,7 +94,7 @@ private:
-  * but then have inner mozAutoDocUpdate call the last EndUpdate before.
-  * we remove that blocker. See bug 423269.
-  */
--class mozAutoDocConditionalContentUpdateBatch
-+class NS_STACK_CLASS mozAutoDocConditionalContentUpdateBatch
- {
- public:
-   mozAutoDocConditionalContentUpdateBatch(nsIDocument* aDocument,
-diff --git a/content/base/src/nsContentAreaDragDrop.cpp b/content/base/src/nsContentAreaDragDrop.cpp
---- a/content/base/src/nsContentAreaDragDrop.cpp
-+++ b/content/base/src/nsContentAreaDragDrop.cpp
-@@ -119,7 +119,7 @@ NS_INTERFACE_MAP_END
- NS_INTERFACE_MAP_END
- 
- 
--class nsTransferableFactory
-+class NS_STACK_CLASS nsTransferableFactory
- {
- public:
-   nsTransferableFactory(nsIDOMEvent* inMouseEvent,
-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
-@@ -323,10 +323,11 @@ nsNodeUtils::GetUserData(nsINode *aNode,
-   return NS_OK;
- }
- 
--struct nsHandlerData
-+struct NS_STACK_CLASS nsHandlerData
- {
-   PRUint16 mOperation;
--  nsCOMPtr<nsIDOMNode> mSource, mDest;
-+  nsCOMPtr<nsIDOMNode> mSource;
-+  nsCOMPtr<nsIDOMNode> mDest;
- };
- 
- static void
-diff --git a/content/base/src/nsRange.cpp b/content/base/src/nsRange.cpp
---- a/content/base/src/nsRange.cpp
-+++ b/content/base/src/nsRange.cpp
-@@ -789,7 +789,7 @@ nsresult nsRange::SelectNodeContents(nsI
- // start/end points in the future, we can switchover relatively
- // easy.
- 
--class RangeSubtreeIterator
-+class NS_STACK_CLASS RangeSubtreeIterator
- {
- private:
- 
-diff --git a/content/events/public/nsEventDispatcher.h b/content/events/public/nsEventDispatcher.h
---- a/content/events/public/nsEventDispatcher.h
-+++ b/content/events/public/nsEventDispatcher.h
-@@ -190,7 +190,7 @@ public:
-  * before handling the system event group.
-  * This is used in nsPresShell.
-  */
--class nsDispatchingCallback {
-+class NS_STACK_CLASS nsDispatchingCallback {
- public:
-   virtual void HandleEvent(nsEventChainPostVisitor& aVisitor) = 0;
- };
-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
-@@ -2869,7 +2869,7 @@ nsEventStateManager::SetCursor(PRInt32 a
-   return NS_OK;
- }
- 
--class nsESMEventCB : public nsDispatchingCallback
-+class NS_STACK_CLASS nsESMEventCB : public nsDispatchingCallback
- {
- public:
-   nsESMEventCB(nsIContent* aTarget) : mTarget(aTarget) {}
-diff --git a/content/events/src/nsQueryContentEventHandler.h b/content/events/src/nsQueryContentEventHandler.h
---- a/content/events/src/nsQueryContentEventHandler.h
-+++ b/content/events/src/nsQueryContentEventHandler.h
-@@ -61,7 +61,7 @@ struct nsRect;
-  *   This class answers to NS_QUERY_* events from actual contents.
-  */
- 
--class nsQueryContentEventHandler {
-+class NS_STACK_CLASS nsQueryContentEventHandler {
- public:
-   nsQueryContentEventHandler(nsPresContext *aPresContext);
- 
-diff --git a/content/html/content/src/nsHTMLSelectElement.h b/content/html/content/src/nsHTMLSelectElement.h
---- a/content/html/content/src/nsHTMLSelectElement.h
-+++ b/content/html/content/src/nsHTMLSelectElement.h
-@@ -190,7 +190,7 @@ private:
-   nsCheapInt32Set mIndices;
- };
- 
--class nsSafeOptionListMutation
-+class NS_STACK_CLASS nsSafeOptionListMutation
- {
- public:
-   /**
-diff --git a/content/svg/content/src/nsSVGFilters.cpp b/content/svg/content/src/nsSVGFilters.cpp
---- a/content/svg/content/src/nsSVGFilters.cpp
-+++ b/content/svg/content/src/nsSVGFilters.cpp
-@@ -82,7 +82,7 @@ using namespace mozilla;
-   * filters.  PLEASE NOTE that nsSVGFilterResource should ONLY be used on the
-   * stack because it has nsAutoString member.
-   */
--class nsSVGFilterResource
-+class NS_STACK_CLASS nsSVGFilterResource
- {
- public:
-   nsSVGFilterResource(nsSVGFE *aFilter, nsSVGFilterInstance* aInstance);
-diff --git a/content/svg/content/src/nsSVGValue.h b/content/svg/content/src/nsSVGValue.h
---- a/content/svg/content/src/nsSVGValue.h
-+++ b/content/svg/content/src/nsSVGValue.h
-@@ -87,7 +87,7 @@ private:
- // Class that will automatically call WillModify and DidModify in its ctor
- // and dtor respectively (for functions that have multiple exit points).
- 
--class nsSVGValueAutoNotifier
-+class NS_STACK_CLASS nsSVGValueAutoNotifier
- {
- public:
-   nsSVGValueAutoNotifier(nsSVGValue* aVal,
-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
-@@ -1539,7 +1539,7 @@ nsXULTemplateBuilder::ParseAttribute(con
- }
- 
- 
--struct SubstituteTextClosure {
-+struct NS_STACK_CLASS SubstituteTextClosure {
-     SubstituteTextClosure(nsIXULTemplateResult* aResult, nsAString& aString)
-         : result(aResult), str(aString) {}
- 
-diff --git a/docshell/base/nsDocShell.cpp b/docshell/base/nsDocShell.cpp
---- a/docshell/base/nsDocShell.cpp
-+++ b/docshell/base/nsDocShell.cpp
-@@ -8440,7 +8440,7 @@ nsDocShell::WalkHistoryEntries(nsISHEntr
- }
- 
- // callback data for WalkHistoryEntries
--struct CloneAndReplaceData
-+struct NS_STACK_CLASS CloneAndReplaceData
- {
-     CloneAndReplaceData(PRUint32 aCloneID, nsISHEntry *aReplaceEntry,
-                         nsISHEntry *aDestTreeParent)
-diff --git a/dom/public/base/nsIFocusController.h b/dom/public/base/nsIFocusController.h
---- a/dom/public/base/nsIFocusController.h
-+++ b/dom/public/base/nsIFocusController.h
-@@ -90,7 +90,7 @@ public:
- 
- NS_DEFINE_STATIC_IID_ACCESSOR(nsIFocusController, NS_IFOCUSCONTROLLER_IID)
- 
--class nsFocusSuppressor {
-+class NS_STACK_CLASS nsFocusSuppressor {
- public:
-   ~nsFocusSuppressor()
-   {
-@@ -128,7 +128,7 @@ private:
-   const char *mReason;
- };
- 
--class nsFocusScrollSuppressor
-+class NS_STACK_CLASS nsFocusScrollSuppressor
- {
- public:
-   nsFocusScrollSuppressor(nsIFocusController* aController = nsnull)
-diff --git a/dom/public/nsDOMScriptObjectHolder.h b/dom/public/nsDOMScriptObjectHolder.h
---- a/dom/public/nsDOMScriptObjectHolder.h
-+++ b/dom/public/nsDOMScriptObjectHolder.h
-@@ -46,7 +46,7 @@
- // functions and a fully inline implementation should keep the cost down.
- // [Note that a fully inline implementation is necessary for use by other
- // languages, which do not link against the layout component module]
--class nsScriptObjectHolder {
-+class NS_STACK_CLASS nsScriptObjectHolder {
- public:
-   // A constructor that will cause a reference to |ctx| to be stored in
-   // the object.  Only use for short-lived object holders.
-diff --git a/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp b/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
---- a/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
-+++ b/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
-@@ -2356,7 +2356,7 @@ public:
-     }
- };
- 
--struct FixRedirectData
-+struct NS_STACK_CLASS FixRedirectData
- {
-     nsCOMPtr<nsIChannel> mNewChannel;
-     nsCOMPtr<nsIURI> mOriginalURI;
-diff --git a/embedding/components/windowwatcher/src/nsWindowWatcher.cpp b/embedding/components/windowwatcher/src/nsWindowWatcher.cpp
---- a/embedding/components/windowwatcher/src/nsWindowWatcher.cpp
-+++ b/embedding/components/windowwatcher/src/nsWindowWatcher.cpp
-@@ -266,7 +266,7 @@ void nsWatcherWindowEnumerator::WindowRe
-  ********************** JSContextAutoPopper *********************
-  ****************************************************************/
- 
--class JSContextAutoPopper {
-+class NS_STACK_CLASS JSContextAutoPopper {
- public:
-   JSContextAutoPopper();
-   ~JSContextAutoPopper();
-diff --git a/layout/base/nsPresShell.cpp b/layout/base/nsPresShell.cpp
---- a/layout/base/nsPresShell.cpp
-+++ b/layout/base/nsPresShell.cpp
-@@ -1237,7 +1237,7 @@ public:
-   PresShell* mShell;
- };
- 
--class nsPresShellEventCB : public nsDispatchingCallback
-+class NS_STACK_CLASS nsPresShellEventCB : public nsDispatchingCallback
- {
- public:
-   nsPresShellEventCB(PresShell* aPresShell) : mPresShell(aPresShell) {}
-diff --git a/modules/plugin/base/src/nsPluginHostImpl.h b/modules/plugin/base/src/nsPluginHostImpl.h
---- a/modules/plugin/base/src/nsPluginHostImpl.h
-+++ b/modules/plugin/base/src/nsPluginHostImpl.h
-@@ -472,7 +472,7 @@ private:
-   static nsPluginHostImpl* sInst;
- };
- 
--class PluginDestructionGuard : protected PRCList
-+class NS_STACK_CLASS PluginDestructionGuard : protected PRCList
- {
- public:
-   PluginDestructionGuard(nsIPluginInstance *aInstance)
--- a/core-refcounting
+++ b/core-refcounting
@@ -293,17 +293,17 @@ new file mode 100644
 +            if (mRefCnt == 0)                                           \
 +                delete this;                                            \
 +        }
 +
 +#endif // mozilla_RefPtr_h__
 diff --git a/xpcom/build.mk b/xpcom/build.mk
 --- a/xpcom/build.mk
 +++ b/xpcom/build.mk
-@@ -37,4 +37,7 @@
+@@ -41,4 +41,7 @@ tier_xpcom_dirs = tools/trace-malloc/lib
+ tier_xpcom_dirs = tools/trace-malloc/lib
+ endif
  
- TIERS += xpcom
- 
--tier_xpcom_dirs = xpcom
+-tier_xpcom_dirs += xpcom
 +tier_xpcom_dirs = \
 +  core \
 +  xpcom \
 +  $(NULL)
new file mode 100644
--- /dev/null
+++ b/core-refcounting2
@@ -0,0 +1,16 @@
+diff --git a/core/RefPtr.h b/core/RefPtr.h
+--- a/core/RefPtr.h
++++ b/core/RefPtr.h
+@@ -74,6 +74,12 @@ namespace mozilla
+         explicit AddRefed(T *ptr) : mRawPtr(ptr) { }
+ 
+         T* get() const { return mRawPtr; }
++
++        // allow conversion from AddRefed<DerivedClass> to AddRefed<BaseClass>
++        template<class D>
++        operator AddRefed<D>() const {
++            return AddRefed<D>(mRawPtr);
++        }
+     };
+ 
+     template<class T>
--- a/editor-stack-classes
+++ b/editor-stack-classes
@@ -1,158 +1,2 @@
 Add stack annotations to editor classes.
 
-diff --git a/editor/libeditor/base/nsEditorUtils.h b/editor/libeditor/base/nsEditorUtils.h
---- a/editor/libeditor/base/nsEditorUtils.h
-+++ b/editor/libeditor/base/nsEditorUtils.h
-@@ -56,7 +56,7 @@ class nsPlaintextEditor;
-  * stack based helper class for batching a collection of txns inside a 
-  * placeholder txn.
-  */
--class nsAutoPlaceHolderBatch
-+class NS_STACK_CLASS nsAutoPlaceHolderBatch
- {
-   private:
-     nsCOMPtr<nsIEditor> mEd;
-@@ -82,7 +82,7 @@ class nsAutoEditBatch : public nsAutoPla
-  * stack based helper class for saving/restoring selection.  Note that this
-  * assumes that the nodes involved are still around afterwards!
-  */
--class nsAutoSelectionReset
-+class NS_STACK_CLASS nsAutoSelectionReset
- {
-   private:
-     /** ref-counted reference to the selection that we are supposed to restore */
-@@ -103,7 +103,7 @@ class nsAutoSelectionReset
- /***************************************************************************
-  * stack based helper class for StartOperation()/EndOperation() sandwich
-  */
--class nsAutoRules
-+class NS_STACK_CLASS nsAutoRules
- {
-   public:
-   
-@@ -134,7 +134,7 @@ class nsAutoRules
-  * stack based helper class for turning off active selection adjustment
-  * by low level transactions
-  */
--class nsAutoTxnsConserveSelection
-+class NS_STACK_CLASS nsAutoTxnsConserveSelection
- {
-   public:
-   
-@@ -163,7 +163,7 @@ class nsAutoTxnsConserveSelection
- /***************************************************************************
-  * stack based helper class for batching reflow and paint requests.
-  */
--class nsAutoUpdateViewBatch
-+class NS_STACK_CLASS nsAutoUpdateViewBatch
- {
-   public:
-   
-@@ -201,7 +201,7 @@ class nsBoolDomIterFunctor
-     virtual PRBool operator()(nsIDOMNode* aNode)=0;
- };
- 
--class nsDOMIterator
-+class NS_STACK_CLASS nsDOMIterator
- {
-   public:
-     nsDOMIterator();
-@@ -239,7 +239,7 @@ class nsTrivialFunctor : public nsBoolDo
- /******************************************************************************
-  * general dom point utility struct
-  *****************************************************************************/
--struct DOMPoint
-+struct NS_STACK_CLASS DOMPoint
- {
-   nsCOMPtr<nsIDOMNode> node;
-   PRInt32 offset;
-diff --git a/editor/libeditor/base/nsSelectionState.h b/editor/libeditor/base/nsSelectionState.h
---- a/editor/libeditor/base/nsSelectionState.h
-+++ b/editor/libeditor/base/nsSelectionState.h
-@@ -135,7 +135,7 @@ class nsRangeUpdater
-  * preservation of dom points across editor actions
-  */
- 
--class nsAutoTrackDOMPoint
-+class NS_STACK_CLASS nsAutoTrackDOMPoint
- {
-   private:
-     nsRangeUpdater &mRU;
-@@ -170,7 +170,7 @@ class nsAutoTrackDOMPoint
-  * Will/DidReplaceContainer()
-  */
- 
--class nsAutoReplaceContainerSelNotify
-+class NS_STACK_CLASS nsAutoReplaceContainerSelNotify
- {
-   private:
-     nsRangeUpdater &mRU;
-@@ -198,7 +198,7 @@ class nsAutoReplaceContainerSelNotify
-  * Will/DidRemoveContainer()
-  */
- 
--class nsAutoRemoveContainerSelNotify
-+class NS_STACK_CLASS nsAutoRemoveContainerSelNotify
- {
-   private:
-     nsRangeUpdater &mRU;
-@@ -233,7 +233,7 @@ class nsAutoRemoveContainerSelNotify
-  * Will/DidInsertContainer()
-  */
- 
--class nsAutoInsertContainerSelNotify
-+class NS_STACK_CLASS nsAutoInsertContainerSelNotify
- {
-   private:
-     nsRangeUpdater &mRU;
-@@ -257,7 +257,7 @@ class nsAutoInsertContainerSelNotify
-  * Will/DidMoveNode()
-  */
- 
--class nsAutoMoveNodeSelNotify
-+class NS_STACK_CLASS nsAutoMoveNodeSelNotify
- {
-   private:
-     nsRangeUpdater &mRU;
-diff --git a/editor/libeditor/html/nsTableEditor.cpp b/editor/libeditor/html/nsTableEditor.cpp
---- a/editor/libeditor/html/nsTableEditor.cpp
-+++ b/editor/libeditor/html/nsTableEditor.cpp
-@@ -69,7 +69,7 @@
- /***************************************************************************
-  * stack based helper class for restoring selection after table edit
-  */
--class nsSetSelectionAfterTableEdit
-+class NS_STACK_CLASS nsSetSelectionAfterTableEdit
- {
-   private:
-     nsCOMPtr<nsITableEditor> mEd;
-@@ -99,7 +99,7 @@ class nsSetSelectionAfterTableEdit
- };
- 
- // Stack-class to turn on/off selection batching for table selection
--class nsSelectionBatcher
-+class NS_STACK_CLASS nsSelectionBatcher
- {
- private:
-   nsCOMPtr<nsISelectionPrivate> mSelection;
-diff --git a/editor/libeditor/html/nsWSRunObject.h b/editor/libeditor/html/nsWSRunObject.h
---- a/editor/libeditor/html/nsWSRunObject.h
-+++ b/editor/libeditor/html/nsWSRunObject.h
-@@ -67,7 +67,7 @@ class nsHTMLEditor;
- // will only render as one space (in non-preformatted stlye html), yet both
- // spaces count as NormalWS.  Together, they render as the one visible space.
- 
--class nsWSRunObject
-+class NS_STACK_CLASS nsWSRunObject
- {
-   public:
- 
-@@ -226,7 +226,7 @@ class nsWSRunObject
-     // always within a textnode that is one of the nodes stored in the list
-     // in the wsRunObject.  For convenience, the character at that point is also 
-     // stored in the struct.
--    struct WSPoint
-+    struct NS_STACK_CLASS WSPoint
-     {
-       nsCOMPtr<nsIContent> mTextNode;
-       PRInt16 mOffset;
--- a/gc-hashtables.patch
+++ b/gc-hashtables.patch
@@ -1,10 +1,9 @@
-* * *
-* * *
+Give hashtable keys knowledge about the outermost allocation they are in... kinda. In some of these cases I just added the param without actually making the key class safe.
 
 diff --git a/caps/include/nsScriptSecurityManager.h b/caps/include/nsScriptSecurityManager.h
 --- a/caps/include/nsScriptSecurityManager.h
 +++ b/caps/include/nsScriptSecurityManager.h
 @@ -96,7 +96,7 @@ public:
      typedef const nsIPrincipal* KeyType;
      typedef const nsIPrincipal* KeyTypePointer;
  
@@ -38,25 +37,54 @@ diff --git a/content/base/src/nsDOMAttri
 -  nsAttrHashKey(KeyTypePointer aKey) : mKey(*aKey) {}
 +  nsAttrHashKey(KeyTypePointer aKey, const void *entryStore) : mKey(*aKey) {}
    nsAttrHashKey(const nsAttrHashKey& aCopy) : mKey(aCopy.mKey) {}
    ~nsAttrHashKey() {}
  
 diff --git a/content/base/src/nsDocument.h b/content/base/src/nsDocument.h
 --- a/content/base/src/nsDocument.h
 +++ b/content/base/src/nsDocument.h
-@@ -144,7 +144,7 @@ class nsUint32ToContentHashEntry : publi
+@@ -145,7 +145,7 @@ class nsUint32ToContentHashEntry : publi
      typedef const PRUint32& KeyType;
      typedef const PRUint32* KeyTypePointer;
  
 -    nsUint32ToContentHashEntry(const KeyTypePointer key) :
 +    nsUint32ToContentHashEntry(const KeyTypePointer key, const void *entryStore) :
        mValue(*key), mValOrHash(nsnull) { }
      nsUint32ToContentHashEntry(const nsUint32ToContentHashEntry& toCopy) :
        mValue(toCopy.mValue), mValOrHash(toCopy.mValOrHash)
+@@ -226,14 +226,9 @@ class nsIdentifierMapEntry : public nsIS
+ class nsIdentifierMapEntry : public nsISupportsHashKey
+ {
+ public:
+-  nsIdentifierMapEntry(const nsISupports* aKey) :
+-    nsISupportsHashKey(aKey), mNameContentList(nsnull)
++  nsIdentifierMapEntry(const nsISupports* aKey, const void *entryStore) :
++    nsISupportsHashKey(aKey, entryStore), mNameContentList(nsnull)
+   {
+-  }
+-  nsIdentifierMapEntry(const nsIdentifierMapEntry& aOther) :
+-    nsISupportsHashKey(GetKey())
+-  {
+-    NS_ERROR("Should never be called");
+   }
+   ~nsIdentifierMapEntry();
+ 
+@@ -286,10 +281,8 @@ public:
+     typedef const ChangeCallback KeyType;
+     typedef const ChangeCallback* KeyTypePointer;
+ 
+-    ChangeCallbackEntry(const ChangeCallback* key) :
++    ChangeCallbackEntry(const ChangeCallback* key, const char *entryStore) :
+       mKey(*key) { }
+-    ChangeCallbackEntry(const ChangeCallbackEntry& toCopy) :
+-      mKey(toCopy.mKey) { }
+ 
+     KeyType GetKey() const { return mKey; }
+     PRBool KeyEquals(KeyTypePointer aKey) const {
 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,7 +81,8 @@ public:
    nsNameSpaceKey(KeyTypePointer aKey) : mKey(aKey)
    {
    }
 -  nsNameSpaceKey(const nsNameSpaceKey& toCopy) : mKey(toCopy.mKey)
@@ -87,20 +115,40 @@ diff --git a/content/xslt/src/xslt/txExe
  {
  public:
 -    txLoadedDocumentEntry(KeyTypePointer aStr) : nsStringHashKey(aStr)
 +    txLoadedDocumentEntry(KeyTypePointer aStr, const void *entryStore)
 +        : nsStringHashKey(aStr, entryStore)
      {
      }
      txLoadedDocumentEntry(const txLoadedDocumentEntry& aToCopy)
+diff --git a/content/xul/document/src/nsXULDocument.h b/content/xul/document/src/nsXULDocument.h
+--- a/content/xul/document/src/nsXULDocument.h
++++ b/content/xul/document/src/nsXULDocument.h
+@@ -80,14 +80,9 @@ class nsRefMapEntry : public nsISupports
+ class nsRefMapEntry : public nsISupportsHashKey
+ {
+ public:
+-  nsRefMapEntry(const nsISupports* aKey) :
+-    nsISupportsHashKey(aKey)
++  nsRefMapEntry(const nsISupports* aKey, const void *entryStore) :
++    nsISupportsHashKey(aKey, entryStore)
+   {
+-  }
+-  nsRefMapEntry(const nsRefMapEntry& aOther) :
+-    nsISupportsHashKey(GetKey())
+-  {
+-    NS_ERROR("Should never be called");
+   }
+ 
+   nsIContent* GetFirstContent();
 diff --git a/db/morkreader/nsMorkReader.h b/db/morkreader/nsMorkReader.h
 --- a/db/morkreader/nsMorkReader.h
 +++ b/db/morkreader/nsMorkReader.h
-@@ -79,7 +79,7 @@ class nsMorkReader
+@@ -79,7 +79,7 @@ class NS_STACK_CLASS nsMorkReader
      typedef const nsCSubstring& KeyType;
      typedef const nsCSubstring* KeyTypePointer;
  
 -    IDKey(KeyTypePointer aStr) : mStr(*aStr) { }
 +    IDKey(KeyTypePointer aStr, const void *entryStore) : mStr(*aStr) { }
      IDKey(const IDKey& toCopy) : mStr(toCopy.mStr) { }
      ~IDKey() { }
  
@@ -335,40 +383,69 @@ diff --git a/netwerk/dns/src/nsEffective
 -  nsDomainEntry(KeyTypePointer aEntry)
 +  nsDomainEntry(KeyTypePointer aEntry, const void *entryStore)
    {
    }
  
 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
-@@ -102,13 +102,8 @@ class nsCertOverrideEntry : public PLDHa
+@@ -102,14 +102,8 @@ 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;
+-      mHostWithPort = toCopy.mHostWithPort;
      }
  
      ~nsCertOverrideEntry()
-@@ -141,8 +136,6 @@ class nsCertOverrideEntry : public PLDHa
+@@ -142,8 +136,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 mHostWithPort; }
+diff --git a/security/manager/ssl/src/nsClientAuthRemember.h b/security/manager/ssl/src/nsClientAuthRemember.h
+--- a/security/manager/ssl/src/nsClientAuthRemember.h
++++ b/security/manager/ssl/src/nsClientAuthRemember.h
+@@ -85,13 +85,9 @@ class nsClientAuthRememberEntry : public
+     typedef const char* KeyTypePointer;
+ 
+     // do nothing with aHost - we require mHead to be set before we're live!
+-    nsClientAuthRememberEntry(KeyTypePointer aHostWithCertUTF8)
++    nsClientAuthRememberEntry(KeyTypePointer aHostWithCertUTF8,
++                              const char *entryStore)
+     {
+-    }
+-
+-    nsClientAuthRememberEntry(const nsClientAuthRememberEntry& toCopy)
+-    {
+-      mSettings = toCopy.mSettings;
+     }
+ 
+     ~nsClientAuthRememberEntry()
+@@ -124,8 +120,6 @@ class nsClientAuthRememberEntry : public
+       // pass nsnull
+       return PL_DHashStringKey(nsnull, aKey);
+     }
+-
+-    enum { ALLOW_MEMMOVE = PR_FALSE };
+ 
+     // get methods
+     inline const nsCString &HostWithCert() const { return mHostWithCert; }
 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
 @@ -75,8 +75,7 @@ public:
    typedef const PRInt64& KeyType;
    typedef const PRInt64* KeyTypePointer;
  
 -  nsTrimInt64HashKey(KeyTypePointer aKey) : mValue(*aKey) { }
@@ -419,53 +496,53 @@ diff --git a/xpcom/components/nsComponen
  static const PLDHashTableOps contractID_DHashTableOps = {
 -    PL_DHashAllocTable,
 -    PL_DHashFreeTable,
 +    GCAllocTable,
 +    GCFreeTable,
      PL_DHashStringKey,
      PL_DHashMatchStringKey,
      PL_DHashMoveEntryStub,
-@@ -974,7 +974,7 @@ nsComponentManagerImpl::ReadPersistentRe
+@@ -977,7 +977,7 @@ nsComponentManagerImpl::ReadPersistentRe
          }
  
          nsFactoryEntry *entry =
 -            new (mem) nsFactoryEntry(aClass, loadertype, values[4]);
 +            new nsFactoryEntry(aClass, loadertype, values[4]);
  
          if (!entry->mLocationKey) {
              rv = NS_ERROR_OUT_OF_MEMORY;
-@@ -1926,7 +1926,7 @@ nsComponentManagerImpl::RegisterService(
+@@ -1929,7 +1929,7 @@ nsComponentManagerImpl::RegisterService(
          PL_ARENA_ALLOCATE(mem, &mArena, sizeof(nsFactoryEntry));
          if (!mem)
              return NS_ERROR_OUT_OF_MEMORY;
 -        entry = new (mem) nsFactoryEntry(aClass, (nsIFactory*) nsnull);
 +        entry = new nsFactoryEntry(aClass, (nsIFactory*) nsnull);
  
          nsFactoryTableEntry* factoryTableEntry =
              static_cast<nsFactoryTableEntry*>
-@@ -1987,7 +1987,7 @@ nsComponentManagerImpl::RegisterService(
+@@ -1990,7 +1990,7 @@ nsComponentManagerImpl::RegisterService(
          PL_ARENA_ALLOCATE(mem, &mArena, sizeof(nsFactoryEntry));
          if (!mem)
              return NS_ERROR_OUT_OF_MEMORY;
 -        entry = new (mem) nsFactoryEntry(kEmptyCID, (nsIFactory*) nsnull);
 +        entry = new nsFactoryEntry(kEmptyCID, (nsIFactory*) nsnull);
  
          nsContractIDTableEntry* contractIDTableEntry =
              static_cast<nsContractIDTableEntry*>
-@@ -2442,7 +2442,7 @@ nsComponentManagerImpl::RegisterFactory(
+@@ -2445,7 +2445,7 @@ nsComponentManagerImpl::RegisterFactory(
      if (!mem)
          return NS_ERROR_OUT_OF_MEMORY;
  
 -    entry = new (mem) nsFactoryEntry(aClass, aFactory, entry);
 +    entry = new nsFactoryEntry(aClass, aFactory, entry);
  
      factoryTableEntry->mFactoryEntry = entry;
  
-@@ -2603,9 +2603,9 @@ nsComponentManagerImpl::RegisterComponen
+@@ -2606,9 +2606,9 @@ nsComponentManagerImpl::RegisterComponen
              return NS_ERROR_OUT_OF_MEMORY;
  
          mRegistryDirty = PR_TRUE;
 -        entry = new (mem) nsFactoryEntry(aClass,
 -                                         typeIndex,
 -                                         aRegistryName);
 +        entry = new nsFactoryEntry(aClass,
 +                                   typeIndex,
@@ -1689,17 +1766,17 @@ diff --git a/xpcom/glue/nsTHashtable.h b
   * @author "Benjamin Smedberg <bsmedberg@covad.net>"
   */
  
 -template<class EntryType>
 +template<class EntryType, class Allocator=CAllocator>
  class nsTHashtable
  {
  public:
-@@ -245,8 +243,22 @@ public:
+@@ -251,8 +249,22 @@ public:
      PL_DHashTableEnumerate(&mTable, PL_DHashStubEnumRemove, nsnull);
    }
  
 +  /**
 +   * Get a pointer to the entry store, for passing to WB()
 +   */
 +  const void* GetEntryStore() const
 +  {
@@ -1712,28 +1789,28 @@ diff --git a/xpcom/glue/nsTHashtable.h b
 +  static void* PR_CALLBACK s_AllocTable(PLDHashTable *table,
 +                                        PRUint32      nbytes);
 +
 +  static void PR_CALLBACK s_FreeTable(PLDHashTable *table,
 +                                      void         *ptr);
  
    static const void* PR_CALLBACK s_GetKey(PLDHashTable    *table,
                                            PLDHashEntryHdr *entry);
-@@ -257,10 +269,6 @@ protected:
+@@ -263,10 +275,6 @@ protected:
    static PRBool PR_CALLBACK s_MatchEntry(PLDHashTable           *table,
                                           const PLDHashEntryHdr  *entry,
                                           const void             *key);
 -  
 -  static void PR_CALLBACK s_CopyEntry(PLDHashTable          *table,
 -                                      const PLDHashEntryHdr *from,
 -                                      PLDHashEntryHdr       *to);
    
    static void PR_CALLBACK s_ClearEntry(PLDHashTable *table,
                                         PLDHashEntryHdr *entry);
-@@ -288,33 +296,33 @@ protected:
+@@ -294,33 +302,33 @@ protected:
                                                  void            *arg);
  private:
    // copy constructor, not implemented
 -  nsTHashtable(nsTHashtable<EntryType>& toCopy);
 +  nsTHashtable(nsTHashtable<EntryType, Allocator>& toCopy);
  
    // assignment operator, not implemented
 -  nsTHashtable<EntryType>& operator= (nsTHashtable<EntryType>& toEqual);
@@ -1765,43 +1842,43 @@ diff --git a/xpcom/glue/nsTHashtable.h b
 -template<class EntryType>
 +template<class EntryType, class Allocator>
  PRBool
 -nsTHashtable<EntryType>::Init(PRUint32 initSize)
 +nsTHashtable<EntryType, Allocator>::Init(PRUint32 initSize)
  {
    if (mTable.entrySize)
    {
-@@ -322,10 +330,10 @@ nsTHashtable<EntryType>::Init(PRUint32 i
+@@ -328,10 +336,10 @@ nsTHashtable<EntryType>::Init(PRUint32 i
      return PR_TRUE;
    }
  
 -  static PLDHashTableOps sOps = 
 +  static const PLDHashTableOps sOps = 
    {
 -    ::PL_DHashAllocTable,
 -    ::PL_DHashFreeTable,
 +    s_AllocTable,
 +    s_FreeTable,
      s_HashKey,
      s_MatchEntry,
      ::PL_DHashMoveEntryStub,
-@@ -334,11 +342,6 @@ nsTHashtable<EntryType>::Init(PRUint32 i
+@@ -340,11 +348,6 @@ nsTHashtable<EntryType>::Init(PRUint32 i
      s_InitEntry
    };
  
 -  if (!EntryType::ALLOW_MEMMOVE)
 -  {
 -    sOps.moveEntry = s_CopyEntry;
 -  }
 -  
    if (!PL_DHashTableInit(&mTable, &sOps, nsnull, sizeof(EntryType), initSize))
    {
      // if failed, reset "flag"
-@@ -351,62 +354,65 @@ nsTHashtable<EntryType>::Init(PRUint32 i
+@@ -357,62 +360,65 @@ nsTHashtable<EntryType>::Init(PRUint32 i
  
  // static definitions
  
 -template<class EntryType>
 +template<class EntryType, class Allocator>
 +void*
 +nsTHashtable<EntryType, Allocator>::s_AllocTable(PLDHashTable *,
 +                                                 PRUint32 nbytes)
--- a/gcobject-nodelete.patch
+++ b/gcobject-nodelete.patch
@@ -1418,60 +1418,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;
-@@ -3475,11 +3474,10 @@ nsresult
+@@ -3489,11 +3488,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;
  }
  
-@@ -3570,10 +3568,10 @@ ObjectPrincipalFinder(JSContext *cx, JSO
+@@ -3584,10 +3582,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;
-@@ -3755,7 +3753,6 @@ nsresult NS_CreateJSRuntime(nsIScriptRun
+@@ -3769,7 +3767,6 @@ nsresult NS_CreateJSRuntime(nsIScriptRun
    *aRuntime = new nsJSRuntime();
    if (*aRuntime == nsnull)
      return NS_ERROR_OUT_OF_MEMORY;
 -  NS_IF_ADDREF(*aRuntime);
    return NS_OK;
  }
  
-@@ -3765,7 +3762,7 @@ nsresult NS_CreateJSRuntime(nsIScriptRun
+@@ -3779,7 +3776,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();
-@@ -3894,7 +3891,6 @@ nsresult NS_CreateJSArgv(JSContext *aCon
+@@ -3908,7 +3905,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
@@ -1610,84 +1610,84 @@ diff --git a/js/src/xpconnect/loader/moz
       * error, then log it with the console service.  The UI can then
       * poll the service to update the Error console.
       */
 -    nsCOMPtr<nsIScriptError> errorObject = 
 +    nsIScriptError* errorObject = 
          do_CreateInstance(NS_SCRIPTERROR_CONTRACTID);
      
      if (consoleService && errorObject) {
-@@ -319,8 +319,8 @@ nsXPCFastLoadIO::GetInputStream(nsIInput
+@@ -324,8 +324,8 @@ nsXPCFastLoadIO::GetInputStream(nsIInput
  nsXPCFastLoadIO::GetInputStream(nsIInputStream **_retval)
  {
      if (! mInputStream) {
 -        nsCOMPtr<nsIInputStream> fileInput;
 -        nsresult rv = NS_NewLocalFileInputStream(getter_AddRefs(fileInput),
 +        nsIInputStream* fileInput = nsnull;
 +        nsresult rv = NS_NewLocalFileInputStream(&fileInput,
                                                   mFile);
          NS_ENSURE_SUCCESS(rv, rv);
  
-@@ -343,8 +343,8 @@ nsXPCFastLoadIO::GetOutputStream(nsIOutp
+@@ -348,8 +348,8 @@ nsXPCFastLoadIO::GetOutputStream(nsIOutp
              ioFlags |= PR_CREATE_FILE | PR_TRUNCATE;
          }
  
 -        nsCOMPtr<nsIOutputStream> fileOutput;
 -        nsresult rv = NS_NewLocalFileOutputStream(getter_AddRefs(fileOutput),
 +        nsIOutputStream* fileOutput = nsnull;
 +        nsresult rv = NS_NewLocalFileOutputStream(&fileOutput,
                                                    mFile, ioFlags, 0644);
          NS_ENSURE_SUCCESS(rv, rv);
  
-@@ -542,7 +542,7 @@ mozJSComponentLoader::ReallyInit()
+@@ -547,7 +547,7 @@ mozJSComponentLoader::ReallyInit()
      JS_SetThreadStackLimit(mContext, stackLimit);
  
  #ifndef XPCONNECT_STANDALONE
 -    nsCOMPtr<nsIScriptSecurityManager> secman = 
 +    nsIScriptSecurityManager* secman = 
          do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
      if (!secman)
          return NS_ERROR_FAILURE;
-@@ -560,7 +560,7 @@ mozJSComponentLoader::ReallyInit()
+@@ -565,7 +565,7 @@ mozJSComponentLoader::ReallyInit()
          return NS_ERROR_OUT_OF_MEMORY;
  
      // Set up our fastload file
 -    nsCOMPtr<nsIFastLoadService> flSvc = do_GetFastLoadService(&rv);
 +    nsIFastLoadService* flSvc = do_GetFastLoadService(&rv);
      if (NS_SUCCEEDED(rv))
          rv = flSvc->NewFastLoadFile("XPC", getter_AddRefs(mFastLoadFile));
      if (NS_FAILED(rv)) {
-@@ -569,7 +569,7 @@ mozJSComponentLoader::ReallyInit()
+@@ -574,7 +574,7 @@ mozJSComponentLoader::ReallyInit()
  
      // Listen for xpcom-shutdown so that we can close out our fastload file
      // at that point (after that we can no longer create an input stream).
 -    nsCOMPtr<nsIObserverService> obsSvc =
 +    nsIObserverService* obsSvc =
          do_GetService(kObserverServiceContractID, &rv);
      NS_ENSURE_SUCCESS(rv, rv);
  
-@@ -604,7 +604,7 @@ mozJSComponentLoader::LoadModule(nsILoca
+@@ -609,7 +609,7 @@ mozJSComponentLoader::LoadModule(nsILoca
              return rv;
      }
  
 -    nsCOMPtr<nsIHashable> lfhash(do_QueryInterface(aComponentFile));
 +    nsIHashable* lfhash(do_QueryInterface(aComponentFile));
      if (!lfhash) {
          NS_ERROR("nsLocalFile not implementing nsIHashable");
          return NS_NOINTERFACE;
-@@ -617,7 +617,7 @@ mozJSComponentLoader::LoadModule(nsILoca
+@@ -622,7 +622,7 @@ mozJSComponentLoader::LoadModule(nsILoca
          return NS_OK;
      }
  
 -    nsAutoPtr<ModuleEntry> entry(new ModuleEntry);
 +    ModuleEntry *entry(new ModuleEntry);
      if (!entry)
          return NS_ERROR_OUT_OF_MEMORY;
  
-@@ -629,23 +629,23 @@ mozJSComponentLoader::LoadModule(nsILoca
+@@ -634,23 +634,23 @@ mozJSComponentLoader::LoadModule(nsILoca
          return rv;
      }
  
 -    nsCOMPtr<nsIXPConnect> xpc = do_GetService(kXPConnectServiceContractID,
 +    nsIXPConnect* xpc = do_GetService(kXPConnectServiceContractID,
                                                 &rv);
      if (NS_FAILED(rv))
          return rv;
@@ -1706,49 +1706,49 @@ diff --git a/js/src/xpconnect/loader/moz
 +    nsIXPConnectJSObjectHolder* cm_holder = nsnull;
      rv = xpc->WrapNative(cx, entry->global, cm, 
                           NS_GET_IID(nsIComponentManager),
 -                         getter_AddRefs(cm_holder));
 +                         &cm_holder);
  
      if (NS_FAILED(rv)) {
  #ifdef DEBUG_shaver
-@@ -664,10 +664,10 @@ mozJSComponentLoader::LoadModule(nsILoca
+@@ -669,10 +669,10 @@ mozJSComponentLoader::LoadModule(nsILoca
      }
  
      JSObject* file_jsobj;
 -    nsCOMPtr<nsIXPConnectJSObjectHolder> file_holder;
 +    nsIXPConnectJSObjectHolder* file_holder = nsnull;
      rv = xpc->WrapNative(cx, entry->global, aComponentFile, 
                           NS_GET_IID(nsIFile),
 -                         getter_AddRefs(file_holder));
 +                         &file_holder);
  
      if (NS_FAILED(rv)) {
          return rv;
-@@ -730,9 +730,6 @@ mozJSComponentLoader::LoadModule(nsILoca
+@@ -735,9 +735,6 @@ mozJSComponentLoader::LoadModule(nsILoca
          return NS_ERROR_OUT_OF_MEMORY;
  
      NS_ADDREF(*aResult = entry->module);
 -
 -    // The hash owns the ModuleEntry now, forget about it
 -    entry.forget();
  
      return NS_OK;
  }
-@@ -836,7 +833,7 @@ mozJSComponentLoader::CloseFastLoad()
+@@ -841,7 +838,7 @@ mozJSComponentLoader::CloseFastLoad()
      if (mFastLoadOutput) {
          nsresult rv = mFastLoadOutput->Close();
          if (NS_SUCCEEDED(rv)) {
 -            nsCOMPtr<nsIFastLoadService> flSvc = do_GetFastLoadService(&rv);
 +            nsIFastLoadService* flSvc = do_GetFastLoadService(&rv);
              if (NS_SUCCEEDED(rv)) {
                  flSvc->CacheChecksum(mFastLoadFile, mFastLoadOutput);
              }
-@@ -875,15 +872,15 @@ mozJSComponentLoader::StartFastLoad(nsIF
+@@ -880,15 +877,15 @@ mozJSComponentLoader::StartFastLoad(nsIF
          if (exists) {
              LOG(("trying to use existing fastload file\n"));
  
 -            nsCOMPtr<nsIInputStream> input;
 -            rv = mFastLoadIO->GetInputStream(getter_AddRefs(input));
 +            nsIInputStream* input = nsnull;
 +            rv = mFastLoadIO->GetInputStream(&input);
              NS_ENSURE_SUCCESS(rv, rv);
@@ -1757,115 +1757,115 @@ diff --git a/js/src/xpconnect/loader/moz
              if (NS_SUCCEEDED(rv)) {
                  LOG(("opened fastload file for reading\n"));
  
 -                nsCOMPtr<nsIFastLoadReadControl>
 +                nsIFastLoadReadControl*
                      readControl(do_QueryInterface(mFastLoadInput));
                  if (readControl) {
                      // Verify checksum, using the FastLoadService's
-@@ -929,8 +926,8 @@ mozJSComponentLoader::StartFastLoad(nsIF
+@@ -934,8 +931,8 @@ mozJSComponentLoader::StartFastLoad(nsIF
          if (!exists) {
              LOG(("Creating new fastload file\n"));
  
 -            nsCOMPtr<nsIOutputStream> output;
 -            rv = mFastLoadIO->GetOutputStream(getter_AddRefs(output));
 +            nsIOutputStream* output = nsnull;
 +            rv = mFastLoadIO->GetOutputStream(&output);
              NS_ENSURE_SUCCESS(rv, rv);
  
              rv = flSvc->NewOutputStream(output,
-@@ -992,8 +989,8 @@ mozJSComponentLoader::ReadScript(nsIFast
+@@ -997,8 +994,8 @@ mozJSComponentLoader::ReadScript(nsIFast
  
      LOG(("Found %s in fastload file\n", nativePath));
  
 -    nsCOMPtr<nsIURI> oldURI;
 -    rv = flSvc->SelectMuxedDocument(uri, getter_AddRefs(oldURI));
 +    nsIURI* oldURI = nsnull;
 +    rv = flSvc->SelectMuxedDocument(uri, (class nsISupports**)&oldURI);
      NS_ENSURE_SUCCESS(rv, rv);
  
      NS_ASSERTION(mFastLoadInput,
-@@ -1033,8 +1030,8 @@ mozJSComponentLoader::WriteScript(nsIFas
+@@ -1038,8 +1035,8 @@ mozJSComponentLoader::WriteScript(nsIFas
                                     nsIFastLoadService::NS_FASTLOAD_WRITE);
      NS_ENSURE_SUCCESS(rv, rv);
  
 -    nsCOMPtr<nsIURI> oldURI;
 -    rv = flSvc->SelectMuxedDocument(uri, getter_AddRefs(oldURI));
 +    nsIURI* oldURI = nsnull;
 +    rv = flSvc->SelectMuxedDocument(uri, (class nsISupports**)&oldURI);
      NS_ENSURE_SUCCESS(rv, rv);
  
      rv = WriteScriptToStream(cx, script, mFastLoadOutput);
-@@ -1059,13 +1056,13 @@ mozJSComponentLoader::GlobalForLocation(
+@@ -1064,13 +1061,13 @@ mozJSComponentLoader::GlobalForLocation(
      JSPrincipalsHolder princHolder(mContext, jsPrincipals);
  #endif
  
 -    nsCOMPtr<nsIXPCScriptable> backstagePass;
 -    rv = mRuntimeService->GetBackstagePass(getter_AddRefs(backstagePass));
 +    nsIXPCScriptable* backstagePass = nsnull;
 +    rv = mRuntimeService->GetBackstagePass(&backstagePass);
      NS_ENSURE_SUCCESS(rv, rv);
  
      JSCLAutoErrorReporterSetter aers(cx, mozJSLoaderErrorReporter);
  
 -    nsCOMPtr<nsIXPConnect> xpc =
 +    nsIXPConnect* xpc =
          do_GetService(kXPConnectServiceContractID, &rv);
      NS_ENSURE_SUCCESS(rv, rv);
  
-@@ -1073,12 +1070,12 @@ mozJSComponentLoader::GlobalForLocation(
+@@ -1078,12 +1075,12 @@ mozJSComponentLoader::GlobalForLocation(
      // backstage pass as the global in our compilation context.
      JS_SetGlobalObject(cx, nsnull);
  
 -    nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
 +    nsIXPConnectJSObjectHolder* holder = nsnull;
      rv = xpc->InitClassesWithNewWrappedGlobal(cx, backstagePass,
                                                NS_GET_IID(nsISupports),
                                                nsIXPConnect::
                                                    FLAG_SYSTEM_GLOBAL_OBJECT,
 -                                              getter_AddRefs(holder));
 +                                              &holder);
      NS_ENSURE_SUCCESS(rv, rv);
  
      JSObject *global;
-@@ -1089,10 +1086,10 @@ mozJSComponentLoader::GlobalForLocation(
+@@ -1094,10 +1091,10 @@ mozJSComponentLoader::GlobalForLocation(
          return NS_ERROR_FAILURE;
      }
  
 -    nsCOMPtr<nsIXPConnectJSObjectHolder> locationHolder;
 +    nsIXPConnectJSObjectHolder* locationHolder = nsnull;
      rv = xpc->WrapNative(cx, global, aComponent,
                           NS_GET_IID(nsILocalFile),
 -                         getter_AddRefs(locationHolder));
 +                         &locationHolder);
      NS_ENSURE_SUCCESS(rv, rv);
  
      JSObject *locationObj;
-@@ -1118,7 +1115,7 @@ mozJSComponentLoader::GlobalForLocation(
+@@ -1123,7 +1120,7 @@ mozJSComponentLoader::GlobalForLocation(
      // Before compiling the script, first check to see if we have it in
      // the fastload file.  Note: as a rule, fastload errors are not fatal
      // to loading the script, since we can always slow-load.
 -    nsCOMPtr<nsIFastLoadService> flSvc = do_GetFastLoadService(&rv);
 +    nsIFastLoadService* flSvc = do_GetFastLoadService(&rv);
  
      // Save the old state and restore it upon return
      FastLoadStateHolder flState(flSvc);
-@@ -1131,8 +1128,8 @@ mozJSComponentLoader::GlobalForLocation(
+@@ -1136,8 +1133,8 @@ mozJSComponentLoader::GlobalForLocation(
          }
      }
  
 -    nsCOMPtr<nsIURI> uri;
 -    rv = NS_NewURI(getter_AddRefs(uri), nativePath);
 +    nsIURI* uri = nsnull;
 +    rv = NS_NewURI(&uri, nativePath);
      NS_ENSURE_SUCCESS(rv, rv);
  
      JSScript *script = nsnull;
-@@ -1151,14 +1148,14 @@ mozJSComponentLoader::GlobalForLocation(
+@@ -1156,14 +1153,14 @@ mozJSComponentLoader::GlobalForLocation(
  
              // Remove the fastload file, it may be corrupted.
              LOG(("Invalid fastload file detected, removing it\n"));
 -            nsCOMPtr<nsIObjectOutputStream> objectOutput;
 -            flSvc->GetOutputStream(getter_AddRefs(objectOutput));
 +            nsIObjectOutputStream* objectOutput = nsnull;
 +            flSvc->GetOutputStream(&objectOutput);
              if (objectOutput) {
@@ -1874,57 +1874,57 @@ 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();
-@@ -1327,7 +1324,7 @@ mozJSComponentLoader::Import(const nsACS
+@@ -1332,7 +1329,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);
      
-@@ -1338,8 +1335,8 @@ mozJSComponentLoader::Import(const nsACS
+@@ -1343,8 +1340,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);
      nsXPIDLCString name;
      info->GetName(getter_Copies(name));
-@@ -1382,8 +1379,8 @@ mozJSComponentLoader::Import(const nsACS
+@@ -1387,8 +1384,8 @@ mozJSComponentLoader::Import(const nsACS
          // Our targetObject is the caller's global object. Find it by
          // walking the calling object's parent chain.
  
 -        nsCOMPtr<nsIXPConnectWrappedNative> wn;
 -        rv = cc->GetCalleeWrapper(getter_AddRefs(wn));
 +        nsIXPConnectWrappedNative* wn = nsnull;
 +        rv = cc->GetCalleeWrapper(&wn);
          NS_ENSURE_SUCCESS(rv, rv);
          
          wn->GetJSObject(&targetObject);
-@@ -1422,7 +1419,7 @@ mozJSComponentLoader::ImportInto(const n
+@@ -1427,7 +1424,7 @@ mozJSComponentLoader::ImportInto(const n
          NS_ENSURE_SUCCESS(rv, rv);
      }
      
 -    nsCOMPtr<nsIIOService> ioService = do_GetIOService(&rv);
 +    nsIIOService* ioService = do_GetIOService(&rv);
      NS_ENSURE_SUCCESS(rv, rv);
  
      // Get the URI.
-@@ -1433,20 +1430,20 @@ mozJSComponentLoader::ImportInto(const n
+@@ -1438,20 +1435,20 @@ mozJSComponentLoader::ImportInto(const n
      NS_ENSURE_SUCCESS(rv, NS_ERROR_INVALID_ARG);
  
      // Get the file belonging to it.
 -    nsCOMPtr<nsIFile> file;
 -    rv = fileURL->GetFile(getter_AddRefs(file));
 +    nsIFile* file = nsnull;
 +    rv = fileURL->GetFile(&file);
      NS_ENSURE_SUCCESS(rv, rv);
@@ -1940,17 +1940,17 @@ diff --git a/js/src/xpconnect/loader/moz
      }
  
      ModuleEntry* mod;
 -    nsAutoPtr<ModuleEntry> newEntry;
 +    ModuleEntry* newEntry = nsnull;
      if (!mImports.Get(lfhash, &mod) && !mInProgressImports.Get(lfhash, &mod)) {
          newEntry = new ModuleEntry;
          if (!newEntry || !mInProgressImports.Put(lfhash, newEntry))
-@@ -1539,7 +1536,6 @@ mozJSComponentLoader::ImportInto(const n
+@@ -1544,7 +1541,6 @@ mozJSComponentLoader::ImportInto(const n
      if (newEntry) {
          if (!mImports.Put(lfhash, newEntry))
              return NS_ERROR_OUT_OF_MEMORY;
 -        newEntry.forget();
      }
      
      return NS_OK;
 diff --git a/js/src/xpconnect/src/xpcjsruntime.cpp b/js/src/xpconnect/src/xpcjsruntime.cpp
@@ -2075,26 +2075,26 @@ diff --git a/js/src/xpconnect/src/xpcwra
          // 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;
-@@ -2441,7 +2433,7 @@ XPCWrappedNative::GetObjectPrincipal() c
+@@ -2447,7 +2439,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
-@@ -2726,8 +2718,8 @@ XPCWrappedNative::HandlePossibleNameCase
+@@ -2732,8 +2724,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) {
@@ -2110,85 +2110,85 @@ diff --git a/js/src/xpconnect/src/xpcwra
 -
 -    delete mScriptableInfo;
  }
  
  JSBool
 diff --git a/layout/generic/nsTextFrameThebes.cpp b/layout/generic/nsTextFrameThebes.cpp
 --- a/layout/generic/nsTextFrameThebes.cpp
 +++ b/layout/generic/nsTextFrameThebes.cpp
-@@ -433,7 +433,6 @@ nsTextFrameTextRunCache::Init() {
+@@ -435,7 +435,6 @@ nsTextFrameTextRunCache::Init() {
  
  void
  nsTextFrameTextRunCache::Shutdown() {
 -    delete gTextRuns;
      gTextRuns = nsnull;
  }
  
-@@ -1293,10 +1292,10 @@ static AddRefed<gfxContext>
+@@ -1295,10 +1294,10 @@ static AddRefed<gfxContext>
  static AddRefed<gfxContext>
  GetReferenceRenderingContext(nsTextFrame* aTextFrame, nsIRenderingContext* aRC)
  {
 -  nsCOMPtr<nsIRenderingContext> tmp = aRC;
 +  nsIRenderingContext* tmp = aRC;
    if (!tmp) {
      nsresult rv = aTextFrame->PresContext()->PresShell()->
 -      CreateRenderingContext(aTextFrame, getter_AddRefs(tmp));
 +      CreateRenderingContext(aTextFrame, &tmp);
      if (NS_FAILED(rv))
        return AddRefed<gfxContext>(nsnull);
    }
-@@ -2510,7 +2509,7 @@ PropertyProvider::SetupJustificationSpac
+@@ -2512,7 +2511,7 @@ PropertyProvider::SetupJustificationSpac
  
  // Helper class for managing blinking text
  
 -class nsBlinkTimer : public nsITimerCallback
 +class nsBlinkTimer : public XPCOMGCFinalizedObject, public nsITimerCallback
  {
  public:
    nsBlinkTimer();
-@@ -2667,7 +2666,6 @@ nsresult nsBlinkTimer::AddBlinkFrame(nsP
+@@ -2669,7 +2668,6 @@ nsresult nsBlinkTimer::AddBlinkFrame(nsP
      if (!sTextBlinker) return NS_ERROR_OUT_OF_MEMORY;
    }
    
 -  NS_ADDREF(sTextBlinker);
  
    sTextBlinker->AddFrame(aPresContext, aFrame);
    return NS_OK;
-@@ -2906,7 +2904,7 @@ nsTextPaintStyle::InitSelectionColors()
+@@ -2908,7 +2906,7 @@ nsTextPaintStyle::InitSelectionColors()
  
    if (selectionContent &&
        selectionStatus == nsISelectionController::SELECTION_ON) {
 -    nsRefPtr<nsStyleContext> sc = nsnull;
 +    nsStyleContext* sc = nsnull;
      sc = mPresContext->StyleSet()->
        ProbePseudoStyleFor(selectionContent, nsCSSPseudoElements::mozSelection,
                            mFrame->GetStyleContext());
-@@ -3085,7 +3083,7 @@ NS_IMETHODIMP nsTextFrame::GetAccessible
+@@ -3087,7 +3085,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);
-@@ -4228,9 +4226,9 @@ nsTextFrame::GetSelectionStatus(PRInt16*
+@@ -4325,9 +4323,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;
  
-@@ -4392,15 +4390,15 @@ nsTextFrame::SetSelected(nsPresContext* 
+@@ -4489,15 +4487,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;
@@ -2271,133 +2271,133 @@ diff --git a/layout/mathml/base/src/nsMa
 -  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
 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
-@@ -612,7 +612,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
+@@ -604,7 +604,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;
-@@ -644,7 +643,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
+@@ -636,7 +635,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
-@@ -680,7 +678,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
+@@ -672,7 +670,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
-@@ -783,7 +780,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
+@@ -775,7 +772,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
    ::UseResFile(appRefNum);
    *aResult = plugin;
  
 -  NS_ADDREF(*aResult);
    if (NS_FAILED((*aResult)->Initialize())) {
      NS_RELEASE(*aResult);
      return NS_ERROR_FAILURE;
-@@ -812,7 +808,6 @@ ns4xPlugin::CreatePlugin(nsIServiceManag
+@@ -804,7 +800,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
-@@ -851,7 +846,7 @@ ns4xPlugin::CreateInstance(nsISupports *
+@@ -843,7 +838,7 @@ ns4xPlugin::CreateInstance(nsISupports *
    *aResult = NULL;
  
    // XXX This is suspicuous!
 -  nsRefPtr<ns4xPluginInstance> inst =
 +  ns4xPluginInstance* inst =
      new ns4xPluginInstance(&fCallbacks, fLibrary);
  
    if (!inst)
-@@ -972,13 +967,13 @@ MakeNew4xStreamInternal(NPP npp, const c
+@@ -964,13 +959,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);
  
-@@ -1113,7 +1108,7 @@ _posturl(NPP npp, const char *relativeUR
+@@ -1105,7 +1100,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
-@@ -1138,7 +1133,6 @@ ns4xStreamWrapper::ns4xStreamWrapper(nsI
+@@ -1130,7 +1125,6 @@ ns4xStreamWrapper::ns4xStreamWrapper(nsI
    NS_ASSERTION(stream != NULL, "bad stream");
  
    fStream = stream;
 -  NS_ADDREF(fStream);
  
    memset(&fNPStream, 0, sizeof(fNPStream));
    fNPStream.ndata = (void*) this;
-@@ -1154,7 +1148,6 @@ ns4xStreamWrapper::GetStream(nsIOutputSt
+@@ -1146,7 +1140,6 @@ ns4xStreamWrapper::GetStream(nsIOutputSt
  ns4xStreamWrapper::GetStream(nsIOutputStream* &result)
  {
    result = fStream;
 -  NS_IF_ADDREF(fStream);
  }
  
  
-@@ -1274,7 +1267,6 @@ _destroystream(NPP npp, NPStream *pstrea
+@@ -1266,7 +1259,6 @@ _destroystream(NPP npp, NPStream *pstrea
        return NPERR_INVALID_PARAM;
  
      // This will release the wrapped nsIOutputStream.
 -    delete wrapper;
      pstream->ndata = nsnull;
    }
  
-@@ -1464,12 +1456,12 @@ GetDocumentFromNPP(NPP npp)
+@@ -1456,12 +1448,12 @@ GetDocumentFromNPP(NPP npp)
    nsCOMPtr<nsPIPluginInstancePeer> pp(do_QueryInterface(pip));
    NS_ENSURE_TRUE(pp, nsnull);
  
 -  nsCOMPtr<nsIPluginInstanceOwner> owner;
 -  pp->GetOwner(getter_AddRefs(owner));
 +  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);
  
    return doc;
  }
-@@ -1526,19 +1518,19 @@ _getpluginelement(NPP npp)
+@@ -1518,19 +1510,19 @@ _getpluginelement(NPP npp)
    }
  
    // Pass ownership of elementp to element
 -  nsCOMPtr<nsIDOMElement> element;
 -  element.swap(elementp);
 +  nsIDOMElement* element = nsnull;
 +  swap(element, elementp);
  
@@ -2412,55 +2412,55 @@ 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;
-@@ -1838,7 +1830,7 @@ _evaluate(NPP npp, NPObject* npobj, NPSt
+@@ -1830,7 +1822,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 = doc->NodePrincipal();
-@@ -2226,8 +2218,8 @@ _getvalue(NPP npp, NPNVariable variable,
+@@ -2218,8 +2210,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))) {
-@@ -2239,7 +2231,7 @@ _getvalue(NPP npp, NPNVariable variable,
+@@ -2231,7 +2223,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);
-@@ -2255,7 +2247,7 @@ _getvalue(NPP npp, NPNVariable variable,
+@@ -2247,7 +2239,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);
-@@ -2280,14 +2272,14 @@ _getvalue(NPP npp, NPNVariable variable,
+@@ -2272,14 +2264,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);
@@ -2471,35 +2471,35 @@ 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;
        }
      }
-@@ -2298,7 +2290,7 @@ _getvalue(NPP npp, NPNVariable variable,
+@@ -2290,7 +2282,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.
-@@ -2425,7 +2417,7 @@ _setvalue(NPP npp, NPPVariable variable,
+@@ -2417,7 +2409,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);
-@@ -2433,9 +2425,9 @@ _setvalue(NPP npp, NPPVariable variable,
+@@ -2425,9 +2417,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) {
@@ -2693,17 +2693,17 @@ diff --git a/xpcom/base/nsAgg.h b/xpcom/
      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
-@@ -1992,7 +1992,6 @@ nsComponentManagerImpl::RegisterService(
+@@ -1995,7 +1995,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
@@ -2970,17 +2970,17 @@ diff --git a/xpfe/components/intl/nsChar
    // rebuild the menu
 -  nsCOMPtr<nsIUTF8StringEnumerator> decoders;
 -  res = mCCManager->GetDecoderList(getter_AddRefs(decoders));
 +  nsIUTF8StringEnumerator* decoders = nsnull;
 +  res = mCCManager->GetDecoderList(&decoders);
    if (NS_FAILED(res)) return res;
  
    nsCStringArray decs;
-@@ -598,16 +597,16 @@ nsresult nsCharsetMenu::RefreshMailviewM
+@@ -602,16 +601,16 @@ nsresult nsCharsetMenu::RefreshMailviewM
  {
    nsresult res = NS_OK;
  
 -  nsCOMPtr<nsIRDFContainer> container;
 -  res = NewRDFContainer(mInner, kNC_MailviewCharsetMenuRoot, getter_AddRefs(container));
 +  nsIRDFContainer* container = nsnull;
 +  res = NewRDFContainer(mInner, kNC_MailviewCharsetMenuRoot, &container);
    if (NS_FAILED(res)) return res;
@@ -2991,17 +2991,17 @@ diff --git a/xpfe/components/intl/nsChar
  
 -  nsCOMPtr<nsIUTF8StringEnumerator> decoders;
 -  res = mCCManager->GetDecoderList(getter_AddRefs(decoders));
 +  nsIUTF8StringEnumerator* decoders = nsnull;
 +  res = mCCManager->GetDecoderList(&decoders);
    if (NS_FAILED(res)) return res;
  
    nsCStringArray decs;
-@@ -631,17 +630,17 @@ nsresult nsCharsetMenu::RefreshMaileditM
+@@ -635,17 +634,17 @@ nsresult nsCharsetMenu::RefreshMaileditM
  {
    nsresult res;
  
 -  nsCOMPtr<nsIRDFContainer> container;
 -  res = NewRDFContainer(mInner, kNC_MaileditCharsetMenuRoot, getter_AddRefs(container));
 +  nsIRDFContainer* container = nsnull;
 +  res = NewRDFContainer(mInner, kNC_MaileditCharsetMenuRoot, &container);
    NS_ENSURE_SUCCESS(res, res);
@@ -3015,28 +3015,28 @@ diff --git a/xpfe/components/intl/nsChar
    // clear the menu
 -  nsCOMPtr<nsIRDFNode> node;
 -  while (NS_SUCCEEDED(enumerator->GetNext(getter_AddRefs(node)))) {
 +  nsIRDFNode* node = nsnull;
 +  while (NS_SUCCEEDED(enumerator->GetNext((class nsISupports**)&node))) {
  
      res = mInner->Unassert(kNC_MaileditCharsetMenuRoot, kNC_Name, node);
      NS_ENSURE_SUCCESS(res, res);
-@@ -651,8 +650,8 @@ nsresult nsCharsetMenu::RefreshMaileditM
+@@ -655,8 +654,8 @@ nsresult nsCharsetMenu::RefreshMaileditM
    }
  
    // get a list of available encoders
 -  nsCOMPtr<nsIUTF8StringEnumerator> encoders;
 -  res = mCCManager->GetEncoderList(getter_AddRefs(encoders));
 +  nsIUTF8StringEnumerator* encoders = nsnull;
 +  res = mCCManager->GetEncoderList(&encoders);
    NS_ENSURE_SUCCESS(res, res);
  
    nsCStringArray encs;
-@@ -669,16 +668,16 @@ nsresult nsCharsetMenu::RefreshComposerM
+@@ -673,16 +672,16 @@ nsresult nsCharsetMenu::RefreshComposerM
  {
    nsresult res = NS_OK;
  
 -  nsCOMPtr<nsIRDFContainer> container;
 -  res = NewRDFContainer(mInner, kNC_ComposerCharsetMenuRoot, getter_AddRefs(container));
 +  nsIRDFContainer* container = nsnull;
 +  res = NewRDFContainer(mInner, kNC_ComposerCharsetMenuRoot, &container);
    if (NS_FAILED(res)) return res;
@@ -3047,28 +3047,28 @@ diff --git a/xpfe/components/intl/nsChar
  
 -  nsCOMPtr<nsIUTF8StringEnumerator> decoders;
 -  res = mCCManager->GetDecoderList(getter_AddRefs(decoders));
 +  nsIUTF8StringEnumerator* decoders = nsnull;
 +  res = mCCManager->GetDecoderList(&decoders);
    if (NS_FAILED(res)) return res;
  
    nsCStringArray decs;
-@@ -705,8 +704,8 @@ nsresult nsCharsetMenu::Init()
+@@ -709,8 +708,8 @@ nsresult nsCharsetMenu::Init()
    if (!mInitialized)  {
  
      //enumerate decoders
 -    nsCOMPtr<nsIUTF8StringEnumerator> decoders;
 -    res = mCCManager->GetDecoderList(getter_AddRefs(decoders));
 +    nsIUTF8StringEnumerator* decoders = nsnull;
 +    res = mCCManager->GetDecoderList(&decoders);
      if (NS_FAILED(res)) return res;
  
      SetArrayFromEnumerator(decoders, mDecoderList);
-@@ -822,20 +821,20 @@ nsresult nsCharsetMenu::SetCharsetCheckm
+@@ -826,20 +825,20 @@ nsresult nsCharsetMenu::SetCharsetCheckm
                                              PRBool aValue)
  {
    nsresult res = NS_OK;
 -  nsCOMPtr<nsIRDFContainer> container;
 -  nsCOMPtr<nsIRDFResource> node;
 +  nsIRDFContainer* container = nsnull;
 +  nsIRDFResource* node = nsnull;
  
@@ -3085,123 +3085,123 @@ diff --git a/xpfe/components/intl/nsChar
 -  nsCOMPtr<nsIRDFLiteral> checkedLiteral;
 +  nsIRDFLiteral* checkedLiteral = nsnull;
    nsAutoString checked; checked.AssignWithConversion((aValue == PR_TRUE) ? "true" : "false");
 -  res = mRDFService->GetLiteral(checked.get(), getter_AddRefs(checkedLiteral));
 +  res = mRDFService->GetLiteral(checked.get(), &checkedLiteral);
    if (NS_FAILED(res)) return res;
    res = Assert(node, kNC_Checked, checkedLiteral, PR_TRUE);
    if (NS_FAILED(res)) return res;
-@@ -851,7 +850,7 @@ nsresult nsCharsetMenu::FreeResources()
+@@ -855,7 +854,7 @@ nsresult nsCharsetMenu::FreeResources()
    nsresult res = NS_OK;
  
    if (mCharsetMenuObserver) {
 -    nsCOMPtr<nsIPrefBranch2> pbi = do_QueryInterface(mPrefs);
 +    nsIPrefBranch2* pbi = do_QueryInterface(mPrefs);
      if (pbi) {
        pbi->RemoveObserver(kBrowserStaticPrefKey, mCharsetMenuObserver);
        pbi->RemoveObserver(kMaileditPrefKey, mCharsetMenuObserver);
-@@ -873,8 +872,8 @@ nsresult nsCharsetMenu::InitBrowserMenu(
+@@ -877,8 +876,8 @@ nsresult nsCharsetMenu::InitBrowserMenu(
    nsresult res = NS_OK;
  
    if (!mBrowserMenuInitialized)  {
 -    nsCOMPtr<nsIRDFContainer> container;
 -    res = NewRDFContainer(mInner, kNC_BrowserCharsetMenuRoot, getter_AddRefs(container));
 +    nsIRDFContainer* container = nsnull;
 +    res = NewRDFContainer(mInner, kNC_BrowserCharsetMenuRoot, &container);
      if (NS_FAILED(res)) return res;
  
  
-@@ -902,7 +901,7 @@ nsresult nsCharsetMenu::InitBrowserMenu(
+@@ -910,7 +909,7 @@ nsresult nsCharsetMenu::InitBrowserMenu(
      NS_ASSERTION(NS_SUCCEEDED(res), "error initializing browser cache charset menu");
  
      // register prefs callback
 -    nsCOMPtr<nsIPrefBranch2> pbi = do_QueryInterface(mPrefs);
 +    nsIPrefBranch2* pbi = do_QueryInterface(mPrefs);
      if (pbi)
        res = pbi->AddObserver(kBrowserStaticPrefKey, mCharsetMenuObserver, PR_FALSE);
    }
-@@ -922,8 +921,8 @@ nsresult nsCharsetMenu::InitMaileditMenu
+@@ -930,8 +929,8 @@ nsresult nsCharsetMenu::InitMaileditMenu
    nsresult res = NS_OK;
  
    if (!mMaileditMenuInitialized)  {
 -    nsCOMPtr<nsIRDFContainer> container;
 -    res = NewRDFContainer(mInner, kNC_MaileditCharsetMenuRoot, getter_AddRefs(container));
 +    nsIRDFContainer* container = nsnull;
 +    res = NewRDFContainer(mInner, kNC_MaileditCharsetMenuRoot, &container);
      if (NS_FAILED(res)) return res;
  
      //enumerate encoders
-@@ -931,8 +930,8 @@ nsresult nsCharsetMenu::InitMaileditMenu
+@@ -939,8 +938,8 @@ nsresult nsCharsetMenu::InitMaileditMenu
      // charset encoders, but it's safe because we rely on prefs to filter
      // them out. Moreover, 'customize' menu lists only genuine charset 
      // encoders further guarding  against  'font encoders' sneaking in. 
 -    nsCOMPtr<nsIUTF8StringEnumerator> encoders;
 -    res = mCCManager->GetEncoderList(getter_AddRefs(encoders));
 +    nsIUTF8StringEnumerator* encoders = nsnull;
 +    res = mCCManager->GetEncoderList(&encoders);
      if (NS_FAILED(res))  return res;
  
      nsCStringArray maileditEncoderList;
-@@ -942,7 +941,7 @@ nsresult nsCharsetMenu::InitMaileditMenu
+@@ -950,7 +949,7 @@ nsresult nsCharsetMenu::InitMaileditMenu
      NS_ASSERTION(NS_SUCCEEDED(res), "error initializing mailedit charset menu from prefs");
  
      // register prefs callback
 -    nsCOMPtr<nsIPrefBranch2> pbi = do_QueryInterface(mPrefs);
 +    nsIPrefBranch2* pbi = do_QueryInterface(mPrefs);
      if (pbi)
        res = pbi->AddObserver(kMaileditPrefKey, mCharsetMenuObserver, PR_FALSE);
    }
-@@ -962,8 +961,8 @@ nsresult nsCharsetMenu::InitMailviewMenu
+@@ -970,8 +969,8 @@ nsresult nsCharsetMenu::InitMailviewMenu
    nsresult res = NS_OK;
  
    if (!mMailviewMenuInitialized)  {
 -    nsCOMPtr<nsIRDFContainer> container;
 -    res = NewRDFContainer(mInner, kNC_MailviewCharsetMenuRoot, getter_AddRefs(container));
 +    nsIRDFContainer* container = nsnull;
 +    res = NewRDFContainer(mInner, kNC_MailviewCharsetMenuRoot, &container);
      if (NS_FAILED(res)) return res;
  
      nsCStringArray mailviewDecoderList;
-@@ -1004,8 +1003,8 @@ nsresult nsCharsetMenu::InitComposerMenu
+@@ -1012,8 +1011,8 @@ nsresult nsCharsetMenu::InitComposerMenu
    nsresult res = NS_OK;
  
    if (!mComposerMenuInitialized)  {
 -    nsCOMPtr<nsIRDFContainer> container;
 -    res = NewRDFContainer(mInner, kNC_ComposerCharsetMenuRoot, getter_AddRefs(container));
 +    nsIRDFContainer* container = nsnull;
 +    res = NewRDFContainer(mInner, kNC_ComposerCharsetMenuRoot, &container);
      if (NS_FAILED(res)) return res;
  
      nsCStringArray composerDecoderList;
-@@ -1109,9 +1108,9 @@ nsresult nsCharsetMenu::InitStaticMenu(n
+@@ -1117,9 +1116,9 @@ nsresult nsCharsetMenu::InitStaticMenu(n
    NS_TIMELINE_START_TIMER("nsCharsetMenu::InitStaticMenu");
  
    nsresult res = NS_OK;
 -  nsCOMPtr<nsIRDFContainer> container;
 +  nsIRDFContainer* container = nsnull;
  
 -  res = NewRDFContainer(mInner, aResource, getter_AddRefs(container));
 +  res = NewRDFContainer(mInner, aResource, &container);
    if (NS_FAILED(res)) return res;
  
    // XXX work around bug that causes the submenus to be first instead of last
-@@ -1136,9 +1135,9 @@ nsresult nsCharsetMenu::InitCacheMenu(
+@@ -1144,9 +1143,9 @@ nsresult nsCharsetMenu::InitCacheMenu(
    NS_TIMELINE_START_TIMER("nsCharsetMenu::InitCacheMenu");
  
    nsresult res = NS_OK;
 -  nsCOMPtr<nsIRDFContainer> container;
 +  nsIRDFContainer* container = nsnull;
  
 -  res = NewRDFContainer(mInner, aResource, getter_AddRefs(container));
 +  res = NewRDFContainer(mInner, aResource, &container);
    if (NS_FAILED(res)) return res;
  
    res = AddFromNolocPrefsToMenu(aArray, container, aKey, aDecs, "charset.");
-@@ -1158,14 +1157,14 @@ nsresult nsCharsetMenu::InitAutodetMenu(
+@@ -1166,14 +1165,14 @@ nsresult nsCharsetMenu::InitAutodetMenu(
  
    if (!mAutoDetectInitialized) {
      nsVoidArray chardetArray;
 -    nsCOMPtr<nsIRDFContainer> container;
 +    nsIRDFContainer* container = nsnull;
      nsCStringArray detectorArray;
  
 -    res = NewRDFContainer(mInner, kNC_BrowserAutodetMenuRoot, getter_AddRefs(container));
@@ -3210,31 +3210,30 @@ diff --git a/xpfe/components/intl/nsChar
  
 -    nsCOMPtr<nsIUTF8StringEnumerator> detectors;
 -    res = mCCManager->GetCharsetDetectorList(getter_AddRefs(detectors));
 +    nsIUTF8StringEnumerator* detectors = nsnull;
 +    res = mCCManager->GetCharsetDetectorList(&detectors);
      if (NS_FAILED(res)) goto done;
  
      res = SetArrayFromEnumerator(detectors, detectorArray);
-@@ -1202,11 +1201,11 @@ nsresult nsCharsetMenu::InitMoreMenu(nsC
+@@ -1210,10 +1209,10 @@ nsresult nsCharsetMenu::InitMoreMenu(nsC
    NS_TIMELINE_START_TIMER("nsCharsetMenu::InitMoreMenu");
  
    nsresult res = NS_OK;
 -  nsCOMPtr<nsIRDFContainer> container;
 +  nsIRDFContainer* container = nsnull;
    nsVoidArray moreMenu;
-   nsAutoString prop; prop.AssignWithConversion(aFlag);
  
 -  res = NewRDFContainer(mInner, aResource, getter_AddRefs(container));
 +  res = NewRDFContainer(mInner, aResource, &container);
    if (NS_FAILED(res)) goto done;
  
    // remove charsets "not for browser"
-@@ -1240,12 +1239,12 @@ nsresult nsCharsetMenu::InitMoreSubmenus
+@@ -1247,12 +1246,12 @@ nsresult nsCharsetMenu::InitMoreSubmenus
  
    nsresult res = NS_OK;
  
 -  nsCOMPtr<nsIRDFContainer> container1;
 -  nsCOMPtr<nsIRDFContainer> container2;
 -  nsCOMPtr<nsIRDFContainer> container3;
 -  nsCOMPtr<nsIRDFContainer> container4;
 -  nsCOMPtr<nsIRDFContainer> container5;
@@ -3243,17 +3242,17 @@ diff --git a/xpfe/components/intl/nsChar
 +  nsIRDFContainer* container2 = nsnull;
 +  nsIRDFContainer* container3 = nsnull;
 +  nsIRDFContainer* container4 = nsnull;
 +  nsIRDFContainer* container5 = nsnull;
 +  nsIRDFContainer* containerU = nsnull;
    const char key1[] = "intl.charsetmenu.browser.more1";
    const char key2[] = "intl.charsetmenu.browser.more2";
    const char key3[] = "intl.charsetmenu.browser.more3";
-@@ -1254,32 +1253,32 @@ nsresult nsCharsetMenu::InitMoreSubmenus
+@@ -1261,32 +1260,32 @@ nsresult nsCharsetMenu::InitMoreSubmenus
    const char keyU[] = "intl.charsetmenu.browser.unicode";
  
    res = NewRDFContainer(mInner, kNC_BrowserMore1CharsetMenuRoot, 
 -    getter_AddRefs(container1));
 +    &container1);
    if (NS_FAILED(res)) return res;
    AddFromPrefsToMenu(NULL, container1, key1, aDecs, NULL);
  
@@ -3282,17 +3281,17 @@ diff --git a/xpfe/components/intl/nsChar
    AddFromPrefsToMenu(NULL, container5, key5, aDecs, NULL);
  
    res = NewRDFContainer(mInner, kNC_BrowserUnicodeCharsetMenuRoot, 
 -    getter_AddRefs(containerU));
 +    &containerU);
    if (NS_FAILED(res)) return res;
    AddFromPrefsToMenu(NULL, containerU, keyU, aDecs, NULL);
  
-@@ -1362,21 +1361,21 @@ nsresult nsCharsetMenu::AddMenuItemToCon
+@@ -1369,21 +1368,21 @@ nsresult nsCharsetMenu::AddMenuItemToCon
                          PRInt32 aPlace) 
  {
    nsresult res = NS_OK;
 -  nsCOMPtr<nsIRDFResource> node;
 +  nsIRDFResource* node = nsnull;
  
    nsCAutoString id;
    if (aIDPrefix != NULL) id.Assign(aIDPrefix);
@@ -3308,57 +3307,57 @@ diff --git a/xpfe/components/intl/nsChar
    // set node's title
 -  nsCOMPtr<nsIRDFLiteral> titleLiteral;
 -  res = mRDFService->GetLiteral(title, getter_AddRefs(titleLiteral));
 +  nsIRDFLiteral* titleLiteral = nsnull;
 +  res = mRDFService->GetLiteral(title, &titleLiteral);
    if (NS_FAILED(res)) return res;
  
    if (aPlace < -1) {
-@@ -1466,8 +1465,8 @@ nsresult nsCharsetMenu::AddFromPrefsToMe
+@@ -1473,8 +1472,8 @@ nsresult nsCharsetMenu::AddFromPrefsToMe
  {
    nsresult res = NS_OK;
  
 -  nsCOMPtr<nsIPrefLocalizedString> pls;
 -  res = mPrefs->GetComplexValue(aKey, NS_GET_IID(nsIPrefLocalizedString), getter_AddRefs(pls));
 +  nsIPrefLocalizedString* pls = nsnull;
 +  res = mPrefs->GetComplexValue(aKey, NS_GET_IID(nsIPrefLocalizedString), (void**)&pls);
    if (NS_FAILED(res)) return res;
  
    if (pls) {
-@@ -1573,8 +1572,8 @@ nsCharsetMenu::AddCharsetToCache(const n
+@@ -1580,8 +1579,8 @@ nsCharsetMenu::AddCharsetToCache(const n
    i = FindMenuItemInArray(aArray, aCharset, NULL);
    if (i >= 0) return res;
  
 -  nsCOMPtr<nsIRDFContainer> container;
 -  res = NewRDFContainer(mInner, aRDFResource, getter_AddRefs(container));
 +  nsIRDFContainer* container = nsnull;
 +  res = NewRDFContainer(mInner, aRDFResource, &container);
    if (NS_FAILED(res)) return res;
  
    // iff too many items, remove last one
-@@ -1765,7 +1764,7 @@ nsresult nsCharsetMenu::ReorderMenuItemA
+@@ -1772,7 +1771,7 @@ nsresult nsCharsetMenu::ReorderMenuItemA
  nsresult nsCharsetMenu::ReorderMenuItemArray(nsVoidArray * aArray)
  {
    nsresult res = NS_OK;
 -  nsCOMPtr<nsICollation> collation;
 +  nsICollation* collation = nsnull;
    PRUint32 count = aArray->Count();
    PRUint32 i;
  
-@@ -1775,7 +1774,7 @@ nsresult nsCharsetMenu::ReorderMenuItemA
+@@ -1782,7 +1781,7 @@ nsresult nsCharsetMenu::ReorderMenuItemA
    for (i = 0; i < count; i++)
      array[i].key = nsnull;
  
 -  res = GetCollation(getter_AddRefs(collation));
 +  res = GetCollation(&collation);
    if (NS_FAILED(res))
      goto done;
  
-@@ -1808,14 +1807,14 @@ nsresult nsCharsetMenu::GetCollation(nsI
+@@ -1815,14 +1814,14 @@ nsresult nsCharsetMenu::GetCollation(nsI
  nsresult nsCharsetMenu::GetCollation(nsICollation ** aCollation)
  {
    nsresult res = NS_OK;
 -  nsCOMPtr<nsILocale> locale = nsnull;
 +  nsILocale* locale = nsnull;
    nsICollationFactory * collationFactory = nsnull;
    
 -  nsCOMPtr<nsILocaleService> localeServ = 
--- a/gfx-refcounting
+++ b/gfx-refcounting
@@ -20,102 +20,94 @@ diff --git a/content/base/src/nsFrameLoa
  
 +#include "nsAutoPtr.h"
  #include "nsThreadUtils.h"
  
  class nsAsyncDocShellDestroyer : public nsRunnable
 diff --git a/content/canvas/src/nsCanvasRenderingContext2D.cpp b/content/canvas/src/nsCanvasRenderingContext2D.cpp
 --- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
 +++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
-@@ -105,6 +105,8 @@
+@@ -106,6 +106,8 @@
  #include "gfxTextRunCache.h"
  
  #include "nsFrameManager.h"
 +
 +using namespace mozilla;
  
  #ifndef M_PI
  #define M_PI		3.14159265358979323846
-@@ -346,15 +348,15 @@ protected:
+@@ -384,8 +386,8 @@ protected:
      nsCOMPtr<nsICSSParser> mCSSParser;
  
      // yay cairo
 -    nsRefPtr<gfxContext> mThebesContext;
 -    nsRefPtr<gfxASurface> mThebesSurface;
 +    RefPtr<gfxContext> mThebesContext;
 +    RefPtr<gfxASurface> mThebesSurface;
  
      PRUint32 mSaveCount;
      cairo_t *mCairo;
-     cairo_surface_t *mSurface;
- 
-     nsString mTextStyle;
--    nsRefPtr<gfxFontGroup> mFontGroup;
-+    RefPtr<gfxFontGroup> mFontGroup;
-     gfxFontGroup *GetCurrentFontStyle();
-  
-     // style handling
-@@ -771,7 +773,7 @@ nsCanvasRenderingContext2D::Render(gfxCo
+@@ -853,7 +855,7 @@ nsCanvasRenderingContext2D::Render(gfxCo
      if (!mThebesSurface)
          return NS_ERROR_FAILURE;
  
 -    nsRefPtr<gfxPattern> pat = new gfxPattern(mThebesSurface);
 +    RefPtr<gfxPattern> pat = new gfxPattern(mThebesSurface);
  
      gfxContext::GraphicsOperator op = ctx->CurrentOperator();
      if (mOpaque)
-@@ -1683,7 +1685,7 @@ nsCanvasRenderingContext2D::MozTextAlong
+@@ -2188,7 +2190,7 @@ nsCanvasRenderingContext2D::MozTextAlong
  nsCanvasRenderingContext2D::MozTextAlongPath(const nsAString& textToDraw, PRBool stroke)
  {
      // Most of this code is copied from its svg equivalent
 -    nsRefPtr<gfxFlattenedPath> path(mThebesContext->GetFlattenedPath());
 +    RefPtr<gfxFlattenedPath> path(mThebesContext->GetFlattenedPath());
  
      const PRUnichar* textdata;
      textToDraw.GetData(&textdata);
-@@ -2236,7 +2238,7 @@ nsCanvasRenderingContext2D::CairoSurface
+@@ -2745,7 +2747,7 @@ nsCanvasRenderingContext2D::CairoSurface
              rv = canvas->GetSize(&w, &h);
              NS_ENSURE_SUCCESS(rv, rv);
  
 -            nsRefPtr<gfxASurface> sourceSurface;
 +            RefPtr<gfxASurface> sourceSurface;
  
              if (!forceCopy && canvas->CountContexts() == 1) {
                  nsICanvasRenderingContextInternal *srcCanvas = canvas->GetContextAtIndex(0);
-@@ -2246,10 +2248,10 @@ nsCanvasRenderingContext2D::CairoSurface
+@@ -2755,10 +2757,10 @@ nsCanvasRenderingContext2D::CairoSurface
              }
  
              if (sourceSurface == nsnull) {
 -                nsRefPtr<gfxASurface> surf =
 +                RefPtr<gfxASurface> surf =
                      gfxPlatform::GetPlatform()->CreateOffscreenSurface
                      (gfxIntSize(w, h), gfxASurface::ImageFormatARGB32);
 -                nsRefPtr<gfxContext> ctx = new gfxContext(surf);
 +                RefPtr<gfxContext> ctx = new gfxContext(surf);
  
                  // we have to clear first, since some platform surfaces (X11, I'm
                  // looking at you) don't follow the cleared-surface convention.
-@@ -2298,13 +2300,13 @@ nsCanvasRenderingContext2D::CairoSurface
+@@ -2807,13 +2809,13 @@ nsCanvasRenderingContext2D::CairoSurface
      if (heightOut)
          *heightOut = imgHeight;
  
 -    nsRefPtr<gfxPattern> gfxpattern;
 +    RefPtr<gfxPattern> gfxpattern;
      img->GetPattern(getter_AddRefs(gfxpattern));
 -    nsRefPtr<gfxASurface> gfxsurf = gfxpattern->GetSurface();
 +    RefPtr<gfxASurface> gfxsurf = gfxpattern->GetSurface();
  
      if (!gfxsurf) {
          gfxsurf = new gfxImageSurface (gfxIntSize(imgWidth, imgHeight), gfxASurface::ImageFormatARGB32);
 -        nsRefPtr<gfxContext> ctx = new gfxContext(gfxsurf);
 +        RefPtr<gfxContext> ctx = new gfxContext(gfxsurf);
  
          ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
          ctx->SetPattern(gfxpattern);
-@@ -2704,9 +2706,7 @@ nsCanvasRenderingContext2D::GetThebesSur
+@@ -3213,9 +3215,7 @@ nsCanvasRenderingContext2D::GetThebesSur
          return NS_ERROR_NOT_AVAILABLE;
      }
  
 -    *surface = mThebesSurface.get();
 -    NS_ADDREF(*surface);
 -
 +    *surface = do_AddRef(mThebesSurface).get();
      return NS_OK;
@@ -130,121 +122,121 @@ diff --git a/content/events/src/nsEventL
  #include "nsCOMPtr.h"
 +#include "nsAutoPtr.h"
  #include "nsIDOMEventTarget.h"
  #include "nsIDOM3EventTarget.h"
  #include "nsHashtable.h"
 diff --git a/content/svg/content/src/nsSVGFilters.cpp b/content/svg/content/src/nsSVGFilters.cpp
 --- a/content/svg/content/src/nsSVGFilters.cpp
 +++ b/content/svg/content/src/nsSVGFilters.cpp
-@@ -74,6 +74,8 @@
+@@ -73,6 +73,8 @@
  #undef LoadImage
  #endif
  
 +using namespace mozilla;
 +
  //--------------------Filter Resource-----------------------
  /**
    * nsSVGFilterResource provides functionality for managing images used by
-@@ -175,7 +177,7 @@ private:
+@@ -171,7 +173,7 @@ private:
  
    nsAutoString mInput, mResult;
    nsRect mSourceRegion, mFilterSubregion, mSurfaceRect;
 -  nsRefPtr<gfxImageSurface> mTargetImage;
 +  RefPtr<gfxImageSurface> mTargetImage;
    nsSVGFE *mFilter;
    nsSVGFilterInstance* mInstance;
    PRUint8 *mSourceData, *mTargetData;
-@@ -233,7 +235,7 @@ nsSVGFilterResource::AcquireSourceImage(
+@@ -227,7 +229,7 @@ nsSVGFilterResource::AcquireSourceImage(
  {
-   aIn->GetAnimVal(mInput);
+   mInput = aIn->GetAnimValue();
  
 -  nsRefPtr<gfxImageSurface> surface;
 +  RefPtr<gfxImageSurface> surface;
    mInstance->LookupImage(mInput, getter_AddRefs(surface),
                           &mSourceRegion,
                           mFilter->GetColorModel(mInstance, aIn));
-@@ -244,8 +246,7 @@ nsSVGFilterResource::AcquireSourceImage(
+@@ -238,8 +240,7 @@ nsSVGFilterResource::AcquireSourceImage(
    mSourceData = surface->Data();
    *aSourceData = mSourceData;
    if (aSurface) {
 -    *aSurface = nsnull;
 -    surface.swap(*aSurface);
 +    *aSurface = surface.forget().get();
    }
    return NS_OK;
  }
-@@ -266,7 +267,7 @@ nsSVGFilterResource::AcquireTargetImage(
+@@ -259,7 +260,7 @@ nsSVGFilterResource::AcquireTargetImage(
    *aTargetData = mTargetData;
    if (aSurface) {
      *aSurface = mTargetImage;
 -    NS_ADDREF(*aSurface);
 +    mTargetImage->AddReference();
    }
    return NS_OK;
  }
-@@ -1683,7 +1684,7 @@ nsSVGFECompositeElement::Filter(nsSVGFil
+@@ -1576,7 +1577,7 @@ nsSVGFECompositeElement::Filter(nsSVGFil
  {
    nsresult rv;
    PRUint8 *sourceData, *targetData;
 -  nsRefPtr<gfxImageSurface> sourceSurface, targetSurface;
 +  RefPtr<gfxImageSurface> sourceSurface, targetSurface;
    nsSVGFilterResource fr(this, instance);
  
-   rv = fr.AcquireSourceImage(mIn2, &sourceData, getter_AddRefs(sourceSurface));
-@@ -2509,7 +2510,7 @@ nsSVGFEMergeElement::Filter(nsSVGFilterI
+   rv = fr.AcquireSourceImage(&mStringAttributes[IN2], &sourceData,
+@@ -2416,7 +2417,7 @@ nsSVGFEMergeElement::Filter(nsSVGFilterI
  {
    nsresult rv;
    PRUint8 *sourceData, *targetData;
 -  nsRefPtr<gfxImageSurface> sourceSurface, targetSurface;
 +  RefPtr<gfxImageSurface> sourceSurface, targetSurface;
    nsSVGFilterResource fr(this, instance);
  
-   rv = fr.AcquireTargetImage(mResult, &targetData,
-@@ -2754,7 +2755,7 @@ nsSVGFEOffsetElement::Filter(nsSVGFilter
+   rv = fr.AcquireTargetImage(&targetData, getter_AddRefs(targetSurface));
+@@ -2654,7 +2655,7 @@ nsSVGFEOffsetElement::Filter(nsSVGFilter
  {
    nsresult rv;
    PRUint8 *sourceData, *targetData;
 -  nsRefPtr<gfxImageSurface> sourceSurface, targetSurface;
 +  RefPtr<gfxImageSurface> sourceSurface, targetSurface;
    nsSVGFilterResource fr(this, instance);
  
-   rv = fr.AcquireSourceImage(mIn1, &sourceData, getter_AddRefs(sourceSurface));
-@@ -2888,7 +2889,7 @@ nsSVGFEFloodElement::Filter(nsSVGFilterI
+   rv = fr.AcquireSourceImage(&mStringAttributes[IN1], &sourceData,
+@@ -2808,7 +2809,7 @@ nsSVGFEFloodElement::Filter(nsSVGFilterI
  {
    nsresult rv;
    PRUint8 *targetData;
 -  nsRefPtr<gfxImageSurface> targetSurface;
 +  RefPtr<gfxImageSurface> targetSurface;
    nsSVGFilterResource fr(this, instance);
  
-   rv = fr.AcquireTargetImage(mResult, &targetData,
-@@ -5596,7 +5597,7 @@ nsSVGFEImageElement::Filter(nsSVGFilterI
+   rv = fr.AcquireTargetImage(&targetData, getter_AddRefs(targetSurface));
+@@ -5461,7 +5462,7 @@ nsSVGFEImageElement::Filter(nsSVGFilterI
  {
    nsresult rv;
    PRUint8 *targetData;
 -  nsRefPtr<gfxImageSurface> targetSurface;
 +  RefPtr<gfxImageSurface> targetSurface;
  
    nsSVGFilterResource fr(this, instance);
  
-@@ -5622,7 +5623,7 @@ nsSVGFEImageElement::Filter(nsSVGFilterI
+@@ -5486,7 +5487,7 @@ nsSVGFEImageElement::Filter(nsSVGFilterI
    if (imageContainer)
      imageContainer->GetCurrentFrame(getter_AddRefs(currentFrame));
  
 -  nsRefPtr<gfxPattern> thebesPattern = nsnull;
 +  RefPtr<gfxPattern> thebesPattern = nsnull;
    if (currentFrame) {
      nsCOMPtr<nsIImage> img(do_GetInterface(currentFrame));
  
 diff --git a/content/svg/content/src/nsSVGFilters.h b/content/svg/content/src/nsSVGFilters.h
 --- a/content/svg/content/src/nsSVGFilters.h
 +++ b/content/svg/content/src/nsSVGFilters.h
-@@ -60,10 +60,10 @@ protected:
-   nsresult Init();
+@@ -59,10 +59,10 @@ protected:
+   nsSVGFE(nsINodeInfo *aNodeInfo) : nsSVGFEBase(aNodeInfo) {}
  
    struct ScaleInfo {
 -    nsRefPtr<gfxImageSurface> mRealSource;
 -    nsRefPtr<gfxImageSurface> mRealTarget;
 -    nsRefPtr<gfxImageSurface> mSource;
 -    nsRefPtr<gfxImageSurface> mTarget;
 +    mozilla::RefPtr<gfxImageSurface> mRealSource;
 +    mozilla::RefPtr<gfxImageSurface> mRealTarget;
@@ -591,47 +583,47 @@ diff --git a/gfx/thebes/public/gfxAlphaR
 +                                                            gfxImageSurface *whiteSurface,
 +                                                            gfxIntSize dimensions);
  };
  
  #endif /* _GFXALPHARECOVERY_H_ */
 diff --git a/gfx/thebes/public/gfxAtsuiFonts.h b/gfx/thebes/public/gfxAtsuiFonts.h
 --- a/gfx/thebes/public/gfxAtsuiFonts.h
 +++ b/gfx/thebes/public/gfxAtsuiFonts.h
-@@ -91,7 +91,7 @@ protected:
+@@ -92,7 +92,7 @@ protected:
  
      ATSUStyle mATSUStyle;
  
 -    nsRefPtr<MacOSFontEntry> mFontEntry;
 +    RefPtr<MacOSFontEntry> mFontEntry;
  
+     PRBool mValid;
      PRBool mHasMirroring;
-     PRBool mHasMirroringLookedUp;
-@@ -138,7 +138,7 @@ public:
+@@ -140,7 +140,7 @@ public:
  
      PRBool HasFont(ATSUFontID fid);
  
 -    inline gfxAtsuiFont* WhichFontSupportsChar(nsTArray< nsRefPtr<gfxFont> >& aFontList, PRUint32 aCh) {
 +    inline gfxAtsuiFont* WhichFontSupportsChar(nsTArray< RefPtr<gfxFont> >& aFontList, PRUint32 aCh) {
          PRUint32 len = aFontList.Length();
          for (PRUint32 i = 0; i < len; i++) {
              gfxAtsuiFont* font = static_cast<gfxAtsuiFont*>(aFontList.ElementAt(i).get());
-@@ -149,9 +149,9 @@ public:
+@@ -151,9 +151,9 @@ public:
      }
  
     // search through pref fonts for a character, return nsnull if no matching pref font
 -   already_AddRefed<gfxAtsuiFont> WhichPrefFontSupportsChar(PRUint32 aCh);
 +   AddRefed<gfxAtsuiFont> WhichPrefFontSupportsChar(PRUint32 aCh);
     
 -   already_AddRefed<gfxAtsuiFont> FindFontForChar(PRUint32 aCh, PRUint32 aPrevCh, PRUint32 aNextCh, gfxAtsuiFont* aPrevMatchedFont);
 +   AddRefed<gfxAtsuiFont> FindFontForChar(PRUint32 aCh, PRUint32 aPrevCh, PRUint32 aNextCh, gfxAtsuiFont* aPrevMatchedFont);
  
  protected:
      static PRBool FindATSUFont(const nsAString& aName,
-@@ -183,8 +183,8 @@ protected:
+@@ -185,8 +185,8 @@ protected:
                         PRUint32 aOffsetInTextRun, PRUint32 aLengthInTextRun);
      
      // cache the most recent pref font to avoid general pref font lookup
 -    nsRefPtr<MacOSFamilyEntry>    mLastPrefFamily;
 -    nsRefPtr<gfxAtsuiFont>        mLastPrefFont;
 +    RefPtr<MacOSFamilyEntry>   mLastPrefFamily;
 +    RefPtr<gfxAtsuiFont>       mLastPrefFont;
      eFontPrefLang                 mLastPrefLang;       // lang group for last pref font
@@ -892,20 +884,20 @@ diff --git a/gfx/thebes/public/gfxPlatfo
          return (gfxPlatformMac*) gfxPlatform::GetPlatform();
      }
  
 -    already_AddRefed<gfxASurface> CreateOffscreenSurface(const gfxIntSize& size,
 -                                                         gfxASurface::gfxImageFormat imageFormat);
 +    AddRefed<gfxASurface> CreateOffscreenSurface(const gfxIntSize& size,
 +                                                           gfxASurface::gfxImageFormat imageFormat);
  
--    already_AddRefed<gfxASurface> gfxPlatformMac::OptimizeImage(gfxImageSurface *aSurface,
--                                                                gfxASurface::gfxImageFormat format);
-+    AddRefed<gfxASurface> gfxPlatformMac::OptimizeImage(gfxImageSurface *aSurface,
-+                                                                  gfxASurface::gfxImageFormat format);
+-    already_AddRefed<gfxASurface> OptimizeImage(gfxImageSurface *aSurface,
+-                                                gfxASurface::gfxImageFormat format);
++    AddRefed<gfxASurface> OptimizeImage(gfxImageSurface *aSurface,
++                                        gfxASurface::gfxImageFormat format);
  
      nsresult ResolveFontName(const nsAString& aFontName,
                               FontResolverCallback aCallback,
 diff --git a/gfx/thebes/public/gfxQuartzImageSurface.h b/gfx/thebes/public/gfxQuartzImageSurface.h
 --- a/gfx/thebes/public/gfxQuartzImageSurface.h
 +++ b/gfx/thebes/public/gfxQuartzImageSurface.h
 @@ -48,7 +48,7 @@ public:
  
@@ -1108,17 +1100,17 @@ diff --git a/gfx/thebes/public/gfxWindow
 +                                                        const gfxIntSize& size,
 +                                                        gfxImageFormat format);
  
      nsresult BeginPrinting(const nsAString& aTitle, const nsAString& aPrintToFileName);
      nsresult EndPrinting();
 diff --git a/gfx/thebes/public/gfxXlibNativeRenderer.h b/gfx/thebes/public/gfxXlibNativeRenderer.h
 --- a/gfx/thebes/public/gfxXlibNativeRenderer.h
 +++ b/gfx/thebes/public/gfxXlibNativeRenderer.h
-@@ -87,7 +87,7 @@ public:
+@@ -89,7 +89,7 @@ public:
      };
  
      struct DrawOutput {
 -        nsRefPtr<gfxASurface> mSurface;
 +        mozilla::RefPtr<gfxASurface> mSurface;
          PRPackedBool mUniformAlpha;
          PRPackedBool mUniformColor;
          gfxRGBA      mColor;
@@ -1258,161 +1250,167 @@ diff --git a/gfx/thebes/src/gfxAlphaReco
 -    return resultSurf.get();
 +    return resultSurf.forget();
  }
  
  /** from cairo-xlib-utils.c, modified */
 diff --git a/gfx/thebes/src/gfxAtsuiFonts.cpp b/gfx/thebes/src/gfxAtsuiFonts.cpp
 --- a/gfx/thebes/src/gfxAtsuiFonts.cpp
 +++ b/gfx/thebes/src/gfxAtsuiFonts.cpp
-@@ -430,20 +430,19 @@ gfxAtsuiFont::GetFontEntry()
+@@ -440,25 +440,24 @@ gfxAtsuiFont::GetFontEntry()
   * except for OOM in which case we do nothing and return null.
   */
   
 -static already_AddRefed<gfxAtsuiFont>
 +static AddRefed<gfxAtsuiFont>
  GetOrMakeFont(MacOSFontEntry *aFontEntry, const gfxFontStyle *aStyle, PRBool aNeedsBold)
  {
      // the font entry name is the psname, not the family name
 -    nsRefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(aFontEntry->Name(), aStyle);
 +    RefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(aFontEntry->Name(), aStyle);
      if (!font) {
-         font = new gfxAtsuiFont(aFontEntry, aStyle, aNeedsBold);
-         if (!font)
+         gfxAtsuiFont *newFont = new gfxAtsuiFont(aFontEntry, aStyle, aNeedsBold);
+         if (!newFont)
 -            return nsnull;
 +            return AddRefed<gfxAtsuiFont>(nsnull);
+         if (!newFont->Valid()) {
+             delete newFont;
+-            return nsnull;
++            return AddRefed<gfxAtsuiFont>(nsnull);
+         }
+         font = newFont;
          gfxFontCache::GetCache()->AddNew(font);
      }
 -    gfxFont *f = nsnull;
 -    font.swap(f);
 -    return static_cast<gfxAtsuiFont *>(f);
 +
 +    return AddRefed<gfxAtsuiFont>(static_cast<gfxAtsuiFont*>(font.forget().get()));
  }
  
  gfxAtsuiFontGroup::gfxAtsuiFontGroup(const nsAString& families,
-@@ -469,7 +468,7 @@ gfxAtsuiFontGroup::gfxAtsuiFontGroup(con
+@@ -484,7 +483,7 @@ gfxAtsuiFontGroup::gfxAtsuiFontGroup(con
          MacOSFontEntry *defaultFont = gfxQuartzFontCache::SharedFontCache()->GetDefaultFont(aStyle, needsBold);
          NS_ASSERTION(defaultFont, "invalid default font returned by GetDefaultFont");
  
 -        nsRefPtr<gfxAtsuiFont> font = GetOrMakeFont(defaultFont, aStyle, needsBold);
 +        RefPtr<gfxAtsuiFont> font = GetOrMakeFont(defaultFont, aStyle, needsBold);
  
          if (font) {
              mFonts.AppendElement(font);
-@@ -505,7 +504,7 @@ gfxAtsuiFontGroup::FindATSUFont(const ns
+@@ -520,7 +519,7 @@ gfxAtsuiFontGroup::FindATSUFont(const ns
      MacOSFontEntry *fe = fc->FindFontForFamily(aName, fontStyle, needsBold);
  
      if (fe && !fontGroup->HasFont(fe->GetFontID())) {
 -        nsRefPtr<gfxAtsuiFont> font = GetOrMakeFont(fe, fontStyle, needsBold);
 +        RefPtr<gfxAtsuiFont> font = GetOrMakeFont(fe, fontStyle, needsBold);
          if (font) {
              fontGroup->mFonts.AppendElement(font);
          }
-@@ -755,11 +754,11 @@ gfxAtsuiFontGroup::HasFont(ATSUFontID fi
+@@ -770,11 +769,11 @@ gfxAtsuiFontGroup::HasFont(ATSUFontID fi
  }
  
  struct PrefFontCallbackData {
 -    PrefFontCallbackData(nsTArray<nsRefPtr<MacOSFamilyEntry> >& aFamiliesArray) 
 +    PrefFontCallbackData(nsTArray<RefPtr<MacOSFamilyEntry> >& aFamiliesArray) 
          : mPrefFamilies(aFamiliesArray)
      {}
  
 -    nsTArray<nsRefPtr<MacOSFamilyEntry> >& mPrefFamilies;
 +    nsTArray<RefPtr<MacOSFamilyEntry> >& mPrefFamilies;
  
      static PRBool AddFontFamilyEntry(eFontPrefLang aLang, const nsAString& aName, void *aClosure)
      {
-@@ -774,12 +773,12 @@ struct PrefFontCallbackData {
+@@ -789,12 +788,12 @@ struct PrefFontCallbackData {
  };
  
  
 -already_AddRefed<gfxAtsuiFont>
 +AddRefed<gfxAtsuiFont>
  gfxAtsuiFontGroup::WhichPrefFontSupportsChar(PRUint32 aCh)
  {
      // FindCharUnicodeRange only supports BMP character points and there are no non-BMP fonts in prefs
      if (aCh > 0xFFFF)
 -        return nsnull;
 +        return AddRefed<gfxAtsuiFont>(nsnull);
  
      // get the pref font list if it hasn't been set up already
      PRUint32 unicodeRange = FindCharUnicodeRange(aCh);
-@@ -787,7 +786,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
+@@ -802,7 +801,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
  
      // if the last pref font was the first family in the pref list, no need to recheck through a list of families
      if (mLastPrefFont && charLang == mLastPrefLang && mLastPrefFirstFont && mLastPrefFont->TestCharacterMap(aCh)) {
 -        nsRefPtr<gfxAtsuiFont> prefFont = mLastPrefFont;
 +        RefPtr<gfxAtsuiFont> prefFont = mLastPrefFont;
          return prefFont.forget();
      }
      
-@@ -799,7 +798,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
+@@ -814,7 +813,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
      macPlatform->GetLangPrefs(prefLangs, numLangs, charLang, mPageLang);
      
      for (i = 0; i < numLangs; i++) {
 -        nsAutoTArray<nsRefPtr<MacOSFamilyEntry>, 5> families;
 +        nsAutoTArray<RefPtr<MacOSFamilyEntry>, 5> families;
          eFontPrefLang currentLang = prefLangs[i];
          
          gfxQuartzFontCache *fc = gfxQuartzFontCache::SharedFontCache();
-@@ -826,7 +825,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
+@@ -841,7 +840,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
              // GetOrMakeFont repeatedly.  speeds up FindFontForChar lookup times for subsequent
              // pref font lookups
              if (family == mLastPrefFamily && mLastPrefFont->TestCharacterMap(aCh)) {
 -                nsRefPtr<gfxAtsuiFont> prefFont = mLastPrefFont;
 +                RefPtr<gfxAtsuiFont> prefFont = mLastPrefFont;
                  return prefFont.forget();
              }
              
-@@ -834,7 +833,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
+@@ -849,7 +848,7 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
              MacOSFontEntry *fe = family->FindFont(&mStyle, needsBold);
              // if ch in cmap, create and return a gfxFont
              if (fe && fe->TestCharacterMap(aCh)) {
 -                nsRefPtr<gfxAtsuiFont> prefFont = GetOrMakeFont(fe, &mStyle, needsBold);
 +                RefPtr<gfxAtsuiFont> prefFont = GetOrMakeFont(fe, &mStyle, needsBold);
+                 if (!prefFont) continue;
                  mLastPrefFamily = family;
                  mLastPrefFont = prefFont;
-                 mLastPrefLang = charLang;
-@@ -845,13 +844,13 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
+@@ -861,13 +860,13 @@ gfxAtsuiFontGroup::WhichPrefFontSupports
          }
      }
      
 -    return nsnull;
 +    return AddRefed<gfxAtsuiFont>(nsnull);
  }
  
 -already_AddRefed<gfxAtsuiFont>
 +AddRefed<gfxAtsuiFont>
  gfxAtsuiFontGroup::FindFontForChar(PRUint32 aCh, PRUint32 aPrevCh, PRUint32 aNextCh, gfxAtsuiFont* aPrevMatchedFont)
  {
 -    nsRefPtr<gfxAtsuiFont>    selectedFont;
 +    RefPtr<gfxAtsuiFont>    selectedFont;
      
      // if this character or the next one is a joiner use the
      // same font as the previous range if we can
-@@ -896,7 +895,7 @@ gfxAtsuiFontGroup::FindFontForChar(PRUin
+@@ -912,7 +911,7 @@ gfxAtsuiFontGroup::FindFontForChar(PRUin
          }
      }
  
 -    return nsnull;
 +    return AddRefed<gfxAtsuiFont>(nsnull);
  }
  
  /**
-@@ -1354,7 +1353,7 @@ public:
+@@ -1370,7 +1369,7 @@ public:
      PRUint32 MatchNextRange() 
      { 
          PRUint32                matchStartOffset, chStartOffset, ch, nextCh;
 -        nsRefPtr<gfxAtsuiFont>  font;
 +        RefPtr<gfxAtsuiFont>  font;
          
          matchStartOffset = mPrevOffset;
  
-@@ -1413,8 +1412,8 @@ private:
+@@ -1429,8 +1428,8 @@ private:
      PRUint32                mPrevCh;
      PRBool                  mFirstRange;
      gfxAtsuiFontGroup       *mFontGroup;
 -    nsRefPtr<gfxAtsuiFont>  mMatchedFont;
 -    nsRefPtr<gfxAtsuiFont>  mNextMatchedFont;
 +    RefPtr<gfxAtsuiFont> mMatchedFont;
 +    RefPtr<gfxAtsuiFont> mNextMatchedFont;
  };
@@ -1618,18 +1616,18 @@ diff --git a/gfx/thebes/src/gfxImageSurf
 +++ b/gfx/thebes/src/gfxImageSurface.cpp
 @@ -40,6 +40,8 @@
  #include "gfxImageSurface.h"
  
  #include "cairo.h"
 +
 +#include <string.h>
  
- gfxImageSurface::gfxImageSurface(const gfxIntSize& size, gfxImageFormat format) :
-     mSize(size), mFormat(format)
+ gfxImageSurface::gfxImageSurface(unsigned char *aData, const gfxIntSize& aSize,
+                                  long aStride, gfxImageFormat aFormat)
 diff --git a/gfx/thebes/src/gfxOS2Fonts.cpp b/gfx/thebes/src/gfxOS2Fonts.cpp
 --- a/gfx/thebes/src/gfxOS2Fonts.cpp
 +++ b/gfx/thebes/src/gfxOS2Fonts.cpp
 @@ -424,10 +424,10 @@ PRBool gfxOS2Font::SetupCairoFont(gfxCon
   * In either case, add a ref and return it ---
   * except for OOM in which case we do nothing and return null.
   */
 -static already_AddRefed<gfxOS2Font> GetOrMakeFont(const nsAString& aName,
@@ -1736,17 +1734,17 @@ diff --git a/gfx/thebes/src/gfxPangoFont
          // be the PangoFont that fontconfig chooses for this style.
      }
 -    NS_ADDREF(font);
 -    return font;
 +    return do_AddRef(font);
  }
  
  static PangoFont*
-@@ -1655,7 +1654,7 @@ gfxPangoFontGroup::CreateGlyphRunsItemiz
+@@ -1657,7 +1656,7 @@ gfxPangoFontGroup::CreateGlyphRunsItemiz
          }
  
          /* look up the gfxPangoFont from the PangoFont */
 -        nsRefPtr<gfxPangoFont> font =
 +        RefPtr<gfxPangoFont> font =
              gfxPangoFont::GetOrMakeFont(item->analysis.font);
  
          nsresult rv = aTextRun->AddGlyphRun(font, utf16Offset, PR_TRUE);
@@ -2648,18 +2646,18 @@ diff --git a/gfx/thebes/src/gfxXlibNativ
 +++ b/gfx/thebes/src/gfxXlibNativeRenderer.cpp
 @@ -39,6 +39,8 @@
  #include "gfxContext.h"
  
  #include "cairo-xlib-utils.h"
 +
 +using namespace mozilla;
  
- typedef struct {
-     gfxXlibNativeRenderer* mRenderer;
+ #ifdef MOZ_WIDGET_GTK2
+ #include <gdk/gdkscreen.h>
 diff --git a/gfx/thebes/test/gfxFontSelectionTest.cpp b/gfx/thebes/test/gfxFontSelectionTest.cpp
 --- a/gfx/thebes/test/gfxFontSelectionTest.cpp
 +++ b/gfx/thebes/test/gfxFontSelectionTest.cpp
 @@ -58,6 +58,8 @@
  #ifdef MOZ_WIDGET_GTK2
  #include "gtk/gtk.h"
  #endif
 +
@@ -2847,26 +2845,26 @@ diff --git a/gfx/thebes/test/gfxWordCach
 -       nsRefPtr<gfxFontGroup> fontGroup =
 +       RefPtr<gfxFontGroup> fontGroup =
             gfxPlatform::GetPlatform()->CreateFontGroup(NS_LITERAL_STRING("Geneva, MS Sans Serif, Helvetica,serif"), &style);
  
         gfxTextRunFactory::Parameters params = {
 diff --git a/layout/base/nsCSSRendering.cpp b/layout/base/nsCSSRendering.cpp
 --- a/layout/base/nsCSSRendering.cpp
 +++ b/layout/base/nsCSSRendering.cpp
-@@ -74,6 +74,8 @@
+@@ -75,6 +75,8 @@
  
  #include "gfxContext.h"
  
 +using namespace mozilla;
 +
  #define BORDER_FULL    0        //entire side
  #define BORDER_INSIDE  1        //inside half
  #define BORDER_OUTSIDE 2        //outside half
-@@ -4562,7 +4564,7 @@ nsCSSRendering::PaintDecorationLine(gfxC
+@@ -4595,7 +4597,7 @@ nsCSSRendering::PaintDecorationLine(gfxC
    PRBool contextIsSaved = PR_FALSE;
  
    gfxFloat oldLineWidth;
 -  nsRefPtr<gfxPattern> oldPattern;
 +  RefPtr<gfxPattern> oldPattern;
  
    switch (aStyle) {
      case NS_STYLE_BORDER_STYLE_SOLID:
@@ -2877,52 +2875,43 @@ diff --git a/layout/base/nsDisplayList.c
  #include "nsRegion.h"
  #include "nsFrameManager.h"
  #include "gfxContext.h"
 +
 +using namespace mozilla;
  
  nsDisplayListBuilder::nsDisplayListBuilder(nsIFrame* aReferenceFrame,
      PRBool aIsForEvents, PRBool aBuildCaret)
-@@ -797,7 +799,7 @@ void nsDisplayOpacity::Paint(nsDisplayLi
-   aCtx->GetDeviceContext(*getter_AddRefs(devCtx));
-   float a2p = 1.0f / devCtx->AppUnitsPerDevPixel();
- 
--  nsRefPtr<gfxContext> ctx = aCtx->ThebesContext();
-+  RefPtr<gfxContext> ctx = aCtx->ThebesContext();
- 
-   ctx->Save();
- 
 diff --git a/layout/base/nsIPresShell.h b/layout/base/nsIPresShell.h
 --- a/layout/base/nsIPresShell.h
 +++ b/layout/base/nsIPresShell.h
 @@ -64,6 +64,7 @@
  #include "mozFlushType.h"
  #include "nsWeakReference.h"
  #include <stdio.h> // for FILE definition
 +#include "gfxASurface.h"
  
  class nsIAtom;
  class nsIContent;
-@@ -743,10 +744,10 @@ public:
+@@ -746,10 +747,10 @@ public:
     * edge of the presshell area. The aPoint, aScreenRect and aSurface
     * arguments function in a similar manner as RenderSelection.
     */
 -  virtual already_AddRefed<gfxASurface> RenderNode(nsIDOMNode* aNode,
 -                                                   nsIRegion* aRegion,
 -                                                   nsPoint& aPoint,
 -                                                   nsRect* aScreenRect) = 0;
 +  virtual mozilla::AddRefed<gfxASurface> RenderNode(nsIDOMNode* aNode,
 +                                                    nsIRegion* aRegion,
 +                                                    nsPoint& aPoint,
 +                                                    nsRect* aScreenRect) = 0;
  
    /*
     * Renders a selection to a surface and returns it. This method is primarily
-@@ -763,9 +764,9 @@ public:
+@@ -766,9 +767,9 @@ public:
     * the original. When scaling does not occur, the mouse point isn't used
     * as the position can be determined from the displayed frames.
     */
 -  virtual already_AddRefed<gfxASurface> RenderSelection(nsISelection* aSelection,
 -                                                        nsPoint& aPoint,
 -                                                        nsRect* aScreenRect) = 0;
 +  virtual mozilla::AddRefed<gfxASurface> RenderSelection(nsISelection* aSelection,
 +                                                         nsPoint& aPoint,
@@ -2940,26 +2929,26 @@ diff --git a/layout/base/nsLayoutUtils.c
 +
 +using namespace mozilla;
  
  /**
   * A namespace class for static layout utilities.
 diff --git a/layout/base/nsPresShell.cpp b/layout/base/nsPresShell.cpp
 --- a/layout/base/nsPresShell.cpp
 +++ b/layout/base/nsPresShell.cpp
-@@ -204,6 +204,8 @@ static NS_DEFINE_CID(kCSSStyleSheetCID, 
+@@ -207,6 +207,8 @@ static NS_DEFINE_CID(kCSSStyleSheetCID, 
  static NS_DEFINE_CID(kCSSStyleSheetCID, NS_CSS_STYLESHEET_CID);
  static NS_DEFINE_IID(kRangeCID,     NS_RANGE_CID);
  
 +using namespace mozilla;
 +
  PRBool nsIPresShell::gIsAccessibilityActive = PR_FALSE;
  
  // convert a color value to a string, in the CSS format #RRGGBB
-@@ -884,14 +886,14 @@ public:
+@@ -887,14 +889,14 @@ public:
                              nscolor aBackgroundColor,
                              gfxContext* aThebesContext);
  
 -  virtual already_AddRefed<gfxASurface> RenderNode(nsIDOMNode* aNode,
 -                                                   nsIRegion* aRegion,
 -                                                   nsPoint& aPoint,
 -                                                   nsRect* aScreenRect);
 -
@@ -2972,106 +2961,106 @@ diff --git a/layout/base/nsPresShell.cpp
 +                                                     nsRect* aScreenRect);
 +
 +  virtual AddRefed<gfxASurface> RenderSelection(nsISelection* aSelection,
 +                                                          nsPoint& aPoint,
 +                                                          nsRect* aScreenRect);
  
    //nsIViewObserver interface
  
-@@ -1091,7 +1093,7 @@ protected:
+@@ -1094,7 +1096,7 @@ protected:
     * aScreenRect - [out] set to the area of the screen the painted area should
     *               be displayed at
     */
 -  already_AddRefed<gfxASurface>
 +  AddRefed<gfxASurface>
    PaintRangePaintInfo(nsTArray<nsAutoPtr<RangePaintInfo> >* aItems,
                        nsISelection* aSelection,
                        nsIRegion* aRegion,
-@@ -5177,7 +5179,7 @@ PresShell::CreateRangePaintInfo(nsIDOMRa
+@@ -5187,7 +5189,7 @@ PresShell::CreateRangePaintInfo(nsIDOMRa
    return info;
  }
  
 -already_AddRefed<gfxASurface>
 +AddRefed<gfxASurface>
  PresShell::PaintRangePaintInfo(nsTArray<nsAutoPtr<RangePaintInfo> >* aItems,
                                 nsISelection* aSelection,
                                 nsIRegion* aRegion,
-@@ -5187,7 +5189,7 @@ PresShell::PaintRangePaintInfo(nsTArray<
+@@ -5197,7 +5199,7 @@ PresShell::PaintRangePaintInfo(nsTArray<
  {
    nsPresContext* pc = GetPresContext();
    if (!pc || aArea.width == 0 || aArea.height == 0)
 -    return nsnull;
 +    return AddRefed<gfxASurface>(nsnull);
  
    nsIDeviceContext* deviceContext = pc->DeviceContext();
  
-@@ -5237,7 +5239,7 @@ PresShell::PaintRangePaintInfo(nsTArray<
+@@ -5247,7 +5249,7 @@ PresShell::PaintRangePaintInfo(nsTArray<
                          gfxImageSurface::ImageFormatARGB32);
    if (!surface || surface->CairoStatus()) {
      delete surface;
 -    return nsnull;
 +    return AddRefed<gfxASurface>(nsnull);
    }
  
    // clear the image
-@@ -5290,11 +5292,11 @@ PresShell::PaintRangePaintInfo(nsTArray<
+@@ -5300,11 +5302,11 @@ PresShell::PaintRangePaintInfo(nsTArray<
    // restore the old selection display state
    frameSelection->SetDisplaySelection(oldDisplaySelection);
  
 -  NS_ADDREF(surface);
 -  return surface;
 -}
 -
 -already_AddRefed<gfxASurface>
 +  surface->AddReference();
 +  return AddRefed<gfxASurface>(surface);
 +}
 +
 +AddRefed<gfxASurface>
  PresShell::RenderNode(nsIDOMNode* aNode,
                        nsIRegion* aRegion,
                        nsPoint& aPoint,
-@@ -5312,7 +5314,7 @@ PresShell::RenderNode(nsIDOMNode* aNode,
+@@ -5322,7 +5324,7 @@ PresShell::RenderNode(nsIDOMNode* aNode,
    RangePaintInfo* info = CreateRangePaintInfo(range, area);
    if (info && !rangeItems.AppendElement(info)) {
      delete info;
 -    return nsnull;
 +    return AddRefed<gfxASurface>(nsnull);
    }
  
    if (aRegion) {
-@@ -5327,7 +5329,7 @@ PresShell::RenderNode(nsIDOMNode* aNode,
+@@ -5337,7 +5339,7 @@ PresShell::RenderNode(nsIDOMNode* aNode,
      
      nsPresContext* pc = GetPresContext();
      if (!pc)
 -      return nsnull;
 +      return AddRefed<gfxASurface>(nsnull);
  
      // move the region so that it is offset from the topleft corner of the surface
      aRegion->Offset(-rrectPixels.x + (rrectPixels.x - pc->AppUnitsToDevPixels(area.x)),
-@@ -5338,7 +5340,7 @@ PresShell::RenderNode(nsIDOMNode* aNode,
+@@ -5348,7 +5350,7 @@ PresShell::RenderNode(nsIDOMNode* aNode,
                               aScreenRect);
  }
  
 -already_AddRefed<gfxASurface>
 +AddRefed<gfxASurface>
  PresShell::RenderSelection(nsISelection* aSelection,
                             nsPoint& aPoint,
                             nsRect* aScreenRect)
-@@ -5363,7 +5365,7 @@ PresShell::RenderSelection(nsISelection*
+@@ -5373,7 +5375,7 @@ PresShell::RenderSelection(nsISelection*
      RangePaintInfo* info = CreateRangePaintInfo(range, area);
      if (info && !rangeItems.AppendElement(info)) {
        delete info;
 -      return nsnull;
 +      return AddRefed<gfxASurface>(nsnull);
      }
    }
  
-@@ -7007,20 +7009,20 @@ DumpToPNG(nsIPresShell* shell, nsAString
+@@ -7047,20 +7049,20 @@ DumpToPNG(nsIPresShell* shell, nsAString
    nsRect r(0, 0, shell->GetPresContext()->DevPixelsToAppUnits(width),
                   shell->GetPresContext()->DevPixelsToAppUnits(height));
  
 -  nsRefPtr<gfxImageSurface> imgSurface =
 +  RefPtr<gfxImageSurface> imgSurface =
       new gfxImageSurface(gfxIntSize(width, height),
                           gfxImageSurface::ImageFormatARGB32);
    NS_ENSURE_TRUE(imgSurface, NS_ERROR_OUT_OF_MEMORY);
@@ -3114,83 +3103,83 @@ diff --git a/layout/generic/nsFrame.cpp 
 +
 +using namespace mozilla;
  
  static NS_DEFINE_CID(kLookAndFeelCID,  NS_LOOKANDFEEL_CID);
  static NS_DEFINE_CID(kWidgetCID, NS_CHILD_CID);
 diff --git a/layout/generic/nsHTMLContainerFrame.cpp b/layout/generic/nsHTMLContainerFrame.cpp
 --- a/layout/generic/nsHTMLContainerFrame.cpp
 +++ b/layout/generic/nsHTMLContainerFrame.cpp
-@@ -71,6 +71,8 @@
+@@ -72,6 +72,8 @@
  #include "nsLineBox.h"
  #include "nsDisplayList.h"
  #include "nsCSSRendering.h"
 +
 +using namespace mozilla;
  
  class nsDisplayTextDecoration : public nsDisplayItem {
  public:
 diff --git a/layout/generic/nsObjectFrame.cpp b/layout/generic/nsObjectFrame.cpp
 --- a/layout/generic/nsObjectFrame.cpp
 +++ b/layout/generic/nsObjectFrame.cpp
-@@ -1443,7 +1443,7 @@ nsObjectFrame::PaintPlugin(nsIRenderingC
+@@ -1436,7 +1436,7 @@ nsObjectFrame::PaintPlugin(nsIRenderingC
  
        /* Set the device offsets as appropriate, for whatever our current group offsets might be */
        gfxFloat xoff, yoff;
 -      nsRefPtr<gfxASurface> surf = ctx->CurrentSurface(&xoff, &yoff);
 +      RefPtr<gfxASurface> surf = ctx->CurrentSurface(&xoff, &yoff);
  
        if (surf->CairoStatus() != 0) {
          NS_WARNING("Plugin is being asked to render to a surface that's in error!");
 diff --git a/layout/generic/nsTextFrameThebes.cpp b/layout/generic/nsTextFrameThebes.cpp
 --- a/layout/generic/nsTextFrameThebes.cpp
 +++ b/layout/generic/nsTextFrameThebes.cpp
-@@ -116,6 +116,8 @@
- #include "gfxContext.h"
+@@ -118,6 +118,8 @@
  #include "gfxTextRunWordCache.h"
+ #include "gfxImageSurface.h"
  
 +using namespace mozilla;
 +
  #ifdef NS_DEBUG
  #undef NOISY_BLINK
  #undef NOISY_REFLOW
-@@ -1288,7 +1290,7 @@ GetFontGroupForFrame(nsIFrame* aFrame,
+@@ -1290,7 +1292,7 @@ GetFontGroupForFrame(nsIFrame* aFrame,
    return fm->GetThebesFontGroup();
  }
  
 -static already_AddRefed<gfxContext>
 +static AddRefed<gfxContext>
  GetReferenceRenderingContext(nsTextFrame* aTextFrame, nsIRenderingContext* aRC)
  {
    nsCOMPtr<nsIRenderingContext> tmp = aRC;
-@@ -1296,12 +1298,11 @@ GetReferenceRenderingContext(nsTextFrame
+@@ -1298,12 +1300,11 @@ GetReferenceRenderingContext(nsTextFrame
      nsresult rv = aTextFrame->PresContext()->PresShell()->
        CreateRenderingContext(aTextFrame, getter_AddRefs(tmp));
      if (NS_FAILED(rv))
 -      return nsnull;
 +      return AddRefed<gfxContext>(nsnull);
    }
  
    gfxContext* ctx = tmp->ThebesContext();
 -  NS_ADDREF(ctx);
 -  return ctx;
 +  return do_AddRef(ctx);
  }
  
  /**
-@@ -1311,7 +1312,7 @@ static gfxTextRun*
+@@ -1313,7 +1314,7 @@ static gfxTextRun*
  static gfxTextRun*
  GetHyphenTextRun(gfxTextRun* aTextRun, gfxContext* aContext, nsTextFrame* aTextFrame)
  {
 -  nsRefPtr<gfxContext> ctx = aContext;
 +  RefPtr<gfxContext> ctx = aContext;
    if (!ctx) {
      ctx = GetReferenceRenderingContext(aTextFrame, nsnull);
    }
-@@ -1783,7 +1784,7 @@ nsTextFrame::EnsureTextRun(gfxContext* a
+@@ -1785,7 +1786,7 @@ nsTextFrame::EnsureTextRun(gfxContext* a
        gTextRuns->MarkUsed(mTextRun);
      }
    } else {
 -    nsRefPtr<gfxContext> ctx = aReferenceContext;
 +    RefPtr<gfxContext> ctx = aReferenceContext;
      if (!ctx) {
        ctx = GetReferenceRenderingContext(this, nsnull);
      }
@@ -3252,53 +3241,53 @@ diff --git a/layout/svg/base/src/nsSVGFi
  #include "gfxASurface.h"
  #include "gfxContext.h"
  #include "gfxImageSurface.h"
 +
 +using namespace mozilla;
  
  nsIFrame*
  NS_NewSVGFilterFrame(nsIPresShell* aPresShell, nsIContent* aContent, nsStyleContext* aContext)
-@@ -446,7 +448,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
+@@ -444,7 +446,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
    if (!analysis.GetSourceColorAlphaNeeded().IsEmpty() ||
        !analysis.GetSourceAlphaNeeded().IsEmpty()) {
      // paint the target geometry
 -    nsRefPtr<gfxImageSurface> tmpSurface = instance.GetImage();
 +    RefPtr<gfxImageSurface> tmpSurface = instance.GetImage();
      if (!tmpSurface) {
        FilterFailCleanup(aContext, aTarget);
        return NS_OK;
-@@ -460,7 +462,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
+@@ -458,7 +460,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
      aTarget->PaintSVG(&tmpState, nsnull);
  
      if (!analysis.GetSourceAlphaNeeded().IsEmpty()) {
 -      nsRefPtr<gfxImageSurface> alpha = instance.GetImage();
 +      RefPtr<gfxImageSurface> alpha = instance.GetImage();
        if (!alpha) {
          FilterFailCleanup(aContext, aTarget);
          return NS_OK;
-@@ -494,7 +496,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
+@@ -492,7 +494,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
      // but we have to because all filter primitives currently need to
      // call AcquireSourceImage and find a source image, even if they don't
      // use it!
 -    nsRefPtr<gfxImageSurface> tmpSurface = instance.GetImage();
 +    RefPtr<gfxImageSurface> tmpSurface = instance.GetImage();
      if (!tmpSurface) {
        FilterFailCleanup(aContext, aTarget);
        return NS_OK;
-@@ -517,7 +519,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
+@@ -515,7 +517,7 @@ nsSVGFilterFrame::FilterPaint(nsSVGRende
    }
  
    nsRect filterRect;
 -  nsRefPtr<gfxImageSurface> filterSurface;
 +  RefPtr<gfxImageSurface> filterSurface;
  
    instance.LookupImage(NS_LITERAL_STRING(""),
                         getter_AddRefs(filterSurface), &filterRect, colorModel);
-@@ -734,15 +736,15 @@ nsSVGFilterInstance::GetFilterSubregion(
+@@ -732,15 +734,15 @@ nsSVGFilterInstance::GetFilterSubregion(
  #endif
  }
  
 -already_AddRefed<gfxImageSurface>
 +AddRefed<gfxImageSurface>
  nsSVGFilterInstance::GetImage()
  {
 -  nsRefPtr<gfxImageSurface> surface =
@@ -3307,28 +3296,28 @@ diff --git a/layout/svg/base/src/nsSVGFi
                          gfxASurface::ImageFormatARGB32);
  
    if (!surface || surface->CairoStatus()) {
 -    return nsnull;
 +    return AddRefed<gfxImageSurface>(nsnull);
    }
  
    surface->SetDeviceOffset(gfxPoint(-mSurfaceRect.x, -mSurfaceRect.y));
-@@ -752,9 +754,7 @@ nsSVGFilterInstance::GetImage()
+@@ -750,9 +752,7 @@ nsSVGFilterInstance::GetImage()
    ctx.SetOperator(gfxContext::OPERATOR_CLEAR);
    ctx.Paint();
  
 -  gfxImageSurface *retval = nsnull;
 -  surface.swap(retval);
 -  return retval;
 +  return surface.forget();
  }
  
  void
-@@ -775,7 +775,7 @@ nsSVGFilterInstance::LookupImage(const n
+@@ -773,7 +773,7 @@ nsSVGFilterInstance::LookupImage(const n
    }
  
    *aImage = entry->mImage;
 -  NS_ADDREF(*aImage);
 +  entry->mImage->AddReference();
    *aRegion = entry->mRegion;
  
    if (aRequiredColorModel == entry->mColorModel)
@@ -3444,64 +3433,64 @@ diff --git a/layout/svg/base/src/nsSVGGl
 -    nsRefPtr<gfxContext> tmpCtx = MakeTmpCtx();
 +    RefPtr<gfxContext> tmpCtx = MakeTmpCtx();
      tmpCtx->SetMatrix(m);
  
      // Use only the word cache here. We don't want to cache the textrun
 diff --git a/layout/svg/base/src/nsSVGGradientFrame.cpp b/layout/svg/base/src/nsSVGGradientFrame.cpp
 --- a/layout/svg/base/src/nsSVGGradientFrame.cpp
 +++ b/layout/svg/base/src/nsSVGGradientFrame.cpp
-@@ -49,6 +49,8 @@
+@@ -48,6 +48,8 @@
  #include "gfxContext.h"
  #include "nsIDOMSVGRect.h"
  #include "gfxPattern.h"
 +
 +using namespace mozilla;
  
  //----------------------------------------------------------------------
  // Implementation
-@@ -345,7 +347,7 @@ nsSVGGradientFrame::SetupPaintServer(gfx
+@@ -344,7 +346,7 @@ nsSVGGradientFrame::SetupPaintServer(gfx
  
    patternMatrix.Invert();
  
 -  nsRefPtr<gfxPattern> gradient = CreateGradient();
 +  RefPtr<gfxPattern> gradient = CreateGradient();
    if (!gradient || gradient->CairoStatus())
      return PR_FALSE;
  
-@@ -598,7 +600,7 @@ nsSVGLinearGradientFrame::GradientLookup
+@@ -597,7 +599,7 @@ nsSVGLinearGradientFrame::GradientLookup
      GetAnimValue(static_cast<nsSVGSVGElement*>(nsnull));
  }
  
 -already_AddRefed<gfxPattern>
 +AddRefed<gfxPattern>
  nsSVGLinearGradientFrame::CreateGradient()
  {
    float x1, y1, x2, y2;
-@@ -608,9 +610,7 @@ nsSVGLinearGradientFrame::CreateGradient
+@@ -607,9 +609,7 @@ nsSVGLinearGradientFrame::CreateGradient
    x2 = GradientLookupAttribute(nsGkAtoms::x2, nsSVGLinearGradientElement::X2);
    y2 = GradientLookupAttribute(nsGkAtoms::y2, nsSVGLinearGradientElement::Y2);
  
 -  gfxPattern *pattern = new gfxPattern(x1, y1, x2, y2);
 -  NS_IF_ADDREF(pattern);
 -  return pattern;
 +  return do_AddRef(new gfxPattern(x1, y1, x2, y2));
  }
  
  // -------------------------------------------------------------------------
-@@ -680,7 +680,7 @@ nsSVGRadialGradientFrame::GradientLookup
+@@ -679,7 +679,7 @@ nsSVGRadialGradientFrame::GradientLookup
      GetAnimValue(static_cast<nsSVGSVGElement*>(nsnull));
  }
  
 -already_AddRefed<gfxPattern>
 +AddRefed<gfxPattern>
  nsSVGRadialGradientFrame::CreateGradient()
  {
    float cx, cy, r, fx, fy;
-@@ -720,9 +720,7 @@ nsSVGRadialGradientFrame::CreateGradient
+@@ -719,9 +719,7 @@ nsSVGRadialGradientFrame::CreateGradient
      }
    }
  
 -  gfxPattern *pattern = new gfxPattern(fx, fy, 0, cx, cy, r);
 -  NS_IF_ADDREF(pattern);
 -  return pattern;
 +  return do_AddRef(new gfxPattern(fx, fy, 0, cx, cy, r));
  }
@@ -3544,17 +3533,17 @@ diff --git a/layout/svg/base/src/nsSVGIm
  #include "gfxContext.h"
  #include "nsIInterfaceRequestorUtils.h"
  #include "nsIImage.h"
 +
 +using namespace mozilla;
  
  class nsSVGImageFrame;
  
-@@ -257,7 +259,7 @@ nsSVGImageFrame::PaintSVG(nsSVGRenderSta
+@@ -252,7 +254,7 @@ nsSVGImageFrame::PaintSVG(nsSVGRenderSta
    if (mImageContainer)
      mImageContainer->GetCurrentFrame(getter_AddRefs(currentFrame));
  
 -  nsRefPtr<gfxPattern> thebesPattern = nsnull;
 +  RefPtr<gfxPattern> thebesPattern = nsnull;
    if (currentFrame) {
      nsCOMPtr<nsIImage> img(do_GetInterface(currentFrame));
  
@@ -3941,53 +3930,54 @@ diff --git a/view/src/nsViewManager.cpp 
 -    nsRefPtr<gfxContext> ctx = localcx->ThebesContext();
 +    RefPtr<gfxContext> ctx = localcx->ThebesContext();
  
      ctx->Save();
  
 diff --git a/widget/src/cocoa/nsChildView.h b/widget/src/cocoa/nsChildView.h
 --- a/widget/src/cocoa/nsChildView.h
 +++ b/widget/src/cocoa/nsChildView.h
-@@ -62,13 +62,13 @@
+@@ -61,13 +61,14 @@
+ #include "nsIEventListener.h"
  #include "nsString.h"
  #include "nsIDragService.h"
- #include "nsIMenuBar.h"
++#include "nsIMenuBar.h"
 +#include "gfxASurface.h"
  
  #include "nsplugindefs.h"
  
  #import <Carbon/Carbon.h>
  #import <Cocoa/Cocoa.h>
  
 -class gfxASurface;
  class nsChildView;
  union nsPluginPort;
  
-@@ -367,7 +367,7 @@ protected:
+@@ -405,7 +406,7 @@ protected:
    nsWeakPtr             mAccessible;
  #endif
  
 -  nsRefPtr<gfxASurface> mTempThebesSurface;
 +  RefPtr<gfxASurface> mTempThebesSurface;
  
    PRPackedBool          mVisible;
    PRPackedBool          mDrawing;
 diff --git a/widget/src/cocoa/nsChildView.mm b/widget/src/cocoa/nsChildView.mm
 --- a/widget/src/cocoa/nsChildView.mm
 +++ b/widget/src/cocoa/nsChildView.mm
-@@ -2657,7 +2657,7 @@ NSEvent* gLastDragEvent = nil;
+@@ -2722,7 +2722,7 @@ NSEvent* gLastDragEvent = nil;
    mGeckoChild->GetBounds(geckoBounds);
  
    NSRect bounds = [self bounds];
 -  nsRefPtr<gfxQuartzSurface> targetSurface =
 +  RefPtr<gfxQuartzSurface> targetSurface =
      new gfxQuartzSurface(cgContext, gfxSize(bounds.size.width, bounds.size.height));
  
  #ifdef DEBUG_UPDATE
-@@ -2670,7 +2670,7 @@ NSEvent* gLastDragEvent = nil;
+@@ -2735,7 +2735,7 @@ NSEvent* gLastDragEvent = nil;
    fprintf (stderr, "  xform in: [%f %f %f %f %f %f]\n", xform.a, xform.b, xform.c, xform.d, xform.tx, xform.ty);
  #endif
  
 -  nsRefPtr<gfxContext> targetContext = new gfxContext(targetSurface);
 +  RefPtr<gfxContext> targetContext = new gfxContext(targetSurface);
  
    nsCOMPtr<nsIRenderingContext> rc;
    mGeckoChild->GetDeviceContext()->CreateRenderingContextInstance(*getter_AddRefs(rc));
@@ -4080,34 +4070,34 @@ diff --git a/widget/src/gtk2/nsDeviceCon
 -  surface.swap(*aSurface);
 +  *aSurface = surface.forget().get();
  
    return NS_OK;
  }
 diff --git a/widget/src/gtk2/nsDragService.cpp b/widget/src/gtk2/nsDragService.cpp
 --- a/widget/src/gtk2/nsDragService.cpp
 +++ b/widget/src/gtk2/nsDragService.cpp
-@@ -63,6 +63,8 @@
- #include "nsPresContext.h"
- #include "nsIDocument.h"
- #include "nsISelection.h"
+@@ -68,6 +68,8 @@
+ 
+ // This sets how opaque the drag image is
+ #define DRAG_IMAGE_ALPHA_LEVEL 0.5
 +
 +using namespace mozilla;
  
  static PRLogModuleInfo *sDragLm = NULL;
  
-@@ -206,7 +208,7 @@ nsDragService::InvokeDragSession(nsIDOMN
+@@ -210,7 +212,7 @@ nsDragService::InvokeDragSession(nsIDOMN
+         PRBool needsFallbackIcon = PR_FALSE;
          nsRect dragRect;
          nsPresContext* pc;
+-        nsRefPtr<gfxASurface> surface;
++        RefPtr<gfxASurface> surface;
          if (mHasImage || mSelection) {
--          nsRefPtr<gfxASurface> surface;
-+          RefPtr<gfxASurface> surface;
            DrawDrag(aDOMNode, aRegion, mScreenX, mScreenY,
                     &dragRect, getter_AddRefs(surface), &pc);
-           if (surface) {
 diff --git a/widget/src/gtk2/nsImageToPixbuf.cpp b/widget/src/gtk2/nsImageToPixbuf.cpp
 --- a/widget/src/gtk2/nsImageToPixbuf.cpp
 +++ b/widget/src/gtk2/nsImageToPixbuf.cpp
 @@ -47,6 +47,8 @@
  
  #include "nsImageToPixbuf.h"
  
 +using namespace mozilla;
@@ -4174,29 +4164,29 @@ diff --git a/widget/src/gtk2/nsWindow.cp
 +using namespace mozilla;
  
  /* For PrepareNativeWidget */
  static NS_DEFINE_IID(kDeviceContextCID, NS_DEVICE_CONTEXT_CID);
 @@ -1677,13 +1679,13 @@ nsWindow::OnExposeEvent(GtkWidget *aWidg
      GetHasTransparentBackground(translucent);
      nsIntRect boundsRect;
      GdkPixmap* bufferPixmap = nsnull;
--    nsRefPtr<gfxXlibSurface> bufferPixmapSurface;
-+    RefPtr<gfxXlibSurface> bufferPixmapSurface;
+-    nsRefPtr<gfxASurface> bufferPixmapSurface;
++    RefPtr<gfxASurface> bufferPixmapSurface;
  
      updateRegion->GetBoundingBox(&boundsRect.x, &boundsRect.y,
                                   &boundsRect.width, &boundsRect.height);
  
      // do double-buffering and clipping here
 -    nsRefPtr<gfxContext> ctx = rc->ThebesContext();
 +    RefPtr<gfxContext> ctx = rc->ThebesContext();
      ctx->Save();
      ctx->NewPath();
      if (translucent) {
-@@ -1767,18 +1769,18 @@ nsWindow::OnExposeEvent(GtkWidget *aWidg
+@@ -1765,18 +1767,18 @@ nsWindow::OnExposeEvent(GtkWidget *aWidg
      if (NS_LIKELY(!mIsDestroyed)) {
          if (status != nsEventStatus_eIgnore) {
              if (translucent) {
 -                nsRefPtr<gfxPattern> pattern = ctx->PopGroup();
 +                RefPtr<gfxPattern> pattern = ctx->PopGroup();
                  ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
                  ctx->SetPattern(pattern);
                  ctx->Paint();
@@ -4222,17 +4212,17 @@ diff --git a/widget/src/gtk2/nsWindow.h 
  
 -#include "nsAutoPtr.h"
 -
  #include "nsCommonWidget.h"
 +#include "gfxTypes.h"
  
  #include "mozcontainer.h"
  #include "mozdrawingarea.h"
-@@ -398,7 +397,7 @@ private:
+@@ -404,7 +403,7 @@ private:
      PRInt32             mTransparencyBitmapWidth;
      PRInt32             mTransparencyBitmapHeight;
  
 -    nsRefPtr<gfxASurface> mThebesSurface;
 +    mozilla::RefPtr<gfxASurface> mThebesSurface;
  
  #ifdef ACCESSIBILITY
      nsCOMPtr<nsIAccessible> mRootAccessible;
@@ -4284,17 +4274,17 @@ diff --git a/widget/src/windows/nsDragSe
 -  nsRefPtr<gfxContext> context = new gfxContext(imgSurface);
 +  RefPtr<gfxContext> context = new gfxContext(imgSurface);
    if (!context)
      return PR_FALSE;
  
 diff --git a/widget/src/windows/nsNativeThemeWin.cpp b/widget/src/windows/nsNativeThemeWin.cpp
 --- a/widget/src/windows/nsNativeThemeWin.cpp
 +++ b/widget/src/windows/nsNativeThemeWin.cpp
-@@ -1264,7 +1264,7 @@ nsNativeThemeWin::DrawWidgetBackground(n
+@@ -1262,7 +1262,7 @@ nsNativeThemeWin::DrawWidgetBackground(n
      }
    }
  
 -  nsRefPtr<gfxContext> ctx = aContext->ThebesContext();
 +  RefPtr<gfxContext> ctx = aContext->ThebesContext();
  
    gfxWindowsNativeDrawing nativeDrawing(ctx, cr, GetWidgetNativeDrawingFlags(aWidgetType));
  
@@ -4331,17 +4321,17 @@ diff --git a/widget/src/windows/nsWindow
 +
 +      RefPtr<gfxContext> thebesContext = new gfxContext(targetSurface);
  
  #ifdef MOZ_XUL
        if (mIsTransparent) {
 diff --git a/widget/src/windows/nsWindow.h b/widget/src/windows/nsWindow.h
 --- a/widget/src/windows/nsWindow.h
 +++ b/widget/src/windows/nsWindow.h
-@@ -421,7 +421,7 @@ protected:
+@@ -420,7 +420,7 @@ protected:
  
  #ifdef MOZ_XUL
    // use layered windows to support full 256 level alpha translucency
 -  nsRefPtr<gfxWindowsSurface> mTransparentSurface;
 +  RefPtr<gfxWindowsSurface> mTransparentSurface;
  
    HDC           mMemoryDC;
    HBITMAP       mMemoryBitmap;
new file mode 100644
--- /dev/null
+++ b/gfx-refcounting2
@@ -0,0 +1,96 @@
+diff --git a/content/canvas/src/nsCanvasRenderingContext2D.cpp b/content/canvas/src/nsCanvasRenderingContext2D.cpp
+--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
++++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
+@@ -473,7 +473,7 @@ protected:
+         float globalAlpha;
+ 
+         nsString font;
+-        nsRefPtr<gfxFontGroup> fontGroup;
++        RefPtr<gfxFontGroup> fontGroup;
+         TextAlign textAlign;
+         TextBaseline textBaseline;
+ 
+diff --git a/layout/base/nsCSSRendering.cpp b/layout/base/nsCSSRendering.cpp
+--- a/layout/base/nsCSSRendering.cpp
++++ b/layout/base/nsCSSRendering.cpp
+@@ -3371,7 +3371,7 @@ nsCSSRendering::PaintBoxShadow(nsPresCon
+     shadowRectPlusBlur.RoundOut();
+ 
+     gfxContext* renderContext = aRenderingContext.ThebesContext();
+-    nsRefPtr<gfxContext> shadowContext;
++    RefPtr<gfxContext> shadowContext;
+     nsContextBoxBlur blurringArea;
+ 
+     // shadowRect has already been converted to device pixels, pass 1 as the appunits/pixel value
+diff --git a/layout/base/nsCSSRendering.h b/layout/base/nsCSSRendering.h
+--- a/layout/base/nsCSSRendering.h
++++ b/layout/base/nsCSSRendering.h
+@@ -390,8 +390,8 @@ protected:
+                        PRUint32 aTopLobe,
+                        PRUint32 aBottomLobe);
+ 
+-  nsRefPtr<gfxContext> mContext;
+-  nsRefPtr<gfxImageSurface> mImageSurface;
++  mozilla::RefPtr<gfxContext> mContext;
++  mozilla::RefPtr<gfxImageSurface> mImageSurface;
+   gfxContext* mDestinationCtx;
+ 
+   // Contrary to what is passed as parameters, these are in device pixels
+diff --git a/widget/src/gtk2/nsDragService.cpp b/widget/src/gtk2/nsDragService.cpp
+--- a/widget/src/gtk2/nsDragService.cpp
++++ b/widget/src/gtk2/nsDragService.cpp
+@@ -271,13 +271,13 @@ nsDragService::SetAlphaPixmap(gfxASurfac
+     gdk_drawable_set_colormap(GDK_DRAWABLE(pixmap), alphaColormap);
+ 
+     // Make a gfxXlibSurface wrapped around the pixmap to render on
+-    nsRefPtr<gfxASurface> xPixmapSurface =
++    RefPtr<gfxASurface> xPixmapSurface =
+          nsWindow::GetSurfaceForGdkDrawable(GDK_DRAWABLE(pixmap),
+                                             dragRect.Size());
+     if (!xPixmapSurface)
+       return PR_FALSE;
+ 
+-    nsRefPtr<gfxContext> xPixmapCtx = new gfxContext(xPixmapSurface);
++    RefPtr<gfxContext> xPixmapCtx = new gfxContext(xPixmapSurface);
+ 
+     // Clear it...
+     xPixmapCtx->SetOperator(gfxContext::OPERATOR_CLEAR);
+diff --git a/widget/src/gtk2/nsWindow.cpp b/widget/src/gtk2/nsWindow.cpp
+--- a/widget/src/gtk2/nsWindow.cpp
++++ b/widget/src/gtk2/nsWindow.cpp
+@@ -6206,7 +6206,7 @@ IM_get_input_context(nsWindow *aWindow)
+ 
+ #endif
+ 
+-/* static */ already_AddRefed<gfxASurface>
++/* static */ AddRefed<gfxASurface>
+ nsWindow::GetSurfaceForGdkDrawable(GdkDrawable* aDrawable,
+                                    const nsSize& aSize)
+ {
+@@ -6215,10 +6215,8 @@ nsWindow::GetSurfaceForGdkDrawable(GdkDr
+     Display* xDisplay = gdk_x11_drawable_get_xdisplay(aDrawable);
+     Drawable xDrawable = gdk_x11_drawable_get_xid(aDrawable);
+ 
+-    gfxASurface* result = new gfxXlibSurface(xDisplay, xDrawable, xVisual,
+-                                       gfxIntSize(aSize.width, aSize.height));
+-    NS_IF_ADDREF(result);
+-    return result;
++    return do_AddRef(new gfxXlibSurface(xDisplay, xDrawable, xVisual,
++                                        gfxIntSize(aSize.width, aSize.height)));
+ }
+ 
+ // return the gfxASurface for rendering to this widget
+diff --git a/widget/src/gtk2/nsWindow.h b/widget/src/gtk2/nsWindow.h
+--- a/widget/src/gtk2/nsWindow.h
++++ b/widget/src/gtk2/nsWindow.h
+@@ -366,8 +366,8 @@ public:
+ 
+     gfxASurface       *GetThebesSurface();
+ 
+-    static already_AddRefed<gfxASurface> GetSurfaceForGdkDrawable(GdkDrawable* aDrawable,
+-                                                                  const nsSize& aSize);
++    static mozilla::AddRefed<gfxASurface> GetSurfaceForGdkDrawable(GdkDrawable* aDrawable,
++                                                                   const nsSize& aSize);
+ 
+ #ifdef ACCESSIBILITY
+     static PRBool      sAccessibilityEnabled;
--- a/hgignore-update
+++ b/hgignore-update
@@ -1,12 +1,12 @@
 diff --git a/.hgignore b/.hgignore
 --- a/.hgignore
 +++ b/.hgignore
-@@ -3,6 +3,8 @@
- # Filenames that should be ignored wherever they appear
+@@ -4,6 +4,8 @@
  ~$
  \.pyc$
+ (^|/)TAGS$
 +\.orig$
 +\.rej$
  
  # User files that may appear at the root
  ^\.mozconfig$
--- a/layout-stack-classes
+++ b/layout-stack-classes
@@ -10,188 +10,8 @@
 * * *
 * * *
 * * *
 * * *
 * * *
 * * *
 * * *
 
-diff --git a/layout/base/nsCSSFrameConstructor.cpp b/layout/base/nsCSSFrameConstructor.cpp
---- a/layout/base/nsCSSFrameConstructor.cpp
-+++ b/layout/base/nsCSSFrameConstructor.cpp
-@@ -1127,7 +1127,7 @@ private:
- 
- // Structure used for maintaining state information during the
- // frame construction process
--class nsFrameConstructorState {
-+class NS_STACK_CLASS nsFrameConstructorState {
- public:
-   nsPresContext            *mPresContext;
-   nsIPresShell             *mPresShell;
-@@ -1731,7 +1731,7 @@ MoveChildrenTo(nsFrameManager*          
- 
- // Structure used to ensure that bindings are properly enqueued in the
- // binding manager's attached queue.
--struct nsAutoEnqueueBinding
-+struct NS_STACK_CLASS nsAutoEnqueueBinding
- {
-   nsAutoEnqueueBinding(nsIDocument* aDocument) :
-     mDocument(aDocument)
-diff --git a/layout/base/nsChildIterator.h b/layout/base/nsChildIterator.h
---- a/layout/base/nsChildIterator.h
-+++ b/layout/base/nsChildIterator.h
-@@ -52,7 +52,7 @@
-  * node APIs, since it handles XBL-generated anonymous content as
-  * well.
-  */
--class ChildIterator
-+class NS_STACK_CLASS ChildIterator
- {
- protected:
-   nsCOMPtr<nsIContent> mContent;
-diff --git a/layout/base/nsDisplayList.h b/layout/base/nsDisplayList.h
---- a/layout/base/nsDisplayList.h
-+++ b/layout/base/nsDisplayList.h
-@@ -117,7 +117,7 @@ class nsDisplayTableItem;
-  * available from the prescontext/presshell, but we copy them into the builder
-  * for faster/more convenient access.
-  */
--class nsDisplayListBuilder {
-+class NS_STACK_CLASS nsDisplayListBuilder {
- public:
-   /**
-    * @param aReferenceFrame the frame at the root of the subtree; its origin
-diff --git a/layout/base/nsICaret.h b/layout/base/nsICaret.h
---- a/layout/base/nsICaret.h
-+++ b/layout/base/nsICaret.h
-@@ -204,7 +204,7 @@ NS_NewCaret(nsICaret** aInstancePtrResul
- 
- // handy stack-based class for temporarily disabling the caret
- 
--class StCaretHider
-+class NS_STACK_CLASS StCaretHider
- {
- public:
-                StCaretHider(nsICaret* aSelCon)
-diff --git a/layout/generic/nsFrame.cpp b/layout/generic/nsFrame.cpp
---- a/layout/generic/nsFrame.cpp
-+++ b/layout/generic/nsFrame.cpp
-@@ -2337,7 +2337,7 @@ NS_IMETHODIMP nsFrame::HandleRelease(nsP
-                            parentContent, aEvent, aEventStatus);
- }
- 
--struct FrameContentRange {
-+struct NS_STACK_CLASS FrameContentRange {
-   FrameContentRange(nsIContent* aContent, PRInt32 aStart, PRInt32 aEnd) :
-     content(aContent), start(aStart), end(aEnd) { }
-   nsCOMPtr<nsIContent> content;
-diff --git a/layout/generic/nsFrameSelection.h b/layout/generic/nsFrameSelection.h
---- a/layout/generic/nsFrameSelection.h
-+++ b/layout/generic/nsFrameSelection.h
-@@ -77,7 +77,7 @@ enum EWordMovementType { eStartWord, eEn
-  *  that are passed to nsFrame::PeekOffset(). See below for the description of
-  *  individual arguments.
-  */
--struct nsPeekOffsetStruct
-+struct NS_STACK_CLASS nsPeekOffsetStruct
- {
-   void SetData(nsSelectionAmount aAmount,
-                nsDirection aDirection,
-diff --git a/layout/generic/nsIFrame.h b/layout/generic/nsIFrame.h
---- a/layout/generic/nsIFrame.h
-+++ b/layout/generic/nsIFrame.h
-@@ -945,7 +945,7 @@ public:
-   // Note that the primary offset can be after the secondary offset; for places
-   // that need the beginning and end of the object, the StartOffset and 
-   // EndOffset helpers can be used.
--  struct ContentOffsets {
-+  struct NS_STACK_CLASS ContentOffsets {
-     nsCOMPtr<nsIContent> content;
-     PRBool IsNull() { return !content; }
-     PRInt32 offset;
-@@ -978,7 +978,7 @@ public:
-    * loaded image that should be preferred. If it is not possible to use it, or
-    * if it is null, mCursor should be used.
-    */
--  struct Cursor {
-+  struct NS_STACK_CLASS Cursor {
-     nsCOMPtr<imgIContainer> mContainer;
-     PRInt32                 mCursor;
-     PRBool                  mHaveHotspot;
-diff --git a/layout/generic/nsSelection.cpp b/layout/generic/nsSelection.cpp
---- a/layout/generic/nsSelection.cpp
-+++ b/layout/generic/nsSelection.cpp
-@@ -381,7 +381,7 @@ private:
- };
- 
- // Stack-class to turn on/off selection batching for table selection
--class nsSelectionBatcher
-+class NS_STACK_CLASS NS_FINAL_CLASS nsSelectionBatcher
- {
- private:
-   nsCOMPtr<nsISelectionPrivate> mSelection;
-@@ -390,7 +390,7 @@ public:
-   {
-     if (mSelection) mSelection->StartBatchChanges();
-   }
--  virtual ~nsSelectionBatcher() 
-+  ~nsSelectionBatcher() 
-   { 
-     if (mSelection) mSelection->EndBatchChanges();
-   }
-diff --git a/layout/generic/nsTextFrameThebes.cpp b/layout/generic/nsTextFrameThebes.cpp
---- a/layout/generic/nsTextFrameThebes.cpp
-+++ b/layout/generic/nsTextFrameThebes.cpp
-@@ -1975,7 +1975,7 @@ static PRBool IsInBounds(const gfxSkipCh
- }
- #endif
- 
--class PropertyProvider : public gfxTextRun::PropertyProvider {
-+class NS_STACK_CLASS PropertyProvider : public gfxTextRun::PropertyProvider {
- public:
-   /**
-    * Use this constructor for reflow, when we don't know what text is
-@@ -4613,7 +4613,7 @@ nsTextFrame::PeekOffsetNoAmount(PRBool a
-  * is interpreted according to aDirection, so if aDirection is -1, "before"
-  * means actually *after* the cluster content.)
-  */
--class ClusterIterator {
-+class NS_STACK_CLASS ClusterIterator {
- public:
-   ClusterIterator(nsTextFrame* aTextFrame, PRInt32 aPosition, PRInt32 aDirection,
-                   nsString& aContext);
-diff --git a/layout/svg/base/src/nsSVGFilterInstance.h b/layout/svg/base/src/nsSVGFilterInstance.h
---- a/layout/svg/base/src/nsSVGFilterInstance.h
-+++ b/layout/svg/base/src/nsSVGFilterInstance.h
-@@ -51,7 +51,7 @@ class nsSVGLength2;
- class nsSVGLength2;
- class nsSVGElement;
- 
--class nsSVGFilterInstance
-+class NS_STACK_CLASS nsSVGFilterInstance
- {
- public:
-   class ColorModel {
-diff --git a/layout/xul/base/src/nsBoxLayoutState.h b/layout/xul/base/src/nsBoxLayoutState.h
---- a/layout/xul/base/src/nsBoxLayoutState.h
-+++ b/layout/xul/base/src/nsBoxLayoutState.h
-@@ -56,7 +56,7 @@ class nsString;
- class nsString;
- class nsHTMLReflowCommand;
- 
--class nsBoxLayoutState
-+class NS_STACK_CLASS nsBoxLayoutState
- {
- public:
-   nsBoxLayoutState(nsPresContext* aPresContext, nsIRenderingContext* aRenderingContext = nsnull,
-diff --git a/view/public/nsIViewManager.h b/view/public/nsIViewManager.h
---- a/view/public/nsIViewManager.h
-+++ b/view/public/nsIViewManager.h
-@@ -322,7 +322,7 @@ public:
-    */
-   NS_IMETHOD EnableRefresh(PRUint32 aUpdateFlags) = 0;
- 
--  class UpdateViewBatch {
-+  class NS_STACK_CLASS UpdateViewBatch {
-   public:
-     UpdateViewBatch() {}
-   /**
--- a/mozStorageStatementScoper-stackclass
+++ b/mozStorageStatementScoper-stackclass
@@ -1,12 +0,0 @@
-diff --git a/storage/public/mozStorageHelper.h b/storage/public/mozStorageHelper.h
---- a/storage/public/mozStorageHelper.h
-+++ b/storage/public/mozStorageHelper.h
-@@ -152,7 +152,7 @@ protected:
-  * Note that this always just resets the statement. If the statement doesn't
-  * need resetting, the reset operation is inexpensive.
-  */
--class mozStorageStatementScoper
-+class NS_STACK_CLASS mozStorageStatementScoper
- {
- public:
-   mozStorageStatementScoper(mozIStorageStatement* aStatement)
--- a/no-standaloneglue.patch
+++ b/no-standaloneglue.patch
@@ -1,23 +1,23 @@
 diff --git a/config/autoconf.mk.in b/config/autoconf.mk.in
 --- a/config/autoconf.mk.in
 +++ b/config/autoconf.mk.in
-@@ -429,7 +429,6 @@ LDAP_CFLAGS	= @LDAP_CFLAGS@
+@@ -464,7 +464,6 @@ LDAP_CFLAGS	= @LDAP_CFLAGS@
  LDAP_CFLAGS	= @LDAP_CFLAGS@
  LDAP_LIBS	= @LDAP_LIBS@
  XPCOM_GLUE_LDOPTS = @XPCOM_GLUE_LDOPTS@
 -XPCOM_STANDALONE_GLUE_LDOPTS = @XPCOM_STANDALONE_GLUE_LDOPTS@
  MOZ_XPCOM_OBSOLETE_LIBS = @MOZ_XPCOM_OBSOLETE_LIBS@
  
  USE_DEPENDENT_LIBS = @USE_DEPENDENT_LIBS@
 diff --git a/configure.in b/configure.in
 --- a/configure.in
 +++ b/configure.in
-@@ -892,7 +892,6 @@ XPCOM_FROZEN_LDOPTS='-L$(LIBXUL_DIST)/bi
+@@ -955,7 +955,6 @@ XPCOM_FROZEN_LDOPTS='-L$(LIBXUL_DIST)/bi
  XPCOM_FROZEN_LDOPTS='-L$(LIBXUL_DIST)/bin -lxpcom'
  LIBXUL_LIBS='$(XPCOM_FROZEN_LDOPTS) -lxul'
  XPCOM_GLUE_LDOPTS='$(LIBXUL_DIST)/lib/$(LIB_PREFIX)xpcomglue_s.$(LIB_SUFFIX) $(XPCOM_FROZEN_LDOPTS)'
 -XPCOM_STANDALONE_GLUE_LDOPTS='$(LIBXUL_DIST)/lib/$(LIB_PREFIX)xpcomglue.$(LIB_SUFFIX)'
  
  MOZ_COMPONENT_NSPR_LIBS='-L$(LIBXUL_DIST)/bin $(NSPR_LIBS)'
  MOZ_XPCOM_OBSOLETE_LIBS='-L$(LIBXUL_DIST)/lib -lxpcom_compat'
 diff --git a/embedding/browser/gtk/Makefile.in b/embedding/browser/gtk/Makefile.in
@@ -50,29 +50,29 @@ diff --git a/embedding/tests/Makefile.in
 -endif
 -
  endif
  
  include $(topsrcdir)/config/rules.mk
 diff --git a/toolkit/toolkit-makefiles.sh b/toolkit/toolkit-makefiles.sh
 --- a/toolkit/toolkit-makefiles.sh
 +++ b/toolkit/toolkit-makefiles.sh
-@@ -469,7 +469,6 @@ MAKEFILES_xpcom="
+@@ -464,7 +464,6 @@ MAKEFILES_xpcom="
    xpcom/components/Makefile
    xpcom/ds/Makefile
    xpcom/glue/Makefile
 -  xpcom/glue/standalone/Makefile
    xpcom/io/Makefile
    xpcom/typelib/Makefile
    xpcom/reflect/Makefile
 diff --git a/xpcom/Makefile.in b/xpcom/Makefile.in
 --- a/xpcom/Makefile.in
 +++ b/xpcom/Makefile.in
-@@ -67,10 +67,6 @@ endif
- endif
+@@ -65,10 +65,6 @@ DIRS += stub
+ DIRS += stub
  endif
  
 -TOOL_DIRS = \
 -	tools \
 -	$(NULL)
 -
  ifeq ($(OS_ARCH),WINNT)
  ifdef MOZ_DEBUG
@@ -84,17 +84,17 @@ diff --git a/xpcom/glue/Makefile.in b/xp
  include $(srcdir)/objs.mk
  
  EXTRA_DEPS += $(srcdir)/objs.mk
 -
 -DIRS            = standalone
  
  MODULE		= xpcom
  LIBRARY_NAME	= xpcomglue_s
-@@ -120,6 +118,7 @@ EXPORTS = \
+@@ -124,6 +122,7 @@ EXPORTS = \
  		nsThreadUtils.h \
  		nsProxyRelease.h \
  		nsXPTCUtils.h \
 +		nsXPCOMGlue.h \
  		$(NULL)
  
  SDK_LIBRARY     =                        \
 diff --git a/xpcom/glue/nsGenericFactory.cpp b/xpcom/glue/nsGenericFactory.cpp
@@ -184,42 +184,42 @@ diff --git a/xpcom/glue/nsISupportsImpl.
  ////////////////////////////////////////////////////////////////////////////////
  // Macros to help detect thread-safety:
  
 -#if defined(NS_DEBUG) && !defined(XPCOM_GLUE_AVOID_NSPR)
 +#if defined(NS_DEBUG)
  
  class nsAutoOwningThread {
  public:
-@@ -1100,8 +1097,6 @@ NS_IMETHODIMP_(nsrefcnt) Class::Release(
+@@ -1163,8 +1160,6 @@ NS_IMETHODIMP_(nsrefcnt) Class::Release(
   *        because the implementation requires PR_ symbols.
   */
  
 -#if !defined(XPCOM_GLUE_AVOID_NSPR)
 -
  /**
   * Use this macro to implement the AddRef method for a given <i>_class</i>
   * @param _class The name of the class implementing the method
-@@ -1139,16 +1134,6 @@ NS_IMETHODIMP_(nsrefcnt) _class::Release
+@@ -1201,16 +1196,6 @@ NS_IMETHODIMP_(nsrefcnt) _class::Release
+   }                                                                           \
    return count;                                                               \
  }
- 
+-
 -#else // XPCOM_GLUE_AVOID_NSPR
 -
 -#define NS_IMPL_THREADSAFE_ADDREF(_class)                                     \
 -  THREADSAFE_ISUPPORTS_NOT_AVAILABLE_IN_STANDALONE_GLUE;
 -
 -#define NS_IMPL_THREADSAFE_RELEASE(_class)                                    \
 -  THREADSAFE_ISUPPORTS_NOT_AVAILABLE_IN_STANDALONE_GLUE;
 -
 -#endif
--
+ 
  #define NS_IMPL_THREADSAFE_ISUPPORTS0(_class)                                 \
    NS_IMPL_THREADSAFE_ADDREF(_class)                                           \
-   NS_IMPL_THREADSAFE_RELEASE(_class)                                          \
 diff --git a/xpcom/glue/nsProxyRelease.h b/xpcom/glue/nsProxyRelease.h
 --- a/xpcom/glue/nsProxyRelease.h
 +++ b/xpcom/glue/nsProxyRelease.h
 @@ -42,10 +42,6 @@
  #include "nsIEventTarget.h"
  #include "nsCOMPtr.h"
  
 -#ifdef XPCOM_GLUE_AVOID_NSPR
@@ -227,76 +227,76 @@ diff --git a/xpcom/glue/nsProxyRelease.h
 -#endif
 -
  /**
   * Ensure that a nsCOMPtr is released on the target thread.
   *
 diff --git a/xpcom/glue/nsStringAPI.cpp b/xpcom/glue/nsStringAPI.cpp
 --- a/xpcom/glue/nsStringAPI.cpp
 +++ b/xpcom/glue/nsStringAPI.cpp
-@@ -469,7 +469,6 @@ nsAString::AppendInt(int aInt, PRInt32 a
+@@ -520,7 +520,6 @@ nsAString::AppendInt(int aInt, PRInt32 a
  
  // Strings
  
 -#ifndef XPCOM_GLUE_AVOID_NSPR
  PRInt32
  nsAString::ToInteger(nsresult *aErrorCode, PRUint32 aRadix) const
  {
-@@ -499,7 +498,6 @@ nsAString::ToInteger(nsresult *aErrorCod
+@@ -550,7 +549,6 @@ nsAString::ToInteger(nsresult *aErrorCod
  
    return result;
  }
 -#endif // XPCOM_GLUE_AVOID_NSPR
  
  // nsACString
  
-@@ -814,7 +812,6 @@ nsACString::AppendInt(int aInt, PRInt32 
+@@ -928,7 +926,6 @@ nsACString::AppendInt(int aInt, PRInt32 
    Append(buf, len);
  }
  
 -#ifndef XPCOM_GLUE_AVOID_NSPR
  PRInt32
  nsACString::ToInteger(nsresult *aErrorCode, PRUint32 aRadix) const
  {
-@@ -842,7 +839,6 @@ nsACString::ToInteger(nsresult *aErrorCo
+@@ -956,7 +953,6 @@ nsACString::ToInteger(nsresult *aErrorCo
  
    return result;
  }
 -#endif // XPCOM_GLUE_AVOID_NSPR
  
  // Substrings
  
 diff --git a/xpcom/glue/nsStringAPI.h b/xpcom/glue/nsStringAPI.h
 --- a/xpcom/glue/nsStringAPI.h
 +++ b/xpcom/glue/nsStringAPI.h
-@@ -321,7 +321,6 @@ public:
+@@ -362,7 +362,6 @@ public:
     */
    NS_HIDDEN_(void) AppendInt(int aInt, PRInt32 aRadix = 10);
  
 -#ifndef XPCOM_GLUE_AVOID_NSPR
    /**
     * Convert this string to an integer.
     *
-@@ -330,7 +329,6 @@ public:
+@@ -371,7 +370,6 @@ public:
     */
    NS_HIDDEN_(PRInt32) ToInteger(nsresult* aErrorCode,
                                  PRUint32 aRadix = 10) const;
 -#endif // XPCOM_GLUE_AVOID_NSPR
  
  protected:
    // Prevent people from allocating a nsAString directly.
-@@ -606,7 +604,6 @@ public:
+@@ -688,7 +686,6 @@ public:
     */
    NS_HIDDEN_(void) AppendInt(int aInt, PRInt32 aRadix = 10);
  
 -#ifndef XPCOM_GLUE_AVOID_NSPR
    /**
     * Convert this string to an integer.
     *
-@@ -615,7 +612,6 @@ public:
+@@ -697,7 +694,6 @@ public:
     */
    NS_HIDDEN_(PRInt32) ToInteger(nsresult* aErrorCode,
                                  PRUint32 aRadix = 10) const;
 -#endif // XPCOM_GLUE_AVOID_NSPR
  
  protected:
    // Prevent people from allocating a nsAString directly.
 diff --git a/xpcom/glue/nsThreadUtils.cpp b/xpcom/glue/nsThreadUtils.cpp
@@ -306,25 +306,25 @@ diff --git a/xpcom/glue/nsThreadUtils.cp
  # include "nsServiceManagerUtils.h"
  #endif
  
 -#ifndef XPCOM_GLUE_AVOID_NSPR
 -
  NS_IMPL_THREADSAFE_ISUPPORTS1(nsRunnable, nsIRunnable)
    
  NS_IMETHODIMP
-@@ -57,8 +55,6 @@ nsRunnable::Run()
+@@ -56,8 +54,6 @@ nsRunnable::Run()
+   // Do nothing
    return NS_OK;
  }
- 
+-
 -#endif  // XPCOM_GLUE_AVOID_NSPR
--
+ 
  //-----------------------------------------------------------------------------
  
- NS_METHOD
 @@ -154,7 +150,6 @@ NS_DispatchToMainThread(nsIRunnable *eve
    return thread->Dispatch(event, dispatchFlags);
  }
  
 -#ifndef XPCOM_GLUE_AVOID_NSPR
  NS_METHOD
  NS_ProcessPendingEvents(nsIThread *thread, PRIntervalTime timeout)
  {
--- a/nsCanvasRenderingContext2D_ContextState-okonstack
+++ b/nsCanvasRenderingContext2D_ContextState-okonstack
@@ -1,34 +1,27 @@
 diff --git a/content/canvas/src/nsCanvasRenderingContext2D.cpp b/content/canvas/src/nsCanvasRenderingContext2D.cpp
 --- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
 +++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
-@@ -364,9 +364,17 @@ protected:
+@@ -434,7 +434,11 @@ protected:
      PRPackedBool mDirtyStyle[STYLE_MAX];
  
      // state stack handling
 -    class ContextState {
 +    class
 +        NS_GC_TYPE
 +        NS_OKONSTACK
 +    ContextState
 +    {
      public:
--        ContextState() : globalAlpha(1.0) { }
-+        ContextState() : globalAlpha(1.0) {
-+            memset(colorStyles, 0, sizeof(colorStyles));
-+            memset(gradientStyles, 0, sizeof(gradientStyles));
-+            memset(patternStyles, 0, sizeof(patternStyles));
-+        }
+         ContextState() : globalAlpha(1.0),
+                          textAlign(TEXT_ALIGN_START),
+@@ -478,11 +482,11 @@ protected:
+         TextBaseline textBaseline;
  
-         ContextState(const ContextState& other)
-             : globalAlpha(other.globalAlpha)
-@@ -396,11 +404,11 @@ protected:
- 
-         float globalAlpha;
          nscolor colorStyles[STYLE_MAX];
 -        nsCOMPtr<nsCanvasGradient> gradientStyles[STYLE_MAX];
 -        nsCOMPtr<nsCanvasPattern> patternStyles[STYLE_MAX];
 +        nsCanvasGradient* gradientStyles[STYLE_MAX];
 +        nsCanvasPattern* patternStyles[STYLE_MAX];
      };
  
 -    nsTArray<ContextState> mStyleStack;
--- a/nsMorkReader-stackclass
+++ b/nsMorkReader-stackclass
@@ -1,12 +0,0 @@
-diff --git a/db/morkreader/nsMorkReader.h b/db/morkreader/nsMorkReader.h
---- a/db/morkreader/nsMorkReader.h
-+++ b/db/morkreader/nsMorkReader.h
-@@ -53,7 +53,7 @@
- //  http://www.mozilla.org/mailnews/arch/mork/grammar.txt
- //  http://www.jwz.org/hacks/mork.pl
- 
--class nsMorkReader
-+class NS_STACK_CLASS nsMorkReader
- {
-  public:
-   // This string type has built-in storage for the hex string representation
--- a/nsProxiedService-stackclass
+++ b/nsProxiedService-stackclass
@@ -1,12 +0,0 @@
-diff --git a/xpcom/proxy/public/nsProxiedService.h b/xpcom/proxy/public/nsProxiedService.h
---- a/xpcom/proxy/public/nsProxiedService.h
-+++ b/xpcom/proxy/public/nsProxiedService.h
-@@ -93,7 +93,7 @@
- // nsProxiedService
- ////////////////////////////////////////////////////////////////////////////////
- 
--class nsProxiedService
-+class NS_STACK_CLASS nsProxiedService
- {
- public:
-     nsProxiedService(const nsCID &aClass, const nsIID &aIID, 
--- a/nsSlots
+++ b/nsSlots
@@ -607,107 +607,98 @@ diff --git a/content/base/src/nsGenericE
    // 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);
-@@ -2172,7 +2148,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 &&
-@@ -2205,7 +2181,7 @@ nsGenericElement::doPreHandleEvent(nsICo
+@@ -2228,7 +2204,7 @@ nsGenericElement::doPreHandleEvent(nsICo
      }
    }
  
 -  nsCOMPtr<nsIContent> parent = aContent->GetParent();
 +  nsIContent* parent = aContent->GetParent();
    if (isAnonForEvents) {
      // If a DOM event is explicitly dispatched using node.dispatchEvent(), then
      // all the events are allowed even in the native anonymous content..
-@@ -2214,7 +2190,7 @@ nsGenericElement::doPreHandleEvent(nsICo
+@@ -2237,7 +2213,7 @@ nsGenericElement::doPreHandleEvent(nsICo
                   "Mutation event dispatched in native anonymous content!?!");
      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;
      }
-@@ -2373,7 +2349,7 @@ nsGenericElement::GetExistingAttrNameFro
+@@ -2396,7 +2372,7 @@ nsGenericElement::GetExistingAttrNameFro
                                                kNameSpaceID_None, &nodeInfo);
    }
    else {
 -    NS_ADDREF(nodeInfo = name->NodeInfo());
 +    nodeInfo = name->NodeInfo();
    }
  
    return nodeInfo;
-@@ -2392,7 +2368,7 @@ nsGenericElement::GetBaseURI() const
+@@ -2415,7 +2391,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) {
-@@ -2409,13 +2385,13 @@ nsGenericElement::GetBaseURI() const
+@@ -2432,13 +2408,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()
-@@ -2431,7 +2407,6 @@ nsGenericElement::GetBaseURI() const
+@@ -2454,7 +2430,6 @@ nsGenericElement::GetBaseURI() const
      base = ourBase;
    }
  
 -  NS_IF_ADDREF(base);
  
    return base;    
  }
-@@ -2449,7 +2424,7 @@ nsGenericElement::SetFocus(nsPresContext
+@@ -2472,7 +2447,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;
    }
-@@ -2480,8 +2455,8 @@ nsGenericElement::ShouldFocus(nsIContent
+@@ -2503,8 +2478,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);
-@@ -2506,13 +2481,13 @@ nsGenericElement::ShouldBlur(nsIContent 
+@@ -2529,13 +2504,13 @@ nsGenericElement::ShouldBlur(nsIContent 
      nsPIDOMWindow *win = document->GetWindow();
  
      if (win) {
 -      nsCOMPtr<nsIFocusController> focusController =
 +      nsIFocusController* focusController =
             win->GetRootFocusController();
  
        if (focusController) {
@@ -715,160 +706,160 @@ 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;
-@@ -2690,7 +2665,7 @@ nsresult
+@@ -2711,7 +2686,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) {
-@@ -2718,7 +2693,7 @@ nsGenericElement::doRemoveChildAt(PRUint
+@@ -2739,7 +2714,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,
-@@ -2791,7 +2766,7 @@ nsGenericElement::DispatchEvent(nsPresCo
+@@ -2810,7 +2785,7 @@ nsGenericElement::DispatchEvent(nsPresCo
      return NS_OK;
    }
  
 -  nsCOMPtr<nsIPresShell> shell = aPresContext->GetPresShell();
 +  nsIPresShell* shell = aPresContext->GetPresShell();
    if (!shell) {
      return NS_OK;
    }
-@@ -2941,7 +2916,7 @@ PRBool IsAllowedAsChild(nsIContent* aNew
+@@ -2960,7 +2935,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,
-@@ -2985,11 +2960,11 @@ PRBool IsAllowedAsChild(nsIContent* aNew
+@@ -3004,11 +2979,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.
-@@ -3012,11 +2987,11 @@ PRBool IsAllowedAsChild(nsIContent* aNew
+@@ -3031,11 +3006,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;
-@@ -3067,7 +3042,7 @@ PRBool IsAllowedAsChild(nsIContent* aNew
+@@ -3086,7 +3061,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,
-@@ -3110,9 +3085,9 @@ nsGenericElement::doReplaceOrInsertBefor
+@@ -3129,9 +3104,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;
  
-@@ -3127,7 +3102,7 @@ nsGenericElement::doReplaceOrInsertBefor
+@@ -3146,7 +3121,7 @@ nsGenericElement::doReplaceOrInsertBefor
      }
  
      if (aRefChild == aNewChild) {
 -      NS_ADDREF(*aReturn = aNewChild);
 +      *aReturn = aNewChild;
  
        return NS_OK;
      }
-@@ -3135,7 +3110,7 @@ nsGenericElement::doReplaceOrInsertBefor
+@@ -3154,7 +3129,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;
    }
-@@ -3252,7 +3227,7 @@ nsGenericElement::doReplaceOrInsertBefor
+@@ -3271,7 +3246,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);
  
-@@ -3332,7 +3307,7 @@ nsGenericElement::doReplaceOrInsertBefor
+@@ -3351,7 +3326,7 @@ nsGenericElement::doReplaceOrInsertBefor
      NS_ENSURE_SUCCESS(res, res);
    }
  
 -  returnVal.swap(*aReturn);
 +  swap(returnVal, *aReturn);
  
    return res;
  }
-@@ -3351,7 +3326,7 @@ nsGenericElement::doRemoveChild(nsIDOMNo
+@@ -3370,7 +3345,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) {
-@@ -3362,7 +3337,6 @@ nsGenericElement::doRemoveChild(nsIDOMNo
+@@ -3381,7 +3356,6 @@ nsGenericElement::doRemoveChild(nsIDOMNo
    nsresult rv = container->RemoveChildAt(index, PR_TRUE);
  
    *aReturn = aOldChild;
 -  NS_ADDREF(aOldChild);
  
    return rv;
  }
-@@ -3437,12 +3411,12 @@ nsGenericElement::AddScriptEventListener
+@@ -3456,12 +3430,12 @@ nsGenericElement::AddScriptEventListener
    }
  
    NS_PRECONDITION(aEventName, "Must have event name!");
 -  nsCOMPtr<nsISupports> target;
 +  nsISupports* target = nsnull;
    PRBool defer = PR_TRUE;
 -  nsCOMPtr<nsIEventListenerManager> manager;
 -
@@ -876,136 +867,136 @@ diff --git a/content/base/src/nsGenericE
 -                                               getter_AddRefs(target),
 +  nsIEventListenerManager* manager = nsnull;
 +
 +  nsresult rv = GetEventListenerManagerForAttr(&manager,
 +                                               &target,
                                                 &defer);
    NS_ENSURE_SUCCESS(rv, rv);
  
-@@ -3593,10 +3567,10 @@ nsGenericElement::SetAttrAndNotify(PRInt
+@@ -3612,10 +3586,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);
-@@ -3697,7 +3671,7 @@ nsGenericElement::GetEventListenerManage
+@@ -3714,7 +3688,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;
-@@ -3842,13 +3816,13 @@ nsGenericElement::UnsetAttr(PRInt32 aNam
+@@ -3859,13 +3833,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
-@@ -4036,9 +4010,9 @@ nsGenericElement::List(FILE* out, PRInt3
+@@ -4051,9 +4025,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);
-@@ -4047,9 +4021,9 @@ nsGenericElement::List(FILE* out, PRInt3
+@@ -4062,9 +4036,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);
          }
  
-@@ -4059,9 +4033,9 @@ nsGenericElement::List(FILE* out, PRInt3
+@@ -4074,9 +4048,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");
  
-@@ -4071,9 +4045,9 @@ nsGenericElement::List(FILE* out, PRInt3
+@@ -4086,9 +4060,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);
          }
  
-@@ -4171,8 +4145,8 @@ nsGenericElement::PreHandleEventForLinks
+@@ -4186,8 +4160,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;
    }
  
-@@ -4226,8 +4200,8 @@ nsGenericElement::PostHandleEventForLink
+@@ -4241,8 +4215,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;
    }
  
-@@ -4254,7 +4228,7 @@ nsGenericElement::PostHandleEventForLink
+@@ -4269,7 +4243,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;
-@@ -4278,7 +4252,7 @@ nsGenericElement::PostHandleEventForLink
+@@ -4293,7 +4267,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;
@@ -1235,70 +1226,70 @@ diff --git a/content/base/src/nsNodeUtil
    }
  
    *aResult = static_cast<nsIVariant*>
                          (aNode->GetProperty(DOM_USER_DATA, key));
 -  NS_IF_ADDREF(*aResult);
  
    return NS_OK;
  }
-@@ -333,10 +270,10 @@ CallHandler(void *aObject, nsIAtom *aKey
+@@ -334,10 +271,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?");
  
-@@ -360,7 +297,7 @@ nsNodeUtils::CallUserDataHandlers(nsCOMA
+@@ -361,7 +298,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;
-@@ -391,10 +328,10 @@ nsNodeUtils::CloneNodeImpl(nsINode *aNod
+@@ -392,10 +329,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();
-@@ -404,7 +341,7 @@ nsNodeUtils::CloneNodeImpl(nsINode *aNod
+@@ -405,7 +342,7 @@ nsNodeUtils::CloneNodeImpl(nsINode *aNod
      NS_ENSURE_SUCCESS(rv, rv);
    }
  
 -  newNode.swap(*aResult);
 +  swap(newNode, *aResult);
  
    return NS_OK;
  }
-@@ -434,7 +371,7 @@ PLDHashOperator PR_CALLBACK
+@@ -435,7 +372,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);
-@@ -442,18 +379,18 @@ AdoptFunc(nsAttrHashKey::KeyType aKey, n
+@@ -443,18 +380,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,
@@ -1311,32 +1302,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);
      }
    }
  
-@@ -487,12 +424,12 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -488,12 +425,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;
-@@ -502,15 +439,15 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -503,15 +440,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);
@@ -1345,85 +1336,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);
-@@ -524,7 +461,7 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -525,7 +462,7 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
      }
    }
    else if (nodeInfoManager) {
 -    nsCOMPtr<nsISupports> oldRef;
 +    nsISupports* oldRef = nsnull;
      nsIDocument* oldDoc = aNode->GetOwnerDoc();
      if (oldDoc) {
        if (aNode->IsNodeOfType(nsINode::eELEMENT)) {
-@@ -546,8 +483,8 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -547,8 +484,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());
          }
-@@ -561,9 +498,9 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -562,9 +499,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);
  
-@@ -577,7 +514,7 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -578,7 +515,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.
-@@ -601,11 +538,11 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -602,11 +539,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);
-@@ -618,10 +555,10 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
+@@ -619,10 +556,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);
      }
    }
-@@ -667,7 +604,7 @@ nsNodeUtils::UnlinkUserData(nsINode *aNo
+@@ -668,7 +605,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/propertycache-gc-assert
+++ b/propertycache-gc-assert
@@ -1,55 +1,55 @@
 Bug 429978 - Assertion failure: JS_PROPERTY_CACHE(cx).disabled >= 0 ... seems to work, but don't know if it's correct!
 
 diff --git a/js/src/jsgc.cpp b/js/src/jsgc.cpp
 --- a/js/src/jsgc.cpp
 +++ b/js/src/jsgc.cpp
-@@ -910,6 +910,8 @@ JSGC::enterExclusiveGC()
+@@ -911,6 +911,8 @@ JSGC::enterExclusiveGC()
  {
      JSContext *cx;
  #ifdef JS_THREADSAFE
 +    JSContext *acx, *iter;
 +
      JSThread *thread = js_GetCurrentThread(rt);
  
      JS_ASSERT_IF(thread->gcPendingContext,
-@@ -940,31 +942,13 @@ JSGC::enterExclusiveGC()
+@@ -941,26 +943,13 @@ JSGC::enterExclusiveGC()
       */
      if (rt->gcKind & GC_KEEP_ATOMS)
          JS_KEEP_ATOMS(rt);
 -}
  
 -void
 -JSGC::enterExclusiveGCNoLock()
 -{
 -    JSContext *cx = rt->gcContext;
 -#ifdef JS_THREADSAFE
 -    JSContext *acx, *iter;
 -#endif
--
+ 
 -    /* Reset malloc counter. */
 -    rt->gcMallocBytes = 0;
 -
 -#ifdef JS_DUMP_SCOPE_METERS
 -  { extern void js_DumpScopeMeters(JSRuntime *rt);
 -    js_DumpScopeMeters(rt);
 -  }
 -#endif
- 
-     /*
-      * Clear property cache weak references and disable the cache so nothing
-      * can fill it during GC (this is paranoia, since scripts should not run
-      * during GC).
-      */
--    js_DisablePropertyCache(cx);
+-
+-    /* Clean property cache weak references */
++    /*
++     * Clear property cache weak references and disable the cache so nothing
++     * can fill it during GC (this is paranoia, since scripts should not run
++     * during GC).
++     */
      js_FlushPropertyCache(cx);
  
  #ifdef JS_THREADSAFE
-@@ -980,12 +964,26 @@ JSGC::enterExclusiveGCNoLock()
+@@ -976,12 +965,26 @@ JSGC::enterExclusiveGCNoLock()
          if (!acx->thread || acx->thread == cx->thread)
              continue;
          GSN_CACHE_CLEAR(&acx->thread->gsnCache);
 -        js_DisablePropertyCache(acx);
          js_FlushPropertyCache(acx);
      }
  #else
      /* The thread-unsafe case just has to clear the runtime's GSN cache. */
@@ -67,33 +67,38 @@ diff --git a/js/src/jsgc.cpp b/js/src/js
 +
 +#ifdef JS_DUMP_SCOPE_METERS
 +  { extern void js_DumpScopeMeters(JSRuntime *rt);
 +    js_DumpScopeMeters(rt);
 +  }
  #endif
  
      rt->gcNumber++;
-@@ -1002,24 +1000,6 @@ void
+@@ -998,29 +1001,6 @@ void
  void
  JSGC::leaveExclusiveGC()
  {
 -    JSContext *cx = rt->gcContext;
 -#ifdef JS_THREADSAFE
 -    JSContext *iter;
 -    JSContext *acx;
 -#endif
 -
--    if (!(rt->shapeGen & SHAPE_OVERFLOW_BIT)) {
--        js_EnablePropertyCache(cx);
+-    if (rt->shapeGen & SHAPE_OVERFLOW_BIT) {
+-        /*
+-         * FIXME bug 440834: The shape id space has overflowed. Currently we
+-         * cope badly with this. Every call to js_GenerateShape does GC, and
+-         * we never re-enable the property cache.
+-         */
+-        js_DisablePropertyCache(cx);
 -#ifdef JS_THREADSAFE
 -        iter = NULL;
 -        while ((acx = js_ContextIterator(rt, JS_FALSE, &iter)) != NULL) {
 -            if (!acx->thread || acx->thread == cx->thread)
 -                continue;
--            js_EnablePropertyCache(acx);
+-            js_DisablePropertyCache(acx);
 -        }
 -#endif
 -    }
 -
      if (rt->gcKind & GC_KEEP_ATOMS)
          JS_UNKEEP_ATOMS(rt);
      rt->gcKind = GC_NOT_RUNNING;
--- a/remove-cycle
+++ b/remove-cycle
@@ -1,15 +1,15 @@
 Get rid of the cycle collector.
 * * *
 
 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
-@@ -858,20 +858,6 @@ public:
+@@ -881,20 +881,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.
 -   *
@@ -20,17 +20,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.
     *
-@@ -1017,74 +1003,6 @@ public:
+@@ -1040,74 +1026,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
@@ -95,31 +95,31 @@ diff --git a/content/base/public/nsConte
 -   *
 -   * @param aScriptObjectHolder the object that holds JS objects that we want to
 -   *                            drop
 -   */
 -  static nsresult DropJSObjects(void* aScriptObjectHolder);
  
    /**
     * Convert nsIContent::IME_STATUS_* to nsIKBStateControll::IME_STATUS_*
-@@ -1355,13 +1273,8 @@ private:
+@@ -1385,13 +1303,8 @@ private:
    static PRUint32 sRunnersCountAtFirstBlocker;
  };
  
 -#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
+ class NS_STACK_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
 @@ -856,39 +856,11 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsIContent
  
  // Some cycle-collecting helper macros for nsIContent subclasses
  
@@ -160,16 +160,41 @@ diff --git a/content/base/public/nsICont
 +#define NS_IMPL_CYCLE_COLLECTION_TRAVERSE_LISTENERMANAGER
 +#define NS_IMPL_CYCLE_COLLECTION_TRAVERSE_PRESERVED_WRAPPER
 +#define NS_IMPL_CYCLE_COLLECTION_TRAVERSE_USERDATA
 +#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/public/nsReferencedElement.h b/content/base/public/nsReferencedElement.h
+--- a/content/base/public/nsReferencedElement.h
++++ b/content/base/public/nsReferencedElement.h
+@@ -69,7 +69,6 @@ public:
+ public:
+   nsReferencedElement() {}
+   ~nsReferencedElement() {
+-    Unlink();
+     if (mPendingNotification) {
+       mPendingNotification->Clear();
+     }
+@@ -91,13 +90,6 @@ public:
+    * value, the current element for the ID.
+    */
+   void Reset(nsIContent* aFrom, nsIURI* aURI, PRBool aWatch = PR_TRUE);
+-  /**
+-   * Clears the reference. ContentChanged is not triggered. get() will return
+-   * null.
+-   */
+-  void Unlink();
+-
+-  void Traverse(nsCycleCollectionTraversalCallback* aCB);
+   
+ protected:
+   /**
 diff --git a/content/base/src/nsContentSink.cpp b/content/base/src/nsContentSink.cpp
 --- a/content/base/src/nsContentSink.cpp
 +++ b/content/base/src/nsContentSink.cpp
 @@ -160,23 +160,6 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(
    NS_INTERFACE_MAP_ENTRY(nsITimerCallback)
    NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIScriptLoaderObserver)
  NS_INTERFACE_MAP_END
 -
@@ -190,17 +215,17 @@ diff --git a/content/base/src/nsContentS
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 -
  
  nsContentSink::nsContentSink()
  {
 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
-@@ -3269,26 +3269,6 @@ nsContentUtils::HasMutationListeners(nsI
+@@ -3245,26 +3245,6 @@ nsContentUtils::HasMutationListeners(nsI
    return PR_FALSE;
  }
  
 -/* static */
 -void
 -nsContentUtils::TraverseListenerManager(nsINode *aNode,
 -                                        nsCycleCollectionTraversalCallback &cb)
 -{
@@ -217,17 +242,17 @@ diff --git a/content/base/src/nsContentU
 -    NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "[via hash] mListenerManager");
 -    cb.NoteXPCOMChild(entry->mListenerManager);
 -  }
 -}
 -
  nsresult
  nsContentUtils::GetListenerManager(nsINode *aNode,
                                     PRBool aCreateIfNotFound,
-@@ -3786,33 +3766,6 @@ nsContentUtils::DropScriptObject(PRUint3
+@@ -3762,33 +3742,6 @@ nsContentUtils::DropScriptObject(PRUint3
    if (--sScriptRootCount[langIndex] == 0) {
      NS_RELEASE(sScriptRuntimes[langIndex]);
    }
 -}
 -
 -/* static */
 -nsresult
 -nsContentUtils::HoldJSObjects(void* aScriptObjectHolder,
@@ -314,28 +339,44 @@ diff --git a/content/base/src/nsDocument
 @@ -154,7 +154,6 @@ static NS_DEFINE_CID(kDOMEventGroupCID, 
  
  #include "nsIJSContextStack.h"
  #include "nsIXPConnect.h"
 -#include "nsCycleCollector.h"
  #include "nsCCUncollectableMarker.h"
  #include "nsIContentPolicy.h"
  
-@@ -804,10 +803,6 @@ nsDocument::~nsDocument()
+@@ -296,15 +295,6 @@ nsIdentifierMapEntry::~nsIdentifierMapEn
+   if (mNameContentList && mNameContentList != NAME_NOT_VALID) {
+     NS_RELEASE(mNameContentList);
+   }
+-}
+-
+-void
+-nsIdentifierMapEntry::Traverse(nsCycleCollectionTraversalCallback* aCallback)
+-{
+-  if (mNameContentList != NAME_NOT_VALID)
+-    aCallback->NoteXPCOMChild(mNameContentList);
+-
+-  aCallback->NoteXPCOMChild(static_cast<nsIDOMNodeList*>(mDocAllList));
+ }
+ 
+ void
+@@ -1024,10 +1014,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;
-@@ -950,173 +945,6 @@ NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUO
+@@ -1170,184 +1156,6 @@ NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUO
                                                          nsIDocument,
                                                          nsNodeUtils::LastRelease(this))
  
 -
 -PR_STATIC_CALLBACK(PLDHashOperator)
 -SubDocTraverser(PLDHashTable *table, PLDHashEntryHdr *hdr, PRUint32 number,
 -                void *arg)
 -{
@@ -388,31 +429,42 @@ diff --git a/content/base/src/nsDocument
 -public:
 -  nsCycleCollectionTraversalCallback *mCb;
 -  virtual void Visit(nsIContent* aContent)
 -  {
 -    mCb->NoteXPCOMChild(aContent);
 -  }
 -};
 -
--PLDHashOperator PR_CALLBACK
+-PR_STATIC_CALLBACK(PLDHashOperator)
 -LinkMapTraverser(nsUint32ToContentHashEntry* aEntry, void* userArg)
 -{
 -  LinkMapTraversalVisitor visitor;
 -  visitor.mCb = static_cast<nsCycleCollectionTraversalCallback*>(userArg);
 -  NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*visitor.mCb, "mLinkMap entry");
 -  aEntry->VisitContent(&visitor);
 -  return PL_DHASH_NEXT;
 -}
 -
+-PR_STATIC_CALLBACK(PLDHashOperator)
+-IdentifierMapEntryTraverse(nsIdentifierMapEntry *aEntry, void *aArg)
+-{
+-  nsCycleCollectionTraversalCallback *cb =
+-    static_cast<nsCycleCollectionTraversalCallback*>(aArg);
+-  aEntry->Traverse(cb);
+-  return PL_DHASH_NEXT;
+-}
+-
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsDocument)
 -  if (nsCCUncollectableMarker::InGeneration(tmp->GetMarkedCCGeneration())) {
 -    return NS_OK;
 -  }
 -
+-  tmp->mIdentifierMap.EnumerateEntries(IdentifierMapEntryTraverse, &cb);
+-
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mNodeInfo)
 -
 -  // Traverse the mChildren nsAttrAndChildArray.
 -  for (PRInt32 indx = PRInt32(tmp->mChildren.ChildCount()); indx > 0; --indx) {
 -    NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mChildren[i]");
 -    cb.NoteXPCOMChild(tmp->mChildren.ChildAt(indx - 1));
 -  }
 -
@@ -499,16 +551,28 @@ diff --git a/content/base/src/nsDocument
 -  // In rare cases where you think an unlink will help here, add one
 -  // manually.
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -
 -
  nsresult
  nsDocument::Init()
  {
+diff --git a/content/base/src/nsDocument.h b/content/base/src/nsDocument.h
+--- a/content/base/src/nsDocument.h
++++ b/content/base/src/nsDocument.h
+@@ -273,8 +273,6 @@ public:
+   PRBool HasContentChangeCallback() { return mChangeCallbacks != nsnull; }
+   void AddContentChangeCallback(nsIDocument::IDTargetObserver aCallback, void* aData);
+   void RemoveContentChangeCallback(nsIDocument::IDTargetObserver aCallback, void* aData);
+-
+-  void Traverse(nsCycleCollectionTraversalCallback* aCallback);
+ 
+   void SetDocAllList(nsContentList* aContentList) { mDocAllList = aContentList; }
+   nsContentList* GetDocAllList() { return mDocAllList; }
 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
 @@ -79,31 +79,6 @@ nsGenericDOMDataNode::~nsGenericDOMDataN
  }
  
  NS_IMPL_CYCLE_COLLECTION_CLASS(nsGenericDOMDataNode)
 -
@@ -551,21 +615,20 @@ diff --git a/content/base/src/nsGenericE
 -  }
 -
 -  if (mAttributeMap) {
 -    mAttributeMap->DropReference();
 -  }
  }
  
  nsGenericElement::nsGenericElement(nsINodeInfo *aNodeInfo)
-@@ -3448,103 +3441,6 @@ nsGenericElement::doRemoveChild(nsIDOMNo
- // nsISupports implementation
+@@ -3472,103 +3465,6 @@ nsGenericElement::doRemoveChild(nsIDOMNo
  
  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);
@@ -652,23 +715,24 @@ diff --git a/content/base/src/nsGenericE
 -    if (slots) {
 -      cb.NoteXPCOMChild(slots->mAttributeMap.get());
 -      if (tmp->IsNodeOfType(nsINode::eXUL))
 -        cb.NoteXPCOMChild(slots->mControllers);
 -    }
 -  }
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 -
- 
+-
  NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsGenericElement)
    NS_INTERFACE_MAP_ENTRY(nsIContent)
+   NS_INTERFACE_MAP_ENTRY(nsINode)
 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
-@@ -385,31 +385,6 @@ nsNodeUtils::CallUserDataHandlers(nsCOMA
+@@ -386,31 +386,6 @@ nsNodeUtils::CallUserDataHandlers(nsCOMA
    return NS_OK;
  }
  
 -static void
 -NoteUserData(void *aObject, nsIAtom *aKey, void *aXPCOMChild, void *aData)
 -{
 -  nsCycleCollectionTraversalCallback* cb =
 -    static_cast<nsCycleCollectionTraversalCallback*>(aData);
@@ -713,29 +777,66 @@ diff --git a/content/base/src/nsNodeUtil
 -
 -  /**
     * 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
-@@ -1323,12 +1323,6 @@ nsObjectLoadingContent::RemovedFromDocum
+@@ -1335,12 +1335,6 @@ nsObjectLoadingContent::RemovedFromDocum
    }
  }
  
 -void
 -nsObjectLoadingContent::Traverse(nsCycleCollectionTraversalCallback &cb)
 -{
 -  cb.NoteXPCOMChild(mFrameLoader);
 -}
 -
  // <private>
  /* static */ PRBool
  nsObjectLoadingContent::IsSuccessfulRequest(nsIRequest* aRequest)
+diff --git a/content/base/src/nsReferencedElement.cpp b/content/base/src/nsReferencedElement.cpp
+--- a/content/base/src/nsReferencedElement.cpp
++++ b/content/base/src/nsReferencedElement.cpp
+@@ -77,8 +77,6 @@ void
+ void
+ nsReferencedElement::Reset(nsIContent* aFromContent, nsIURI* aURI, PRBool aWatch)
+ {
+-  Unlink();
+-
+   nsCOMPtr<nsIURL> url = do_QueryInterface(aURI);
+   if (!url)
+     return;
+@@ -173,24 +171,6 @@ nsReferencedElement::Reset(nsIContent* a
+   }
+ }
+ 
+-void
+-nsReferencedElement::Traverse(nsCycleCollectionTraversalCallback* aCB)
+-{
+-  aCB->NoteXPCOMChild(mWatchDocument);
+-  aCB->NoteXPCOMChild(mContent);
+-}
+-
+-void
+-nsReferencedElement::Unlink()
+-{
+-  if (mWatchDocument && mWatchID) {
+-    mWatchDocument->RemoveIDTargetObserver(mWatchID, Observe, this);
+-  }
+-  mWatchDocument = nsnull;
+-  mWatchID = nsnull;
+-  mContent = nsnull;
+-}
+-
+ PRBool
+ nsReferencedElement::Observe(nsIContent* aOldContent,
+                              nsIContent* aNewContent, void* aData)
 diff --git a/content/base/src/nsXMLHttpRequest.cpp b/content/base/src/nsXMLHttpRequest.cpp
 --- a/content/base/src/nsXMLHttpRequest.cpp
 +++ b/content/base/src/nsXMLHttpRequest.cpp
 @@ -1663,7 +1663,7 @@ nsXMLHttpRequest::RequestCompleted()
      ChangeState(XML_HTTP_REQUEST_OPENED);
    }
  
 -  nsJSContext::MaybeCC(PR_FALSE);
@@ -800,17 +901,17 @@ diff --git a/content/events/src/nsDOMDat
 -    TraverseEntry(const nsAString& aKey, nsIVariant *aDataItem, void* aUserArg);
 -
    nsInterfaceHashtable<nsStringHashKey, nsIVariant> mData;
  };
  
 diff --git a/content/events/src/nsDOMEvent.cpp b/content/events/src/nsDOMEvent.cpp
 --- a/content/events/src/nsDOMEvent.cpp
 +++ b/content/events/src/nsDOMEvent.cpp
-@@ -155,59 +155,6 @@ NS_INTERFACE_MAP_END
+@@ -163,59 +163,6 @@ NS_INTERFACE_MAP_END
  
  NS_IMPL_CYCLE_COLLECTING_ADDREF(nsDOMEvent)
  NS_IMPL_CYCLE_COLLECTING_RELEASE(nsDOMEvent)
 -
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDOMEvent)
 -  if (tmp->mEventIsInternal) {
 -    tmp->mEvent->target = nsnull;
 -    tmp->mEvent->currentTarget = nsnull;
@@ -885,33 +986,20 @@ diff --git a/content/events/src/nsEventL
 -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
-@@ -678,66 +678,6 @@ NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOU
+@@ -678,53 +678,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)
--TraverseAccessKeyContent(nsHashKey *aKey, void *aData, void* aClosure)
--{
--  nsCycleCollectionTraversalCallback *cb =
--    static_cast<nsCycleCollectionTraversalCallback*>(aClosure);
--  nsIContent *content =
--    static_cast<nsIContent*>(aData);
--
--  cb->NoteXPCOMChild(content);
--
--  return kHashEnumerateNext;
--}
--
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsEventStateManager)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mCurrentTargetContent);
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mLastMouseOverElement);
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mGestureDownContent);
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mGestureDownFrameOwner);
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mLastLeftMouseDownContent);
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mLastMiddleMouseDownContent);
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mLastRightMouseDownContent);
@@ -1008,17 +1096,17 @@ diff --git a/content/html/content/src/ns
 -  tmp->mNameLookupTable.EnumerateRead(ControlTraverser, &cb);
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  
  // XPConnect interface list for nsFormControlList
  NS_INTERFACE_TABLE_HEAD(nsFormControlList)
 diff --git a/content/html/content/src/nsHTMLObjectElement.cpp b/content/html/content/src/nsHTMLObjectElement.cpp
 --- a/content/html/content/src/nsHTMLObjectElement.cpp
 +++ b/content/html/content/src/nsHTMLObjectElement.cpp
-@@ -158,10 +158,6 @@ nsHTMLObjectElement::DoneAddingChildren(
+@@ -168,10 +168,6 @@ nsHTMLObjectElement::DoneAddingChildren(
  }
  
  NS_IMPL_CYCLE_COLLECTION_CLASS(nsHTMLObjectElement)
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsHTMLObjectElement,
 -                                                  nsGenericHTMLFormElement)
 -  tmp->Traverse(cb);
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  
@@ -1036,43 +1124,22 @@ 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
-@@ -380,40 +380,6 @@ nsHTMLDocument::~nsHTMLDocument()
+@@ -234,19 +234,6 @@ nsHTMLDocument::nsHTMLDocument()
  }
  
  NS_IMPL_CYCLE_COLLECTION_CLASS(nsHTMLDocument)
 -
--PR_STATIC_CALLBACK(PLDHashOperator)
--IdAndNameMapEntryTraverse(PLDHashTable *table, PLDHashEntryHdr *hdr,
--                          PRUint32 number, void *arg)
--{
--  nsCycleCollectionTraversalCallback *cb =
--    static_cast<nsCycleCollectionTraversalCallback*>(arg);
--  IdAndNameMapEntry *entry = static_cast<IdAndNameMapEntry*>(hdr);
--
--  if (entry->mNameContentList != NAME_NOT_VALID)
--    cb->NoteXPCOMChild(entry->mNameContentList);
--
--  cb->NoteXPCOMChild(static_cast<nsIDOMNodeList*>(entry->mDocAllList));
--
--  return PL_DHASH_NEXT;
--}
--
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsHTMLDocument, nsDocument)
--  if (tmp->mIdAndNameHashTable.ops) {
--    PL_DHashTableEnumerate(&tmp->mIdAndNameHashTable,
--                           IdAndNameMapEntryTraverse,
--                           &cb);
--  }
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mImageMaps)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mImages)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mApplets)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mEmbeds)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mLinks)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mAnchors)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mFragmentParser)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mForms, nsIDOMNodeList)
@@ -1111,38 +1178,81 @@ diff --git a/content/html/document/src/n
 -  }
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  
  NS_IMETHODIMP
  nsHTMLFragmentContentSink::WillBuildModel(void)
 diff --git a/content/svg/content/src/nsSVGUseElement.cpp b/content/svg/content/src/nsSVGUseElement.cpp
 --- a/content/svg/content/src/nsSVGUseElement.cpp
 +++ b/content/svg/content/src/nsSVGUseElement.cpp
-@@ -61,21 +61,6 @@ NS_IMPL_NS_NEW_SVG_ELEMENT(Use)
- 
+@@ -64,21 +64,6 @@ NS_IMPL_NS_NEW_SVG_ELEMENT(Use)
  //----------------------------------------------------------------------
  // nsISupports methods
--
+ 
 -NS_IMPL_CYCLE_COLLECTION_CLASS(nsSVGUseElement)
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsSVGUseElement,
 -                                                nsSVGUseElementBase)
 -  nsAutoScriptBlocker scriptBlocker;
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOriginal)
 -  tmp->DestroyAnonymousContent();
--  tmp->RemoveListener();
+-  tmp->UnlinkSource();
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsSVGUseElement,
 -                                                  nsSVGUseElementBase)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOriginal)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mClone)
--  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mSourceContent)
+-  tmp->mSource.Traverse(&cb);
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
- 
+-
  NS_IMPL_ADDREF_INHERITED(nsSVGUseElement,nsSVGUseElementBase)
  NS_IMPL_RELEASE_INHERITED(nsSVGUseElement,nsSVGUseElementBase)
+ 
+@@ -105,7 +90,6 @@ nsSVGUseElement::nsSVGUseElement(nsINode
+ 
+ nsSVGUseElement::~nsSVGUseElement()
+ {
+-  UnlinkSource();
+ }
+ 
+ //----------------------------------------------------------------------
+@@ -232,7 +216,6 @@ void
+ void
+ nsSVGUseElement::NodeWillBeDestroyed(const nsINode *aNode)
+ {
+-  UnlinkSource();
+ }
+ 
+ //----------------------------------------------------------------------
+@@ -434,15 +417,6 @@ nsSVGUseElement::TriggerReclone()
+   presShell->PostRecreateFramesFor(this);
+ }
+ 
+-void
+-nsSVGUseElement::UnlinkSource()
+-{
+-  if (mSource.get()) {
+-    mSource.get()->RemoveMutationObserver(this);
+-  }
+-  mSource.Unlink();
+-}
+-
+ //----------------------------------------------------------------------
+ // nsSVGElement methods
+ 
+diff --git a/content/svg/content/src/nsSVGUseElement.h b/content/svg/content/src/nsSVGUseElement.h
+--- a/content/svg/content/src/nsSVGUseElement.h
++++ b/content/svg/content/src/nsSVGUseElement.h
+@@ -127,7 +127,6 @@ protected:
+   void SyncWidthHeight(PRUint8 aAttrEnum);
+   void LookupHref();
+   void TriggerReclone();
+-  void UnlinkSource();
+ 
+   enum { X, Y, WIDTH, HEIGHT };
+   nsSVGLength2 mLengthAttributes[4];
 diff --git a/content/xbl/src/nsBindingManager.cpp b/content/xbl/src/nsBindingManager.cpp
 --- a/content/xbl/src/nsBindingManager.cpp
 +++ b/content/xbl/src/nsBindingManager.cpp
 @@ -143,15 +143,6 @@ NS_INTERFACE_MAP_END
  NS_INTERFACE_MAP_END
  
  NS_IMPL_CYCLE_COLLECTION_UNLINK_0(nsAnonymousContentList)
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsAnonymousContentList)
@@ -1948,31 +2058,20 @@ diff --git a/content/xul/document/src/ns
 -  }
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  
  NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsXULControllers)
    NS_INTERFACE_MAP_ENTRY(nsIControllers)
 diff --git a/content/xul/document/src/nsXULDocument.cpp b/content/xul/document/src/nsXULDocument.cpp
 --- a/content/xul/document/src/nsXULDocument.cpp
 +++ b/content/xul/document/src/nsXULDocument.cpp
-@@ -290,73 +290,6 @@ NS_NewXULDocument(nsIXULDocument** resul
+@@ -315,60 +315,6 @@ NS_NewXULDocument(nsIXULDocument** resul
  
  NS_IMPL_CYCLE_COLLECTION_CLASS(nsXULDocument)
  
--static PRIntn
--TraverseElement(const PRUnichar* aID, nsIContent* aElement, void* aContext)
--{
--    nsCycleCollectionTraversalCallback *cb =
--        static_cast<nsCycleCollectionTraversalCallback*>(aContext);
--
--    cb->NoteXPCOMChild(aElement);
--
--    return HT_ENUMERATE_NEXT;
--}
--
 -static PLDHashOperator PR_CALLBACK
 -TraverseTemplateBuilders(nsISupports* aKey, nsIXULTemplateBuilder* aData,
 -                         void* aContext)
 -{
 -    nsCycleCollectionTraversalCallback *cb =
 -        static_cast<nsCycleCollectionTraversalCallback*>(aContext);
 -
 -    cb->NoteXPCOMChild(aKey);
@@ -1991,18 +2090,16 @@ diff --git a/content/xul/document/src/ns
 -
 -    return PL_DHASH_NEXT;
 -}
 -
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsXULDocument, nsXMLDocument)
 -    // XXX tmp->mForwardReferences?
 -    // XXX tmp->mContextStack?
 -
--    tmp->mElementMap.Enumerate(TraverseElement, &cb);
--
 -    // An element will only have a template builder as long as it's in the
 -    // document, so we'll traverse the table here instead of from the element.
 -    if (tmp->mTemplateBuilderTable)
 -        tmp->mTemplateBuilderTable->EnumerateRead(TraverseTemplateBuilders, &cb);
 -        
 -    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mCurrentPrototype,
 -                                                     nsIScriptGlobalObjectOwner)
 -    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mMasterPrototype,
@@ -2555,17 +2652,17 @@ diff --git a/dom/src/base/nsJSEnvironmen
 -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)
-@@ -3317,77 +3296,15 @@ nsJSContext::CC()
+@@ -3331,77 +3310,15 @@ nsJSContext::CC()
  nsJSContext::CC()
  {
    ++sCCollectCount;
 -#ifdef DEBUG_smaug
 -  printf("Will run cycle collector (%i), %lldms since previous.\n",
 -         sCCollectCount, (PR_Now() - sPreviousCCTime) / PR_USEC_PER_MSEC);
 -#endif
 -  sPreviousCCTime = PR_Now();
@@ -2638,37 +2735,37 @@ diff --git a/dom/src/base/nsJSEnvironmen
 -    }
 -#endif
 -  }
 -  return PR_FALSE;
 +  // add future call to NS_GetGC()->MaybeGC(true);
  }
  
  //static
-@@ -3395,7 +3312,7 @@ nsJSContext::CCIfUserInactive()
+@@ -3409,7 +3326,7 @@ nsJSContext::CCIfUserInactive()
  nsJSContext::CCIfUserInactive()
  {
    if (sUserIsActive) {
 -    MaybeCC(PR_TRUE);
 +    MaybeCC();
    } else {
      CC();
    }
-@@ -3598,10 +3515,6 @@ nsJSRuntime::Startup()
+@@ -3612,10 +3529,6 @@ nsJSRuntime::Startup()
    sCCollectCount = 0;
    sUserIsActive = PR_FALSE;
    sPreviousCCTime = 0;
 -  sCollectedObjectsCounts = 0;
 -  sGCCount = 0;
 -  sCCSuspectChanges = 0;
 -  sCCSuspectedCount = 0;
    sGCTimer = nsnull;
    sReadyForGC = PR_FALSE;
    sLoadInProgressGCTimer = PR_FALSE;
-@@ -3916,27 +3829,6 @@ nsJSArgArray::ReleaseJSObjects()
+@@ -3930,27 +3843,6 @@ nsJSArgArray::ReleaseJSObjects()
  }
  
  // QueryInterface implementation for nsJSArgArray
 -NS_IMPL_CYCLE_COLLECTION_CLASS(nsJSArgArray)
 -NS_IMPL_CYCLE_COLLECTION_ROOT_BEGIN(nsJSArgArray)
 -  tmp->ReleaseJSObjects();
 -NS_IMPL_CYCLE_COLLECTION_ROOT_END
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_0(nsJSArgArray)
@@ -4529,17 +4626,17 @@ diff --git a/layout/base/nsPresContext.c
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 -
  
  #define MAKE_FONT_PREF_KEY(_pref, _s0, _s1) \
   _pref.Assign(_s0); \
 diff --git a/layout/build/nsLayoutStatics.cpp b/layout/build/nsLayoutStatics.cpp
 --- a/layout/build/nsLayoutStatics.cpp
 +++ b/layout/build/nsLayoutStatics.cpp
-@@ -112,8 +112,6 @@ PRBool NS_SVGEnabled();
+@@ -116,8 +116,6 @@ PRBool NS_SVGEnabled();
  
  #include "nsError.h"
  #include "nsTraceRefcnt.h"
 -
 -#include "nsCycleCollector.h"
  
  static nsrefcnt sLayoutStaticRefcnt;
  
@@ -4611,17 +4708,17 @@ diff --git a/toolkit/components/places/s
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END 
 -
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsNavHistoryResultNode)
 -  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mParent, nsINavHistoryContainerResultNode);
 -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  
  NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsNavHistoryResultNode)
    NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsINavHistoryResultNode)
-@@ -3696,35 +3686,6 @@ RemoveBookmarkFolderObserversCallback(ns
+@@ -3699,35 +3689,6 @@ RemoveBookmarkFolderObserversCallback(ns
    return PL_DHASH_REMOVE;
  }
  
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsNavHistoryResult)
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mRootNode)
 -  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mView)
 -  tmp->mBookmarkFolderObservers.Enumerate(&RemoveBookmarkFolderObserversCallback, nsnull);
 -NS_IMPL_CYCLE_COLLECTION_UNLINK_END 
@@ -4824,17 +4921,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,2919 +38,21 @@
+@@ -38,2925 +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
 -//
@@ -6237,18 +6334,24 @@ diff --git a/xpcom/base/nsCycleCollector
 -{
 -#ifdef DEBUG_CC
 -    nsCString edgeName(mNextEdgeName);
 -    mNextEdgeName.Truncate();
 -#endif
 -    if (!child)
 -        return;
 -
--    if (langID > nsIProgrammingLanguage::MAX || !mRuntimes[langID]) {
--        Fault("traversing pointer for unregistered language", child);
+-    if (langID > nsIProgrammingLanguage::MAX) {
+-        Fault("traversing pointer for unknown language", child);
+-        return;
+-    }
+-
+-    if (!mRuntimes[langID]) {
+-        NS_WARNING("Not collecting cycles involving objects for scripting "
+-                   "languages that don't participate in cycle collection.");
 -        return;
 -    }
 -
 -    nsCycleCollectionParticipant *cp = mRuntimes[langID]->ToParticipant(child);
 -    if (!cp)
 -        return;
 -
 -    PtrInfo *childPi = AddNode(child, cp, langID);
--- a/root-contentutils
+++ b/root-contentutils
@@ -1,25 +1,25 @@
 Root objects that hang off contentutils in one easy object.
 * * *
 * * *
 
 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
-@@ -135,6 +135,8 @@ struct nsShortcutCandidate {
+@@ -137,6 +137,8 @@ struct nsShortcutCandidate {
  
  class nsContentUtils
  {
 +  struct LayoutRoots;
 +
  public:
    static nsresult Init();
  
-@@ -436,17 +438,17 @@ public:
+@@ -454,17 +456,17 @@ public:
  
    static nsINameSpaceManager* NameSpaceManager()
    {
 -    return sNameSpaceManager;
 +    return sLayoutRoots->sNameSpaceManager;
    }
  
    static nsIIOService* GetIOService()
@@ -30,26 +30,26 @@ diff --git a/content/base/public/nsConte
  
    static imgILoader* GetImgLoader()
    {
 -    return sImgLoader;
 +    return sLayoutRoots->sImgLoader;
    }
  
  #ifdef MOZ_XTF
-@@ -463,7 +465,7 @@ public:
+@@ -481,7 +483,7 @@ public:
     */
    static nsIScriptSecurityManager* GetSecurityManager()
    {
 -    return sSecurityManager;
 +    return sLayoutRoots->sSecurityManager;
    }
  
    static nsresult GenerateStateKey(nsIContent* aContent,
-@@ -548,22 +550,22 @@ public:
+@@ -566,27 +568,27 @@ public:
    static void AddBoolPrefVarCache(const char* aPref, PRBool* aVariable);
    static nsIPrefBranch *GetPrefBranch()
    {
 -    return sPrefBranch;
 +    return sLayoutRoots->sPrefBranch;
    }
  
    static nsILineBreaker* LineBreaker()
@@ -65,81 +65,87 @@ diff --git a/content/base/public/nsConte
    }
    
    static nsICaseConversion* GetCaseConv()
    {
 -    return sCaseConv;
 +    return sLayoutRoots->sCaseConv;
    }
  
+   static nsIUGenCategory* GetGenCat()
+   {
+-    return sGenCat;
++    return sLayoutRoots->sGenCat;
+   }
+ 
    /**
-@@ -631,7 +633,7 @@ public:
+@@ -654,7 +656,7 @@ public:
     * @param aRequest The image request [out]
     * @return the nsIImage corresponding to the first frame of the image
     */
 -  static already_AddRefed<nsIImage> GetImageFromContent(nsIImageLoadingContent* aContent, imgIRequest **aRequest = nsnull);
 +  static nsIImage* GetImageFromContent(nsIImageLoadingContent* aContent, imgIRequest **aRequest = nsnull);
  
    /**
     * Method that decides whether a content node is draggable
-@@ -715,7 +717,7 @@ public:
+@@ -738,7 +740,7 @@ public:
     */
    static nsIXPConnect *XPConnect()
    {
 -    return sXPConnect;
 +    return sLayoutRoots->sXPConnect;
    }
  
    /**
-@@ -788,11 +790,10 @@ public:
+@@ -811,11 +813,10 @@ public:
    /**
     * Release *aSupportsPtr when the shutdown notification is received
     */
 -  static nsresult ReleasePtrOnShutdown(nsISupports** aSupportsPtr) {
 -    NS_ASSERTION(aSupportsPtr, "Expect to crash!");
 -    NS_ASSERTION(*aSupportsPtr, "Expect to crash!");
 -    return sPtrsToPtrsToRelease->AppendElement(aSupportsPtr) ? NS_OK :
 -      NS_ERROR_OUT_OF_MEMORY;
 +  static nsresult RootUntilLayoutShutdown(void *aSupportsPtr) {
 +    NS_ASSERTION(aSupportsPtr, "Useless call");
 +    return sLayoutRoots->sExtraLayoutRoots.
 +      AppendElement(aSupportsPtr) ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
    }
  
    /**
-@@ -878,7 +879,7 @@ public:
+@@ -901,7 +902,7 @@ public:
  
    static PRBool IsInitialized()
    {
 -    return sInitialized;
 +    return sLayoutRoots != nsnull;
    }
  
    /**
-@@ -1132,6 +1133,10 @@ public:
+@@ -1161,6 +1162,10 @@ public:
     */
    static PRBool OfflineAppAllowed(nsIURI *aURI);
  
 +  static JSRuntime *GetJSScriptRuntime();
 +  static nsresult AddJSGCRoot(void *aPtr, const char* aName);
 +  static nsresult RemoveJSGCRoot(void *aPtr);
 +
    /**
     * Increases the count of blockers preventing scripts from running.
     * NOTE: You might want to use nsAutoScriptBlocker rather than calling
-@@ -1196,8 +1201,6 @@ public:
+@@ -1225,8 +1230,6 @@ public:
  
  private:
  
 -  static PRBool InitializeEventTable();
 -
    static nsresult doReparentContentWrapper(nsIContent *aChild,
                                             JSContext *cx,
                                             JSObject *aOldGlobal,
-@@ -1216,59 +1219,68 @@ private:
+@@ -1245,60 +1248,69 @@ private:
    static PRBool CanCallerAccess(nsIPrincipal* aSubjectPrincipal,
                                  nsIPrincipal* aPrincipal);
  
 -  static nsIDOMScriptObjectFactory *sDOMScriptObjectFactory;
 +  struct LayoutRoots : public MMgc::GCRoot
 +  {
 +    LayoutRoots() :
 +      MMgc::GCRoot(NS_GetGC()) { }
@@ -176,16 +182,17 @@ diff --git a/content/base/public/nsConte
 +    nsIStringBundleService* sStringBundleService;
 +    nsIStringBundle* sStringBundles[PropertiesFile_COUNT];
 +    nsIContentPolicy* sContentPolicyService;
  
 -  static nsINameSpaceManager *sNameSpaceManager;
 +    nsILineBreaker* sLineBreaker;
 +    nsIWordBreaker* sWordBreaker;
 +    nsICaseConversion* sCaseConv;
++    nsIUGenCategory* sGenCat;
  
 -  static nsIIOService *sIOService;
 +    // Holds pointers to nsISupports* that should be released at shutdown
 +    nsVoidArrayBase<GCAllocator> sExtraLayoutRoots;
  
 -#ifdef MOZ_XTF
 -  static nsIXTFService *sXTFService;
 +    nsIScriptRuntime* sScriptRuntimes[NS_STID_ARRAY_UBOUND];
@@ -213,16 +220,17 @@ diff --git a/content/base/public/nsConte
 -  static nsIStringBundle* sStringBundles[PropertiesFile_COUNT];
 -
 -  static nsIContentPolicy* sContentPolicyService;
 -  static PRBool sTriedToGetContentPolicy;
 -
 -  static nsILineBreaker* sLineBreaker;
 -  static nsIWordBreaker* sWordBreaker;
 -  static nsICaseConversion* sCaseConv;
+-  static nsIUGenCategory* sGenCat;
 -
 -  // Holds pointers to nsISupports* that should be released at shutdown
 -  static nsVoidArray* sPtrsToPtrsToRelease;
 -
 -  static nsIScriptRuntime* sScriptRuntimes[NS_STID_ARRAY_UBOUND];
    static PRInt32 sScriptRootCount[NS_STID_ARRAY_UBOUND];
    static PRUint32 sJSGCThingRootCount;
  
@@ -233,17 +241,17 @@ diff --git a/content/base/public/nsConte
  
 -  static PRBool sInitialized;
    static PRUint32 sScriptBlockerCount;
    static PRUint32 sRemovableScriptBlockerCount;
 -  static nsCOMArray<nsIRunnable>* sBlockedScriptRunners;
    static PRUint32 sRunnersCountAtFirstBlocker;
  };
  
-@@ -1298,37 +1310,30 @@ public:
+@@ -1328,37 +1340,30 @@ public:
    nsAutoGCRoot(jsval* aPtr, nsresult* aResult) :
      mPtr(aPtr)
    {
 -    mResult = *aResult = AddJSGCRoot(aPtr, "nsAutoGCRoot");
 +    mResult = *aResult = nsContentUtils::AddJSGCRoot(aPtr, "nsAutoGCRoot");
    }
  
    // aPtr should be the pointer to the JSObject* we want to protect
@@ -278,17 +286,17 @@ diff --git a/content/base/public/nsConte
 -  static nsIJSRuntimeService* sJSRuntimeService;
 -  static JSRuntime* sJSScriptRuntime;
  
    void* mPtr;
    nsresult mResult;
 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
-@@ -170,44 +170,12 @@ static NS_DEFINE_CID(kParserServiceCID, 
+@@ -174,45 +174,12 @@ static NS_DEFINE_CID(kParserServiceCID, 
  static NS_DEFINE_CID(kParserServiceCID, NS_PARSERSERVICE_CID);
  static NS_DEFINE_CID(kCParserCID, NS_PARSER_CID);
  
 -nsIDOMScriptObjectFactory *nsContentUtils::sDOMScriptObjectFactory = nsnull;
 -nsIXPConnect *nsContentUtils::sXPConnect;
 -nsIScriptSecurityManager *nsContentUtils::sSecurityManager;
 -nsIThreadJSContextStack *nsContentUtils::sThreadJSContextStack;
 -nsIParserService *nsContentUtils::sParserService = nsnull;
@@ -304,16 +312,17 @@ diff --git a/content/base/src/nsContentU
 -nsDataHashtable<nsISupportsHashKey, EventNameMapping, GCAllocator>* nsContentUtils::sEventTable = nsnull;
 -nsIStringBundleService *nsContentUtils::sStringBundleService;
 -nsIStringBundle *nsContentUtils::sStringBundles[PropertiesFile_COUNT];
 -nsIContentPolicy *nsContentUtils::sContentPolicyService;
 -PRBool nsContentUtils::sTriedToGetContentPolicy = PR_FALSE;
 -nsILineBreaker *nsContentUtils::sLineBreaker;
 -nsIWordBreaker *nsContentUtils::sWordBreaker;
 -nsICaseConversion *nsContentUtils::sCaseConv;
+-nsIUGenCategory *nsContentUtils::sGenCat;
 -nsVoidArray *nsContentUtils::sPtrsToPtrsToRelease;
 -nsIScriptRuntime *nsContentUtils::sScriptRuntimes[NS_STID_ARRAY_UBOUND];
 +nsContentUtils::LayoutRoots* nsContentUtils::sLayoutRoots;
  PRInt32 nsContentUtils::sScriptRootCount[NS_STID_ARRAY_UBOUND];
 -PRUint32 nsContentUtils::sJSGCThingRootCount;
 -#ifdef IBMBIDI
 -nsIBidiKeyboard *nsContentUtils::sBidiKeyboard = nsnull;
 -#endif
@@ -328,17 +337,17 @@ diff --git a/content/base/src/nsContentU
 -PRBool nsContentUtils::sInitialized = PR_FALSE;
 +PRBool nsContentUtils::sTriedToGetContentPolicy;
 +PRUint32 nsContentUtils::sScriptBlockerCount;
 +PRUint32 nsContentUtils::sRemovableScriptBlockerCount;
 +PRUint32 nsContentUtils::sRunnersCountAtFirstBlocker;
  
  static PLDHashTable sEventListenerManagersHash;
  
-@@ -254,20 +222,31 @@ nsresult
+@@ -259,20 +226,31 @@ nsresult
  nsresult
  nsContentUtils::Init()
  {
 -  if (sInitialized) {
 -    NS_WARNING("Init() called twice");
 -
 -    return NS_OK;
 -  }
@@ -366,31 +375,31 @@ diff --git a/content/base/src/nsContentU
 +  sPrefBranch = nsnull;
    CallGetService(NS_PREFSERVICE_CONTRACTID, &sPrefBranch);
  
    // It's ok to not have prefs too.
 +  sPref = nsnull;
    CallGetService(NS_PREF_CONTRACTID, &sPref);
  
    rv = NS_GetNameSpaceManager(&sNameSpaceManager);
-@@ -279,12 +258,8 @@ nsContentUtils::Init()
+@@ -284,12 +262,8 @@ nsContentUtils::Init()
    rv = CallGetService(kJSStackContractID, &sThreadJSContextStack);
    NS_ENSURE_SUCCESS(rv, rv);
  
 +  sIOService = nsnull;
    rv = CallGetService(NS_IOSERVICE_CONTRACTID, &sIOService);
 -  if (NS_FAILED(rv)) {
 -    // This makes life easier, but we can live without it.
 -
 -    sIOService = nsnull;
 -  }
  
    rv = CallGetService(NS_LBRK_CONTRACTID, &sLineBreaker);
    NS_ENSURE_SUCCESS(rv, rv);
-@@ -296,16 +271,8 @@ nsContentUtils::Init()
+@@ -304,16 +278,8 @@ nsContentUtils::Init()
    NS_ENSURE_SUCCESS(rv, rv);
  
    // Ignore failure and just don't load images
 +  sImgLoader = nsnull;
    rv = CallGetService("@mozilla.org/image/loader;1", &sImgLoader);
 -  if (NS_FAILED(rv)) {
 -    // no image loading for us.  Oh, well.
 -    sImgLoader = nsnull;
@@ -398,17 +407,17 @@ diff --git a/content/base/src/nsContentU
 -
 -  sPtrsToPtrsToRelease = new nsVoidArray();
 -  if (!sPtrsToPtrsToRelease) {
 -    return NS_ERROR_OUT_OF_MEMORY;
 -  }
  
    if (!InitializeEventTable())
      return NS_ERROR_FAILURE;
-@@ -331,18 +298,11 @@ nsContentUtils::Init()
+@@ -339,18 +305,11 @@ nsContentUtils::Init()
      }
    }
  
 -  sBlockedScriptRunners = new nsCOMArray<nsIRunnable>;
 -  NS_ENSURE_TRUE(sBlockedScriptRunners, NS_ERROR_OUT_OF_MEMORY);
 -
 -  sInitialized = PR_TRUE;
 -
@@ -422,18 +431,18 @@ diff --git a/content/base/src/nsContentU
 +  return NS_OK;
 +}
 +
 +PRBool
 +nsContentUtils::LayoutRoots::InitializeEventTable() {
    struct EventItem
    {
      nsIAtom** mAtom;
-@@ -431,21 +391,12 @@ nsContentUtils::InitializeEventTable() {
- #endif // MOZ_SVG
+@@ -461,21 +420,12 @@ nsContentUtils::InitializeEventTable() {
+ #endif //MOZ_MEDIA
    };
  
 -  sEventTable = new nsDataHashtable<nsISupportsHashKey, EventNameMapping, GCAllocator>;
 -  if (!sEventTable ||
 -      !sEventTable->Init(int(NS_ARRAY_LENGTH(eventArray) / 0.75) + 1)) {
 -    delete sEventTable;
 -    sEventTable = nsnull;
 -    return PR_FALSE;
@@ -449,17 +458,17 @@ diff --git a/content/base/src/nsContentU
 +  for (PRUint32 i = 0; i < NS_ARRAY_LENGTH(eventArray); ++i)
 +    if (!sEventTable.Put(*(eventArray[i].mAtom), eventArray[i].mValue))
        return PR_FALSE;
 -    }
 -  }
  
    return PR_TRUE;
  }
-@@ -459,30 +410,30 @@ nsContentUtils::GetParserService()
+@@ -489,30 +439,30 @@ nsContentUtils::GetParserService()
  nsContentUtils::GetParserService()
  {
    // XXX: This isn't accessed from several threads, is it?
 -  if (!sParserService) {
 +  if (!sLayoutRoots->sParserService) {
      // Lock, recheck sCachedParserService and aquire if this should be
      // safe for multiple threads.
 -    nsresult rv = CallGetService(kParserServiceCID, &sParserService);
@@ -496,17 +505,17 @@ diff --git a/content/base/src/nsContentU
 +      sLayoutRoots->sXTFService = nsnull;
 +    }
 +  }
 +
 +  return sLayoutRoots->sXTFService;
  }
  #endif
  
-@@ -490,13 +441,13 @@ nsIBidiKeyboard*
+@@ -520,13 +470,13 @@ nsIBidiKeyboard*
  nsIBidiKeyboard*
  nsContentUtils::GetBidiKeyboard()
  {
 -  if (!sBidiKeyboard) {
 -    nsresult rv = CallGetService("@mozilla.org/widget/bidikeyboard;1", &sBidiKeyboard);
 -    if (NS_FAILED(rv)) {
 -      sBidiKeyboard = nsnull;
 -    }
@@ -517,17 +526,26 @@ diff --git a/content/base/src/nsContentU
 +    if (NS_FAILED(rv)) {
 +      sLayoutRoots->sBidiKeyboard = nsnull;
 +    }
 +  }
 +  return sLayoutRoots->sBidiKeyboard;
  }
  #endif
  
-@@ -764,51 +715,13 @@ void
+@@ -733,7 +683,7 @@ nsContentUtils::IsPunctuationMarkAt(cons
+ // static
+ PRBool nsContentUtils::IsAlphanumeric(PRUint32 aChar)
+ {
+-  nsIUGenCategory::nsUGenCategory cat = sGenCat->Get(aChar);
++  nsIUGenCategory::nsUGenCategory cat = sLayoutRoots->sGenCat->Get(aChar);
+ 
+   return (cat == nsIUGenCategory::kLetter || cat == nsIUGenCategory::kNumber);
+ }
+@@ -846,52 +796,13 @@ void
  void
  nsContentUtils::Shutdown()
  {
 -  sInitialized = PR_FALSE;
 +  LayoutRoots *roots = sLayoutRoots;
 +  sLayoutRoots = nsnull;
  
    NS_HTMLParanoidFragmentSinkShutdown();
@@ -546,16 +564,17 @@ diff --git a/content/base/src/nsContentU
 -  NS_IF_RELEASE(sSecurityManager);
 -  NS_IF_RELEASE(sThreadJSContextStack);
 -  NS_IF_RELEASE(sNameSpaceManager);
 -  NS_IF_RELEASE(sParserService);
 -  NS_IF_RELEASE(sIOService);
 -  NS_IF_RELEASE(sLineBreaker);
 -  NS_IF_RELEASE(sWordBreaker);
 -  NS_IF_RELEASE(sCaseConv);
+-  NS_IF_RELEASE(sGenCat);
 -#ifdef MOZ_XTF
 -  NS_IF_RELEASE(sXTFService);
 -#endif
 -  NS_IF_RELEASE(sImgLoader);
 -  NS_IF_RELEASE(sPrefBranch);
 -  NS_IF_RELEASE(sPref);
 -#ifdef IBMBIDI
 -  NS_IF_RELEASE(sBidiKeyboard);
@@ -571,78 +590,78 @@ diff --git a/content/base/src/nsContentU
 -      NS_RELEASE(*ptrToPtr);
 -    }
 -    delete sPtrsToPtrsToRelease;
 -    sPtrsToPtrsToRelease = nsnull;
 -  }
  
    if (sEventListenerManagersHash.ops) {
      NS_ASSERTION(sEventListenerManagersHash.entryCount == 0,
-@@ -829,13 +742,10 @@ nsContentUtils::Shutdown()
+@@ -912,13 +823,10 @@ nsContentUtils::Shutdown()
      }
    }
  
 -  NS_ASSERTION(!sBlockedScriptRunners ||
 -               sBlockedScriptRunners->Count() == 0,
 +  NS_ASSERTION(roots->sBlockedScriptRunners.Count() == 0,
                 "How'd this happen?");
 -  delete sBlockedScriptRunners;
 -  sBlockedScriptRunners = nsnull;
 -
 -  nsAutoGCRoot::Shutdown();
 +
 +  delete roots;
  }
  
  // static
-@@ -845,12 +755,12 @@ nsContentUtils::IsCallerTrustedForCapabi
+@@ -928,12 +836,12 @@ nsContentUtils::IsCallerTrustedForCapabi
    // The secman really should handle UniversalXPConnect case, since that
    // should include UniversalBrowserRead... doesn't right now, though.
    PRBool hasCap;
 -  if (NS_FAILED(sSecurityManager->IsCapabilityEnabled(aCapability, &hasCap)))
 +  if (NS_FAILED(sLayoutRoots->sSecurityManager->IsCapabilityEnabled(aCapability, &hasCap)))
      return PR_FALSE;
    if (hasCap)
      return PR_TRUE;
      
 -  if (NS_FAILED(sSecurityManager->IsCapabilityEnabled("UniversalXPConnect",
 +  if (NS_FAILED(sLayoutRoots->sSecurityManager->IsCapabilityEnabled("UniversalXPConnect",
                                                        &hasCap)))
      return PR_FALSE;
    return hasCap;
-@@ -871,7 +781,7 @@ nsContentUtils::CheckSameOrigin(nsIDOMNo
+@@ -954,7 +862,7 @@ nsContentUtils::CheckSameOrigin(nsIDOMNo
    NS_PRECONDITION(aTrustedNode, "There must be a trusted node");
  
    PRBool isSystem = PR_FALSE;
 -  sSecurityManager->SubjectPrincipalIsSystem(&isSystem);
 +  sLayoutRoots->sSecurityManager->SubjectPrincipalIsSystem(&isSystem);
    if (isSystem) {
      // we're running as system, grant access to the node.
  
-@@ -881,8 +791,8 @@ nsContentUtils::CheckSameOrigin(nsIDOMNo
+@@ -964,8 +872,8 @@ nsContentUtils::CheckSameOrigin(nsIDOMNo
    /*
     * Get hold of each node's principal
     */
 -  nsCOMPtr<nsINode> trustedNode = do_QueryInterface(aTrustedNode);
 -  nsCOMPtr<nsINode> unTrustedNode = do_QueryInterface(aUnTrustedNode);
 +  nsINode* trustedNode = do_QueryInterface(aTrustedNode);
 +  nsINode* unTrustedNode = do_QueryInterface(aUnTrustedNode);
  
    // Make sure these are both real nodes
    NS_ENSURE_TRUE(trustedNode && unTrustedNode, NS_ERROR_UNEXPECTED);
-@@ -922,7 +832,7 @@ nsContentUtils::CanCallerAccess(nsIPrinc
+@@ -1005,7 +913,7 @@ nsContentUtils::CanCallerAccess(nsIPrinc
    // has either "UniversalXPConnect" (if aPrincipal is system principal) or
    // "UniversalBrowserRead" (in all other cases).
    PRBool isSystem;
 -  rv = sSecurityManager->IsSystemPrincipal(aPrincipal, &isSystem);
 +  rv = sLayoutRoots->sSecurityManager->IsSystemPrincipal(aPrincipal, &isSystem);
    isSystem = NS_FAILED(rv) || isSystem;
    const char* capability =
      NS_FAILED(rv) || isSystem ? "UniversalXPConnect" : "UniversalBrowserRead";
-@@ -933,34 +843,34 @@ nsContentUtils::CanCallerAccess(nsIPrinc
+@@ -1016,34 +924,34 @@ nsContentUtils::CanCallerAccess(nsIPrinc
  // static
  PRBool
  nsContentUtils::CanCallerAccess(nsIDOMNode *aNode)
 +{
 +  // XXXbz why not check the IsCapabilityEnabled thing up front, and not bother
 +  // with the system principal games?  But really, there should be a simpler
 +  // API here, dammit.
 +  nsIPrincipal* subjectPrincipal = nsnull;
@@ -690,17 +709,17 @@ diff --git a/content/base/src/nsContentU
 -  // with the system principal games?  But really, there should be a simpler
 -  // API here, dammit.
 -  nsCOMPtr<nsIPrincipal> subjectPrincipal;
 -  sSecurityManager->GetSubjectPrincipal(getter_AddRefs(subjectPrincipal));
 +  sLayoutRoots->sSecurityManager->GetSubjectPrincipal(getter_AddRefs(subjectPrincipal));
  
    if (!subjectPrincipal) {
      // we're running as system, grant access to the node.
-@@ -1002,17 +912,17 @@ nsContentUtils::doReparentContentWrapper
+@@ -1085,17 +993,17 @@ nsContentUtils::doReparentContentWrapper
                                           nsIDocument *aOldDocument,
                                           nsIDocument *aNewDocument)
  {
 -  nsCOMPtr<nsIXPConnectJSObjectHolder> old_wrapper;
 -
 -  nsresult rv;
 -
 -  rv = sXPConnect->ReparentWrappedNativeIfFound(cx, aOldGlobal, aNewGlobal,
@@ -715,52 +734,52 @@ diff --git a/content/base/src/nsContentU
    NS_ENSURE_SUCCESS(rv, rv);
  
    if (aOldDocument) {
 -    nsCOMPtr<nsISupports> old_ref = aOldDocument->GetReference(aNode);
 +    nsISupports* old_ref = aOldDocument->GetReference(aNode);
      if (old_ref) {
        // Transfer the reference from aOldDocument to aNewDocument
        aOldDocument->RemoveReference(aNode);
-@@ -1108,7 +1018,7 @@ nsContentUtils::GetContextAndScopes(nsID
+@@ -1191,7 +1099,7 @@ nsContentUtils::GetContextAndScopes(nsID
      return NS_OK;
    }
  
 -  NS_ENSURE_TRUE(sXPConnect, NS_ERROR_NOT_INITIALIZED);
 +  NS_ENSURE_TRUE(sLayoutRoots->sXPConnect, NS_ERROR_NOT_INITIALIZED);
  
    // Make sure to get our hands on the right scope object, since
    // GetWrappedNativeOfNativeObject doesn't call PreCreate and hence won't get
-@@ -1133,10 +1043,10 @@ nsContentUtils::GetContextAndScopes(nsID
+@@ -1216,10 +1124,10 @@ nsContentUtils::GetContextAndScopes(nsID
        // calling context, or the safe context if no caller can be
        // found.
  
 -      sThreadJSContextStack->Peek(&cx);
 +      sLayoutRoots->sThreadJSContextStack->Peek(&cx);
  
        if (!cx) {
 -        sThreadJSContextStack->GetSafeJSContext(&cx);
 +        sLayoutRoots->sThreadJSContextStack->GetSafeJSContext(&cx);
  
          if (!cx) {
            // No safe context reachable, bail.
-@@ -1174,10 +1084,10 @@ nsContentUtils::ReparentContentWrappersI
+@@ -1257,10 +1165,10 @@ nsContentUtils::ReparentContentWrappersI
      }
  
      if (!cx) {
 -      sThreadJSContextStack->Peek(&cx);
 +      sLayoutRoots->sThreadJSContextStack->Peek(&cx);
  
        if (!cx) {
 -        sThreadJSContextStack->GetSafeJSContext(&cx);
 +        sLayoutRoots->sThreadJSContextStack->GetSafeJSContext(&cx);
  
          if (!cx) {
            // Wow, this is really bad!
-@@ -1201,18 +1111,18 @@ nsContentUtils::ReparentContentWrappersI
+@@ -1284,18 +1192,18 @@ nsContentUtils::ReparentContentWrappersI
      return NS_ERROR_NOT_AVAILABLE;
    }
  
 -  return sXPConnect->ReparentScopeAwareWrappers(cx, oldScopeObj, newScopeObj);
 +  return sLayoutRoots->sXPConnect->ReparentScopeAwareWrappers(cx, oldScopeObj, newScopeObj);
  }
  
  nsIDocShell *
@@ -772,60 +791,60 @@ diff --git a/content/base/src/nsContentU
  
    if (cx) {
      nsIScriptGlobalObject *sgo = nsJSUtils::GetDynamicScriptGlobal(cx);
 -    nsCOMPtr<nsPIDOMWindow> win(do_QueryInterface(sgo));
 +    nsPIDOMWindow* win(do_QueryInterface(sgo));
  
      if (win) {
        return win->GetDocShell();
-@@ -1226,7 +1136,7 @@ nsContentUtils::GetDocumentFromCaller()
+@@ -1309,7 +1217,7 @@ nsContentUtils::GetDocumentFromCaller()
  nsContentUtils::GetDocumentFromCaller()
  {
    JSContext *cx = nsnull;
 -  sThreadJSContextStack->Peek(&cx);
 +  sLayoutRoots->sThreadJSContextStack->Peek(&cx);
  
    nsIDOMDocument *doc = nsnull;
  
-@@ -1237,7 +1147,7 @@ nsContentUtils::GetDocumentFromCaller()
+@@ -1320,7 +1228,7 @@ nsContentUtils::GetDocumentFromCaller()
        callee = ::JS_GetFrameCalleeObject(cx, fp);
      }
  
 -    nsCOMPtr<nsPIDOMWindow> win =
 +    nsPIDOMWindow* win =
        do_QueryInterface(nsJSUtils::GetStaticScriptGlobal(cx, callee));
      if (win) {
        doc = win->GetExtantDocument();
-@@ -1251,13 +1161,13 @@ nsContentUtils::GetDocumentFromContext()
+@@ -1334,13 +1242,13 @@ nsContentUtils::GetDocumentFromContext()
  nsContentUtils::GetDocumentFromContext()
  {
    JSContext *cx = nsnull;
 -  sThreadJSContextStack->Peek(&cx);
 +  sLayoutRoots->sThreadJSContextStack->Peek(&cx);
  
    if (cx) {
      nsIScriptGlobalObject *sgo = nsJSUtils::GetDynamicScriptGlobal(cx);
  
      if (sgo) {
 -      nsCOMPtr<nsPIDOMWindow> pwin = do_QueryInterface(sgo);
 +      nsPIDOMWindow* pwin = do_QueryInterface(sgo);
        if (pwin) {
          return pwin->GetExtantDocument();
        }
-@@ -1271,7 +1181,7 @@ nsContentUtils::IsCallerChrome()
+@@ -1354,7 +1262,7 @@ nsContentUtils::IsCallerChrome()
  nsContentUtils::IsCallerChrome()
  {
    PRBool is_caller_chrome = PR_FALSE;
 -  nsresult rv = sSecurityManager->SubjectPrincipalIsSystem(&is_caller_chrome);
 +  nsresult rv = sLayoutRoots->sSecurityManager->SubjectPrincipalIsSystem(&is_caller_chrome);
    if (NS_FAILED(rv)) {
      return PR_FALSE;
    }
-@@ -1316,13 +1226,13 @@ nsContentUtils::GetAncestors(nsIDOMNode*
+@@ -1399,13 +1307,13 @@ nsContentUtils::GetAncestors(nsIDOMNode*
  {
    NS_ENSURE_ARG_POINTER(aNode);
  
 -  nsCOMPtr<nsIDOMNode> node(aNode);
 -  nsCOMPtr<nsIDOMNode> ancestor;
 -
 -  do {
 -    aArray->AppendElement(node.get());
@@ -836,176 +855,176 @@ diff --git a/content/base/src/nsContentU
 +
 +  do {
 +    aArray->AppendElement(node);
 +    node->GetParentNode(&ancestor);
 +    swap(node, ancestor);
    } while (node);
  
    return NS_OK;
-@@ -1337,7 +1247,7 @@ nsContentUtils::GetAncestorsAndOffsets(n
+@@ -1420,7 +1328,7 @@ nsContentUtils::GetAncestorsAndOffsets(n
  {
    NS_ENSURE_ARG_POINTER(aNode);
  
 -  nsCOMPtr<nsIContent> content(do_QueryInterface(aNode));
 +  nsIContent* content(do_QueryInterface(aNode));
  
    if (!content) {
      return NS_ERROR_FAILURE;
-@@ -1354,7 +1264,7 @@ nsContentUtils::GetAncestorsAndOffsets(n
+@@ -1437,7 +1345,7 @@ nsContentUtils::GetAncestorsAndOffsets(n
    }
  
    // insert the node itself
 -  aAncestorNodes->AppendElement(content.get());
 +  aAncestorNodes->AppendElement(content);
    aAncestorOffsets->AppendElement(NS_INT32_TO_PTR(aOffset));
  
    // insert all the ancestors
-@@ -1378,8 +1288,8 @@ nsContentUtils::GetCommonAncestor(nsIDOM
+@@ -1461,8 +1369,8 @@ nsContentUtils::GetCommonAncestor(nsIDOM
  {
    *aCommonAncestor = nsnull;
  
 -  nsCOMPtr<nsINode> node1 = do_QueryInterface(aNode);
 -  nsCOMPtr<nsINode> node2 = do_QueryInterface(aOther);
 +  nsINode* node1 = do_QueryInterface(aNode);
 +  nsINode* node2 = do_QueryInterface(aOther);
  
    NS_ENSURE_TRUE(node1 && node2, NS_ERROR_UNEXPECTED);
  
-@@ -1626,8 +1536,8 @@ nsContentUtils::FindFirstChildWithResolv
+@@ -1709,8 +1617,8 @@ nsContentUtils::FindFirstChildWithResolv
    }
  
    // now look for children in XBL
 -  nsCOMPtr<nsIDOMNodeList> children;
 -  bindingManager->GetXBLChildNodesFor(aParent, getter_AddRefs(children));
 +  nsIDOMNodeList* children = nsnull;
 +  bindingManager->GetXBLChildNodesFor(aParent, &children);
    if (!children) {
      return nsnull;
    }
-@@ -1635,9 +1545,9 @@ nsContentUtils::FindFirstChildWithResolv
+@@ -1718,9 +1626,9 @@ nsContentUtils::FindFirstChildWithResolv
    PRUint32 length;
    children->GetLength(&length);
    for (i = 0; i < length; i++) {
 -    nsCOMPtr<nsIDOMNode> childNode;
 -    children->Item(i, getter_AddRefs(childNode));
 -    nsCOMPtr<nsIContent> childContent = do_QueryInterface(childNode);
 +    nsIDOMNode* childNode = nsnull;
 +    children->Item(i, &childNode);
 +    nsIContent* childContent = do_QueryInterface(childNode);
      nsIAtom* tag = bindingManager->ResolveTag(childContent, &namespaceID);
      if (tag == aTag && namespaceID == aNamespace) {
        return childContent;
-@@ -1812,12 +1722,12 @@ nsContentUtils::GenerateStateKey(nsICont
+@@ -1895,12 +1803,12 @@ nsContentUtils::GenerateStateKey(nsICont
      return NS_OK;
    }
  
 -  nsCOMPtr<nsIDOMElement> element(do_QueryInterface(aContent));
 +  nsIDOMElement* element(do_QueryInterface(aContent));
    if (element && IsAutocompleteOff(element)) {
      return NS_OK;
    }
  
 -  nsCOMPtr<nsIHTMLDocument> htmlDocument(do_QueryInterface(aContent->GetCurrentDoc()));
 +  nsIHTMLDocument* htmlDocument(do_QueryInterface(aContent->GetCurrentDoc()));
  
    KeyAppendInt(partID, aKey);  // first append a partID
    // Make sure we can't possibly collide with an nsIStatefulFrame
-@@ -1848,7 +1758,7 @@ nsContentUtils::GenerateStateKey(nsICont
+@@ -1931,7 +1839,7 @@ nsContentUtils::GenerateStateKey(nsICont
      // XXX We don't need to use index if name is there
      // XXXbz We don't?  Why not?  I don't follow.
      //
 -    nsCOMPtr<nsIFormControl> control(do_QueryInterface(aContent));
 +    nsIFormControl* control(do_QueryInterface(aContent));
      if (control && htmlFormControls && htmlForms) {
  
        // Append the control type
-@@ -1856,8 +1766,8 @@ nsContentUtils::GenerateStateKey(nsICont
+@@ -1939,8 +1847,8 @@ nsContentUtils::GenerateStateKey(nsICont
  
        // If in a form, add form name / index of form / index in form
        PRInt32 index = -1;
 -      nsCOMPtr<nsIDOMHTMLFormElement> formElement;
 -      control->GetForm(getter_AddRefs(formElement));
 +      nsIDOMHTMLFormElement* formElement = nsnull;
 +      control->GetForm(&formElement);
        if (formElement) {
  
          if (IsAutocompleteOff(formElement)) {
-@@ -1868,7 +1778,7 @@ nsContentUtils::GenerateStateKey(nsICont
+@@ -1951,7 +1859,7 @@ nsContentUtils::GenerateStateKey(nsICont
          KeyAppendString(NS_LITERAL_CSTRING("f"), aKey);
  
          // Append the index of the form in the document
 -        nsCOMPtr<nsIContent> formContent(do_QueryInterface(formElement));
 +        nsIContent* formContent(do_QueryInterface(formElement));
          index = htmlForms->IndexOf(formContent, PR_FALSE);
          if (index <= -1) {
            //
-@@ -1884,7 +1794,7 @@ nsContentUtils::GenerateStateKey(nsICont
+@@ -1967,7 +1875,7 @@ nsContentUtils::GenerateStateKey(nsICont
            KeyAppendInt(index, aKey);
  
            // Append the index of the control in the form
 -          nsCOMPtr<nsIForm> form(do_QueryInterface(formElement));
 +          nsIForm* form(do_QueryInterface(formElement));
            form->IndexOfControl(control, &index);
  
            if (index > -1) {
-@@ -1955,7 +1865,7 @@ nsContentUtils::NewURIWithDocumentCharse
+@@ -2038,7 +1946,7 @@ nsContentUtils::NewURIWithDocumentCharse
  {
    return NS_NewURI(aResult, aSpec,
                     aDocument ? aDocument->GetDocumentCharacterSet().get() : nsnull,
 -                   aBaseURI, sIOService);
 +                   aBaseURI, sLayoutRoots->sIOService);
  }
  
  // static
-@@ -1966,7 +1876,7 @@ nsContentUtils::BelongsInForm(nsIDOMHTML
+@@ -2049,7 +1957,7 @@ nsContentUtils::BelongsInForm(nsIDOMHTML
    NS_PRECONDITION(aForm, "Must have a form");
    NS_PRECONDITION(aContent, "Must have a content node");
  
 -  nsCOMPtr<nsIContent> form(do_QueryInterface(aForm));
 +  nsIContent* form(do_QueryInterface(aForm));
  
    if (!form) {
      NS_ERROR("This should not happen, form is not an nsIContent!");
-@@ -2088,7 +1998,7 @@ nsContentUtils::LookupNamespaceURI(nsICo
+@@ -2171,7 +2079,7 @@ nsContentUtils::LookupNamespaceURI(nsICo
      return NS_OK;
    }
  
 -  nsCOMPtr<nsIAtom> name;
 +  nsIAtom* name = nsnull;
    if (!aNamespacePrefix.IsEmpty()) {
      name = do_GetAtom(aNamespacePrefix);
      NS_ENSURE_TRUE(name, NS_ERROR_OUT_OF_MEMORY);
-@@ -2122,12 +2032,12 @@ nsContentUtils::GetNodeInfoFromQName(con
+@@ -2205,12 +2113,12 @@ nsContentUtils::GetNodeInfoFromQName(con
    NS_ENSURE_SUCCESS(rv, rv);
  
    PRInt32 nsID;
 -  sNameSpaceManager->RegisterNameSpace(aNamespaceURI, nsID);
 +  sLayoutRoots->sNameSpaceManager->RegisterNameSpace(aNamespaceURI, nsID);
    if (colon) {
      const PRUnichar* end;
      qName.EndReading(end);
  
 -    nsCOMPtr<nsIAtom> prefix = do_GetAtom(Substring(qName.get(), colon));
 +    nsIAtom* prefix = do_GetAtom(Substring(qName.get(), colon));
  
      rv = aNodeInfoManager->GetNodeInfo(Substring(colon + 1, end), prefix,
                                         nsID, aNodeInfo);
-@@ -2175,8 +2085,8 @@ nsContentUtils::SplitExpatName(const PRU
+@@ -2258,8 +2166,8 @@ nsContentUtils::SplitExpatName(const PRU
  
    const PRUnichar *nameStart;
    if (uriEnd) {
 -    if (sNameSpaceManager) {
 -      sNameSpaceManager->RegisterNameSpace(nsDependentSubstring(aExpatName,
 +    if (sLayoutRoots->sNameSpaceManager) {
 +      sLayoutRoots->sNameSpaceManager->RegisterNameSpace(nsDependentSubstring(aExpatName,
                                                                  uriEnd),
                                             *aNameSpaceID);
      }
-@@ -2235,15 +2145,15 @@ nsContentUtils::CanLoadImage(nsIURI* aUR
+@@ -2318,15 +2226,15 @@ nsContentUtils::CanLoadImage(nsIURI* aUR
    PRUint32 appType = nsIDocShell::APP_TYPE_UNKNOWN;
  
    {
 -    nsCOMPtr<nsISupports> container = aLoadingDocument->GetContainer();
 -    nsCOMPtr<nsIDocShellTreeItem> docShellTreeItem =
 +    nsISupports* container = aLoadingDocument->GetContainer();
 +    nsIDocShellTreeItem* docShellTreeItem =
        do_QueryInterface(container);
@@ -1017,68 +1036,68 @@ diff --git a/content/base/src/nsContentU
 -      nsCOMPtr<nsIDocShell> docShell(do_QueryInterface(root));
 +      nsIDocShellTreeItem* root = nsnull;
 +      docShellTreeItem->GetRootTreeItem(&root);
 +
 +      nsIDocShell* docShell(do_QueryInterface(root));
  
        if (!docShell || NS_FAILED(docShell->GetAppType(&appType))) {
          appType = nsIDocShell::APP_TYPE_UNKNOWN;
-@@ -2255,7 +2165,7 @@ nsContentUtils::CanLoadImage(nsIURI* aUR
+@@ -2338,7 +2246,7 @@ nsContentUtils::CanLoadImage(nsIURI* aUR
      // Editor apps get special treatment here, editors can load images
      // from anywhere.  This allows editor to insert images from file://
      // into documents that are being edited.
 -    rv = sSecurityManager->
 +    rv = sLayoutRoots->sSecurityManager->
        CheckLoadURIWithPrincipal(aLoadingPrincipal, aURI,
                                  nsIScriptSecurityManager::ALLOW_CHROME);
      if (NS_FAILED(rv)) {
-@@ -2278,7 +2188,7 @@ nsContentUtils::CanLoadImage(nsIURI* aUR
+@@ -2361,7 +2269,7 @@ nsContentUtils::CanLoadImage(nsIURI* aUR
                                   nsnull,         //extra
                                   &decision,
                                   GetContentPolicy(),
 -                                 sSecurityManager);
 +                                 sLayoutRoots->sSecurityManager);
  
    if (aImageBlockingStatus) {
      *aImageBlockingStatus =
-@@ -2299,12 +2209,12 @@ nsContentUtils::LoadImage(nsIURI* aURI, 
+@@ -2382,12 +2290,12 @@ nsContentUtils::LoadImage(nsIURI* aURI, 
    NS_PRECONDITION(aLoadingPrincipal, "Must have a principal");
    NS_PRECONDITION(aRequest, "Null out param");
  
 -  if (!sImgLoader) {
 +  if (!sLayoutRoots->sImgLoader) {
      // nothing we can do here
      return NS_OK;
    }
  
 -  nsCOMPtr<nsILoadGroup> loadGroup = aLoadingDocument->GetDocumentLoadGroup();
 +  nsILoadGroup* loadGroup = aLoadingDocument->GetDocumentLoadGroup();
    NS_ASSERTION(loadGroup, "Could not get loadgroup; onload may fire too early");
  
    nsIURI *documentURI = aLoadingDocument->GetDocumentURI();
-@@ -2317,7 +2227,7 @@ nsContentUtils::LoadImage(nsIURI* aURI, 
+@@ -2400,7 +2308,7 @@ nsContentUtils::LoadImage(nsIURI* aURI, 
  
    // XXXbz using "documentURI" for the initialDocumentURI is not quite
    // right, but the best we can do here...
 -  return sImgLoader->LoadImage(aURI,                 /* uri to load */
 +  return sLayoutRoots->sImgLoader->LoadImage(aURI,                 /* uri to load */
                                 documentURI,          /* initialDocumentURI */
                                 aReferrer,            /* referrer */
                                 loadGroup,            /* loadgroup */
-@@ -2330,7 +2240,7 @@ nsContentUtils::LoadImage(nsIURI* aURI, 
+@@ -2413,7 +2321,7 @@ nsContentUtils::LoadImage(nsIURI* aURI, 
  }
  
  // static
 -already_AddRefed<nsIImage>
 +nsIImage*
  nsContentUtils::GetImageFromContent(nsIImageLoadingContent* aContent,
                                      imgIRequest **aRequest)
  {
-@@ -2340,39 +2250,39 @@ nsContentUtils::GetImageFromContent(nsII
+@@ -2423,39 +2331,39 @@ nsContentUtils::GetImageFromContent(nsII
  
    NS_ENSURE_TRUE(aContent, nsnull);
  
 -  nsCOMPtr<imgIRequest> imgRequest;
 +  imgIRequest* imgRequest = nsnull;
    aContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
 -                      getter_AddRefs(imgRequest));
 +                      &imgRequest);
@@ -1117,17 +1136,17 @@ diff --git a/content/base/src/nsContentU
    }
  
    nsIImage* image = nsnull;
 -  CallGetInterface(ir.get(), &image);
 +  CallGetInterface(ir, &image);
    return image;
  }
  
-@@ -2382,14 +2292,14 @@ nsContentUtils::IsDraggableImage(nsICont
+@@ -2465,14 +2373,14 @@ nsContentUtils::IsDraggableImage(nsICont
  {
    NS_PRECONDITION(aContent, "Must have content node to test");
  
 -  nsCOMPtr<nsIImageLoadingContent> imageContent(do_QueryInterface(aContent));
 +  nsIImageLoadingContent* imageContent(do_QueryInterface(aContent));
    if (!imageContent) {
      return PR_FALSE;
    }
@@ -1135,135 +1154,135 @@ diff --git a/content/base/src/nsContentU
 -  nsCOMPtr<imgIRequest> imgRequest;
 +  imgIRequest* imgRequest = nsnull;
    imageContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
 -                           getter_AddRefs(imgRequest));
 +                           &imgRequest);
  
    // XXXbz It may be draggable even if the request resulted in an error.  Why?
    // Not sure; that's what the old nsContentAreaDragDrop/nsFrame code did.
-@@ -2399,8 +2309,8 @@ nsContentUtils::IsDraggableImage(nsICont
+@@ -2482,8 +2390,8 @@ nsContentUtils::IsDraggableImage(nsICont
  // static
  PRBool
  nsContentUtils::IsDraggableLink(nsIContent* aContent) {
 -  nsCOMPtr<nsIURI> absURI;
 -  return aContent->IsLink(getter_AddRefs(absURI));
 +  nsIURI* absURI = nsnull;
 +  return aContent->IsLink(&absURI);
  }
  
  // static
-@@ -2409,8 +2319,8 @@ nsContentUtils::GetCharPref(const char *
+@@ -2492,8 +2400,8 @@ nsContentUtils::GetCharPref(const char *
  {
    nsAdoptingCString result;
  
 -  if (sPrefBranch) {
 -    sPrefBranch->GetCharPref(aPref, getter_Copies(result));
 +  if (sLayoutRoots->sPrefBranch) {
 +    sLayoutRoots->sPrefBranch->GetCharPref(aPref, getter_Copies(result));
    }
  
    return result;
-@@ -2422,8 +2332,8 @@ nsContentUtils::GetBoolPref(const char *
+@@ -2505,8 +2413,8 @@ nsContentUtils::GetBoolPref(const char *
  {
    PRBool result;
  
 -  if (!sPrefBranch ||
 -      NS_FAILED(sPrefBranch->GetBoolPref(aPref, &result))) {
 +  if (!sLayoutRoots->sPrefBranch ||
 +      NS_FAILED(sLayoutRoots->sPrefBranch->GetBoolPref(aPref, &result))) {
      result = aDefault;
    }
  
-@@ -2436,8 +2346,8 @@ nsContentUtils::GetIntPref(const char *a
+@@ -2519,8 +2427,8 @@ nsContentUtils::GetIntPref(const char *a
  {
    PRInt32 result;
  
 -  if (!sPrefBranch ||
 -      NS_FAILED(sPrefBranch->GetIntPref(aPref, &result))) {
 +  if (!sLayoutRoots->sPrefBranch ||
 +      NS_FAILED(sLayoutRoots->sPrefBranch->GetIntPref(aPref, &result))) {
      result = aDefault;
    }
  
-@@ -2450,10 +2360,10 @@ nsContentUtils::GetLocalizedStringPref(c
+@@ -2533,10 +2441,10 @@ nsContentUtils::GetLocalizedStringPref(c
  {
    nsAdoptingString result;
  
 -  if (sPrefBranch) {
 -    nsCOMPtr<nsIPrefLocalizedString> prefLocalString;
 -    sPrefBranch->GetComplexValue(aPref, NS_GET_IID(nsIPrefLocalizedString),
 -                                 getter_AddRefs(prefLocalString));
 +  if (sLayoutRoots->sPrefBranch) {
 +    nsIPrefLocalizedString* prefLocalString = nsnull;
 +    sLayoutRoots->sPrefBranch->GetComplexValue(aPref, NS_GET_IID(nsIPrefLocalizedString),
 +                                 (void**)&prefLocalString);
      if (prefLocalString) {
        prefLocalString->GetData(getter_Copies(result));
      }
-@@ -2468,10 +2378,10 @@ nsContentUtils::GetStringPref(const char
+@@ -2551,10 +2459,10 @@ nsContentUtils::GetStringPref(const char
  {
    nsAdoptingString result;
  
 -  if (sPrefBranch) {
 -    nsCOMPtr<nsISupportsString> theString;
 -    sPrefBranch->GetComplexValue(aPref, NS_GET_IID(nsISupportsString),
 -                                 getter_AddRefs(theString));
 +  if (sLayoutRoots->sPrefBranch) {
 +    nsISupportsString* theString = nsnull;
 +    sLayoutRoots->sPrefBranch->GetComplexValue(aPref, NS_GET_IID(nsISupportsString),
 +                                 (void**)&theString);
      if (theString) {
        theString->ToString(getter_Copies(result));
      }
-@@ -2486,8 +2396,8 @@ nsContentUtils::RegisterPrefCallback(con
+@@ -2569,8 +2477,8 @@ nsContentUtils::RegisterPrefCallback(con
                                       PrefChangedFunc aCallback,
                                       void * aClosure)
  {
 -  if (sPref)
 -    sPref->RegisterCallback(aPref, aCallback, aClosure);
 +  if (sLayoutRoots->sPref)
 +    sLayoutRoots->sPref->RegisterCallback(aPref, aCallback, aClosure);
  }
  
  // static
-@@ -2496,8 +2406,8 @@ nsContentUtils::UnregisterPrefCallback(c
+@@ -2579,8 +2487,8 @@ nsContentUtils::UnregisterPrefCallback(c
                                         PrefChangedFunc aCallback,
                                         void * aClosure)
  {
 -  if (sPref)
 -    sPref->UnregisterCallback(aPref, aCallback, aClosure);
 +  if (sLayoutRoots->sPref)
 +    sLayoutRoots->sPref->UnregisterCallback(aPref, aCallback, aClosure);
  }
  
  static int PR_CALLBACK
-@@ -2567,7 +2477,7 @@ IsContextOnStack(nsIJSContextStack *aSta
+@@ -2650,7 +2558,7 @@ IsContextOnStack(nsIJSContextStack *aSta
    if (ctx == aContext)
      return PR_TRUE;
  
 -  nsCOMPtr<nsIJSContextStackIterator>
 +  nsIJSContextStackIterator*
      iterator(do_CreateInstance("@mozilla.org/js/xpc/ContextStackIterator;1"));
    NS_ENSURE_TRUE(iterator, PR_FALSE);
  
-@@ -2599,9 +2509,9 @@ nsCxPusher::Push(nsISupports *aCurrentTa
+@@ -2682,9 +2590,9 @@ nsCxPusher::Push(nsISupports *aCurrentTa
      return PR_FALSE;
    }
  
 -  nsCOMPtr<nsIScriptGlobalObject> sgo;
 -  nsCOMPtr<nsINode> node(do_QueryInterface(aCurrentTarget));
 -  nsCOMPtr<nsIDocument> document;
 +  nsIScriptGlobalObject* sgo = nsnull;
 +  nsINode* node(do_QueryInterface(aCurrentTarget));
 +  nsIDocument* document = nsnull;
  
    if (node) {
      document = node->GetOwnerDoc();
-@@ -2715,17 +2625,17 @@ static const char gPropertiesFiles[nsCon
+@@ -2798,17 +2706,17 @@ static const char gPropertiesFiles[nsCon
  /* static */ nsresult
  nsContentUtils::EnsureStringBundle(PropertiesFile aFile)
  {
 -  if (!sStringBundles[aFile]) {
 -    if (!sStringBundleService) {
 +  if (!sLayoutRoots->sStringBundles[aFile]) {
 +    if (!sLayoutRoots->sStringBundleService) {
        nsresult rv =
@@ -1277,75 +1296,75 @@ diff --git a/content/base/src/nsContentU
 -    NS_ENSURE_SUCCESS(rv, rv);
 -    sStringBundles[aFile] = bundle; // transfer ownership
 +      sLayoutRoots->sStringBundleService->CreateBundle(gPropertiesFiles[aFile], &bundle);
 +    NS_ENSURE_SUCCESS(rv, rv);
 +    sLayoutRoots->sStringBundles[aFile] = bundle; // transfer ownership
    }
    return NS_OK;
  }
-@@ -2737,7 +2647,7 @@ nsresult nsContentUtils::GetLocalizedStr
+@@ -2820,7 +2728,7 @@ nsresult nsContentUtils::GetLocalizedStr
  {
    nsresult rv = EnsureStringBundle(aFile);
    NS_ENSURE_SUCCESS(rv, rv);
 -  nsIStringBundle *bundle = sStringBundles[aFile];
 +  nsIStringBundle *bundle = sLayoutRoots->sStringBundles[aFile];
  
    return bundle->GetStringFromName(NS_ConvertASCIItoUTF16(aKey).get(),
                                     getter_Copies(aResult));
-@@ -2752,7 +2662,7 @@ nsresult nsContentUtils::FormatLocalized
+@@ -2835,7 +2743,7 @@ nsresult nsContentUtils::FormatLocalized
  {
    nsresult rv = EnsureStringBundle(aFile);
    NS_ENSURE_SUCCESS(rv, rv);
 -  nsIStringBundle *bundle = sStringBundles[aFile];
 +  nsIStringBundle *bundle = sLayoutRoots->sStringBundles[aFile];
  
    return bundle->FormatStringFromName(NS_ConvertASCIItoUTF16(aKey).get(),
                                        aParams, aParamsLength,
-@@ -2776,8 +2686,8 @@ nsContentUtils::ReportToConsole(Properti
+@@ -2859,8 +2767,8 @@ nsContentUtils::ReportToConsole(Properti
                 "parameters and 0.");
  
    nsresult rv;
 -  if (!sConsoleService) { // only need to bother null-checking here
 -    rv = CallGetService(NS_CONSOLESERVICE_CONTRACTID, &sConsoleService);
 +  if (!sLayoutRoots->sConsoleService) { // only need to bother null-checking here
 +    rv = CallGetService(NS_CONSOLESERVICE_CONTRACTID, &sLayoutRoots->sConsoleService);
      NS_ENSURE_SUCCESS(rv, rv);
    }
  
-@@ -2795,7 +2705,7 @@ nsContentUtils::ReportToConsole(Properti
+@@ -2878,7 +2786,7 @@ nsContentUtils::ReportToConsole(Properti
    if (aURI)
      aURI->GetSpec(spec);
  
 -  nsCOMPtr<nsIScriptError> errorObject =
 +  nsIScriptError* errorObject =
        do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = errorObject->Init(errorText.get(),
-@@ -2805,7 +2715,7 @@ nsContentUtils::ReportToConsole(Properti
+@@ -2888,7 +2796,7 @@ nsContentUtils::ReportToConsole(Properti
                           aErrorFlags, aCategory);
    NS_ENSURE_SUCCESS(rv, rv);
  
 -  return sConsoleService->LogMessage(errorObject);
 +  return sLayoutRoots->sConsoleService->LogMessage(errorObject);
  }
  
  PRBool
-@@ -2815,8 +2725,8 @@ nsContentUtils::IsChromeDoc(nsIDocument 
+@@ -2898,8 +2806,8 @@ nsContentUtils::IsChromeDoc(nsIDocument 
      return PR_FALSE;
    }
    
 -  nsCOMPtr<nsIPrincipal> systemPrincipal;
 -  sSecurityManager->GetSystemPrincipal(getter_AddRefs(systemPrincipal));
 +  nsIPrincipal* systemPrincipal = nsnull;
 +  sLayoutRoots->sSecurityManager->GetSystemPrincipal(&systemPrincipal);
  
    return aDocument->NodePrincipal() == systemPrincipal;
  }
-@@ -2847,33 +2757,44 @@ nsContentUtils::GetContentPolicy()
+@@ -2930,33 +2838,44 @@ nsContentUtils::GetContentPolicy()
  nsContentUtils::GetContentPolicy()
  {
    if (!sTriedToGetContentPolicy) {
 -    CallGetService(NS_CONTENTPOLICY_CONTRACTID, &sContentPolicyService);
 +    CallGetService(NS_CONTENTPOLICY_CONTRACTID, &sLayoutRoots->sContentPolicyService);
      // It's OK to not have a content policy service
      sTriedToGetContentPolicy = PR_TRUE;
    }
@@ -1400,17 +1419,17 @@ diff --git a/content/base/src/nsContentU
 +    return NS_ERROR_FAILURE;
  
    PRBool ok;
 -  ok = ::JS_AddNamedRootRT(sJSScriptRuntime, aPtr, aName);
 +  ok = ::JS_AddNamedRootRT(rt, aPtr, aName);
    if (!ok) {
      NS_WARNING("JS_AddNamedRootRT failed");
      return NS_ERROR_OUT_OF_MEMORY;
-@@ -2884,14 +2805,12 @@ nsAutoGCRoot::AddJSGCRoot(void* aPtr, co
+@@ -2967,14 +2886,12 @@ nsAutoGCRoot::AddJSGCRoot(void* aPtr, co
  
  /* static */
  nsresult
 -nsAutoGCRoot::RemoveJSGCRoot(void* aPtr)
 -{
 -  if (!sJSScriptRuntime) {
 -    NS_NOTREACHED("Trying to remove a JS GC root when none were added");
 -    return NS_ERROR_UNEXPECTED;
@@ -1421,35 +1440,35 @@ diff --git a/content/base/src/nsContentU
 +{
 +  JSRuntime *rt = GetJSScriptRuntime();
 +  NS_ASSERTION(rt, "Removing a JSGC root when none were added?");
 +
 +  ::JS_RemoveRootRT(rt, aPtr);
  
    return NS_OK;
  }
-@@ -2906,7 +2825,7 @@ nsContentUtils::IsEventAttributeName(nsI
+@@ -2989,7 +2906,7 @@ nsContentUtils::IsEventAttributeName(nsI
      return PR_FALSE;
  
    EventNameMapping mapping;
 -  return (sEventTable->Get(aName, &mapping) && mapping.mType & aType);
 +  return (sLayoutRoots->sEventTable.Get(aName, &mapping) && mapping.mType & aType);
  }
  
  // static
-@@ -2914,7 +2833,7 @@ nsContentUtils::GetEventId(nsIAtom* aNam
+@@ -2997,7 +2914,7 @@ nsContentUtils::GetEventId(nsIAtom* aNam
  nsContentUtils::GetEventId(nsIAtom* aName)
  {
    EventNameMapping mapping;
 -  if (sEventTable->Get(aName, &mapping))
 +  if (sLayoutRoots->sEventTable.Get(aName, &mapping))
      return mapping.mId;
  
    return NS_USER_DEFINED_EVENT;
-@@ -2927,16 +2846,16 @@ nsContentUtils::DispatchTrustedEvent(nsI
+@@ -3010,16 +2927,16 @@ nsContentUtils::DispatchTrustedEvent(nsI
                                       PRBool aCanBubble, PRBool aCancelable,
                                       PRBool *aDefaultAction)
  {
 -  nsCOMPtr<nsIDOMDocumentEvent> docEvent(do_QueryInterface(aDoc));
 -  nsCOMPtr<nsIDOMEventTarget> target(do_QueryInterface(aTarget));
 +  nsIDOMDocumentEvent* docEvent(do_QueryInterface(aDoc));
 +  nsIDOMEventTarget* target(do_QueryInterface(aTarget));
    NS_ENSURE_TRUE(docEvent && target, NS_ERROR_INVALID_ARG);
@@ -1463,26 +1482,26 @@ diff --git a/content/base/src/nsContentU
 -  nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(event));
 +    docEvent->CreateEvent(NS_LITERAL_STRING("Events"), &event);
 +  NS_ENSURE_SUCCESS(rv, rv);
 +
 +  nsIPrivateDOMEvent* privateEvent(do_QueryInterface(event));
    NS_ENSURE_TRUE(privateEvent, NS_ERROR_FAILURE);
  
    rv = event->InitEvent(aEventName, aCanBubble, aCancelable);
-@@ -2976,7 +2895,7 @@ nsContentUtils::MatchElementId(nsIConten
+@@ -3059,7 +2976,7 @@ nsContentUtils::MatchElementId(nsIConten
    NS_PRECONDITION(!aId.IsEmpty(), "Will match random elements");
    
    // ID attrs are generally stored as atoms, so just atomize this up front
 -  nsCOMPtr<nsIAtom> id(do_GetAtom(aId));
 +  nsIAtom* id(do_GetAtom(aId));
    if (!id) {
      // OOM, so just bail
      return nsnull;
-@@ -2999,14 +2918,14 @@ nsContentUtils::ConvertStringFromCharset
+@@ -3082,14 +2999,14 @@ nsContentUtils::ConvertStringFromCharset
    }
  
    nsresult rv;
 -  nsCOMPtr<nsICharsetConverterManager> ccm =
 +  nsICharsetConverterManager* ccm =
      do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);
    if (NS_FAILED(rv))
      return rv;
@@ -1490,192 +1509,232 @@ diff --git a/content/base/src/nsContentU
 -  nsCOMPtr<nsIUnicodeDecoder> decoder;
 +  nsIUnicodeDecoder* decoder = nsnull;
    rv = ccm->GetUnicodeDecoder(PromiseFlatCString(aCharset).get(),
 -                              getter_AddRefs(decoder));
 +                              &decoder);
    if (NS_FAILED(rv))
      return rv;
  
-@@ -3075,18 +2994,18 @@ nsContentUtils::CheckForBOM(const unsign
+@@ -3156,13 +3073,120 @@ nsContentUtils::CheckForBOM(const unsign
+   return found;
+ }
  
- static PRBool EqualExceptRef(nsIURL* aURL1, nsIURL* aURL2)
- {
--  nsCOMPtr<nsIURI> u1;
--  nsCOMPtr<nsIURI> u2;
--
--  nsresult rv = aURL1->Clone(getter_AddRefs(u1));
++static PRBool EqualExceptRef(nsIURL* aURL1, nsIURL* aURL2)
++{
 +  nsIURI* u1 = nsnull;
 +  nsIURI* u2 = nsnull;
 +
 +  nsresult rv = aURL1->Clone(&u1);
-   if (NS_SUCCEEDED(rv)) {
--    rv = aURL2->Clone(getter_AddRefs(u2));
++  if (NS_SUCCEEDED(rv)) {
 +    rv = aURL2->Clone(&u2);
-   }
-   if (NS_FAILED(rv))
-     return PR_FALSE;
- 
--  nsCOMPtr<nsIURL> url1 = do_QueryInterface(u1);
--  nsCOMPtr<nsIURL> url2 = do_QueryInterface(u2);
++  }
++  if (NS_FAILED(rv))
++    return PR_FALSE;
++
 +  nsIURL* url1 = do_QueryInterface(u1);
 +  nsIURL* url2 = do_QueryInterface(u2);
-   if (!url1 || !url2) {
-     NS_WARNING("Cloning a URL produced a non-URL");
-     return PR_FALSE;
-@@ -3103,7 +3022,7 @@ nsIContent*
++  if (!url1 || !url2) {
++    NS_WARNING("Cloning a URL produced a non-URL");
++    return PR_FALSE;
++  }
++  url1->SetRef(EmptyCString());
++  url2->SetRef(EmptyCString());
++
++  PRBool equal;
++  rv = url1->Equals(url2, &equal);
++  return NS_SUCCEEDED(rv) && equal;
++}
++
+ /* static */
  nsIContent*
  nsContentUtils::GetReferencedElement(nsIURI* aURI, nsIContent *aFromContent)
  {
--  nsCOMPtr<nsIURL> url = do_QueryInterface(aURI);
+-  nsReferencedElement ref;
+-  ref.Reset(aFromContent, aURI);
+-  return ref.get();
 +  nsIURL* url = do_QueryInterface(aURI);
-   if (!url)
-     return nsnull;
- 
-@@ -3131,7 +3050,7 @@ nsContentUtils::GetReferencedElement(nsI
-   // This will be the URI of the document the content belongs to
-   // (the URI of the XBL document if the content is anonymous
-   // XBL content)
--  nsCOMPtr<nsIURL> documentURL = do_QueryInterface(doc->GetDocumentURI());
++  if (!url)
++    return nsnull;
++
++  nsCAutoString refPart;
++  url->GetRef(refPart);
++  // Unescape %-escapes in the reference. The result will be in the
++  // origin charset of the URL, hopefully...
++  NS_UnescapeURL(refPart);
++
++  nsCAutoString charset;
++  url->GetOriginCharset(charset);
++  nsAutoString ref;
++  nsresult rv = ConvertStringFromCharset(charset, refPart, ref);
++  if (NS_FAILED(rv)) {
++    CopyUTF8toUTF16(refPart, ref);
++  }
++  if (ref.IsEmpty())
++    return nsnull;
++
++  // Get the current document
++  nsIDocument *doc = aFromContent->GetCurrentDoc();
++  if (!doc)
++    return nsnull;
++
++  // This will be the URI of the document the content belongs to
++  // (the URI of the XBL document if the content is anonymous
++  // XBL content)
 +  nsIURL* documentURL = do_QueryInterface(doc->GetDocumentURI());
-   nsIContent* bindingParent = aFromContent->GetBindingParent();
-   PRBool isXBL = PR_FALSE;
-   if (bindingParent) {
-@@ -3157,30 +3076,30 @@ nsContentUtils::GetReferencedElement(nsI
-   }
- 
-   // Get the element
--  nsCOMPtr<nsIContent> content;
++  nsIContent* bindingParent = aFromContent->GetBindingParent();
++  PRBool isXBL = PR_FALSE;
++  if (bindingParent) {
++    nsXBLBinding* binding = doc->BindingManager()->GetBinding(bindingParent);
++    if (binding) {
++      // XXX sXBL/XBL2 issue
++      // If this is an anonymous XBL element then the URI is
++      // relative to the binding document. A full fix requires a
++      // proper XBL2 implementation but for now URIs that are
++      // relative to the binding document should be resolve to the
++      // copy of the target element that has been inserted into the
++      // bound document.
++      documentURL = do_QueryInterface(binding->PrototypeBinding()->DocURI());
++      isXBL = PR_TRUE;
++    }
++  }
++  if (!documentURL)
++    return nsnull;
++
++  if (!EqualExceptRef(url, documentURL)) {
++    // Oops -- we don't support off-document references
++    return nsnull;
++  }
++
++  // Get the element
 +  nsIContent* content = nsnull;
-   if (isXBL) {
--    nsCOMPtr<nsIDOMNodeList> anonymousChildren;
++  if (isXBL) {
 +    nsIDOMNodeList* anonymousChildren = nsnull;
-     doc->BindingManager()->
--      GetAnonymousNodesFor(bindingParent, getter_AddRefs(anonymousChildren));
++    doc->BindingManager()->
 +      GetAnonymousNodesFor(bindingParent, &anonymousChildren);
- 
-     if (anonymousChildren) {
-       PRUint32 length;
-       anonymousChildren->GetLength(&length);
-       for (PRUint32 i = 0; i < length && !content; ++i) {
--        nsCOMPtr<nsIDOMNode> node;
--        anonymousChildren->Item(i, getter_AddRefs(node));
--        nsCOMPtr<nsIContent> c = do_QueryInterface(node);
++
++    if (anonymousChildren) {
++      PRUint32 length;
++      anonymousChildren->GetLength(&length);
++      for (PRUint32 i = 0; i < length && !content; ++i) {
 +        nsIDOMNode* node = nsnull;
 +        anonymousChildren->Item(i, &node);
 +        nsIContent* c = do_QueryInterface(node);
-         if (c) {
-           content = MatchElementId(c, ref);
-         }
-       }
-     }
-   } else {
--    nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(doc);
++        if (c) {
++          content = MatchElementId(c, ref);
++        }
++      }
++    }
++  } else {
 +    nsIDOMDocument* domDoc = do_QueryInterface(doc);
-     NS_ASSERTION(domDoc, "Content doesn't reference a dom Document");
- 
--    nsCOMPtr<nsIDOMElement> element;
--    rv = domDoc->GetElementById(ref, getter_AddRefs(element));
++    NS_ASSERTION(domDoc, "Content doesn't reference a dom Document");
++
 +    nsIDOMElement* element = nsnull;
 +    rv = domDoc->GetElementById(ref, &element);
-     if (element) {
-       content = do_QueryInterface(element);
-     }
-@@ -3211,7 +3130,7 @@ nsContentUtils::HasMutationListeners(nsI
++    if (element) {
++      content = do_QueryInterface(element);
++    }
++  }
++
++  return content;
+ }
+ 
+ /* static */
+@@ -3187,7 +3211,7 @@ nsContentUtils::HasMutationListeners(nsI
    }
  
    // global object will be null for documents that don't have windows.
 -  nsCOMPtr<nsPIDOMWindow> window;
 +  nsPIDOMWindow* window = nsnull;
    window = do_QueryInterface(doc->GetScriptGlobalObject());
    // This relies on nsEventListenerManager::AddEventListener, which sets
    // all mutation bits when there is a listener for DOMSubtreeModified event.
-@@ -3227,10 +3146,10 @@ nsContentUtils::HasMutationListeners(nsI
+@@ -3203,10 +3227,10 @@ nsContentUtils::HasMutationListeners(nsI
    doc->MayDispatchMutationEvent(aTargetForSubtreeModified);
  
    // If we have a window, we can check it for mutation listeners now.
 -  nsCOMPtr<nsPIDOMEventTarget> piTarget(do_QueryInterface(window));
 +  nsPIDOMEventTarget* piTarget(do_QueryInterface(window));
    if (piTarget) {
 -    nsCOMPtr<nsIEventListenerManager> manager;
 -    piTarget->GetListenerManager(PR_FALSE, getter_AddRefs(manager));
 +    nsIEventListenerManager* manager = nsnull;
 +    piTarget->GetListenerManager(PR_FALSE, &manager);
      if (manager) {
        PRBool hasListeners = PR_FALSE;
        manager->HasMutationListeners(&hasListeners);
-@@ -3244,8 +3163,8 @@ nsContentUtils::HasMutationListeners(nsI
+@@ -3220,8 +3244,8 @@ nsContentUtils::HasMutationListeners(nsI
    // might not be in our chain.  If we don't have a window, we might have a
    // mutation listener.  Check quickly to see.
    while (aNode) {
 -    nsCOMPtr<nsIEventListenerManager> manager;
 -    aNode->GetListenerManager(PR_FALSE, getter_AddRefs(manager));
 +    nsIEventListenerManager* manager = nsnull;
 +    aNode->GetListenerManager(PR_FALSE, &manager);
      if (manager) {
        PRBool hasListeners = PR_FALSE;
        manager->HasMutationListeners(&hasListeners);
-@@ -3294,7 +3213,6 @@ nsContentUtils::GetListenerManager(nsINo
+@@ -3270,7 +3294,6 @@ nsContentUtils::GetListenerManager(nsINo
                                            PL_DHASH_LOOKUP));
      if (PL_DHASH_ENTRY_IS_BUSY(entry)) {
        *aResult = entry->mListenerManager;
 -      NS_ADDREF(*aResult);
      }
      return NS_OK;
    }
-@@ -3323,7 +3241,7 @@ nsContentUtils::GetListenerManager(nsINo
+@@ -3299,7 +3322,7 @@ nsContentUtils::GetListenerManager(nsINo
      aNode->SetFlags(NODE_HAS_LISTENERMANAGER);
    }
  
 -  NS_ADDREF(*aResult = entry->mListenerManager);
 +  *aResult = entry->mListenerManager;
  
    return NS_OK;
  }
-@@ -3338,8 +3256,8 @@ nsContentUtils::RemoveListenerManager(ns
+@@ -3314,8 +3337,8 @@ nsContentUtils::RemoveListenerManager(ns
                   (PL_DHashTableOperate(&sEventListenerManagersHash, aNode,
                                            PL_DHASH_LOOKUP));
      if (PL_DHASH_ENTRY_IS_BUSY(entry)) {
 -      nsCOMPtr<nsIEventListenerManager> listenerManager;
 -      listenerManager.swap(entry->mListenerManager);
 +      nsIEventListenerManager* listenerManager = nsnull;
 +      swap(listenerManager, entry->mListenerManager);
        // Remove the entry and *then* do operations that could cause further
        // modification of sEventListenerManagersHash.  See bug 334177.
        PL_DHashTableRawRemove(&sEventListenerManagersHash, entry);
-@@ -3466,7 +3384,7 @@ nsContentUtils::CreateContextualFragment
+@@ -3442,7 +3465,7 @@ nsContentUtils::CreateContextualFragment
    LossyCopyUTF16toASCII(buf, contentType);
    bCaseSensitive = document->IsCaseSensitive();
  
 -  nsCOMPtr<nsIHTMLDocument> htmlDoc(do_QueryInterface(document));
 +  nsIHTMLDocument* htmlDoc(do_QueryInterface(document));
    PRBool bHTML = htmlDoc && !bCaseSensitive;
  
    // See if the document has a cached fragment parser. nsHTMLDocument is the
-@@ -3558,7 +3476,7 @@ nsContentUtils::CreateDocument(const nsA
+@@ -3534,7 +3557,7 @@ nsContentUtils::CreateDocument(const nsA
                                    PR_TRUE);
    NS_ENSURE_SUCCESS(rv, rv);
  
 -  nsCOMPtr<nsIDocument> document = do_QueryInterface(*aResult);
 +  nsIDocument* document = do_QueryInterface(*aResult);
    document->SetScriptHandlingObject(aEventObject);
    return NS_OK;
  }
-@@ -3608,8 +3526,8 @@ nsContentUtils::SetNodeTextContent(nsICo
+@@ -3584,8 +3607,8 @@ nsContentUtils::SetNodeTextContent(nsICo
      return NS_OK;
    }
  
 -  nsCOMPtr<nsIContent> textContent;
 -  nsresult rv = NS_NewTextNode(getter_AddRefs(textContent),
 +  nsIContent* textContent = nsnull;
 +  nsresult rv = NS_NewTextNode(&textContent,
                                 aContent->NodeInfo()->NodeInfoManager());
    NS_ENSURE_SUCCESS(rv, rv);
  
-@@ -3709,14 +3627,14 @@ nsIDOMScriptObjectFactory*
+@@ -3685,14 +3708,14 @@ nsIDOMScriptObjectFactory*
  nsIDOMScriptObjectFactory*
  nsContentUtils::GetDOMScriptObjectFactory()
  {
 -  if (!sDOMScriptObjectFactory) {
 +  if (!sLayoutRoots->sDOMScriptObjectFactory) {
      static NS_DEFINE_CID(kDOMScriptObjectFactoryCID,
                           NS_DOM_SCRIPT_OBJECT_FACTORY_CID);
  
@@ -1685,26 +1744,26 @@ diff --git a/content/base/src/nsContentU
 -  return sDOMScriptObjectFactory;
 +    CallGetService(kDOMScriptObjectFactoryCID, &sLayoutRoots->sDOMScriptObjectFactory);
 +  }
 +
 +  return sLayoutRoots->sDOMScriptObjectFactory;
  }
  
  /* static */
-@@ -3729,7 +3647,7 @@ nsContentUtils::HoldScriptObject(PRUint3
+@@ -3705,7 +3728,7 @@ nsContentUtils::HoldScriptObject(PRUint3
    nsresult rv;
  
    PRUint32 langIndex = NS_STID_INDEX(aLangID);
 -  nsIScriptRuntime *runtime = sScriptRuntimes[langIndex];
 +  nsIScriptRuntime *runtime = sLayoutRoots->sScriptRuntimes[langIndex];
    if (!runtime) {
      nsIDOMScriptObjectFactory *factory = GetDOMScriptObjectFactory();
      NS_ENSURE_TRUE(factory, NS_ERROR_FAILURE);
-@@ -3737,15 +3655,15 @@ nsContentUtils::HoldScriptObject(PRUint3
+@@ -3713,15 +3736,15 @@ nsContentUtils::HoldScriptObject(PRUint3
      rv = factory->GetScriptRuntimeByID(aLangID, &runtime);
      NS_ENSURE_SUCCESS(rv, rv);
  
 -    // This makes sScriptRuntimes hold a strong ref.
 -    sScriptRuntimes[langIndex] = runtime;
 +    // This makes sLayoutRoots->sScriptRuntimes hold a strong ref.
 +    sLayoutRoots->sScriptRuntimes[langIndex] = runtime;
    }
@@ -1713,41 +1772,41 @@ diff --git a/content/base/src/nsContentU
    NS_ENSURE_SUCCESS(rv, rv);
  
    ++sScriptRootCount[langIndex];
 -  NS_LOG_ADDREF(sScriptRuntimes[langIndex], sScriptRootCount[langIndex],
 +  NS_LOG_ADDREF(sLayoutRoots->sScriptRuntimes[langIndex], sScriptRootCount[langIndex],
                  "HoldScriptObject", sizeof(void*));
  
    return NS_OK;
-@@ -3760,11 +3678,11 @@ nsContentUtils::DropScriptObject(PRUint3
+@@ -3736,11 +3759,11 @@ nsContentUtils::DropScriptObject(PRUint3
    NS_ASSERTION(aLangID != nsIProgrammingLanguage::JAVASCRIPT,
                 "Should use DropJSObjects.");
    PRUint32 langIndex = NS_STID_INDEX(aLangID);
 -  NS_LOG_RELEASE(sScriptRuntimes[langIndex], sScriptRootCount[langIndex] - 1,
 +  NS_LOG_RELEASE(sLayoutRoots->sScriptRuntimes[langIndex], sScriptRootCount[langIndex] - 1,
                   "HoldScriptObject");
 -  sScriptRuntimes[langIndex]->DropScriptObject(aObject);
 +  sLayoutRoots->sScriptRuntimes[langIndex]->DropScriptObject(aObject);
    if (--sScriptRootCount[langIndex] == 0) {
 -    NS_RELEASE(sScriptRuntimes[langIndex]);
 +    NS_RELEASE(sLayoutRoots->sScriptRuntimes[langIndex]);
    }
  }
  
-@@ -3794,7 +3712,7 @@ nsContentUtils::NotifyInstalledMenuKeybo
+@@ -3770,7 +3793,7 @@ nsContentUtils::NotifyInstalledMenuKeybo
  
  static PRBool SchemeIs(nsIURI* aURI, const char* aScheme)
  {
 -  nsCOMPtr<nsIURI> baseURI = NS_GetInnermostURI(aURI);
 +  nsIURI* baseURI = NS_GetInnermostURI(aURI);
    NS_ENSURE_TRUE(baseURI, PR_FALSE);
  
    PRBool isScheme = PR_FALSE;
-@@ -3815,15 +3733,15 @@ nsContentUtils::CheckSecurityBeforeLoad(
+@@ -3791,15 +3814,15 @@ nsContentUtils::CheckSecurityBeforeLoad(
    NS_PRECONDITION(aLoadingPrincipal, "Must have a loading principal here");
  
    PRBool isSystemPrin = PR_FALSE;
 -  if (NS_SUCCEEDED(sSecurityManager->IsSystemPrincipal(aLoadingPrincipal,
 -                                                       &isSystemPrin)) &&
 +  if (NS_SUCCEEDED(sLayoutRoots->sSecurityManager->
 +                   IsSystemPrincipal(aLoadingPrincipal, &isSystemPrin)) &&
        isSystemPrin) {
@@ -1756,51 +1815,51 @@ diff --git a/content/base/src/nsContentU
    
    // XXXbz do we want to fast-path skin stylesheets loading XBL here somehow?
    // CheckLoadURIWithPrincipal
 -  nsresult rv = sSecurityManager->
 +  nsresult rv = sLayoutRoots->sSecurityManager->
      CheckLoadURIWithPrincipal(aLoadingPrincipal, aURIToLoad, aCheckLoadFlags);
    NS_ENSURE_SUCCESS(rv, rv);
  
-@@ -3837,7 +3755,7 @@ nsContentUtils::CheckSecurityBeforeLoad(
+@@ -3813,7 +3836,7 @@ nsContentUtils::CheckSecurityBeforeLoad(
                                   aExtra,
                                   &shouldLoad,
                                   GetContentPolicy(),
 -                                 sSecurityManager);
 +                                 sLayoutRoots->sSecurityManager);
    NS_ENSURE_SUCCESS(rv, rv);
    if (NS_CP_REJECTED(shouldLoad)) {
      return NS_ERROR_CONTENT_BLOCKED;
-@@ -3880,13 +3798,13 @@ nsContentUtils::TriggerLink(nsIContent *
+@@ -3856,13 +3879,13 @@ nsContentUtils::TriggerLink(nsIContent *
    // Check that this page is allowed to load this URI.
    nsresult proceed = NS_OK;
  
 -  if (sSecurityManager) {
 +  if (sLayoutRoots->sSecurityManager) {
      PRUint32 flag =
        aIsUserTriggered ?
        (PRUint32)nsIScriptSecurityManager::STANDARD :
        (PRUint32)nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT;
      proceed =
 -      sSecurityManager->CheckLoadURIWithPrincipal(aContent->NodePrincipal(),
 +      sLayoutRoots->sSecurityManager->CheckLoadURIWithPrincipal(aContent->NodePrincipal(),
                                                    aLinkURI, flag);
    }
  
-@@ -4145,7 +4063,7 @@ nsContentUtils::AddScriptBlocker()
+@@ -4121,7 +4144,7 @@ nsContentUtils::AddScriptBlocker()
    if (!sScriptBlockerCount) {
      NS_ASSERTION(sRunnersCountAtFirstBlocker == 0,
                   "Should not already have a count");
 -    sRunnersCountAtFirstBlocker = sBlockedScriptRunners->Count();
 +    sRunnersCountAtFirstBlocker = sLayoutRoots->sBlockedScriptRunners.Count();
    }
    ++sScriptBlockerCount;
  }
-@@ -4161,18 +4079,19 @@ nsContentUtils::RemoveScriptBlocker()
+@@ -4137,18 +4160,19 @@ nsContentUtils::RemoveScriptBlocker()
    }
  
    PRUint32 firstBlocker = sRunnersCountAtFirstBlocker;
 -  PRUint32 lastBlocker = sBlockedScriptRunners->Count();
 +  PRUint32 lastBlocker = sLayoutRoots->sBlockedScriptRunners.Count();
    sRunnersCountAtFirstBlocker = 0;
    NS_ASSERTION(firstBlocker <= lastBlocker,
                 "bad sRunnersCountAtFirstBlocker");
@@ -1814,44 +1873,46 @@ diff --git a/content/base/src/nsContentU
      --lastBlocker;
  
      runnable->Run();
 -    NS_ASSERTION(lastBlocker == sBlockedScriptRunners->Count() &&
 +    NS_ASSERTION(lastBlocker == sLayoutRoots->sBlockedScriptRunners.Count() &&
                   sRunnersCountAtFirstBlocker == 0,
                   "Bad count");
      NS_ASSERTION(!sScriptBlockerCount, "This is really bad");
-@@ -4189,7 +4108,7 @@ nsContentUtils::AddScriptRunner(nsIRunna
+@@ -4165,7 +4189,7 @@ nsContentUtils::AddScriptRunner(nsIRunna
    }
  
    if (sScriptBlockerCount) {
 -    return sBlockedScriptRunners->AppendObject(aRunnable);
 +    return sLayoutRoots->sBlockedScriptRunners.AppendObject(aRunnable);
    }
    
    nsCOMPtr<nsIRunnable> run = aRunnable;
-@@ -4220,17 +4139,10 @@ nsContentUtils::URIIsLocalFile(nsIURI *a
+@@ -4196,19 +4220,12 @@ nsContentUtils::URIIsLocalFile(nsIURI *a
  nsContentUtils::URIIsLocalFile(nsIURI *aURI)
  {
    PRBool isFile;
 -  nsCOMPtr<nsINetUtil> util = do_QueryInterface(sIOService);
 +  nsCOMPtr<nsINetUtil> util = do_QueryInterface(sLayoutRoots->sIOService);
  
    return util && NS_SUCCEEDED(util->ProtocolHasFlags(aURI,
                                  nsIProtocolHandler::URI_IS_LOCAL_FILE,
                                  &isFile)) &&
           isFile;
- }
+-}
 -
 -/* static */
 -void
 -nsAutoGCRoot::Shutdown()
 -{
 -  NS_IF_RELEASE(sJSRuntimeService);
--}
+ }
+ 
+ nsIAtom*
 diff --git a/content/html/content/src/nsHTMLInputElement.cpp b/content/html/content/src/nsHTMLInputElement.cpp
 --- a/content/html/content/src/nsHTMLInputElement.cpp
 +++ b/content/html/content/src/nsHTMLInputElement.cpp
 @@ -145,7 +145,8 @@ static NS_DEFINE_CID(kXULControllersCID,
  
  static const char kWhitespace[] = "\n\r\t\b";
  
 -class nsHTMLInputElement : public nsGenericHTMLFormElement,
--- a/root-layout-stuff
+++ b/root-layout-stuff
@@ -1,32 +1,32 @@
 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
-@@ -60,6 +60,7 @@
- #include "nsTArray.h"
+@@ -61,6 +61,7 @@
+ #include "nsTextFragment.h"
  
  struct nsNativeKeyEvent; // Don't include nsINativeKeyBindings.h here: it will force strange compilation error!
 +#include "nsGkAtoms.h"
  
  class nsIDOMScriptObjectFactory;
  class nsIXPConnect;
-@@ -1269,6 +1270,8 @@ private:
+@@ -1300,6 +1301,8 @@ private:
      JSRuntime* sJSScriptRuntime;
  
      nsCOMArray<nsIRunnable> sBlockedScriptRunners;
 +
 +    nsGkAtoms sGKAtoms;
    };
  
    static LayoutRoots *sLayoutRoots;
 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
-@@ -277,6 +277,8 @@ nsContentUtils::LayoutRoots::Init()
+@@ -284,6 +284,8 @@ nsContentUtils::LayoutRoots::Init()
    if (!InitializeEventTable())
      return NS_ERROR_FAILURE;
  
 +  sGKAtoms.RootAtoms();
 +
    if (!sEventListenerManagersHash.ops) {
      static PLDHashTableOps hash_table_ops =
      {
@@ -111,16 +111,16 @@ diff --git a/layout/build/nsLayoutStatic
 @@ -62,7 +62,6 @@
  #include "nsGenericElement.h"  // for nsDOMEventRTTearoff
  #include "nsStyledElement.h"
  #include "nsGlobalWindow.h"
 -#include "nsGkAtoms.h"
  #include "nsImageFrame.h"
  #include "nsLayoutStylesheetCache.h"
  #include "nsNodeInfo.h"
-@@ -134,7 +133,6 @@ nsLayoutStatics::Initialize()
+@@ -138,7 +137,6 @@ nsLayoutStatics::Initialize()
    nsCSSKeywords::AddRefTable();
    nsCSSProps::AddRefTable();
    nsColorNames::AddRefTable();
 -  nsGkAtoms::AddRefAtoms();
  
    nsDOMScriptObjectFactory::Startup();
    rv = nsContentUtils::Init();
--- a/series
+++ b/series
@@ -1,10 +1,10 @@
 # This series is currently based against actionmonkey
-# revision ae61246c0f6e
+# revision 4979b6e6b997
 tamarin-remove-extra-auto-storage-specifiers
 tamarin-const-workitem.patch
 tamarin-gcstack-access
 tamarin-workitems-notgc-noassert
 tamarin-enable-traces
 tamarin-debug-print-finalizers
 tamarin-finalizable-merge-fixup
 tamarin-remove-finalize-method
@@ -13,16 +13,19 @@ tamarin-stack-access2
 tamarin-double-mark-is-ok
 tamarin-uninline-fixedmalloc
 tamarin-gcc43-strict-warnings
 tamarin-bug-427030-v1.patch
 crashrepoter-notparallel
 core-refcounting
 template-hashtable-getters
 gfx-refcounting
+tamarin-bug-427030-v1.patch2
+core-refcounting2
+gfx-refcounting2
 64bit
 nscore-class-annotation-types
 psm-remove-init-isupports
 success-macros.patch
 no-standaloneglue.patch
 prerewrite_fixes.patch
 maybeweak-crap.patch
 remove-cycle
--- a/stack-comptr-fixup
+++ b/stack-comptr-fixup
@@ -1,27 +1,27 @@
 * * *
 * * *
 
 diff --git a/content/base/src/nsGenericElement.h b/content/base/src/nsGenericElement.h
 --- a/content/base/src/nsGenericElement.h
 +++ b/content/base/src/nsGenericElement.h
-@@ -996,10 +996,9 @@ _elementName::Clone(nsINodeInfo *aNodeIn
+@@ -999,10 +999,9 @@ _elementName::Clone(nsINodeInfo *aNodeIn
      return NS_ERROR_OUT_OF_MEMORY;                                          \
    }                                                                         \
                                                                              \
 -  nsCOMPtr<nsINode> kungFuDeathGrip = it;                                   \
    nsresult rv = CopyInnerTo(it);                                            \
    if (NS_SUCCEEDED(rv)) {                                                   \
 -    kungFuDeathGrip.swap(*aResult);                                         \
 +    *aResult = it;                                                          \
    }                                                                         \
                                                                              \
    return rv;                                                                \
-@@ -1016,11 +1015,10 @@ _elementName::Clone(nsINodeInfo *aNodeIn
+@@ -1019,11 +1018,10 @@ _elementName::Clone(nsINodeInfo *aNodeIn
      return NS_ERROR_OUT_OF_MEMORY;                                          \
    }                                                                         \
                                                                              \
 -  nsCOMPtr<nsINode> kungFuDeathGrip = it;                                   \
    nsresult rv = it->Init();                                                 \
    rv |= CopyInnerTo(it);                                                    \
    if (NS_SUCCEEDED(rv)) {                                                   \
 -    kungFuDeathGrip.swap(*aResult);                                         \
@@ -413,68 +413,59 @@ diff --git a/intl/unicharutil/src/nsCate
 +  }
 +  return gCategoryImp;
  }
  
  nsIUGenCategory::nsUGenCategory nsCategoryImp::Get(PRUint32 aChar)
 diff --git a/layout/style/nsCSSLoader.cpp b/layout/style/nsCSSLoader.cpp
 --- a/layout/style/nsCSSLoader.cpp
 +++ b/layout/style/nsCSSLoader.cpp
-@@ -1564,7 +1564,7 @@ CSSLoaderImpl::SheetComplete(SheetLoadDa
+@@ -1566,7 +1566,7 @@ CSSLoaderImpl::SheetComplete(SheetLoadDa
      while (iter.HasMore()) {
        obs = iter.GetNext();
        LOG(("  Notifying global observer 0x%x for data 0x%s.  wasAlternate: %d",
 -           obs.get(), data, data->mWasAlternate));
 +           (nsICSSLoaderObserver*) obs, data, data->mWasAlternate));
        obs->StyleSheetLoaded(data->mSheet, data->mWasAlternate, aStatus);
      }
    }
-@@ -2070,7 +2070,7 @@ CSSLoaderImpl::PostLoadEvent(nsIURI* aUR
+@@ -2072,7 +2072,7 @@ CSSLoaderImpl::PostLoadEvent(nsIURI* aUR
    NS_PRECONDITION(aSheet, "Must have sheet");
    NS_PRECONDITION(aObserver, "Must have observer");
  
 -  nsRefPtr<SheetLoadData> evt =
 +  SheetLoadData* evt =
      new SheetLoadData(this, EmptyString(), // title doesn't matter here
                        aURI,
                        aSheet,
 diff --git a/layout/style/nsCSSParser.cpp b/layout/style/nsCSSParser.cpp
 --- a/layout/style/nsCSSParser.cpp
 +++ b/layout/style/nsCSSParser.cpp
-@@ -3917,7 +3917,7 @@ PRBool CSSParserImpl::ParseCounter(nsres
+@@ -4061,7 +4061,7 @@ PRBool CSSParserImpl::ParseCounter(nsres
      return PR_FALSE;
    }
  
 -  nsRefPtr<nsCSSValue::Array> val =
 +  nsCSSValue::Array* val =
      nsCSSValue::Array::Create(unit == eCSSUnit_Counter ? 2 : 3);
    if (!val) {
      aErrorCode = NS_ERROR_OUT_OF_MEMORY;
-@@ -5791,7 +5791,7 @@ PRBool CSSParserImpl::ParseCursor(nsresu
+@@ -5941,7 +5941,7 @@ PRBool CSSParserImpl::ParseCursor(nsresu
        return PR_TRUE;
      } 
      // We have a URL, so make a value array with three values.
 -    nsRefPtr<nsCSSValue::Array> val = nsCSSValue::Array::Create(3);
 +    nsCSSValue::Array* val = nsCSSValue::Array::Create(3);
      if (!val) {
        aErrorCode = NS_ERROR_OUT_OF_MEMORY;
        break;
-@@ -6331,7 +6331,7 @@ PRBool CSSParserImpl::ParseTextShadow(ns
-     nsCSSUnit unit = cur->mValue.GetUnit();
-     if (unit != eCSSUnit_None && unit != eCSSUnit_Inherit &&
-         unit != eCSSUnit_Initial) {
--      nsRefPtr<nsCSSValue::Array> val = nsCSSValue::Array::Create(4);
-+      nsCSSValue::Array* val = nsCSSValue::Array::Create(4);
-       if (!val) {
-         aErrorCode = NS_ERROR_OUT_OF_MEMORY;
-         break;
 diff --git a/layout/xul/base/src/nsListBoxBodyFrame.cpp b/layout/xul/base/src/nsListBoxBodyFrame.cpp
 --- a/layout/xul/base/src/nsListBoxBodyFrame.cpp
 +++ b/layout/xul/base/src/nsListBoxBodyFrame.cpp
-@@ -877,7 +877,7 @@ nsresult
+@@ -880,7 +880,7 @@ nsresult
  nsresult
  nsListBoxBodyFrame::InternalPositionChanged(PRBool aUp, PRInt32 aDelta)
  {
 -  nsRefPtr<nsPositionChangedEvent> ev =
 +  nsPositionChangedEvent* ev =
      new nsPositionChangedEvent(this, aUp, aDelta);
    nsresult rv = NS_DispatchToCurrentThread(ev);
    if (NS_SUCCEEDED(rv)) {
@@ -575,17 +566,17 @@ diff --git a/uriloader/prefetch/nsOfflin
      for (PRUint32 i = 0; i < count; i++) {
          nsCOMPtr<nsIURI> uri;
          if (NS_SUCCEEDED(NS_NewURI(getter_AddRefs(uri), keys[i]))) {
 -            nsRefPtr<nsOfflineCacheUpdateItem> item =
 +            nsOfflineCacheUpdateItem* item =
                  new nsOfflineCacheUpdateItem(this, uri, mDocumentURI,
                                               mClientID);
              if (!item) return NS_ERROR_OUT_OF_MEMORY;
-@@ -1311,7 +1311,7 @@ nsOfflineCacheUpdate::AddURI(nsIURI *aUR
+@@ -1314,7 +1314,7 @@ nsOfflineCacheUpdate::AddURI(nsIURI *aUR
          }
      }
  
 -    nsRefPtr<nsOfflineCacheUpdateItem> item =
 +    nsOfflineCacheUpdateItem* item =
          new nsOfflineCacheUpdateItem(this, aURI, mDocumentURI, mClientID);
      if (!item) return NS_ERROR_OUT_OF_MEMORY;
  
--- a/static-check-gc-attributes
+++ b/static-check-gc-attributes
@@ -4,52 +4,24 @@ stack checking switched to treehydra and
 
 need NS_MANAGED annotation
 
 should remove the finalizer-related annotations for the subsequenet finalizer-checking patch
 
 diff --git a/config/config.mk b/config/config.mk
 --- a/config/config.mk
 +++ b/config/config.mk
-@@ -528,11 +528,13 @@ DEHYDRA_SCRIPT = $(topsrcdir)/xpcom/anal
- DEHYDRA_SCRIPT = $(topsrcdir)/xpcom/analysis/static-checking.js
- 
- DEHYDRA_MODULES = \
--  $(topsrcdir)/xpcom/analysis/stack.js \
-+  $(topsrcdir)/xpcom/analysis/final.js \
-   $(NULL)
- 
+@@ -514,6 +514,7 @@ TREEHYDRA_MODULES = \
  TREEHYDRA_MODULES = \
    $(topsrcdir)/xpcom/analysis/outparams.js \
-+  $(topsrcdir)/xpcom/analysis/stack.js \
+   $(topsrcdir)/xpcom/analysis/stack.js \
 +  $(topsrcdir)/xpcom/analysis/gc.js \
    $(NULL)
  
  DEHYDRA_ARGS = \
-diff --git a/xpcom/analysis/final.js b/xpcom/analysis/final.js
-new file mode 100644
---- /dev/null
-+++ b/xpcom/analysis/final.js
-@@ -0,0 +1,16 @@
-+function process_type(c)
-+{
-+  if ((c.kind == 'class' || c.kind == 'struct') && !c.isIncomplete) {
-+    for each (let base in c.bases)
-+      if (isFinal(base))
-+	error("Class '" + c.name + "' derives from final class '" + base.name + "'.", c.loc);
-+  }
-+}
-+
-+function isFinal(c)
-+{
-+  if (c.isIncomplete)
-+    throw Error("Can't get final property for incomplete type.");
-+
-+  return hasAttribute(c, 'NS_final');
-+}
 diff --git a/xpcom/analysis/gc.js b/xpcom/analysis/gc.js
 new file mode 100644
 --- /dev/null
 +++ b/xpcom/analysis/gc.js
 @@ -0,0 +1,272 @@
 +include("unstable/lazy_types.js");
 +include("gcc_util.js");
 +
@@ -317,425 +289,16 @@ new file mode 100644
 +	error("Constructing GC class " + v.memberOf.name + " on the stack.",
 +	  getLocation());
 +      }
 +    }
 +  }
 +  for each (stmt in stmts)
 +    iter(processVar, stmt.statements);
 +}
-diff --git a/xpcom/analysis/stack.js b/xpcom/analysis/stack.js
---- a/xpcom/analysis/stack.js
-+++ b/xpcom/analysis/stack.js
-@@ -1,3 +1,182 @@ function process_function(f, stmts)
-+include("gcc_util.js");
-+include("unstable/lazy_types.js");
-+
-+function process_type(c)
-+{
-+  if ((c.kind == 'class' || c.kind == 'struct') &&
-+      !c.isIncomplete)
-+    isStack(c);
-+}
-+
-+function isStack(c)
-+{
-+  function calculate()
-+  {
-+    if (hasAttribute(c, 'NS_stack'))
-+      return true;
-+
-+    for each (let base in c.bases)
-+    if (isStack(base))
-+      return true;
-+
-+    for each (let member in c.members) {
-+      if (member.isFunction)
-+	continue;
-+
-+      let type = member.type;
-+      while (true) {
-+	if (type === undefined)
-+	  break;
-+
-+	if (type.isArray) {
-+	  type = type.type;
-+	  continue;
-+	}
-+
-+	if (type.typedef) {
-+	  if (hasAttribute(type, 'NS_stack'))
-+	    return true;
-+
-+	  type = type.typedef;
-+	  continue;
-+	}
-+	break;
-+      }
-+
-+      if (type === undefined) {
-+	warning("incomplete type for member " + member + ".", member.loc);
-+	continue;
-+      }
-+
-+      if (type.isPointer || type.isReference)
-+	continue;
-+
-+      if (!type.kind || (type.kind != 'class' && type.kind != 'struct'))
-+	continue;
-+
-+      if (isStack(type))
-+	return true;
-+    }
-+    return false;
-+  }
-+
-+  if (c.isIncomplete)
-+    throw Error("Can't get stack property for incomplete type.");
-+
-+  if (!c.hasOwnProperty('isStack'))
-+    c.isStack = calculate();
-+
-+  return c.isStack;
-+}
-+
-+function iter_statement_list(sl)
-+{
-+  for (let ptr = STATEMENT_LIST_HEAD(sl);
-+       ptr;
-+       ptr = ptr.next)
-+    yield ptr.stmt;
-+}
-+
-+function IDENTIFIER_OPNAME_P(name)
-+{
-+  return !!name.base.lang_flag_2;
-+}
-+
-+function isVoidPtr(t)
-+{
-+  return t.isPointer && t.type.name == 'void';
-+}
-+
-+/**
-+ * @returns null if the expression is not a call to operator new
-+ * @returns vardecl if the call is a call to operator new
-+ */
-+function operator_new_assign(stmt)
-+{
-+  if (TREE_CODE(stmt) != GIMPLE_MODIFY_STMT)
-+    return null;
-+
-+  let [varDecl, callExpr] = stmt.operands();
-+
-+  if (TREE_CODE(varDecl) != VAR_DECL ||
-+      TREE_CODE(callExpr) != CALL_EXPR)
-+    return null;
-+
-+  let fncall = callable_arg_function_decl(CALL_EXPR_FN(callExpr));
-+  let fncalltype = TREE_CODE(fncall);
-+  if (fncalltype != FUNCTION_DECL)
-+    return null;
-+
-+  let nameid = DECL_NAME(fncall);
-+  if (IDENTIFIER_OPNAME_P(nameid)) {
-+    let name = IDENTIFIER_POINTER(nameid);
-+    if (name == "operator new" || name == "operator new []") {
-+      // if this is placement-new, ignore it (should we issue a warning?)
-+      let fncallobj = dehydra_convert(TREE_TYPE(fncall));
-+      if (fncallobj.parameters.length == 2 &&
-+	  isVoidPtr(fncallobj.parameters[1]))
-+	return null;
-+
-+      return varDecl;
-+    }
-+  }
-+
-+  return null;
-+}
-+
-+function check_opnew_assignment(varDecl, stmt)
-+{
-+  if (TREE_CODE(stmt) != GIMPLE_MODIFY_STMT) {
-+    warning("operator new not followed by a GIMPLE_MODIFY_STMT: " + TREE_CODE(stmt), location_of(stmt));
-+    return;
-+  }
-+
-+  let [destVar, assign] = stmt.operands();
-+  if (TREE_CODE(assign) == NOP_EXPR)
-+    assign = assign.operands()[0];
-+
-+  if (assign != varDecl) {
-+    warning("operator new not followed by an known assignment pattern", location_of(nop));
-+    return;
-+  }
-+
-+  let destType = dehydra_convert(TREE_TYPE(destVar));
-+  if (!destType.isPointer && !destType.isReference) {
-+    error("operator new not assigned to pointer/ref?", location_of(stmt));
-+    return;
-+  }
-+  destType = destType.type;
-+
-+  if (isStack(destType))
-+    error("constructed object of type '" + destType.name + "' not on the stack.", location_of(stmt));
-+}
-+
-+function process_tree(fndecl)
-+{
-+  function findconstructors(t)
-+  {
-+    if (TREE_CODE(t) != STATEMENT_LIST)
-+      return;
-+
-+    // if we find a tuple of "operator new" / GIMPLE_MODIFY_STMT casting
-+    // the result of operator new to a pointer type
-+    let opnew = null;
-+    for (let stmt in iter_statement_list(t)) {
-+      if (opnew != null)
-+	check_opnew_assignment(opnew, stmt);
-+
-+      opnew = operator_new_assign(stmt);
-+    }
-+
-+    if (opnew != null)
-+      warning("operator new not followed by an assignment", location_of(t));
-+  }
-+  
-+  let tmap = new Map();
-+  walk_tree(DECL_SAVED_TREE(fndecl), findconstructors, tmap);
-+}
-+
-+/*
- function process_function(f, stmts)
- {
-   var stmt;
-@@ -13,10 +192,10 @@ function process_function(f, stmts)
-   {
-     if (v.isConstructor &&
-         v.fieldOf &&
--        get_class(v.memberOf, false).stack &&
-+        isStack(v.memberOf) &&
-         v.fieldOf.type.isPointer) {
--      error(getLocation() + ": constructed object of type '" +
--            v.memberOf.name + "' not on the stack.");
-+      error("constructed object of type '" +
-+            v.memberOf.name + "' not on the stack.", getLocation());
-     }
-   }
- 
-@@ -24,3 +203,4 @@ function process_function(f, stmts)
-     iter(processVar, stmt.statements);
-   }
- }
-+*/
-\ No newline at end of file
-diff --git a/xpcom/analysis/static-checking.js b/xpcom/analysis/static-checking.js
---- a/xpcom/analysis/static-checking.js
-+++ b/xpcom/analysis/static-checking.js
-@@ -36,192 +36,23 @@ if (treehydra_enabled())
- if (treehydra_enabled())
-   LoadModules(options['treehydra-modules']);
- 
--/**
-- * gClassMap maps class names to an object with the following properties:
-- *
-- * .final = true   if the class has been annotated as final, and may not be
-- *                 subclassed
-- * .stack = true   if the class has been annotated as a class which may only
-- *                 be instantiated on the stack
-- */
--var gClassMap = {};
--
--function ClassType(name)
--{
--  this.name = name;
--}
--
--ClassType.prototype = {
--  final: false,
--  stack: false,
--};
--
- function process_type(c)
- {
--  if (c.kind == 'class' || c.kind == 'struct')
--    get_class(c, true);
--
-   for each (let module in modules)
-     if (module.hasOwnProperty('process_type'))
-       module.process_type(c);
- }
- 
--/**
-- * Get the ClassType for a type 'c'
-- *
-- * If allowIncomplete is true and the type is incomplete, this function
-- * will return null.
-- *
-- * If allowIncomplete is false and the type is incomplete, this function will
-- * throw.
-- */
--function get_class(c, allowIncomplete)
-+function hasAttribute(c, attrname)
- {
--  var classattr, base, member, type, realtype, foundConstructor;
--  var bases = [];
-+  if (c.attributes === undefined)
-+    return false;
- 
--  if (c.isIncomplete) {
--    if (allowIncomplete)
--      return null;
-+  for each (let attr in c.attributes)
-+    if (attr.name == 'user' && attr.value[0] == attrname)
-+      return true;
- 
--    throw Error("Can't process incomplete type '" + c + "'.");
--  }
--
--  if (gClassMap.hasOwnProperty(c.name)) {
--    return gClassMap[c.name];
--  }
--
--  for each (base in c.bases) {
--      realtype = get_class(base, allowIncomplete);
--      if (realtype == null) {
--        error("Complete type " + c + " has incomplete base " + base);
--        return null;
--      }
--
--      bases.push(realtype);
--  }
--
--  function hasAttribute(attrname)
--  {
--    var attr;
--
--    if (c.attributes === undefined)
--      return false;
--
--    for each (attr in c.attributes) {
--      if (attr.name == 'user' && attr.value[0] == attrname) {
--        return true;
--      }
--    }
--
--    return false;
--  }
--
--  classattr = new ClassType(c.name);
--  gClassMap[c.name] = classattr;
--
--  // check for .final
--
--  if (hasAttribute('NS_final')) {
--    classattr.final = true;
--  }
--
--  // check for .stack
--
--  if (hasAttribute('NS_stack')) {
--    classattr.stack = true;
--  }
--  else {
--    for each (base in bases) {
--      if (base.stack) {
--        classattr.stack = true;
--        break;
--      }
--    }
--  }
--
--  if (!classattr.stack) {
--    // Check members
--    for each (member in c.members) {
--      if (member.isFunction)
--        continue;
--
--      type = member.type;
--
--      /* recurse through arrays and typedefs */
--      while (true) {
--          if (type === undefined) {
--              break;
--          }
--              
--          if (type.isArray) {
--              type = type.type;
--              continue;
--          }
--          if (type.typedef) {
--              type = type.typedef;
--              continue;
--          }
--          break;
--      }
--
--      if (type === undefined) {
--          warning("incomplete type  for member " + member + ".");
--          continue;
--      }
--
--      if (type.isPointer || type.isReference) {
--          continue;
--      }
--
--      if (!type.kind || (type.kind != 'class' && type.kind != 'struct')) {
--          continue;
--      }
--
--      var membertype = get_class(type, false);
--      if (membertype.stack) {
--        classattr.stack = true;
--        break;
--      }
--    }
--  }
--
--  // Check for errors at declaration-time
--
--  for each (base in bases) {
--    if (base.final) {
--      error("class '" + c.name + "' inherits from final class '" + base.name + "'.");
--    }
--  }
--
--  // At the moment, any class that is .final has to have a constructor, or
--  // we can't detect callsites... this may change with treehydra.
--  if (classattr.stack) {
--    foundConstructor = false;
--    for each (member in c.members) {
--      if (member.isConstructor) {
--        foundConstructor = true;
--        break;
--      }
--    }
--
--    if (!foundConstructor) {
--      warning(c.loc + ": class " + c.name + " is marked stack-only but doesn't have a constructor. Static checking can't detect instantiations of this class properly.");
--    }
--  }
--
--  return classattr;
--}
--
--/**
-- * Unwrap any array of types back to their base type.
-- */
--function unwrapArray(t)
--{
--  while (t.isArray) {
--    t = t.type;
--  }
--  return t;
-+  return false;
- }
- 
- function process_function(f, stmts)
 diff --git a/xpcom/base/nscore.h b/xpcom/base/nscore.h
 --- a/xpcom/base/nscore.h
 +++ b/xpcom/base/nscore.h
 @@ -487,17 +487,37 @@ typedef PRUint32 nsrefcnt;
   *
   * NS_STACK_CLASS: a class which must only be instantiated on the stack
   * NS_FINAL_CLASS: a class which may not be subclassed
 + * NS_GC_TYPE    : a class which must be GC-allocated
@@ -956,104 +519,40 @@ diff --git a/xpcom/tests/static-checker/
 +GC_PASS_TESTCASES = \
 +  GCNew.cpp \
 +  GCNotStack-constructor.cpp \
 +  GCNotStack-static.cpp \
 +  $(NULL)
  
  FINAL_FAILURE_TESTCASES = \
    TestFinal.cpp \
-@@ -55,6 +71,13 @@ STACK_FAILURE_TESTCASES = \
- STACK_FAILURE_TESTCASES = \
-   TestStack.cpp \
+@@ -57,6 +73,7 @@ STACK_FAILURE_TESTCASES = \
    TestStackTemplate.cpp \
+   StackNoConstructor.cpp \
+   StackVector.cpp \
 +  TestStackCOMPtr.cpp \
-+  StackNoConstructor.cpp \
-+  StackVector.cpp \
-+  $(NULL)
-+
-+STACK_PASS_TESTCASES = \
-+  StackPlacementNewOK.cpp \
    $(NULL)
  
- OUTPARAMS_WARNING_TESTCASES = \
-@@ -90,16 +113,20 @@ OUTPARAMS_PASS_TESTCASES = \
+ STACK_PASS_TESTCASES = \
+@@ -99,6 +116,7 @@ OUTPARAMS_PASS_TESTCASES = \
    $(NULL)
  
  STATIC_FAILURE_TESTCASES = \
 +  $(GC_FAILURE_TESTCASES) \
    $(FINAL_FAILURE_TESTCASES) \
    $(STACK_FAILURE_TESTCASES) \
    $(NULL)
- 
- STATIC_WARNING_TESTCASES = \
-   $(OUTPARAMS_WARNING_TESTCASES) \
-+  $(STACK_WARNING_TESTCASES) \
-   $(NULL)
- 
+@@ -110,6 +128,7 @@ STATIC_PASS_TESTCASES = \
  STATIC_PASS_TESTCASES = \
    $(OUTPARAMS_PASS_TESTCASES) \
-+  $(STACK_PASS_TESTCASES) \
+   $(STACK_PASS_TESTCASES) \
 +  $(GC_PASS_TESTCASES) \
    $(NULL)
  
  include $(topsrcdir)/config/rules.mk
-diff --git a/xpcom/tests/static-checker/StackNoConstructor.cpp b/xpcom/tests/static-checker/StackNoConstructor.cpp
-new file mode 100644
---- /dev/null
-+++ b/xpcom/tests/static-checker/StackNoConstructor.cpp
-@@ -0,0 +1,11 @@
-+#include "nscore.h"
-+
-+struct NS_STACK_CLASS A
-+{
-+  int i;
-+};
-+
-+void* Foo()
-+{
-+  return new A();
-+}
-diff --git a/xpcom/tests/static-checker/StackPlacementNewOK.cpp b/xpcom/tests/static-checker/StackPlacementNewOK.cpp
-new file mode 100644
---- /dev/null
-+++ b/xpcom/tests/static-checker/StackPlacementNewOK.cpp
-@@ -0,0 +1,15 @@
-+#include "nscore.h"
-+#include NEW_H
-+
-+struct NS_STACK_CLASS A
-+{
-+  int i;
-+};
-+
-+int Foo()
-+{
-+  char buf[sizeof(A)];
-+
-+  A *a = new(&buf) A;
-+  return a->i;
-+}
-diff --git a/xpcom/tests/static-checker/StackVector.cpp b/xpcom/tests/static-checker/StackVector.cpp
-new file mode 100644
---- /dev/null
-+++ b/xpcom/tests/static-checker/StackVector.cpp
-@@ -0,0 +1,12 @@
-+#include "nscore.h"
-+
-+struct NS_STACK_CLASS A
-+{
-+  int i;
-+};
-+
-+void* Foo()
-+{
-+  A *a = new A[8];
-+  return a;
-+}
 diff --git a/xpcom/tests/static-checker/TestStackCOMPtr.cpp b/xpcom/tests/static-checker/TestStackCOMPtr.cpp
 new file mode 100644
 --- /dev/null
 +++ b/xpcom/tests/static-checker/TestStackCOMPtr.cpp
 @@ -0,0 +1,6 @@
 +#include "nsCOMPtr.h"
 +
 +void TestFunc()
--- a/system-metrics-comarray
+++ b/system-metrics-comarray
@@ -1,23 +1,23 @@
 * * *
 
 diff --git a/layout/style/nsCSSRuleProcessor.cpp b/layout/style/nsCSSRuleProcessor.cpp
 --- a/layout/style/nsCSSRuleProcessor.cpp
 +++ b/layout/style/nsCSSRuleProcessor.cpp
-@@ -81,7 +81,7 @@
- #include "nsTArray.h"
+@@ -82,7 +82,7 @@
+ #include "nsContentUtils.h"
  
  static NS_DEFINE_CID(kLookAndFeelCID, NS_LOOKANDFEEL_CID);
 -static nsTArray< nsCOMPtr<nsIAtom> >* sSystemMetrics = 0;
 +static nsCOMArray<nsIAtom>* sSystemMetrics = 0;
  
  struct RuleValue {
    /**
-@@ -751,41 +751,41 @@ InitSystemMetrics()
+@@ -752,41 +752,41 @@ InitSystemMetrics()
  {
    NS_ASSERTION(!sSystemMetrics, "already initialized");
  
 -  sSystemMetrics = new nsTArray< nsCOMPtr<nsIAtom> >;
 +  sSystemMetrics = new nsCOMArray<nsIAtom>;
    NS_ENSURE_TRUE(sSystemMetrics, PR_FALSE);
  
    nsresult rv;
@@ -58,38 +58,38 @@ diff --git a/layout/style/nsCSSRuleProce
  
    rv = lookAndFeel->GetMetric(nsILookAndFeel::eMetric_WindowsDefaultTheme, metricResult);
    if (NS_SUCCEEDED(rv) && metricResult) {
 -    sSystemMetrics->AppendElement(do_GetAtom("windows-default-theme"));
 +    sSystemMetrics->AppendObject(do_GetAtom("windows-default-theme"));
    }
  
    return PR_TRUE;
-@@ -1312,8 +1312,7 @@ static PRBool SelectorMatches(RuleProces
+@@ -1324,8 +1324,7 @@ static PRBool SelectorMatches(RuleProces
        }
        NS_ASSERTION(pseudoClass->u.mString, "Must have string!");
        nsCOMPtr<nsIAtom> metric = do_GetAtom(pseudoClass->u.mString);
 -      result = sSystemMetrics->IndexOf(metric) !=
 -               sSystemMetrics->NoIndex;
 +      result = sSystemMetrics->IndexOf(metric) != -1;
      }
      else if (nsCSSPseudoClasses::mozHasHandlerRef == pseudoClass->mAtom) {
        nsIContent *child = nsnull;
-@@ -1804,8 +1803,8 @@ static void ContentEnumFunc(nsICSSStyleR
+@@ -1816,8 +1815,8 @@ static void ContentEnumFunc(nsICSSStyleR
        // nsICSSStyleRule return the same pointer for nsIStyleRule (why
        // would anything multiply inherit nsIStyleRule anyway?)
  #ifdef DEBUG
 -      nsCOMPtr<nsIStyleRule> iRule = do_QueryInterface(aRule);
 -      NS_ASSERTION(static_cast<nsIStyleRule*>(aRule) == iRule.get(),
 +      nsIStyleRule* iRule = do_QueryInterface(aRule);
 +      NS_ASSERTION(static_cast<nsIStyleRule*>(aRule) == iRule,
                     "Please fix QI so this performance optimization is valid");
  #endif
        data->mRuleWalker->Forward(static_cast<nsIStyleRule*>(aRule));
-@@ -1869,8 +1868,8 @@ static void PseudoEnumFunc(nsICSSStyleRu
+@@ -1881,8 +1880,8 @@ static void PseudoEnumFunc(nsICSSStyleRu
      // nsICSSStyleRule return the same pointer for nsIStyleRule (why
      // would anything multiply inherit nsIStyleRule anyway?)
  #ifdef DEBUG
 -    nsCOMPtr<nsIStyleRule> iRule = do_QueryInterface(aRule);
 -    NS_ASSERTION(static_cast<nsIStyleRule*>(aRule) == iRule.get(),
 +    nsIStyleRule* iRule = do_QueryInterface(aRule);
 +    NS_ASSERTION(static_cast<nsIStyleRule*>(aRule) == iRule,
                   "Please fix QI so this performance optimization is valid");
--- a/tamarin-bug-427030-v1.patch
+++ b/tamarin-bug-427030-v1.patch
@@ -1,11 +1,11 @@
-diff -r 264e5303a97b js/tamarin/MMgc/GC.cpp
---- a/js/tamarin/MMgc/GC.cpp	Wed Jul 02 13:41:02 2008 -0700
-+++ b/js/tamarin/MMgc/GC.cpp	Wed Jul 02 13:41:35 2008 -0700
+diff --git a/js/tamarin/MMgc/GC.cpp b/js/tamarin/MMgc/GC.cpp
+--- a/js/tamarin/MMgc/GC.cpp
++++ b/js/tamarin/MMgc/GC.cpp
 @@ -629,6 +629,7 @@ namespace MMgc
  			PushWorkItem(work, item);
  			Mark(work);
  		}
 +		MarkLinks(work);
  		
  		m_currentQueue = NULL;
  
@@ -129,73 +129,73 @@ diff -r 264e5303a97b js/tamarin/MMgc/GC.
 +		GCAssert(iter != m_hardLinks.end());
 +		if (--iter->second == 0)
 +			m_hardLinks.erase(iter);
 +	}
 +
  	void GC::AddCallback(GCCallback *cb)
  	{
  		cb->prevCB = NULL;
-diff -r 264e5303a97b js/tamarin/MMgc/GC.h
---- a/js/tamarin/MMgc/GC.h	Wed Jul 02 13:41:02 2008 -0700
-+++ b/js/tamarin/MMgc/GC.h	Wed Jul 02 13:41:35 2008 -0700
+diff --git a/js/tamarin/MMgc/GC.h b/js/tamarin/MMgc/GC.h
+--- a/js/tamarin/MMgc/GC.h
++++ b/js/tamarin/MMgc/GC.h
 @@ -39,6 +39,9 @@
  
  #ifndef __GC__
  #define __GC__
 +
 +#include <map>
 +#include <utility>
  
  #if defined MMGC_IA32
  
-@@ -731,6 +734,12 @@ namespace MMgc
+@@ -733,6 +736,12 @@ namespace MMgc
  		 */
- 		void Free(void *ptr);
+ 		void Free(const void *ptr);
  
 +		/** @access Requires(request) */
 +		void Link(void *source, void *target);
 +
 +		/** @access Requires(request) */
 +		void Unlink(void *source, void *target);
 +
  		/**
  		 * return the size of a piece of memory, may be bigger than what was asked for
  		 *
-@@ -1358,9 +1367,13 @@ namespace MMgc
+@@ -1365,9 +1374,13 @@ namespace MMgc
  		/** @access Requires(exclusiveGC) */
  		void ForceSweep() { Sweep(true); }
  		/** @access Requires(exclusiveGC) */
 +		void SweepLinks();
 +		/** @access Requires(exclusiveGC) */
  		void Mark(GCStack<GCWorkItem> &work);
  		/** @access Requires(exclusiveGC) */
  		void MarkQueueAndStack(GCStack<GCWorkItem> &work);
 +		/** @access Requires(exclusiveGC) */
 +		void MarkLinks(GCStack<GCWorkItem> &work);
  		/** @access Requires(exclusiveGC) */
  		void MarkItem(GCStack<GCWorkItem> &work)
  		{
-@@ -1435,7 +1448,12 @@ namespace MMgc
+@@ -1442,7 +1455,12 @@ namespace MMgc
  		GCRoot *m_roots;
  		void AddRoot(GCRoot *root);
  		void RemoveRoot(GCRoot *root);
 -		
 +
 +		typedef std::pair<void *, void *> PtrPair;
 +		typedef std::map<PtrPair, size_t> HardLinks;
 +		/** @access Requires(request && m_lock || exclusiveGC) */
 +		HardLinks m_hardLinks;
 +
  		/**
  		 * Points to the head of a linked list of callback objects.
  		 *
-diff -r 264e5303a97b js/tamarin/MMgc/GCTests.cpp
---- a/js/tamarin/MMgc/GCTests.cpp	Wed Jul 02 13:41:02 2008 -0700
-+++ b/js/tamarin/MMgc/GCTests.cpp	Wed Jul 02 13:41:35 2008 -0700
+diff --git a/js/tamarin/MMgc/GCTests.cpp b/js/tamarin/MMgc/GCTests.cpp
+--- a/js/tamarin/MMgc/GCTests.cpp
++++ b/js/tamarin/MMgc/GCTests.cpp
 @@ -173,6 +173,96 @@ namespace MMgc
  			delete wr->get();
  	}
  
 +	class HardLinkTests {
 +		static GCObject *a;
 +		static GCObject *b;
 +		static GCWeakRef *wra;
new file mode 100644
--- /dev/null
+++ b/tamarin-bug-427030-v1.patch2
@@ -0,0 +1,35 @@
+diff --git a/js/tamarin/MMgc/GC.cpp b/js/tamarin/MMgc/GC.cpp
+--- a/js/tamarin/MMgc/GC.cpp
++++ b/js/tamarin/MMgc/GC.cpp
+@@ -877,7 +877,7 @@ bail:
+ 	{
+ 		HardLinks::iterator i = m_hardLinks.begin();
+ 		while (i != m_hardLinks.end()) {
+-			void *source = i->first.first;
++			const void *source = i->first.first;
+ 			if (!GetMark(source))
+ 				m_hardLinks.erase(i++);
+ 			else
+@@ -1322,8 +1322,8 @@ bail:
+ 			for (HardLinks::iterator i = m_hardLinks.begin();
+ 			     i != m_hardLinks.end();
+ 			     ++i) {
+-				void *source = i->first.first;
+-				void *target = i->first.second;
++				const void *source = i->first.first;
++				const void *target = i->first.second;
+ 
+ 				GCAssert(i->second != 0);
+ 				if (GetMark(source) && !GetMark(target)) {
+diff --git a/js/tamarin/MMgc/GC.h b/js/tamarin/MMgc/GC.h
+--- a/js/tamarin/MMgc/GC.h
++++ b/js/tamarin/MMgc/GC.h
+@@ -1456,7 +1456,7 @@ namespace MMgc
+ 		void AddRoot(GCRoot *root);
+ 		void RemoveRoot(GCRoot *root);
+ 
+-		typedef std::pair<void *, void *> PtrPair;
++		typedef std::pair<const void *, const void *> PtrPair;
+ 		typedef std::map<PtrPair, size_t> HardLinks;
+ 		/** @access Requires(request && m_lock || exclusiveGC) */
+ 		HardLinks m_hardLinks;
--- a/tamarin-debug-print-finalizers
+++ b/tamarin-debug-print-finalizers
@@ -1,11 +1,11 @@
-diff -r 0ea60d28113c js/tamarin/MMgc/GCAlloc.cpp
---- a/js/tamarin/MMgc/GCAlloc.cpp	Wed Jul 02 13:34:09 2008 -0700
-+++ b/js/tamarin/MMgc/GCAlloc.cpp	Wed Jul 02 13:34:48 2008 -0700
+diff --git a/js/tamarin/MMgc/GCAlloc.cpp b/js/tamarin/MMgc/GCAlloc.cpp
+--- a/js/tamarin/MMgc/GCAlloc.cpp
++++ b/js/tamarin/MMgc/GCAlloc.cpp
 @@ -42,6 +42,9 @@
  #include <stdlib.h>
  
  #include "MMgc.h"
 +
 +#include <typeinfo>
 +#include <stdio.h>
  
@@ -15,21 +15,21 @@ diff -r 0ea60d28113c js/tamarin/MMgc/GCA
  					{     
  						GCFinalizable *obj = (GCFinalizedObject*)GetUserPointer(item);
  						GCAssert(*(int*)obj != 0);
 +
 +						fprintf(stderr, "Finalizing class %s at %p\n",
 +							typeid(*obj).name(), obj);
 +
  						obj->~GCFinalizable();
+ 						bits[i] &= ~(kFinalize<<(j*4));
  
- 						bits[i] &= ~(kFinalize<<(j*4));
-diff -r 0ea60d28113c js/tamarin/MMgc/GCLargeAlloc.cpp
---- a/js/tamarin/MMgc/GCLargeAlloc.cpp	Wed Jul 02 13:34:09 2008 -0700
-+++ b/js/tamarin/MMgc/GCLargeAlloc.cpp	Wed Jul 02 13:34:48 2008 -0700
+diff --git a/js/tamarin/MMgc/GCLargeAlloc.cpp b/js/tamarin/MMgc/GCLargeAlloc.cpp
+--- a/js/tamarin/MMgc/GCLargeAlloc.cpp
++++ b/js/tamarin/MMgc/GCLargeAlloc.cpp
 @@ -43,6 +43,9 @@
  #include <string.h>
  
  #include "MMgc.h"
 +
 +#include <typeinfo>
 +#include <stdio.h>