Bug 1134920 - Use moz_xmalloc/moz_xrealloc/free instead of nsMemory::Alloc/Realloc/Free. r=nfroyd
authorMike Hommey <mh+mozilla@glandium.org>
Fri, 27 Mar 2015 09:01:12 +0900
changeset 254732 e60e056a230c3792c8390f3e6808e97ad7cc3b47
parent 254731 d9687f023f9fd9c8867ed897c3bd3f47daeb157d
child 254733 da6cbd725f5f14b3b26d286b72852041c2b773ba
push id1357
push usermartin.thomson@gmail.com
push dateWed, 01 Apr 2015 17:21:06 +0000
reviewersnfroyd
bugs1134920
milestone40.0a1
Bug 1134920 - Use moz_xmalloc/moz_xrealloc/free instead of nsMemory::Alloc/Realloc/Free. r=nfroyd
accessible/base/nsAccessiblePivot.cpp
caps/nsScriptSecurityManager.cpp
docshell/base/nsDocShell.cpp
dom/base/nsDOMClassInfo.cpp
dom/base/nsDOMWindowUtils.cpp
dom/base/nsDocument.cpp
dom/base/nsFormData.cpp
dom/base/nsGlobalWindow.cpp
dom/base/nsHTMLContentSerializer.cpp
dom/base/nsHostObjectURI.cpp
dom/base/nsJSEnvironment.cpp
dom/base/nsPlainTextSerializer.cpp
dom/base/nsScriptNameSpaceManager.cpp
dom/base/nsXMLHttpRequest.cpp
dom/canvas/WebGL2ContextTransformFeedback.cpp
dom/events/Event.cpp
dom/events/EventListenerService.cpp
dom/html/HTMLInputElement.cpp
dom/html/nsFormSubmission.cpp
dom/html/nsHTMLDocument.cpp
dom/mobileconnection/MobileConnection.cpp
dom/mobileconnection/ipc/MobileConnectionChild.cpp
dom/mobileconnection/ipc/MobileConnectionParent.cpp
dom/plugins/base/nsNPAPIPlugin.cpp
dom/plugins/base/nsNPAPIPluginInstance.cpp
dom/plugins/base/nsPluginHost.cpp
dom/plugins/base/nsPluginTags.cpp
dom/xbl/nsXBLProtoImplField.cpp
dom/xbl/nsXBLProtoImplMember.h
dom/xbl/nsXBLProtoImplMethod.h
dom/xbl/nsXBLPrototypeBinding.cpp
dom/xbl/nsXBLPrototypeHandler.cpp
dom/xslt/xpath/txNodeSet.cpp
dom/xslt/xslt/txMozillaXSLTProcessor.cpp
dom/xul/XULDocument.cpp
editor/composer/nsEditorSpellCheck.cpp
extensions/auth/nsAuthSASL.cpp
extensions/auth/nsAuthSSPI.cpp
extensions/auth/nsAuthSambaNTLM.cpp
extensions/auth/nsHttpNegotiateAuth.cpp
extensions/gio/nsGIOProtocolHandler.cpp
extensions/spellcheck/hunspell/src/mozHunspell.cpp
extensions/spellcheck/src/mozEnglishWordUtils.cpp
gfx/src/nsThebesFontEnumerator.cpp
image/decoders/nsPNGDecoder.cpp
intl/locale/nsLocale.cpp
intl/strres/nsStringBundle.cpp
intl/uconv/nsIUnicodeEncoder.h
intl/unicharutil/nsSaveAsCharset.cpp
intl/unicharutil/nsUnicodeNormalizer.cpp
intl/unicharutil/tests/UnicharSelfTest.cpp
js/xpconnect/src/XPCComponents.cpp
js/xpconnect/src/XPCConvert.cpp
js/xpconnect/src/XPCJSID.cpp
js/xpconnect/src/XPCRuntimeService.cpp
js/xpconnect/src/XPCVariant.cpp
js/xpconnect/src/XPCWrappedJS.cpp
js/xpconnect/src/XPCWrappedJSClass.cpp
js/xpconnect/src/XPCWrappedNative.cpp
js/xpconnect/src/nsScriptError.cpp
js/xpconnect/src/nsXPConnect.cpp
js/xpconnect/src/xpcprivate.h
js/xpconnect/tests/components/native/xpctest_attributes.cpp
layout/base/nsDocumentViewer.cpp
layout/base/nsPresShell.cpp
layout/generic/nsFloatManager.cpp
layout/generic/nsImageMap.cpp
layout/generic/nsPageFrame.cpp
layout/generic/nsSelection.cpp
layout/generic/nsTextFrame.cpp
layout/inspector/inDOMUtils.cpp
layout/printing/nsPrintEngine.cpp
layout/style/nsROCSSPrimitiveValue.cpp
layout/xul/nsMenuFrame.cpp
media/mtransport/gonk_addrs.cpp
modules/libjar/nsJAR.cpp
modules/libjar/nsJARURI.cpp
modules/libpref/nsPrefBranch.cpp
netwerk/base/nsDirectoryIndexStream.cpp
netwerk/base/nsIAuthModule.idl
netwerk/base/nsProtocolProxyService.h
netwerk/base/nsSimpleURI.cpp
netwerk/base/nsStandardURL.cpp
netwerk/cache/nsCacheEntryDescriptor.cpp
netwerk/mime/nsIMIMEHeaderParam.idl
netwerk/mime/nsMIMEHeaderParamImpl.cpp
netwerk/protocol/about/nsAboutCache.cpp
netwerk/protocol/about/nsAboutCacheEntry.cpp
netwerk/protocol/device/AndroidCaptureProvider.cpp
netwerk/protocol/ftp/nsFtpConnectionThread.cpp
netwerk/protocol/ftp/nsFtpProtocolHandler.h
netwerk/protocol/http/nsHttpNTLMAuth.cpp
netwerk/streamconv/converters/nsBinHexDecoder.cpp
netwerk/streamconv/converters/nsFTPDirListingConv.cpp
netwerk/streamconv/converters/nsHTTPCompressConv.cpp
netwerk/streamconv/test/TestStreamConv.cpp
netwerk/test/TestCacheBlockFiles.cpp
netwerk/test/TestMakeAbs.cpp
parser/html/nsHtml5TreeOperation.cpp
security/manager/pki/src/nsNSSDialogs.cpp
security/manager/ssl/src/PSMContentListener.cpp
security/manager/ssl/src/TransportSecurityInfo.cpp
security/manager/ssl/src/nsCertPicker.cpp
security/manager/ssl/src/nsKeygenHandler.cpp
security/manager/ssl/src/nsNSSASN1Object.cpp
security/manager/ssl/src/nsNSSCallbacks.cpp
security/manager/ssl/src/nsNSSCertHelper.cpp
security/manager/ssl/src/nsNSSCertificate.cpp
security/manager/ssl/src/nsNSSCertificateDB.cpp
security/manager/ssl/src/nsNSSCertificateFakeTransport.cpp
security/manager/ssl/src/nsNSSIOLayer.cpp
security/manager/ssl/src/nsNTLMAuthModule.cpp
security/manager/ssl/src/nsPKCS11Slot.cpp
security/manager/ssl/src/nsSDR.cpp
security/manager/ssl/src/nsSSLStatus.cpp
toolkit/components/downloads/ApplicationReputation.cpp
toolkit/components/places/nsAnnotationService.cpp
toolkit/components/places/nsFaviconService.cpp
toolkit/components/places/nsNavBookmarks.cpp
toolkit/components/places/nsNavHistory.cpp
toolkit/components/places/nsNavHistoryQuery.cpp
toolkit/components/places/nsNavHistoryResult.cpp
toolkit/components/telemetry/Telemetry.cpp
toolkit/components/url-classifier/nsUrlClassifierPrefixSet.cpp
toolkit/xre/nsAndroidStartup.cpp
tools/profiler/nsProfiler.cpp
widget/GfxInfoBase.cpp
widget/android/nsAppShell.cpp
widget/cocoa/nsClipboard.mm
widget/gtk/nsClipboard.cpp
widget/gtk/nsWindow.cpp
widget/nsPrimitiveHelpers.cpp
widget/nsTransferable.cpp
widget/qt/nsClipboard.cpp
widget/qt/nsWindow.cpp
widget/windows/nsClipboard.cpp
widget/windows/nsDataObj.cpp
widget/windows/nsNativeDragTarget.cpp
widget/windows/nsPrintSettingsWin.cpp
xpcom/base/nsConsoleService.cpp
xpcom/ds/nsProperties.cpp
xpcom/ds/nsStaticNameTable.cpp
xpcom/ds/nsSupportsPrimitives.cpp
xpcom/ds/nsVariant.cpp
xpcom/glue/nsIClassInfoImpl.h
xpcom/glue/nsMemory.h
xpcom/glue/nsTextFormatter.cpp
xpcom/glue/nsTextFormatter.h
xpcom/io/nsEscape.cpp
xpcom/io/nsIStringStream.idl
xpcom/io/nsLinebreakConverter.cpp
xpcom/io/nsLocalFileUnix.cpp
xpcom/io/nsScriptableInputStream.cpp
xpcom/io/nsSegmentedBuffer.cpp
xpcom/reflect/xptcall/tests/TestXPTCInvoke.cpp
xpcom/string/nsReadableUtils.cpp
xpcom/string/nsReadableUtils.h
xpcom/string/nsSubstring.cpp
xpcom/string/nsTSubstring.h
xpcom/string/nsXPCOMStrings.h
xpcom/tests/gtest/TestStrings.cpp
xpfe/appshell/nsWebShellWindow.cpp
--- a/accessible/base/nsAccessiblePivot.cpp
+++ b/accessible/base/nsAccessiblePivot.cpp
@@ -19,17 +19,17 @@ using namespace mozilla::a11y;
  */
 class RuleCache
 {
 public:
   explicit RuleCache(nsIAccessibleTraversalRule* aRule) : mRule(aRule),
                                                           mAcceptRoles(nullptr) { }
   ~RuleCache () {
     if (mAcceptRoles)
-      nsMemory::Free(mAcceptRoles);
+      free(mAcceptRoles);
   }
 
   nsresult ApplyFilter(Accessible* aAccessible, uint16_t* aResult);
 
 private:
   nsCOMPtr<nsIAccessibleTraversalRule> mRule;
   uint32_t* mAcceptRoles;
   uint32_t mAcceptRolesLength;
--- a/caps/nsScriptSecurityManager.cpp
+++ b/caps/nsScriptSecurityManager.cpp
@@ -168,17 +168,17 @@ public:
           mDidGetFlags(false),
           mMustFreeName(false)
     {
     }
 
     ~ClassInfoData()
     {
         if (mMustFreeName)
-            nsMemory::Free(mName);
+            free(mName);
     }
 
     uint32_t GetFlags()
     {
         if (!mDidGetFlags) {
             if (mClassInfo) {
                 nsresult rv = mClassInfo->GetFlags(&mFlags);
                 if (NS_FAILED(rv)) {
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -11042,17 +11042,17 @@ nsDocShell::ScrollToAnchor(nsACString& a
     // In that case, we should just fall through to using the
     // page's charset.
     nsresult rv = NS_ERROR_FAILURE;
     NS_ConvertUTF8toUTF16 uStr(str);
     if (!uStr.IsEmpty()) {
       rv = shell->GoToAnchor(NS_ConvertUTF8toUTF16(str), scroll,
                              nsIPresShell::SCROLL_SMOOTH_AUTO);
     }
-    nsMemory::Free(str);
+    free(str);
 
     // Above will fail if the anchor name is not UTF-8.  Need to
     // convert from document charset to unicode.
     if (NS_FAILED(rv)) {
       // Get a document charset
       NS_ENSURE_TRUE(mContentViewer, NS_ERROR_FAILURE);
       nsIDocument* doc = mContentViewer->GetDocument();
       NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE);
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -512,17 +512,17 @@ nsDOMClassInfo::RegisterExternalClasses(
     nsCID *cid;
     rv = registrar->ContractIDToCID(contractId, &cid);
     if (NS_FAILED(rv)) {
       NS_WARNING("Bad contract id registered with the script namespace manager");
       continue;
     }
 
     rv = nameSpaceManager->RegisterExternalClassName(categoryEntry.get(), *cid);
-    nsMemory::Free(cid);
+    free(cid);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return nameSpaceManager->RegisterExternalInterfaces(true);
 }
 
 #define _DOM_CLASSINFO_MAP_BEGIN(_class, _ifptr, _has_class_if)               \
   {                                                                           \
@@ -803,17 +803,17 @@ nsDOMClassInfo::GetInterfaces(uint32_t *
   *aCount = count;
 
   if (!count) {
     *aArray = nullptr;
 
     return NS_OK;
   }
 
-  *aArray = static_cast<nsIID **>(nsMemory::Alloc(count * sizeof(nsIID *)));
+  *aArray = static_cast<nsIID **>(moz_xmalloc(count * sizeof(nsIID *)));
   NS_ENSURE_TRUE(*aArray, NS_ERROR_OUT_OF_MEMORY);
 
   uint32_t i;
   for (i = 0; i < count; i++) {
     nsIID *iid = static_cast<nsIID *>(nsMemory::Clone(mData->mInterfaces[i],
                                                          sizeof(nsIID)));
 
     if (!iid) {
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -2522,17 +2522,17 @@ nsDOMWindowUtils::StopFrameTimeRecording
   LayerManager *mgr = widget->GetLayerManager();
   if (!mgr)
     return NS_ERROR_FAILURE;
 
   nsTArray<float> tmpFrameIntervals;
   mgr->StopFrameTimeRecording(startIndex, tmpFrameIntervals);
   *frameCount = tmpFrameIntervals.Length();
 
-  *frameIntervals = (float*)nsMemory::Alloc(*frameCount * sizeof(float));
+  *frameIntervals = (float*)moz_xmalloc(*frameCount * sizeof(float));
 
   /* copy over the frame intervals and paint times into the arrays we just allocated */
   for (uint32_t i = 0; i < *frameCount; i++) {
     (*frameIntervals)[i] = tmpFrameIntervals[i];
   }
 
   return NS_OK;
 }
--- a/dom/base/nsDocument.cpp
+++ b/dom/base/nsDocument.cpp
@@ -10082,17 +10082,17 @@ nsDocument::ScrollToRef()
   char* tmpstr = ToNewCString(mScrollToRef);
   if (!tmpstr) {
     return;
   }
 
   nsUnescape(tmpstr);
   nsAutoCString unescapedRef;
   unescapedRef.Assign(tmpstr);
-  nsMemory::Free(tmpstr);
+  free(tmpstr);
 
   nsresult rv = NS_ERROR_FAILURE;
   // We assume that the bytes are in UTF-8, as it says in the spec:
   // http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.1
   NS_ConvertUTF8toUTF16 ref(unescapedRef);
 
   nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
--- a/dom/base/nsFormData.cpp
+++ b/dom/base/nsFormData.cpp
@@ -235,17 +235,17 @@ nsFormData::Append(const nsAString& aNam
 
   if (dataType == nsIDataType::VTYPE_INTERFACE ||
       dataType == nsIDataType::VTYPE_INTERFACE_IS) {
     nsCOMPtr<nsISupports> supports;
     nsID *iid;
     rv = aValue->GetAsInterface(&iid, getter_AddRefs(supports));
     NS_ENSURE_SUCCESS(rv, rv);
 
-    nsMemory::Free(iid);
+    free(iid);
 
     nsCOMPtr<nsIDOMBlob> domBlob = do_QueryInterface(supports);
     nsRefPtr<File> blob = static_cast<File*>(domBlob.get());
     if (domBlob) {
       Optional<nsAString> temp;
       Append(aName, *blob, temp);
       return NS_OK;
     }
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -6086,17 +6086,17 @@ nsGlobalWindow::Dump(const nsAString& aS
     PrintToDebugger(cstr);
 #endif
 #ifdef ANDROID
     __android_log_write(ANDROID_LOG_INFO, "GeckoDump", cstr);
 #endif
     FILE *fp = gDumpFile ? gDumpFile : stdout;
     fputs(cstr, fp);
     fflush(fp);
-    nsMemory::Free(cstr);
+    free(cstr);
   }
 
   return NS_OK;
 }
 
 void
 nsGlobalWindow::EnsureReflowFlushAndPaint()
 {
--- a/dom/base/nsHTMLContentSerializer.cpp
+++ b/dom/base/nsHTMLContentSerializer.cpp
@@ -582,17 +582,17 @@ nsHTMLContentSerializer::AppendAndTransl
       }
       else if (fullConstEntityText) {
         NS_ENSURE_TRUE(aOutputStr.AppendASCII(fullConstEntityText, mozilla::fallible), false);
         ++advanceLength;
       }
       // if it comes from nsIEntityConverter, it already has '&' and ';'
       else if (fullEntityText) {
         bool ok = AppendASCIItoUTF16(fullEntityText, aOutputStr, mozilla::fallible);
-        nsMemory::Free(fullEntityText);
+        free(fullEntityText);
         advanceLength += lengthReplaced;
         NS_ENSURE_TRUE(ok, false);
       }
       NS_ENSURE_TRUE(result, false);
     }
   } else {
     NS_ENSURE_TRUE(nsXMLContentSerializer::AppendAndTranslateEntities(aStr, aOutputStr), false);
   }
--- a/dom/base/nsHostObjectURI.cpp
+++ b/dom/base/nsHostObjectURI.cpp
@@ -223,17 +223,17 @@ nsHostObjectURI::GetClassDescription(cha
   return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsHostObjectURI::GetClassID(nsCID * *aClassID)
 {
   // Make sure to modify any subclasses as needed if this ever
   // changes to not call the virtual GetClassIDNoAlloc.
-  *aClassID = (nsCID*) nsMemory::Alloc(sizeof(nsCID));
+  *aClassID = (nsCID*) moz_xmalloc(sizeof(nsCID));
   NS_ENSURE_TRUE(*aClassID, NS_ERROR_OUT_OF_MEMORY);
 
   return GetClassIDNoAlloc(*aClassID);
 }
 
 NS_IMETHODIMP 
 nsHostObjectURI::GetFlags(uint32_t *aFlags)
 {
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -312,17 +312,17 @@ nsJSEnvironmentObserver::Observe(nsISupp
  ****************************************************************/
 
 class AutoFree {
 public:
   explicit AutoFree(void* aPtr) : mPtr(aPtr) {
   }
   ~AutoFree() {
     if (mPtr)
-      nsMemory::Free(mPtr);
+      free(mPtr);
   }
   void Invalidate() {
     mPtr = 0;
   }
 private:
   void *mPtr;
 };
 
--- a/dom/base/nsPlainTextSerializer.cpp
+++ b/dom/base/nsPlainTextSerializer.cpp
@@ -1705,17 +1705,17 @@ nsPlainTextSerializer::Write(const nsASt
     // Find a place where we may have to do whitespace compression
     nextpos = str.FindCharInSet(" \t\n\r", bol);
 #ifdef DEBUG_wrapping
     nsAutoString remaining;
     str.Right(remaining, totLen - bol);
     foo = ToNewCString(remaining);
     //    printf("Next line: bol = %d, newlinepos = %d, totLen = %d, string = '%s'\n",
     //           bol, nextpos, totLen, foo);
-    nsMemory::Free(foo);
+    free(foo);
 #endif
 
     if (nextpos == kNotFound) {
       // The rest of the string
       offsetIntoBuffer = str.get() + bol;
       AddToLine(offsetIntoBuffer, totLen-bol);
       bol=totLen;
       mInWhitespace=false;
--- a/dom/base/nsScriptNameSpaceManager.cpp
+++ b/dom/base/nsScriptNameSpaceManager.cpp
@@ -629,17 +629,17 @@ nsScriptNameSpaceManager::OperateCategor
   if (NS_FAILED(rv)) {
     NS_WARNING("Bad contract id registed with the script namespace manager");
     return NS_OK;
   }
 
   // Copy CID onto the stack, so we can free it right away and avoid having
   // to add cleanup code at every exit point from this function.
   nsCID cid = *cidPtr;
-  nsMemory::Free(cidPtr);
+  free(cidPtr);
 
   if (type == nsGlobalNameStruct::eTypeExternalConstructor) {
     nsXPIDLCString constructorProto;
     rv = aCategoryManager->GetCategoryEntry(JAVASCRIPT_GLOBAL_CONSTRUCTOR_PROTO_ALIAS_CATEGORY,
                                             categoryEntry.get(),
                                             getter_Copies(constructorProto));
     if (NS_SUCCEEDED(rv)) {
       nsGlobalNameStruct *s = AddToHash(&mGlobalNames, categoryEntry.get());
--- a/dom/base/nsXMLHttpRequest.cpp
+++ b/dom/base/nsXMLHttpRequest.cpp
@@ -2461,17 +2461,17 @@ GetRequestBody(nsIVariant* aBody, nsIInp
 
   if (dataType == nsIDataType::VTYPE_INTERFACE ||
       dataType == nsIDataType::VTYPE_INTERFACE_IS) {
     nsCOMPtr<nsISupports> supports;
     nsID *iid;
     rv = aBody->GetAsInterface(&iid, getter_AddRefs(supports));
     NS_ENSURE_SUCCESS(rv, rv);
 
-    nsMemory::Free(iid);
+    free(iid);
 
     // document?
     nsCOMPtr<nsIDOMDocument> doc = do_QueryInterface(supports);
     if (doc) {
       return GetRequestBody(doc, aResult, aContentLength, aContentType, aCharset);
     }
 
     // nsISupportsString?
--- a/dom/canvas/WebGL2ContextTransformFeedback.cpp
+++ b/dom/canvas/WebGL2ContextTransformFeedback.cpp
@@ -201,17 +201,17 @@ WebGL2Context::TransformFeedbackVaryings
 {
     if (IsContextLost())
         return;
 
     if (!ValidateObject("transformFeedbackVaryings: program", program))
         return;
 
     GLsizei count = varyings.Length();
-    GLchar** tmpVaryings = (GLchar**) nsMemory::Alloc(count * sizeof(GLchar*));
+    GLchar** tmpVaryings = (GLchar**) moz_xmalloc(count * sizeof(GLchar*));
 
     for (GLsizei n = 0; n < count; n++) {
         tmpVaryings[n] = (GLchar*) ToNewCString(varyings[n]);
     }
 
     GLuint progname = program->mGLName;
     MakeContextCurrent();
     gl->fTransformFeedbackVaryings(progname, count, tmpVaryings, bufferMode);
--- a/dom/events/Event.cpp
+++ b/dom/events/Event.cpp
@@ -853,32 +853,32 @@ Event::GetEventPopupControlState(WidgetE
   return abuse;
 }
 
 // static
 void
 Event::PopupAllowedEventsChanged()
 {
   if (sPopupAllowedEvents) {
-    nsMemory::Free(sPopupAllowedEvents);
+    free(sPopupAllowedEvents);
   }
 
   nsAdoptingCString str = Preferences::GetCString("dom.popup_allowed_events");
 
   // We'll want to do this even if str is empty to avoid looking up
   // this pref all the time if it's not set.
   sPopupAllowedEvents = ToNewCString(str);
 }
 
 // static
 void
 Event::Shutdown()
 {
   if (sPopupAllowedEvents) {
-    nsMemory::Free(sPopupAllowedEvents);
+    free(sPopupAllowedEvents);
   }
 }
 
 LayoutDeviceIntPoint
 Event::GetScreenCoords(nsPresContext* aPresContext,
                        WidgetEvent* aEvent,
                        LayoutDeviceIntPoint aPoint)
 {
--- a/dom/events/EventListenerService.cpp
+++ b/dom/events/EventListenerService.cpp
@@ -147,17 +147,17 @@ EventListenerService::GetListenerInfoFor
 
   int32_t count = listenerInfos.Count();
   if (count == 0) {
     return NS_OK;
   }
 
   *aOutArray =
     static_cast<nsIEventListenerInfo**>(
-      nsMemory::Alloc(sizeof(nsIEventListenerInfo*) * count));
+      moz_xmalloc(sizeof(nsIEventListenerInfo*) * count));
   NS_ENSURE_TRUE(*aOutArray, NS_ERROR_OUT_OF_MEMORY);
 
   for (int32_t i = 0; i < count; ++i) {
     NS_ADDREF((*aOutArray)[i] = listenerInfos[i]);
   }
   *aCount = count;
   return NS_OK;
 }
@@ -177,17 +177,17 @@ EventListenerService::GetEventTargetChai
   NS_ENSURE_SUCCESS(rv, rv);
   int32_t count = targets.Length();
   if (count == 0) {
     return NS_OK;
   }
 
   *aOutArray =
     static_cast<nsIDOMEventTarget**>(
-      nsMemory::Alloc(sizeof(nsIDOMEventTarget*) * count));
+      moz_xmalloc(sizeof(nsIDOMEventTarget*) * count));
   NS_ENSURE_TRUE(*aOutArray, NS_ERROR_OUT_OF_MEMORY);
 
   for (int32_t i = 0; i < count; ++i) {
     NS_ADDREF((*aOutArray)[i] = targets[i]);
   }
   *aCount = count;
 
   return NS_OK;
--- a/dom/html/HTMLInputElement.cpp
+++ b/dom/html/HTMLInputElement.cpp
@@ -1174,17 +1174,17 @@ HTMLInputElement::~HTMLInputElement()
   DestroyImageLoadingContent();
   FreeData();
 }
 
 void
 HTMLInputElement::FreeData()
 {
   if (!IsSingleLineTextControl(false)) {
-    nsMemory::Free(mInputData.mValue);
+    free(mInputData.mValue);
     mInputData.mValue = nullptr;
   } else {
     UnbindFromFrame(nullptr);
     delete mInputData.mState;
     mInputData.mState = nullptr;
   }
 }
 
@@ -2890,17 +2890,17 @@ HTMLInputElement::SetValueInternal(const
       if (IsSingleLineTextControl(false)) {
         if (!mInputData.mState->SetValue(value, aUserInput, aSetValueChanged)) {
           return NS_ERROR_OUT_OF_MEMORY;
         }
         if (mType == NS_FORM_INPUT_EMAIL) {
           UpdateAllValidityStates(mParserCreating);
         }
       } else {
-        nsMemory::Free(mInputData.mValue);
+        free(mInputData.mValue);
         mInputData.mValue = ToNewUnicode(value);
         if (aSetValueChanged) {
           SetValueChanged(true);
         }
         if (mType == NS_FORM_INPUT_NUMBER) {
           // This has to happen before OnValueChanged is called because that
           // method needs the new value of our frame's anon text control.
           nsNumberControlFrame* numberControlFrame =
--- a/dom/html/nsFormSubmission.cpp
+++ b/dom/html/nsFormSubmission.cpp
@@ -355,17 +355,17 @@ nsFSURLEncoded::URLEncode(const nsAStrin
   char16_t* convertedBuf =
     nsLinebreakConverter::ConvertUnicharLineBreaks(PromiseFlatString(aStr).get(),
                                                    nsLinebreakConverter::eLinebreakAny,
                                                    nsLinebreakConverter::eLinebreakNet);
   NS_ENSURE_TRUE(convertedBuf, NS_ERROR_OUT_OF_MEMORY);
 
   nsAutoCString encodedBuf;
   nsresult rv = EncodeVal(nsDependentString(convertedBuf), encodedBuf, false);
-  nsMemory::Free(convertedBuf);
+  free(convertedBuf);
   NS_ENSURE_SUCCESS(rv, rv);
 
   char* escapedBuf = nsEscape(encodedBuf.get(), url_XPAlphas);
   NS_ENSURE_TRUE(escapedBuf, NS_ERROR_OUT_OF_MEMORY);
   aEncoded.Adopt(escapedBuf);
 
   return NS_OK;
 }
--- a/dom/html/nsHTMLDocument.cpp
+++ b/dom/html/nsHTMLDocument.cpp
@@ -3464,17 +3464,17 @@ nsHTMLDocument::QueryCommandState(const 
   if (cmdToDispatch.EqualsLiteral("cmd_align")) {
     char * actualAlignmentType = nullptr;
     rv = cmdParams->GetCStringValue("state_attribute", &actualAlignmentType);
     bool retval = false;
     if (!rv.Failed() && actualAlignmentType && actualAlignmentType[0]) {
       retval = paramToCheck.Equals(actualAlignmentType);
     }
     if (actualAlignmentType) {
-      nsMemory::Free(actualAlignmentType);
+      free(actualAlignmentType);
     }
     return retval;
   }
 
   // If command does not have a state_all value, this call fails and sets
   // retval to false.  This is fine -- we want to return false in that case
   // anyway (bug 738385), so we just succeed and return false regardless.
   bool retval = false;
--- a/dom/mobileconnection/MobileConnection.cpp
+++ b/dom/mobileconnection/MobileConnection.cpp
@@ -434,17 +434,17 @@ MobileConnection::GetSupportedNetworkTyp
 
   for (uint32_t i = 0; i < length; ++i) {
     int32_t type = types[i];
 
     MOZ_ASSERT(type < static_cast<int32_t>(MobileNetworkType::EndGuard_));
     aTypes.AppendElement(static_cast<MobileNetworkType>(type));
   }
 
-  nsMemory::Free(types);
+  free(types);
 }
 
 already_AddRefed<DOMRequest>
 MobileConnection::GetNetworks(ErrorResult& aRv)
 {
   if (!mMobileConnection) {
     aRv.Throw(NS_ERROR_FAILURE);
     return nullptr;
--- a/dom/mobileconnection/ipc/MobileConnectionChild.cpp
+++ b/dom/mobileconnection/ipc/MobileConnectionChild.cpp
@@ -109,17 +109,17 @@ NS_IMETHODIMP
 MobileConnectionChild::GetSupportedNetworkTypes(int32_t** aTypes,
                                                 uint32_t* aLength)
 {
   NS_ENSURE_ARG(aTypes);
   NS_ENSURE_ARG(aLength);
 
   *aLength = mSupportedNetworkTypes.Length();
   *aTypes =
-    static_cast<int32_t*>(nsMemory::Alloc((*aLength) * sizeof(int32_t)));
+    static_cast<int32_t*>(moz_xmalloc((*aLength) * sizeof(int32_t)));
   NS_ENSURE_TRUE(*aTypes, NS_ERROR_OUT_OF_MEMORY);
 
   for (uint32_t i = 0; i < *aLength; i++) {
     (*aTypes)[i] = mSupportedNetworkTypes[i];
   }
 
   return NS_OK;
 }
--- a/dom/mobileconnection/ipc/MobileConnectionParent.cpp
+++ b/dom/mobileconnection/ipc/MobileConnectionParent.cpp
@@ -142,17 +142,17 @@ MobileConnectionParent::RecvInit(nsMobil
 
   nsresult rv = mMobileConnection->GetSupportedNetworkTypes(&types, &length);
   NS_ENSURE_SUCCESS(rv, false);
 
   for (uint32_t i = 0; i < length; ++i) {
     aSupportedNetworkTypes->AppendElement(types[i]);
   }
 
-  nsMemory::Free(types);
+  free(types);
 
   return true;
 }
 
 // nsIMobileConnectionListener
 
 NS_IMPL_ISUPPORTS(MobileConnectionParent, nsIMobileConnectionListener)
 
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -1107,17 +1107,17 @@ void
 _memfree (void *ptr)
 {
   if (!NS_IsMainThread()) {
     NPN_PLUGIN_LOG(PLUGIN_LOG_ALWAYS,("NPN_memfree called from the wrong thread\n"));
   }
   NPN_PLUGIN_LOG(PLUGIN_LOG_NOISY, ("NPN_MemFree: ptr=%p\n", ptr));
 
   if (ptr)
-    nsMemory::Free(ptr);
+    free(ptr);
 }
 
 uint32_t
 _memflush(uint32_t size)
 {
   if (!NS_IsMainThread()) {
     NPN_PLUGIN_LOG(PLUGIN_LOG_ALWAYS,("NPN_memflush called from the wrong thread\n"));
   }
@@ -2534,17 +2534,17 @@ const char *
 
 void *
 _memalloc (uint32_t size)
 {
   if (!NS_IsMainThread()) {
     NPN_PLUGIN_LOG(PLUGIN_LOG_NORMAL,("NPN_memalloc called from the wrong thread\n"));
   }
   NPN_PLUGIN_LOG(PLUGIN_LOG_NOISY, ("NPN_MemAlloc: size=%d\n", size));
-  return nsMemory::Alloc(size);
+  return moz_xmalloc(size);
 }
 
 // Deprecated, only stubbed out
 void* /* OJI type: jref */
 _getJavaPeer(NPP npp)
 {
   NPN_PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("NPN_GetJavaPeer: npp=%p\n", (void*)npp));
   return nullptr;
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -1288,17 +1288,17 @@ nsNPAPIPluginInstance::GetFormValue(nsAS
   nsresult rv = GetValueFromPlugin(NPPVformValue, &value);
   if (NS_FAILED(rv) || !value)
     return NS_ERROR_FAILURE;
 
   CopyUTF8toUTF16(value, aValue);
 
   // NPPVformValue allocates with NPN_MemAlloc(), which uses
   // nsMemory.
-  nsMemory::Free(value);
+  free(value);
 
   return NS_OK;
 }
 
 nsresult
 nsNPAPIPluginInstance::PushPopupsEnabledState(bool aEnabled)
 {
   nsCOMPtr<nsPIDOMWindow> window = GetDOMWindow();
--- a/dom/plugins/base/nsPluginHost.cpp
+++ b/dom/plugins/base/nsPluginHost.cpp
@@ -1123,17 +1123,17 @@ nsPluginHost::GetPluginTags(uint32_t* aP
   uint32_t count = 0;
   nsRefPtr<nsPluginTag> plugin = mPlugins;
   while (plugin != nullptr) {
     count++;
     plugin = plugin->mNext;
   }
 
   *aResults = static_cast<nsIPluginTag**>
-                         (nsMemory::Alloc(count * sizeof(**aResults)));
+                         (moz_xmalloc(count * sizeof(**aResults)));
   if (!*aResults)
     return NS_ERROR_OUT_OF_MEMORY;
 
   *aPluginCount = count;
 
   plugin = mPlugins;
   for (uint32_t i = 0; i < count; i++) {
     (*aResults)[i] = plugin;
@@ -3504,17 +3504,17 @@ nsPluginHost::ParsePostBufferToFixHeader
     // of ContentLenHeader value in this case.
 
     newBufferLen = dataLen + headersLen;
     // in case there were single LFs in headers
     // reserve an extra space for CR will be added before each single LF
     int cntSingleLF = singleLF.Length();
     newBufferLen += cntSingleLF;
 
-    if (!(*outPostData = p = (char*)nsMemory::Alloc(newBufferLen)))
+    if (!(*outPostData = p = (char*)moz_xmalloc(newBufferLen)))
       return NS_ERROR_OUT_OF_MEMORY;
 
     // deal with single LF
     const char *s = inPostData;
     if (cntSingleLF) {
       for (int i=0; i<cntSingleLF; i++) {
         const char *plf = singleLF.ElementAt(i); // ptr to single LF in headers
         int n = plf - s; // bytes to copy
@@ -3533,21 +3533,21 @@ nsPluginHost::ParsePostBufferToFixHeader
       memcpy(p, s, headersLen); // copy the rest
       p += headersLen;
     }
   } else  if (dataLen) { // no ContentLenHeader is found but there is a data
     // make new output buffer big enough
     // to keep ContentLenHeader+value followed by data
     uint32_t l = sizeof(ContentLenHeader) + sizeof(CRLFCRLF) + 32;
     newBufferLen = dataLen + l;
-    if (!(*outPostData = p = (char*)nsMemory::Alloc(newBufferLen)))
+    if (!(*outPostData = p = (char*)moz_xmalloc(newBufferLen)))
       return NS_ERROR_OUT_OF_MEMORY;
     headersLen = PR_snprintf(p, l,"%s: %ld%s", ContentLenHeader, dataLen, CRLFCRLF);
     if (headersLen == l) { // if PR_snprintf has ate all extra space consider this as an error
-      nsMemory::Free(p);
+      free(p);
       *outPostData = 0;
       return NS_ERROR_FAILURE;
     }
     p += headersLen;
     newBufferLen = headersLen + dataLen;
   }
   // at this point we've done with headers.
   // there is a possibility that input buffer has only headers info in it
@@ -3637,17 +3637,17 @@ nsPluginHost::CreateTempFileToPost(const
         // a blank line, then the body. If no custom headers are required, simply
         // add a blank line ('\n') to the beginning of the file or buffer.
 
         char *parsedBuf;
         // assuming first 1K (or what we got) has all headers in,
         // lets parse it through nsPluginHost::ParsePostBufferToFixHeaders()
         ParsePostBufferToFixHeaders((const char *)buf, br, &parsedBuf, &bw);
         rv = outStream->Write(parsedBuf, bw, &br);
-        nsMemory::Free(parsedBuf);
+        free(parsedBuf);
         if (NS_FAILED(rv) || (bw != br))
           break;
 
         firstRead = false;
         continue;
       }
       bw = br;
       rv = outStream->Write(buf, bw, &br);
--- a/dom/plugins/base/nsPluginTags.cpp
+++ b/dom/plugins/base/nsPluginTags.cpp
@@ -117,17 +117,17 @@ CStringArrayToXPCArray(nsTArray<nsCStrin
   uint32_t count = aArray.Length();
   if (!count) {
     *aResults = nullptr;
     *aCount = 0;
     return NS_OK;
   }
 
   *aResults =
-    static_cast<char16_t**>(nsMemory::Alloc(count * sizeof(**aResults)));
+    static_cast<char16_t**>(moz_xmalloc(count * sizeof(**aResults)));
   *aCount = count;
 
   for (uint32_t i = 0; i < count; i++) {
     (*aResults)[i] = ToNewUnicode(NS_ConvertUTF8toUTF16(aArray[i]));
   }
 
   return NS_OK;
 }
--- a/dom/xbl/nsXBLProtoImplField.cpp
+++ b/dom/xbl/nsXBLProtoImplField.cpp
@@ -57,31 +57,31 @@ nsXBLProtoImplField::nsXBLProtoImplField
   if (aIsReadOnly)
     mJSAttributes |= JSPROP_READONLY;
 }
 
 nsXBLProtoImplField::~nsXBLProtoImplField()
 {
   MOZ_COUNT_DTOR(nsXBLProtoImplField);
   if (mFieldText)
-    nsMemory::Free(mFieldText);
+    free(mFieldText);
   NS_Free(mName);
   NS_CONTENT_DELETE_LIST_MEMBER(nsXBLProtoImplField, this, mNext);
 }
 
 void 
 nsXBLProtoImplField::AppendFieldText(const nsAString& aText)
 {
   if (mFieldText) {
     nsDependentString fieldTextStr(mFieldText, mFieldTextLength);
     nsAutoString newFieldText = fieldTextStr + aText;
     char16_t* temp = mFieldText;
     mFieldText = ToNewUnicode(newFieldText);
     mFieldTextLength = newFieldText.Length();
-    nsMemory::Free(temp);
+    free(temp);
   }
   else {
     mFieldText = ToNewUnicode(aText);
     mFieldTextLength = aText.Length();
   }
 }
 
 // XBL fields are represented on elements inheriting that field a bit trickily.
--- a/dom/xbl/nsXBLProtoImplMember.h
+++ b/dom/xbl/nsXBLProtoImplMember.h
@@ -26,25 +26,25 @@ struct nsXBLTextWithLineNumber
     mLineNumber(0)
   {
     MOZ_COUNT_CTOR(nsXBLTextWithLineNumber);
   }
 
   ~nsXBLTextWithLineNumber() {
     MOZ_COUNT_DTOR(nsXBLTextWithLineNumber);
     if (mText) {
-      nsMemory::Free(mText);
+      free(mText);
     }
   }
 
   void AppendText(const nsAString& aText) {
     if (mText) {
       char16_t* temp = mText;
       mText = ToNewUnicode(nsDependentString(temp) + aText);
-      nsMemory::Free(temp);
+      free(temp);
     } else {
       mText = ToNewUnicode(aText);
     }
   }
 
   char16_t* GetText() {
     return mText;
   }
@@ -63,17 +63,17 @@ class nsXBLProtoImplMember
 public:
   explicit nsXBLProtoImplMember(const char16_t* aName)
     : mNext(nullptr)
     , mExposeToUntrustedContent(false)
   {
     mName = ToNewUnicode(nsDependentString(aName));
   }
   virtual ~nsXBLProtoImplMember() {
-    nsMemory::Free(mName);
+    free(mName);
     NS_CONTENT_DELETE_LIST_MEMBER(nsXBLProtoImplMember, this, mNext);
   }
 
   nsXBLProtoImplMember* GetNext() { return mNext; }
   void SetNext(nsXBLProtoImplMember* aNext) { mNext = aNext; }
   bool ShouldExposeToUntrustedContent() { return mExposeToUntrustedContent; }
   void SetExposeToUntrustedContent(bool aExpose) { mExposeToUntrustedContent = aExpose; }
   const char16_t* GetName() { return mName; }
--- a/dom/xbl/nsXBLProtoImplMethod.h
+++ b/dom/xbl/nsXBLProtoImplMethod.h
@@ -23,17 +23,17 @@ struct nsXBLParameter {
   explicit nsXBLParameter(const nsAString& aName) {
     MOZ_COUNT_CTOR(nsXBLParameter);
     mName = ToNewCString(aName);
     mNext = nullptr;
   }
 
   ~nsXBLParameter() {
     MOZ_COUNT_DTOR(nsXBLParameter);
-    nsMemory::Free(mName);
+    free(mName);
     NS_CONTENT_DELETE_LIST_MEMBER(nsXBLParameter, this, mNext);
   }
 };
 
 struct nsXBLUncompiledMethod {
   nsXBLParameter* mParameters;
   nsXBLParameter* mLastParameter;
   nsXBLTextWithLineNumber mBodyText;
--- a/dom/xbl/nsXBLPrototypeBinding.cpp
+++ b/dom/xbl/nsXBLPrototypeBinding.cpp
@@ -696,17 +696,17 @@ nsXBLPrototypeBinding::ConstructAttribut
         // by the template only, and we don't need it anymore.
         // XXXdwh Don't do this for XUL elements, since it faults them into heavyweight
         // elements. Should nuke from the prototype instead.
         // aElement->UnsetAttr(kNameSpaceID_XBL, nsGkAtoms::inherits, false);
 
         token = nsCRT::strtok( newStr, ", ", &newStr );
       }
 
-      nsMemory::Free(str);
+      free(str);
     }
   }
 
   // Recur into our children.
   for (nsIContent* child = aElement->GetFirstChild();
        child;
        child = child->GetNextSibling()) {
     ConstructAttributeTable(child);
--- a/dom/xbl/nsXBLPrototypeHandler.cpp
+++ b/dom/xbl/nsXBLPrototypeHandler.cpp
@@ -119,17 +119,17 @@ nsXBLPrototypeHandler::nsXBLPrototypeHan
 }
 
 nsXBLPrototypeHandler::~nsXBLPrototypeHandler()
 {
   --gRefCnt;
   if (mType & NS_HANDLER_TYPE_XUL) {
     NS_IF_RELEASE(mHandlerElement);
   } else if (mHandlerText) {
-    nsMemory::Free(mHandlerText);
+    free(mHandlerText);
   }
 
   // We own the next handler in the chain, so delete it now.
   NS_CONTENT_DELETE_LIST_MEMBER(nsXBLPrototypeHandler, this, mNextHandler);
 }
 
 already_AddRefed<nsIContent>
 nsXBLPrototypeHandler::GetHandlerElement()
@@ -144,17 +144,17 @@ nsXBLPrototypeHandler::GetHandlerElement
 
 void
 nsXBLPrototypeHandler::AppendHandlerText(const nsAString& aText) 
 {
   if (mHandlerText) {
     // Append our text to the existing text.
     char16_t* temp = mHandlerText;
     mHandlerText = ToNewUnicode(nsDependentString(temp) + aText);
-    nsMemory::Free(temp);
+    free(temp);
   }
   else {
     mHandlerText = ToNewUnicode(aText);
   }
 }
 
 /////////////////////////////////////////////////////////////////////////////
 // Get the menu access key from prefs.
@@ -829,17 +829,17 @@ nsXBLPrototypeHandler::ConstructPrototyp
       else if (PL_strcmp(token, "access") == 0)
         mKeyMask |= KeyToMask(kMenuAccessKey);
       else if (PL_strcmp(token, "any") == 0)
         mKeyMask &= ~(mKeyMask << 5);
     
       token = nsCRT::strtok( newStr, ", \t", &newStr );
     }
 
-    nsMemory::Free(str);
+    free(str);
   }
 
   nsAutoString key(aCharCode);
   if (key.IsEmpty()) {
     if (mType & NS_HANDLER_TYPE_XUL) {
       aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::key, key);
       if (key.IsEmpty()) 
         aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::charcode, key);
--- a/dom/xslt/xpath/txNodeSet.cpp
+++ b/dom/xslt/xpath/txNodeSet.cpp
@@ -79,17 +79,17 @@ txNodeSet::txNodeSet(const txNodeSet& aS
 
 txNodeSet::~txNodeSet()
 {
     delete [] mMarks;
 
     if (mStartBuffer) {
         destroyElements(mStart, mEnd);
 
-        nsMemory::Free(mStartBuffer);
+        free(mStartBuffer);
     }
 }
 
 nsresult txNodeSet::add(const txXPathNode& aNode)
 {
     NS_ASSERTION(mDirection == kForward,
                  "only append(aNode) is supported on reversed nodesets");
 
@@ -132,17 +132,17 @@ nsresult txNodeSet::add(const txNodeSet&
 nsresult txNodeSet::addAndTransfer(txNodeSet* aNodes)
 {
     // failure is out-of-memory, transfer didn't happen
     nsresult rv = add(*aNodes, transferElements, destroyElements);
     NS_ENSURE_SUCCESS(rv, rv);
 
 #ifdef TX_DONT_RECYCLE_BUFFER
     if (aNodes->mStartBuffer) {
-        nsMemory::Free(aNodes->mStartBuffer);
+        free(aNodes->mStartBuffer);
         aNodes->mStartBuffer = aNodes->mEndBuffer = nullptr;
     }
 #endif
     aNodes->mStart = aNodes->mEnd = aNodes->mStartBuffer;
 
     return NS_OK;
 }
 
@@ -407,17 +407,17 @@ txNodeSet::sweep()
 }
 
 void
 txNodeSet::clear()
 {
     destroyElements(mStart, mEnd);
 #ifdef TX_DONT_RECYCLE_BUFFER
     if (mStartBuffer) {
-        nsMemory::Free(mStartBuffer);
+        free(mStartBuffer);
         mStartBuffer = mEndBuffer = nullptr;
     }
 #endif
     mStart = mEnd = mStartBuffer;
     delete [] mMarks;
     mMarks = nullptr;
     mDirection = kForward;
 }
@@ -522,17 +522,17 @@ bool txNodeSet::ensureGrowSize(int32_t a
     // it should be ok.
     int32_t newLength = std::max(oldLength, kTxNodeSetMinSize);
 
     while (newLength < ensureSize) {
         newLength *= kTxNodeSetGrowFactor;
     }
 
     txXPathNode* newArr = static_cast<txXPathNode*>
-                                     (nsMemory::Alloc(newLength *
+                                     (moz_xmalloc(newLength *
                                                          sizeof(txXPathNode)));
     if (!newArr) {
         return false;
     }
 
     txXPathNode* dest = newArr;
     if (mDirection == kReversed) {
         dest += newLength - oldSize;
@@ -543,17 +543,17 @@ bool txNodeSet::ensureGrowSize(int32_t a
         memcpy(dest, mStart, oldSize * sizeof(txXPathNode));
     }
 
     if (mStartBuffer) {
 #ifdef DEBUG
         memset(mStartBuffer, 0,
                (mEndBuffer - mStartBuffer) * sizeof(txXPathNode));
 #endif
-        nsMemory::Free(mStartBuffer);
+        free(mStartBuffer);
     }
 
     mStartBuffer = newArr;
     mEndBuffer = mStartBuffer + newLength;
     mStart = dest;
     mEnd = dest + oldSize;
 
     return true;
--- a/dom/xslt/xslt/txMozillaXSLTProcessor.cpp
+++ b/dom/xslt/xslt/txMozillaXSLTProcessor.cpp
@@ -887,17 +887,17 @@ txMozillaXSLTProcessor::SetParameter(con
             nsIID iid;
             uint32_t count;
             void* array;
             nsresult rv = value->GetAsArray(&type, &iid, &count, &array);
             NS_ENSURE_SUCCESS(rv, rv);
 
             if (type != nsIDataType::VTYPE_INTERFACE &&
                 type != nsIDataType::VTYPE_INTERFACE_IS) {
-                nsMemory::Free(array);
+                free(array);
 
                 // We only support arrays of DOM nodes.
                 return NS_ERROR_ILLEGAL_VALUE;
             }
 
             nsISupports** values = static_cast<nsISupports**>(array);
 
             uint32_t i;
@@ -914,25 +914,25 @@ txMozillaXSLTProcessor::SetParameter(con
                     rv = NS_ERROR_ILLEGAL_VALUE;
                 }
 
                 if (NS_FAILED(rv)) {
                     while (i < count) {
                         NS_IF_RELEASE(values[i]);
                         ++i;
                     }
-                    nsMemory::Free(array);
+                    free(array);
 
                     return rv;
                 }
 
                 NS_RELEASE(supports);
             }
 
-            nsMemory::Free(array);
+            free(array);
 
             break;
         }
 
         default:
         {
             return NS_ERROR_FAILURE;
         }        
@@ -1574,27 +1574,27 @@ txVariable::Convert(nsIVariant *aValue, 
 
                 nsAutoPtr<txXPathNode> xpathNode(
                     txXPathNativeNode::createXPathNode(node));
                 if (!xpathNode) {
                     while (i < count) {
                         NS_RELEASE(values[i]);
                         ++i;
                     }
-                    nsMemory::Free(array);
+                    free(array);
 
                     return NS_ERROR_FAILURE;
                 }
 
                 nodeSet->add(*xpathNode);
 
                 NS_RELEASE(supports);
             }
 
-            nsMemory::Free(array);
+            free(array);
 
             NS_ADDREF(*aResult = nodeSet);
 
             return NS_OK;
         }
     }
 
     return NS_ERROR_ILLEGAL_VALUE;
--- a/dom/xul/XULDocument.cpp
+++ b/dom/xul/XULDocument.cpp
@@ -4366,17 +4366,17 @@ XULDocument::InsertElement(nsINode* aPar
 
         while (token) {
             content = document->GetElementById(NS_ConvertASCIItoUTF16(token));
             if (content)
                 break;
 
             token = nsCRT::strtok(rest, ", ", &rest);
         }
-        nsMemory::Free(str);
+        free(str);
 
         if (content) {
             int32_t pos = aParent->IndexOf(content);
 
             if (pos != -1) {
                 pos = isInsertAfter ? pos + 1 : pos;
                 nsresult rv = aParent->InsertChildAt(aChild, pos, aNotify);
                 if (NS_FAILED(rv))
--- a/editor/composer/nsEditorSpellCheck.cpp
+++ b/editor/composer/nsEditorSpellCheck.cpp
@@ -539,28 +539,28 @@ nsEditorSpellCheck::GetDictionaryList(ch
 
   char16_t **tmpPtr = 0;
 
   if (dictList.Length() < 1)
   {
     // If there are no dictionaries, return an array containing
     // one element and a count of one.
 
-    tmpPtr = (char16_t **)nsMemory::Alloc(sizeof(char16_t *));
+    tmpPtr = (char16_t **)moz_xmalloc(sizeof(char16_t *));
 
     NS_ENSURE_TRUE(tmpPtr, NS_ERROR_OUT_OF_MEMORY);
 
     *tmpPtr          = 0;
     *aDictionaryList = tmpPtr;
     *aCount          = 0;
 
     return NS_OK;
   }
 
-  tmpPtr = (char16_t **)nsMemory::Alloc(sizeof(char16_t *) * dictList.Length());
+  tmpPtr = (char16_t **)moz_xmalloc(sizeof(char16_t *) * dictList.Length());
 
   NS_ENSURE_TRUE(tmpPtr, NS_ERROR_OUT_OF_MEMORY);
 
   *aDictionaryList = tmpPtr;
   *aCount          = dictList.Length();
 
   uint32_t i;
 
--- a/extensions/auth/nsAuthSASL.cpp
+++ b/extensions/auth/nsAuthSASL.cpp
@@ -95,35 +95,35 @@ nsAuthSASL::GetNextToken(const void *inT
         if (NS_FAILED(rv)) {
             Reset();
             return rv;
         }
         
         // If we were doing security layers then we'd care what the
         // server had sent us. We're not, so all we had to do was make
         // sure that the signature was correct with the above unwrap()
-        nsMemory::Free(unwrappedToken);
+        free(unwrappedToken);
         
         NS_CopyUnicodeToNative(mUsername, userbuf);
         messageLen = userbuf.Length() + 4 + 1;
-        message = (char *)nsMemory::Alloc(messageLen);
+        message = (char *)moz_xmalloc(messageLen);
         if (!message) {
           Reset();
           return NS_ERROR_OUT_OF_MEMORY;
         }
         message[0] = 0x01; // No security layer
         message[1] = 0x00;
         message[2] = 0x00;
         message[3] = 0x00; // Maxbuf must be zero if we've got no sec layer
         strcpy(message+4, userbuf.get());
         // Userbuf should not be nullptr terminated, so trim the trailing nullptr
         // when wrapping the message
         rv = mInnerModule->Wrap((void *) message, messageLen-1, false, 
                                 outToken, outTokenLen);
-        nsMemory::Free(message);
+        free(message);
         Reset(); // All done
         return NS_SUCCEEDED(rv) ? NS_SUCCESS_AUTH_FINISHED : rv;
     }
     rv = mInnerModule->GetNextToken(inToken, inTokenLen, outToken, 
                                     outTokenLen);
     if (rv == NS_SUCCESS_AUTH_FINISHED) {
         mSASLReady = true;
         rv = NS_OK;
--- a/extensions/auth/nsAuthSSPI.cpp
+++ b/extensions/auth/nsAuthSSPI.cpp
@@ -162,17 +162,17 @@ nsAuthSSPI::~nsAuthSSPI()
 }
 
 void
 nsAuthSSPI::Reset()
 {
     mIsFirst = true;
 
     if (mCertDERData){
-        nsMemory::Free(mCertDERData);
+        free(mCertDERData);
         mCertDERData = nullptr;
         mCertDERLength = 0;   
     }
 
     if (mCtxt.dwLower || mCtxt.dwUpper) {
         (sspi->DeleteSecurityContext)(&mCtxt);
         memset(&mCtxt, 0, sizeof(mCtxt));
     }
@@ -329,17 +329,17 @@ nsAuthSSPI::GetNextToken(const void *inT
         ctxReq |= ISC_REQ_MUTUAL_AUTH;
 
     if (inToken) {
         if (mIsFirst) {
             // First time if it comes with a token,
             // the token represents the server certificate.
             mIsFirst = false;
             mCertDERLength = inTokenLen;
-            mCertDERData = nsMemory::Alloc(inTokenLen);
+            mCertDERData = moz_xmalloc(inTokenLen);
             if (!mCertDERData)
                 return NS_ERROR_OUT_OF_MEMORY;
             memcpy(mCertDERData, inToken, inTokenLen);
 
             // We are starting a new authentication sequence.  
             // If we have already initialized our
             // security context, then we're in trouble because it means that the
             // first sequence failed.  We need to bail or else we might end up in
@@ -373,17 +373,17 @@ nsAuthSSPI::GetNextToken(const void *inT
                                             sizeof(SEC_CHANNEL_BINDINGS);
 
                 // Then add it to the array of sec buffers accordingly.
                 ib[ibd.cBuffers].BufferType = SECBUFFER_CHANNEL_BINDINGS;
                 ib[ibd.cBuffers].cbBuffer =
                         pendpoint_binding.cbApplicationDataLength
                         + pendpoint_binding.dwApplicationDataOffset;
           
-                sspi_cbt = (char *) nsMemory::Alloc(ib[ibd.cBuffers].cbBuffer);
+                sspi_cbt = (char *) moz_xmalloc(ib[ibd.cBuffers].cbBuffer);
                 if (!sspi_cbt){
                     return NS_ERROR_OUT_OF_MEMORY;
                 }
 
                 // Helper to write in the memory block that stores the CBT
                 char* sspi_cbt_ptr = sspi_cbt;
           
                 ib[ibd.cBuffers].pvBuffer = sspi_cbt;
@@ -405,30 +405,30 @@ nsAuthSSPI::GetNextToken(const void *inT
                 crypto = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, &rv);
                 if (NS_SUCCEEDED(rv))
                     rv = crypto->Init(nsICryptoHash::SHA256);
                 if (NS_SUCCEEDED(rv))
                     rv = crypto->Update((unsigned char*)mCertDERData, mCertDERLength);
                 if (NS_SUCCEEDED(rv))
                     rv = crypto->Finish(false, hashString);
                 if (NS_FAILED(rv)) {
-                    nsMemory::Free(mCertDERData);
+                    free(mCertDERData);
                     mCertDERData = nullptr;
                     mCertDERLength = 0;
-                    nsMemory::Free(sspi_cbt);
+                    free(sspi_cbt);
                     return rv;
                 }
           
                 // Once the hash has been computed, we store it in memory right
                 // after the Endpoint structure and the "tls-server-end-point:"
                 // char array.
                 memcpy(sspi_cbt_ptr, hashString.get(), hash_size);
           
                 // Free memory used to store the server certificate
-                nsMemory::Free(mCertDERData);
+                free(mCertDERData);
                 mCertDERData = nullptr;
                 mCertDERLength = 0;
             } // End of CBT computation.
 
             // We always need this SECBUFFER.
             ib[ibd.cBuffers].BufferType = SECBUFFER_TOKEN;
             ib[ibd.cBuffers].cbBuffer = inTokenLen;
             ib[ibd.cBuffers].pvBuffer = (void *) inToken;
@@ -448,20 +448,20 @@ nsAuthSSPI::GetNextToken(const void *inT
         mIsFirst = false;
     }
 
     obd.ulVersion = SECBUFFER_VERSION;
     obd.cBuffers = 1;
     obd.pBuffers = &ob;
     ob.BufferType = SECBUFFER_TOKEN;
     ob.cbBuffer = mMaxTokenLen;
-    ob.pvBuffer = nsMemory::Alloc(ob.cbBuffer);
+    ob.pvBuffer = moz_xmalloc(ob.cbBuffer);
     if (!ob.pvBuffer){
         if (sspi_cbt)
-            nsMemory::Free(sspi_cbt);
+            free(sspi_cbt);
         return NS_ERROR_OUT_OF_MEMORY;
     }
     memset(ob.pvBuffer, 0, ob.cbBuffer);
 
     NS_ConvertUTF8toUTF16 wSN(mServiceName);
     SEC_WCHAR *sn = (SEC_WCHAR *) wSN.get();
 
     rc = (sspi->InitializeSecurityContextW)(&mCred,
@@ -480,34 +480,34 @@ nsAuthSSPI::GetNextToken(const void *inT
 
 #ifdef PR_LOGGING
         if (rc == SEC_E_OK)
             LOG(("InitializeSecurityContext: succeeded.\n"));
         else
             LOG(("InitializeSecurityContext: continue.\n"));
 #endif
         if (sspi_cbt)
-            nsMemory::Free(sspi_cbt);
+            free(sspi_cbt);
             
         if (!ob.cbBuffer) {
-            nsMemory::Free(ob.pvBuffer);
+            free(ob.pvBuffer);
             ob.pvBuffer = nullptr;
         }
         *outToken = ob.pvBuffer;
         *outTokenLen = ob.cbBuffer;
 
         if (rc == SEC_E_OK)
             return NS_SUCCESS_AUTH_FINISHED;
 
         return NS_OK;
     }
 
     LOG(("InitializeSecurityContext failed [rc=%d:%s]\n", rc, MapErrorCode(rc)));
     Reset();
-    nsMemory::Free(ob.pvBuffer);
+    free(ob.pvBuffer);
     return NS_ERROR_FAILURE;
 }
 
 NS_IMETHODIMP
 nsAuthSSPI::Unwrap(const void *inToken,
                    uint32_t    inTokenLen,
                    void      **outToken,
                    uint32_t   *outTokenLen)
@@ -518,17 +518,17 @@ nsAuthSSPI::Unwrap(const void *inToken,
 
     ibd.cBuffers = 2;
     ibd.pBuffers = ib;
     ibd.ulVersion = SECBUFFER_VERSION; 
 
     // SSPI Buf
     ib[0].BufferType = SECBUFFER_STREAM;
     ib[0].cbBuffer = inTokenLen;
-    ib[0].pvBuffer = nsMemory::Alloc(ib[0].cbBuffer);
+    ib[0].pvBuffer = moz_xmalloc(ib[0].cbBuffer);
     if (!ib[0].pvBuffer)
         return NS_ERROR_OUT_OF_MEMORY;
     
     memcpy(ib[0].pvBuffer, inToken, inTokenLen);
 
     // app data
     ib[1].BufferType = SECBUFFER_DATA;
     ib[1].cbBuffer = 0;
@@ -545,24 +545,24 @@ nsAuthSSPI::Unwrap(const void *inToken,
         // check if ib[1].pvBuffer is really just ib[0].pvBuffer, in which
         // case we can let the caller free it. Otherwise, we need to
         // clone it, and free the original
         if (ib[0].pvBuffer == ib[1].pvBuffer) {
             *outToken = ib[1].pvBuffer;
         }
         else {
             *outToken = nsMemory::Clone(ib[1].pvBuffer, ib[1].cbBuffer);
-            nsMemory::Free(ib[0].pvBuffer);
+            free(ib[0].pvBuffer);
             if (!*outToken)
                 return NS_ERROR_OUT_OF_MEMORY;
         }
         *outTokenLen = ib[1].cbBuffer;
     }
     else
-        nsMemory::Free(ib[0].pvBuffer);
+        free(ib[0].pvBuffer);
 
     if (!SEC_SUCCESS(rc))
         return NS_ERROR_FAILURE;
 
     return NS_OK;
 }
 
 // utility class used to free memory on exit
@@ -572,23 +572,23 @@ public:
 
     SecBuffer ib[3];
 
     secBuffers() { memset(&ib, 0, sizeof(ib)); }
 
     ~secBuffers() 
     {
         if (ib[0].pvBuffer)
-            nsMemory::Free(ib[0].pvBuffer);
+            free(ib[0].pvBuffer);
 
         if (ib[1].pvBuffer)
-            nsMemory::Free(ib[1].pvBuffer);
+            free(ib[1].pvBuffer);
 
         if (ib[2].pvBuffer)
-            nsMemory::Free(ib[2].pvBuffer);
+            free(ib[2].pvBuffer);
     }
 };
 
 NS_IMETHODIMP
 nsAuthSSPI::Wrap(const void *inToken,
                  uint32_t    inTokenLen,
                  bool        confidential,
                  void      **outToken,
@@ -610,46 +610,46 @@ nsAuthSSPI::Wrap(const void *inToken,
     
     ibd.cBuffers = 3;
     ibd.pBuffers = bufs.ib;
     ibd.ulVersion = SECBUFFER_VERSION;
     
     // SSPI
     bufs.ib[0].cbBuffer = sizes.cbSecurityTrailer;
     bufs.ib[0].BufferType = SECBUFFER_TOKEN;
-    bufs.ib[0].pvBuffer = nsMemory::Alloc(sizes.cbSecurityTrailer);
+    bufs.ib[0].pvBuffer = moz_xmalloc(sizes.cbSecurityTrailer);
 
     if (!bufs.ib[0].pvBuffer)
         return NS_ERROR_OUT_OF_MEMORY;
 
     // APP Data
     bufs.ib[1].BufferType = SECBUFFER_DATA;
-    bufs.ib[1].pvBuffer = nsMemory::Alloc(inTokenLen);
+    bufs.ib[1].pvBuffer = moz_xmalloc(inTokenLen);
     bufs.ib[1].cbBuffer = inTokenLen;
     
     if (!bufs.ib[1].pvBuffer)
         return NS_ERROR_OUT_OF_MEMORY;
 
     memcpy(bufs.ib[1].pvBuffer, inToken, inTokenLen);
 
     // SSPI
     bufs.ib[2].BufferType = SECBUFFER_PADDING;
     bufs.ib[2].cbBuffer = sizes.cbBlockSize;
-    bufs.ib[2].pvBuffer = nsMemory::Alloc(bufs.ib[2].cbBuffer);
+    bufs.ib[2].pvBuffer = moz_xmalloc(bufs.ib[2].cbBuffer);
 
     if (!bufs.ib[2].pvBuffer)
         return NS_ERROR_OUT_OF_MEMORY;
 
     rc = (sspi->EncryptMessage)(&mCtxt,
           confidential ? 0 : KERB_WRAP_NO_ENCRYPT,
          &ibd, 0);
 
     if (SEC_SUCCESS(rc)) {
         int len  = bufs.ib[0].cbBuffer + bufs.ib[1].cbBuffer + bufs.ib[2].cbBuffer;
-        char *p = (char *) nsMemory::Alloc(len);
+        char *p = (char *) moz_xmalloc(len);
 
         if (!p)
             return NS_ERROR_OUT_OF_MEMORY;
 				
         *outToken = (void *) p;
         *outTokenLen = len;
 
         memcpy(p, bufs.ib[0].pvBuffer, bufs.ib[0].cbBuffer);
--- a/extensions/auth/nsAuthSambaNTLM.cpp
+++ b/extensions/auth/nsAuthSambaNTLM.cpp
@@ -258,17 +258,16 @@ nsAuthSambaNTLM::GetNextToken(const void
         return NS_ERROR_FAILURE;
     if (!StringBeginsWith(line, NS_LITERAL_CSTRING("KK "))) {
         // Something went wrong. Perhaps no credentials are accessible.
         return NS_ERROR_FAILURE;
     }
     uint8_t* buf = ExtractMessage(line, outTokenLen);
     if (!buf)
         return NS_ERROR_FAILURE;
-    // *outToken has to be freed by nsMemory::Free, which may not be free() 
     *outToken = nsMemory::Clone(buf, *outTokenLen);
     free(buf);
     if (!*outToken) {
         return NS_ERROR_OUT_OF_MEMORY;
     }
     
     // We're done. Close our file descriptors now and reap the helper
     // process.
--- a/extensions/auth/nsHttpNegotiateAuth.cpp
+++ b/extensions/auth/nsHttpNegotiateAuth.cpp
@@ -263,25 +263,25 @@ nsHttpNegotiateAuth::GenerateCredentials
         return NS_ERROR_FAILURE;
     }
 
     //
     // base64 encode the output token.
     //
     char *encoded_token = PL_Base64Encode((char *)outToken, outTokenLen, nullptr);
 
-    nsMemory::Free(outToken);
+    free(outToken);
 
     if (!encoded_token)
         return NS_ERROR_OUT_OF_MEMORY;
 
     LOG(("  Sending a token of length %d\n", outTokenLen));
 
     // allocate a buffer sizeof("Negotiate" + " " + b64output_token + "\0")
-    *creds = (char *) nsMemory::Alloc(kNegotiateLen + 1 + strlen(encoded_token) + 1);
+    *creds = (char *) moz_xmalloc(kNegotiateLen + 1 + strlen(encoded_token) + 1);
     if (MOZ_UNLIKELY(!*creds))
         rv = NS_ERROR_OUT_OF_MEMORY;
     else
         sprintf(*creds, "%s %s", kNegotiate, encoded_token);
 
     PR_Free(encoded_token);
     return rv;
 }
@@ -363,17 +363,17 @@ nsHttpNegotiateAuth::TestPref(nsIURI *ur
             break;
         if (MatchesBaseURI(scheme, host, port, start, end))
             return true;
         if (*end == '\0')
             break;
         start = end + 1;
     }
     
-    nsMemory::Free(hostList);
+    free(hostList);
     return false;
 }
 
 bool
 nsHttpNegotiateAuth::MatchesBaseURI(const nsCSubstring &matchScheme,
                                     const nsCSubstring &matchHost,
                                     int32_t             matchPort,
                                     const char         *baseStart,
--- a/extensions/gio/nsGIOProtocolHandler.cpp
+++ b/extensions/gio/nsGIOProtocolHandler.cpp
@@ -870,18 +870,18 @@ mount_operation_ask_password (GMountOper
   }
   if (NS_FAILED(rv) || !retval) {  //  was || user == '\0' || pass == '\0'
     g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_ABORTED);
     return;
   }
   /* GIO should accept UTF8 */
   g_mount_operation_set_username(mount_op, NS_ConvertUTF16toUTF8(user).get());
   g_mount_operation_set_password(mount_op, NS_ConvertUTF16toUTF8(pass).get());
-  nsMemory::Free(user);
-  nsMemory::Free(pass);
+  free(user);
+  free(pass);
   g_mount_operation_reply(mount_op, G_MOUNT_OPERATION_HANDLED);
 }
 
 //-----------------------------------------------------------------------------
 
 class nsGIOProtocolHandler final : public nsIProtocolHandler
                                  , public nsIObserver
 {
--- a/extensions/spellcheck/hunspell/src/mozHunspell.cpp
+++ b/extensions/spellcheck/hunspell/src/mozHunspell.cpp
@@ -504,17 +504,17 @@ nsresult mozHunspell::ConvertCharset(con
   NS_ENSURE_ARG_POINTER(aDst);
   NS_ENSURE_TRUE(mEncoder, NS_ERROR_NULL_POINTER);
 
   int32_t outLength;
   int32_t inLength = NS_strlen(aStr);
   nsresult rv = mEncoder->GetMaxLength(aStr, inLength, &outLength);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  *aDst = (char *) nsMemory::Alloc(sizeof(char) * (outLength+1));
+  *aDst = (char *) moz_xmalloc(sizeof(char) * (outLength+1));
   NS_ENSURE_TRUE(*aDst, NS_ERROR_OUT_OF_MEMORY);
 
   rv = mEncoder->Convert(aStr, &inLength, *aDst, &outLength);
   if (NS_SUCCEEDED(rv))
     (*aDst)[outLength] = '\0';
 
   return rv;
 }
@@ -552,27 +552,27 @@ NS_IMETHODIMP mozHunspell::Suggest(const
   nsXPIDLCString charsetWord;
   rv = ConvertCharset(aWord, getter_Copies(charsetWord));
   NS_ENSURE_SUCCESS(rv, rv);
 
   char ** wlst;
   *aSuggestionCount = mHunspell->suggest(&wlst, charsetWord);
 
   if (*aSuggestionCount) {
-    *aSuggestions  = (char16_t **)nsMemory::Alloc(*aSuggestionCount * sizeof(char16_t *));
+    *aSuggestions  = (char16_t **)moz_xmalloc(*aSuggestionCount * sizeof(char16_t *));
     if (*aSuggestions) {
       uint32_t index = 0;
       for (index = 0; index < *aSuggestionCount && NS_SUCCEEDED(rv); ++index) {
         // Convert the suggestion to utf16
         int32_t inLength = strlen(wlst[index]);
         int32_t outLength;
         rv = mDecoder->GetMaxLength(wlst[index], inLength, &outLength);
         if (NS_SUCCEEDED(rv))
         {
-          (*aSuggestions)[index] = (char16_t *) nsMemory::Alloc(sizeof(char16_t) * (outLength+1));
+          (*aSuggestions)[index] = (char16_t *) moz_xmalloc(sizeof(char16_t) * (outLength+1));
           if ((*aSuggestions)[index])
           {
             rv = mDecoder->Convert(wlst[index], &inLength, (*aSuggestions)[index], &outLength);
             if (NS_SUCCEEDED(rv))
               (*aSuggestions)[index][outLength] = 0;
           }
           else
             rv = NS_ERROR_OUT_OF_MEMORY;
--- a/extensions/spellcheck/src/mozEnglishWordUtils.cpp
+++ b/extensions/spellcheck/src/mozEnglishWordUtils.cpp
@@ -57,31 +57,31 @@ NS_IMETHODIMP mozEnglishWordUtils::GetRo
 
   *count = 0;
 
   mozEnglishWordUtils::myspCapitalization ct = captype(word);
   switch (ct)
     {
     case HuhCap:
     case NoCap: 
-      tmpPtr = (char16_t **)nsMemory::Alloc(sizeof(char16_t *));
+      tmpPtr = (char16_t **)moz_xmalloc(sizeof(char16_t *));
       if (!tmpPtr)
         return NS_ERROR_OUT_OF_MEMORY;
       tmpPtr[0] = ToNewUnicode(word);
       if (!tmpPtr[0]) {
         NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(0, tmpPtr);
         return NS_ERROR_OUT_OF_MEMORY;
       }
       *words = tmpPtr;
       *count = 1;
       break;
     
 
     case AllCap:
-      tmpPtr = (char16_t **)nsMemory::Alloc(sizeof(char16_t *) * 3);
+      tmpPtr = (char16_t **)moz_xmalloc(sizeof(char16_t *) * 3);
       if (!tmpPtr)
         return NS_ERROR_OUT_OF_MEMORY;
       tmpPtr[0] = ToNewUnicode(word);
       if (!tmpPtr[0]) {
         NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(0, tmpPtr);
         return NS_ERROR_OUT_OF_MEMORY;
       }
       ToLowerCase(tmpPtr[0], tmpPtr[0], length);
@@ -100,17 +100,17 @@ NS_IMETHODIMP mozEnglishWordUtils::GetRo
         return NS_ERROR_OUT_OF_MEMORY;
       }
 
       *words = tmpPtr;
       *count = 3;
       break;
  
     case InitCap:  
-      tmpPtr = (char16_t **)nsMemory::Alloc(sizeof(char16_t *) * 2);
+      tmpPtr = (char16_t **)moz_xmalloc(sizeof(char16_t *) * 2);
       if (!tmpPtr)
         return NS_ERROR_OUT_OF_MEMORY;
 
       tmpPtr[0] = ToNewUnicode(word);
       if (!tmpPtr[0]) {
         NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(0, tmpPtr);
         return NS_ERROR_OUT_OF_MEMORY;
       }
@@ -209,50 +209,50 @@ NS_IMETHODIMP mozEnglishWordUtils::FindN
 }
 
 mozEnglishWordUtils::myspCapitalization 
 mozEnglishWordUtils::captype(const nsString &word)
 {
   char16_t* lword=ToNewUnicode(word);  
   ToUpperCase(lword,lword,word.Length());
   if(word.Equals(lword)){
-    nsMemory::Free(lword);
+    free(lword);
     return AllCap;
   }
 
   ToLowerCase(lword,lword,word.Length());
   if(word.Equals(lword)){
-    nsMemory::Free(lword);
+    free(lword);
     return NoCap;
   }
   int32_t length=word.Length();
   if(Substring(word,1,length-1).Equals(lword+1)){
-    nsMemory::Free(lword);
+    free(lword);
     return InitCap;
   }
-  nsMemory::Free(lword);
+  free(lword);
   return HuhCap;
 }
 
 // Convert the list of words in iwords to the same capitalization aWord and 
 // return them in owords.
 NS_IMETHODIMP mozEnglishWordUtils::FromRootForm(const char16_t *aWord, const char16_t **iwords, uint32_t icount, char16_t ***owords, uint32_t *ocount)
 {
   nsAutoString word(aWord);
   nsresult rv = NS_OK;
 
   int32_t length;
-  char16_t **tmpPtr  = (char16_t **)nsMemory::Alloc(sizeof(char16_t *)*icount);
+  char16_t **tmpPtr  = (char16_t **)moz_xmalloc(sizeof(char16_t *)*icount);
   if (!tmpPtr)
     return NS_ERROR_OUT_OF_MEMORY;
 
   mozEnglishWordUtils::myspCapitalization ct = captype(word);
   for(uint32_t i = 0; i < icount; ++i) {
     length = NS_strlen(iwords[i]);
-    tmpPtr[i] = (char16_t *) nsMemory::Alloc(sizeof(char16_t) * (length + 1));
+    tmpPtr[i] = (char16_t *) moz_xmalloc(sizeof(char16_t) * (length + 1));
     if (MOZ_UNLIKELY(!tmpPtr[i])) {
       NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(i, tmpPtr);
       return NS_ERROR_OUT_OF_MEMORY;
     }
     memcpy(tmpPtr[i], iwords[i], (length + 1) * sizeof(char16_t));
 
     nsAutoString capTest(tmpPtr[i]);
     mozEnglishWordUtils::myspCapitalization newCt=captype(capTest);
--- a/gfx/src/nsThebesFontEnumerator.cpp
+++ b/gfx/src/nsThebesFontEnumerator.cpp
@@ -60,17 +60,17 @@ nsThebesFontEnumerator::EnumerateFonts(c
     if (NS_FAILED(rv)) {
         *aCount = 0;
         *aResult = nullptr;
         /* XXX in this case, do we want to return the CSS generics? */
         return NS_OK;
     }
 
     char16_t **fs = static_cast<char16_t **>
-                                (nsMemory::Alloc(fontList.Length() * sizeof(char16_t*)));
+                                (moz_xmalloc(fontList.Length() * sizeof(char16_t*)));
     for (uint32_t i = 0; i < fontList.Length(); i++) {
         fs[i] = ToNewUnicode(fontList[i]);
     }
 
     *aResult = fs;
     *aCount = fontList.Length();
 
     return NS_OK;
--- a/image/decoders/nsPNGDecoder.cpp
+++ b/image/decoders/nsPNGDecoder.cpp
@@ -121,20 +121,20 @@ nsPNGDecoder::nsPNGDecoder(RasterImage* 
 }
 
 nsPNGDecoder::~nsPNGDecoder()
 {
   if (mPNG) {
     png_destroy_read_struct(&mPNG, mInfo ? &mInfo : nullptr, nullptr);
   }
   if (mCMSLine) {
-    nsMemory::Free(mCMSLine);
+    free(mCMSLine);
   }
   if (interlacebuf) {
-    nsMemory::Free(interlacebuf);
+    free(interlacebuf);
   }
   if (mInProfile) {
     qcms_profile_release(mInProfile);
 
     // mTransform belongs to us only if mInProfile is non-null
     if (mTransform) {
       qcms_transform_release(mTransform);
     }
--- a/intl/locale/nsLocale.cpp
+++ b/intl/locale/nsLocale.cpp
@@ -55,23 +55,23 @@ NS_IMETHODIMP
 nsLocale::AddCategory(const nsAString &category, const nsAString &value)
 {
   char16_t* newKey = ToNewUnicode(category);
   if (!newKey)
     return NS_ERROR_OUT_OF_MEMORY;
 
   char16_t* newValue = ToNewUnicode(value);
   if (!newValue) {
-    nsMemory::Free(newKey);
+    free(newKey);
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   if (!PL_HashTableAdd(fHashtable, newKey, newValue)) {
-    nsMemory::Free(newKey);
-    nsMemory::Free(newValue);
+    free(newKey);
+    free(newValue);
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   return NS_OK;
 }
 
 
 PLHashNumber
@@ -95,14 +95,14 @@ nsLocale::Hash_CompareNSString(const voi
   return !nsCRT::strcmp((const char16_t *) s1, (const char16_t *) s2);
 }
 
 
 int
 nsLocale::Hash_EnumerateDelete(PLHashEntry *he, int hashIndex, void *arg)
 {
   // delete an entry
-  nsMemory::Free((char16_t *)he->key);
-  nsMemory::Free((char16_t *)he->value);
+  free((char16_t *)he->key);
+  free((char16_t *)he->value);
 
   return (HT_ENUMERATE_NEXT | HT_ENUMERATE_REMOVE);
 }
 
--- a/intl/strres/nsStringBundle.cpp
+++ b/intl/strres/nsStringBundle.cpp
@@ -746,13 +746,13 @@ nsStringBundleService::FormatStatusMessa
       rv = FormatWithBundle(bundle, aStatus, argCount, argArray, result);
     }
   }
 
 done:
   if (argCount > 1) {
     for (i = 0; i < argCount; i++) {
       if (argArray[i])
-        nsMemory::Free(argArray[i]);
+        free(argArray[i]);
     }
   }
   return rv;
 }
--- a/intl/uconv/nsIUnicodeEncoder.h
+++ b/intl/uconv/nsIUnicodeEncoder.h
@@ -57,32 +57,32 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsIUnichar
 //  sbl = static buffer length (uint32_t)
 //   al = actual buffer length (int32_t)
 //
 #define ENCODER_BUFFER_ALLOC_IF_NEEDED(p,e,s,l,sb,sbl,al) \
   PR_BEGIN_MACRO                                          \
     if (e                                                 \
         && NS_SUCCEEDED((e)->GetMaxLength((s), (l), &(al)))\
         && ((al) > (int32_t)(sbl))                        \
-        && (nullptr!=((p)=(char*)nsMemory::Alloc((al)+1))) \
+        && (nullptr!=((p)=(char*)moz_xmalloc((al)+1)))    \
         ) {                                               \
     }                                                     \
     else {                                                \
       (p) = (char*)(sb);                                  \
       (al) = (sbl);                                       \
     }                                                     \
   PR_END_MACRO 
 
 //
 // Free the Encoder buffer if it was allocated
 //
 #define ENCODER_BUFFER_FREE_IF_NEEDED(p,sb) \
   PR_BEGIN_MACRO                            \
     if ((p) != (char*)(sb))                 \
-      nsMemory::Free(p);                    \
+      free(p);                              \
   PR_END_MACRO 
 
 /**
  * Interface for a Converter from Unicode into a Charset.
  *
  * @created         23/Nov/1998
  * @author  Catalin Rotaru [CATA]
  */
--- a/intl/unicharutil/nsSaveAsCharset.cpp
+++ b/intl/unicharutil/nsSaveAsCharset.cpp
@@ -91,17 +91,17 @@ nsSaveAsCharset::Convert(const char16_t 
     if (attr_EntityBeforeCharsetConv == MASK_ENTITY(mAttribute)) {
       NS_ASSERTION(mEntityConverter, "need to call Init() before Convert()");
       NS_ENSURE_TRUE(mEntityConverter, NS_ERROR_FAILURE);
       char16_t *entity = nullptr;
       // do the entity conversion first
       rv = mEntityConverter->ConvertToEntities(inString, mEntityVersion, &entity);
       if(NS_SUCCEEDED(rv)) {
         rv = DoCharsetConversion(entity, _retval);
-        nsMemory::Free(entity);
+        free(entity);
       }
     }
     else
       rv = DoCharsetConversion(inString, _retval);
 
   } while (MASK_CHARSET_FALLBACK(mAttribute) && NS_ERROR_UENC_NOMAPPING == rv);
 
   return rv;
@@ -282,17 +282,17 @@ nsSaveAsCharset::DoConversionFallBack(ui
   if (attr_EntityAfterCharsetConv == MASK_ENTITY(mAttribute)) {
     char *entity = nullptr;
     rv = mEntityConverter->ConvertUTF32ToEntity(inUCS4, mEntityVersion, &entity);
     if (NS_SUCCEEDED(rv)) {
       if (!entity || (int32_t)strlen(entity) > bufferLength) {
         return NS_ERROR_OUT_OF_MEMORY;
       }
       PL_strcpy(outString, entity);
-      nsMemory::Free(entity);
+      free(entity);
       return rv;
     }
   }
 
   switch (MASK_FALLBACK(mAttribute)) {
   case attr_FallbackQuestionMark:
     if(bufferLength>=2) {
       *outString++='?';
--- a/intl/unicharutil/nsUnicodeNormalizer.cpp
+++ b/intl/unicharutil/nsUnicodeNormalizer.cpp
@@ -571,41 +571,41 @@ workbuf_init(workbuf_t *wb) {
 	wb->size = WORKBUF_SIZE;
 	wb->ucs = wb->ucs_buf;
 	wb->cclass = wb->class_buf;
 }
 
 static void
 workbuf_free(workbuf_t *wb) {
 	if (wb->ucs != wb->ucs_buf) {
-		nsMemory::Free(wb->ucs);
-		nsMemory::Free(wb->cclass);
+		free(wb->ucs);
+		free(wb->cclass);
 	}
 }
 
 static nsresult
 workbuf_extend(workbuf_t *wb) {
 	int32_t newsize = wb->size * 3;
 
 	if (wb->ucs == wb->ucs_buf) {
-		wb->ucs = (uint32_t*)nsMemory::Alloc(sizeof(wb->ucs[0]) * newsize);
+		wb->ucs = (uint32_t*)moz_xmalloc(sizeof(wb->ucs[0]) * newsize);
 		if (!wb->ucs)
 			return NS_ERROR_OUT_OF_MEMORY;
-		wb->cclass = (int32_t*)nsMemory::Alloc(sizeof(wb->cclass[0]) * newsize);
+		wb->cclass = (int32_t*)moz_xmalloc(sizeof(wb->cclass[0]) * newsize);
 		if (!wb->cclass) {
-			nsMemory::Free(wb->ucs);
+			free(wb->ucs);
 			wb->ucs = nullptr;
 			return NS_ERROR_OUT_OF_MEMORY;
 		}
 	} else {
-		void* buf = nsMemory::Realloc(wb->ucs, sizeof(wb->ucs[0]) * newsize);
+		void* buf = moz_xrealloc(wb->ucs, sizeof(wb->ucs[0]) * newsize);
 		if (!buf)
 			return NS_ERROR_OUT_OF_MEMORY;
 		wb->ucs = (uint32_t*)buf;
-		buf = nsMemory::Realloc(wb->cclass, sizeof(wb->cclass[0]) * newsize);
+		buf = moz_xrealloc(wb->cclass, sizeof(wb->cclass[0]) * newsize);
 		if (!buf)
 			return NS_ERROR_OUT_OF_MEMORY;
 		wb->cclass = (int32_t*)buf;
 	}
 	return (NS_OK);
 }
 
 static nsresult
--- a/intl/unicharutil/tests/UnicharSelfTest.cpp
+++ b/intl/unicharutil/tests/UnicharSelfTest.cpp
@@ -502,30 +502,30 @@ static void TestEntityConversion(uint32_
   uint32_t length = NS_StringGetData(inString, &data);
 
   // convert char by char
   for (i = 0; i < length; i++) {
     char *entity = nullptr;
     res = entityConv->ConvertToEntity(data[i], version, &entity);
     if (NS_SUCCEEDED(res) && entity) {
       printf("%c %s\n", data[i], entity);
-      nsMemory::Free(entity);
+      free(entity);
     }
   }
 
   // convert at once as a string
   char16_t *entities;
   res = entityConv->ConvertToEntities(inString.get(), version, &entities);
   if (NS_SUCCEEDED(res) && entities) {
     for (char16_t *centity = entities; *centity; ++centity) {
       printf("%c", (char) *centity);
       if (';' == (char) *centity)
         printf("\n");
     }
-    nsMemory::Free(entities);
+    free(entities);
   }
 
   printf("==============================\n");
   printf("Finish nsIEntityConverter Test \n");
   printf("==============================\n\n");
 }
 
 static void TestSaveAsCharset()
@@ -555,73 +555,73 @@ static void TestSaveAsCharset()
   printf("ISO-8859-1 attr_plainTextDefault entityNone\n");
   res = saveAsCharset->Init("ISO-8859-1", 
                                  nsISaveAsCharset::attr_plainTextDefault, 
                                  nsIEntityConverter::entityNone);
   if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   res = saveAsCharset->Convert(inString.get(), &outString);
   if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   if (!outString) {printf("\tFailed!! output null\n");}
-  else {printf("%s\n", outString); nsMemory::Free(outString);}
+  else {printf("%s\n", outString); free(outString);}
 
   printf("ISO-2022-JP attr_plainTextDefault entityNone\n");
   res = saveAsCharset->Init("ISO-2022-JP", 
                                  nsISaveAsCharset::attr_plainTextDefault,
                                  nsIEntityConverter::entityNone);
   if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   res = saveAsCharset->Convert(inString.get(), &outString);
   if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   if (!outString) {printf("\tFailed!! output null\n");}
-  else {printf("%s\n", outString); nsMemory::Free(outString);}
+  else {printf("%s\n", outString); free(outString);}
   if (NS_ERROR_UENC_NOMAPPING == res) {
     outString = ToNewUTF8String(inString);
     if (!outString) {printf("\tFailed!! output null\n");}
-    else {printf("Fall back to UTF-8: %s\n", outString); nsMemory::Free(outString);}
+    else {printf("Fall back to UTF-8: %s\n", outString); free(outString);}
   }
 
   printf("ISO-2022-JP attr_FallbackQuestionMark entityNone\n");
   res = saveAsCharset->Init("ISO-2022-JP", 
                                  nsISaveAsCharset::attr_FallbackQuestionMark,
                                  nsIEntityConverter::entityNone);
   if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   res = saveAsCharset->Convert(inString.get(), &outString);
   if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   if (!outString) {printf("\tFailed!! output null\n");}
-  else {printf("%s\n", outString); nsMemory::Free(outString);}
+  else {printf("%s\n", outString); free(outString);}
 
   printf("ISO-2022-JP attr_FallbackEscapeU entityNone\n");
   res = saveAsCharset->Init("ISO-2022-JP", 
                                  nsISaveAsCharset::attr_FallbackEscapeU,
                                  nsIEntityConverter::entityNone);
   if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   res = saveAsCharset->Convert(inString.get(), &outString);
   if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   if (!outString) {printf("\tFailed!! output null\n");}
-  else {printf("%s\n", outString); nsMemory::Free(outString);}
+  else {printf("%s\n", outString); free(outString);}
 
   printf("ISO-8859-1 attr_htmlTextDefault html40Latin1\n");
   res = saveAsCharset->Init("ISO-8859-1", 
                                  nsISaveAsCharset::attr_htmlTextDefault, 
                                  nsIEntityConverter::html40Latin1);
   if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   res = saveAsCharset->Convert(inString.get(), &outString);
   if (NS_ERROR_UENC_NOMAPPING != res && NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   if (!outString) {printf("\tFailed!! output null\n");}
-  else {printf("%s\n", outString); nsMemory::Free(outString);}
+  else {printf("%s\n", outString); free(outString);}
 
   printf("ISO-8859-1 attr_FallbackHexNCR+attr_EntityAfterCharsetConv html40Latin1 \n");
   res = saveAsCharset->Init("ISO-8859-1", 
                                  nsISaveAsCharset::attr_FallbackHexNCR + 
                                  nsISaveAsCharset::attr_EntityAfterCharsetConv, 
                                  nsIEntityConverter::html40Latin1);
   if (NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   res = saveAsCharset->Convert(inString.get(), &outString);
   if (NS_ERROR_UENC_NOMAPPING != res && NS_FAILED(res)) {printf("\tFailed!! return value != NS_OK\n");}
   if (!outString) {printf("\tFailed!! output null\n");}
-  else {printf("%s\n", outString); nsMemory::Free(outString);}
+  else {printf("%s\n", outString); free(outString);}
 
 
   printf("==============================\n");
   printf("Finish nsISaveAsCharset Test \n");
   printf("==============================\n\n");
 }
 
 static char16_t normStr[] = 
--- a/js/xpconnect/src/XPCComponents.cpp
+++ b/js/xpconnect/src/XPCComponents.cpp
@@ -122,17 +122,17 @@ private:
 /* void getInterfaces (out uint32_t count, [array, size_is (count), retval]
                        out nsIIDPtr array); */
 NS_IMETHODIMP
 nsXPCComponents_Interfaces::GetInterfaces(uint32_t* aCount, nsIID * **aArray)
 {
     const uint32_t count = 2;
     *aCount = count;
     nsIID** array;
-    *aArray = array = static_cast<nsIID**>(nsMemory::Alloc(count * sizeof(nsIID*)));
+    *aArray = array = static_cast<nsIID**>(moz_xmalloc(count * sizeof(nsIID*)));
     if (!array)
         return NS_ERROR_OUT_OF_MEMORY;
 
     uint32_t index = 0;
     nsIID* clone;
 #define PUSH_IID(id)                                                          \
     clone = static_cast<nsIID*>(nsMemory::Clone(&NS_GET_IID( id ),           \
                                                  sizeof(nsIID)));             \
@@ -142,18 +142,18 @@ nsXPCComponents_Interfaces::GetInterface
 
     PUSH_IID(nsIXPCComponents_Interfaces)
     PUSH_IID(nsIXPCScriptable)
 #undef PUSH_IID
 
     return NS_OK;
 oom:
     while (index)
-        nsMemory::Free(array[--index]);
-    nsMemory::Free(array);
+        free(array[--index]);
+    free(array);
     *aArray = nullptr;
     return NS_ERROR_OUT_OF_MEMORY;
 }
 
 /* nsIXPCScriptable getScriptableHelper(); */
 NS_IMETHODIMP
 nsXPCComponents_Interfaces::GetScriptableHelper(nsIXPCScriptable** retval)
 {
@@ -357,17 +357,17 @@ private:
 /* void getInterfaces (out uint32_t count, [array, size_is (count), retval]
                        out nsIIDPtr array); */
 NS_IMETHODIMP
 nsXPCComponents_InterfacesByID::GetInterfaces(uint32_t* aCount, nsIID * **aArray)
 {
     const uint32_t count = 2;
     *aCount = count;
     nsIID** array;
-    *aArray = array = static_cast<nsIID**>(nsMemory::Alloc(count * sizeof(nsIID*)));
+    *aArray = array = static_cast<nsIID**>(moz_xmalloc(count * sizeof(nsIID*)));
     if (!array)
         return NS_ERROR_OUT_OF_MEMORY;
 
     uint32_t index = 0;
     nsIID* clone;
 #define PUSH_IID(id)                                                          \
     clone = static_cast<nsIID*>(nsMemory::Clone(&NS_GET_IID( id ),           \
                                                  sizeof(nsIID)));             \
@@ -377,18 +377,18 @@ nsXPCComponents_InterfacesByID::GetInter
 
     PUSH_IID(nsIXPCComponents_InterfacesByID)
     PUSH_IID(nsIXPCScriptable)
 #undef PUSH_IID
 
     return NS_OK;
 oom:
     while (index)
-        nsMemory::Free(array[--index]);
-    nsMemory::Free(array);
+        free(array[--index]);
+    free(array);
     *aArray = nullptr;
     return NS_ERROR_OUT_OF_MEMORY;
 }
 
 /* nsIXPCScriptable getScriptableHelper(); */
 NS_IMETHODIMP
 nsXPCComponents_InterfacesByID::GetScriptableHelper(nsIXPCScriptable** retval)
 {
@@ -594,17 +594,17 @@ private:
 /* void getInterfaces (out uint32_t count, [array, size_is (count), retval]
                        out nsIIDPtr array); */
 NS_IMETHODIMP
 nsXPCComponents_Classes::GetInterfaces(uint32_t* aCount, nsIID * **aArray)
 {
     const uint32_t count = 2;
     *aCount = count;
     nsIID** array;
-    *aArray = array = static_cast<nsIID**>(nsMemory::Alloc(count * sizeof(nsIID*)));
+    *aArray = array = static_cast<nsIID**>(moz_xmalloc(count * sizeof(nsIID*)));
     if (!array)
         return NS_ERROR_OUT_OF_MEMORY;
 
     uint32_t index = 0;
     nsIID* clone;
 #define PUSH_IID(id)                                                          \
     clone = static_cast<nsIID*>(nsMemory::Clone(&NS_GET_IID( id ),           \
                                                  sizeof(nsIID)));             \
@@ -614,18 +614,18 @@ nsXPCComponents_Classes::GetInterfaces(u
 
     PUSH_IID(nsIXPCComponents_Classes)
     PUSH_IID(nsIXPCScriptable)
 #undef PUSH_IID
 
     return NS_OK;
 oom:
     while (index)
-        nsMemory::Free(array[--index]);
-    nsMemory::Free(array);
+        free(array[--index]);
+    free(array);
     *aArray = nullptr;
     return NS_ERROR_OUT_OF_MEMORY;
 }
 
 /* nsIXPCScriptable getScriptableHelper(); */
 NS_IMETHODIMP
 nsXPCComponents_Classes::GetScriptableHelper(nsIXPCScriptable** retval)
 {
@@ -811,17 +811,17 @@ private:
 /* void getInterfaces (out uint32_t count, [array, size_is (count), retval]
                        out nsIIDPtr array); */
 NS_IMETHODIMP
 nsXPCComponents_ClassesByID::GetInterfaces(uint32_t* aCount, nsIID * **aArray)
 {
     const uint32_t count = 2;
     *aCount = count;
     nsIID** array;
-    *aArray = array = static_cast<nsIID**>(nsMemory::Alloc(count * sizeof(nsIID*)));
+    *aArray = array = static_cast<nsIID**>(moz_xmalloc(count * sizeof(nsIID*)));
     if (!array)
         return NS_ERROR_OUT_OF_MEMORY;
 
     uint32_t index = 0;
     nsIID* clone;
 #define PUSH_IID(id)                                                          \
     clone = static_cast<nsIID*>(nsMemory::Clone(&NS_GET_IID( id ),           \
                                                  sizeof(nsIID)));             \
@@ -831,18 +831,18 @@ nsXPCComponents_ClassesByID::GetInterfac
 
     PUSH_IID(nsIXPCComponents_ClassesByID)
     PUSH_IID(nsIXPCScriptable)
 #undef PUSH_IID
 
     return NS_OK;
 oom:
     while (index)
-        nsMemory::Free(array[--index]);
-    nsMemory::Free(array);
+        free(array[--index]);
+    free(array);
     *aArray = nullptr;
     return NS_ERROR_OUT_OF_MEMORY;
 }
 
 /* nsIXPCScriptable getScriptableHelper(); */
 NS_IMETHODIMP
 nsXPCComponents_ClassesByID::GetScriptableHelper(nsIXPCScriptable** retval)
 {
@@ -1051,17 +1051,17 @@ private:
 /* void getInterfaces (out uint32_t count, [array, size_is (count), retval]
                        out nsIIDPtr array); */
 NS_IMETHODIMP
 nsXPCComponents_Results::GetInterfaces(uint32_t* aCount, nsIID * **aArray)
 {
     const uint32_t count = 2;
     *aCount = count;
     nsIID** array;
-    *aArray = array = static_cast<nsIID**>(nsMemory::Alloc(count * sizeof(nsIID*)));
+    *aArray = array = static_cast<nsIID**>(moz_xmalloc(count * sizeof(nsIID*)));
     if (!array)
         return NS_ERROR_OUT_OF_MEMORY;
 
     uint32_t index = 0;
     nsIID* clone;
 #define PUSH_IID(id)                                                          \
     clone = static_cast<nsIID*>(nsMemory::Clone(&NS_GET_IID( id ),           \
                                                  sizeof(nsIID)));             \
@@ -1071,18 +1071,18 @@ nsXPCComponents_Results::GetInterfaces(u
 
     PUSH_IID(nsIXPCComponents_Results)
     PUSH_IID(nsIXPCScriptable)
 #undef PUSH_IID
 
     return NS_OK;
 oom:
     while (index)
-        nsMemory::Free(array[--index]);
-    nsMemory::Free(array);
+        free(array[--index]);
+    free(array);
     *aArray = nullptr;
     return NS_ERROR_OUT_OF_MEMORY;
 }
 
 /* nsIXPCScriptable getScriptableHelper(); */
 NS_IMETHODIMP
 nsXPCComponents_Results::GetScriptableHelper(nsIXPCScriptable** retval)
 {
@@ -1248,17 +1248,17 @@ private:
 /* void getInterfaces (out uint32_t count, [array, size_is (count), retval]
                        out nsIIDPtr array); */
 NS_IMETHODIMP
 nsXPCComponents_ID::GetInterfaces(uint32_t* aCount, nsIID * **aArray)
 {
     const uint32_t count = 2;
     *aCount = count;
     nsIID** array;
-    *aArray = array = static_cast<nsIID**>(nsMemory::Alloc(count * sizeof(nsIID*)));
+    *aArray = array = static_cast<nsIID**>(moz_xmalloc(count * sizeof(nsIID*)));
     if (!array)
         return NS_ERROR_OUT_OF_MEMORY;
 
     uint32_t index = 0;
     nsIID* clone;
 #define PUSH_IID(id)                                                          \
     clone = static_cast<nsIID*>(nsMemory::Clone(&NS_GET_IID( id ),           \
                                                  sizeof(nsIID)));             \
@@ -1268,18 +1268,18 @@ nsXPCComponents_ID::GetInterfaces(uint32
 
     PUSH_IID(nsIXPCComponents_ID)
     PUSH_IID(nsIXPCScriptable)
 #undef PUSH_IID
 
     return NS_OK;
 oom:
     while (index)
-        nsMemory::Free(array[--index]);
-    nsMemory::Free(array);
+        free(array[--index]);
+    free(array);
     *aArray = nullptr;
     return NS_ERROR_OUT_OF_MEMORY;
 }
 
 /* nsIXPCScriptable getScriptableHelper(); */
 NS_IMETHODIMP
 nsXPCComponents_ID::GetScriptableHelper(nsIXPCScriptable** retval)
 {
@@ -1456,17 +1456,17 @@ private:
 /* void getInterfaces (out uint32_t count, [array, size_is (count), retval]
                        out nsIIDPtr array); */
 NS_IMETHODIMP
 nsXPCComponents_Exception::GetInterfaces(uint32_t* aCount, nsIID * **aArray)
 {
     const uint32_t count = 2;
     *aCount = count;
     nsIID** array;
-    *aArray = array = static_cast<nsIID**>(nsMemory::Alloc(count * sizeof(nsIID*)));
+    *aArray = array = static_cast<nsIID**>(moz_xmalloc(count * sizeof(nsIID*)));
     if (!array)
         return NS_ERROR_OUT_OF_MEMORY;
 
     uint32_t index = 0;
     nsIID* clone;
 #define PUSH_IID(id)                                                          \
     clone = static_cast<nsIID*>(nsMemory::Clone(&NS_GET_IID( id ),           \
                                                  sizeof(nsIID)));             \
@@ -1476,18 +1476,18 @@ nsXPCComponents_Exception::GetInterfaces
 
     PUSH_IID(nsIXPCComponents_Exception)
     PUSH_IID(nsIXPCScriptable)
 #undef PUSH_IID
 
     return NS_OK;
 oom:
     while (index)
-        nsMemory::Free(array[--index]);
-    nsMemory::Free(array);
+        free(array[--index]);
+    free(array);
     *aArray = nullptr;
     return NS_ERROR_OUT_OF_MEMORY;
 }
 
 /* nsIXPCScriptable getScriptableHelper(); */
 NS_IMETHODIMP
 nsXPCComponents_Exception::GetScriptableHelper(nsIXPCScriptable** retval)
 {
@@ -1837,17 +1837,17 @@ private:
 /* void getInterfaces (out uint32_t count, [array, size_is (count), retval]
                        out nsIIDPtr array); */
 NS_IMETHODIMP
 nsXPCConstructor::GetInterfaces(uint32_t* aCount, nsIID * **aArray)
 {
     const uint32_t count = 2;
     *aCount = count;
     nsIID** array;
-    *aArray = array = static_cast<nsIID**>(nsMemory::Alloc(count * sizeof(nsIID*)));
+    *aArray = array = static_cast<nsIID**>(moz_xmalloc(count * sizeof(nsIID*)));
     if (!array)
         return NS_ERROR_OUT_OF_MEMORY;
 
     uint32_t index = 0;
     nsIID* clone;
 #define PUSH_IID(id)                                                          \
     clone = static_cast<nsIID*>(nsMemory::Clone(&NS_GET_IID( id ),           \
                                                  sizeof(nsIID)));             \
@@ -1857,18 +1857,18 @@ nsXPCConstructor::GetInterfaces(uint32_t
 
     PUSH_IID(nsIXPCConstructor)
     PUSH_IID(nsIXPCScriptable)
 #undef PUSH_IID
 
     return NS_OK;
 oom:
     while (index)
-        nsMemory::Free(array[--index]);
-    nsMemory::Free(array);
+        free(array[--index]);
+    free(array);
     *aArray = nullptr;
     return NS_ERROR_OUT_OF_MEMORY;
 }
 
 /* nsIXPCScriptable getScriptableHelper(); */
 NS_IMETHODIMP
 nsXPCConstructor::GetScriptableHelper(nsIXPCScriptable** retval)
 {
@@ -1925,17 +1925,17 @@ nsXPCConstructor::nsXPCConstructor(nsIJS
     mInitializer = aInitializer ?
         (char*) nsMemory::Clone(aInitializer, strlen(aInitializer)+1) :
         nullptr;
 }
 
 nsXPCConstructor::~nsXPCConstructor()
 {
     if (mInitializer)
-        nsMemory::Free(mInitializer);
+        free(mInitializer);
 }
 
 /* readonly attribute nsIJSCID classID; */
 NS_IMETHODIMP
 nsXPCConstructor::GetClassID(nsIJSCID * *aClassID)
 {
     nsRefPtr<nsIJSCID> rval = mClassID;
     rval.forget(aClassID);
@@ -2083,17 +2083,17 @@ private:
 /* void getInterfaces (out uint32_t count, [array, size_is (count), retval]
                        out nsIIDPtr array); */
 NS_IMETHODIMP
 nsXPCComponents_Constructor::GetInterfaces(uint32_t* aCount, nsIID * **aArray)
 {
     const uint32_t count = 2;
     *aCount = count;
     nsIID** array;
-    *aArray = array = static_cast<nsIID**>(nsMemory::Alloc(count * sizeof(nsIID*)));
+    *aArray = array = static_cast<nsIID**>(moz_xmalloc(count * sizeof(nsIID*)));
     if (!array)
         return NS_ERROR_OUT_OF_MEMORY;
 
     uint32_t index = 0;
     nsIID* clone;
 #define PUSH_IID(id)                                                          \
     clone = static_cast<nsIID*>(nsMemory::Clone(&NS_GET_IID( id ),           \
                                                  sizeof(nsIID)));             \
@@ -2103,18 +2103,18 @@ nsXPCComponents_Constructor::GetInterfac
 
     PUSH_IID(nsIXPCComponents_Constructor)
     PUSH_IID(nsIXPCScriptable)
 #undef PUSH_IID
 
     return NS_OK;
 oom:
     while (index)
-        nsMemory::Free(array[--index]);
-    nsMemory::Free(array);
+        free(array[--index]);
+    free(array);
     *aArray = nullptr;
     return NS_ERROR_OUT_OF_MEMORY;
 }
 
 /* nsIXPCScriptable getScriptableHelper(); */
 NS_IMETHODIMP
 nsXPCComponents_Constructor::GetScriptableHelper(nsIXPCScriptable** retval)
 {
--- a/js/xpconnect/src/XPCConvert.cpp
+++ b/js/xpconnect/src/XPCConvert.cpp
@@ -560,17 +560,17 @@ XPCConvert::JSData2Native(void* d, Handl
             if (chars)
                 CheckCharsInCharRange(chars, len);
         }
 #endif // DEBUG
         size_t length = JS_GetStringEncodingLength(cx, str);
         if (length == size_t(-1)) {
             return false;
         }
-        char* buffer = static_cast<char*>(nsMemory::Alloc(length + 1));
+        char* buffer = static_cast<char *>(moz_xmalloc(length + 1));
         if (!buffer) {
             return false;
         }
         JS_EncodeStringToBuffer(cx, str, buffer, length);
         buffer[length] = '\0';
         *((void**)d) = buffer;
         return true;
     }
@@ -584,17 +584,17 @@ XPCConvert::JSData2Native(void* d, Handl
             return true;
         }
 
         if (!(str = ToString(cx, s))) {
             return false;
         }
         int len = JS_GetStringLength(str);
         int byte_len = (len+1)*sizeof(char16_t);
-        if (!(*((void**)d) = nsMemory::Alloc(byte_len))) {
+        if (!(*((void**)d) = moz_xmalloc(byte_len))) {
             // XXX should report error
             return false;
         }
         mozilla::Range<char16_t> destChars(*((char16_t**)d), len + 1);
         if (!JS_CopyStringChars(cx, destChars, str))
             return false;
         destChars[len] = 0;
 
@@ -1351,17 +1351,17 @@ CheckTargetAndPopulate(const nsXPTType& 
     }
 
     // Calulate the maximum number of elements that can fit in
     // UINT32_MAX bytes.
     size_t max = UINT32_MAX / typeSize;
 
     // This could overflow on 32-bit systems so check max first.
     size_t byteSize = count * typeSize;
-    if (count > max || !(*output = nsMemory::Alloc(byteSize))) {
+    if (count > max || !(*output = moz_xmalloc(byteSize))) {
         if (pErr)
             *pErr = NS_ERROR_OUT_OF_MEMORY;
 
         return false;
     }
 
     JS::AutoCheckCannotGC nogc;
     memcpy(*output, JS_GetArrayBufferViewData(tArr, nogc), byteSize);
@@ -1536,17 +1536,17 @@ XPCConvert::JSArray2Native(void** d, Han
     if (pErr)
         *pErr = NS_ERROR_XPC_BAD_CONVERT_JS;
 
 #define POPULATE(_mode, _t)                                                    \
     PR_BEGIN_MACRO                                                             \
         cleanupMode = _mode;                                                   \
         size_t max = UINT32_MAX / sizeof(_t);                                  \
         if (count > max ||                                                     \
-            nullptr == (array = nsMemory::Alloc(count * sizeof(_t)))) {        \
+            nullptr == (array = moz_xmalloc(count * sizeof(_t)))) {            \
             if (pErr)                                                          \
                 *pErr = NS_ERROR_OUT_OF_MEMORY;                                \
             goto failure;                                                      \
         }                                                                      \
         for (initedCount = 0; initedCount < count; initedCount++) {            \
             if (!JS_GetElement(cx, jsarray, initedCount, &current) ||          \
                 !JSData2Native(((_t*)array)+initedCount, current, type,        \
                                iid, pErr))                                     \
@@ -1606,20 +1606,20 @@ failure:
             for (uint32_t i = 0; i < initedCount; i++) {
                 nsISupports* p = a[i];
                 NS_IF_RELEASE(p);
             }
         } else if (cleanupMode == fr) {
             void** a = (void**) array;
             for (uint32_t i = 0; i < initedCount; i++) {
                 void* p = a[i];
-                if (p) nsMemory::Free(p);
+                if (p) free(p);
             }
         }
-        nsMemory::Free(array);
+        free(array);
     }
 
     return false;
 
 #undef POPULATE
 }
 
 // static
@@ -1686,17 +1686,17 @@ XPCConvert::JSStringWithSize2Native(void
             if (s.isUndefined() || s.isNull()) {
                 if (0 != count) {
                     if (pErr)
                         *pErr = NS_ERROR_XPC_NOT_ENOUGH_CHARS_IN_STRING;
                     return false;
                 }
                 if (0 != count) {
                     len = (count + 1) * sizeof(char);
-                    if (!(*((void**)d) = nsMemory::Alloc(len)))
+                    if (!(*((void**)d) = moz_xmalloc(len)))
                         return false;
                     return true;
                 }
                 // else ...
 
                 *((char**)d) = nullptr;
                 return true;
             }
@@ -1716,17 +1716,17 @@ XPCConvert::JSStringWithSize2Native(void
                 return false;
             }
             len = uint32_t(length);
 
             if (len < count)
                 len = count;
 
             uint32_t alloc_len = (len + 1) * sizeof(char);
-            char* buffer = static_cast<char*>(nsMemory::Alloc(alloc_len));
+            char* buffer = static_cast<char *>(moz_xmalloc(alloc_len));
             if (!buffer) {
                 return false;
             }
             JS_EncodeStringToBuffer(cx, str, buffer, len);
             buffer[len] = '\0';
             *((char**)d) = buffer;
 
             return true;
@@ -1740,17 +1740,17 @@ XPCConvert::JSStringWithSize2Native(void
                 if (0 != count) {
                     if (pErr)
                         *pErr = NS_ERROR_XPC_NOT_ENOUGH_CHARS_IN_STRING;
                     return false;
                 }
 
                 if (0 != count) {
                     len = (count + 1) * sizeof(char16_t);
-                    if (!(*((void**)d) = nsMemory::Alloc(len)))
+                    if (!(*((void**)d) = moz_xmalloc(len)))
                         return false;
                     return true;
                 }
 
                 // else ...
                 *((const char16_t**)d) = nullptr;
                 return true;
             }
@@ -1764,17 +1764,17 @@ XPCConvert::JSStringWithSize2Native(void
                 if (pErr)
                     *pErr = NS_ERROR_XPC_NOT_ENOUGH_CHARS_IN_STRING;
                 return false;
             }
 
             len = count;
 
             uint32_t alloc_len = (len + 1) * sizeof(char16_t);
-            if (!(*((void**)d) = nsMemory::Alloc(alloc_len))) {
+            if (!(*((void**)d) = moz_xmalloc(alloc_len))) {
                 // XXX should report error
                 return false;
             }
             mozilla::Range<char16_t> destChars(*((char16_t**)d), len + 1);
             if (!JS_CopyStringChars(cx, destChars, str))
                 return false;
             destChars[count] = 0;
 
--- a/js/xpconnect/src/XPCJSID.cpp
+++ b/js/xpconnect/src/XPCJSID.cpp
@@ -594,17 +594,17 @@ nsJSCID::NewID(const char* str)
         nsCOMPtr<nsIComponentRegistrar> registrar;
         NS_GetComponentRegistrar(getter_AddRefs(registrar));
         NS_ENSURE_TRUE(registrar, nullptr);
 
         nsCID* cid;
         if (NS_FAILED(registrar->ContractIDToCID(str, &cid)))
             return nullptr;
         bool success = idObj->mDetails->InitWithName(*cid, str);
-        nsMemory::Free(cid);
+        free(cid);
         if (!success)
             return nullptr;
     }
     return idObj.forget();
 }
 
 static const nsID*
 GetIIDArg(uint32_t argc, const JS::Value& val, JSContext* cx)
--- a/js/xpconnect/src/XPCRuntimeService.cpp
+++ b/js/xpconnect/src/XPCRuntimeService.cpp
@@ -82,17 +82,17 @@ BackstagePass::Enumerate(nsIXPConnectWra
 /* void getInterfaces (out uint32_t count, [array, size_is (count), retval]
                        out nsIIDPtr array); */
 NS_IMETHODIMP
 BackstagePass::GetInterfaces(uint32_t* aCount, nsIID * **aArray)
 {
     const uint32_t count = 2;
     *aCount = count;
     nsIID** array;
-    *aArray = array = static_cast<nsIID**>(nsMemory::Alloc(count * sizeof(nsIID*)));
+    *aArray = array = static_cast<nsIID**>(moz_xmalloc(count * sizeof(nsIID*)));
     if (!array)
         return NS_ERROR_OUT_OF_MEMORY;
 
     uint32_t index = 0;
     nsIID* clone;
 #define PUSH_IID(id)                                                          \
     clone = static_cast<nsIID*>(nsMemory::Clone(&NS_GET_IID( id ),           \
                                                  sizeof(nsIID)));             \
@@ -102,18 +102,18 @@ BackstagePass::GetInterfaces(uint32_t* a
 
     PUSH_IID(nsIXPCScriptable)
     PUSH_IID(nsIScriptObjectPrincipal)
 #undef PUSH_IID
 
     return NS_OK;
 oom:
     while (index)
-        nsMemory::Free(array[--index]);
-    nsMemory::Free(array);
+        free(array[--index]);
+    free(array);
     *aArray = nullptr;
     return NS_ERROR_OUT_OF_MEMORY;
 }
 
 /* nsIXPCScriptable getScriptableHelper (); */
 NS_IMETHODIMP
 BackstagePass::GetScriptableHelper(nsIXPCScriptable** retval)
 {
--- a/js/xpconnect/src/XPCVariant.cpp
+++ b/js/xpconnect/src/XPCVariant.cpp
@@ -489,61 +489,61 @@ XPCVariant::VariantDataToJS(nsIVariant* 
         }
         case nsIDataType::VTYPE_CHAR_STR:
         {
             char* pc;
             if (NS_FAILED(variant->GetAsString(&pc)))
                 return false;
             bool success = XPCConvert::NativeData2JS(pJSVal, (const void*)&pc,
                                                      TD_PSTRING, &iid, pErr);
-            nsMemory::Free(pc);
+            free(pc);
             return success;
         }
         case nsIDataType::VTYPE_STRING_SIZE_IS:
         {
             char* pc;
             uint32_t size;
             if (NS_FAILED(variant->GetAsStringWithSize(&size, &pc)))
                 return false;
             bool success = XPCConvert::NativeStringWithSize2JS(pJSVal, (const void*)&pc,
                                                                TD_PSTRING_SIZE_IS, size, pErr);
-            nsMemory::Free(pc);
+            free(pc);
             return success;
         }
         case nsIDataType::VTYPE_WCHAR_STR:
         {
             char16_t* pwc;
             if (NS_FAILED(variant->GetAsWString(&pwc)))
                 return false;
             bool success = XPCConvert::NativeData2JS(pJSVal, (const void*)&pwc,
                                                      TD_PSTRING, &iid, pErr);
-            nsMemory::Free(pwc);
+            free(pwc);
             return success;
         }
         case nsIDataType::VTYPE_WSTRING_SIZE_IS:
         {
             char16_t* pwc;
             uint32_t size;
             if (NS_FAILED(variant->GetAsWStringWithSize(&size, &pwc)))
                 return false;
             bool success = XPCConvert::NativeStringWithSize2JS(pJSVal, (const void*)&pwc,
                                                                TD_PWSTRING_SIZE_IS, size, pErr);
-            nsMemory::Free(pwc);
+            free(pwc);
             return success;
         }
         case nsIDataType::VTYPE_INTERFACE:
         case nsIDataType::VTYPE_INTERFACE_IS:
         {
             nsISupports* pi;
             nsID* piid;
             if (NS_FAILED(variant->GetAsInterface(&piid, (void**)&pi)))
                 return false;
 
             iid = *piid;
-            nsMemory::Free((char*)piid);
+            free((char*)piid);
 
             bool success = XPCConvert::NativeData2JS(pJSVal, (const void*)&pi,
                                                      TD_INTERFACE_IS_TYPE, &iid, pErr);
             if (pi)
                 pi->Release();
             return success;
         }
         case nsIDataType::VTYPE_ARRAY:
--- a/js/xpconnect/src/XPCWrappedJS.cpp
+++ b/js/xpconnect/src/XPCWrappedJS.cpp
@@ -626,17 +626,17 @@ nsXPCWrappedJS::DebugDump(int16_t depth)
         XPC_LOG_INDENT();
 
         XPC_LOG_ALWAYS(("%s wrapper around JSObject @ %x", \
                         IsRootWrapper() ? "ROOT":"non-root", mJSObj.get()));
         char* name;
         GetClass()->GetInterfaceInfo()->GetName(&name);
         XPC_LOG_ALWAYS(("interface name is %s", name));
         if (name)
-            nsMemory::Free(name);
+            free(name);
         char * iid = GetClass()->GetIID().ToString();
         XPC_LOG_ALWAYS(("IID number is %s", iid ? iid : "invalid"));
         if (iid)
             NS_Free(iid);
         XPC_LOG_ALWAYS(("nsXPCWrappedJSClass @ %x", mClass.get()));
 
         if (!IsRootWrapper())
             XPC_LOG_OUTDENT();
--- a/js/xpconnect/src/XPCWrappedJSClass.cpp
+++ b/js/xpconnect/src/XPCWrappedJSClass.cpp
@@ -167,17 +167,17 @@ nsXPCWrappedJSClass::nsXPCWrappedJSClass
 nsXPCWrappedJSClass::~nsXPCWrappedJSClass()
 {
     if (mDescriptors && mDescriptors != &zero_methods_descriptor)
         delete [] mDescriptors;
     if (mRuntime)
         mRuntime->GetWrappedJSClassMap()->Remove(this);
 
     if (mName)
-        nsMemory::Free(mName);
+        free(mName);
 }
 
 JSObject*
 nsXPCWrappedJSClass::CallQueryInterfaceOnJSObject(JSContext* cx,
                                                   JSObject* jsobjArg,
                                                   REFNSIID aIID)
 {
     RootedObject jsobj(cx, jsobjArg);
@@ -685,32 +685,32 @@ nsXPCWrappedJSClass::CleanupPointerArray
         for (uint32_t k = 0; k < array_count; k++) {
             nsISupports* p = pp[k];
             NS_IF_RELEASE(p);
         }
     } else {
         void** pp = (void**) arrayp;
         for (uint32_t k = 0; k < array_count; k++) {
             void* p = pp[k];
-            if (p) nsMemory::Free(p);
+            if (p) free(p);
         }
     }
 }
 
 void
 nsXPCWrappedJSClass::CleanupPointerTypeObject(const nsXPTType& type,
                                               void** pp)
 {
     MOZ_ASSERT(pp,"null pointer");
     if (type.IsInterfacePointer()) {
         nsISupports* p = *((nsISupports**)pp);
         if (p) p->Release();
     } else {
         void* p = *((void**)pp);
-        if (p) nsMemory::Free(p);
+        if (p) free(p);
     }
 }
 
 nsresult
 nsXPCWrappedJSClass::CheckForException(XPCCallContext & ccx,
                                        const char * aPropertyName,
                                        const char * anInterfaceName,
                                        bool aForceReport)
@@ -1173,17 +1173,17 @@ pre_call_clean_up:
                         GetArraySizeFromParam(cx, info, param, methodIndex,
                                               i, nativeParams, &array_count) &&
                         array_count) {
 
                         CleanupPointerArray(datum_type, array_count, pp);
                     }
 
                     // always release the array if it is inout
-                    nsMemory::Free(pp);
+                    free(pp);
                 }
             } else
                 CleanupPointerTypeObject(type, (void**)p);
         }
         *((void**)p) = nullptr;
     }
 
     // Make sure "this" doesn't get deleted during this call.
@@ -1413,17 +1413,17 @@ pre_call_clean_up:
                                                             1, &datum_type)) &&
                         datum_type.deprecated_IsPointer() &&
                         GetArraySizeFromParam(cx, info, param, methodIndex,
                                               k, nativeParams, &array_count) &&
                         array_count) {
 
                         CleanupPointerArray(datum_type, array_count, pp);
                     }
-                    nsMemory::Free(pp);
+                    free(pp);
                 }
             } else
                 CleanupPointerTypeObject(type, (void**)p);
             *((void**)p) = nullptr;
         }
     } else {
         // set to whatever the JS code might have set as the result
         retval = xpcc->GetPendingResult();
@@ -1481,17 +1481,17 @@ nsXPCWrappedJSClass::DebugDump(int16_t d
 #ifdef DEBUG
     depth-- ;
     XPC_LOG_ALWAYS(("nsXPCWrappedJSClass @ %x with mRefCnt = %d", this, mRefCnt.get()));
     XPC_LOG_INDENT();
         char* name;
         mInfo->GetName(&name);
         XPC_LOG_ALWAYS(("interface name is %s", name));
         if (name)
-            nsMemory::Free(name);
+            free(name);
         char * iid = mIID.ToString();
         XPC_LOG_ALWAYS(("IID number is %s", iid ? iid : "invalid"));
         if (iid)
             NS_Free(iid);
         XPC_LOG_ALWAYS(("InterfaceInfo @ %x", mInfo.get()));
         uint16_t methodCount = 0;
         if (depth) {
             uint16_t i;
--- a/js/xpconnect/src/XPCWrappedNative.cpp
+++ b/js/xpconnect/src/XPCWrappedNative.cpp
@@ -1462,17 +1462,17 @@ CallMethodHelper::~CallMethodHelper()
                     for (uint32_t k = 0; k < array_count; k++) {
                         nsXPTCMiniVariant v;
                         v.val.p = static_cast<void**>(p)[k];
                         CleanupParam(v, datum_type);
                     }
                 }
 
                 // always free the array itself
-                nsMemory::Free(p);
+                free(p);
             } else {
                 // Clean up single parameters (if requested).
                 if (dp->DoesValNeedCleanup())
                     CleanupParam(*dp, dp->type);
             }
         }
     }
 
@@ -2029,17 +2029,17 @@ CallMethodHelper::CleanupParam(nsXPTCMin
             nsXPConnect::GetRuntimeInstance()->mScratchStrings.Destroy((nsString*)param.val.p);
             break;
         case nsXPTType::T_UTF8STRING:
         case nsXPTType::T_CSTRING:
             nsXPConnect::GetRuntimeInstance()->mScratchCStrings.Destroy((nsCString*)param.val.p);
             break;
         default:
             MOZ_ASSERT(!type.IsArithmetic(), "Cleanup requested on unexpected type.");
-            nsMemory::Free(param.val.p);
+            free(param.val.p);
             break;
     }
 }
 
 bool
 CallMethodHelper::AllocateStringClass(nsXPTCVariant* dp,
                                       const nsXPTParamInfo& paramInfo)
 {
@@ -2315,19 +2315,19 @@ static void DEBUG_CheckClassInfoClaims(X
                "   classname: %s \n"
                "   contractid: %s \n"
                "   unimplemented interface name: %s\n\n",
                className ? className : "<unknown>",
                contractID ? contractID : "<unknown>",
                interfaceName);
 
         if (className)
-            nsMemory::Free(className);
+            free(className);
         if (contractID)
-            nsMemory::Free(contractID);
+            free(contractID);
     }
 }
 #endif
 
 NS_IMPL_ISUPPORTS(XPCJSObjectHolder, nsIXPConnectJSObjectHolder)
 
 JSObject*
 XPCJSObjectHolder::GetJSObject()
--- a/js/xpconnect/src/nsScriptError.cpp
+++ b/js/xpconnect/src/nsScriptError.cpp
@@ -222,21 +222,21 @@ nsScriptError::ToString(nsACString& /*UT
                            tempSourceName,
                            mLineNumber);
     else
         temp = JS_smprintf(format2,
                            severity,
                            tempMessage);
 
     if (nullptr != tempMessage)
-        nsMemory::Free(tempMessage);
+        free(tempMessage);
     if (nullptr != tempSourceName)
-        nsMemory::Free(tempSourceName);
+        free(tempSourceName);
     if (nullptr != tempSourceLine)
-        nsMemory::Free(tempSourceLine);
+        free(tempSourceLine);
 
     if (!temp)
         return NS_ERROR_OUT_OF_MEMORY;
 
     aResult.Assign(temp);
     JS_smprintf_free(temp);
     return NS_OK;
 }
--- a/js/xpconnect/src/nsXPConnect.cpp
+++ b/js/xpconnect/src/nsXPConnect.cpp
@@ -1259,17 +1259,17 @@ ReadScriptOrFunction(nsIObjectInputStrea
             JSObject* funobj = JS_DecodeInterpretedFunction(cx, data, size);
             if (!funobj)
                 rv = NS_ERROR_OUT_OF_MEMORY;
             else
                 *functionObjp = funobj;
         }
     }
 
-    nsMemory::Free(data);
+    free(data);
     return rv;
 }
 
 NS_IMETHODIMP
 nsXPConnect::WriteScript(nsIObjectOutputStream* stream, JSContext* cx, JSScript* script)
 {
     return WriteScriptOrFunction(stream, cx, script, NullPtr());
 }
--- a/js/xpconnect/src/xpcprivate.h
+++ b/js/xpconnect/src/xpcprivate.h
@@ -1692,17 +1692,17 @@ public:
 
     XPCNativeScriptableShared(uint32_t aFlags, char* aName)
         : mFlags(aFlags)
         {memset(&mJSClass, 0, sizeof(mJSClass));
          mJSClass.base.name = aName;  // take ownership
          MOZ_COUNT_CTOR(XPCNativeScriptableShared);}
 
     ~XPCNativeScriptableShared()
-        {if (mJSClass.base.name)nsMemory::Free((void*)mJSClass.base.name);
+        {if (mJSClass.base.name)free((void*)mJSClass.base.name);
          MOZ_COUNT_DTOR(XPCNativeScriptableShared);}
 
     char* TransferNameOwnership()
         {char* name=(char*)mJSClass.base.name; mJSClass.base.name = nullptr;
         return name;}
 
     void PopulateJSClass();
 
--- a/js/xpconnect/tests/components/native/xpctest_attributes.cpp
+++ b/js/xpconnect/tests/components/native/xpctest_attributes.cpp
@@ -66,29 +66,29 @@ xpcTestObjectReadWrite :: xpcTestObjectR
     charProperty = 'X';
     // timeProperty is PRTime and signed type.
     // So it has to allow negative value.
     timeProperty = -1;
 }
 
 xpcTestObjectReadWrite :: ~xpcTestObjectReadWrite()
 {
-    nsMemory::Free(stringProperty);
+    free(stringProperty);
 }
 
 NS_IMETHODIMP xpcTestObjectReadWrite :: GetStringProperty(char * *aStringProperty) {
     if (!aStringProperty)
         return NS_ERROR_NULL_POINTER;
     *aStringProperty = (char*) nsMemory::Clone(stringProperty,
                                                sizeof(char)*(strlen(stringProperty)+1));
     return *aStringProperty ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
 
 }
 NS_IMETHODIMP xpcTestObjectReadWrite :: SetStringProperty(const char * aStringProperty) {
-    nsMemory::Free(stringProperty);
+    free(stringProperty);
     stringProperty = (char*) nsMemory::Clone(aStringProperty,
                                              sizeof(char)*(strlen(aStringProperty)+1));
     return NS_OK;
 }
 
 NS_IMETHODIMP xpcTestObjectReadWrite :: GetBooleanProperty(bool* aBooleanProperty) {
     *aBooleanProperty = boolProperty;
     return NS_OK;
--- a/layout/base/nsDocumentViewer.cpp
+++ b/layout/base/nsDocumentViewer.cpp
@@ -2260,17 +2260,17 @@ nsDocumentViewer::CreateStyleSet(nsIDocu
           if (!uri) continue;
 
           cssLoader->LoadSheetSync(uri, getter_AddRefs(csssheet));
           if (!csssheet) continue;
 
           styleSet->PrependStyleSheet(nsStyleSet::eAgentSheet, csssheet);
           shouldOverride = true;
         }
-        nsMemory::Free(str);
+        free(str);
       }
     }
   }
 
   if (!shouldOverride) {
     sheet = nsLayoutStylesheetCache::ScrollbarsSheet();
     if (sheet) {
       styleSet->PrependStyleSheet(nsStyleSet::eAgentSheet, sheet);
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -10432,17 +10432,17 @@ static void RecurseIndiTotals(nsPresCont
   IndiReflowCounter * counter = (IndiReflowCounter *)PL_HashTableLookup(aHT, key);
   if (counter) {
     counter->mHasBeenOutput = true;
     char * name = ToNewCString(counter->mName);
     for (int32_t i=0;i<aLevel;i++) printf(" ");
     printf("%s - %p   [%d][", name, (void*)aParentFrame, counter->mCount);
     printf("%d", counter->mCounter.GetTotal());
     printf("]\n");
-    nsMemory::Free(name);
+    free(name);
   }
 
   nsIFrame* child = aParentFrame->GetFirstPrincipalChild();
   while (child) {
     RecurseIndiTotals(aPresContext, aHT, child, aLevel+1);
     child = child->GetNextSibling();
   }
 
@@ -10452,17 +10452,17 @@ static void RecurseIndiTotals(nsPresCont
 int ReflowCountMgr::DoSingleIndi(PLHashEntry *he, int i, void *arg)
 {
   IndiReflowCounter * counter = (IndiReflowCounter *)he->value;
   if (counter && !counter->mHasBeenOutput) {
     char * name = ToNewCString(counter->mName);
     printf("%s - %p   [%d][", name, (void*)counter->mFrame, counter->mCount);
     printf("%d", counter->mCounter.GetTotal());
     printf("]\n");
-    nsMemory::Free(name);
+    free(name);
   }
   return HT_ENUMERATE_NEXT;
 }
 
 //------------------------------------------------------------------
 void ReflowCountMgr::DoIndiTotalsTree()
 {
   if (nullptr != mCounts) {
--- a/layout/generic/nsFloatManager.cpp
+++ b/layout/generic/nsFloatManager.cpp
@@ -61,17 +61,17 @@ void* nsFloatManager::operator new(size_
   if (sCachedFloatManagerCount > 0) {
     // We have cached unused instances of this class, return a cached
     // instance in stead of always creating a new one.
     return sCachedFloatManagers[--sCachedFloatManagerCount];
   }
 
   // The cache is empty, this means we haveto create a new instance using
   // the global |operator new|.
-  return nsMemory::Alloc(aSize);
+  return moz_xmalloc(aSize);
 }
 
 void
 nsFloatManager::operator delete(void* aPtr, size_t aSize)
 {
   if (!aPtr)
     return;
   // This float manager is no longer used, if there's still room in
@@ -84,32 +84,32 @@ nsFloatManager::operator delete(void* aP
     // instance in the cache in stead of deleting it.
 
     sCachedFloatManagers[sCachedFloatManagerCount++] = aPtr;
     return;
   }
 
   // The cache is full, or the layout module has been shut down,
   // delete this float manager.
-  nsMemory::Free(aPtr);
+  free(aPtr);
 }
 
 
 /* static */
 void nsFloatManager::Shutdown()
 {
   // The layout module is being shut down, clean up the cache and
   // disable further caching.
 
   int32_t i;
 
   for (i = 0; i < sCachedFloatManagerCount; i++) {
     void* floatManager = sCachedFloatManagers[i];
     if (floatManager)
-      nsMemory::Free(floatManager);
+      free(floatManager);
   }
 
   // Disable further caching.
   sCachedFloatManagerCount = -1;
 }
 
 nsFlowAreaRect
 nsFloatManager::GetFlowArea(WritingMode aWM, nscoord aBOffset,
--- a/layout/generic/nsImageMap.cpp
+++ b/layout/generic/nsImageMap.cpp
@@ -107,31 +107,31 @@ void Area::ParseCoords(const nsAString& 
 
     /*
      * Nothing in an empty list
      */
     mNumCoords = 0;
     mCoords = nullptr;
     if (*cp == '\0')
     {
-      nsMemory::Free(cp);
+      free(cp);
       return;
     }
 
     /*
      * Skip beginning whitespace, all whitespace is empty list.
      */
     n_str = cp;
     while (is_space(*n_str))
     {
       n_str++;
     }
     if (*n_str == '\0')
     {
-      nsMemory::Free(cp);
+      free(cp);
       return;
     }
 
     /*
      * Make a pass where any two numbers separated by just whitespace
      * are given a comma separator.  Count entries while passing.
      */
     cnt = 0;
@@ -206,17 +206,17 @@ void Area::ParseCoords(const nsAString& 
     cnt++;
 
     /*
      * Allocate space for the coordinate array.
      */
     value_list = new nscoord[cnt];
     if (!value_list)
     {
-      nsMemory::Free(cp);
+      free(cp);
       return;
     }
 
     /*
      * Second pass to copy integer values into list.
      */
     tptr = cp;
     for (i=0; i<cnt; i++)
@@ -249,17 +249,17 @@ void Area::ParseCoords(const nsAString& 
         *ptr = ',';
         tptr = ptr + 1;
       }
     }
 
     mNumCoords = cnt;
     mCoords = value_list;
 
-    nsMemory::Free(cp);
+    free(cp);
   }
 }
 
 void Area::HasFocus(bool aHasFocus)
 {
   mHasFocus = aHasFocus;
 }
 
--- a/layout/generic/nsPageFrame.cpp
+++ b/layout/generic/nsPageFrame.cpp
@@ -201,43 +201,43 @@ nsPageFrame::ProcessSpecialCodes(const n
   //
   // Search to see if the "page number and page" total code are in the string
   // and replace the page number and page total code with the actual
   // values
   NS_NAMED_LITERAL_STRING(kPageAndTotal, "&PT");
   if (aStr.Find(kPageAndTotal) != kNotFound) {
     char16_t * uStr = nsTextFormatter::smprintf(mPD->mPageNumAndTotalsFormat.get(), mPageNum, mTotNumPages);
     aNewStr.ReplaceSubstring(kPageAndTotal.get(), uStr);
-    nsMemory::Free(uStr);
+    free(uStr);
   }
 
   // Search to see if the page number code is in the string
   // and replace the page number code with the actual value
   NS_NAMED_LITERAL_STRING(kPage, "&P");
   if (aStr.Find(kPage) != kNotFound) {
     char16_t * uStr = nsTextFormatter::smprintf(mPD->mPageNumFormat.get(), mPageNum);
     aNewStr.ReplaceSubstring(kPage.get(), uStr);
-    nsMemory::Free(uStr);
+    free(uStr);
   }
 
   NS_NAMED_LITERAL_STRING(kTitle, "&T");
   if (aStr.Find(kTitle) != kNotFound) {
     aNewStr.ReplaceSubstring(kTitle.get(), mPD->mDocTitle.get());
   }
 
   NS_NAMED_LITERAL_STRING(kDocURL, "&U");
   if (aStr.Find(kDocURL) != kNotFound) {
     aNewStr.ReplaceSubstring(kDocURL.get(), mPD->mDocURL.get());
   }
 
   NS_NAMED_LITERAL_STRING(kPageTotal, "&L");
   if (aStr.Find(kPageTotal) != kNotFound) {
     char16_t * uStr = nsTextFormatter::smprintf(mPD->mPageNumFormat.get(), mTotNumPages);
     aNewStr.ReplaceSubstring(kPageTotal.get(), uStr);
-    nsMemory::Free(uStr);
+    free(uStr);
   }
 }
 
 
 //------------------------------------------------------------------------------
 nscoord nsPageFrame::GetXPosition(nsRenderingContext& aRenderingContext,
                                   nsFontMetrics&       aFontMetrics,
                                   const nsRect&        aRect, 
--- a/layout/generic/nsSelection.cpp
+++ b/layout/generic/nsSelection.cpp
@@ -3874,17 +3874,17 @@ Selection::GetRangesForInterval(nsIDOMNo
     return result.ErrorCode();
   }
   *aResultCount = results.Length();
   if (*aResultCount == 0) {
     return NS_OK;
   }
 
   *aResults = static_cast<nsIDOMRange**>
-                         (nsMemory::Alloc(sizeof(nsIDOMRange*) * *aResultCount));
+                         (moz_xmalloc(sizeof(nsIDOMRange*) * *aResultCount));
   NS_ENSURE_TRUE(*aResults, NS_ERROR_OUT_OF_MEMORY);
 
   for (uint32_t i = 0; i < *aResultCount; i++) {
     (*aResults)[i] = results[i].forget().take();
   }
   return NS_OK;
 }
 
--- a/layout/generic/nsTextFrame.cpp
+++ b/layout/generic/nsTextFrame.cpp
@@ -402,17 +402,17 @@ protected:
                                nscolor aBackColor);
 };
 
 static void
 DestroyUserData(void* aUserData)
 {
   TextRunUserData* userData = static_cast<TextRunUserData*>(aUserData);
   if (userData) {
-    nsMemory::Free(userData);
+    free(userData);
   }
 }
 
 /**
  * Remove |aTextRun| from the frame continuation chain starting at
  * |aStartContinuation| if non-null, otherwise starting at |aFrame|.
  * Unmark |aFrame| as a text run owner if it's the frame we start at.
  * Return true if |aStartContinuation| is non-null and was found
@@ -1891,17 +1891,17 @@ BuildTextRunsScanner::BuildTextRunForFra
   // allocate userData.
   if (mMappedFlows.Length() == 1 && !mMappedFlows[0].mEndFrame &&
       mMappedFlows[0].mStartFrame->GetContentOffset() == 0) {
     userData = &dummyData;
     userDataToDestroy = nullptr;
     dummyData.mMappedFlows = &dummyMappedFlow;
   } else {
     userData = static_cast<TextRunUserData*>
-      (nsMemory::Alloc(sizeof(TextRunUserData) + mMappedFlows.Length()*sizeof(TextRunMappedFlow)));
+      (moz_xmalloc(sizeof(TextRunUserData) + mMappedFlows.Length()*sizeof(TextRunMappedFlow)));
     userDataToDestroy = userData;
     userData->mMappedFlows = reinterpret_cast<TextRunMappedFlow*>(userData + 1);
   }
   userData->mMappedFlowCount = mMappedFlows.Length();
   userData->mLastFlowIndex = 0;
 
   uint32_t currentTransformedTextOffset = 0;
 
@@ -2285,17 +2285,17 @@ BuildTextRunsScanner::SetupLineBreakerCo
   // allocate userData.
   if (mMappedFlows.Length() == 1 && !mMappedFlows[0].mEndFrame &&
       mMappedFlows[0].mStartFrame->GetContentOffset() == 0) {
     userData = &dummyData;
     userDataToDestroy = nullptr;
     dummyData.mMappedFlows = &dummyMappedFlow;
   } else {
     userData = static_cast<TextRunUserData*>
-      (nsMemory::Alloc(sizeof(TextRunUserData) + mMappedFlows.Length()*sizeof(TextRunMappedFlow)));
+      (moz_xmalloc(sizeof(TextRunUserData) + mMappedFlows.Length()*sizeof(TextRunMappedFlow)));
     userDataToDestroy = userData;
     userData->mMappedFlows = reinterpret_cast<TextRunMappedFlow*>(userData + 1);
   }
   userData->mMappedFlowCount = mMappedFlows.Length();
   userData->mLastFlowIndex = 0;
 
   uint32_t nextBreakIndex = 0;
   nsTextFrame* nextBreakBeforeFrame = GetNextBreakBeforeFrame(&nextBreakIndex);
--- a/layout/inspector/inDOMUtils.cpp
+++ b/layout/inspector/inDOMUtils.cpp
@@ -451,17 +451,17 @@ inDOMUtils::GetCSSPropertyNames(uint32_t
     maxCount = eCSSProperty_COUNT;
   }
 
   if (aFlags & INCLUDE_ALIASES) {
     maxCount += (eCSSProperty_COUNT_with_aliases - eCSSProperty_COUNT);
   }
 
   char16_t** props =
-    static_cast<char16_t**>(nsMemory::Alloc(maxCount * sizeof(char16_t*)));
+    static_cast<char16_t**>(moz_xmalloc(maxCount * sizeof(char16_t*)));
 
 #define DO_PROP(_prop)                                                  \
   PR_BEGIN_MACRO                                                        \
     nsCSSProperty cssProp = nsCSSProperty(_prop);                       \
     if (nsCSSProps::IsEnabled(cssProp)) {                               \
       props[propCount] =                                                \
         ToNewUnicode(nsDependentCString(kCSSRawProperties[_prop]));     \
       ++propCount;                                                      \
@@ -611,31 +611,31 @@ inDOMUtils::GetSubpropertiesForCSSProper
 
   if (propertyID == eCSSProperty_UNKNOWN ||
       propertyID == eCSSPropertyExtra_variable) {
     return NS_ERROR_FAILURE;
   }
 
   nsTArray<nsString> array;
   if (!nsCSSProps::IsShorthand(propertyID)) {
-    *aValues = static_cast<char16_t**>(nsMemory::Alloc(sizeof(char16_t*)));
+    *aValues = static_cast<char16_t**>(moz_xmalloc(sizeof(char16_t*)));
     (*aValues)[0] = ToNewUnicode(nsCSSProps::GetStringValue(propertyID));
     *aLength = 1;
     return NS_OK;
   }
 
   // Count up how many subproperties we have.
   size_t subpropCount = 0;
   for (const nsCSSProperty *props = nsCSSProps::SubpropertyEntryFor(propertyID);
        *props != eCSSProperty_UNKNOWN; ++props) {
     ++subpropCount;
   }
 
   *aValues =
-    static_cast<char16_t**>(nsMemory::Alloc(subpropCount * sizeof(char16_t*)));
+    static_cast<char16_t**>(moz_xmalloc(subpropCount * sizeof(char16_t*)));
   *aLength = subpropCount;
   for (const nsCSSProperty *props = nsCSSProps::SubpropertyEntryFor(propertyID),
                            *props_start = props;
        *props != eCSSProperty_UNKNOWN; ++props) {
     (*aValues)[props-props_start] = ToNewUnicode(nsCSSProps::GetStringValue(*props));
   }
   return NS_OK;
 }
--- a/layout/printing/nsPrintEngine.cpp
+++ b/layout/printing/nsPrintEngine.cpp
@@ -894,17 +894,17 @@ nsPrintEngine::EnumerateDocumentNames(ui
 {
   NS_ENSURE_ARG(aCount);
   NS_ENSURE_ARG_POINTER(aResult);
 
   *aCount = 0;
   *aResult = nullptr;
 
   int32_t     numDocs = mPrt->mPrintDocList.Length();
-  char16_t** array   = (char16_t**) nsMemory::Alloc(numDocs * sizeof(char16_t*));
+  char16_t** array   = (char16_t**) moz_xmalloc(numDocs * sizeof(char16_t*));
   if (!array)
     return NS_ERROR_OUT_OF_MEMORY;
 
   for (int32_t i=0;i<numDocs;i++) {
     nsPrintObject* po = mPrt->mPrintDocList.ElementAt(i);
     NS_ASSERTION(po, "nsPrintObject can't be null!");
     nsAutoString docTitleStr;
     nsAutoString docURLStr;
@@ -1448,18 +1448,18 @@ nsPrintEngine::GetDisplayTitleAndURL(nsP
     if (docTitleStrPS) {
       aTitle = docTitleStrPS;
     }
 
     if (docURLStrPS) {
       aURLStr = docURLStrPS;
     }
 
-    nsMemory::Free(docTitleStrPS);
-    nsMemory::Free(docURLStrPS);
+    free(docTitleStrPS);
+    free(docURLStrPS);
   }
 
   nsAutoString docTitle;
   nsAutoString docUrl;
   GetDocumentTitleAndURL(aPO->mDocument, docTitle, docUrl);
 
   if (aURLStr.IsEmpty() && !docUrl.IsEmpty()) {
     aURLStr = docUrl;
@@ -3017,19 +3017,19 @@ void nsPrintEngine::SetIsPrintPreview(bo
   }
 }
 
 //---------------------------------------------------------------------
 void
 nsPrintEngine::CleanupDocTitleArray(char16_t**& aArray, int32_t& aCount)
 {
   for (int32_t i = aCount - 1; i >= 0; i--) {
-    nsMemory::Free(aArray[i]);
+    free(aArray[i]);
   }
-  nsMemory::Free(aArray);
+  free(aArray);
   aArray = nullptr;
   aCount = 0;
 }
 
 //---------------------------------------------------------------------
 // static
 bool nsPrintEngine::HasFramesetChild(nsIContent* aContent)
 {
--- a/layout/style/nsROCSSPrimitiveValue.cpp
+++ b/layout/style/nsROCSSPrimitiveValue.cpp
@@ -692,17 +692,17 @@ nsROCSSPrimitiveValue::Reset()
 {
   switch (mType) {
     case CSS_IDENT:
       break;
     case CSS_STRING:
     case CSS_ATTR:
     case CSS_COUNTER: // FIXME: Counter should use an object
       NS_ASSERTION(mValue.mString, "Null string should never happen");
-      nsMemory::Free(mValue.mString);
+      free(mValue.mString);
       mValue.mString = nullptr;
       break;
     case CSS_URI:
       NS_IF_RELEASE(mValue.mURI);
       break;
     case CSS_RECT:
       NS_ASSERTION(mValue.mRect, "Null Rect should never happen");
       NS_RELEASE(mValue.mRect);
--- a/layout/xul/nsMenuFrame.cpp
+++ b/layout/xul/nsMenuFrame.cpp
@@ -1147,17 +1147,17 @@ nsMenuFrame::BuildAcceleratorText(bool a
       }
     }
     
     accelText += modifierSeparator;
 
     token = nsCRT::strtok(newStr, ", \t", &newStr);
   }
 
-  nsMemory::Free(str);
+  free(str);
 
   accelText += accelString;
 
   mIgnoreAccelTextChange = true;
   mContent->SetAttr(kNameSpaceID_None, nsGkAtoms::acceltext, accelText, aNotify);
   ENSURE_TRUE(weakFrame.IsAlive());
 
   mIgnoreAccelTextChange = false;
--- a/media/mtransport/gonk_addrs.cpp
+++ b/media/mtransport/gonk_addrs.cpp
@@ -80,17 +80,17 @@ GetInterfaces(std::vector<NetworkInterfa
       ip.Assign(ips[j]);
       if (inet_pton(AF_INET, NS_ConvertUTF16toUTF8(ip).get(),
                     &(interface.addr.sin_addr.s_addr)) == 1) {
         isAddressGot = true;
         break;
       }
     }
 
-    nsMemory::Free(prefixs);
+    free(prefixs);
     NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, ips);
 
     if (!isAddressGot) {
       continue;
     }
 
     nsAutoString ifaceName;
     if (NS_FAILED(iface->GetName(ifaceName))) {
--- a/modules/libjar/nsJAR.cpp
+++ b/modules/libjar/nsJAR.cpp
@@ -860,17 +860,17 @@ void nsJAR::ReportError(const nsACString
   if (console)
   {
     console->LogStringMessage(message.get());
   }
 #ifdef DEBUG
   char* messageCstr = ToNewCString(message);
   if (!messageCstr) return;
   fprintf(stderr, "%s\n", messageCstr);
-  nsMemory::Free(messageCstr);
+  free(messageCstr);
 #endif
 }
 
 
 nsresult nsJAR::CalculateDigest(const char* aInBuf, uint32_t aLen,
                                 nsCString& digest)
 {
   nsresult rv;
--- a/modules/libjar/nsJARURI.cpp
+++ b/modules/libjar/nsJARURI.cpp
@@ -183,17 +183,17 @@ nsJARURI::GetClassDescription(char * *aC
 {
     *aClassDescription = nullptr;
     return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsJARURI::GetClassID(nsCID * *aClassID)
 {
-    *aClassID = (nsCID*) nsMemory::Alloc(sizeof(nsCID));
+    *aClassID = (nsCID*) moz_xmalloc(sizeof(nsCID));
     if (!*aClassID)
         return NS_ERROR_OUT_OF_MEMORY;
     return GetClassIDNoAlloc(*aClassID);
 }
 
 NS_IMETHODIMP 
 nsJARURI::GetFlags(uint32_t *aFlags)
 {
--- a/modules/libpref/nsPrefBranch.cpp
+++ b/modules/libpref/nsPrefBranch.cpp
@@ -565,17 +565,17 @@ NS_IMETHODIMP nsPrefBranch::GetChildList
   ed.pref_list = &prefArray;
   PL_DHashTableEnumerate(&gHashTable, pref_enumChild, &ed);
 
   // now that we've built up the list, run the callback on
   // all the matching elements
   numPrefs = prefArray.Length();
 
   if (numPrefs) {
-    outArray = (char **)nsMemory::Alloc(numPrefs * sizeof(char *));
+    outArray = (char **)moz_xmalloc(numPrefs * sizeof(char *));
     if (!outArray)
       return NS_ERROR_OUT_OF_MEMORY;
 
     for (dwIndex = 0; dwIndex < numPrefs; ++dwIndex) {
       // we need to lop off mPrefRoot in case the user is planning to pass this
       // back to us because if they do we are going to add mPrefRoot again.
       const nsCString& element = prefArray[dwIndex];
       outArray[dwIndex] = (char *)nsMemory::Clone(
--- a/netwerk/base/nsDirectoryIndexStream.cpp
+++ b/netwerk/base/nsDirectoryIndexStream.cpp
@@ -294,17 +294,17 @@ nsDirectoryIndexStream::Read(char* aBuf,
                 rv = current->GetNativeLeafName(leafname);
                 if (NS_FAILED(rv)) return rv;
                 if (!leafname.IsEmpty())
                     escaped = nsEscape(leafname.get(), url_Path);
             }
             if (escaped) {
                 mBuf += escaped;
                 mBuf.Append(' ');
-                nsMemory::Free(escaped);
+                free(escaped);
             }
 
             // The "content-length" field
             mBuf.AppendInt(fileSize, 10);
             mBuf.Append(' ');
 
             // The "last-modified" field
             PRExplodedTime tm;
--- a/netwerk/base/nsIAuthModule.idl
+++ b/netwerk/base/nsIAuthModule.idl
@@ -73,17 +73,17 @@ interface nsIAuthModule : nsISupports
      *        A buffer containing the input token (e.g., a challenge from a
      *        server).  This may be null.
      * @param aInTokenLength
      *        The length of the input token.
      * @param aOutToken
      *        If getNextToken succeeds, then aOutToken will point to a buffer
      *        to be sent in response to the server challenge.  The length of
      *        this buffer is given by aOutTokenLength.  The buffer at aOutToken
-     *        must be recycled with a call to nsMemory::Free.
+     *        must be recycled with a call to free.
      * @param aOutTokenLength
      *        If getNextToken succeeds, then aOutTokenLength contains the
      *        length of the buffer (number of bytes) pointed to by aOutToken.
      */
     void getNextToken([const] in voidPtr  aInToken,
                       in unsigned long    aInTokenLength,
                       out voidPtr         aOutToken,
                       out unsigned long   aOutTokenLength);
--- a/netwerk/base/nsProtocolProxyService.h
+++ b/netwerk/base/nsProtocolProxyService.h
@@ -326,17 +326,17 @@ protected:
             HostInfoName name;
         };
 
         HostInfo()
             : is_ipaddr(false)
             { /* other members intentionally uninitialized */ }
        ~HostInfo() {
             if (!is_ipaddr && name.host)
-                nsMemory::Free(name.host);
+                free(name.host);
         }
     };
 
     // An instance of this struct is allocated for each registered
     // nsIProtocolProxyFilter and each nsIProtocolProxyChannelFilter.
     struct FilterLink {
       struct FilterLink                *next;
       uint32_t                          position;
--- a/netwerk/base/nsSimpleURI.cpp
+++ b/netwerk/base/nsSimpleURI.cpp
@@ -578,17 +578,17 @@ nsSimpleURI::GetClassDescription(char * 
     return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsSimpleURI::GetClassID(nsCID * *aClassID)
 {
     // Make sure to modify any subclasses as needed if this ever
     // changes to not call the virtual GetClassIDNoAlloc.
-    *aClassID = (nsCID*) nsMemory::Alloc(sizeof(nsCID));
+    *aClassID = (nsCID*) moz_xmalloc(sizeof(nsCID));
     if (!*aClassID)
         return NS_ERROR_OUT_OF_MEMORY;
     return GetClassIDNoAlloc(*aClassID);
 }
 
 NS_IMETHODIMP 
 nsSimpleURI::GetFlags(uint32_t *aFlags)
 {
--- a/netwerk/base/nsStandardURL.cpp
+++ b/netwerk/base/nsStandardURL.cpp
@@ -3201,17 +3201,17 @@ nsStandardURL::GetClassDescription(char 
 {
     *aClassDescription = nullptr;
     return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsStandardURL::GetClassID(nsCID * *aClassID)
 {
-    *aClassID = (nsCID*) nsMemory::Alloc(sizeof(nsCID));
+    *aClassID = (nsCID*) moz_xmalloc(sizeof(nsCID));
     if (!*aClassID)
         return NS_ERROR_OUT_OF_MEMORY;
     return GetClassIDNoAlloc(*aClassID);
 }
 
 NS_IMETHODIMP 
 nsStandardURL::GetFlags(uint32_t *aFlags)
 {
--- a/netwerk/cache/nsCacheEntryDescriptor.cpp
+++ b/netwerk/cache/nsCacheEntryDescriptor.cpp
@@ -918,17 +918,17 @@ nsDecompressInputStreamWrapper::Read(cha
     if (mReadBufferLen < count) {
         // Allocate a buffer for reading from the input stream. This will
         // determine the max number of compressed bytes read from the
         // input stream at one time. Making the buffer size proportional
         // to the request size is not necessary, but helps minimize the
         // number of read requests to the input stream.
         uint32_t newBufLen = std::max(count, (uint32_t)kMinDecompressReadBufLen);
         unsigned char* newBuf;
-        newBuf = (unsigned char*)nsMemory::Realloc(mReadBuffer, 
+        newBuf = (unsigned char*)moz_xrealloc(mReadBuffer,
             newBufLen);
         if (newBuf) {
             mReadBuffer = newBuf;
             mReadBufferLen = newBufLen;
         }
         if (!mReadBuffer) {
             mReadBufferLen = 0;
             return NS_ERROR_OUT_OF_MEMORY;
@@ -981,17 +981,17 @@ nsDecompressInputStreamWrapper::Close()
 {
     mozilla::MutexAutoLock lock(mLock);
 
     if (!mDescriptor)
         return NS_ERROR_NOT_AVAILABLE;
 
     EndZstream();
     if (mReadBuffer) {
-        nsMemory::Free(mReadBuffer);
+        free(mReadBuffer);
         mReadBuffer = 0;
         mReadBufferLen = 0;
     }
     return nsInputStreamWrapper::Close_Locked();
 }
 
 nsresult nsCacheEntryDescriptor::
 nsDecompressInputStreamWrapper::InitZstream()
@@ -1328,17 +1328,17 @@ nsCompressOutputStreamWrapper::Write(con
         }
     }
 
     if (!mWriteBuffer) {
         // Once allocated, this buffer is referenced by the zlib stream and
         // cannot be grown. We use 2x(initial write request) to approximate
         // a stream buffer size proportional to request buffers.
         mWriteBufferLen = std::max(count*2, (uint32_t)kMinCompressWriteBufLen);
-        mWriteBuffer = (unsigned char*)nsMemory::Alloc(mWriteBufferLen);
+        mWriteBuffer = (unsigned char*)moz_xmalloc(mWriteBufferLen);
         if (!mWriteBuffer) {
             mWriteBufferLen = 0;
             return NS_ERROR_OUT_OF_MEMORY;
         }
         mZstream.next_out = mWriteBuffer;
         mZstream.avail_out = mWriteBufferLen;
     }
 
@@ -1413,17 +1413,17 @@ nsCompressOutputStreamWrapper::Close()
         uncompressedLenStr.AppendInt(mUncompressedCount);
         rv = mDescriptor->SetMetaDataElement("uncompressed-len",
             uncompressedLenStr.get());
         if (NS_FAILED(rv))
             retval = rv;
     }
 
     if (mWriteBuffer) {
-        nsMemory::Free(mWriteBuffer);
+        free(mWriteBuffer);
         mWriteBuffer = 0;
         mWriteBufferLen = 0;
     }
 
     rv = nsOutputStreamWrapper::Close_Locked();
     if (NS_FAILED(rv))
         retval = rv;
 
--- a/netwerk/mime/nsIMIMEHeaderParam.idl
+++ b/netwerk/mime/nsIMIMEHeaderParam.idl
@@ -54,17 +54,17 @@ interface nsIMIMEHeaderParam : nsISuppor
    * @param  aFallbackCharset  fallback charset to try if  the string after
    *                           RFC 2231/2047 decoding or the raw 8bit 
    *                           string is not UTF-8
    * @param  aTryLocaleCharset If set, makes yet another attempt 
    *                           with the locale charset.
    * @param  aLang             If non-null, assigns it to a pointer 
    *                           to a string containing the value of language 
    *                           obtained from RFC 2231 parsing. Caller has to 
-   *                           nsMemory::Free it.
+   *                           free it.
    * @return the value of <code>aParamName</code> in Unichar(UTF-16).
    */
   AString getParameter(in ACString aHeaderVal,
                        in string aParamName,
                        in ACString aFallbackCharset,
                        in boolean aTryLocaleCharset, 
                        out string aLang);
 
@@ -118,20 +118,20 @@ interface nsIMIMEHeaderParam : nsISuppor
    * Otherwise, this method would have been made static.
    *
    * @param  aHeaderVal  a header string to get the value of a parameter from.
    * @param  aParamName  the name of a MIME header parameter (e.g. 
    *                     filename, name, charset). If empty,  returns 
    *                     the first (possibly) _unnamed_ 'parameter'.
    * @param  aCharset    If non-null, it gets assigned a new pointer
    *                     to a string containing the value of charset obtained
-   *                     from RFC 2231 parsing. Caller has to nsMemory::Free it.
+   *                     from RFC 2231 parsing. Caller has to free it.
    * @param  aLang       If non-null, it gets assigned a new pointer
    *                     to a string containing the value of language obtained
-   *                     from RFC 2231 parsing. Caller has to nsMemory::Free it.
+   *                     from RFC 2231 parsing. Caller has to free it.
    * @return             the value of <code>aParamName</code> after
    *                     RFC 2231 decoding but without charset conversion.
    */
 
   [noscript]
   string getParameterInternal(in string aHeaderVal,
                               in string aParamName,
                               out string aCharset,
--- a/netwerk/mime/nsMIMEHeaderParamImpl.cpp
+++ b/netwerk/mime/nsMIMEHeaderParamImpl.cpp
@@ -210,17 +210,17 @@ char *combineContinuations(nsTArray<Cont
 
   // Get an upper bound for the length
   uint32_t length = 0;
   for (uint32_t i = 0; i < aArray.Length(); i++) {
     length += aArray[i].length;
   }
 
   // Allocate
-  char *result = (char *) nsMemory::Alloc(length + 1);
+  char *result = (char *) moz_xmalloc(length + 1);
 
   // Concatenate
   if (result) {
     *result = '\0';
 
     for (uint32_t i = 0; i < aArray.Length(); i++) {
       Continuation cont = aArray[i];
       if (! cont.value) break;
@@ -232,17 +232,17 @@ char *combineContinuations(nsTArray<Cont
       }
       if (cont.wasQuotedString) {
         RemoveQuotedStringEscapes(c);
       }
     }
 
     // return null if empty value
     if (*result == '\0') {
-      nsMemory::Free(result);
+      free(result);
       result = nullptr;
     }
   } else {
     // Handle OOM
     NS_WARNING("Out of memory\n");
   }
 
   return result;
@@ -699,19 +699,19 @@ increment_str:
     charset.Assign(charsetCD);
   }
   else if (caseAResult) {
     *aResult = caseAResult;
     caseAResult = nullptr;
   }
 
   // free unused stuff
-  nsMemory::Free(caseAResult);
-  nsMemory::Free(caseBResult);
-  nsMemory::Free(caseCDResult);
+  free(caseAResult);
+  free(caseBResult);
+  free(caseCDResult);
 
   // if we have a result
   if (*aResult) {
     // then return charset and lang as well
     if (aLang && !lang.IsEmpty()) {
       uint32_t len = lang.Length();
       *aLang = (char *) nsMemory::Clone(lang.BeginReading(), len + 1);
       if (*aLang) {
@@ -793,25 +793,25 @@ bool IsRFC5987AttrChar(char aChar)
           c == '+' || c == '-' || c == '.' || c == '^' ||
           c == '_' || c == '`' || c == '|' || c == '~');
 }
 
 // percent-decode a value
 // returns false on failure
 bool PercentDecode(nsACString& aValue)
 {
-  char *c = (char *) nsMemory::Alloc(aValue.Length() + 1);
+  char *c = (char *) moz_xmalloc(aValue.Length() + 1);
   if (!c) {
     return false;
   }
 
   strcpy(c, PromiseFlatCString(aValue).get());
   nsUnescape(c);
   aValue.Assign(c);
-  nsMemory::Free(c);
+  free(c);
 
   return true;
 }
 
 // Decode a parameter value using the encoding defined in RFC 5987
 // 
 // charset  "'" [ language ] "'" value-chars
 NS_IMETHODIMP 
--- a/netwerk/protocol/about/nsAboutCache.cpp
+++ b/netwerk/protocol/about/nsAboutCache.cpp
@@ -105,17 +105,17 @@ nsAboutCache::NewChannel(nsIURI* aURI,
     mBuffer.AppendLiteral(
         "<label><input id='submit' type='button' value='Update' onclick='navigate()'/></label>\n"
     );
 
     if (!mOverview) {
         mBuffer.AppendLiteral("<a href=\"about:cache?storage=&amp;context=");
         char* escapedContext = nsEscapeHTML(mContextString.get());
         mBuffer.Append(escapedContext);
-        nsMemory::Free(escapedContext);
+        free(escapedContext);
         mBuffer.AppendLiteral("\">Back to overview</a>");
     }
 
     FlushBuffer();
 
     // Kick it, this goes async.
     rv = VisitNextStorage();
     if (NS_FAILED(rv)) return rv;
@@ -190,23 +190,23 @@ nsAboutCache::FireVisitStorage()
 
     rv = VisitStorage(mStorageName);
     if (NS_FAILED(rv)) {
         if (mLoadInfo) {
             char* escaped = nsEscapeHTML(mStorageName.get());
             mBuffer.Append(
                 nsPrintfCString("<p>Unrecognized storage name '%s' in about:cache URL</p>",
                                 escaped));
-            nsMemory::Free(escaped);
+            free(escaped);
         } else {
             char* escaped = nsEscapeHTML(mContextString.get());
             mBuffer.Append(
                 nsPrintfCString("<p>Unrecognized context key '%s' in about:cache URL</p>",
                                 escaped));
-            nsMemory::Free(escaped);
+            free(escaped);
         }
 
         FlushBuffer();
 
         // Simulate finish of a visit cycle, this tries the next storage
         // or closes the output stream (i.e. the UI loader will stop spinning)
         OnCacheEntryVisitCompleted();
     }
@@ -314,17 +314,17 @@ nsAboutCache::OnCacheStorageInfo(uint32_
     if (mOverview) { // The about:cache case
         if (aEntryCount != 0) { // Add the "List Cache Entries" link
             mBuffer.AppendLiteral("  <tr>\n"
                                   "    <th><a href=\"about:cache?storage=");
             mBuffer.Append(mStorageName);
             mBuffer.AppendLiteral("&amp;context=");
             char* escapedContext = nsEscapeHTML(mContextString.get());
             mBuffer.Append(escapedContext);
-            nsMemory::Free(escapedContext);
+            free(escapedContext);
             mBuffer.AppendLiteral("\">List Cache Entries</a></th>\n"
                                   "  </tr>\n");
         }
     }
 
     mBuffer.AppendLiteral("</table>\n");
 
     // The entries header is added on encounter of the first entry
@@ -378,22 +378,22 @@ nsAboutCache::OnCacheEntryInfo(nsIURI *a
 
     nsAutoCString url;
     url.AssignLiteral("about:cache-entry?storage=");
     url.Append(mStorageName);
 
     url.AppendLiteral("&amp;context=");
     char* escapedContext = nsEscapeHTML(mContextString.get());
     url += escapedContext;
-    nsMemory::Free(escapedContext);
+    free(escapedContext);
 
     url.AppendLiteral("&amp;eid=");
     char* escapedEID = nsEscapeHTML(aIdEnhance.BeginReading());
     url += escapedEID;
-    nsMemory::Free(escapedEID);
+    free(escapedEID);
 
     nsAutoCString cacheUriSpec;
     aURI->GetAsciiSpec(cacheUriSpec);
     char* escapedCacheURI = nsEscapeHTML(cacheUriSpec.get());
     url.AppendLiteral("&amp;uri=");
     url += escapedCacheURI;
 
     // Entry start...
@@ -405,17 +405,17 @@ nsAboutCache::OnCacheEntryInfo(nsIURI *a
     mBuffer.AppendLiteral("\">");
     if (!aIdEnhance.IsEmpty()) {
         mBuffer.Append(aIdEnhance);
         mBuffer.Append(':');
     }
     mBuffer.Append(escapedCacheURI);
     mBuffer.AppendLiteral("</a></td>\n");
 
-    nsMemory::Free(escapedCacheURI);
+    free(escapedCacheURI);
 
     // Content length
     mBuffer.AppendLiteral("    <td>");
     mBuffer.AppendInt(aDataSize);
     mBuffer.AppendLiteral(" bytes</td>\n");
 
     // Number of accesses
     mBuffer.AppendLiteral("    <td>");
--- a/netwerk/protocol/about/nsAboutCacheEntry.cpp
+++ b/netwerk/protocol/about/nsAboutCacheEntry.cpp
@@ -368,17 +368,17 @@ nsAboutCacheEntry::WriteCacheEntryDescri
         buffer.Append(escapedStr);
         buffer.AppendLiteral("\">");
         buffer.Append(escapedStr);
         buffer.AppendLiteral("</a>");
         uri = 0;
     } else {
         buffer.Append(escapedStr);
     }
-    nsMemory::Free(escapedStr);
+    free(escapedStr);
     buffer.AppendLiteral("</td>\n"
                          "  </tr>\n");
 
     // temp vars for reporting
     char timeBuf[255];
     uint32_t u = 0;
     int32_t  i = 0;
     nsAutoCString s;
@@ -501,17 +501,17 @@ nsAboutCacheEntry::OnMetaDataElement(cha
 {
     mBuffer->AppendLiteral("  <tr>\n"
                            "    <th>");
     mBuffer->Append(key);
     mBuffer->AppendLiteral(":</th>\n"
                            "    <td>");
     char* escapedValue = nsEscapeHTML(value);
     mBuffer->Append(escapedValue);
-    nsMemory::Free(escapedValue);
+    free(escapedValue);
     mBuffer->AppendLiteral("</td>\n"
                            "  </tr>\n");
 
     return NS_OK;
 }
 
 //-----------------------------------------------------------------------------
 // nsIStreamListener implementation
--- a/netwerk/protocol/device/AndroidCaptureProvider.cpp
+++ b/netwerk/protocol/device/AndroidCaptureProvider.cpp
@@ -25,17 +25,17 @@ AndroidCameraInputStream::AndroidCameraI
 {
   mAvailable = sizeof(RawVideoHeader);
   mFrameQueue = new nsDeque();
 }
 
 AndroidCameraInputStream::~AndroidCameraInputStream() {
   // clear the frame queue
   while (mFrameQueue->GetSize() > 0) {
-    nsMemory::Free(mFrameQueue->PopFront());
+    free(mFrameQueue->PopFront());
   }
   delete mFrameQueue;
 }
 
 NS_IMETHODIMP
 AndroidCameraInputStream::Init(nsACString& aContentType, nsCaptureParams* aParams)
 {
   if (XRE_GetProcessType() != GeckoProcessType_Default)
@@ -56,24 +56,24 @@ AndroidCameraInputStream::Init(nsACStrin
   }
   return NS_OK;
 }
 
 void AndroidCameraInputStream::ReceiveFrame(char* frame, uint32_t length) {
   {
     mozilla::ReentrantMonitorAutoEnter autoMonitor(mMonitor);
     if (mFrameQueue->GetSize() > MAX_FRAMES_QUEUED) {
-      nsMemory::Free(mFrameQueue->PopFront());
+      free(mFrameQueue->PopFront());
       mAvailable -= mFrameSize;
     }
   }
   
   mFrameSize = sizeof(RawPacketHeader) + length;
   
-  char* fullFrame = (char*)nsMemory::Alloc(mFrameSize);
+  char* fullFrame = (char*)moz_xmalloc(mFrameSize);
 
   if (!fullFrame)
     return;
   
   RawPacketHeader* header = (RawPacketHeader*) fullFrame;
   header->packetID = 0xFF;
   header->codecID = 0x595556; // "YUV"
   
@@ -172,17 +172,17 @@ NS_IMETHODIMP AndroidCameraInputStream::
       rv = aWriter(this, aClosure, (const char*)frame, *aRead, mFrameSize, &readThisTime);
 
       if (readThisTime != mFrameSize) {
         mFrameQueue->PushFront((void*)frame);
         return NS_OK;
       }
   
       // RawReader does a copy when calling VideoData::Create()
-      nsMemory::Free(frame);
+      free(frame);
   
       if (NS_FAILED(rv))
         return NS_OK;
 
       aCount -= readThisTime;
       mAvailable -= readThisTime;
       *aRead += readThisTime;
     }
--- a/netwerk/protocol/ftp/nsFtpConnectionThread.cpp
+++ b/netwerk/protocol/ftp/nsFtpConnectionThread.cpp
@@ -942,17 +942,17 @@ nsFtpState::R_syst() {
             
             char16_t* ucs2Response = ToNewUnicode(mResponseMsg);
             const char16_t *formatStrings[1] = { ucs2Response };
             NS_NAMED_LITERAL_STRING(name, "UnsupportedFTPServer");
 
             nsXPIDLString formattedString;
             rv = bundle->FormatStringFromName(name.get(), formatStrings, 1,
                                               getter_Copies(formattedString));
-            nsMemory::Free(ucs2Response);
+            free(ucs2Response);
             if (NS_FAILED(rv))
                 return FTP_ERROR;
 
             // TODO(darin): this code should not be dictating UI like this!
             nsCOMPtr<nsIPrompt> prompter;
             mChannel->GetCallback(prompter);
             if (prompter)
                 prompter->Alert(nullptr, formattedString.get());
--- a/netwerk/protocol/ftp/nsFtpProtocolHandler.h
+++ b/netwerk/protocol/ftp/nsFtpProtocolHandler.h
@@ -47,17 +47,17 @@ private:
         char                   *key;
         
         timerStruct() : conn(nullptr), key(nullptr) {}
         
         ~timerStruct() {
             if (timer)
                 timer->Cancel();
             if (key)
-                nsMemory::Free(key);
+                free(key);
             if (conn) {
                 conn->Disconnect(NS_ERROR_ABORT);
                 NS_RELEASE(conn);
             }
         }
     };
 
     static void Timeout(nsITimer *aTimer, void *aClosure);
--- a/netwerk/protocol/http/nsHttpNTLMAuth.cpp
+++ b/netwerk/protocol/http/nsHttpNTLMAuth.cpp
@@ -152,17 +152,17 @@ TestPref(nsIURI *uri, const char *pref)
             break;
         if (MatchesBaseURI(scheme, host, port, start, end))
             return true;
         if (*end == '\0')
             break;
         start = end + 1;
     }
 
-    nsMemory::Free(hostList);
+    free(hostList);
     return false;
 }
 
 // Check to see if we should use our generic (internal) NTLM auth module.
 static bool
 ForceGenericNTLM()
 {
     nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
@@ -441,44 +441,44 @@ nsHttpNTLMAuth::GenerateCredentials(nsIH
         len -= 5;
 
         // strip off any padding (see bug 230351)
         while (challenge[len - 1] == '=')
           len--;
 
         // decode into the input secbuffer
         inBufLen = (len * 3)/4;      // sufficient size (see plbase64.h)
-        inBuf = nsMemory::Alloc(inBufLen);
+        inBuf = moz_xmalloc(inBufLen);
         if (!inBuf)
             return NS_ERROR_OUT_OF_MEMORY;
 
         if (PL_Base64Decode(challenge, len, (char *) inBuf) == nullptr) {
-            nsMemory::Free(inBuf);
+            free(inBuf);
             return NS_ERROR_UNEXPECTED; // improper base64 encoding
         }
     }
 
     rv = module->GetNextToken(inBuf, inBufLen, &outBuf, &outBufLen);
     if (NS_SUCCEEDED(rv)) {
         // base64 encode data in output buffer and prepend "NTLM "
         int credsLen = 5 + ((outBufLen + 2)/3)*4;
-        *creds = (char *) nsMemory::Alloc(credsLen + 1);
+        *creds = (char *) moz_xmalloc(credsLen + 1);
         if (!*creds)
             rv = NS_ERROR_OUT_OF_MEMORY;
         else {
             memcpy(*creds, "NTLM ", 5);
             PL_Base64Encode((char *) outBuf, outBufLen, *creds + 5);
             (*creds)[credsLen] = '\0'; // null terminate
         }
         // OK, we are done with |outBuf|
-        nsMemory::Free(outBuf);
+        free(outBuf);
     }
 
     if (inBuf)
-        nsMemory::Free(inBuf);
+        free(inBuf);
 
     return rv;
 }
 
 NS_IMETHODIMP
 nsHttpNTLMAuth::GetAuthFlags(uint32_t *flags)
 {
     *flags = CONNECTION_BASED | IDENTITY_INCLUDES_DOMAIN | IDENTITY_ENCRYPTED;
--- a/netwerk/streamconv/converters/nsBinHexDecoder.cpp
+++ b/netwerk/streamconv/converters/nsBinHexDecoder.cpp
@@ -34,19 +34,19 @@ nsBinHexDecoder::nsBinHexDecoder() :
   mHeader.flags = 0;
   mHeader.dlen = 0;
   mHeader.rlen = 0;
 }
 
 nsBinHexDecoder::~nsBinHexDecoder()
 {
   if (mDataBuffer)
-    nsMemory::Free(mDataBuffer);
+    free(mDataBuffer);
   if (mOutgoingBuffer)
-    nsMemory::Free(mOutgoingBuffer);
+    free(mOutgoingBuffer);
 }
 
 NS_IMPL_ADDREF(nsBinHexDecoder)
 NS_IMPL_RELEASE(nsBinHexDecoder)
 
 NS_INTERFACE_MAP_BEGIN(nsBinHexDecoder)
   NS_INTERFACE_MAP_ENTRY(nsIStreamConverter)
   NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
--- a/netwerk/streamconv/converters/nsFTPDirListingConv.cpp
+++ b/netwerk/streamconv/converters/nsFTPDirListingConv.cpp
@@ -137,17 +137,17 @@ nsFTPDirListingConv::OnDataAvailable(nsI
     PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() sending the following %d bytes...\n\n%s\n\n", 
         indexFormat.Length(), indexFormat.get()) );
 #else
     char *unescData = ToNewCString(indexFormat);
     NS_ENSURE_TRUE(unescData, NS_ERROR_OUT_OF_MEMORY);
     
     nsUnescape(unescData);
     printf("::OnData() sending the following %d bytes...\n\n%s\n\n", indexFormat.Length(), unescData);
-    nsMemory::Free(unescData);
+    free(unescData);
 #endif // DEBUG_dougt
 
     // if there's any data left over, buffer it.
     if (line && *line) {
         mBuffer.Append(line);
         PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() buffering the following %d bytes...\n\n%s\n\n",
             strlen(line), line) );
     }
@@ -320,17 +320,17 @@ nsFTPDirListingConv::DigestBufferLines(c
         // the application/http-index-format specs
         // viewers of such a format can then reformat this into the
         // current locale (or anything else they choose)
         PR_FormatTimeUSEnglish(buffer, sizeof(buffer),
                                "%a, %d %b %Y %H:%M:%S", &result.fe_time );
 
         char *escapedDate = nsEscape(buffer, url_Path);
         aString.Append(escapedDate);
-        nsMemory::Free(escapedDate);
+        free(escapedDate);
         aString.Append(' ');
 
         // ENTRY TYPE
         if (type == 'd')
             aString.AppendLiteral("DIRECTORY");
         else if (type == 'l')
             aString.AppendLiteral("SYMBOLIC-LINK");
         else
--- a/netwerk/streamconv/converters/nsHTTPCompressConv.cpp
+++ b/netwerk/streamconv/converters/nsHTTPCompressConv.cpp
@@ -47,20 +47,20 @@ nsHTTPCompressConv::nsHTTPCompressConv()
     }
 }
 
 nsHTTPCompressConv::~nsHTTPCompressConv()
 {
     NS_IF_RELEASE(mListener);
 
     if (mInpBuffer)
-        nsMemory::Free(mInpBuffer);
+        free(mInpBuffer);
 
     if (mOutBuffer)
-        nsMemory::Free(mOutBuffer);
+        free(mOutBuffer);
 
     // For some reason we are not getting Z_STREAM_END.  But this was also seen
     //    for mozilla bug 198133.  Need to handle this case.
     if (mStreamInitialized && !mStreamEnded)
         inflateEnd (&d_stream);
 }
 
 NS_IMETHODIMP
--- a/netwerk/streamconv/test/TestStreamConv.cpp
+++ b/netwerk/streamconv/test/TestStreamConv.cpp
@@ -61,26 +61,26 @@ public:
     {
         nsresult rv;
         uint32_t read;
         uint64_t len64;
         rv = inStr->Available(&len64);
         if (NS_FAILED(rv)) return rv;
         uint32_t len = (uint32_t)std::min(len64, (uint64_t)(UINT32_MAX - 1));
 
-        char *buffer = (char*)nsMemory::Alloc(len + 1);
+        char *buffer = (char*)moz_xmalloc(len + 1);
         if (!buffer) return NS_ERROR_OUT_OF_MEMORY;
 
         rv = inStr->Read(buffer, len, &read);
         buffer[len] = '\0';
         if (NS_SUCCEEDED(rv)) {
             printf("CONTEXT %p: Received %u bytes and the following data: \n %s\n\n",
                    static_cast<void*>(ctxt), read, buffer);
         }
-        nsMemory::Free(buffer);
+        free(buffer);
 
         return NS_OK;
     }
 
     // nsIRequestObserver methods
     NS_IMETHOD OnStartRequest(nsIRequest* request, nsISupports *ctxt) override { return NS_OK; }
 
     NS_IMETHOD OnStopRequest(nsIRequest* request, nsISupports *ctxt, 
--- a/netwerk/test/TestCacheBlockFiles.cpp
+++ b/netwerk/test/TestCacheBlockFiles.cpp
@@ -853,17 +853,17 @@ main(void)
             goto exit;
 
         printf("Test 19: passed\n");
 
 
 exit:
 
         if (currentDirPath)
-            nsMemory::Free(currentDirPath);
+            free(currentDirPath);
     } // this scopes the nsCOMPtrs
     // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
     if (NS_FAILED(rv))
         printf("Test failed: 0x%.8x\n", rv);
 
     rv = NS_ShutdownXPCOM(nullptr);
     NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");
 
--- a/netwerk/test/TestMakeAbs.cpp
+++ b/netwerk/test/TestMakeAbs.cpp
@@ -52,18 +52,18 @@ main(int argc, char* argv[])
         rv = serv->NewURI(base, nullptr, getter_AddRefs(uri));
         if (NS_FAILED(rv)) return rv;
 
         char *absURLString;
         uint32_t i = 0;
         while (i++ < cycles) {
             rv = ServiceMakeAbsolute(uri, rel, &absURLString);
             if (NS_FAILED(rv)) return rv;
-            nsMemory::Free(absURLString);
+            free(absURLString);
 
             rv = URLMakeAbsolute(uri, rel, &absURLString);
-            nsMemory::Free(absURLString);
+            free(absURLString);
         }
     } // this scopes the nsCOMPtrs
     // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
     NS_ShutdownXPCOM(nullptr);
     return rv;
 }
--- a/parser/html/nsHtml5TreeOperation.cpp
+++ b/parser/html/nsHtml5TreeOperation.cpp
@@ -103,17 +103,17 @@ nsHtml5TreeOperation::~nsHtml5TreeOperat
     case eTreeOpAddViewSourceBase:
       delete[] mTwo.unicharPtr;
       break;
     case eTreeOpSetDocumentCharset:
     case eTreeOpNeedsCharsetSwitchTo:
       delete[] mOne.charPtr;
       break;
     case eTreeOpProcessOfflineManifest:
-      nsMemory::Free(mOne.unicharPtr);
+      free(mOne.unicharPtr);
       break;
     default: // keep the compiler happy
       break;
   }
 }
 
 nsresult
 nsHtml5TreeOperation::AppendTextToTextNode(const char16_t* aBuffer,
--- a/security/manager/pki/src/nsNSSDialogs.cpp
+++ b/security/manager/pki/src/nsNSSDialogs.cpp
@@ -328,17 +328,17 @@ nsNSSDialogs::SetPKCS12FilePassword(nsII
   if (NS_FAILED(rv)) return rv;
   *_retval = (status == 0) ? false : true;
   if (*_retval) {
     // retrieve the password
     char16_t *pw;
     rv = block->GetString(2, &pw);
     if (NS_SUCCEEDED(rv)) {
       _password = pw;
-      nsMemory::Free(pw);
+      free(pw);
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP
 nsNSSDialogs::GetPKCS12FilePassword(nsIInterfaceRequestor* ctx,
                                     nsAString& _password,
@@ -366,17 +366,17 @@ nsNSSDialogs::GetPKCS12FilePassword(nsII
   rv = promptSvc->PromptPassword(parent, nullptr, msg.get(), &pwTemp, nullptr,
                                  &ignored, _retval);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   if (*_retval) {
     _password.Assign(pwTemp);
-    nsMemory::Free(pwTemp);
+    free(pwTemp);
   }
 
   return NS_OK;
 }
 
 /* void viewCert (in nsIX509Cert cert); */
 NS_IMETHODIMP 
 nsNSSDialogs::ViewCert(nsIInterfaceRequestor *ctx, 
--- a/security/manager/ssl/src/PSMContentListener.cpp
+++ b/security/manager/ssl/src/PSMContentListener.cpp
@@ -58,17 +58,17 @@ PSMContentDownloader::PSMContentDownload
   : mByteData(nullptr),
     mType(type)
 {
 }
 
 PSMContentDownloader::~PSMContentDownloader()
 {
   if (mByteData)
-    nsMemory::Free(mByteData);
+    free(mByteData);
 }
 
 NS_IMPL_ISUPPORTS(PSMContentDownloader, nsIStreamListener, nsIRequestObserver)
 
 const int32_t kDefaultCertAllocLength = 2048;
 
 NS_IMETHODIMP
 PSMContentDownloader::OnStartRequest(nsIRequest* request, nsISupports* context)
@@ -85,17 +85,17 @@ PSMContentDownloader::OnStartRequest(nsI
   rv = channel->GetContentLength(&contentLength);
   if (NS_FAILED(rv) || contentLength <= 0)
     contentLength = kDefaultCertAllocLength;
   if (contentLength > INT32_MAX)
     return NS_ERROR_OUT_OF_MEMORY;
   
   mBufferOffset = 0;
   mBufferSize = 0;
-  mByteData = (char*)nsMemory::Alloc(AssertedCast<size_t>(contentLength));
+  mByteData = (char*)moz_xmalloc(AssertedCast<size_t>(contentLength));
   if (!mByteData)
     return NS_ERROR_OUT_OF_MEMORY;
   
   mBufferSize = int32_t(contentLength);
   return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -109,17 +109,17 @@ PSMContentDownloader::OnDataAvailable(ns
     return NS_ERROR_OUT_OF_MEMORY;
   
   uint32_t amt;
   nsresult err;
   //Do a check to see if we need to allocate more memory.
   if ((mBufferOffset + (int32_t)aLength) > mBufferSize) {
       size_t newSize = (mBufferOffset + aLength) *2; // grow some more than needed
       char *newBuffer;
-      newBuffer = (char*)nsMemory::Realloc(mByteData, newSize);
+      newBuffer = (char*)moz_xrealloc(mByteData, newSize);
       if (!newBuffer) {
         return NS_ERROR_OUT_OF_MEMORY;
       }
       mByteData = newBuffer;
       mBufferSize = newSize;
   }
   
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CertDownloader::OnDataAvailable\n"));
--- a/security/manager/ssl/src/TransportSecurityInfo.cpp
+++ b/security/manager/ssl/src/TransportSecurityInfo.cpp
@@ -464,17 +464,17 @@ TransportSecurityInfo::GetClassDescripti
 {
   *aClassDescription = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TransportSecurityInfo::GetClassID(nsCID * *aClassID)
 {
-  *aClassID = (nsCID*) nsMemory::Alloc(sizeof(nsCID));
+  *aClassID = (nsCID*) moz_xmalloc(sizeof(nsCID));
   if (!*aClassID)
     return NS_ERROR_OUT_OF_MEMORY;
   return GetClassIDNoAlloc(*aClassID);
 }
 
 NS_IMETHODIMP
 TransportSecurityInfo::GetFlags(uint32_t *aFlags)
 {
--- a/security/manager/ssl/src/nsCertPicker.cpp
+++ b/security/manager/ssl/src/nsCertPicker.cpp
@@ -66,22 +66,22 @@ NS_IMETHODIMP nsCertPicker::PickByUsage(
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   ScopedCERTCertNicknames nicknames(getNSSCertNicknamesFromCertList(certList.get()));
   if (!nicknames) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
-  certNicknameList = (char16_t **)nsMemory::Alloc(sizeof(char16_t *) * nicknames->numnicknames);
-  certDetailsList = (char16_t **)nsMemory::Alloc(sizeof(char16_t *) * nicknames->numnicknames);
+  certNicknameList = (char16_t **)moz_xmalloc(sizeof(char16_t *) * nicknames->numnicknames);
+  certDetailsList = (char16_t **)moz_xmalloc(sizeof(char16_t *) * nicknames->numnicknames);
 
   if (!certNicknameList || !certDetailsList) {
-    nsMemory::Free(certNicknameList);
-    nsMemory::Free(certDetailsList);
+    free(certNicknameList);
+    free(certDetailsList);
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   int32_t CertsToUse;
 
   for (CertsToUse = 0, node = CERT_LIST_HEAD(certList.get());
        !CERT_LIST_END(node, certList.get()) &&
          CertsToUse < nicknames->numnicknames;
@@ -142,21 +142,21 @@ NS_IMETHODIMP nsCertPicker::PickByUsage(
       }
 
       NS_RELEASE(dialogs);
     }
   }
 
   int32_t i;
   for (i = 0; i < CertsToUse; ++i) {
-    nsMemory::Free(certNicknameList[i]);
-    nsMemory::Free(certDetailsList[i]);
+    free(certNicknameList[i]);
+    free(certDetailsList[i]);
   }
-  nsMemory::Free(certNicknameList);
-  nsMemory::Free(certDetailsList);
+  free(certNicknameList);
+  free(certDetailsList);
   
   if (!CertsToUse) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   if (NS_SUCCEEDED(rv) && !*canceled) {
     for (i = 0, node = CERT_LIST_HEAD(certList);
          !CERT_LIST_END(node, certList);
--- a/security/manager/ssl/src/nsKeygenHandler.cpp
+++ b/security/manager/ssl/src/nsKeygenHandler.cpp
@@ -384,17 +384,17 @@ GetSlotWithMechanism(uint32_t aMechanism
         // Gerenate a list of slots and ask the user to choose //
         tmpSlot = slotList->head;
         while (tmpSlot) {
             numSlots++;
             tmpSlot = tmpSlot->next;
         }
 
         // Allocate the slot name buffer //
-        tokenNameList = static_cast<char16_t**>(nsMemory::Alloc(sizeof(char16_t *) * numSlots));
+        tokenNameList = static_cast<char16_t**>(moz_xmalloc(sizeof(char16_t *) * numSlots));
         if (!tokenNameList) {
             rv = NS_ERROR_OUT_OF_MEMORY;
             goto loser;
         }
 
         i = 0;
         slotElement = PK11_GetFirstSafe(slotList);
         while (slotElement) {
@@ -756,20 +756,20 @@ loser:
     }
     if (slot) {
         PK11_FreeSlot(slot);
     }
     if (KeygenRunnable) {
         NS_RELEASE(KeygenRunnable);
     }
     if (keyparamsString) {
-        nsMemory::Free(keyparamsString);
+        free(keyparamsString);
     }
     if (pkac.challenge.data) {
-        nsMemory::Free(pkac.challenge.data);
+        free(pkac.challenge.data);
     }
     return rv;
 }
 
 // static
 void
 nsKeygenFormProcessor::ExtractParams(nsIDOMHTMLElement* aElement,
                                      nsAString& challengeValue,
--- a/security/manager/ssl/src/nsNSSASN1Object.cpp
+++ b/security/manager/ssl/src/nsNSSASN1Object.cpp
@@ -331,17 +331,17 @@ nsNSSASN1PrintableItem::nsNSSASN1Printab
 {
   /* member initializers and constructor code */
 }
 
 nsNSSASN1PrintableItem::~nsNSSASN1PrintableItem()
 {
   /* destructor code */
   if (mData)
-    nsMemory::Free(mData);
+    free(mData);
 }
 
 /* readonly attribute wstring value; */
 NS_IMETHODIMP 
 nsNSSASN1PrintableItem::GetDisplayValue(nsAString &aValue)
 {
   aValue = mValue;
   return NS_OK;
@@ -382,27 +382,27 @@ nsNSSASN1PrintableItem::SetType(uint32_t
   return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsNSSASN1PrintableItem::SetData(char *data, uint32_t len)
 {
   if (len > 0) {
     if (mLen < len) {
-      unsigned char* newData = (unsigned char*)nsMemory::Realloc(mData, len);
+      unsigned char* newData = (unsigned char*)moz_xrealloc(mData, len);
       if (!newData)
         return NS_ERROR_OUT_OF_MEMORY;
 
       mData = newData;
     }
 
     memcpy(mData, data, len);
   } else if (len == 0) {
     if (mData) {
-      nsMemory::Free(mData);
+      free(mData);
       mData = nullptr;
     }
   }
   mLen = len;
   return NS_OK;  
 }
 
 NS_IMETHODIMP
--- a/security/manager/ssl/src/nsNSSCallbacks.cpp
+++ b/security/manager/ssl/src/nsNSSCallbacks.cpp
@@ -830,17 +830,17 @@ void PK11PasswordPromptRunnable::RunOnTa
     return; 
 
   const char16_t* formatStrings[1] = { 
     ToNewUnicode(NS_ConvertUTF8toUTF16(PK11_GetTokenName(mSlot)))
   };
   rv = nssComponent->PIPBundleFormatStringFromName("CertPassPrompt",
                                       formatStrings, 1,
                                       promptString);
-  nsMemory::Free(const_cast<char16_t*>(formatStrings[0]));
+  free(const_cast<char16_t*>(formatStrings[0]));
 
   if (NS_FAILED(rv))
     return;
 
   {
     nsPSMUITracker tracker;
     if (tracker.isUIForbidden()) {
       rv = NS_ERROR_NOT_AVAILABLE;
--- a/security/manager/ssl/src/nsNSSCertHelper.cpp
+++ b/security/manager/ssl/src/nsNSSCertHelper.cpp
@@ -665,17 +665,17 @@ ProcessKeyUsageExtension(SECItem *extDat
     nssComponent->GetPIPNSSBundleString("CertDumpExtensionFailure", local);
     text.Append(local.get());
     return NS_OK;
   }
   unsigned char keyUsage = 0;
   if (decoded.len) {
     keyUsage = decoded.data[0];
   }
-  nsMemory::Free(decoded.data);  
+  free(decoded.data);
   if (keyUsage & KU_DIGITAL_SIGNATURE) {
     nssComponent->GetPIPNSSBundleString("CertDumpKUSign", local);
     text.Append(local.get());
     text.AppendLiteral(SEPARATOR);
   }
   if (keyUsage & KU_NON_REPUDIATION) {
     nssComponent->GetPIPNSSBundleString("CertDumpKUNonRep", local);
     text.Append(local.get());
@@ -896,17 +896,17 @@ ProcessIA5String(SECItem  *extData,
 {
   SECItem item;
   nsAutoString local;
   if (SECSuccess != SEC_ASN1DecodeItem(nullptr, &item, 
 				       SEC_ASN1_GET(SEC_IA5StringTemplate),
 				       extData))
     return NS_ERROR_FAILURE;
   local.AssignASCII((char*)item.data, item.len);
-  nsMemory::Free(item.data);
+  free(item.data);
   text.Append(local);
   return NS_OK;
 }
 
 static nsresult
 AppendBMPtoUTF16(PLArenaPool *arena,
 		 unsigned char* data, unsigned int len,
 		 nsAString& text)
@@ -1511,17 +1511,17 @@ ProcessMSCAVersion(SECItem  *extData,
 				       SEC_ASN1_GET(SEC_IntegerTemplate), 
 				       extData))
     /* This extension used to be an Integer when this code
        was written, but apparently isn't anymore. Display
        the raw bytes instead. */
     return ProcessRawBytes(nssComponent, extData, text);
 
   rv = GetIntValue(&decoded, &version);
-  nsMemory::Free(decoded.data);
+  free(decoded.data);
   if (NS_FAILED(rv))
     /* Value out of range, display raw bytes */
     return ProcessRawBytes(nssComponent, extData, text);
 
   /* Apparently, the encoding is <minor><major>, with 16 bits each */
   PR_snprintf(buf, sizeof(buf), "%d.%d", version & 0xFFFF, version>>16);
   text.AppendASCII(buf);
   return NS_OK;
--- a/security/manager/ssl/src/nsNSSCertificate.cpp
+++ b/security/manager/ssl/src/nsNSSCertificate.cpp
@@ -497,30 +497,30 @@ nsNSSCertificate::GetDbKey(char** aDbKey
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   SECItem key;
 
   NS_ENSURE_ARG(aDbKey);
   *aDbKey = nullptr;
   key.len = NS_NSS_LONG*4+mCert->serialNumber.len+mCert->derIssuer.len;
-  key.data = (unsigned char*) nsMemory::Alloc(key.len);
+  key.data = (unsigned char*) moz_xmalloc(key.len);
   if (!key.data)
     return NS_ERROR_OUT_OF_MEMORY;
   NS_NSS_PUT_LONG(0,key.data); // later put moduleID
   NS_NSS_PUT_LONG(0,&key.data[NS_NSS_LONG]); // later put slotID
   NS_NSS_PUT_LONG(mCert->serialNumber.len,&key.data[NS_NSS_LONG*2]);
   NS_NSS_PUT_LONG(mCert->derIssuer.len,&key.data[NS_NSS_LONG*3]);
   memcpy(&key.data[NS_NSS_LONG*4], mCert->serialNumber.data,
          mCert->serialNumber.len);
   memcpy(&key.data[NS_NSS_LONG*4+mCert->serialNumber.len],
          mCert->derIssuer.data, mCert->derIssuer.len);
 
   *aDbKey = NSSBase64_EncodeItem(nullptr, nullptr, 0, &key);
-  nsMemory::Free(key.data); // SECItem is a 'c' type without a destrutor
+  free(key.data); // SECItem is a 'c' type without a destructor
   return (*aDbKey) ? NS_OK : NS_ERROR_FAILURE;
 }
 
 NS_IMETHODIMP
 nsNSSCertificate::GetWindowTitle(nsAString& aWindowTitle)
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown()) {
@@ -617,17 +617,17 @@ nsNSSCertificate::GetEmailAddresses(uint
        ;
        aAddr
        ;
        aAddr = CERT_GetNextEmailAddress(mCert.get(), aAddr))
   {
     ++(*aLength);
   }
 
-  *aAddresses = (char16_t**) nsMemory::Alloc(sizeof(char16_t*) * (*aLength));
+  *aAddresses = (char16_t**) moz_xmalloc(sizeof(char16_t*) * (*aLength));
   if (!*aAddresses)
     return NS_ERROR_OUT_OF_MEMORY;
 
   uint32_t iAddr;
   for (aAddr = CERT_GetFirstEmailAddress(mCert.get()), iAddr = 0
        ;
        aAddr
        ;
@@ -934,17 +934,17 @@ nsNSSCertificate::GetAllTokenNames(uint3
 
   // read the token names from slots
   PK11SlotListElement* le;
 
   for (le = slots->head; le; le = le->next) {
     ++(*aLength);
   }
 
-  *aTokenNames = (char16_t**) nsMemory::Alloc(sizeof(char16_t*) * (*aLength));
+  *aTokenNames = (char16_t**) moz_xmalloc(sizeof(char16_t*) * (*aLength));
   if (!*aTokenNames) {
     *aLength = 0;
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   uint32_t iToken;
   for (le = slots->head, iToken = 0; le; le = le->next, ++iToken) {
     char* token = PK11_GetTokenName(le->slot);
@@ -1109,17 +1109,17 @@ nsNSSCertificate::GetSha256SubjectPublic
 NS_IMETHODIMP
 nsNSSCertificate::GetRawDER(uint32_t* aLength, uint8_t** aArray)
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   if (mCert) {
-    *aArray = (uint8_t*)nsMemory::Alloc(mCert->derCert.len);
+    *aArray = (uint8_t*)moz_xmalloc(mCert->derCert.len);
     if (*aArray) {
       memcpy(*aArray, mCert->derCert.data, mCert->derCert.len);
       *aLength = mCert->derCert.len;
       return NS_OK;
     }
   }
   *aLength = 0;
   return NS_ERROR_FAILURE;
@@ -1235,17 +1235,17 @@ nsNSSCertificate::ExportAsCMS(uint32_t c
   }
 
   if (NSS_CMSEncoder_Finish(ecx) != SECSuccess) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
            ("nsNSSCertificate::ExportAsCMS - failed to add encoded data\n"));
     return NS_ERROR_FAILURE;
   }
 
-  *aArray = (uint8_t*)nsMemory::Alloc(certP7.len);
+  *aArray = (uint8_t*)moz_xmalloc(certP7.len);
   if (!*aArray)
     return NS_ERROR_OUT_OF_MEMORY;
 
   memcpy(*aArray, certP7.data, certP7.len);
   *aLength = certP7.len;
   return NS_OK;
 }
 
@@ -1289,26 +1289,26 @@ nsNSSCertificate::GetUsagesArray(bool lo
   char16_t* tmpUsages[max_usages];
   const char* suffix = "";
   uint32_t tmpCount;
   nsUsageArrayHelper uah(mCert.get());
   rv = uah.GetUsagesArray(suffix, localOnly, max_usages, _verified, &tmpCount,
                           tmpUsages);
   NS_ENSURE_SUCCESS(rv,rv);
   if (tmpCount > 0) {
-    *_usages = (char16_t**) nsMemory::Alloc(sizeof(char16_t*) * tmpCount);
+    *_usages = (char16_t**) moz_xmalloc(sizeof(char16_t*) * tmpCount);
     if (!*_usages)
       return NS_ERROR_OUT_OF_MEMORY;
     for (uint32_t i=0; i<tmpCount; i++) {
       (*_usages)[i] = tmpUsages[i];
     }
     *_count = tmpCount;
     return NS_OK;
   }
-  *_usages = (char16_t**) nsMemory::Alloc(sizeof(char16_t*));
+  *_usages = (char16_t**) moz_xmalloc(sizeof(char16_t*));
   if (!*_usages)
     return NS_ERROR_OUT_OF_MEMORY;
   *_count = 0;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNSSCertificate::RequestUsagesArrayAsync(
@@ -1348,17 +1348,17 @@ nsNSSCertificate::GetUsagesString(bool l
   nsUsageArrayHelper uah(mCert.get());
   rv = uah.GetUsagesArray(suffix, localOnly, max_usages, _verified, &tmpCount,
                           tmpUsages);
   NS_ENSURE_SUCCESS(rv,rv);
   _usages.Truncate();
   for (uint32_t i=0; i<tmpCount; i++) {
     if (i>0) _usages.Append(',');
     _usages.Append(tmpUsages[i]);
-    nsMemory::Free(tmpUsages[i]);
+    free(tmpUsages[i]);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNSSCertificate::GetASN1Structure(nsIASN1Object** aASN1Structure)
 {
   NS_ENSURE_ARG_POINTER(aASN1Structure);
@@ -1938,17 +1938,17 @@ nsNSSCertificate::GetClassDescription(ch
 {
   *aClassDescription = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNSSCertificate::GetClassID(nsCID** aClassID)
 {
-  *aClassID = (nsCID*) nsMemory::Alloc(sizeof(nsCID));
+  *aClassID = (nsCID*) moz_xmalloc(sizeof(nsCID));
   if (!*aClassID)
     return NS_ERROR_OUT_OF_MEMORY;
   return GetClassIDNoAlloc(*aClassID);
 }
 
 NS_IMETHODIMP
 nsNSSCertificate::GetFlags(uint32_t* aFlags)
 {
--- a/security/manager/ssl/src/nsNSSCertificateDB.cpp
+++ b/security/manager/ssl/src/nsNSSCertificateDB.cpp
@@ -350,17 +350,17 @@ nsNSSCertificateDB::handleCACertDownload
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Creating temp cert\n"));
   CERTCertDBHandle *certdb = CERT_GetDefaultCertDB();
   ScopedCERTCertificate tmpCert(CERT_FindCertByDERCert(certdb, &der));
   if (!tmpCert) {
     tmpCert = CERT_NewTempCertificate(certdb, &der,
                                       nullptr, false, true);
   }
-  nsMemory::Free(der.data);
+  free(der.data);
   der.data = nullptr;
   der.len = 0;
   
   if (!tmpCert) {
     NS_ERROR("Couldn't create cert from DER blob");
     return NS_ERROR_FAILURE;
   }
 
@@ -419,17 +419,17 @@ nsNSSCertificateDB::handleCACertDownload
     }
 
     certToShow = do_QueryElementAt(x509Certs, i);
     certToShow->GetRawDER(&der.len, (uint8_t **)&der.data);
 
     CERTCertificate *tmpCert2 = 
       CERT_NewTempCertificate(certdb, &der, nullptr, false, true);
 
-    nsMemory::Free(der.data);
+    free(der.data);
     der.data = nullptr;
     der.len = 0;
 
     if (!tmpCert2) {
       NS_ERROR("Couldn't create temp cert from DER blob");
       continue;  // Let's try to import the rest of 'em
     }
     
@@ -1228,17 +1228,17 @@ nsNSSCertificateDB::getCertNames(CERTCer
        !CERT_LIST_END(node, certList);
        node = CERT_LIST_NEXT(node)) {
     if (getCertType(node->cert) == type) {
       numcerts++;
     }
   }
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("num certs: %d\n", numcerts));
   int nc = (numcerts == 0) ? 1 : numcerts;
-  tmpArray = (char16_t **)nsMemory::Alloc(sizeof(char16_t *) * nc);
+  tmpArray = (char16_t **)moz_xmalloc(sizeof(char16_t *) * nc);
   if (numcerts == 0) goto finish;
   for (node = CERT_LIST_HEAD(certList);
        !CERT_LIST_END(node, certList);
        node = CERT_LIST_NEXT(node)) {
     if (getCertType(node->cert) == type) {
       RefPtr<nsNSSCertificate> pipCert(new nsNSSCertificate(node->cert));
       char *dbkey = nullptr;
       char *namestr = nullptr;
@@ -1615,17 +1615,17 @@ NS_IMETHODIMP nsNSSCertificateDB::AddCer
   NS_ENSURE_SUCCESS(rv, rv);
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Creating temp cert\n"));
   CERTCertDBHandle *certdb = CERT_GetDefaultCertDB();
   ScopedCERTCertificate tmpCert(CERT_FindCertByDERCert(certdb, &der));
   if (!tmpCert)
     tmpCert = CERT_NewTempCertificate(certdb, &der,
                                       nullptr, false, true);
-  nsMemory::Free(der.data);
+  free(der.data);
   der.data = nullptr;
   der.len = 0;
 
   if (!tmpCert) {
     NS_ERROR("Couldn't create cert from DER blob");
     return MapSECStatus(SECFailure);
   }
 
--- a/security/manager/ssl/src/nsNSSCertificateFakeTransport.cpp
+++ b/security/manager/ssl/src/nsNSSCertificateFakeTransport.cpp
@@ -307,17 +307,17 @@ nsNSSCertificateFakeTransport::GetClassD
 {
   *aClassDescription = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNSSCertificateFakeTransport::GetClassID(nsCID** aClassID)
 {
-  *aClassID = (nsCID*) nsMemory::Alloc(sizeof(nsCID));
+  *aClassID = (nsCID*) moz_xmalloc(sizeof(nsCID));
   if (!*aClassID)
     return NS_ERROR_OUT_OF_MEMORY;
   return GetClassIDNoAlloc(*aClassID);
 }
 
 NS_IMETHODIMP
 nsNSSCertificateFakeTransport::GetFlags(uint32_t* aFlags)
 {
--- a/security/manager/ssl/src/nsNSSIOLayer.cpp
+++ b/security/manager/ssl/src/nsNSSIOLayer.cpp
@@ -1966,17 +1966,17 @@ nsGetUserCertChoice(SSM_UserCertChoice* 
   } else {
     // Most likely we see a nickname from a migrated cert.
     // We do not currently support that, ask the user which cert to use.
     *certChoice = ASK;
   }
 
 loser:
   if (mode) {
-    nsMemory::Free(mode);
+    free(mode);
   }
   return ret;
 }
 
 static bool
 hasExplicitKeyUsageNonRepudiation(CERTCertificate* cert)
 {
   // There is no extension, v1 or v2 certificate
@@ -2337,23 +2337,23 @@ ClientAuthDataRunnable::RunOnTargetThrea
       NS_ConvertUTF8toUTF16 org(corg);
       if (corg) PORT_Free(corg);
 
       char* cissuer = CERT_GetOrgName(&mServerCert->issuer);
       NS_ConvertUTF8toUTF16 issuer(cissuer);
       if (cissuer) PORT_Free(cissuer);
 
       certNicknameList =
-        (char16_t**)nsMemory::Alloc(sizeof(char16_t*)* nicknames->numnicknames);
+        (char16_t**)moz_xmalloc(sizeof(char16_t*)* nicknames->numnicknames);
       if (!certNicknameList)
         goto loser;
       certDetailsList =
-        (char16_t**)nsMemory::Alloc(sizeof(char16_t*)* nicknames->numnicknames);
+        (char16_t**)moz_xmalloc(sizeof(char16_t*)* nicknames->numnicknames);
       if (!certDetailsList) {
-        nsMemory::Free(certNicknameList);
+        free(certNicknameList);
         goto loser;
       }
 
       int32_t CertsToUse;
       for (CertsToUse = 0, node = CERT_LIST_HEAD(certList);
         !CERT_LIST_END(node, certList) && CertsToUse < nicknames->numnicknames;
         node = CERT_LIST_NEXT(node)
         ) {
@@ -2368,17 +2368,17 @@ ClientAuthDataRunnable::RunOnTargetThrea
         if (NS_FAILED(tempCert->FormatUIStrings(i_nickname, nickWithSerial, details)))
           continue;
 
         certNicknameList[CertsToUse] = ToNewUnicode(nickWithSerial);
         if (!certNicknameList[CertsToUse])
           continue;
         certDetailsList[CertsToUse] = ToNewUnicode(details);
         if (!certDetailsList[CertsToUse]) {
-          nsMemory::Free(certNicknameList[CertsToUse]);
+          free(certNicknameList[CertsToUse]);
           continue;
         }
 
         ++CertsToUse;
       }
 
       // Throw up the client auth dialog and get back the index of the selected cert
       nsresult rv = getNSSDialogs((void**)&dialogs,
--- a/security/manager/ssl/src/nsNTLMAuthModule.cpp
+++ b/security/manager/ssl/src/nsNTLMAuthModule.cpp
@@ -404,17 +404,17 @@ LM_Response(const uint8_t *hash, const u
 
 static nsresult
 GenerateType1Msg(void **outBuf, uint32_t *outLen)
 {
   //
   // verify that bufLen is sufficient
   //
   *outLen = NTLM_TYPE1_HEADER_LEN;
-  *outBuf = nsMemory::Alloc(*outLen);
+  *outBuf = moz_xmalloc(*outLen);
   if (!*outBuf)
     return NS_ERROR_OUT_OF_MEMORY;
 
   //
   // write out type 1 msg
   //
   void *cursor = *outBuf;
 
@@ -872,17 +872,17 @@ GenerateType3Msg(const nsString &domain,
   totalLen += domainLen;
   totalLen += userLen;
   totalLen += ntlmRespLen.value();
 
   if (!totalLen.isValid()) {
     NS_ERROR("failed preparing to allocate NTLM response: integer overflow?!?");
     return NS_ERROR_FAILURE;
   }
-  *outBuf = nsMemory::Alloc(totalLen.value());
+  *outBuf = moz_xmalloc(totalLen.value());
   *outLen = totalLen.value();
   if (!*outBuf) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   //
   // finally, we assemble the Type-3 msg :-)
   //
--- a/security/manager/ssl/src/nsPKCS11Slot.cpp
+++ b/security/manager/ssl/src/nsPKCS11Slot.cpp
@@ -315,21 +315,21 @@ nsPKCS11Module::FindSlotByName(const cha
   if (!slotinfo) {
     // workaround - the builtin module has no name
     if (!asciiname) {
       return NS_ERROR_FAILURE;
     } else if (nsCRT::strcmp(asciiname, "Root Certificates") == 0) {
       slotinfo = PK11_ReferenceSlot(mModule->slots[0]);
     } else {
       // give up
-      nsMemory::Free(asciiname);
+      free(asciiname);
       return NS_ERROR_FAILURE;
     }
   } 
-  nsMemory::Free(asciiname);
+  free(asciiname);
   nsCOMPtr<nsIPKCS11Slot> slot = new nsPKCS11Slot(slotinfo);
   PK11_FreeSlot(slotinfo);
   *_retval = slot;
   NS_ADDREF(*_retval);
   return NS_OK;
 }
 
 /* nsIEnumerator listSlots (); */
--- a/security/manager/ssl/src/nsSDR.cpp
+++ b/security/manager/ssl/src/nsSDR.cpp
@@ -173,17 +173,17 @@ DecryptString(const char *crypt, char **
 
   rv = decode(crypt, &decoded, &decodedLen);
   if (rv != NS_OK) goto loser;
 
   rv = Decrypt(decoded, decodedLen, &decrypted, &decryptedLen);
   if (rv != NS_OK) goto loser;
 
   // Convert to NUL-terminated string
-  r = (char *)nsMemory::Alloc(decryptedLen+1);
+  r = (char *)moz_xmalloc(decryptedLen+1);
   if (!r) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; }
 
   memcpy(r, decrypted, decryptedLen);
   r[decryptedLen] = 0;
 
   *_retval = r;
   r = 0;
 
--- a/security/manager/ssl/src/nsSSLStatus.cpp
+++ b/security/manager/ssl/src/nsSSLStatus.cpp
@@ -231,17 +231,17 @@ nsSSLStatus::GetClassDescription(char** 
 {
   *aClassDescription = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSSLStatus::GetClassID(nsCID** aClassID)
 {
-  *aClassID = (nsCID*) nsMemory::Alloc(sizeof(nsCID));
+  *aClassID = (nsCID*) moz_xmalloc(sizeof(nsCID));
   if (!*aClassID) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   return GetClassIDNoAlloc(*aClassID);
 }
 
 NS_IMETHODIMP
 nsSSLStatus::GetFlags(uint32_t* aFlags)
--- a/toolkit/components/downloads/ApplicationReputation.cpp
+++ b/toolkit/components/downloads/ApplicationReputation.cpp
@@ -774,17 +774,17 @@ PendingLookup::ParseCertificates(nsIArra
 
       uint8_t* data = nullptr;
       uint32_t len = 0;
       rv = cert->GetRawDER(&len, &data);
       NS_ENSURE_SUCCESS(rv, rv);
 
       // Add this certificate to the protobuf to send remotely.
       certChain->add_element()->set_certificate(data, len);
-      nsMemory::Free(data);
+      free(data);
 
       rv = chainElt->HasMoreElements(&hasMoreCerts);
       NS_ENSURE_SUCCESS(rv, rv);
     }
     rv = chains->HasMoreElements(&hasMoreChains);
     NS_ENSURE_SUCCESS(rv, rv);
   }
   if (mRequest.signature().certificate_chain_size() > 0) {
--- a/toolkit/components/places/nsAnnotationService.cpp
+++ b/toolkit/components/places/nsAnnotationService.cpp
@@ -967,17 +967,17 @@ nsAnnotationService::GetPagesWithAnnotat
   nsresult rv = GetPagesWithAnnotationCOMArray(aName, &results);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Convert to raw array.
   if (results.Count() == 0)
     return NS_OK;
 
   *_results = static_cast<nsIURI**>
-                         (nsMemory::Alloc(results.Count() * sizeof(nsIURI*)));
+                         (moz_xmalloc(results.Count() * sizeof(nsIURI*)));
   NS_ENSURE_TRUE(*_results, NS_ERROR_OUT_OF_MEMORY);
 
   *_resultCount = results.Count();
   for (uint32_t i = 0; i < *_resultCount; i ++) {
     (*_results)[i] = results[i];
     NS_ADDREF((*_results)[i]);
   }
 
@@ -1040,17 +1040,17 @@ nsAnnotationService::GetItemsWithAnnotat
   nsresult rv = GetItemsWithAnnotationTArray(aName, &results);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Convert to raw array.
   if (results.Length() == 0)
     return NS_OK;
 
   *_results = static_cast<int64_t*>
-                         (nsMemory::Alloc(results.Length() * sizeof(int64_t)));
+                         (moz_xmalloc(results.Length() * sizeof(int64_t)));
   NS_ENSURE_TRUE(*_results, NS_ERROR_OUT_OF_MEMORY);
 
   *_resultCount = results.Length();
   for (uint32_t i = 0; i < *_resultCount; i ++) {
     (*_results)[i] = results[i];
   }
 
   return NS_OK;
@@ -1145,17 +1145,17 @@ nsAnnotationService::GetAnnotationsWithN
     NS_ENSURE_TRUE(annotations.AppendObject(anno), NS_ERROR_OUT_OF_MEMORY);
   }
 
   // Convert to raw array.
   if (annotations.Count() == 0)
     return NS_OK;
 
   *_annotations = static_cast<mozIAnnotatedResult**>
-    (nsMemory::Alloc(annotations.Count() * sizeof(mozIAnnotatedResult*)));
+    (moz_xmalloc(annotations.Count() * sizeof(mozIAnnotatedResult*)));
   NS_ENSURE_TRUE(*_annotations, NS_ERROR_OUT_OF_MEMORY);
 
   *_count = annotations.Count();
   for (uint32_t i = 0; i < *_count; ++i) {
     NS_ADDREF((*_annotations)[i] = annotations[i]);
   }
 
   return NS_OK;
@@ -1204,26 +1204,26 @@ nsAnnotationService::GetPageAnnotationNa
   nsTArray<nsCString> names;
   nsresult rv = GetAnnotationNamesTArray(aURI, 0, &names);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (names.Length() == 0)
     return NS_OK;
 
   *_result = static_cast<nsIVariant**>
-                        (nsMemory::Alloc(sizeof(nsIVariant*) * names.Length()));
+                        (moz_xmalloc(sizeof(nsIVariant*) * names.Length()));
   NS_ENSURE_TRUE(*_result, NS_ERROR_OUT_OF_MEMORY);
 
   for (uint32_t i = 0; i < names.Length(); i ++) {
     nsCOMPtr<nsIWritableVariant> var = new nsVariant();
     if (!var) {
       // need to release all the variants we've already created
       for (uint32_t j = 0; j < i; j ++)
         NS_RELEASE((*_result)[j]);
-      nsMemory::Free(*_result);
+      free(*_result);
       *_result = nullptr;
       return NS_ERROR_OUT_OF_MEMORY;
     }
     var->SetAsAUTF8String(names[i]);
     NS_ADDREF((*_result)[i] = var);
   }
   *_count = names.Length();
 
@@ -1296,26 +1296,26 @@ nsAnnotationService::GetItemAnnotationNa
   nsTArray<nsCString> names;
   nsresult rv = GetAnnotationNamesTArray(nullptr, aItemId, &names);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (names.Length() == 0)
     return NS_OK;
 
   *_result = static_cast<nsIVariant**>
-                        (nsMemory::Alloc(sizeof(nsIVariant*) * names.Length()));
+                        (moz_xmalloc(sizeof(nsIVariant*) * names.Length()));
   NS_ENSURE_TRUE(*_result, NS_ERROR_OUT_OF_MEMORY);
 
   for (uint32_t i = 0; i < names.Length(); i ++) {
     nsCOMPtr<nsIWritableVariant> var = new nsVariant();
     if (!var) {
       // need to release all the variants we've already created
       for (uint32_t j = 0; j < i; j ++)
         NS_RELEASE((*_result)[j]);
-      nsMemory::Free(*_result);
+      free(*_result);
       *_result = nullptr;
       return NS_ERROR_OUT_OF_MEMORY;
     }
     var->SetAsAUTF8String(names[i]);
     NS_ADDREF((*_result)[i] = var);
   }
   *_count = names.Length();
 
--- a/toolkit/components/places/nsFaviconService.cpp
+++ b/toolkit/components/places/nsFaviconService.cpp
@@ -351,36 +351,36 @@ nsFaviconService::ReplaceFaviconDataFrom
   rv = stream->Available(&available64);
   NS_ENSURE_SUCCESS(rv, rv);
   if (available64 == 0 || available64 > UINT32_MAX / sizeof(uint8_t))
     return NS_ERROR_FILE_TOO_BIG;
   uint32_t available = (uint32_t)available64;
 
   // Read all the decoded data.
   uint8_t* buffer = static_cast<uint8_t*>
-                               (nsMemory::Alloc(sizeof(uint8_t) * available));
+                               (moz_xmalloc(sizeof(uint8_t) * available));
   if (!buffer)
     return NS_ERROR_OUT_OF_MEMORY;
   uint32_t numRead;
   rv = stream->Read(TO_CHARBUFFER(buffer), available, &numRead);
   if (NS_FAILED(rv) || numRead != available) {
-    nsMemory::Free(buffer);
+    free(buffer);
     return rv;
   }
 
   nsAutoCString mimeType;
   rv = channel->GetContentType(mimeType);
   if (NS_FAILED(rv)) {
-    nsMemory::Free(buffer);
+    free(buffer);
     return rv;
   }
 
   // ReplaceFaviconData can now do the dirty work.
   rv = ReplaceFaviconData(aFaviconURI, buffer, available, mimeType, aExpiration);
-  nsMemory::Free(buffer);
+  free(buffer);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsFaviconService::GetFaviconURLForPage(nsIURI *aPageURI,
                                        nsIFaviconDataCallback* aCallback)
--- a/toolkit/components/places/nsNavBookmarks.cpp
+++ b/toolkit/components/places/nsNavBookmarks.cpp
@@ -2143,17 +2143,17 @@ nsNavBookmarks::GetBookmarkIdsForURI(nsI
   // Get the information from the DB as a TArray
   // TODO (bug 653816): make this API skip tags by default.
   nsresult rv = GetBookmarkIdsForURITArray(aURI, bookmarks, false);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Copy the results into a new array for output
   if (bookmarks.Length()) {
     *aBookmarks =
-      static_cast<int64_t*>(nsMemory::Alloc(sizeof(int64_t) * bookmarks.Length()));
+      static_cast<int64_t*>(moz_xmalloc(sizeof(int64_t) * bookmarks.Length()));
     if (!*aBookmarks)
       return NS_ERROR_OUT_OF_MEMORY;
     for (uint32_t i = 0; i < bookmarks.Length(); i ++)
       (*aBookmarks)[i] = bookmarks[i];
   }
 
   *aCount = bookmarks.Length();
   return NS_OK;
@@ -2538,17 +2538,17 @@ nsNavBookmarks::GetObservers(uint32_t* _
     if (observer)
       observers.AppendElement(observer);
   }
 
   if (observers.Count() == 0)
     return NS_OK;
 
   *_observers = static_cast<nsINavBookmarkObserver**>
-    (nsMemory::Alloc(observers.Count() * sizeof(nsINavBookmarkObserver*)));
+    (moz_xmalloc(observers.Count() * sizeof(nsINavBookmarkObserver*)));
   NS_ENSURE_TRUE(*_observers, NS_ERROR_OUT_OF_MEMORY);
 
   *_count = observers.Count();
   for (uint32_t i = 0; i < *_count; ++i) {
     NS_ADDREF((*_observers)[i] = observers[i]);
   }
 
   return NS_OK;
--- a/toolkit/components/places/nsNavHistory.cpp
+++ b/toolkit/components/places/nsNavHistory.cpp
@@ -2285,17 +2285,17 @@ nsNavHistory::GetObservers(uint32_t* _co
     if (observer)
       observers.AppendElement(observer);
   }
 
   if (observers.Count() == 0)
     return NS_OK;
 
   *_observers = static_cast<nsINavHistoryObserver**>
-    (nsMemory::Alloc(observers.Count() * sizeof(nsINavHistoryObserver*)));
+    (moz_xmalloc(observers.Count() * sizeof(nsINavHistoryObserver*)));
   NS_ENSURE_TRUE(*_observers, NS_ERROR_OUT_OF_MEMORY);
 
   *_count = observers.Count();
   for (uint32_t i = 0; i < *_count; ++i) {
     NS_ADDREF((*_observers)[i] = observers[i]);
   }
 
   return NS_OK;
--- a/toolkit/components/places/nsNavHistoryQuery.cpp
+++ b/toolkit/components/places/nsNavHistoryQuery.cpp
@@ -270,17 +270,17 @@ nsNavHistory::QueryStringToQueries(const
   nsresult rv = QueryStringToQueryArray(aQueryString, &queries,
                                         getter_AddRefs(options));
   NS_ENSURE_SUCCESS(rv, rv);
 
   *aResultCount = queries.Count();
   if (queries.Count() > 0) {
     // convert COM array to raw
     *aQueries = static_cast<nsINavHistoryQuery**>
-                           (nsMemory::Alloc(sizeof(nsINavHistoryQuery*) * queries.Count()));
+                           (moz_xmalloc(sizeof(nsINavHistoryQuery*) * queries.Count()));
     NS_ENSURE_TRUE(*aQueries, NS_ERROR_OUT_OF_MEMORY);
     for (int32_t i = 0; i < queries.Count(); i ++) {
       (*aQueries)[i] = queries[i];
       NS_ADDREF((*aQueries)[i]);
     }
   }
   NS_ADDREF(*aOptions = options);
   return NS_OK;
@@ -466,17 +466,17 @@ nsNavHistory::QueriesToQueryString(nsINa
     uint32_t folderCount = 0;
     query->GetFolders(&folderCount, &folders);
     for (uint32_t i = 0; i < folderCount; ++i) {
       AppendAmpersandIfNonempty(queryString);
       queryString += NS_LITERAL_CSTRING(QUERYKEY_FOLDER "=");
       nsresult rv = PlacesFolderConversion::AppendFolder(queryString, folders[i]);
       NS_ENSURE_SUCCESS(rv, rv);
     }
-    nsMemory::Free(folders);
+    free(folders);
 
     // tags
     const nsTArray<nsString> &tags = query->Tags();
     for (uint32_t i = 0; i < tags.Length(); ++i) {
       nsAutoCString escapedTag;
       if (!NS_Escape(NS_ConvertUTF16toUTF8(tags[i]), escapedTag, url_XAlphas))
         return NS_ERROR_OUT_OF_MEMORY;
 
@@ -1269,17 +1269,17 @@ NS_IMETHODIMP nsNavHistoryQuery::SetTags
 
 NS_IMETHODIMP nsNavHistoryQuery::GetFolders(uint32_t *aCount,
                                             int64_t **aFolders)
 {
   uint32_t count = mFolders.Length();
   int64_t *folders = nullptr;
   if (count > 0) {
     folders = static_cast<int64_t*>
-                         (nsMemory::Alloc(count * sizeof(int64_t)));
+                         (moz_xmalloc(count * sizeof(int64_t)));
     NS_ENSURE_TRUE(folders, NS_ERROR_OUT_OF_MEMORY);
 
     for (uint32_t i = 0; i < count; ++i) {
       folders[i] = mFolders[i];
     }
   }
   *aCount = count;
   *aFolders = folders;
--- a/toolkit/components/places/nsNavHistoryResult.cpp
+++ b/toolkit/components/places/nsNavHistoryResult.cpp
@@ -2008,17 +2008,17 @@ NS_IMETHODIMP
 nsNavHistoryQueryResultNode::GetQueries(uint32_t* queryCount,
                                         nsINavHistoryQuery*** queries)
 {
   nsresult rv = VerifyQueriesParsed();
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ASSERTION(mQueries.Count() > 0, "Must have >= 1 query");
 
   *queries = static_cast<nsINavHistoryQuery**>
-                        (nsMemory::Alloc(mQueries.Count() * sizeof(nsINavHistoryQuery*)));
+                        (moz_xmalloc(mQueries.Count() * sizeof(nsINavHistoryQuery*)));
   NS_ENSURE_TRUE(*queries, NS_ERROR_OUT_OF_MEMORY);
 
   for (int32_t i = 0; i < mQueries.Count(); ++i)
     NS_ADDREF((*queries)[i] = mQueries[i]);
   *queryCount = mQueries.Count();
   return NS_OK;
 }
 
@@ -3103,17 +3103,17 @@ nsNavHistoryFolderResultNode::GetUri(nsA
 
   nsNavHistory* history = nsNavHistory::GetHistoryService();
   NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
 
   rv = history->QueriesToQueryString(queries, queryCount, mOptions, aURI);
   for (uint32_t queryIndex = 0; queryIndex < queryCount; ++queryIndex) {
     NS_RELEASE(queries[queryIndex]);
   }
-  nsMemory::Free(queries);
+  free(queries);
   return rv;
 }
 
 
 /**
  * @return the queries that give you this bookmarks folder
  */
 NS_IMETHODIMP
@@ -3128,17 +3128,17 @@ nsNavHistoryFolderResultNode::GetQueries
   NS_ENSURE_SUCCESS(rv, rv);
 
   // query just has the folder ID set and nothing else
   rv = query->SetFolders(&mTargetFolderItemId, 1);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // make array of our 1 query
   *queries = static_cast<nsINavHistoryQuery**>
-                        (nsMemory::Alloc(sizeof(nsINavHistoryQuery*)));
+                        (moz_xmalloc(sizeof(nsINavHistoryQuery*)));
   if (!*queries)
     return NS_ERROR_OUT_OF_MEMORY;
   NS_ADDREF((*queries)[0] = query);
   *queryCount = 1;
   return NS_OK;
 }
 
 
--- a/toolkit/components/telemetry/Telemetry.cpp
+++ b/toolkit/components/telemetry/Telemetry.cpp
@@ -3071,17 +3071,17 @@ GetRegisteredHistogramIds(bool keyed, ui
     }
 
     const char* id = h.id();
     const size_t len = strlen(id);
     collection.AppendElement(static_cast<char*>(nsMemory::Clone(id, len+1)));
   }
 
   const size_t bytes = collection.Length() * sizeof(char*);
-  char** histograms = static_cast<char**>(nsMemory::Alloc(bytes));
+  char** histograms = static_cast<char**>(moz_xmalloc(bytes));
   memcpy(histograms, collection.Elements(), bytes);
   *aHistograms = histograms;
   *aCount = collection.Length();
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/toolkit/components/url-classifier/nsUrlClassifierPrefixSet.cpp
+++ b/toolkit/components/url-classifier/nsUrlClassifierPrefixSet.cpp
@@ -172,17 +172,17 @@ nsUrlClassifierPrefixSet::GetPrefixes(ui
 
   FallibleTArray<uint32_t> prefixes;
   nsresult rv = GetPrefixesNative(prefixes);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   uint64_t itemCount = prefixes.Length();
-  uint32_t* prefixArray = static_cast<uint32_t*>(nsMemory::Alloc(itemCount * sizeof(uint32_t)));
+  uint32_t* prefixArray = static_cast<uint32_t*>(moz_xmalloc(itemCount * sizeof(uint32_t)));
   NS_ENSURE_TRUE(prefixArray, NS_ERROR_OUT_OF_MEMORY);
 
   memcpy(prefixArray, prefixes.Elements(), sizeof(uint32_t) * itemCount);
 
   *aCount = itemCount;
   *aPrefixes = prefixArray;
 
   return NS_OK;
--- a/toolkit/xre/nsAndroidStartup.cpp
+++ b/toolkit/xre/nsAndroidStartup.cpp
@@ -73,11 +73,11 @@ GeckoStart(void *data, const nsXREAppDat
     int result = XRE_main(targs.Length() - 1, targs.Elements(), appData, 0);
 
     if (result)
         LOG("XRE_main returned %d", result);
 
     mozilla::widget::GeckoAppShell::NotifyXreExit();
 
     free(targs[0]);
-    nsMemory::Free(data);
+    free(data);
     return;
 }
--- a/tools/profiler/nsProfiler.cpp
+++ b/tools/profiler/nsProfiler.cpp
@@ -231,17 +231,17 @@ nsProfiler::GetFeatures(uint32_t *aCount
     return NS_OK;
   }
 
   while (features[len]) {
     len++;
   }
 
   char **featureList = static_cast<char **>
-                       (nsMemory::Alloc(len * sizeof(char*)));
+                       (moz_xmalloc(len * sizeof(char*)));
 
   for (size_t i = 0; i < len; i++) {
     size_t strLen = strlen(features[i]);
     featureList[i] = static_cast<char *>
                          (nsMemory::Clone(features[i], (strLen + 1) * sizeof(char)));
   }
 
   *aFeatures = featureList;
--- a/widget/GfxInfoBase.cpp
+++ b/widget/GfxInfoBase.cpp
@@ -914,17 +914,17 @@ GfxInfoBase::LogFailure(const nsACString
   // detail that it's nicer to just add an extra lock here and in ::GetFailures()
   MutexAutoLock lock(mMutex);
 
   // By default, gfxCriticalError asserts; make it not assert in this case.
   gfxCriticalError(CriticalLog::DefaultOptions(false)) << "(LF) " << failure.BeginReading();
 }
 
 /* void getFailures (out unsigned long failureCount, [optional, array, size_is (failureCount)] out long indices, [array, size_is (failureCount), retval] out string failures); */
-/* XPConnect method of returning arrays is very ugly. Would not recommend. Fallable nsMemory::Alloc makes things worse */
+/* XPConnect method of returning arrays is very ugly. Would not recommend. */
 NS_IMETHODIMP GfxInfoBase::GetFailures(uint32_t* failureCount,
 				       int32_t** indices,
 				       char ***failures)
 {
   MutexAutoLock lock(mMutex);
 
   NS_ENSURE_ARG_POINTER(failureCount);
   NS_ENSURE_ARG_POINTER(failures);
@@ -945,24 +945,24 @@ NS_IMETHODIMP GfxInfoBase::GetFailures(u
   // assuming this is not a big deal, as the size of the array should be small
   // and the strings in it should be small as well (the error messages in the
   // code.)  The second copy happens with the Clone() calls.  Technically,
   // we don't need the mutex lock after the StringVectorCopy() call.
   std::vector<std::pair<int32_t,std::string> > loggedStrings = logForwarder->StringsVectorCopy();
   *failureCount = loggedStrings.size();
 
   if (*failureCount != 0) {
-    *failures = (char**)nsMemory::Alloc(*failureCount * sizeof(char*));
+    *failures = (char**)moz_xmalloc(*failureCount * sizeof(char*));
     if (!(*failures)) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
     if (indices) {
-      *indices = (int32_t*)nsMemory::Alloc(*failureCount * sizeof(int32_t));
+      *indices = (int32_t*)moz_xmalloc(*failureCount * sizeof(int32_t));
       if (!(*indices)) {
-        nsMemory::Free(*failures);
+        free(*failures);
         *failures = nullptr;
         return NS_ERROR_OUT_OF_MEMORY;
       }
     }
 
     /* copy over the failure messages into the array we just allocated */
     std::vector<std::pair<int32_t, std::string> >::const_iterator it;
     uint32_t i=0;
--- a/widget/android/nsAppShell.cpp
+++ b/widget/android/nsAppShell.cpp
@@ -505,19 +505,19 @@ nsAppShell::ProcessNextNativeEvent(bool 
             "dummyappname",
             "-url",
             uri,
             flag ? flag : ""
         };
         nsresult rv = cmdline->Init(4, argv, nullptr, nsICommandLine::STATE_REMOTE_AUTO);
         if (NS_SUCCEEDED(rv))
             cmdline->Run();
-        nsMemory::Free(uri);
+        free(uri);
         if (flag)
-            nsMemory::Free(flag);
+            free(flag);
         break;
     }
 
     case AndroidGeckoEvent::SIZE_CHANGED: {
         // store the last resize event to dispatch it to new windows with a FORCED_RESIZE event
         if (curEvent != gLastSizeChange) {
             gLastSizeChange = AndroidGeckoEvent::CopyResizeEvent(curEvent);
         }
--- a/widget/cocoa/nsClipboard.mm
+++ b/widget/cocoa/nsClipboard.mm
@@ -434,17 +434,17 @@ nsClipboard::PasteboardDictFromTransfera
       else
         nativeString = [NSString string];
       
       // be nice to Carbon apps, normalize the receiver's contents using Form C.
       nativeString = [nativeString precomposedStringWithCanonicalMapping];
 
       [pasteboardOutputDict setObject:nativeString forKey:pboardType];
       
-      nsMemory::Free(data);
+      free(data);
     }
     else if (flavorStr.EqualsLiteral(kPNGImageMime) || flavorStr.EqualsLiteral(kJPEGImageMime) ||
              flavorStr.EqualsLiteral(kJPGImageMime) || flavorStr.EqualsLiteral(kGIFImageMime) ||
              flavorStr.EqualsLiteral(kNativeImageMime)) {
       uint32_t dataSize = 0;
       nsCOMPtr<nsISupports> transferSupports;
       aTransferable->GetTransferData(flavorStr, getter_AddRefs(transferSupports), &dataSize);
       nsCOMPtr<nsISupportsInterfacePointer> ptrPrimitive(do_QueryInterface(transferSupports));
--- a/widget/gtk/nsClipboard.cpp
+++ b/widget/gtk/nsClipboard.cpp
@@ -326,17 +326,17 @@ nsClipboard::GetData(nsITransferable *aT
                     ConvertHTMLtoUCS2(const_cast<guchar*>(clipboardData), length,
                                       &htmlBody, htmlBodyLen);
                     // Try next data format?
                     if (!htmlBodyLen)
                         continue;
                     data = (guchar *)htmlBody;
                     length = htmlBodyLen * 2;
                 } else {
-                    data = (guchar *)nsMemory::Alloc(length);
+                    data = (guchar *)moz_xmalloc(length);
                     if (!data)
                         break;
                     memcpy(data, clipboardData, length);
                 }
                 gtk_selection_data_free(selectionData);
                 foundData = true;
                 foundFlavor = flavorStr;
                 break;
@@ -349,17 +349,17 @@ nsClipboard::GetData(nsITransferable *aT
         nsPrimitiveHelpers::CreatePrimitiveForData(foundFlavor.get(),
                                                    data, length,
                                                    getter_AddRefs(wrapper));
         aTransferable->SetTransferData(foundFlavor.get(),
                                        wrapper, length);
     }
 
     if (data)
-        nsMemory::Free(data);
+        free(data);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsClipboard::EmptyClipboard(int32_t aWhichClipboard)
 {
     if (aWhichClipboard == kSelectionClipboard) {
@@ -542,17 +542,17 @@ nsClipboard::SelectionGetEvent(GtkClipbo
         wideString->GetData(ucs2string);
         char *utf8string = ToNewUTF8String(ucs2string);
         if (!utf8string)
             return;
         
         gtk_selection_data_set_text (aSelectionData, utf8string,
                                      strlen(utf8string));
 
-        nsMemory::Free(utf8string);
+        free(utf8string);
         return;
     }
 
     // Check to see if the selection data is an image type
     if (gtk_targets_include_image(&selectionTarget, 1, TRUE)) {
         // Look through our transfer data for the image
         static const char* const imageMimeTypes[] = {
             kNativeImageMime, kPNGImageMime, kJPEGImageMime, kJPGImageMime, kGIFImageMime };
@@ -604,31 +604,31 @@ nsClipboard::SelectionGetEvent(GtkClipbo
             /*
              * "text/html" can be encoded UCS2. It is recommended that
              * documents transmitted as UCS2 always begin with a ZERO-WIDTH
              * NON-BREAKING SPACE character (hexadecimal FEFF, also called
              * Byte Order Mark (BOM)). Adding BOM can help other app to
              * detect mozilla use UCS2 encoding when copy-paste.
              */
             guchar *buffer = (guchar *)
-                    nsMemory::Alloc((len * sizeof(guchar)) + sizeof(char16_t));
+                    moz_xmalloc((len * sizeof(guchar)) + sizeof(char16_t));
             if (!buffer)
                 return;
             char16_t prefix = 0xFEFF;
             memcpy(buffer, &prefix, sizeof(prefix));
             memcpy(buffer + sizeof(prefix), primitive_data, len);
-            nsMemory::Free((guchar *)primitive_data);
+            free((guchar *)primitive_data);
             primitive_data = (guchar *)buffer;
             len += sizeof(prefix);
         }
   
         gtk_selection_data_set(aSelectionData, selectionTarget,
                                8, /* 8 bits in a unit */
                                (const guchar *)primitive_data, len);
-        nsMemory::Free(primitive_data);
+        free(primitive_data);
     }
 
     g_free(target_name);
                            
 }
 
 void
 nsClipboard::SelectionClearEvent(GtkClipboard *aGtkClipboard)
@@ -686,17 +686,17 @@ clipboard_clear_cb(GtkClipboard *aGtkCli
 void ConvertHTMLtoUCS2(guchar * data, int32_t dataLength,
                        char16_t** unicodeData, int32_t& outUnicodeLen)
 {
     nsAutoCString charset;
     GetHTMLCharset(data, dataLength, charset);// get charset of HTML
     if (charset.EqualsLiteral("UTF-16")) {//current mozilla
         outUnicodeLen = (dataLength / 2) - 1;
         *unicodeData = reinterpret_cast<char16_t*>
-                                       (nsMemory::Alloc((outUnicodeLen + sizeof('\0')) *
+                                       (moz_xmalloc((outUnicodeLen + sizeof('\0')) *
                        sizeof(char16_t)));
         if (*unicodeData) {
             memcpy(*unicodeData, data + sizeof(char16_t),
                    outUnicodeLen * sizeof(char16_t));
             (*unicodeData)[outUnicodeLen] = '\0';
         }
     } else if (charset.EqualsLiteral("UNKNOWN")) {
         outUnicodeLen = 0;
@@ -715,17 +715,17 @@ void ConvertHTMLtoUCS2(guchar * data, in
             return;
         }
         decoder = EncodingUtils::DecoderForEncoding(encoding);
         // converting
         decoder->GetMaxLength((const char *)data, dataLength, &outUnicodeLen);
         // |outUnicodeLen| is number of chars
         if (outUnicodeLen) {
             *unicodeData = reinterpret_cast<char16_t*>
-                                           (nsMemory::Alloc((outUnicodeLen + sizeof('\0')) *
+                                           (moz_xmalloc((outUnicodeLen + sizeof('\0')) *
                            sizeof(char16_t)));
             if (*unicodeData) {
                 int32_t numberTmp = dataLength;
                 decoder->Convert((const char *)data, &numberTmp,
                                  *unicodeData, &outUnicodeLen);
 #ifdef DEBUG_CLIPBOARD
                 if (numberTmp != dataLength)
                     printf("didn't consume all the bytes\n");
--- a/widget/gtk/nsWindow.cpp
+++ b/widget/gtk/nsWindow.cpp
@@ -3920,32 +3920,32 @@ nsWindow::SetWindowClass(const nsAString
   GdkWindow *shellWindow = gtk_widget_get_window(GTK_WIDGET(mShell));
   gdk_window_set_role(shellWindow, role);
 
 #ifdef MOZ_X11
   GdkDisplay *display = gdk_display_get_default();
   if (GDK_IS_X11_DISPLAY(display)) {
       XClassHint *class_hint = XAllocClassHint();
       if (!class_hint) {
-        nsMemory::Free(res_name);
+        free(res_name);
         return NS_ERROR_OUT_OF_MEMORY;
       }
       class_hint->res_name = res_name;
       class_hint->res_class = const_cast<char*>(res_class);
 
       // Can't use gtk_window_set_wmclass() for this; it prints
       // a warning & refuses to make the change.
       XSetClassHint(GDK_DISPLAY_XDISPLAY(display),
                     gdk_x11_window_get_xid(shellWindow),
                     class_hint);
       XFree(class_hint);
   }
 #endif /* MOZ_X11 */
 
-  nsMemory::Free(res_name);
+  free(res_name);
 
   return NS_OK;
 }
 
 void
 nsWindow::NativeResize(int32_t aWidth, int32_t aHeight, bool    aRepaint)
 {
     gint width = DevicePixelsToGdkCoordRoundUp(aWidth);
--- a/widget/nsPrimitiveHelpers.cpp
+++ b/widget/nsPrimitiveHelpers.cpp
@@ -205,17 +205,17 @@ nsPrimitiveHelpers :: ConvertPlatformPla
 
     hasConverter = true;
   }
   
   // Estimate out length and allocate the buffer based on a worst-case estimate, then do
   // the conversion. 
   decoder->GetMaxLength(inText, inTextLen, outUnicodeLen);   // |outUnicodeLen| is number of chars
   if ( *outUnicodeLen ) {
-    *outUnicode = reinterpret_cast<char16_t*>(nsMemory::Alloc((*outUnicodeLen + 1) * sizeof(char16_t)));
+    *outUnicode = reinterpret_cast<char16_t*>(moz_xmalloc((*outUnicodeLen + 1) * sizeof(char16_t)));
     if ( *outUnicode ) {
       rv = decoder->Convert(inText, &inTextLen, *outUnicode, outUnicodeLen);
       (*outUnicode)[*outUnicodeLen] = '\0';                   // null terminate. Convert() doesn't do it for us
     }
   } // if valid length
 
   NS_ASSERTION ( NS_SUCCEEDED(rv), "Error converting plain text to unicode" );
 
@@ -246,33 +246,33 @@ nsLinebreakHelpers :: ConvertPlatformToD
   if ( strcmp(inFlavor, "text/plain") == 0 ) {
     char* buffAsChars = reinterpret_cast<char*>(*ioData);
     char* oldBuffer = buffAsChars;
     retVal = nsLinebreakConverter::ConvertLineBreaksInSitu ( &buffAsChars, nsLinebreakConverter::eLinebreakAny, 
                                                               nsLinebreakConverter::eLinebreakContent, 
                                                               *ioLengthInBytes, ioLengthInBytes );
     if ( NS_SUCCEEDED(retVal) ) {
       if ( buffAsChars != oldBuffer )             // check if buffer was reallocated
-        nsMemory::Free ( oldBuffer );
+        free ( oldBuffer );
       *ioData = buffAsChars;
     }
   }
   else if ( strcmp(inFlavor, "image/jpeg") == 0 ) {
     // I'd assume we don't want to do anything for binary data....
   }
   else {       
     char16_t* buffAsUnichar = reinterpret_cast<char16_t*>(*ioData);
     char16_t* oldBuffer = buffAsUnichar;
     int32_t newLengthInChars;
     retVal = nsLinebreakConverter::ConvertUnicharLineBreaksInSitu ( &buffAsUnichar, nsLinebreakConverter::eLinebreakAny, 
                                                                      nsLinebreakConverter::eLinebreakContent, 
                                                                      *ioLengthInBytes / sizeof(char16_t), &newLengthInChars );
     if ( NS_SUCCEEDED(retVal) ) {
       if ( buffAsUnichar != oldBuffer )           // check if buffer was reallocated
-        nsMemory::Free ( oldBuffer );
+        free ( oldBuffer );
       *ioData = buffAsUnichar;
       *ioLengthInBytes = newLengthInChars * sizeof(char16_t);
     }
   }
   
   return retVal;
 
 } // ConvertPlatformToDOMLinebreaks
--- a/widget/nsTransferable.cpp
+++ b/widget/nsTransferable.cpp
@@ -147,17 +147,17 @@ DataStruct::WriteCache(nsISupports* aDat
 
     if (!outStr) return NS_ERROR_FAILURE;
 
     void* buff = nullptr;
     nsPrimitiveHelpers::CreateDataFromPrimitive ( mFlavor.get(), aData, &buff, aDataLen );
     if ( buff ) {
       uint32_t ignored;
       outStr->Write(reinterpret_cast<char*>(buff), aDataLen, &ignored);
-      nsMemory::Free(buff);
+      free(buff);
       return NS_OK;
     }
   }
   return NS_ERROR_FAILURE;
 }
 
 
 //-------------------------------------------------------------------------
--- a/widget/qt/nsClipboard.cpp
+++ b/widget/qt/nsClipboard.cpp
@@ -218,17 +218,17 @@ nsClipboard::SetNativeClipboardData( nsI
                 nsPrimitiveHelpers::CreateDataFromPrimitive(flavorStr.get(), clip,
                                                             &primitive_data, len);
 
                 if (primitive_data)
                 {
                     QByteArray data ((const char *)primitive_data, len);
                     // Add data to the mimeData
                     mimeData->setData(flavorStr.get(), data);
-                    nsMemory::Free(primitive_data);
+                    free(primitive_data);
                 }
             }
         }
     }
 
     // If we have some mime data, add it to the clipboard
     if(!mimeData->formats().isEmpty())
         cb->setMimeData(mimeData, clipboardMode);
--- a/widget/qt/nsWindow.cpp
+++ b/widget/qt/nsWindow.cpp
@@ -1720,17 +1720,17 @@ nsWindow::SetWindowClass(const nsAString
     const char *role = nullptr;
     class_hint->res_name = ToNewCString(xulWinType);
     if (!class_hint->res_name) {
         XFree(class_hint);
         return NS_ERROR_OUT_OF_MEMORY;
     }
     class_hint->res_class = ToNewCString(brandName);
     if (!class_hint->res_class) {
-        nsMemory::Free(class_hint->res_name);
+        free(class_hint->res_name);
         XFree(class_hint);
         return NS_ERROR_OUT_OF_MEMORY;
     }
 
     // Parse res_name into a name and role. Characters other than
     // [A-Za-z0-9_-] are converted to '_'. Anything after the first
     // colon is assigned to role; if there's no colon, assign the
     // whole thing to both role and res_name.
@@ -1748,18 +1748,18 @@ nsWindow::SetWindowClass(const nsAString
     QWindow *widget = mWidget;
     // If widget not show, handle might be null
     if (widget && widget->winId()) {
         XSetClassHint(gfxQtPlatform::GetXDisplay(widget),
                       widget->winId(),
                       class_hint);
     }
 
-    nsMemory::Free(class_hint->res_class);
-    nsMemory::Free(class_hint->res_name);
+    free(class_hint->res_class);
+    free(class_hint->res_name);
     XFree(class_hint);
 #endif
 
     return NS_OK;
 }
 
 void
 nsWindow::NativeResize(int32_t aWidth, int32_t aHeight, bool    aRepaint)
--- a/widget/windows/nsClipboard.cpp
+++ b/widget/windows/nsClipboard.cpp
@@ -277,17 +277,17 @@ nsresult nsClipboard::GetGlobalData(HGLO
   // Allocate a new memory buffer and copy the data from global memory.
   // Recall that win98 allocates to nearest DWORD boundary. As a safety
   // precaution, allocate an extra 2 bytes (but don't report them!) and
   // null them out to ensure that all of our strlen calls will succeed.
   nsresult  result = NS_ERROR_FAILURE;
   if (aHGBL != nullptr) {
     LPSTR lpStr = (LPSTR) GlobalLock(aHGBL);
     DWORD allocSize = GlobalSize(aHGBL);
-    char* data = static_cast<char*>(nsMemory::Alloc(allocSize + sizeof(char16_t)));
+    char* data = static_cast<char*>(moz_xmalloc(allocSize + sizeof(char16_t)));
     if ( data ) {    
       memcpy ( data, lpStr, allocSize );
       data[allocSize] = data[allocSize + 1] = '\0';     // null terminate for safety
 
       GlobalUnlock(aHGBL);
       *aData = data;
       *aLen = allocSize;
 
@@ -489,17 +489,17 @@ nsresult nsClipboard::GetNativeDataOffCl
                 // if there really are multiple drag items.
                 HDROP dropFiles = (HDROP) GlobalLock(stm.hGlobal);
 
                 UINT numFiles = ::DragQueryFileW(dropFiles, 0xFFFFFFFF, nullptr, 0);
                 NS_ASSERTION ( numFiles > 0, "File drop flavor, but no files...hmmmm" );
                 NS_ASSERTION ( aIndex < numFiles, "Asked for a file index out of range of list" );
                 if (numFiles > 0) {
                   UINT fileNameLen = ::DragQueryFileW(dropFiles, aIndex, nullptr, 0);
-                  wchar_t* buffer = reinterpret_cast<wchar_t*>(nsMemory::Alloc((fileNameLen + 1) * sizeof(wchar_t)));
+                  wchar_t* buffer = reinterpret_cast<wchar_t*>(moz_xmalloc((fileNameLen + 1) * sizeof(wchar_t)));
                   if ( buffer ) {
                     ::DragQueryFileW(dropFiles, aIndex, buffer, fileNameLen + 1);
                     *aData = buffer;
                     *aLen = fileNameLen * sizeof(char16_t);
                     result = NS_OK;
                   }
                   else
                     result = NS_ERROR_OUT_OF_MEMORY;
@@ -634,47 +634,47 @@ nsresult nsClipboard::GetDataFromDataObj
       if ( dataFound ) {
         nsCOMPtr<nsISupports> genericDataWrapper;
           if ( strcmp(flavorStr, kFileMime) == 0 ) {
             // we have a file path in |data|. Create an nsLocalFile object.
             nsDependentString filepath(reinterpret_cast<char16_t*>(data));
             nsCOMPtr<nsIFile> file;
             if ( NS_SUCCEEDED(NS_NewLocalFile(filepath, false, getter_AddRefs(file))) )
               genericDataWrapper = do_QueryInterface(file);
-            nsMemory::Free(data);
+            free(data);
           }
         else if ( strcmp(flavorStr, kNativeHTMLMime) == 0) {
           // the editor folks want CF_HTML exactly as it's on the clipboard, no conversions,
           // no fancy stuff. Pull it off the clipboard, stuff it into a wrapper and hand
           // it back to them.
           if ( FindPlatformHTML(aDataObject, anIndex, &data, &dataLen) )
             nsPrimitiveHelpers::CreatePrimitiveForData ( flavorStr, data, dataLen, getter_AddRefs(genericDataWrapper) );
           else
           {
-            nsMemory::Free(data);
+            free(data);
             continue;     // something wrong with this flavor, keep looking for other data
           }
-          nsMemory::Free(data);
+          free(data);
         }
         else if ( strcmp(flavorStr, kJPEGImageMime) == 0 ||
                   strcmp(flavorStr, kJPGImageMime) == 0 ||
                   strcmp(flavorStr, kPNGImageMime) == 0) {
           nsIInputStream * imageStream = reinterpret_cast<nsIInputStream*>(data);
           genericDataWrapper = do_QueryInterface(imageStream);
           NS_IF_RELEASE(imageStream);
         }
         else {
           // we probably have some form of text. The DOM only wants LF, so convert from Win32 line 
           // endings to DOM line endings.
           int32_t signedLen = static_cast<int32_t>(dataLen);
           nsLinebreakHelpers::ConvertPlatformToDOMLinebreaks ( flavorStr, &data, &signedLen );
           dataLen = signedLen;
 
           nsPrimitiveHelpers::CreatePrimitiveForData ( flavorStr, data, dataLen, getter_AddRefs(genericDataWrapper) );
-          nsMemory::Free(data);
+          free(data);
         }
         
         NS_ASSERTION ( genericDataWrapper, "About to put null data into the transferable" );
         aTransferable->SetTransferData(flavorStr, genericDataWrapper, dataLen);
         res = NS_OK;
 
         // we found one, get out of the loop
         break;
@@ -760,17 +760,17 @@ nsClipboard :: FindUnicodeFromPlainText 
   if ( NS_SUCCEEDED(loadResult) && *outData ) {
     const char* castedText = reinterpret_cast<char*>(*outData);          
     char16_t* convertedText = nullptr;
     int32_t convertedTextLen = 0;
     nsPrimitiveHelpers::ConvertPlatformPlainTextToUnicode ( castedText, *outDataLen, 
                                                               &convertedText, &convertedTextLen );
     if ( convertedText ) {
       // out with the old, in with the new 
-      nsMemory::Free(*outData);
+      free(*outData);
       *outData = convertedText;
       *outDataLen = convertedTextLen * sizeof(char16_t);
       dataFound = true;
     }
   } // if plain text data on clipboard
 
   return dataFound;
 
@@ -792,22 +792,22 @@ nsClipboard :: FindURLFromLocalFile ( ID
 
   nsresult loadResult = GetNativeDataOffClipboard(inDataObject, inIndex, GetFormat(kFileMime), nullptr, outData, outDataLen);
   if ( NS_SUCCEEDED(loadResult) && *outData ) {
     // we have a file path in |data|. Is it an internet shortcut or a normal file?
     const nsDependentString filepath(static_cast<char16_t*>(*outData));
     nsCOMPtr<nsIFile> file;
     nsresult rv = NS_NewLocalFile(filepath, true, getter_AddRefs(file));
     if (NS_FAILED(rv)) {
-      nsMemory::Free(*outData);
+      free(*outData);
       return dataFound;
     }
 
     if ( IsInternetShortcut(filepath) ) {
-      nsMemory::Free(*outData);
+      free(*outData);
       nsAutoCString url;
       ResolveShortcut( file, url );
       if ( !url.IsEmpty() ) {
         // convert it to unicode and pass it out
         nsDependentString urlString(UTF8ToNewUnicode(url));
         // the internal mozilla URL format, text/x-moz-url, contains
         // URL\ntitle.  We can guess the title from the file's name.
         nsAutoString title;
@@ -823,17 +823,17 @@ nsClipboard :: FindURLFromLocalFile ( ID
       }
     }
     else {
       // we have a normal file, use some Necko objects to get our file path
       nsAutoCString urlSpec;
       NS_GetURLSpecFromFile(file, urlSpec);
 
       // convert it to unicode and pass it out
-      nsMemory::Free(*outData);
+      free(*outData);
       *outData = UTF8ToNewUnicode(urlSpec);
       *outDataLen = NS_strlen(static_cast<char16_t*>(*outData)) * sizeof(char16_t);
       dataFound = true;
     } // else regular file
   }
 
   return dataFound;
 } // FindURLFromLocalFile
@@ -856,17 +856,17 @@ nsClipboard :: FindURLFromNativeURL ( ID
   nsresult loadResult = GetNativeDataOffClipboard(inDataObject, inIndex, ::RegisterClipboardFormat(CFSTR_INETURLW), nullptr, &tempOutData, &tempDataLen);
   if ( NS_SUCCEEDED(loadResult) && tempOutData ) {
     nsDependentString urlString(static_cast<char16_t*>(tempOutData));
     // the internal mozilla URL format, text/x-moz-url, contains
     // URL\ntitle.  Since we don't actually have a title here,
     // just repeat the URL to fake it.
     *outData = ToNewUnicode(urlString + NS_LITERAL_STRING("\n") + urlString);
     *outDataLen = NS_strlen(static_cast<char16_t*>(*outData)) * sizeof(char16_t);
-    nsMemory::Free(tempOutData);
+    free(tempOutData);
     dataFound = true;
   }
   else {
     loadResult = GetNativeDataOffClipboard(inDataObject, inIndex, ::RegisterClipboardFormat(CFSTR_INETURLA), nullptr, &tempOutData, &tempDataLen);
     if ( NS_SUCCEEDED(loadResult) && tempOutData ) {
       // CFSTR_INETURLA is (currently) equal to CFSTR_SHELLURL which is equal to CF_TEXT
       // which is by definition ANSI encoded.
       nsCString urlUnescapedA;
@@ -878,17 +878,17 @@ nsClipboard :: FindURLFromNativeURL ( ID
       else
         NS_CopyNativeToUnicode(nsDependentCString(static_cast<char*>(tempOutData), tempDataLen), urlString);
 
       // the internal mozilla URL format, text/x-moz-url, contains
       // URL\ntitle.  Since we don't actually have a title here,
       // just repeat the URL to fake it.
       *outData = ToNewUnicode(urlString + NS_LITERAL_STRING("\n") + urlString);
       *outDataLen = NS_strlen(static_cast<char16_t*>(*outData)) * sizeof(char16_t);
-      nsMemory::Free(tempOutData);
+      free(tempOutData);
       dataFound = true;
     }
   }
 
   return dataFound;
 } // FindURLFromNativeURL
 
 //
--- a/widget/windows/nsDataObj.cpp
+++ b/widget/windows/nsDataObj.cpp
@@ -1287,40 +1287,40 @@ HRESULT nsDataObj::GetText(const nsACStr
   // the |len| parameter. Windoze apps expect this null to be there so bump our data buffer
   // by the appropriate size to account for the null (one char for CF_TEXT, one char16_t for
   // CF_UNICODETEXT).
   DWORD allocLen = (DWORD)len;
   if ( aFE.cfFormat == CF_TEXT ) {
     // Someone is asking for text/plain; convert the unicode (assuming it's present)
     // to text with the correct platform encoding.
     size_t bufferSize = sizeof(char)*(len + 2);
-    char* plainTextData = static_cast<char*>(nsMemory::Alloc(bufferSize));
+    char* plainTextData = static_cast<char*>(moz_xmalloc(bufferSize));
     char16_t* castedUnicode = reinterpret_cast<char16_t*>(data);
     int32_t plainTextLen = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)castedUnicode, len / 2 + 1, plainTextData, bufferSize, NULL, NULL);
     // replace the unicode data with our plaintext data. Recall that |plainTextLen| doesn't include
     // the null in the length.
-    nsMemory::Free(data);
+    free(data);
     if ( plainTextLen ) {
       data = plainTextData;
       allocLen = plainTextLen;
     }
     else {
-      nsMemory::Free(plainTextData);
+      free(plainTextData);
       NS_WARNING ( "Oh no, couldn't convert unicode to plain text" );
       return S_OK;
     }
   }
   else if ( aFE.cfFormat == nsClipboard::CF_HTML ) {
     // Someone is asking for win32's HTML flavor. Convert our html fragment
     // from unicode to UTF-8 then put it into a format specified by msft.
     NS_ConvertUTF16toUTF8 converter ( reinterpret_cast<char16_t*>(data) );
     char* utf8HTML = nullptr;
     nsresult rv = BuildPlatformHTML ( converter.get(), &utf8HTML );      // null terminates
     
-    nsMemory::Free(data);
+    free(data);
     if ( NS_SUCCEEDED(rv) && utf8HTML ) {
       // replace the unicode data with our HTML data. Don't forget the null.
       data = utf8HTML;
       allocLen = strlen(utf8HTML) + sizeof(char);
     }
     else {
       NS_WARNING ( "Oh no, couldn't convert to HTML" );
       return S_OK;
@@ -1339,17 +1339,17 @@ HRESULT nsDataObj::GetText(const nsACStr
     char* dest = reinterpret_cast<char*>(GlobalLock(hGlobalMemory));
     char* source = reinterpret_cast<char*>(data);
     memcpy ( dest, source, allocLen );                         // copies the null as well
     GlobalUnlock(hGlobalMemory);
   }
   aSTG.hGlobal = hGlobalMemory;
 
   // Now, delete the memory that was created by CreateDataFromPrimitive (or our text/plain data)
-  nsMemory::Free(data);
+  free(data);
 
   return S_OK;
 }
 
 //-----------------------------------------------------
 HRESULT nsDataObj::GetFile(FORMATETC& aFE, STGMEDIUM& aSTG)
 {
   uint32_t dfInx = 0;
--- a/widget/windows/nsNativeDragTarget.cpp
+++ b/widget/windows/nsNativeDragTarget.cpp
@@ -248,17 +248,17 @@ nsNativeDragTarget::DragEnter(LPDATAOBJE
   mDragService->StartDragSession();
 
   void* tempOutData = nullptr;
   uint32_t tempDataLen = 0;
   nsresult loadResult = nsClipboard::GetNativeDataOffClipboard(
       pIDataSource, 0, ::RegisterClipboardFormat(CFSTR_PREFERREDDROPEFFECT), nullptr, &tempOutData, &tempDataLen);
   if (NS_SUCCEEDED(loadResult) && tempOutData) {
     mEffectsPreferred = *((DWORD*)tempOutData);
-    nsMemory::Free(tempOutData);
+    free(tempOutData);
   } else {
     // We have no preference if we can't obtain it
     mEffectsPreferred = DROPEFFECT_NONE;
   }
 
   // Set the native data object into drag service
   //
   // This cast is ok because in the constructor we created a
--- a/widget/windows/nsPrintSettingsWin.cpp
+++ b/widget/windows/nsPrintSettingsWin.cpp
@@ -35,42 +35,42 @@ nsPrintSettingsWin::nsPrintSettingsWin(c
 }
 
 /** ---------------------------------------------------
  *  See documentation in nsPrintSettingsWin.h
  *	@update 
  */
 nsPrintSettingsWin::~nsPrintSettingsWin()
 {
-  if (mDeviceName) nsMemory::Free(mDeviceName);
-  if (mDriverName) nsMemory::Free(mDriverName);
+  if (mDeviceName) free(mDeviceName);
+  if (mDriverName) free(mDriverName);
   if (mDevMode) ::HeapFree(::GetProcessHeap(), 0, mDevMode);
 }
 
 /* [noscript] attribute charPtr deviceName; */
 NS_IMETHODIMP nsPrintSettingsWin::SetDeviceName(const char16_t * aDeviceName)
 {
   if (mDeviceName) {
-    nsMemory::Free(mDeviceName);
+    free(mDeviceName);
   }
   mDeviceName = aDeviceName?wcsdup(char16ptr_t(aDeviceName)):nullptr;
   return NS_OK;
 }
 NS_IMETHODIMP nsPrintSettingsWin::GetDeviceName(char16_t **aDeviceName)
 {
   NS_ENSURE_ARG_POINTER(aDeviceName);
   *aDeviceName = mDeviceName?reinterpret_cast<char16_t*>(wcsdup(mDeviceName)):nullptr;
   return NS_OK;
 }
 
 /* [noscript] attribute charPtr driverName; */
 NS_IMETHODIMP nsPrintSettingsWin::SetDriverName(const char16_t * aDriverName)
 {
   if (mDriverName) {
-    nsMemory::Free(mDriverName);
+    free(mDriverName);
   }
   mDriverName = aDriverName?wcsdup(char16ptr_t(aDriverName)):nullptr;
   return NS_OK;
 }
 NS_IMETHODIMP nsPrintSettingsWin::GetDriverName(char16_t **aDriverName)
 {
   NS_ENSURE_ARG_POINTER(aDriverName);
   *aDriverName = mDriverName?reinterpret_cast<char16_t*>(wcsdup(mDriverName)):nullptr;
--- a/xpcom/base/nsConsoleService.cpp
+++ b/xpcom/base/nsConsoleService.cpp
@@ -66,17 +66,17 @@ nsConsoleService::~nsConsoleService()
 {
   uint32_t i = 0;
   while (i < mBufferSize && mMessages[i]) {
     NS_RELEASE(mMessages[i]);
     i++;
   }
 
   if (mMessages) {
-    nsMemory::Free(mMessages);
+    free(mMessages);
   }
 }
 
 class AddConsolePrefWatchers : public nsRunnable
 {
 public:
   explicit AddConsolePrefWatchers(nsConsoleService* aConsole) : mConsole(aConsole)
   {
@@ -95,17 +95,17 @@ public:
 private:
   nsRefPtr<nsConsoleService> mConsole;
 };
 
 nsresult
 nsConsoleService::Init()
 {
   mMessages = (nsIConsoleMessage**)
-    nsMemory::Alloc(mBufferSize * sizeof(nsIConsoleMessage*));
+    moz_xmalloc(mBufferSize * sizeof(nsIConsoleMessage*));
   if (!mMessages) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   // Array elements should be 0 initially for circular buffer algorithm.
   memset(mMessages, 0, mBufferSize * sizeof(nsIConsoleMessage*));
 
   NS_DispatchToMainThread(new AddConsolePrefWatchers(this));
@@ -327,27 +327,27 @@ nsConsoleService::GetMessageArray(uint32
 
   if (mCurrent == 0 && !mFull) {
     /*
      * Make a 1-length output array so that nobody gets confused,
      * and return a count of 0.  This should result in a 0-length
      * array object when called from script.
      */
     messageArray = (nsIConsoleMessage**)
-      nsMemory::Alloc(sizeof(nsIConsoleMessage*));
+      moz_xmalloc(sizeof(nsIConsoleMessage*));
     *messageArray = nullptr;
     *aMessages = messageArray;
     *aCount = 0;
 
     return NS_OK;
   }
 
   uint32_t resultSize = mFull ? mBufferSize : mCurrent;
   messageArray =
-    (nsIConsoleMessage**)nsMemory::Alloc((sizeof(nsIConsoleMessage*))
+    (nsIConsoleMessage**)moz_xmalloc((sizeof(nsIConsoleMessage*))
                                          * resultSize);
 
   if (!messageArray) {
     *aMessages = nullptr;
     *aCount = 0;
     return NS_ERROR_FAILURE;
   }
 
--- a/xpcom/ds/nsProperties.cpp
+++ b/xpcom/ds/nsProperties.cpp
@@ -89,32 +89,32 @@ GetKeysEnumerate(const char* aKey, nsISu
 NS_IMETHODIMP
 nsProperties::GetKeys(uint32_t* aCount, char*** aKeys)
 {
   if (NS_WARN_IF(!aCount) || NS_WARN_IF(!aKeys)) {
     return NS_ERROR_INVALID_ARG;
   }
 
   uint32_t n = Count();
-  char** k = (char**)nsMemory::Alloc(n * sizeof(char*));
+  char** k = (char**)moz_xmalloc(n * sizeof(char*));
 
   GetKeysEnumData gked;
   gked.keys = k;
   gked.next = 0;
   gked.res = NS_OK;
 
   EnumerateRead(GetKeysEnumerate, &gked);
 
   nsresult rv = gked.res;
   if (NS_FAILED(rv)) {
     // Free 'em all
     for (uint32_t i = 0; i < gked.next; i++) {
-      nsMemory::Free(k[i]);
+      free(k[i]);
     }
-    nsMemory::Free(k);
+    free(k);
     return rv;
   }
 
   *aCount = n;
   *aKeys = k;
   return NS_OK;
 }
 
--- a/xpcom/ds/nsStaticNameTable.cpp
+++ b/xpcom/ds/nsStaticNameTable.cpp
@@ -110,17 +110,17 @@ nsStaticCaseInsensitiveNameTable::nsStat
 
 nsStaticCaseInsensitiveNameTable::~nsStaticCaseInsensitiveNameTable()
 {
   if (mNameArray) {
     // manually call the destructor on placement-new'ed objects
     for (uint32_t index = 0; index < mNameTable.EntryCount(); index++) {
       mNameArray[index].~nsDependentCString();
     }
-    nsMemory::Free((void*)mNameArray);
+    free((void*)mNameArray);
   }
   if (mNameTable.IsInitialized()) {
     PL_DHashTableFinish(&mNameTable);
   }
   MOZ_COUNT_DTOR(nsStaticCaseInsensitiveNameTable);
 }
 
 bool
@@ -128,17 +128,17 @@ nsStaticCaseInsensitiveNameTable::Init(c
                                        int32_t aLength)
 {
   NS_ASSERTION(!mNameArray, "double Init");
   NS_ASSERTION(!mNameTable.IsInitialized(), "double Init");
   NS_ASSERTION(aNames, "null name table");
   NS_ASSERTION(aLength, "0 length");
 
   mNameArray = (nsDependentCString*)
-    nsMemory::Alloc(aLength * sizeof(nsDependentCString));
+    moz_xmalloc(aLength * sizeof(nsDependentCString));
   if (!mNameArray) {
     return false;
   }
 
   if (!PL_DHashTableInit(&mNameTable, &nametable_CaseInsensitiveHashTableOps,
                          sizeof(NameTableEntry), fallible,
                          aLength)) {
     return false;
--- a/xpcom/ds/nsSupportsPrimitives.cpp
+++ b/xpcom/ds/nsSupportsPrimitives.cpp
@@ -36,17 +36,17 @@ nsSupportsIDImpl::GetData(nsID** aData)
   *aData = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSupportsIDImpl::SetData(const nsID* aData)
 {
   if (mData) {
-    nsMemory::Free(mData);
+    free(mData);
   }
   if (aData) {
     mData = (nsID*)nsMemory::Clone(aData, sizeof(nsID));
   } else {
     mData = nullptr;
   }
   return NS_OK;
 }
@@ -464,17 +464,17 @@ nsSupportsCharImpl::SetData(char aData)
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSupportsCharImpl::ToString(char** aResult)
 {
   NS_ASSERTION(aResult, "Bad pointer");
 
-  char* result = (char*)nsMemory::Alloc(2 * sizeof(char));
+  char* result = (char*)moz_xmalloc(2 * sizeof(char));
   if (result) {
     result[0] = mData;
     result[1] = '\0';
   }
   *aResult = result;
   return result ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
 }
 
@@ -764,17 +764,17 @@ NS_IMPL_ISUPPORTS(nsSupportsInterfacePoi
 nsSupportsInterfacePointerImpl::nsSupportsInterfacePointerImpl()
   : mIID(nullptr)
 {
 }
 
 nsSupportsInterfacePointerImpl::~nsSupportsInterfacePointerImpl()
 {
   if (mIID) {
-    nsMemory::Free(mIID);
+    free(mIID);
   }
 }
 
 NS_IMETHODIMP
 nsSupportsInterfacePointerImpl::GetType(uint16_t* aType)
 {
   NS_ASSERTION(aType, "Bad pointer");
   *aType = TYPE_INTERFACE_POINTER;
@@ -813,17 +813,17 @@ nsSupportsInterfacePointerImpl::GetDataI
   *aIID = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSupportsInterfacePointerImpl::SetDataIID(const nsID* aIID)
 {
   if (mIID) {
-    nsMemory::Free(mIID);
+    free(mIID);
   }
   if (aIID) {
     mIID = (nsID*)nsMemory::Clone(aIID, sizeof(nsID));
   } else {
     mIID = nullptr;
   }
 
   return NS_OK;
--- a/xpcom/ds/nsVariant.cpp
+++ b/xpcom/ds/nsVariant.cpp
@@ -35,17 +35,17 @@ String2Double(const char* aString, doubl
 static nsresult
 AString2Double(const nsAString& aString, double* aResult)
 {
   char* pChars = ToNewCString(aString);
   if (!pChars) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   nsresult rv = String2Double(pChars, aResult);
-  nsMemory::Free(pChars);
+  free(pChars);
   return rv;
 }
 
 static nsresult
 AUTF8String2Double(const nsAUTF8String& aString, double* aResult)
 {
   return String2Double(PromiseFlatUTF8String(aString).get(), aResult);
 }
@@ -175,17 +175,17 @@ FreeArray(nsDiscriminatedUnion* aData)
   NS_ASSERTION(aData->u.array.mArrayCount, "bad array count");
 
 #define CASE__FREE_ARRAY_PTR(type_, ctype_)                                   \
         case nsIDataType:: type_ :                                            \
         {                                                                     \
             ctype_ ** p = (ctype_ **) aData->u.array.mArrayValue;             \
             for(uint32_t i = aData->u.array.mArrayCount; i > 0; p++, i--)     \
                 if(*p)                                                        \
-                    nsMemory::Free((char*)*p);                                \
+                    free((char*)*p);                                \
             break;                                                            \
         }
 
 #define CASE__FREE_ARRAY_IFACE(type_, ctype_)                                 \
         case nsIDataType:: type_ :                                            \
         {                                                                     \
             ctype_ ** p = (ctype_ **) aData->u.array.mArrayValue;             \
             for(uint32_t i = aData->u.array.mArrayCount; i > 0; p++, i--)     \
@@ -229,17 +229,17 @@ FreeArray(nsDiscriminatedUnion* aData)
     case nsIDataType::VTYPE_EMPTY_ARRAY:
     case nsIDataType::VTYPE_EMPTY:
     default:
       NS_ERROR("bad type in array!");
       break;
   }
 
   // Free the array memory.
-  nsMemory::Free((char*)aData->u.array.mArrayValue);
+  free((char*)aData->u.array.mArrayValue);
 
 #undef CASE__FREE_ARRAY_PTR
 #undef CASE__FREE_ARRAY_IFACE
 }
 
 static nsresult
 CloneArray(uint16_t aInType, const nsIID* aInIID,
            uint32_t aInCount, void* aInValue,
@@ -326,17 +326,17 @@ CloneArray(uint16_t aInType, const nsIID
       NS_ERROR("bad type in array!");
       return NS_ERROR_CANNOT_CONVERT_DATA;
   }
 
 
   // Alloc the u.array.
 
   allocSize = aInCount * elementSize;
-  *aOutValue = nsMemory::Alloc(allocSize);
+  *aOutValue = moz_xmalloc(allocSize);
   if (!*aOutValue) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   // Clone the elements.
 
   switch (aInType) {
     case nsIDataType::VTYPE_INT8:
@@ -445,19 +445,19 @@ CloneArray(uint16_t aInType, const nsIID
   *aOutCount = aInCount;
   return NS_OK;
 
 bad:
   if (*aOutValue) {
     char** p = (char**)*aOutValue;
     for (i = allocatedValueCount; i > 0; ++p, --i)
       if (*p) {
-        nsMemory::Free(*p);
+        free(*p);
       }
-    nsMemory::Free((char*)*aOutValue);
+    free((char*)*aOutValue);
     *aOutValue = nullptr;
   }
   return rv;
 }
 
 /***************************************************************************/
 
 #define TRIVIAL_DATA_CONVERTER(type_, data_, member_, retval_)                \
@@ -705,17 +705,17 @@ String2ID(const nsDiscriminatedUnion& aD
       return false;
   }
 
   char* pChars = ToNewCString(*pString);
   if (!pChars) {
     return false;
   }
   bool result = aPid->Parse(pChars);
-  nsMemory::Free(pChars);
+  free(pChars);
   return result;
 }
 
 /* static */ nsresult
 nsVariant::ConvertToID(const nsDiscriminatedUnion& aData, nsID* aResult)
 {
   nsID id;
 
@@ -786,17 +786,17 @@ ToString(const nsDiscriminatedUnion& aDa
     // nsID has its own text formatter.
 
     case nsIDataType::VTYPE_ID:
       ptr = aData.u.mIDValue.ToString();
       if (!ptr) {
         return NS_ERROR_OUT_OF_MEMORY;
       }
       aOutString.Assign(ptr);
-      nsMemory::Free(ptr);
+      free(ptr);
       return NS_OK;
 
     // Can't use PR_smprintf for floats, since it's locale-dependent
 #define CASE__APPENDFLOAT_NUMBER(type_, member_)                        \
     case nsIDataType :: type_ :                                         \
     {                                                                   \
         nsAutoCString str;                                              \
         str.AppendFloat(aData.u. member_);                              \
@@ -1338,17 +1338,17 @@ nsVariant::SetFromVariant(nsDiscriminate
     case nsIDataType::VTYPE_INTERFACE:
     case nsIDataType::VTYPE_INTERFACE_IS:
       CASE__SET_FROM_VARIANT_VTYPE_PROLOGUE(VTYPE_INTERFACE_IS);
       // XXX This iid handling is ugly!
       nsIID* iid;
       rv = aValue->GetAsInterface(&iid, (void**)&aData->u.iface.mInterfaceValue);
       if (NS_SUCCEEDED(rv)) {
         aData->u.iface.mInterfaceID = *iid;
-        nsMemory::Free((char*)iid);
+        free((char*)iid);
       }
       CASE__SET_FROM_VARIANT_VTYPE_EPILOGUE(VTYPE_INTERFACE_IS)
 
     case nsIDataType::VTYPE_ARRAY:
       CASE__SET_FROM_VARIANT_VTYPE_PROLOGUE(VTYPE_ARRAY);
       rv = aValue->GetAsArray(&aData->u.array.mArrayType,
                               &aData->u.array.mArrayInterfaceID,
                               &aData->u.array.mArrayCount,
@@ -1623,21 +1623,21 @@ nsVariant::Cleanup(nsDiscriminatedUnion*
     case nsIDataType::VTYPE_CSTRING:
       delete aData->u.mCStringValue;
       break;
     case nsIDataType::VTYPE_UTF8STRING:
       delete aData->u.mUTF8StringValue;
       break;
     case nsIDataType::VTYPE_CHAR_STR:
     case nsIDataType::VTYPE_STRING_SIZE_IS:
-      nsMemory::Free((char*)aData->u.str.mStringValue);
+      free((char*)aData->u.str.mStringValue);
       break;
     case nsIDataType::VTYPE_WCHAR_STR:
     case nsIDataType::VTYPE_WSTRING_SIZE_IS:
-      nsMemory::Free((char*)aData->u.wstr.mWStringValue);
+      free((char*)aData->u.wstr.mWStringValue);
       break;
     case nsIDataType::VTYPE_INTERFACE:
     case nsIDataType::VTYPE_INTERFACE_IS:
       NS_IF_RELEASE(aData->u.iface.mInterfaceValue);
       break;
     case nsIDataType::VTYPE_ARRAY:
       FreeArray(aData);
       break;
--- a/xpcom/glue/nsIClassInfoImpl.h
+++ b/xpcom/glue/nsIClassInfoImpl.h
@@ -133,17 +133,17 @@ private:
     foundInterface = NS_CLASSINFO_NAME(_class);                               \
   } else
 
 #define NS_CLASSINFO_HELPER_BEGIN(_class, _c)                                 \
 NS_IMETHODIMP                                                                 \
 NS_CI_INTERFACE_GETTER_NAME(_class)(uint32_t *count, nsIID ***array)          \
 {                                                                             \
     *count = _c;                                                              \
-    *array = (nsIID **)nsMemory::Alloc(sizeof (nsIID *) * _c);                \
+    *array = (nsIID **)moz_xmalloc(sizeof (nsIID *) * _c);                \
     uint32_t i = 0;
 
 #define NS_CLASSINFO_HELPER_ENTRY(_interface)                                 \
     (*array)[i++] = (nsIID*)nsMemory::Clone(&NS_GET_IID(_interface),          \
                                             sizeof(nsIID));
 
 #define NS_CLASSINFO_HELPER_END                                               \
     MOZ_ASSERT(i == *count, "Incorrent number of entries");                   \
--- a/xpcom/glue/nsMemory.h
+++ b/xpcom/glue/nsMemory.h
@@ -50,42 +50,40 @@ public:
 
   static nsresult   HeapMinimize(bool aImmediate);
   static void*      Clone(const void* aPtr, size_t aSize);
   static nsIMemory* GetGlobalMemoryService();       // AddRefs
 };
 
 /**
  * Macro to free all elements of an XPCOM array of a given size using
- * freeFunc, then frees the array itself using nsMemory::Free().
+ * freeFunc, then frees the array itself using free().
  *
  * Note that this macro (and its wrappers) can be used to deallocate a
  * partially- or completely-built array while unwinding an error
  * condition inside the XPCOM routine that was going to return the
  * array.  For this to work on a partially-built array, your code
  * needs to be building the array from index 0 upwards, and simply
  * pass the number of elements that have already been built (and thus
  * need to be freed) as |size|.
  *
  * Thanks to <alecf@netscape.com> for suggesting this form, which
  * allows the macro to be used with NS_RELEASE / NS_RELEASE_IF in
- * addition to nsMemory::Free.
+ * addition to free.
  *
  * @param size      Number of elements in the array.  If not a constant, this
  *                  should be a int32_t.  Note that this means this macro
  *                  will not work if size >= 2^31.
  * @param array     The array to be freed.
  * @param freeFunc  The function or macro to be used to free it.
  *                  For arrays of nsISupports (or any class derived
  *                  from it), NS_IF_RELEASE (or NS_RELEASE) should be
  *                  passed as freeFunc.  For most (all?) other pointer
  *                  types (including XPCOM strings and wstrings),
- *                  nsMemory::Free should be used, since the
- *                  shared-allocator (nsMemory) is what will have been
- *                  used to allocate the memory.
+ *                  free should be used.
  */
 #define NS_FREE_XPCOM_POINTER_ARRAY(size, array, freeFunc)                    \
     PR_BEGIN_MACRO                                                            \
         int32_t iter_ = int32_t(size);                                        \
         while (--iter_ >= 0)                                                  \
             freeFunc((array)[iter_]);                                         \
         NS_Free((array));                                                     \
     PR_END_MACRO
--- a/xpcom/glue/nsTextFormatter.cpp
+++ b/xpcom/glue/nsTextFormatter.cpp
@@ -598,17 +598,17 @@ BuildArgArray(const char16_t* aFmt, va_l
     }
   }
 
   if (number == 0) {
     return nullptr;
   }
 
   if (number > NAS_DEFAULT_NUM) {
-    nas = (struct NumArgState*)nsMemory::Alloc(number * sizeof(struct NumArgState));
+    nas = (struct NumArgState*)moz_xmalloc(number * sizeof(struct NumArgState));
     if (!nas) {
       *aRv = -1;
       return nullptr;
     }
   } else {
     nas = aNasArray;
   }
 
@@ -1198,20 +1198,20 @@ GrowStuff(SprintfState* aState, const ch
   char16_t* newbase;
   uint32_t newlen;
 
   off = aState->cur - aState->base;
   if (off + aLen >= aState->maxlen) {
     /* Grow the buffer */
     newlen = aState->maxlen + ((aLen > 32) ? aLen : 32);
     if (aState->base) {
-      newbase = (char16_t*)nsMemory::Realloc(aState->base,
-                                             newlen * sizeof(char16_t));
+      newbase = (char16_t*)moz_xrealloc(aState->base,
+                                        newlen * sizeof(char16_t));
     } else {
-      newbase = (char16_t*)nsMemory::Alloc(newlen * sizeof(char16_t));
+      newbase = (char16_t*)moz_xmalloc(newlen * sizeof(char16_t));
     }
     if (!newbase) {
       /* Ran out of memory */
       return -1;
     }
     aState->base = newbase;
     aState->maxlen = newlen;
     aState->cur = aState->base + off;
@@ -1356,11 +1356,11 @@ nsTextFormatter::vsnprintf(char16_t* aOu
 }
 
 /*
  * Free memory allocated, for the caller, by smprintf
  */
 void
 nsTextFormatter::smprintf_free(char16_t* aMem)
 {
-  nsMemory::Free(aMem);
+  free(aMem);
 }
 
--- a/xpcom/glue/nsTextFormatter.h
+++ b/xpcom/glue/nsTextFormatter.h
@@ -48,17 +48,17 @@ public:
    * sprintf into a fixed size buffer. Guarantees that the buffer is null
    * terminated. Returns the length of the written output, NOT including the
    * null terminator, or (uint32_t)-1 if an error occurs.
    */
   static uint32_t snprintf(char16_t* aOut, uint32_t aOutLen,
                            const char16_t* aFmt, ...);
 
   /*
-   * sprintf into a nsMemory::Alloc'd buffer. Return a pointer to
+   * sprintf into a moz_xmalloc'd buffer. Return a pointer to
    * buffer on success, nullptr on failure.
    */
   static char16_t* smprintf(const char16_t* aFmt, ...);
 
   static uint32_t ssprintf(nsAString& aOut, const char16_t* aFmt, ...);
 
   /*
    * va_list forms of the above.
@@ -66,15 +66,15 @@ public:
   static uint32_t vsnprintf(char16_t* aOut, uint32_t aOutLen, const char16_t* aFmt,
                             va_list aAp);
   static char16_t* vsmprintf(const char16_t* aFmt, va_list aAp);
   static uint32_t vssprintf(nsAString& aOut, const char16_t* aFmt, va_list aAp);
 
   /*
    * Free the memory allocated, for the caller, by smprintf.
    * -- Deprecated --
-   * Callers can substitute calling smprintf_free with nsMemory::Free
+   * Callers can substitute calling smprintf_free with free
    */
   static void smprintf_free(char16_t* aMem);
 
 };
 
 #endif /* nsTextFormatter_h___ */
--- a/xpcom/io/nsEscape.cpp
+++ b/xpcom/io/nsEscape.cpp
@@ -99,24 +99,24 @@ nsEscapeCount(const char* aStr, nsEscape
     return 0;
   }
   dstSize += charsToEscape;
   if (dstSize < len) {
     return 0;
   }
 
   // fail if we need more than 4GB
-  // size_t is likely to be long unsigned int but nsMemory::Alloc(size_t)
+  // size_t is likely to be long unsigned int but moz_xmalloc(size_t)
   // calls NS_Alloc_P(size_t) which calls PR_Malloc(uint32_t), so there is
-  // no chance to allocate more than 4GB using nsMemory::Alloc()
+  // no chance to allocate more than 4GB using moz_xmalloc()
   if (dstSize > UINT32_MAX) {
     return 0;
   }
 
-  char* result = (char*)nsMemory::Alloc(dstSize);
+  char* result = (char*)moz_xmalloc(dstSize);
   if (!result) {
     return 0;
   }
 
   unsigned char* dst = (unsigned char*)result;
   src = (const unsigned char*)aStr;
   if (aFlags == url_XPAlphas) {
     for (size_t i = 0; i < len; ++i) {
@@ -286,17 +286,17 @@ nsEscapeHTML2(const char16_t* aSourceBuf
   }
 
   /* XXX Hardcoded max entity len. */
   if (uint32_t(aSourceBufferLen) >=
       ((UINT32_MAX - sizeof(char16_t)) / (6 * sizeof(char16_t)))) {
     return nullptr;
   }
 
-  char16_t* resultBuffer = (char16_t*)nsMemory::Alloc(
+  char16_t* resultBuffer = (char16_t*)moz_xmalloc(
     aSourceBufferLen * 6 * sizeof(char16_t) + sizeof(char16_t('\0')));
   char16_t* ptr = resultBuffer;
 
   if (resultBuffer) {
     int32_t i;
 
     for (i = 0; i < aSourceBufferLen; ++i) {
       if (aSourceBuffer[i] == '<') {
--- a/xpcom/io/nsIStringStream.idl
+++ b/xpcom/io/nsIStringStream.idl
@@ -32,17 +32,17 @@ interface nsIStringInputStream : nsIInpu
 
     /**
      * NOTE: the following methods are designed to give C++ code added control
      * over the ownership and lifetime of the stream data.  Use with care :-)
      */
 
     /**
      * AdoptData - assign data to the input stream.  the input stream takes
-     * ownership of the given data buffer and will nsMemory::Free it when
+     * ownership of the given data buffer and will free it when
      * the input stream is destroyed.
      *
      * @param data      - stream data
      * @param dataLen   - stream data length (-1 if length should be computed)
      */
     [noscript] void adoptData(in charPtr data, in long dataLen);
 
     /**
--- a/xpcom/io/nsLinebreakConverter.cpp
+++ b/xpcom/io/nsLinebreakConverter.cpp
@@ -95,31 +95,31 @@ ConvertBreaks(const T* aInSrc, int32_t& 
               const char* aDestBreak)
 {
   NS_ASSERTION(aInSrc && aSrcBreak && aDestBreak, "Got a null string");
 
   T* resultString = nullptr;
 
   // handle the no conversion case
   if (nsCRT::strcmp(aSrcBreak, aDestBreak) == 0) {
-    resultString = (T*)nsMemory::Alloc(sizeof(T) * aIoLen);
+    resultString = (T*)moz_xmalloc(sizeof(T) * aIoLen);
     if (!resultString) {
       return nullptr;
     }
     memcpy(resultString, aInSrc, sizeof(T) * aIoLen); // includes the null, if any
     return resultString;
   }
 
   int32_t srcBreakLen = strlen(aSrcBreak);
   int32_t destBreakLen = strlen(aDestBreak);
 
   // handle the easy case, where the string length does not change, and the
   // breaks are only 1 char long, i.e. CR <-> LF
   if (srcBreakLen == destBreakLen && srcBreakLen == 1) {
-    resultString = (T*)nsMemory::Alloc(sizeof(T) * aIoLen);
+    resultString = (T*)moz_xmalloc(sizeof(T) * aIoLen);
     if (!resultString) {
       return nullptr;
     }
 
     const T* src = aInSrc;
     const T* srcEnd = aInSrc + aIoLen;  // includes null, if any
     T* dst = resultString;
 
@@ -139,17 +139,17 @@ ConvertBreaks(const T* aInSrc, int32_t& 
   } else {
     // src and dest termination is different length. Do it a slower way.
 
     // count linebreaks in src. Assumes that chars in 2-char linebreaks are unique.
     int32_t numLinebreaks = CountLinebreaks(aInSrc, aIoLen, aSrcBreak);
 
     int32_t newBufLen =
       aIoLen - (numLinebreaks * srcBreakLen) + (numLinebreaks * destBreakLen);
-    resultString = (T*)nsMemory::Alloc(sizeof(T) * newBufLen);
+    resultString = (T*)moz_xmalloc(sizeof(T) * newBufLen);
     if (!resultString) {
       return nullptr;
     }
 
     const T* src = aInSrc;
     const T* srcEnd = aInSrc + aIoLen;  // includes null, if any
     T* dst = resultString;
 
@@ -230,17 +230,17 @@ ConvertUnknownBreaks(const T* aInSrc, in
       // Lone LF
       finalLen += destBreakLen;
     } else {
       finalLen++;
     }
     src++;
   }
 
-  T* resultString = (T*)nsMemory::Alloc(sizeof(T) * finalLen);
+  T* resultString = (T*)moz_xmalloc(sizeof(T) * finalLen);
   if (!resultString) {
     return nullptr;
   }
 
   src = aInSrc;
   srcEnd = aInSrc + aIoLen;  // includes null, if any
 
   T* dst = resultString;
--- a/xpcom/io/nsLocalFileUnix.cpp
+++ b/xpcom/io/nsLocalFileUnix.cpp
@@ -1760,23 +1760,23 @@ nsLocalFile::GetNativeTarget(nsACString&
     return NSRESULT_FOR_ERRNO();
   }
 
   if (!S_ISLNK(symStat.st_mode)) {
     return NS_ERROR_FILE_INVALID_PATH;
   }
 
   int32_t size = (int32_t)symStat.st_size;
-  char* target = (char*)nsMemory::Alloc(size + 1);
+  char* target = (char*)moz_xmalloc(size + 1);
   if (!target) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   if (readlink(mPath.get(), target, (size_t)size) < 0) {
-    nsMemory::Free(target);
+    free(target);
     return NSRESULT_FOR_ERRNO();
   }
   target[size] = '\0';
 
   nsresult rv = NS_OK;
   nsCOMPtr<nsIFile> self(this);
   int32_t maxLinks = 40;
   while (true) {
@@ -1811,34 +1811,34 @@ nsLocalFile::GetNativeTarget(nsACString&
 
     // And of course we're done if it isn't a symlink.
     if (!S_ISLNK(symStat.st_mode)) {
       break;
     }
 
     int32_t newSize = (int32_t)symStat.st_size;
     if (newSize > size) {
-      char* newTarget = (char*)nsMemory::Realloc(target, newSize + 1);
+      char* newTarget = (char*)moz_xrealloc(target, newSize + 1);
       if (!newTarget) {
         rv = NS_ERROR_OUT_OF_MEMORY;
         break;
       }
       target = newTarget;
       size = newSize;
     }
 
     int32_t linkLen = readlink(flatRetval.get(), target, size);
     if (linkLen == -1) {
       rv = NSRESULT_FOR_ERRNO();
       break;
     }
     target[linkLen] = '\0';
   }
 
-  nsMemory::Free(target);
+  free(target);
 
   if (NS_FAILED(rv)) {
     aResult.Truncate();
   }
   return rv;
 }
 
 NS_IMETHODIMP
--- a/xpcom/io/nsScriptableInputStream.cpp
+++ b/xpcom/io/nsScriptableInputStream.cpp
@@ -60,17 +60,17 @@ nsScriptableInputStream::Read(uint32_t a
     XPCOM_MIN((uint32_t)XPCOM_MIN<uint64_t>(count64, aCount), UINT32_MAX - 1);
   buffer = (char*)malloc(count + 1);  // make room for '\0'
   if (!buffer) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   rv = ReadHelper(buffer, count);
   if (NS_FAILED(rv)) {
-    nsMemory::Free(buffer);
+    free(buffer);
     return rv;
   }
 
   buffer[count] = '\0';
   *aResult = buffer;
   return NS_OK;
 }
 
--- a/xpcom/io/nsSegmentedBuffer.cpp
+++ b/xpcom/io/nsSegmentedBuffer.cpp
@@ -27,27 +27,27 @@ char*
 nsSegmentedBuffer::AppendNewSegment()
 {
   if (GetSize() >= mMaxSize) {
     return nullptr;
   }
 
   if (!mSegmentArray) {
     uint32_t bytes = mSegmentArrayCount * sizeof(char*);
-    mSegmentArray = (char**)nsMemory::Alloc(bytes);
+    mSegmentArray = (char**)moz_xmalloc(bytes);
     if (!mSegmentArray) {
       return nullptr;
     }
     memset(mSegmentArray, 0, bytes);
   }
 
   if (IsFull()) {
     uint32_t newArraySize = mSegmentArrayCount * 2;
     uint32_t bytes = newArraySize * sizeof(char*);
-    char** newSegArray = (char**)nsMemory::Realloc(mSegmentArray, bytes);
+    char** newSegArray = (char**)moz_xrealloc(mSegmentArray, bytes);
     if (!newSegArray) {
       return nullptr;
     }
     mSegmentArray = newSegArray;
     // copy wrapped content to new extension
     if (mFirstSegmentIndex > mLastSegmentIndex) {
       // deal with wrap around case
       memcpy(&mSegmentArray[mSegmentArrayCount],
@@ -117,17 +117,17 @@ void
 nsSegmentedBuffer::Empty()
 {
   if (mSegmentArray) {
     for (uint32_t i = 0; i < mSegmentArrayCount; i++) {
       if (mSegmentArray[i]) {
         free(mSegmentArray[i]);
       }
     }
-    nsMemory::Free(mSegmentArray);
+    free(mSegmentArray);
     mSegmentArray = nullptr;
   }
   mSegmentArrayCount = NS_SEGMENTARRAY_INITIAL_COUNT;
   mFirstSegmentIndex = mLastSegmentIndex = 0;
 }
 
 #if 0
 void
--- a/xpcom/reflect/xptcall/tests/TestXPTCInvoke.cpp
+++ b/xpcom/reflect/xptcall/tests/TestXPTCInvoke.cpp
@@ -292,17 +292,17 @@ InvokeTestTarget::AddMixedInts3(int64_t 
     *retval = p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10;
     return NS_OK;
 }
 
 NS_IMETHODIMP
 InvokeTestTarget::PassTwoStrings(const char* s1, const char* s2, char** retval)
 {
     const char milk[] = "milk";
-    char *ret = (char*)nsMemory::Alloc(sizeof(milk));
+    char *ret = (char*)moz_xmalloc(sizeof(milk));
     if (!ret)
       return NS_ERROR_OUT_OF_MEMORY;
     strncpy(ret, milk, sizeof(milk));
     printf("\t%s %s", s1, s2);
     *retval = ret;
     return NS_OK;
 }
 
@@ -398,17 +398,17 @@ int main()
 
      if(NS_SUCCEEDED(test->AddMixedFloats(1,2,3,4,5,6,7,8,9,10,11,&outD)))
          printf("\t1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 = %f\n", (double)outD);
      else
          printf("\tFAILED");
 
      if (NS_SUCCEEDED(test->PassTwoStrings("moo","cow",&outS))) {
        printf(" = %s\n", outS);
-        nsMemory::Free(outS);
+        free(outS);
       } else
         printf("\tFAILED");
 
      failed_rv = test->ShouldFail(5);
      printf("should fail %s, returned %x\n", failed_rv == NS_ERROR_NULL_POINTER ? "failed" :"passed", failed_rv);
     
     printf("calling via invoke:\n");
 
--- a/xpcom/string/nsReadableUtils.cpp
+++ b/xpcom/string/nsReadableUtils.cpp
@@ -270,25 +270,25 @@ AppendUTF8toUTF16(const char* aSource, n
   }
 }
 
 
 /**
  * A helper function that allocates a buffer of the desired character type big enough to hold a copy of the supplied string (plus a zero terminator).
  *
  * @param aSource an string you will eventually be making a copy of
- * @return a new buffer (of the type specified by the second parameter) which you must free with |nsMemory::Free|.
+ * @return a new buffer (of the type specified by the second parameter) which you must free with |free|.
  *
  */
 template <class FromStringT, class ToCharT>
 inline
 ToCharT*
 AllocateStringCopy(const FromStringT& aSource, ToCharT*)
 {
-  return static_cast<ToCharT*>(nsMemory::Alloc(
+  return static_cast<ToCharT*>(moz_xmalloc(
     (aSource.Length() + 1) * sizeof(ToCharT)));
 }
 
 
 char*
 ToNewCString(const nsAString& aSource)
 {
   char* result = AllocateStringCopy(aSource, (char*)0);
@@ -311,17 +311,17 @@ ToNewUTF8String(const nsAString& aSource
   copy_string(aSource.BeginReading(start), aSource.EndReading(end),
               calculator);
 
   if (aUTF8Count) {
     *aUTF8Count = calculator.Size();
   }
 
   char* result = static_cast<char*>
-                 (nsMemory::Alloc(calculator.Size() + 1));
+                 (moz_xmalloc(calculator.Size() + 1));
   if (!result) {
     return nullptr;
   }
 
   ConvertUTF16toUTF8 converter(result);
   copy_string(aSource.BeginReading(start), aSource.EndReading(end),
               converter).write_terminator();
   NS_ASSERTION(calculator.Size() == converter.Size(), "length mismatch");
@@ -403,17 +403,17 @@ UTF8ToUnicodeBuffer(const nsACString& aS
   return aBuffer;
 }
 
 char16_t*
 UTF8ToNewUnicode(const nsACString& aSource, uint32_t* aUTF16Count)
 {
   const uint32_t length = CalcUTF8ToUnicodeLength(aSource);
   const size_t buffer_size = (length + 1) * sizeof(char16_t);
-  char16_t* buffer = static_cast<char16_t*>(nsMemory::Alloc(buffer_size));
+  char16_t* buffer = static_cast<char16_t*>(moz_xmalloc(buffer_size));
   if (!buffer) {
     return nullptr;
   }
 
   uint32_t copied;
   UTF8ToUnicodeBuffer(aSource, buffer, &copied);
   NS_ASSERTION(length == copied, "length mismatch");
 
--- a/xpcom/string/nsReadableUtils.h
+++ b/xpcom/string/nsReadableUtils.h
@@ -77,81 +77,81 @@ inline void AppendUTF16toUTF8(char16ptr_
 {
   return AppendUTF16toUTF8(static_cast<const char16_t*>(aSource), aDest);
 }
 #endif
 
 /**
  * Returns a new |char| buffer containing a zero-terminated copy of |aSource|.
  *
- * Allocates and returns a new |char| buffer which you must free with |nsMemory::Free|.
+ * Allocates and returns a new |char| buffer which you must free with |free|.
  * Performs a lossy encoding conversion by chopping 16-bit wide characters down to 8-bits wide while copying |aSource| to your new buffer.
  * This conversion is not well defined; but it reproduces legacy string behavior.
  * The new buffer is zero-terminated, but that may not help you if |aSource| contains embedded nulls.
  *
  * @param aSource a 16-bit wide string
- * @return a new |char| buffer you must free with |nsMemory::Free|.
+ * @return a new |char| buffer you must free with |free|.
  */
 char* ToNewCString(const nsAString& aSource);
 
 
 /**
  * Returns a new |char| buffer containing a zero-terminated copy of |aSource|.
  *
- * Allocates and returns a new |char| buffer which you must free with |nsMemory::Free|.
+ * Allocates and returns a new |char| buffer which you must free with |free|.
  * The new buffer is zero-terminated, but that may not help you if |aSource| contains embedded nulls.
  *
  * @param aSource an 8-bit wide string
- * @return a new |char| buffer you must free with |nsMemory::Free|.
+ * @return a new |char| buffer you must free with |free|.
  */
 char* ToNewCString(const nsACString& aSource);
 
 /**
  * Returns a new |char| buffer containing a zero-terminated copy of |aSource|.
  *
  * Allocates and returns a new |char| buffer which you must free with
- * |nsMemory::Free|.
+ * |free|.
  * Performs an encoding conversion from a UTF-16 string to a UTF-8 string
  * copying |aSource| to your new buffer.
  * The new buffer is zero-terminated, but that may not help you if |aSource|
  * contains embedded nulls.
  *
  * @param aSource a UTF-16 string (made of char16_t's)
  * @param aUTF8Count the number of 8-bit units that was returned
- * @return a new |char| buffer you must free with |nsMemory::Free|.
+ * @return a new |char| buffer you must free with |free|.
  */
 
 char* ToNewUTF8String(const nsAString& aSource, uint32_t* aUTF8Count = nullptr);
 
 
 /**
  * Returns a new |char16_t| buffer containing a zero-terminated copy of
  * |aSource|.
  *
  * Allocates and returns a new |char16_t| buffer which you must free with
- * |nsMemory::Free|.
+ * |free|.
  * The new buffer is zero-terminated, but that may not help you if |aSource|
  * contains embedded nulls.
  *
  * @param aSource a UTF-16 string
- * @return a new |char16_t| buffer you must free with |nsMemory::Free|.
+ * @return a new |char16_t| buffer you must free with |free|.
  */
 char16_t* ToNewUnicode(const nsAString& aSource);
 
 
 /**
  * Returns a new |char16_t| buffer containing a zero-terminated copy of |aSource|.
  *
- * Allocates and returns a new |char16_t| buffer which you must free with |nsMemory::Free|.
+ * Allocates and returns a new |char16_t| buffer which you must free with |free|.
  * Performs an encoding conversion by 0-padding 8-bit wide characters up to 16-bits wide while copying |aSource| to your new buffer.
  * This conversion is not well defined; but it reproduces legacy string behavior.
  * The new buffer is zero-terminated, but that may not help you if |aSource| contains embedded nulls.
  *
  * @param aSource an 8-bit wide string (a C-string, NOT UTF-8)
- * @return a new |char16_t| buffer you must free with |nsMemory::Free|.
+ * @return a new |char16_t| buffer you must free with |free|.
  */
 char16_t* ToNewUnicode(const nsACString& aSource);
 
 /**
  * Returns the required length for a char16_t buffer holding
  * a copy of aSource, using UTF-8 to UTF-16 conversion.
  * The length does NOT include any space for zero-termination.
  *
@@ -182,24 +182,24 @@ char16_t* UTF8ToUnicodeBuffer(const nsAC
                               char16_t* aBuffer,
                               uint32_t* aUTF16Count = nullptr);
 
 /**
  * Returns a new |char16_t| buffer containing a zero-terminated copy
  * of |aSource|.
  *
  * Allocates and returns a new |char| buffer which you must free with
- * |nsMemory::Free|.  Performs an encoding conversion from UTF-8 to UTF-16
+ * |free|.  Performs an encoding conversion from UTF-8 to UTF-16
  * while copying |aSource| to your new buffer.  This conversion is well defined
  * for a valid UTF-8 string.  The new buffer is zero-terminated, but that
  * may not help you if |aSource| contains embedded nulls.
  *
  * @param aSource an 8-bit wide string, UTF-8 encoded
  * @param aUTF16Count the number of 16-bit units that was returned
- * @return a new |char16_t| buffer you must free with |nsMemory::Free|.
+ * @return a new |char16_t| buffer you must free with |free|.
  *         (UTF-16 encoded)
  */
 char16_t* UTF8ToNewUnicode(const nsACString& aSource,
                            uint32_t* aUTF16Count = nullptr);
 
 /**
  * Copies |aLength| 16-bit code units from the start of |aSource| to the
  * |char16_t| buffer |aDest|.
--- a/xpcom/string/nsSubstring.cpp
+++ b/xpcom/string/nsSubstring.cpp
@@ -107,17 +107,17 @@ static nsStringStats gStringStats;
 // ---------------------------------------------------------------------------
 
 void
 ReleaseData(void* aData, uint32_t aFlags)
 {
   if (aFlags & nsSubstring::F_SHARED) {
     nsStringBuffer::FromData(aData)->Release();
   } else if (aFlags & nsSubstring::F_OWNED) {
-    nsMemory::Free(aData);
+    free(aData);
     STRING_STAT_INCREMENT(AdoptFree);
 #ifdef NS_BUILD_REFCNT_LOGGING
     // Treat this as destruction of a "StringAdopt" object for leak
     // tracking purposes.
     NS_LogDtor(aData, "StringAdopt", 1);
 #endif // NS_BUILD_REFCNT_LOGGING
   }
   // otherwise, nothing to do.
--- a/xpcom/string/nsTSubstring.h
+++ b/xpcom/string/nsTSubstring.h
@@ -1101,17 +1101,17 @@ public:
   //   "shared buffer"       A shared buffer is one that the string class
   //                         allocates.  When it allocates a shared string
   //                         buffer, it allocates some additional space at
   //                         the beginning of the buffer for additional
   //                         fields, including a reference count and a
   //                         buffer length.  See nsStringHeader.
   //
   //   "adopted buffer"      An adopted buffer is a raw string buffer
-  //                         allocated on the heap (using nsMemory::Alloc)
+  //                         allocated on the heap (using moz_xmalloc)
   //                         of which the string class subsumes ownership.
   //
   // Some comments about the string flags:
   //
   //   F_SHARED, F_OWNED, and F_FIXED are all mutually exlusive.  They
   //   indicate the allocation type of mData.  If none of these flags
   //   are set, then the string buffer is dependent.
   //
--- a/xpcom/string/nsXPCOMStrings.h
+++ b/xpcom/string/nsXPCOMStrings.h
@@ -233,17 +233,17 @@ XPCOM_API(uint32_t) NS_StringGetMutableD
 /**
  * NS_StringCloneData
  *
  * This function returns a null-terminated copy of the string's
  * internal buffer.
  *
  * @param aStr          abstract string reference
  * @return              null-terminated copy of the string's internal buffer
- *                      (it must be free'd using using nsMemory::Free)
+ *                      (it must be free'd using using free)
  */
 XPCOM_API(char16_t*) NS_StringCloneData(const nsAString& aStr);
 
 /**
  * NS_StringSetData
  *
  * This function copies aData into aStr.
  *
@@ -529,17 +529,17 @@ XPCOM_API(uint32_t) NS_CStringGetMutable
 /**
  * NS_CStringCloneData
  *
  * This function returns a null-terminated copy of the string's
  * internal buffer.
  *
  * @param aStr          abstract string reference
  * @return              null-terminated copy of the string's internal buffer
- *                      (it must be free'd using using nsMemory::Free)
+ *                      (it must be free'd using using free)
  */
 XPCOM_API(char*) NS_CStringCloneData(const nsACString& aStr);
 
 /**
  * NS_CStringSetData
  *
  * This function copies aData into aStr.
  *
--- a/xpcom/tests/gtest/TestStrings.cpp
+++ b/xpcom/tests/gtest/TestStrings.cpp
@@ -126,40 +126,40 @@ TEST(Strings, findinreadable)
                              delim_end   (end);
 
   // Search for last !/ at the end of the string
   EXPECT_TRUE(FindInReadable(NS_LITERAL_CSTRING("!/"), delim_begin, delim_end));
   char *r = ToNewCString(Substring(delim_begin, delim_end));
   // Should match the first "!/" but not the last
   EXPECT_NE(delim_end, end);
   EXPECT_STREQ(r, "!/");
-  nsMemory::Free(r);
+  free(r);
 
   delim_begin = begin;
   delim_end = end;
 
   // Search for first jar:
   EXPECT_TRUE(FindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end));
 
   r = ToNewCString(Substring(delim_begin, delim_end));
   // Should not match the first jar:, but the second one
   EXPECT_EQ(delim_begin, begin);
   EXPECT_STREQ(r, "jar:");
-  nsMemory::Free(r);
+  free(r);
 
   // Search for jar: in a Substring
   delim_begin = begin; delim_begin++;
   delim_end = end;
   EXPECT_TRUE(FindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end));
 
   r = ToNewCString(Substring(delim_begin, delim_end));
   // Should not match the first jar:, but the second one
   EXPECT_NE(delim_begin, begin);
   EXPECT_STREQ(r, "jar:");
-  nsMemory::Free(r);
+  free(r);
 
   // Should not find a match
   EXPECT_FALSE(FindInReadable(NS_LITERAL_CSTRING("gecko"), delim_begin, delim_end));
 
   // When no match is found, range should be empty
   EXPECT_EQ(delim_begin, delim_end);
 
   // Should not find a match (search not beyond Substring)
@@ -191,40 +191,40 @@ TEST(Strings, rfindinreadable)
                              delim_end   (end);
 
   // Search for last !/ at the end of the string
   EXPECT_TRUE(RFindInReadable(NS_LITERAL_CSTRING("!/"), delim_begin, delim_end));
   char *r = ToNewCString(Substring(delim_begin, delim_end));
   // Should match the last "!/"
   EXPECT_EQ(delim_end, end);
   EXPECT_STREQ(r, "!/");
-  nsMemory::Free(r);
+  free(r);
 
   delim_begin = begin;
   delim_end = end;
 
   // Search for last jar: but not the first one...
   EXPECT_TRUE(RFindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end));
 
   r = ToNewCString(Substring(delim_begin, delim_end));
   // Should not match the first jar:, but the second one
   EXPECT_NE(delim_begin, begin);
   EXPECT_STREQ(r, "jar:");
-  nsMemory::Free(r);
+  free(r);
 
   // Search for jar: in a Substring
   delim_begin = begin;
   delim_end = begin; for (int i=0;i<6;i++) delim_end++;
   EXPECT_TRUE(RFindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end));
 
   r = ToNewCString(Substring(delim_begin, delim_end));
   // Should not match the first jar:, but the second one
   EXPECT_EQ(delim_begin, begin);
   EXPECT_STREQ(r, "jar:");
-  nsMemory::Free(r);
+  free(r);
 
   // Should not find a match
   delim_begin = begin;
   delim_end = end;
   EXPECT_FALSE(RFindInReadable(NS_LITERAL_CSTRING("gecko"), delim_begin, delim_end));
 
   // When no match is found, range should be empty
   EXPECT_EQ(delim_begin, delim_end);
@@ -467,17 +467,17 @@ TEST(Strings, xpidl_string)
   EXPECT_STREQ(a, b);
 
   a.Adopt(0);
   nsACString::const_iterator begin, end;
   a.BeginReading(begin);
   a.EndReading(end);
   char *r = ToNewCString(Substring(begin, end));
   EXPECT_STREQ(r, "");
-  nsMemory::Free(r);
+  free(r);
 
   a.Adopt(0);
   EXPECT_TRUE(a.IsVoid());
 
   int32_t index = a.FindCharInSet("xyz");
   EXPECT_EQ(index, kNotFound);
 }
 
--- a/xpfe/appshell/nsWebShellWindow.cpp
+++ b/xpfe/appshell/nsWebShellWindow.cpp
@@ -657,17 +657,17 @@ void nsWebShellWindow::LoadContentAreas(
           if (urlChar) {
             nsUnescape(urlChar);
             contentURL.AssignWithConversion(urlChar);
             webNav->LoadURI(contentURL.get(),
                           nsIWebNavigation::LOAD_FLAGS_NONE,
                           nullptr,
                           nullptr,
                           nullptr);
-            nsMemory::Free(urlChar);
+            free(urlChar);
           }
         }
       }
     }
   }
 }
 
 /**