Bug 1134923 - Remove NS_Alloc/NS_Realloc/NS_Free. r=nfroyd
authorMike Hommey <mh+mozilla@glandium.org>
Wed, 01 Apr 2015 14:29:55 +0900
changeset 271790 7bc6ca1495610504491cc2c0634441a9b8abd873
parent 271789 efa98fd2a0450d3355ff5ae233aba3cb52dfe628
child 271791 35dfb84cc70f937cf359de009a84fe551862ed3d
push id4830
push userjlund@mozilla.com
push dateMon, 29 Jun 2015 20:18:48 +0000
treeherdermozilla-beta@4c2175bb0420 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersnfroyd
bugs1134923
milestone40.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1134923 - Remove NS_Alloc/NS_Realloc/NS_Free. r=nfroyd They are kept around for the sake of the standalone glue, which is used for e.g. webapprt, which doesn't have direct access to jemalloc, and thus still needs a wrapper to go through the xpcom function list and get to jemalloc from there.
dom/base/Crypto.cpp
dom/fetch/Fetch.cpp
dom/html/HTMLInputElement.cpp
dom/html/UndoManager.cpp
dom/indexedDB/ActorsParent.cpp
dom/ipc/ContentParent.cpp
dom/json/nsJSON.cpp
dom/media/MediaDevices.cpp
dom/media/MediaPermissionGonk.cpp
dom/media/VideoUtils.cpp
dom/plugins/base/PluginPRLibrary.cpp
dom/plugins/base/nsNPAPIPlugin.cpp
dom/plugins/base/nsNPAPIPluginInstance.cpp
dom/plugins/base/nsPluginHost.cpp
dom/plugins/base/nsPluginsDirDarwin.cpp
dom/plugins/ipc/PluginModuleChild.cpp
dom/tv/FakeTVService.cpp
dom/tv/TVTypes.cpp
dom/xbl/nsXBLProtoImplField.cpp
editor/libeditor/ChangeStyleTxn.cpp
editor/libeditor/nsHTMLDataTransfer.cpp
editor/libeditor/nsHTMLEditor.cpp
editor/libeditor/nsPlaintextDataTransfer.cpp
editor/libeditor/nsPlaintextEditor.cpp
editor/txmgr/nsTransactionList.cpp
embedding/components/commandhandler/nsControllerCommandTable.cpp
extensions/spellcheck/hunspell/src/mozHunspell.cpp
gfx/thebes/gfxDWriteFontList.cpp
gfx/thebes/gfxFT2FontList.cpp
gfx/thebes/gfxGDIFontList.cpp
gfx/thebes/gfxMacPlatformFontList.mm
gfx/thebes/gfxPangoFonts.cpp
gfx/thebes/gfxPlatform.cpp
gfx/thebes/gfxPlatformFontList.h
gfx/thebes/gfxPlatformMac.cpp
gfx/thebes/gfxUserFontSet.cpp
gfx/thebes/gfxUserFontSet.h
image/decoders/icon/android/nsIconChannel.cpp
image/decoders/icon/gtk/nsIconChannel.cpp
image/decoders/icon/qt/nsIconChannel.cpp
intl/uconv/nsTextToSubURI.cpp
js/xpconnect/loader/mozJSComponentLoader.h
js/xpconnect/src/XPCJSID.cpp
js/xpconnect/src/XPCWrappedJS.cpp
js/xpconnect/src/XPCWrappedJSClass.cpp
js/xpconnect/tests/components/native/xpctest_params.cpp
layout/base/nsPresShell.cpp
layout/inspector/inDOMUtils.cpp
layout/printing/nsPrintData.cpp
layout/style/FontFace.cpp
layout/style/FontFaceSet.cpp
layout/style/StyleRule.cpp
layout/style/StyleRule.h
layout/style/nsStyleStruct.cpp
memory/replace/dmd/dmd.py
modules/libpref/Preferences.cpp
netwerk/base/nsStandardURL.cpp
netwerk/cache/nsDiskCacheDeviceSQL.cpp
netwerk/protocol/websocket/WebSocketChannel.cpp
netwerk/streamconv/converters/nsDirIndexParser.cpp
parser/html/nsParserUtils.cpp
rdf/base/nsInMemoryDataSource.cpp
rdf/base/nsRDFContentSink.cpp
rdf/datasource/nsFileSystemDataSource.cpp
security/manager/ssl/src/nsNSSCallbacks.cpp
security/manager/ssl/src/nsRandomGenerator.cpp
storage/public/mozIStorageBindingParams.idl
storage/src/Variant.h
storage/src/mozStorageBindingParams.cpp
storage/src/mozStorageConnection.cpp
storage/src/variantToSQLiteT_impl.h
toolkit/components/commandlines/nsCommandLine.cpp
toolkit/components/filepicker/nsFileView.cpp
toolkit/components/parentalcontrols/nsParentalControlsServiceWin.cpp
toolkit/components/places/nsAnnoProtocolHandler.cpp
toolkit/components/places/nsNavHistoryQuery.cpp
toolkit/crashreporter/mac_utils.mm
toolkit/crashreporter/nsExceptionHandler.cpp
toolkit/xre/nsAppRunner.cpp
toolkit/xre/nsConsoleWriter.cpp
uriloader/exthandler/android/nsExternalSharingAppService.cpp
uriloader/exthandler/nsExternalHelperAppService.cpp
widget/cocoa/nsPrintDialogX.mm
widget/windows/nsFilePicker.cpp
xpcom/base/nsCycleCollector.cpp
xpcom/base/nsIMemory.idl
xpcom/base/nsMemoryImpl.cpp
xpcom/base/nsUUIDGenerator.cpp
xpcom/build/FrozenFunctions.cpp
xpcom/build/PoisonIOInterposerMac.cpp
xpcom/build/PoisonIOInterposerWin.cpp
xpcom/build/XPCOMInit.cpp
xpcom/build/nsXPCOM.h
xpcom/build/nsXREAppData.h
xpcom/components/nsCategoryManager.cpp
xpcom/components/nsComponentManager.cpp
xpcom/ds/nsVariant.cpp
xpcom/io/nsBinaryStream.cpp
xpcom/io/nsEscape.cpp
xpcom/io/nsWildCard.cpp
xpcom/string/nsTString.h
xpcom/tests/external/TestMinStringAPI.cpp
xpcom/tests/gtest/TestEncoding.cpp
xpcom/threads/nsProcessCommon.cpp
--- a/dom/base/Crypto.cpp
+++ b/dom/base/Crypto.cpp
@@ -105,17 +105,17 @@ Crypto::GetRandomValues(JSContext* aCx, 
     uint8_t *buf = GetRandomValues(dataLen);
 
     if (!buf) {
       aRv.Throw(NS_ERROR_FAILURE);
       return;
     }
 
     memcpy(data, buf, dataLen);
-    NS_Free(buf);
+    free(buf);
   }
 
   aRetval.set(view);
 }
 
 SubtleCrypto*
 Crypto::Subtle()
 {
--- a/dom/fetch/Fetch.cpp
+++ b/dom/fetch/Fetch.cpp
@@ -753,17 +753,17 @@ private:
     NS_ConvertUTF8toUTF16 name(mName);
 
     if (mFilename.IsVoid()) {
       mFormData->Append(name, NS_ConvertUTF8toUTF16(body));
     } else {
       // Unfortunately we've to copy the data first since all our strings are
       // going to free it. We also need fallible alloc, so we can't just use
       // ToNewCString().
-      char* copy = static_cast<char*>(NS_Alloc(body.Length()));
+      char* copy = static_cast<char*>(moz_xmalloc(body.Length()));
       if (!copy) {
         NS_WARNING("Failed to copy File entry body.");
         return false;
       }
       nsCString::const_iterator bodyIter, bodyEnd;
       body.BeginReading(bodyIter);
       body.EndReading(bodyEnd);
       char *p = copy;
--- a/dom/html/HTMLInputElement.cpp
+++ b/dom/html/HTMLInputElement.cpp
@@ -2318,17 +2318,17 @@ HTMLInputElement::MozGetFileNameArray(ui
     return NS_ERROR_DOM_SECURITY_ERR;
   }
 
   nsTArray<nsString> array;
   MozGetFileNameArray(array);
 
   *aLength = array.Length();
   char16_t** ret =
-    static_cast<char16_t**>(NS_Alloc(*aLength * sizeof(char16_t*)));
+    static_cast<char16_t**>(moz_xmalloc(*aLength * sizeof(char16_t*)));
   if (!ret) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   for (uint32_t i = 0; i < *aLength; ++i) {
     ret[i] = NS_strdup(array[i].get());
   }
 
--- a/dom/html/UndoManager.cpp
+++ b/dom/html/UndoManager.cpp
@@ -1023,17 +1023,17 @@ UndoManager::ItemInternal(uint32_t aInde
     aRv.Throw(rv);
     return;
   }
 
   for (uint32_t i = 0; i < listDataLength; i++) {
     aItems.AppendElement(static_cast<DOMTransaction*>(listData[i]));
     NS_RELEASE(listData[i]);
   }
-  NS_Free(listData);
+  free(listData);
 }
 
 void
 UndoManager::Item(uint32_t aIndex,
                   Nullable<nsTArray<nsRefPtr<DOMTransaction> > >& aItems,
                   ErrorResult& aRv)
 {
   int32_t numRedo;
--- a/dom/indexedDB/ActorsParent.cpp
+++ b/dom/indexedDB/ActorsParent.cpp
@@ -21263,18 +21263,16 @@ ObjectStoreAddOrPutRequestOp::DoDatabase
     reinterpret_cast<const char*>(mParams.cloneInfo().data().Elements());
   size_t uncompressedLength = mParams.cloneInfo().data().Length();
 
   // We don't have a smart pointer class that calls free, so we need to
   // manage | compressed | manually.
   {
     size_t compressedLength = snappy::MaxCompressedLength(uncompressedLength);
 
-    // malloc is equivalent to NS_Alloc, which we use because mozStorage
-    // expects to be able to free the adopted pointer with NS_Free.
     char* compressed = static_cast<char*>(malloc(compressedLength));
     if (NS_WARN_IF(!compressed)) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
 
     snappy::RawCompress(uncompressed, uncompressedLength, compressed,
                         &compressedLength);
 
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -4044,17 +4044,17 @@ ContentParent::RecvGetRandomValues(const
         return true;
     }
 
     randomValues->SetCapacity(length);
     randomValues->SetLength(length);
 
     memcpy(randomValues->Elements(), buf, length);
 
-    NS_Free(buf);
+    free(buf);
 
     return true;
 }
 
 bool
 ContentParent::RecvGetSystemMemory(const uint64_t& aGetterId)
 {
     uint32_t memoryTotal = 0;
--- a/dom/json/nsJSON.cpp
+++ b/dom/json/nsJSON.cpp
@@ -339,25 +339,25 @@ nsJSONWriter::WriteToStream(nsIOutputStr
   uint32_t bytesWritten;
 
   // The bytes written to the stream might differ from the char16_t size
   int32_t aDestLength;
   rv = encoder->GetMaxLength(aBuffer, srcLength, &aDestLength);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // create the buffer we need
-  char* destBuf = (char *) NS_Alloc(aDestLength);
+  char* destBuf = (char *) moz_xmalloc(aDestLength);
   if (!destBuf)
     return NS_ERROR_OUT_OF_MEMORY;
 
   rv = encoder->Convert(aBuffer, &srcLength, destBuf, &aDestLength);
   if (NS_SUCCEEDED(rv))
     rv = aStream->Write(destBuf, aDestLength, &bytesWritten);
 
-  NS_Free(destBuf);
+  free(destBuf);
   mDidWrite = true;
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsJSON::Decode(const nsAString& json, JSContext* cx,
                JS::MutableHandle<JS::Value> aRetval)
--- a/dom/media/MediaDevices.cpp
+++ b/dom/media/MediaDevices.cpp
@@ -92,27 +92,27 @@ public:
     {
       void* rawArray;
       uint32_t arrayLen;
       nsresult rv;
       rv = aDevices->GetAsArray(&elementType, &elementIID, &arrayLen, &rawArray);
       NS_ENSURE_SUCCESS(rv, rv);
 
       if (elementType != nsIDataType::VTYPE_INTERFACE) {
-        NS_Free(rawArray);
+        free(rawArray);
         return NS_ERROR_FAILURE;
       }
 
       nsISupports **supportsArray = reinterpret_cast<nsISupports **>(rawArray);
       for (uint32_t i = 0; i < arrayLen; ++i) {
         nsCOMPtr<nsIMediaDevice> device(do_QueryInterface(supportsArray[i]));
         devices.AppendElement(device);
         NS_IF_RELEASE(supportsArray[i]); // explicitly decrease refcount for rawptr
       }
-      NS_Free(rawArray); // explicitly free memory from nsIVariant::GetAsArray
+      free(rawArray); // explicitly free memory from nsIVariant::GetAsArray
     }
     nsTArray<nsRefPtr<MediaDeviceInfo>> infos;
     for (auto& device : devices) {
       nsString type;
       device->GetType(type);
       bool isVideo = type.EqualsLiteral("video");
       bool isAudio = type.EqualsLiteral("audio");
       if (isVideo || isAudio) {
--- a/dom/media/MediaPermissionGonk.cpp
+++ b/dom/media/MediaPermissionGonk.cpp
@@ -352,30 +352,30 @@ MediaDeviceSuccessCallback::OnSuccess(ns
   void* rawArray;
   uint32_t arrayLen;
 
   nsresult rv;
   rv = aDevices->GetAsArray(&elementType, &elementIID, &arrayLen, &rawArray);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (elementType != nsIDataType::VTYPE_INTERFACE) {
-    NS_Free(rawArray);
+    free(rawArray);
     return NS_ERROR_FAILURE;
   }
 
   // Create array for nsIMediaDevice
   nsTArray<nsCOMPtr<nsIMediaDevice> > devices;
 
   nsISupports **supportsArray = reinterpret_cast<nsISupports **>(rawArray);
   for (uint32_t i = 0; i < arrayLen; ++i) {
     nsCOMPtr<nsIMediaDevice> device(do_QueryInterface(supportsArray[i]));
     devices.AppendElement(device);
     NS_IF_RELEASE(supportsArray[i]); // explicitly decrease reference count for raw pointer
   }
-  NS_Free(rawArray); // explicitly free for the memory from nsIVariant::GetAsArray
+  free(rawArray); // explicitly free for the memory from nsIVariant::GetAsArray
 
   // Send MediaPermissionRequest
   nsRefPtr<MediaPermissionRequest> req = new MediaPermissionRequest(mRequest, devices);
   rv = DoPrompt(req);
 
   NS_ENSURE_SUCCESS(rv, rv);
   return NS_OK;
 }
--- a/dom/media/VideoUtils.cpp
+++ b/dom/media/VideoUtils.cpp
@@ -275,17 +275,17 @@ GenerateRandomName(nsCString& aOutSalt, 
   uint8_t* buffer;
   rv = rg->GenerateRandomBytes(requiredBytesLength, &buffer);
   if (NS_FAILED(rv)) return rv;
 
   nsAutoCString temp;
   nsDependentCSubstring randomData(reinterpret_cast<const char*>(buffer),
                                    requiredBytesLength);
   rv = Base64Encode(randomData, temp);
-  NS_Free(buffer);
+  free(buffer);
   buffer = nullptr;
   if (NS_FAILED (rv)) return rv;
 
   aOutSalt = temp;
   return NS_OK;
 }
 
 nsresult
--- a/dom/plugins/base/PluginPRLibrary.cpp
+++ b/dom/plugins/base/PluginPRLibrary.cpp
@@ -238,20 +238,20 @@ PluginPRLibrary::NPP_GetSitesWithData(In
   char** sites = mNPP_GetSitesWithData();
   if (!sites) {
     return NS_OK;
   }
 
   char** iterator = sites;
   while (*iterator) {
     result.AppendElement(*iterator);
-    NS_Free(*iterator);
+    free(*iterator);
     ++iterator;
   }
-  NS_Free(sites);
+  free(sites);
 
   return NS_OK;
 }
 
 nsresult
 PluginPRLibrary::AsyncSetWindow(NPP instance, NPWindow* window)
 {
   nsNPAPIPluginInstance* inst = (nsNPAPIPluginInstance*)instance->ndata;
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -1843,17 +1843,17 @@ void
           for (DWORD i = 0; i < nheaps; i++) {
             if (InHeap(heaps[i], p)) {
               HeapFree(heaps[i], 0, p);
               break;
             }
           }
         }
 #else
-        NS_Free((void *)s->UTF8Characters);
+        free((void *)s->UTF8Characters);
 #endif
       }
       break;
     }
   case NPVariantType_Object:
     {
       NPObject *npobj = NPVARIANT_TO_OBJECT(*variant);
 
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -225,29 +225,29 @@ nsNPAPIPluginInstance::~nsNPAPIPluginIns
 
   if (!mCachedParamValues || !mCachedParamNames) {
     return;
   }
   MOZ_ASSERT(mCachedParamValues && mCachedParamNames);
 
   for (uint32_t i = 0; i < mCachedParamLength; i++) {
     if (mCachedParamNames[i]) {
-      NS_Free(mCachedParamNames[i]);
+      free(mCachedParamNames[i]);
       mCachedParamNames[i] = nullptr;
     }
     if (mCachedParamValues[i]) {
-      NS_Free(mCachedParamValues[i]);
+      free(mCachedParamValues[i]);
       mCachedParamValues[i] = nullptr;
     }
   }
 
-  NS_Free(mCachedParamNames);
+  free(mCachedParamNames);
   mCachedParamNames = nullptr;
 
-  NS_Free(mCachedParamValues);
+  free(mCachedParamValues);
   mCachedParamValues = nullptr;
 }
 
 uint32_t nsNPAPIPluginInstance::gInUnsafePluginCalls = 0;
 
 void
 nsNPAPIPluginInstance::Destroy()
 {
@@ -449,18 +449,18 @@ nsNPAPIPluginInstance::Start()
   mCachedParamLength = attributes.Length() + 1 + params.Length();
 
   // We add an extra entry "PARAM" as a separator between the attribute
   // and param values, but we don't count it if there are no <param> entries.
   // Legacy behavior quirk.
   uint32_t quirkParamLength = params.Length() ?
                                 mCachedParamLength : attributes.Length();
 
-  mCachedParamNames = (char**)NS_Alloc(sizeof(char*) * mCachedParamLength);
-  mCachedParamValues = (char**)NS_Alloc(sizeof(char*) * mCachedParamLength);
+  mCachedParamNames = (char**)moz_xmalloc(sizeof(char*) * mCachedParamLength);
+  mCachedParamValues = (char**)moz_xmalloc(sizeof(char*) * mCachedParamLength);
 
   for (uint32_t i = 0; i < attributes.Length(); i++) {
     mCachedParamNames[i] = ToNewUTF8String(attributes[i].mName);
     mCachedParamValues[i] = ToNewUTF8String(attributes[i].mValue);
   }
 
   // Android expects and empty string instead of null.
   mCachedParamNames[attributes.Length()] = ToNewUTF8String(NS_LITERAL_STRING("PARAM"));
--- a/dom/plugins/base/nsPluginHost.cpp
+++ b/dom/plugins/base/nsPluginHost.cpp
@@ -552,17 +552,17 @@ nsresult nsPluginHost::PostURL(nsISuppor
     char *dataToPost;
     uint32_t newDataToPostLen;
     ParsePostBufferToFixHeaders(postData, postDataLen, &dataToPost, &newDataToPostLen);
     if (!dataToPost)
       return NS_ERROR_UNEXPECTED;
 
     nsCOMPtr<nsIStringInputStream> sis = do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv);
     if (!sis) {
-      NS_Free(dataToPost);
+      free(dataToPost);
       return rv;
     }
 
     // data allocated by ParsePostBufferToFixHeaders() is managed and
     // freed by the string stream.
     postDataLen = newDataToPostLen;
     sis->AdoptData(dataToPost, postDataLen);
     postStream = sis;
--- a/dom/plugins/base/nsPluginsDirDarwin.cpp
+++ b/dom/plugins/base/nsPluginsDirDarwin.cpp
@@ -99,29 +99,29 @@ static char* CFStringRefToUTF8Buffer(CFS
   const char* buffer = ::CFStringGetCStringPtr(cfString, kCFStringEncodingUTF8);
   if (buffer) {
     return PL_strdup(buffer);
   }
 
   int bufferLength =
     ::CFStringGetMaximumSizeForEncoding(::CFStringGetLength(cfString),
                                         kCFStringEncodingUTF8) + 1;
-  char* newBuffer = static_cast<char*>(NS_Alloc(bufferLength));
+  char* newBuffer = static_cast<char*>(moz_xmalloc(bufferLength));
   if (!newBuffer) {
     return nullptr;
   }
 
   if (!::CFStringGetCString(cfString, newBuffer, bufferLength,
                             kCFStringEncodingUTF8)) {
-    NS_Free(newBuffer);
+    free(newBuffer);
     return nullptr;
   }
 
-  newBuffer = static_cast<char*>(NS_Realloc(newBuffer,
-                                            strlen(newBuffer) + 1));
+  newBuffer = static_cast<char*>(moz_xrealloc(newBuffer,
+                                              strlen(newBuffer) + 1));
   return newBuffer;
 }
 
 class AutoCFTypeObject {
 public:
   explicit AutoCFTypeObject(CFTypeRef aObject)
   {
     mObject = aObject;
@@ -219,25 +219,25 @@ static void ParsePlistPluginInfo(nsPlugi
     mimeDict = static_cast<CFDictionaryRef>(::CFRetain(mimeTypes));
   }
   
   AutoCFTypeObject mimeDictAutorelease(mimeDict);
   int mimeDictKeyCount = ::CFDictionaryGetCount(mimeDict);
 
   // Allocate memory for mime data
   int mimeDataArraySize = mimeDictKeyCount * sizeof(char*);
-  info.fMimeTypeArray = static_cast<char**>(NS_Alloc(mimeDataArraySize));
+  info.fMimeTypeArray = static_cast<char**>(moz_xmalloc(mimeDataArraySize));
   if (!info.fMimeTypeArray)
     return;
   memset(info.fMimeTypeArray, 0, mimeDataArraySize);
-  info.fExtensionArray = static_cast<char**>(NS_Alloc(mimeDataArraySize));
+  info.fExtensionArray = static_cast<char**>(moz_xmalloc(mimeDataArraySize));
   if (!info.fExtensionArray)
     return;
   memset(info.fExtensionArray, 0, mimeDataArraySize);
-  info.fMimeDescriptionArray = static_cast<char**>(NS_Alloc(mimeDataArraySize));
+  info.fMimeDescriptionArray = static_cast<char**>(moz_xmalloc(mimeDataArraySize));
   if (!info.fMimeDescriptionArray)
     return;
   memset(info.fMimeDescriptionArray, 0, mimeDataArraySize);
 
   // Allocate memory for mime dictionary keys and values
   nsAutoArrayPtr<CFTypeRef> keys(new CFTypeRef[mimeDictKeyCount]);
   if (!keys)
     return;
@@ -345,17 +345,17 @@ nsresult nsPluginFile::LoadPlugin(PRLibr
   printf("[loaded plugin %s]\n", bundlePath.get());
 #endif
   return NS_OK;
 }
 
 static char* p2cstrdup(StringPtr pstr)
 {
   int len = pstr[0];
-  char* cstr = static_cast<char*>(NS_Alloc(len + 1));
+  char* cstr = static_cast<char*>(moz_xmalloc(len + 1));
   if (cstr) {
     memmove(cstr, pstr + 1, len);
     cstr[len] = '\0';
   }
   return cstr;
 }
 
 static char* GetNextPluginStringFromHandle(Handle h, short *index)
@@ -535,24 +535,24 @@ nsresult nsPluginFile::GetPluginInfo(nsP
       ::HLock(mi.typeStrings);
       if (mi.infoStrings)  // it's possible some plugins have infoStrings missing
         ::HLock(mi.infoStrings);
     }
   }
 
   // Fill in the info struct based on the data in the BPSupportedMIMETypes struct
   int variantCount = info.fVariantCount;
-  info.fMimeTypeArray = static_cast<char**>(NS_Alloc(variantCount * sizeof(char*)));
+  info.fMimeTypeArray = static_cast<char**>(moz_xmalloc(variantCount * sizeof(char*)));
   if (!info.fMimeTypeArray)
     return NS_ERROR_OUT_OF_MEMORY;
-  info.fExtensionArray = static_cast<char**>(NS_Alloc(variantCount * sizeof(char*)));
+  info.fExtensionArray = static_cast<char**>(moz_xmalloc(variantCount * sizeof(char*)));
   if (!info.fExtensionArray)
     return NS_ERROR_OUT_OF_MEMORY;
   if (mi.infoStrings) {
-    info.fMimeDescriptionArray = static_cast<char**>(NS_Alloc(variantCount * sizeof(char*)));
+    info.fMimeDescriptionArray = static_cast<char**>(moz_xmalloc(variantCount * sizeof(char*)));
     if (!info.fMimeDescriptionArray)
       return NS_ERROR_OUT_OF_MEMORY;
   }
   short mimeIndex = 2;
   short descriptionIndex = 2;
   for (int i = 0; i < variantCount; i++) {
     info.fMimeTypeArray[i] = GetNextPluginStringFromHandle(mi.typeStrings, &mimeIndex);
     info.fExtensionArray[i] = GetNextPluginStringFromHandle(mi.typeStrings, &mimeIndex);
@@ -567,25 +567,25 @@ nsresult nsPluginFile::GetPluginInfo(nsP
     ::DisposeHandle(mi.infoStrings);
   }
 
   return NS_OK;
 }
 
 nsresult nsPluginFile::FreePluginInfo(nsPluginInfo& info)
 {
-  NS_Free(info.fName);
-  NS_Free(info.fDescription);
+  free(info.fName);
+  free(info.fDescription);
   int variantCount = info.fVariantCount;
   for (int i = 0; i < variantCount; i++) {
-    NS_Free(info.fMimeTypeArray[i]);
-    NS_Free(info.fExtensionArray[i]);
-    NS_Free(info.fMimeDescriptionArray[i]);
+    free(info.fMimeTypeArray[i]);
+    free(info.fExtensionArray[i]);
+    free(info.fMimeDescriptionArray[i]);
   }
-  NS_Free(info.fMimeTypeArray);
-  NS_Free(info.fMimeDescriptionArray);
-  NS_Free(info.fExtensionArray);
-  NS_Free(info.fFileName);
-  NS_Free(info.fFullPath);
-  NS_Free(info.fVersion);
+  free(info.fMimeTypeArray);
+  free(info.fMimeDescriptionArray);
+  free(info.fExtensionArray);
+  free(info.fFileName);
+  free(info.fFullPath);
+  free(info.fVersion);
 
   return NS_OK;
 }
--- a/dom/plugins/ipc/PluginModuleChild.cpp
+++ b/dom/plugins/ipc/PluginModuleChild.cpp
@@ -747,20 +747,20 @@ PluginModuleChild::AnswerNPP_GetSitesWit
 {
     char** result = mFunctions.getsiteswithdata();
     if (!result)
         return true;
 
     char** iterator = result;
     while (*iterator) {
         aResult->AppendElement(*iterator);
-        NS_Free(*iterator);
+        free(*iterator);
         ++iterator;
     }
-    NS_Free(result);
+    free(result);
 
     return true;
 }
 
 bool
 PluginModuleChild::RecvSetAudioSessionData(const nsID& aId,
                                            const nsString& aDisplayName,
                                            const nsString& aIconPath)
@@ -1325,17 +1325,17 @@ void
 }
 
 void
 _memfree(void* aPtr)
 {
     PLUGIN_LOG_DEBUG_FUNCTION;
     // Only assert plugin thread here for consistency with in-process plugins.
     AssertPluginThread();
-    NS_Free(aPtr);
+    free(aPtr);
 }
 
 uint32_t
 _memflush(uint32_t aSize)
 {
     PLUGIN_LOG_DEBUG_FUNCTION;
     // Only assert plugin thread here for consistency with in-process plugins.
     AssertPluginThread();
@@ -1394,17 +1394,17 @@ const char*
 }
 
 void*
 _memalloc(uint32_t aSize)
 {
     PLUGIN_LOG_DEBUG_FUNCTION;
     // Only assert plugin thread here for consistency with in-process plugins.
     AssertPluginThread();
-    return NS_Alloc(aSize);
+    return moz_xmalloc(aSize);
 }
 
 // Deprecated entry points for the old Java plugin.
 void* /* OJI type: JRIEnv* */
 _getjavaenv(void)
 {
     PLUGIN_LOG_DEBUG_FUNCTION;
     return 0;
--- a/dom/tv/FakeTVService.cpp
+++ b/dom/tv/FakeTVService.cpp
@@ -195,17 +195,17 @@ public:
     , mChannelData(aChannelData)
   {}
 
   NS_IMETHODIMP
   Notify(nsITimer* aTimer) override
   {
     // Notify mock EIT broadcasting.
     nsITVProgramData** programDataList =
-      static_cast<nsITVProgramData **>(NS_Alloc(1 * sizeof(nsITVProgramData*)));
+      static_cast<nsITVProgramData **>(moz_xmalloc(1 * sizeof(nsITVProgramData*)));
     programDataList[0] = new TVProgramData();
     programDataList[0]->SetEventId(NS_LITERAL_STRING("eventId"));
     programDataList[0]->SetTitle(NS_LITERAL_STRING("title"));
     programDataList[0]->SetStartTime(PR_Now() + 3600000);
     programDataList[0]->SetDuration(3600000);
     programDataList[0]->SetDescription(NS_LITERAL_STRING("description"));
     programDataList[0]->SetRating(NS_LITERAL_STRING("rating"));
     programDataList[0]->SetAudioLanguages(0, nullptr);
--- a/dom/tv/TVTypes.cpp
+++ b/dom/tv/TVTypes.cpp
@@ -50,17 +50,17 @@ TVTunerData::SetId(const nsAString& aId)
 
 /* virtual */ NS_IMETHODIMP
 TVTunerData::GetSupportedSourceTypes(uint32_t* aCount,
                                      char*** aSourceTypes)
 {
   *aCount = mCount;
 
   char** sourceTypes = (mCount > 0) ?
-                       static_cast<char **>(NS_Alloc(mCount * sizeof(char*))) :
+                       static_cast<char **>(moz_xmalloc(mCount * sizeof(char*))) :
                        nullptr;
   for (uint32_t i = 0; i < mCount; i++) {
     sourceTypes[i] = NS_strdup(mSupportedSourceTypes[i]);
   }
 
   *aSourceTypes = sourceTypes;
   return NS_OK;
 }
@@ -82,17 +82,17 @@ TVTunerData::SetSupportedSourceTypes(uin
 
   if (mSupportedSourceTypes) {
     NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mCount, mSupportedSourceTypes);
   }
 
   mCount = aCount;
 
   mSupportedSourceTypes = (mCount > 0) ?
-                          static_cast<char **>(NS_Alloc(mCount * sizeof(char*))) :
+                          static_cast<char **>(moz_xmalloc(mCount * sizeof(char*))) :
                           nullptr;
   for (uint32_t i = 0; i < mCount; i++) {
     mSupportedSourceTypes[i] = NS_strdup(aSourceTypes[i]);
   }
 
   return NS_OK;
 }
 
@@ -372,17 +372,17 @@ TVProgramData::SetRating(const nsAString
 
 /* virtual */ NS_IMETHODIMP
 TVProgramData::GetAudioLanguages(uint32_t* aCount,
                                  char*** aLanguages)
 {
   *aCount = mAudioLanguageCount;
 
   char** languages = (mAudioLanguageCount > 0) ?
-                     static_cast<char **>(NS_Alloc(mAudioLanguageCount * sizeof(char*))) :
+                     static_cast<char **>(moz_xmalloc(mAudioLanguageCount * sizeof(char*))) :
                      nullptr;
   for (uint32_t i = 0; i < mAudioLanguageCount; i++) {
     languages[i] = NS_strdup(mAudioLanguages[i]);
   }
 
   *aLanguages = languages;
   return NS_OK;
 }
@@ -397,33 +397,33 @@ TVProgramData::SetAudioLanguages(uint32_
 
   if (mAudioLanguages) {
     NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mAudioLanguageCount, mAudioLanguages);
   }
 
   mAudioLanguageCount = aCount;
 
   mAudioLanguages = (mAudioLanguageCount > 0) ?
-                    static_cast<char **>(NS_Alloc(mAudioLanguageCount * sizeof(char*))) :
+                    static_cast<char **>(moz_xmalloc(mAudioLanguageCount * sizeof(char*))) :
                     nullptr;
   for (uint32_t i = 0; i < mAudioLanguageCount; i++) {
     mAudioLanguages[i] = NS_strdup(aLanguages[i]);
   }
 
   return NS_OK;
 }
 
 /* virtual */ NS_IMETHODIMP
 TVProgramData::GetSubtitleLanguages(uint32_t* aCount,
                                     char*** aLanguages)
 {
   *aCount = mSubtitleLanguageCount;
 
   char** languages = (mSubtitleLanguageCount > 0) ?
-                     static_cast<char **>(NS_Alloc(mSubtitleLanguageCount * sizeof(char*))) :
+                     static_cast<char **>(moz_xmalloc(mSubtitleLanguageCount * sizeof(char*))) :
                      nullptr;
   for (uint32_t i = 0; i < mSubtitleLanguageCount; i++) {
     languages[i] = NS_strdup(mSubtitleLanguages[i]);
   }
 
   *aLanguages = languages;
   return NS_OK;
 }
@@ -438,17 +438,17 @@ TVProgramData::SetSubtitleLanguages(uint
 
   if (mSubtitleLanguages) {
     NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mSubtitleLanguageCount, mSubtitleLanguages);
   }
 
   mSubtitleLanguageCount = aCount;
 
   mSubtitleLanguages = (mSubtitleLanguageCount > 0) ?
-                       static_cast<char **>(NS_Alloc(mSubtitleLanguageCount * sizeof(char*))) :
+                       static_cast<char **>(moz_xmalloc(mSubtitleLanguageCount * sizeof(char*))) :
                        nullptr;
   for (uint32_t i = 0; i < mSubtitleLanguageCount; i++) {
     mSubtitleLanguages[i] = NS_strdup(aLanguages[i]);
   }
 
   return NS_OK;
 }
 
--- a/dom/xbl/nsXBLProtoImplField.cpp
+++ b/dom/xbl/nsXBLProtoImplField.cpp
@@ -58,17 +58,17 @@ nsXBLProtoImplField::nsXBLProtoImplField
     mJSAttributes |= JSPROP_READONLY;
 }
 
 nsXBLProtoImplField::~nsXBLProtoImplField()
 {
   MOZ_COUNT_DTOR(nsXBLProtoImplField);
   if (mFieldText)
     free(mFieldText);
-  NS_Free(mName);
+  free(mName);
   NS_CONTENT_DELETE_LIST_MEMBER(nsXBLProtoImplField, this, mNext);
 }
 
 void 
 nsXBLProtoImplField::AppendFieldText(const nsAString& aText)
 {
   if (mFieldText) {
     nsDependentString fieldTextStr(mFieldText, mFieldTextLength);
--- a/editor/libeditor/ChangeStyleTxn.cpp
+++ b/editor/libeditor/ChangeStyleTxn.cpp
@@ -12,17 +12,16 @@
 #include "nsError.h"                    // for NS_ERROR_NULL_POINTER, etc
 #include "nsGkAtoms.h"                  // for nsGkAtoms, etc
 #include "nsIDOMCSSStyleDeclaration.h"  // for nsIDOMCSSStyleDeclaration
 #include "nsIDOMElementCSSInlineStyle.h" // for nsIDOMElementCSSInlineStyle
 #include "nsLiteralString.h"            // for NS_LITERAL_STRING, etc
 #include "nsReadableUtils.h"            // for ToNewUnicode
 #include "nsString.h"                   // for nsAutoString, nsString, etc
 #include "nsUnicharUtils.h"             // for nsCaseInsensitiveStringComparator
-#include "nsXPCOM.h"                    // for NS_Free
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 #define kNullCh (char16_t('\0'))
 
 NS_IMPL_CYCLE_COLLECTION_INHERITED(ChangeStyleTxn, EditTxn, mElement)
 
@@ -70,17 +69,17 @@ ChangeStyleTxn::ValueIncludes(const nsAS
       if (nsDependentString(value).Equals(nsDependentString(start),
             nsCaseInsensitiveStringComparator())) {
         result = true;
         break;
       }
     }
     start = ++end;
   }
-  NS_Free(value);
+  free(value);
   return result;
 }
 
 // Removes the value aRemoveValue from the string list of white-space separated
 // values aValueList
 void
 ChangeStyleTxn::RemoveValueFromListOfValues(nsAString& aValues,
                                             const nsAString& aRemoveValue)
--- a/editor/libeditor/nsHTMLDataTransfer.cpp
+++ b/editor/libeditor/nsHTMLDataTransfer.cpp
@@ -1627,17 +1627,17 @@ NS_IMETHODIMP nsHTMLEditor::PasteAsPlain
     {
       nsAutoString stuffToPaste;
       textDataObj->GetData(stuffToPaste);
       NS_ASSERTION(stuffToPaste.Length() <= (len/2), "Invalid length!");
       nsAutoEditBatch beginBatching(this);
       rv = InsertAsPlaintextQuotation(stuffToPaste, true, 0);
     }
   }
-  NS_Free(flav);
+  free(flav);
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsHTMLEditor::InsertTextWithQuotations(const nsAString &aStringToInsert)
 {
   if (mWrapToWindow)
--- a/editor/libeditor/nsHTMLEditor.cpp
+++ b/editor/libeditor/nsHTMLEditor.cpp
@@ -723,17 +723,17 @@ AssertParserServiceIsCorrect(nsIAtom* aT
     if (!aIsBlock) {
       nsAutoString assertmsg (NS_LITERAL_STRING("Parser and editor disagree on blockness: "));
 
       nsAutoString tagName;
       aTag->ToString(tagName);
       assertmsg.Append(tagName);
       char* assertstr = ToNewCString(assertmsg);
       NS_ASSERTION(aIsBlock, assertstr);
-      NS_Free(assertstr);
+      free(assertstr);
     }
   }
 #endif // DEBUG
 }
 
 /**
  * Returns true if the id represents an element of block type.
  * Can be used to determine if a new paragraph should be started.
--- a/editor/libeditor/nsPlaintextDataTransfer.cpp
+++ b/editor/libeditor/nsPlaintextDataTransfer.cpp
@@ -122,17 +122,17 @@ NS_IMETHODIMP nsPlaintextEditor::InsertT
 
       // Sanitize possible carriage returns in the string to be inserted
       nsContentUtils::PlatformToDOMLineBreaks(stuffToPaste);
 
       nsAutoEditBatch beginBatching(this);
       rv = InsertTextAt(stuffToPaste, aDestinationNode, aDestOffset, aDoDeleteSelection);
     }
   }
-  NS_Free(bestFlavor);
+  free(bestFlavor);
       
   // Try to scroll the selection into view if the paste/drop succeeded
 
   if (NS_SUCCEEDED(rv))
     ScrollSelectionIntoView(false);
 
   return rv;
 }
--- a/editor/libeditor/nsPlaintextEditor.cpp
+++ b/editor/libeditor/nsPlaintextEditor.cpp
@@ -1385,17 +1385,17 @@ nsPlaintextEditor::PasteAsQuotation(int3
       if (textDataObj && len > 0)
       {
         nsAutoString stuffToPaste;
         textDataObj->GetData ( stuffToPaste );
         nsAutoEditBatch beginBatching(this);
         rv = InsertAsQuotation(stuffToPaste, 0);
       }
     }
-    NS_Free(flav);
+    free(flav);
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsPlaintextEditor::InsertAsQuotation(const nsAString& aQuotedText,
                                      nsIDOMNode **aNodeInserted)
--- a/editor/txmgr/nsTransactionList.cpp
+++ b/editor/txmgr/nsTransactionList.cpp
@@ -105,17 +105,17 @@ NS_IMETHODIMP nsTransactionList::GetData
     item = mTxnStack->GetItem(aIndex);
   } else if (mTxnItem) {
     nsresult result = mTxnItem->GetChild(aIndex, getter_AddRefs(item));
     NS_ENSURE_SUCCESS(result, result);
   }
 
   nsCOMArray<nsISupports>& data = item->GetData();
 
-  nsISupports** ret = static_cast<nsISupports**>(NS_Alloc(data.Count() *
+  nsISupports** ret = static_cast<nsISupports**>(moz_xmalloc(data.Count() *
     sizeof(nsISupports*)));
 
   for (int32_t i = 0; i < data.Count(); i++) {
     NS_ADDREF(ret[i] = data[i]);
   }
 
   *aLength = data.Count();
   *aData = ret;
--- a/embedding/components/commandhandler/nsControllerCommandTable.cpp
+++ b/embedding/components/commandhandler/nsControllerCommandTable.cpp
@@ -200,17 +200,17 @@ AddCommand(const nsACString& aKey, nsICo
   return PL_DHASH_NEXT;
 }
 
 NS_IMETHODIMP
 nsControllerCommandTable::GetSupportedCommands(uint32_t* aCount,
                                                char*** aCommands)
 {
   char** commands =
-    static_cast<char **>(NS_Alloc(sizeof(char *) * mCommandsTable.Count()));
+    static_cast<char **>(moz_xmalloc(sizeof(char *) * mCommandsTable.Count()));
   *aCount = mCommandsTable.Count();
   *aCommands = commands;
 
   mCommandsTable.EnumerateRead(AddCommand, &commands);
   return NS_OK;
 }
 
 nsresult
--- a/extensions/spellcheck/hunspell/src/mozHunspell.cpp
+++ b/extensions/spellcheck/hunspell/src/mozHunspell.cpp
@@ -317,30 +317,30 @@ AppendNewString(const nsAString& aString
 /* void GetDictionaryList ([array, size_is (count)] out wstring dictionaries, out uint32_t count); */
 NS_IMETHODIMP mozHunspell::GetDictionaryList(char16_t ***aDictionaries,
                                             uint32_t *aCount)
 {
   if (!aDictionaries || !aCount)
     return NS_ERROR_NULL_POINTER;
 
   AppendNewStruct ans = {
-    (char16_t**) NS_Alloc(sizeof(char16_t*) * mDictionaries.Count()),
+    (char16_t**) moz_xmalloc(sizeof(char16_t*) * mDictionaries.Count()),
     0,
     false
   };
 
   // This pointer is used during enumeration
   mDictionaries.EnumerateRead(AppendNewString, &ans);
 
   if (ans.failed) {
     while (ans.count) {
       --ans.count;
-      NS_Free(ans.dics[ans.count]);
+      free(ans.dics[ans.count]);
     }
-    NS_Free(ans.dics);
+    free(ans.dics);
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   *aDictionaries = ans.dics;
   *aCount = ans.count;
 
   return NS_OK;
 }
--- a/gfx/thebes/gfxDWriteFontList.cpp
+++ b/gfx/thebes/gfxDWriteFontList.cpp
@@ -774,24 +774,24 @@ gfxDWriteFontList::MakePlatformFont(cons
                                     bool aItalic,
                                     const uint8_t* aFontData,
                                     uint32_t aLength)
 {
     nsresult rv;
     nsAutoString uniqueName;
     rv = gfxFontUtils::MakeUniqueUserFontName(uniqueName);
     if (NS_FAILED(rv)) {
-        NS_Free((void*)aFontData);
+        free((void*)aFontData);
         return nullptr;
     }
 
     FallibleTArray<uint8_t> newFontData;
 
     rv = gfxFontUtils::RenameFont(uniqueName, aFontData, aLength, &newFontData);
-    NS_Free((void*)aFontData);
+    free((void*)aFontData);
 
     if (NS_FAILED(rv)) {
         return nullptr;
     }
     
     nsRefPtr<IDWriteFontFile> fontFile;
     HRESULT hr;
 
--- a/gfx/thebes/gfxFT2FontList.cpp
+++ b/gfx/thebes/gfxFT2FontList.cpp
@@ -261,22 +261,22 @@ FT2FontEntry::CreateFontEntry(const nsAS
     // Ownership of aFontData is passed in here; the fontEntry must
     // retain it as long as the FT_Face needs it, and ensure it is
     // eventually deleted.
     FT_Face face;
     FT_Error error =
         FT_New_Memory_Face(gfxToolkitPlatform::GetPlatform()->GetFTLibrary(),
                            aFontData, aLength, 0, &face);
     if (error != FT_Err_Ok) {
-        NS_Free((void*)aFontData);
+        free((void*)aFontData);
         return nullptr;
     }
     if (FT_Err_Ok != FT_Select_Charmap(face, FT_ENCODING_UNICODE)) {
         FT_Done_Face(face);
-        NS_Free((void*)aFontData);
+        free((void*)aFontData);
         return nullptr;
     }
     // Create our FT2FontEntry, which inherits the name of the userfont entry
     // as it's not guaranteed that the face has valid names (bug 737315)
     FT2FontEntry* fe =
         FT2FontEntry::CreateFontEntry(face, nullptr, 0, aFontName,
                                       aFontData);
     if (fe) {
@@ -294,17 +294,17 @@ public:
         : mFace(aFace), mFontData(aData)
     {
     }
 
     ~FTUserFontData()
     {
         FT_Done_Face(mFace);
         if (mFontData) {
-            NS_Free((void*)mFontData);
+            free((void*)mFontData);
         }
     }
 
     const uint8_t *FontData() const { return mFontData; }
 
 private:
     FT_Face        mFace;
     const uint8_t *mFontData;
--- a/gfx/thebes/gfxGDIFontList.cpp
+++ b/gfx/thebes/gfxGDIFontList.cpp
@@ -757,23 +757,23 @@ gfxGDIFontList::LookupLocalFont(const ns
 gfxFontEntry*
 gfxGDIFontList::MakePlatformFont(const nsAString& aFontName,
                                  uint16_t aWeight,
                                  int16_t aStretch,
                                  bool aItalic,
                                  const uint8_t* aFontData,
                                  uint32_t aLength)
 {
-    // MakePlatformFont is responsible for deleting the font data with NS_Free
+    // MakePlatformFont is responsible for deleting the font data with free
     // so we set up a stack object to ensure it is freed even if we take an
     // early exit
     struct FontDataDeleter {
         FontDataDeleter(const uint8_t* aFontData)
             : mFontData(aFontData) { }
-        ~FontDataDeleter() { NS_Free((void*)mFontData); }
+        ~FontDataDeleter() { free((void*)mFontData); }
         const uint8_t *mFontData;
     };
     FontDataDeleter autoDelete(aFontData);
 
     bool isCFF = gfxFontUtils::IsCffFont(aFontData);
 
     nsresult rv;
     HANDLE fontRef = nullptr;
--- a/gfx/thebes/gfxMacPlatformFontList.mm
+++ b/gfx/thebes/gfxMacPlatformFontList.mm
@@ -966,17 +966,17 @@ gfxMacPlatformFontList::LookupLocalFont(
                            false, true);
     ::CFRelease(fontRef);
 
     return newFontEntry;
 }
 
 static void ReleaseData(void *info, const void *data, size_t size)
 {
-    NS_Free((void*)data);
+    free((void*)data);
 }
 
 gfxFontEntry*
 gfxMacPlatformFontList::MakePlatformFont(const nsAString& aFontName,
                                          uint16_t aWeight,
                                          int16_t aStretch,
                                          bool aItalic,
                                          const uint8_t* aFontData,
--- a/gfx/thebes/gfxPangoFonts.cpp
+++ b/gfx/thebes/gfxPangoFonts.cpp
@@ -468,17 +468,17 @@ public:
 
     virtual hb_blob_t* GetFontTable(uint32_t aTableTag) override;
 
 protected:
     void InitPattern();
 
     // mFontData holds the data used to instantiate the FT_Face;
     // this has to persist until we are finished with the face,
-    // then be released with NS_Free().
+    // then be released with free().
     const uint8_t* mFontData;
 
     FT_Face mFace;
 };
 
 // A property for recording gfxDownloadedFcFontEntrys on FcPatterns.
 static const char *kFontEntryFcProp = "-moz-font-entry";
 
@@ -517,17 +517,17 @@ gfxDownloadedFcFontEntry::~gfxDownloaded
         // Remove back reference to this font entry and the face in case
         // anyone holds a reference to the pattern.
         NS_ASSERTION(mPatterns.Length() == 1,
                      "More than one pattern in gfxDownloadedFcFontEntry!");
         DelDownloadedFontEntry(mPatterns[0]);
         FcPatternDel(mPatterns[0], FC_FT_FACE);
     }
     FT_Done_Face(mFace);
-    NS_Free((void*)mFontData);
+    free((void*)mFontData);
 }
 
 typedef FcPattern* (*QueryFaceFunction)(const FT_Face face,
                                         const FcChar8 *file, int id,
                                         FcBlanks *blanks);
 
 void
 gfxDownloadedFcFontEntry::InitPattern()
@@ -1701,17 +1701,17 @@ gfxPangoFontGroup::NewFontEntry(const ns
     // new fontEntry, which will release it when no longer needed.
 
     // Using face_index = 0 for the first face in the font, as we have no
     // other information.  FT_New_Memory_Face checks for a nullptr FT_Library.
     FT_Face face;
     FT_Error error =
         FT_New_Memory_Face(GetFTLibrary(), aFontData, aLength, 0, &face);
     if (error != 0) {
-        NS_Free((void*)aFontData);
+        free((void*)aFontData);
         return nullptr;
     }
 
     return new gfxDownloadedFcFontEntry(aFontName, aWeight,
                                         aStretch, aItalic,
                                         aFontData, face);
 }
 
--- a/gfx/thebes/gfxPlatform.cpp
+++ b/gfx/thebes/gfxPlatform.cpp
@@ -1328,17 +1328,17 @@ gfxPlatform::MakePlatformFont(const nsAS
                               uint32_t aLength)
 {
     // Default implementation does not handle activating downloaded fonts;
     // just free the data and return.
     // Platforms that support @font-face must override this,
     // using the data to instantiate the font, and taking responsibility
     // for freeing it when no longer required.
     if (aFontData) {
-        NS_Free((void*)aFontData);
+        free((void*)aFontData);
     }
     return nullptr;
 }
 
 static void
 AppendGenericFontFromPref(nsString& aFonts, nsIAtom *aLangGroup, const char *aGenericName)
 {
     NS_ENSURE_TRUE_VOID(Preferences::GetRootBranch());
--- a/gfx/thebes/gfxPlatformFontList.h
+++ b/gfx/thebes/gfxPlatformFontList.h
@@ -150,17 +150,17 @@ public:
 
     // look up a font by name on the host platform
     virtual gfxFontEntry* LookupLocalFont(const nsAString& aFontName,
                                           uint16_t aWeight,
                                           int16_t aStretch,
                                           bool aItalic) = 0;
 
     // create a new platform font from downloaded data (@font-face)
-    // this method is responsible to ensure aFontData is NS_Free()'d
+    // this method is responsible to ensure aFontData is free()'d
     virtual gfxFontEntry* MakePlatformFont(const nsAString& aFontName,
                                            uint16_t aWeight,
                                            int16_t aStretch,
                                            bool aItalic,
                                            const uint8_t* aFontData,
                                            uint32_t aLength) = 0;
 
     // get the standard family name on the platform for a given font name
--- a/gfx/thebes/gfxPlatformMac.cpp
+++ b/gfx/thebes/gfxPlatformMac.cpp
@@ -161,17 +161,17 @@ gfxPlatformMac::MakePlatformFont(const n
                                  uint16_t aWeight,
                                  int16_t aStretch,
                                  bool aItalic,
                                  const uint8_t* aFontData,
                                  uint32_t aLength)
 {
     // Ownership of aFontData is received here, and passed on to
     // gfxPlatformFontList::MakePlatformFont(), which must ensure the data
-    // is released with NS_Free when no longer needed
+    // is released with free when no longer needed
     return gfxPlatformFontList::PlatformFontList()->MakePlatformFont(aFontName,
                                                                      aWeight,
                                                                      aStretch,
                                                                      aItalic,
                                                                      aFontData,
                                                                      aLength);
 }
 
--- a/gfx/thebes/gfxUserFontSet.cpp
+++ b/gfx/thebes/gfxUserFontSet.cpp
@@ -42,25 +42,25 @@ static uint64_t sFontSetGeneration = 0;
 
 // Based on ots::ExpandingMemoryStream from ots-memory-stream.h,
 // adapted to use Mozilla allocators and to allow the final
 // memory buffer to be adopted by the client.
 class ExpandingMemoryStream : public ots::OTSStream {
 public:
     ExpandingMemoryStream(size_t initial, size_t limit)
         : mLength(initial), mLimit(limit), mOff(0) {
-        mPtr = NS_Alloc(mLength);
+        mPtr = moz_xmalloc(mLength);
     }
 
     ~ExpandingMemoryStream() {
-        NS_Free(mPtr);
+        free(mPtr);
     }
 
     // return the buffer, and give up ownership of it
-    // so the caller becomes responsible to call NS_Free
+    // so the caller becomes responsible to call free
     // when finished with it
     void* forget() {
         void* p = mPtr;
         mPtr = nullptr;
         return p;
     }
 
     bool WriteRaw(const void* data, size_t length) {
@@ -71,17 +71,17 @@ public:
             }
             size_t newLength = (mLength + 1) * 2;
             if (newLength < mLength) {
                 return false;
             }
             if (newLength > mLimit) {
                 newLength = mLimit;
             }
-            mPtr = NS_Realloc(mPtr, newLength);
+            mPtr = moz_xrealloc(mPtr, newLength);
             mLength = newLength;
             return WriteRaw(data, length);
         }
         std::memcpy(static_cast<char*>(mPtr) + mOff, data, length);
         mOff += length;
         return true;
     }
 
--- a/gfx/thebes/gfxUserFontSet.h
+++ b/gfx/thebes/gfxUserFontSet.h
@@ -606,24 +606,24 @@ protected:
     // change the load state
     virtual void SetLoadState(UserFontLoadState aLoadState);
 
     // when download has been completed, pass back data here
     // aDownloadStatus == NS_OK ==> download succeeded, error otherwise
     // returns true if platform font creation sucessful (or local()
     // reference was next in line)
     // Ownership of aFontData is passed in here; the font set must
-    // ensure that it is eventually deleted with NS_Free().
+    // ensure that it is eventually deleted with free().
     bool FontDataDownloadComplete(const uint8_t* aFontData, uint32_t aLength,
                                   nsresult aDownloadStatus);
 
     // helper method for creating a platform font
     // returns true if platform font creation successful
     // Ownership of aFontData is passed in here; the font must
-    // ensure that it is eventually deleted with NS_Free().
+    // ensure that it is eventually deleted with free().
     bool LoadPlatformFont(const uint8_t* aFontData, uint32_t& aLength);
 
     // store metadata and src details for current src into aFontEntry
     void StoreUserFontData(gfxFontEntry*      aFontEntry,
                            bool               aPrivate,
                            const nsAString&   aOriginalName,
                            FallibleTArray<uint8_t>* aMetadata,
                            uint32_t           aMetaOrigLen,
--- a/image/decoders/icon/android/nsIconChannel.cpp
+++ b/image/decoders/icon/android/nsIconChannel.cpp
@@ -67,17 +67,17 @@ moz_icon_to_channel(nsIURI* aURI, const 
 
   int width = aIconSize;
   int height = aIconSize;
 
   // moz-icon data should have two bytes for the size,
   // then the ARGB pixel values with pre-multiplied Alpha
   const int channels = 4;
   long int buf_size = 2 + channels * height * width;
-  uint8_t* const buf = (uint8_t*)NS_Alloc(buf_size);
+  uint8_t* const buf = (uint8_t*)moz_xmalloc(buf_size);
   NS_ENSURE_TRUE(buf, NS_ERROR_OUT_OF_MEMORY);
   uint8_t* out = buf;
 
   *(out++) = width;
   *(out++) = height;
 
   nsresult rv;
   if (XRE_GetProcessType() == GeckoProcessType_Default) {
--- a/image/decoders/icon/gtk/nsIconChannel.cpp
+++ b/image/decoders/icon/gtk/nsIconChannel.cpp
@@ -42,17 +42,17 @@ moz_gdk_pixbuf_to_channel(GdkPixbuf* aPi
                  gdk_pixbuf_get_colorspace(aPixbuf) == GDK_COLORSPACE_RGB &&
                  gdk_pixbuf_get_bits_per_sample(aPixbuf) == 8 &&
                  gdk_pixbuf_get_has_alpha(aPixbuf) &&
                  gdk_pixbuf_get_n_channels(aPixbuf) == 4,
                  NS_ERROR_UNEXPECTED);
 
   const int n_channels = 4;
   gsize buf_size = 2 + n_channels * height * width;
-  uint8_t* const buf = (uint8_t*)NS_Alloc(buf_size);
+  uint8_t* const buf = (uint8_t*)moz_xmalloc(buf_size);
   NS_ENSURE_TRUE(buf, NS_ERROR_OUT_OF_MEMORY);
   uint8_t* out = buf;
 
   *(out++) = width;
   *(out++) = height;
 
   const guchar* const pixels = gdk_pixbuf_get_pixels(aPixbuf);
   int rowextra = gdk_pixbuf_get_rowstride(aPixbuf) - width * n_channels;
@@ -84,17 +84,17 @@ moz_gdk_pixbuf_to_channel(GdkPixbuf* aPi
   NS_ASSERTION(out == buf + buf_size, "size miscalculation");
 
   nsresult rv;
   nsCOMPtr<nsIStringInputStream> stream =
     do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv);
 
   // Prevent the leaking of buf
   if (NS_WARN_IF(NS_FAILED(rv))) {
-    NS_Free(buf);
+    free(buf);
     return rv;
   }
 
   // stream takes ownership of buf and will free it on destruction.
   // This function cannot fail.
   rv = stream->AdoptData((char*)buf, buf_size);
 
   // If this no longer holds then re-examine buf's lifetime.
--- a/image/decoders/icon/qt/nsIconChannel.cpp
+++ b/image/decoders/icon/qt/nsIconChannel.cpp
@@ -35,17 +35,17 @@ moz_qicon_to_channel(QImage* image, nsIU
   int width = image->width();
   int height = image->height();
 
   NS_ENSURE_TRUE(height < 256 && width < 256 && height > 0 && width > 0,
                  NS_ERROR_UNEXPECTED);
 
   const int n_channels = 4;
   long int buf_size = 2 + n_channels * height * width;
-  uint8_t* const buf = (uint8_t*)NS_Alloc(buf_size);
+  uint8_t* const buf = (uint8_t*)moz_xmalloc(buf_size);
   NS_ENSURE_TRUE(buf, NS_ERROR_OUT_OF_MEMORY);
   uint8_t* out = buf;
 
   *(out++) = width;
   *(out++) = height;
 
   const uchar* const pixels = image->bits();
   int rowextra = image->bytesPerLine() - width * n_channels;
--- a/intl/uconv/nsTextToSubURI.cpp
+++ b/intl/uconv/nsTextToSubURI.cpp
@@ -67,17 +67,17 @@ NS_IMETHODIMP  nsTextToSubURI::ConvertAn
   rv = encoder->SetOutputErrorBehavior(nsIUnicodeEncoder::kOnError_Replace, nullptr, (char16_t)'?');
   if (NS_SUCCEEDED(rv) ) {
     char buf[256];
     char *pBuf = buf;
     int32_t ulen = text ? NS_strlen(text) : 0;
     int32_t outlen = 0;
     if (NS_SUCCEEDED(rv = encoder->GetMaxLength(text, ulen, &outlen))) {
       if (outlen >= 256) {
-        pBuf = (char*)NS_Alloc(outlen+1);
+        pBuf = (char*)moz_xmalloc(outlen+1);
       }
       if (nullptr == pBuf) {
         outlen = 255;
         pBuf = buf;
       }
       int32_t bufLen = outlen;
       if (NS_SUCCEEDED(rv = encoder->Convert(text,&ulen, pBuf, &outlen))) {
         // put termination characters (e.g. ESC(B of ISO-2022-JP) if necessary
@@ -90,17 +90,17 @@ NS_IMETHODIMP  nsTextToSubURI::ConvertAn
         pBuf[outlen] = '\0';
         *_retval = nsEscape(pBuf, url_XPAlphas);
         if (nullptr == *_retval) {
           rv = NS_ERROR_OUT_OF_MEMORY;
         }
       }
     }
     if (pBuf != buf) {
-      NS_Free(pBuf);
+      free(pBuf);
     }
   }
   
   return rv;
 }
 
 NS_IMETHODIMP  nsTextToSubURI::UnEscapeAndConvert(
   const char *charset, const char *text, char16_t **_retval) 
@@ -133,29 +133,29 @@ NS_IMETHODIMP  nsTextToSubURI::UnEscapeA
     return NS_ERROR_UCONV_NOCONV;
   }
   nsCOMPtr<nsIUnicodeDecoder> decoder =
     EncodingUtils::DecoderForEncoding(encoding);
   char16_t *pBuf = nullptr;
   int32_t len = strlen(unescaped);
   int32_t outlen = 0;
   if (NS_SUCCEEDED(rv = decoder->GetMaxLength(unescaped, len, &outlen))) {
-    pBuf = (char16_t *) NS_Alloc((outlen+1)*sizeof(char16_t));
+    pBuf = (char16_t *) moz_xmalloc((outlen+1)*sizeof(char16_t));
     if (nullptr == pBuf) {
       rv = NS_ERROR_OUT_OF_MEMORY;
     } else {
       if (NS_SUCCEEDED(rv = decoder->Convert(unescaped, &len, pBuf, &outlen))) {
         pBuf[outlen] = 0;
         *_retval = pBuf;
       } else {
-        NS_Free(pBuf);
+        free(pBuf);
       }
     }
   }
-  NS_Free(unescaped);
+  free(unescaped);
 
   return rv;
 }
 
 static bool statefulCharset(const char *charset)
 {
   // HZ, UTF-7 and the CN and KR ISO-2022 variants are no longer in
   // mozilla-central but keeping them here just in case for the benefit of
@@ -198,25 +198,25 @@ nsresult nsTextToSubURI::convertURItoUni
 
   unicodeDecoder->SetInputErrorBehavior(nsIUnicodeDecoder::kOnError_Signal);
 
   int32_t srcLen = aURI.Length();
   int32_t dstLen;
   nsresult rv = unicodeDecoder->GetMaxLength(aURI.get(), srcLen, &dstLen);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  char16_t *ustr = (char16_t *) NS_Alloc(dstLen * sizeof(char16_t));
+  char16_t *ustr = (char16_t *) moz_xmalloc(dstLen * sizeof(char16_t));
   NS_ENSURE_TRUE(ustr, NS_ERROR_OUT_OF_MEMORY);
 
   rv = unicodeDecoder->Convert(aURI.get(), &srcLen, ustr, &dstLen);
 
   if (NS_SUCCEEDED(rv))
     _retval.Assign(ustr, dstLen);
   
-  NS_Free(ustr);
+  free(ustr);
 
   return rv;
 }
 
 NS_IMETHODIMP  nsTextToSubURI::UnEscapeURIForUI(const nsACString & aCharset, 
                                                 const nsACString &aURIFragment, 
                                                 nsAString &_retval)
 {
--- a/js/xpconnect/loader/mozJSComponentLoader.h
+++ b/js/xpconnect/loader/mozJSComponentLoader.h
@@ -113,17 +113,17 @@ class mozJSComponentLoader : public mozi
                 JSAutoCompartment ac(cx, obj);
 
                 JS_SetAllNonReservedSlotsToUndefined(cx, obj);
                 obj = nullptr;
                 thisObjectKey = nullptr;
             }
 
             if (location)
-                NS_Free(location);
+                free(location);
 
             obj = nullptr;
             thisObjectKey = nullptr;
             location = nullptr;
         }
 
         size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
 
--- a/js/xpconnect/src/XPCJSID.cpp
+++ b/js/xpconnect/src/XPCJSID.cpp
@@ -28,29 +28,29 @@ nsJSID::nsJSID()
       mNumber(const_cast<char*>(gNoString)),
       mName(const_cast<char*>(gNoString))
 {
 }
 
 nsJSID::~nsJSID()
 {
     if (mNumber && mNumber != gNoString)
-        NS_Free(mNumber);
+        free(mNumber);
     if (mName && mName != gNoString)
-        NS_Free(mName);
+        free(mName);
 }
 
 void nsJSID::Reset()
 {
     mID = GetInvalidIID();
 
     if (mNumber && mNumber != gNoString)
-        NS_Free(mNumber);
+        free(mNumber);
     if (mName && mName != gNoString)
-        NS_Free(mName);
+        free(mName);
 
     mNumber = mName = nullptr;
 }
 
 bool
 nsJSID::SetName(const char* name)
 {
     MOZ_ASSERT(!mName || mName == gNoString ,"name already set");
--- a/js/xpconnect/src/XPCWrappedJS.cpp
+++ b/js/xpconnect/src/XPCWrappedJS.cpp
@@ -619,17 +619,17 @@ nsXPCWrappedJS::DebugDump(int16_t depth)
         char* name;
         GetClass()->GetInterfaceInfo()->GetName(&name);
         XPC_LOG_ALWAYS(("interface name is %s", name));
         if (name)
             free(name);
         char * iid = GetClass()->GetIID().ToString();
         XPC_LOG_ALWAYS(("IID number is %s", iid ? iid : "invalid"));
         if (iid)
-            NS_Free(iid);
+            free(iid);
         XPC_LOG_ALWAYS(("nsXPCWrappedJSClass @ %x", mClass.get()));
 
         if (!IsRootWrapper())
             XPC_LOG_OUTDENT();
         if (mNext) {
             if (IsRootWrapper()) {
                 XPC_LOG_ALWAYS(("Additional wrappers for this object..."));
                 XPC_LOG_INDENT();
--- a/js/xpconnect/src/XPCWrappedJSClass.cpp
+++ b/js/xpconnect/src/XPCWrappedJSClass.cpp
@@ -1476,17 +1476,17 @@ nsXPCWrappedJSClass::DebugDump(int16_t d
         char* name;
         mInfo->GetName(&name);
         XPC_LOG_ALWAYS(("interface name is %s", name));
         if (name)
             free(name);
         char * iid = mIID.ToString();
         XPC_LOG_ALWAYS(("IID number is %s", iid ? iid : "invalid"));
         if (iid)
-            NS_Free(iid);
+            free(iid);
         XPC_LOG_ALWAYS(("InterfaceInfo @ %x", mInfo.get()));
         uint16_t methodCount = 0;
         if (depth) {
             uint16_t i;
             nsCOMPtr<nsIInterfaceInfo> parent;
             XPC_LOG_INDENT();
             mInfo->GetParent(getter_AddRefs(parent));
             XPC_LOG_ALWAYS(("parent @ %x", parent.get()));
--- a/js/xpconnect/tests/components/native/xpctest_params.cpp
+++ b/js/xpconnect/tests/components/native/xpctest_params.cpp
@@ -44,25 +44,25 @@ nsXPCTestParams::~nsXPCTestParams()
 //   'padding' is an offset added to length, allowing us to handle
 //             null-terminated strings.
 //   'TAKE_OWNERSHIP' is one of the macros above.
 #define BUFFER_METHOD_IMPL(type, padding, TAKE_OWNERSHIP) {                   \
     uint32_t elemSize = sizeof(type);                                         \
                                                                               \
     /* Copy b into rv. */                                                     \
     *rvLength = *bLength;                                                     \
-    *rv = static_cast<type*>(NS_Alloc(elemSize * (*bLength + padding)));      \
+    *rv = static_cast<type*>(moz_xmalloc(elemSize * (*bLength + padding)));   \
     if (!*rv)                                                                 \
         return NS_ERROR_OUT_OF_MEMORY;                                        \
     memcpy(*rv, *b, elemSize * (*bLength + padding));                         \
                                                                               \
     /* Copy a into b. */                                                      \
     *bLength = aLength;                                                       \
-    NS_Free(*b);                                                              \
-    *b = static_cast<type*>(NS_Alloc(elemSize * (aLength + padding)));        \
+    free(*b);                                                                 \
+    *b = static_cast<type*>(moz_xmalloc(elemSize * (aLength + padding)));     \
     if (!*b)                                                                  \
         return NS_ERROR_OUT_OF_MEMORY;                                        \
     memcpy(*b, a, elemSize * (aLength + padding));                            \
                                                                               \
     /* We need to take ownership of the data we got from a,                   \
        since the caller owns it. */                                           \
     for (unsigned i = 0; i < *bLength + padding; ++i)                         \
         TAKE_OWNERSHIP((*b)[i]);                                              \
@@ -141,17 +141,17 @@ NS_IMETHODIMP nsXPCTestParams::TestStrin
 {
     nsDependentCString aprime(a);
     nsDependentCString bprime(*b);
     *_retval = ToNewCString(bprime);
     *b = ToNewCString(aprime);
 
     // XPCOM ownership rules dictate that overwritten inout params must be callee-freed.
     // See https://developer.mozilla.org/en/XPIDL
-    NS_Free(const_cast<char*>(bprime.get()));
+    free(const_cast<char*>(bprime.get()));
 
     return NS_OK;
 }
 
 /* wchar testWchar (in wchar a, inout wchar b); */
 NS_IMETHODIMP nsXPCTestParams::TestWchar(char16_t a, char16_t* b, char16_t* _retval)
 {
     GENERIC_METHOD_IMPL;
@@ -162,17 +162,17 @@ NS_IMETHODIMP nsXPCTestParams::TestWstri
 {
     nsDependentString aprime(a);
     nsDependentString bprime(*b);
     *_retval = ToNewUnicode(bprime);
     *b = ToNewUnicode(aprime);
 
     // XPCOM ownership rules dictate that overwritten inout params must be callee-freed.
     // See https://developer.mozilla.org/en/XPIDL
-    NS_Free((void*)bprime.get());
+    free((void*)bprime.get());
 
     return NS_OK;
 }
 
 /* DOMString testDOMString (in DOMString a, inout DOMString b); */
 NS_IMETHODIMP nsXPCTestParams::TestDOMString(const nsAString & a, nsAString & b, nsAString & _retval)
 {
     STRING_METHOD_IMPL;
@@ -292,17 +292,17 @@ NS_IMETHODIMP nsXPCTestParams::TestInter
     // by XPConnect for the duration of the call. If we snatch it away from b
     // and leave no trace, XPConnect won't Release it. Since we also need to
     // return an already-AddRef'd pointer in rv, we don't need to do anything
     // special here.
     *rv = *b;
 
     // rvIID is out-only, so nobody allocated an IID buffer for us. Do that now,
     // and store b's IID in the new buffer.
-    *rvIID = static_cast<nsIID*>(NS_Alloc(sizeof(nsID)));
+    *rvIID = static_cast<nsIID*>(moz_xmalloc(sizeof(nsID)));
     if (!*rvIID)
         return NS_ERROR_OUT_OF_MEMORY;
     **rvIID = **bIID;
 
     // Copy the interface pointer from a to b. Since a is in-only, XPConnect will
     // release it upon completion of the call. AddRef it for b.
     *b = a;
     static_cast<nsISupports*>(*b)->AddRef();
@@ -323,17 +323,17 @@ NS_IMETHODIMP nsXPCTestParams::TestInter
                                                     void** a,
                                                     uint32_t* bLength, nsIID** bIID,
                                                     void*** b,
                                                     uint32_t* rvLength, nsIID** rvIID,
                                                     void*** rv)
 {
     // Transfer the IIDs. See the comments in TestInterfaceIs (above) for an
     // explanation of what we're doing.
-    *rvIID = static_cast<nsIID*>(NS_Alloc(sizeof(nsID)));
+    *rvIID = static_cast<nsIID*>(moz_xmalloc(sizeof(nsID)));
     if (!*rvIID)
         return NS_ERROR_OUT_OF_MEMORY;
     **rvIID = **bIID;
     **bIID = *aIID;
 
     // The macro is agnostic to the actual interface types, so we can re-use code here.
     //
     // Do this second, since the macro returns.
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -10408,28 +10408,28 @@ void ReflowCountMgr::PaintCount(const ch
 }
 
 //------------------------------------------------------------------
 int ReflowCountMgr::RemoveItems(PLHashEntry *he, int i, void *arg)
 {
   char *str = (char *)he->key;
   ReflowCounter * counter = (ReflowCounter *)he->value;
   delete counter;
-  NS_Free(str);
+  free(str);
 
   return HT_ENUMERATE_REMOVE;
 }
 
 //------------------------------------------------------------------
 int ReflowCountMgr::RemoveIndiItems(PLHashEntry *he, int i, void *arg)
 {
   char *str = (char *)he->key;
   IndiReflowCounter * counter = (IndiReflowCounter *)he->value;
   delete counter;
-  NS_Free(str);
+  free(str);
 
   return HT_ENUMERATE_REMOVE;
 }
 
 //------------------------------------------------------------------
 void ReflowCountMgr::CleanUp()
 {
   if (nullptr != mCounts) {
--- a/layout/inspector/inDOMUtils.cpp
+++ b/layout/inspector/inDOMUtils.cpp
@@ -91,17 +91,17 @@ inDOMUtils::GetAllStyleSheets(nsIDOMDocu
     }
   }
 
   // Get the document sheets.
   for (int32_t i = 0; i < document->GetNumberOfStyleSheets(); i++) {
     sheets.AppendElement(document->GetStyleSheetAt(i));
   }
 
-  nsISupports** ret = static_cast<nsISupports**>(NS_Alloc(sheets.Count() *
+  nsISupports** ret = static_cast<nsISupports**>(moz_xmalloc(sheets.Count() *
                                                  sizeof(nsISupports*)));
 
   for (int32_t i = 0; i < sheets.Count(); i++) {
     NS_ADDREF(ret[i] = sheets[i]);
   }
 
   *aLength = sheets.Count();
   *aSheets = ret;
@@ -768,17 +768,17 @@ inDOMUtils::GetCSSValuesForProperty(cons
   }
   // All CSS properties take initial, inherit and unset.
   InsertNoDuplicates(array, NS_LITERAL_STRING("initial"));
   InsertNoDuplicates(array, NS_LITERAL_STRING("inherit"));
   InsertNoDuplicates(array, NS_LITERAL_STRING("unset"));
 
   *aLength = array.Length();
   char16_t** ret =
-    static_cast<char16_t**>(NS_Alloc(*aLength * sizeof(char16_t*)));
+    static_cast<char16_t**>(moz_xmalloc(*aLength * sizeof(char16_t*)));
   for (uint32_t i = 0; i < *aLength; ++i) {
     ret[i] = ToNewUnicode(array[i]);
   }
   *aValues = ret;
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/layout/printing/nsPrintData.cpp
+++ b/layout/printing/nsPrintData.cpp
@@ -93,17 +93,17 @@ nsPrintData::~nsPrintData()
         // XXX nsPrintData::ShowPrintErrorDialog(rv);
       }
     }
   }
 
   delete mPrintObject;
 
   if (mBrandName) {
-    NS_Free(mBrandName);
+    free(mBrandName);
   }
 }
 
 void nsPrintData::OnStartPrinting()
 {
   if (!mOnStartSent) {
     DoOnProgressChange(0, 0, true, nsIWebProgressListener::STATE_START|nsIWebProgressListener::STATE_IS_DOCUMENT|nsIWebProgressListener::STATE_IS_NETWORK);
     mOnStartSent = true;
--- a/layout/style/FontFace.cpp
+++ b/layout/style/FontFace.cpp
@@ -125,17 +125,17 @@ FontFace::~FontFace()
 
   SetUserFontEntry(nullptr);
 
   if (mFontFaceSet && !IsInFontFaceSet()) {
     mFontFaceSet->RemoveUnavailableFontFace(this);
   }
 
   if (mSourceBuffer) {
-    NS_Free(mSourceBuffer);
+    free(mSourceBuffer);
   }
 }
 
 JSObject*
 FontFace::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
 {
   return FontFaceBinding::Wrap(aCx, this, aGivenProto);
 }
--- a/layout/style/FontFaceSet.cpp
+++ b/layout/style/FontFaceSet.cpp
@@ -1257,17 +1257,17 @@ FontFaceSet::SyncLoadFontData(gfxUserFon
     return NS_ERROR_FAILURE;
   }
   if (bufferLength64 > UINT32_MAX) {
     return NS_ERROR_FILE_TOO_BIG;
   }
   aBufferLength = static_cast<uint32_t>(bufferLength64);
 
   // read all the decoded data
-  aBuffer = static_cast<uint8_t*> (NS_Alloc(sizeof(uint8_t) * aBufferLength));
+  aBuffer = static_cast<uint8_t*> (moz_xmalloc(sizeof(uint8_t) * aBufferLength));
   if (!aBuffer) {
     aBufferLength = 0;
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   uint32_t numRead, totalRead = 0;
   while (NS_SUCCEEDED(rv =
            stream->Read(reinterpret_cast<char*>(aBuffer + totalRead),
@@ -1284,17 +1284,17 @@ FontFaceSet::SyncLoadFontData(gfxUserFon
   // make sure there's a mime type
   if (NS_SUCCEEDED(rv)) {
     nsAutoCString mimeType;
     rv = channel->GetContentType(mimeType);
     aBufferLength = totalRead;
   }
 
   if (NS_FAILED(rv)) {
-    NS_Free(aBuffer);
+    free(aBuffer);
     aBuffer = nullptr;
     aBufferLength = 0;
     return rv;
   }
 
   return NS_OK;
 }
 
--- a/layout/style/StyleRule.cpp
+++ b/layout/style/StyleRule.cpp
@@ -205,17 +205,17 @@ nsPseudoClassList::SizeOfIncludingThis(m
 }
 
 nsPseudoClassList::~nsPseudoClassList(void)
 {
   MOZ_COUNT_DTOR(nsPseudoClassList);
   if (nsCSSPseudoClasses::HasSelectorListArg(mType)) {
     delete u.mSelectors;
   } else if (u.mMemory) {
-    NS_Free(u.mMemory);
+    free(u.mMemory);
   }
   NS_CSS_DELETE_LIST_MEMBER(nsPseudoClassList, this, mNext);
 }
 
 nsAttrSelector::nsAttrSelector(int32_t aNameSpace, const nsString& aAttr)
   : mValue(),
     mNext(nullptr),
     mLowercaseAttr(nullptr),
--- a/layout/style/StyleRule.h
+++ b/layout/style/StyleRule.h
@@ -66,17 +66,17 @@ public:
     //   a. no value, which means mMemory is always null
     //      (if none of the conditions for (b), (c), or (d) is true)
     //   b. a string value, which means mString/mMemory is non-null
     //      (if nsCSSPseudoClasses::HasStringArg(mType))
     //   c. an integer pair value, which means mNumbers/mMemory is non-null
     //      (if nsCSSPseudoClasses::HasNthPairArg(mType))
     //   d. a selector list, which means mSelectors is non-null
     //      (if nsCSSPseudoClasses::HasSelectorListArg(mType))
-    void*           mMemory; // mString and mNumbers use NS_Alloc/NS_Free
+    void*           mMemory; // mString and mNumbers use moz_xmalloc/free
     char16_t*      mString;
     int32_t*        mNumbers;
     nsCSSSelectorList* mSelectors;
   } u;
   nsCSSPseudoClasses::Type mType;
   nsPseudoClassList* mNext;
 private: 
   nsPseudoClassList* Clone(bool aDeep) const;
--- a/layout/style/nsStyleStruct.cpp
+++ b/layout/style/nsStyleStruct.cpp
@@ -1881,17 +1881,17 @@ nsStyleImage::SetNull()
   MOZ_ASSERT(!mImageTracked,
              "Calling SetNull() with image tracked!");
 
   if (mType == eStyleImageType_Gradient)
     mGradient->Release();
   else if (mType == eStyleImageType_Image)
     NS_RELEASE(mImage);
   else if (mType == eStyleImageType_Element)
-    NS_Free(mElementId);
+    free(mElementId);
 
   mType = eStyleImageType_Null;
   mCropRect = nullptr;
 }
 
 void
 nsStyleImage::SetImageData(imgRequestProxy* aImage)
 {
@@ -2979,17 +2979,17 @@ nsStyleContentData::~nsStyleContentData(
   MOZ_ASSERT(!mImageTracked,
              "nsStyleContentData being destroyed while still tracking image!");
   if (mType == eStyleContentType_Image) {
     NS_IF_RELEASE(mContent.mImage);
   } else if (mType == eStyleContentType_Counter ||
              mType == eStyleContentType_Counters) {
     mContent.mCounters->Release();
   } else if (mContent.mString) {
-    NS_Free(mContent.mString);
+    free(mContent.mString);
   }
 }
 
 nsStyleContentData& nsStyleContentData::operator=(const nsStyleContentData& aOther)
 {
   if (this == &aOther)
     return *this;
   this->~nsStyleContentData();
--- a/memory/replace/dmd/dmd.py
+++ b/memory/replace/dmd/dmd.py
@@ -32,18 +32,16 @@ allocatorFns = [
     # Matches calloc, replace_calloc, moz_xcalloc, vpx_calloc, js_calloc, pod_calloc, malloc_zone_calloc, pod_callocCanGC.
     'calloc',
     # Matches realloc, replace_realloc, moz_xrealloc, vpx_realloc, js_realloc, pod_realloc, pod_reallocCanGC.
     'realloc',
     # Matches memalign, posix_memalign, replace_memalign, replace_posix_memalign, moz_xmemalign, moz_xposix_memalign, vpx_memalign, malloc_zone_memalign.
     'memalign',
     'operator new(',
     'operator new[](',
-    'NS_Alloc',
-    'NS_Realloc',
     'g_slice_alloc',
     # This one necessary to fully filter some sequences of allocation functions
     # that happen in practice. Note that ??? entries that follow non-allocation
     # functions won't be stripped, as explained above.
     '???',
 ]
 
 class Record(object):
--- a/modules/libpref/Preferences.cpp
+++ b/modules/libpref/Preferences.cpp
@@ -973,17 +973,17 @@ Preferences::WritePrefFile(nsIFile* aFil
   // write out the file header
   outStream->Write(outHeader, sizeof(outHeader) - 1, &writeAmount);
 
   char** walker = valueArray;
   for (uint32_t valueIdx = 0; valueIdx < gHashTable.EntryCount(); valueIdx++, walker++) {
     if (*walker) {
       outStream->Write(*walker, strlen(*walker), &writeAmount);
       outStream->Write(NS_LINEBREAK, NS_LINEBREAK_LEN, &writeAmount);
-      NS_Free(*walker);
+      free(*walker);
     }
   }
 
   // tell the safe output stream to overwrite the real prefs file
   // (it'll abort if there were any errors during writing)
   nsCOMPtr<nsISafeOutputStream> safeStream = do_QueryInterface(outStream);
   NS_ASSERTION(safeStream, "expected a safe output stream!");
   if (safeStream) {
--- a/netwerk/base/nsStandardURL.cpp
+++ b/netwerk/base/nsStandardURL.cpp
@@ -884,17 +884,17 @@ nsStandardURL::AppendToSubstring(uint32_
         return nullptr;
 
     uint32_t tailLen = strlen(tail);
 
     // Check for int overflow for proposed length of combined string
     if (UINT32_MAX - ((uint32_t)len + 1) < tailLen)
         return nullptr;
 
-    char *result = (char *) NS_Alloc(len + tailLen + 1);
+    char *result = (char *) moz_xmalloc(len + tailLen + 1);
     if (result) {
         memcpy(result, mSpec.get() + pos, len);
         memcpy(result + len, tail, tailLen);
         result[len + tailLen] = '\0';
     }
     return result;
 }
 
--- a/netwerk/cache/nsDiskCacheDeviceSQL.cpp
+++ b/netwerk/cache/nsDiskCacheDeviceSQL.cpp
@@ -2281,17 +2281,17 @@ nsOfflineCacheDevice::RunSimpleQuery(moz
     valArray.AppendElement(
       nsDependentCString(statement->AsSharedUTF8String(resultIndex, &length)));
 
     rv = statement->ExecuteStep(&hasRows);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   *count = valArray.Length();
-  char **ret = static_cast<char **>(NS_Alloc(*count * sizeof(char*)));
+  char **ret = static_cast<char **>(moz_xmalloc(*count * sizeof(char*)));
   if (!ret) return NS_ERROR_OUT_OF_MEMORY;
 
   for (uint32_t i = 0; i <  *count; i++) {
     ret[i] = NS_strdup(valArray[i].get());
     if (!ret[i]) {
       NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(i, ret);
       return NS_ERROR_OUT_OF_MEMORY;
     }
--- a/netwerk/protocol/websocket/WebSocketChannel.cpp
+++ b/netwerk/protocol/websocket/WebSocketChannel.cpp
@@ -2049,17 +2049,17 @@ WebSocketChannel::PrimeNewOutgoingMessag
     nsresult rv = mRandomGenerator->GenerateRandomBytes(4, &buffer);
     if (NS_FAILED(rv)) {
       LOG(("WebSocketChannel::PrimeNewOutgoingMessage(): "
            "GenerateRandomBytes failure %x\n", rv));
       StopSession(rv);
       return;
     }
     mask = * reinterpret_cast<uint32_t *>(buffer);
-    NS_Free(buffer);
+    free(buffer);
   } while (!mask);
   NetworkEndian::writeUint32(payload - sizeof(uint32_t), mask);
 
   LOG(("WebSocketChannel::PrimeNewOutgoingMessage() using mask %08x\n", mask));
 
   // We don't mask the framing, but occasionally we stick a little payload
   // data in the buffer used for the framing. Close frames are the current
   // example. This data needs to be masked, but it is never more than a
@@ -2487,17 +2487,17 @@ WebSocketChannel::SetupRequest()
                                    false);
 
   uint8_t      *secKey;
   nsAutoCString secKeyString;
 
   rv = mRandomGenerator->GenerateRandomBytes(16, &secKey);
   NS_ENSURE_SUCCESS(rv, rv);
   char* b64 = PL_Base64Encode((const char *)secKey, 16, nullptr);
-  NS_Free(secKey);
+  free(secKey);
   if (!b64)
     return NS_ERROR_OUT_OF_MEMORY;
   secKeyString.Assign(b64);
   PR_Free(b64);
   mHttpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Sec-WebSocket-Key"),
                                  secKeyString, false);
   LOG(("WebSocketChannel::SetupRequest: client key %s\n", secKeyString.get()));
 
--- a/netwerk/streamconv/converters/nsDirIndexParser.cpp
+++ b/netwerk/streamconv/converters/nsDirIndexParser.cpp
@@ -250,17 +250,17 @@ nsDirIndexParser::ParseData(nsIDirIndex 
         if (NS_SUCCEEDED(rv = gTextToSubURI->UnEscapeAndConvert(mEncoding.get(), filename.get(),
                                                                 &result)) && (result)) {
           if (*result) {
             aIdx->SetLocation(filename.get());
             if (!mHasDescription)
               aIdx->SetDescription(result);
             success = true;
           }
-          NS_Free(result);
+          free(result);
         } else {
           NS_WARNING("UnEscapeAndConvert error");
         }
       }
       
       if (!success) {
         // if unsuccessfully at charset conversion, then
         // just fallback to unescape'ing in-place
--- a/parser/html/nsParserUtils.cpp
+++ b/parser/html/nsParserUtils.cpp
@@ -168,17 +168,17 @@ nsParserUtils::ParseFragment(const nsASt
       base.AppendLiteral(XHTML_DIV_TAG);
       base.AppendLiteral(" xml:base=\"");
       aBaseURI->GetSpec(spec);
       // nsEscapeHTML is good enough, because we only need to get
       // quotes, ampersands, and angle brackets
       char* escapedSpec = nsEscapeHTML(spec.get());
       if (escapedSpec)
         base += escapedSpec;
-      NS_Free(escapedSpec);
+      free(escapedSpec);
       base.Append('"');
       tagStack.AppendElement(NS_ConvertUTF8toUTF16(base));
     }  else {
       tagStack.AppendElement(NS_LITERAL_STRING(XHTML_DIV_TAG));
     }
   }
 
   nsresult rv = NS_OK;
--- a/rdf/base/nsInMemoryDataSource.cpp
+++ b/rdf/base/nsInMemoryDataSource.cpp
@@ -903,17 +903,17 @@ InMemoryDataSource::LogOperation(const c
         nsXPIDLString value;
         literal->GetValue(getter_Copies(value));
         nsAutoString valueStr(value);
         char* valueCStr = ToNewCString(valueStr);
 
         PR_LogPrint
            ("  -->(\"%s\")\n", valueCStr);
 
-        NS_Free(valueCStr);
+        free(valueCStr);
     }
     else {
         PR_LogPrint
            ("  -->(unknown-type)\n");
     }
 }
 #endif
 
--- a/rdf/base/nsRDFContentSink.cpp
+++ b/rdf/base/nsRDFContentSink.cpp
@@ -450,17 +450,17 @@ RDFContentSinkImpl::HandleEndElement(con
       if (PR_LOG_TEST(gLog, PR_LOG_WARNING)) {
           nsAutoString tagStr(aName);
           char* tagCStr = ToNewCString(tagStr);
 
           PR_LogPrint
                  ("rdfxml: extra close tag '%s' at line %d",
                   tagCStr, 0/*XXX fix me */);
 
-          NS_Free(tagCStr);
+          free(tagCStr);
       }
 #endif
 
       return NS_ERROR_UNEXPECTED; // XXX
   }
 
   // If we've just popped a member or property element, _now_ is the
   // time to add that element to the graph.
--- a/rdf/datasource/nsFileSystemDataSource.cpp
+++ b/rdf/datasource/nsFileSystemDataSource.cpp
@@ -1007,17 +1007,17 @@ FileSystemDataSource::GetFolderList(nsIR
 
         char    *escLeafStr = nsEscape(NS_ConvertUTF16toUTF8(leafStr).get(), url_Path);
         leafStr.Truncate();
 
         if (!escLeafStr)
             continue;
   
         nsAutoCString           leaf(escLeafStr);
-        NS_Free(escLeafStr);
+        free(escLeafStr);
         escLeafStr = nullptr;
 
         // using nsEscape() [above] doesn't escape slashes, so do that by hand
         int32_t         aOffset;
         while ((aOffset = leaf.FindChar('/')) >= 0)
         {
             leaf.Cut((uint32_t)aOffset, 1);
             leaf.Insert("%2F", (uint32_t)aOffset);
--- a/security/manager/ssl/src/nsNSSCallbacks.cpp
+++ b/security/manager/ssl/src/nsNSSCallbacks.cpp
@@ -851,17 +851,17 @@ void PK11PasswordPromptRunnable::RunOnTa
       bool checkState = false;
       rv = prompt->PromptPassword(nullptr, promptString.get(),
                                   &password, nullptr, &checkState, &value);
     }
   }
   
   if (NS_SUCCEEDED(rv) && value) {
     mResult = ToNewUTF8String(nsDependentString(password));
-    NS_Free(password);
+    free(password);
   }
 }
 
 char*
 PK11PasswordPrompt(PK11SlotInfo* slot, PRBool retry, void* arg)
 {
   RefPtr<PK11PasswordPromptRunnable> runnable(
     new PK11PasswordPromptRunnable(slot,
--- a/security/manager/ssl/src/nsRandomGenerator.cpp
+++ b/security/manager/ssl/src/nsRandomGenerator.cpp
@@ -25,25 +25,25 @@ nsRandomGenerator::GenerateRandomBytes(u
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   mozilla::ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
   if (!slot) {
     return NS_ERROR_FAILURE;
   }
 
-  uint8_t* buf = reinterpret_cast<uint8_t*>(NS_Alloc(aLength));
+  uint8_t* buf = reinterpret_cast<uint8_t*>(moz_xmalloc(aLength));
   if (!buf) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   SECStatus srv = PK11_GenerateRandomOnSlot(slot, buf, aLength);
 
   if (srv != SECSuccess) {
-    NS_Free(buf);
+    free(buf);
     return NS_ERROR_FAILURE;
   }
 
   *aBuffer = buf;
 
   return NS_OK;
 }
 
--- a/storage/public/mozIStorageBindingParams.idl
+++ b/storage/public/mozIStorageBindingParams.idl
@@ -35,17 +35,17 @@ interface mozIStorageBindingParams : nsI
                        [array, const, size_is(aValueSize)] in octet aValue,
                        in unsigned long aValueSize);
 
    // Convenience routines for storing strings as blobs.
    void bindStringAsBlobByName(in AUTF8String aName, in AString aValue);
    void bindUTF8StringAsBlobByName(in AUTF8String aName, in AUTF8String aValue);
 
    // The function adopts the storage for the provided blob.  After calling
-   // this function, mozStorage will ensure that NS_Free is called on the
+   // this function, mozStorage will ensure that free is called on the
    // underlying pointer.
    [noscript]
    void bindAdoptedBlobByName(in AUTF8String aName,
                               [array, size_is(aValueSize)] in octet aValue,
                               in unsigned long aValueSize);
 
    /**
     * Binds aValue to the parameter with the index aIndex.
@@ -72,15 +72,15 @@ interface mozIStorageBindingParams : nsI
                         [array, const, size_is(aValueSize)] in octet aValue,
                         in unsigned long aValueSize);
 
    // Convenience routines for storing strings as blobs.
    void bindStringAsBlobByIndex(in unsigned long aIndex, in AString aValue);
    void bindUTF8StringAsBlobByIndex(in unsigned long aIndex, in AUTF8String aValue);
 
    // The function adopts the storage for the provided blob.  After calling
-   // this function, mozStorage will ensure that NS_Free is called on the
+   // this function, mozStorage will ensure that free is called on the
    // underlying pointer.
    [noscript]
    void bindAdoptedBlobByIndex(in unsigned long aIndex,
                                [array, size_is(aValueSize)] in octet aValue,
                                in unsigned long aValueSize);
 };
--- a/storage/src/Variant.h
+++ b/storage/src/Variant.h
@@ -276,17 +276,17 @@ struct variant_storage_traits<uint8_t[],
   typedef std::pair<uint8_t *, int> StorageType;
   static inline void storage_conversion(ConstructorType aBlob, StorageType* _outData)
   {
     *_outData = aBlob;
   }
   static inline void destroy(StorageType &aData)
   {
     if (aData.first) {
-      NS_Free(aData.first);
+      free(aData.first);
       aData.first = nullptr;
     }
   }
 };
 template < >
 struct variant_blob_traits<uint8_t[], false>
 {
   static inline nsresult asArray(FallibleTArray<uint8_t> &aData,
--- a/storage/src/mozStorageBindingParams.cpp
+++ b/storage/src/mozStorageBindingParams.cpp
@@ -87,17 +87,17 @@ sqlite3_T_null(BindingColumnData aData)
 }
 
 int
 sqlite3_T_blob(BindingColumnData aData,
                const void *aBlob,
                int aSize)
 {
   return ::sqlite3_bind_blob(aData.stmt, aData.column + 1, aBlob, aSize,
-                             NS_Free);
+                             free);
 
 }
 
 #include "variantToSQLiteT_impl.h"
 
 } // anonymous namespace
 
 ////////////////////////////////////////////////////////////////////////////////
--- a/storage/src/mozStorageConnection.cpp
+++ b/storage/src/mozStorageConnection.cpp
@@ -125,17 +125,17 @@ sqlite3_T_null(sqlite3_context *aCtx)
   return SQLITE_OK;
 }
 
 int
 sqlite3_T_blob(sqlite3_context *aCtx,
                const void *aData,
                int aSize)
 {
-  ::sqlite3_result_blob(aCtx, aData, aSize, NS_Free);
+  ::sqlite3_result_blob(aCtx, aData, aSize, free);
   return SQLITE_OK;
 }
 
 #include "variantToSQLiteT_impl.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 //// Modules
 
--- a/storage/src/variantToSQLiteT_impl.h
+++ b/storage/src/variantToSQLiteT_impl.h
@@ -102,17 +102,17 @@ variantToSQLiteT(T aObj,
       NS_ENSURE_SUCCESS(rv, SQLITE_MISMATCH);
 
       // Check to make sure it's a supported type.
       NS_ASSERTION(type == nsIDataType::VTYPE_UINT8,
                    "Invalid type passed!  You may leak!");
       if (type != nsIDataType::VTYPE_UINT8) {
         // Technically this could leak with certain data types, but somebody was
         // being stupid passing us this anyway.
-        NS_Free(data);
+        free(data);
         return SQLITE_MISMATCH;
       }
 
       // Finally do our thing.  The function should free the array accordingly!
       int rc = sqlite3_T_blob(aObj, data, count);
       return rc;
     }
     // Maybe, it'll be possible to convert these
--- a/toolkit/components/commandlines/nsCommandLine.cpp
+++ b/toolkit/components/commandlines/nsCommandLine.cpp
@@ -484,17 +484,17 @@ LogConsoleMessage(const char16_t* fmt, .
   va_start(args, fmt);
   char16_t* msg = nsTextFormatter::vsmprintf(fmt, args);
   va_end(args);
 
   nsCOMPtr<nsIConsoleService> cs = do_GetService("@mozilla.org/consoleservice;1");
   if (cs)
     cs->LogStringMessage(msg);
 
-  NS_Free(msg);
+  free(msg);
 }
 
 nsresult
 nsCommandLine::EnumerateHandlers(EnumerateHandlersCallback aCallback, void *aClosure)
 {
   nsresult rv;
 
   nsCOMPtr<nsICategoryManager> catman
--- a/toolkit/components/filepicker/nsFileView.cpp
+++ b/toolkit/components/filepicker/nsFileView.cpp
@@ -288,17 +288,17 @@ nsFileView::nsFileView() :
   mReverseSort(false)
 {
 }
 
 nsFileView::~nsFileView()
 {
   uint32_t count = mCurrentFilters.Length();
   for (uint32_t i = 0; i < count; ++i)
-    NS_Free(mCurrentFilters[i]);
+    free(mCurrentFilters[i]);
 }
 
 nsresult
 nsFileView::Init()
 {
   mDateFormatter = do_CreateInstance(NS_DATETIMEFORMAT_CONTRACTID);
   if (!mDateFormatter)
     return NS_ERROR_OUT_OF_MEMORY;
@@ -464,17 +464,17 @@ nsFileView::SetDirectory(nsIFile* aDirec
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsFileView::SetFilter(const nsAString& aFilterString)
 {
   uint32_t filterCount = mCurrentFilters.Length();
   for (uint32_t i = 0; i < filterCount; ++i)
-    NS_Free(mCurrentFilters[i]);
+    free(mCurrentFilters[i]);
   mCurrentFilters.Clear();
 
   nsAString::const_iterator start, iter, end;
   aFilterString.BeginReading(iter);
   aFilterString.EndReading(end);
 
   while (true) {
     // skip over delimiters
@@ -493,17 +493,17 @@ nsFileView::SetFilter(const nsAString& a
     while (iter != end && (*iter != ';' && *iter != ' '))
       ++iter;
 
     char16_t* filter = ToNewUnicode(Substring(start, iter));
     if (!filter)
       return NS_ERROR_OUT_OF_MEMORY;
 
     if (!mCurrentFilters.AppendElement(filter)) {
-      NS_Free(filter);
+      free(filter);
       return NS_ERROR_OUT_OF_MEMORY;
     }
 
     if (iter == end)
       break;
 
     ++iter; // we know this is either ';' or ' ', skip to next char
   }
--- a/toolkit/components/parentalcontrols/nsParentalControlsServiceWin.cpp
+++ b/toolkit/components/parentalcontrols/nsParentalControlsServiceWin.cpp
@@ -278,17 +278,17 @@ nsParentalControlsService::RequestURIOve
   if (SUCCEEDED(mPC->GetWebSettings(nullptr, getter_AddRefs(wpcws)))) {
     wpcws->RequestURLOverride(hWnd, NS_ConvertUTF8toUTF16(rootSpec).get(),
                              uriIdx, (LPCWSTR*)arrUrls.get(), &ret);
    *_retval = ret;
   }
 
   // Free up the allocated strings in our array
   for (idx = 0; idx < uriIdx; idx++)
-    NS_Free((void*)arrUrls[idx]);
+    free((void*)arrUrls[idx]);
 
   return NS_OK;
 }
 
 //------------------------------------------------------------------------
 
 // Sends a file download event to the Vista Event Log 
 void
--- a/toolkit/components/places/nsAnnoProtocolHandler.cpp
+++ b/toolkit/components/places/nsAnnoProtocolHandler.cpp
@@ -125,17 +125,17 @@ public:
       if (NS_FAILED(rv) || !bytesWritten)
         break;
       totalWritten += bytesWritten;
     } while (size != totalWritten);
     NS_ASSERTION(NS_FAILED(rv) || size == totalWritten,
                  "Failed to write all of our data out to the stream!");
 
     // Free our favicon array.
-    NS_Free(favicon);
+    free(favicon);
 
     // Handle an error to write if it occurred, but only after we've freed our
     // favicon.
     NS_ENSURE_SUCCESS(rv, rv);
 
     // At this point, we should have written out all of our data to our stream.
     // HandleCompletion will close the output stream, so we are done here.
     mReturnDefaultIcon = false;
--- a/toolkit/components/places/nsNavHistoryQuery.cpp
+++ b/toolkit/components/places/nsNavHistoryQuery.cpp
@@ -1143,28 +1143,28 @@ NS_IMETHODIMP nsNavHistoryQuery::GetTags
 
   uint32_t arrayLen = mTags.Length();
 
   if (arrayLen == 0)
     rv = out->SetAsEmptyArray();
   else {
     // Note: The resulting nsIVariant dupes both the array and its elements.
     const char16_t **array = reinterpret_cast<const char16_t **>
-                              (NS_Alloc(arrayLen * sizeof(char16_t *)));
+                              (moz_xmalloc(arrayLen * sizeof(char16_t *)));
     NS_ENSURE_TRUE(array, NS_ERROR_OUT_OF_MEMORY);
 
     for (uint32_t i = 0; i < arrayLen; ++i) {
       array[i] = mTags[i].get();
     }
 
     rv = out->SetAsArray(nsIDataType::VTYPE_WCHAR_STR,
                          nullptr,
                          arrayLen,
                          reinterpret_cast<void *>(array));
-    NS_Free(array);
+    free(array);
   }
   NS_ENSURE_SUCCESS(rv, rv);
 
   out.forget(aTags);
   return NS_OK;
 }
 
 NS_IMETHODIMP nsNavHistoryQuery::SetTags(nsIVariant *aTags)
@@ -1197,61 +1197,61 @@ NS_IMETHODIMP nsNavHistoryQuery::SetTags
   if (eltType != nsIDataType::VTYPE_WCHAR_STR) {
     switch (eltType) {
     case nsIDataType::VTYPE_ID:
     case nsIDataType::VTYPE_CHAR_STR:
       {
         char **charArray = reinterpret_cast<char **>(array);
         for (uint32_t i = 0; i < arrayLen; ++i) {
           if (charArray[i])
-            NS_Free(charArray[i]);
+            free(charArray[i]);
         }
       }
       break;
     case nsIDataType::VTYPE_INTERFACE:
     case nsIDataType::VTYPE_INTERFACE_IS:
       {
         nsISupports **supportsArray = reinterpret_cast<nsISupports **>(array);
         for (uint32_t i = 0; i < arrayLen; ++i) {
           NS_IF_RELEASE(supportsArray[i]);
         }
       }
       break;
     // The other types are primitives that do not need to be freed.
     }
-    NS_Free(array);
+    free(array);
     return NS_ERROR_ILLEGAL_VALUE;
   }
 
   char16_t **tags = reinterpret_cast<char16_t **>(array);
   mTags.Clear();
 
   // Finally, add each passed-in tag to our mTags array and then sort it.
   for (uint32_t i = 0; i < arrayLen; ++i) {
 
     // Don't allow nulls.
     if (!tags[i]) {
-      NS_Free(tags);
+      free(tags);
       return NS_ERROR_ILLEGAL_VALUE;
     }
 
     nsDependentString tag(tags[i]);
 
     // Don't store duplicate tags.  This isn't just to save memory or to be
     // fancy; the SQL that's built from the tags relies on no dupes.
     if (!mTags.Contains(tag)) {
       if (!mTags.AppendElement(tag)) {
-        NS_Free(tags[i]);
-        NS_Free(tags);
+        free(tags[i]);
+        free(tags);
         return NS_ERROR_OUT_OF_MEMORY;
       }
     }
-    NS_Free(tags[i]);
+    free(tags[i]);
   }
-  NS_Free(tags);
+  free(tags);
 
   mTags.Sort();
 
   return NS_OK;
 }
 
 /* attribute boolean tagsAreNot; */
 NS_IMETHODIMP nsNavHistoryQuery::GetTagsAreNot(bool *aTagsAreNot)
@@ -1305,17 +1305,17 @@ NS_IMETHODIMP nsNavHistoryQuery::SetFold
 
 NS_IMETHODIMP nsNavHistoryQuery::GetTransitions(uint32_t* aCount,
                                                 uint32_t** aTransitions)
 {
   uint32_t count = mTransitions.Length();
   uint32_t* transitions = nullptr;
   if (count > 0) {
     transitions = reinterpret_cast<uint32_t*>
-                  (NS_Alloc(count * sizeof(uint32_t)));
+                  (moz_xmalloc(count * sizeof(uint32_t)));
     NS_ENSURE_TRUE(transitions, NS_ERROR_OUT_OF_MEMORY);
     for (uint32_t i = 0; i < count; ++i) {
       transitions[i] = mTransitions[i];
     }
   }
   *aCount = count;
   *aTransitions = transitions;
   return NS_OK;
--- a/toolkit/crashreporter/mac_utils.mm
+++ b/toolkit/crashreporter/mac_utils.mm
@@ -12,30 +12,30 @@ void GetObjCExceptionInfo(void* inExcept
 {
   NSException* e = (NSException*)inException;
 
   NSString* name = [e name];
   NSString* reason = [e reason];
   unsigned int nameLength = [name length];
   unsigned int reasonLength = [reason length];
 
-  unichar* nameBuffer = (unichar*)NS_Alloc(sizeof(unichar) * (nameLength + 1));
+  unichar* nameBuffer = (unichar*)moz_xmalloc(sizeof(unichar) * (nameLength + 1));
   if (!nameBuffer)
     return;
-  unichar* reasonBuffer = (unichar*)NS_Alloc(sizeof(unichar) * (reasonLength + 1));
+  unichar* reasonBuffer = (unichar*)moz_xmalloc(sizeof(unichar) * (reasonLength + 1));
   if (!reasonBuffer) {
-    NS_Free(nameBuffer);
+    free(nameBuffer);
     return;
   }
 
   [name getCharacters:nameBuffer];
   [reason getCharacters:reasonBuffer];
   nameBuffer[nameLength] = '\0';
   reasonBuffer[reasonLength] = '\0';
 
   outString.AssignLiteral("\nObj-C Exception data:\n");
   AppendUTF16toUTF8(reinterpret_cast<const char16_t*>(nameBuffer), outString);
   outString.AppendLiteral(": ");
   AppendUTF16toUTF8(reinterpret_cast<const char16_t*>(reasonBuffer), outString);
 
-  NS_Free(nameBuffer);
-  NS_Free(reasonBuffer);
+  free(nameBuffer);
+  free(reasonBuffer);
 }
--- a/toolkit/crashreporter/nsExceptionHandler.cpp
+++ b/toolkit/crashreporter/nsExceptionHandler.cpp
@@ -1640,32 +1640,32 @@ nsresult UnsetExceptionHandler()
 
   delete notesField;
   notesField = nullptr;
 
   delete lastRunCrashID;
   lastRunCrashID = nullptr;
 
   if (pendingDirectory) {
-    NS_Free(pendingDirectory);
+    free(pendingDirectory);
     pendingDirectory = nullptr;
   }
 
   if (crashReporterPath) {
-    NS_Free(crashReporterPath);
+    free(crashReporterPath);
     crashReporterPath = nullptr;
   }
 
   if (eventsDirectory) {
-    NS_Free(eventsDirectory);
+    free(eventsDirectory);
     eventsDirectory = nullptr;
   }
 
   if (memoryReportPath) {
-    NS_Free(memoryReportPath);
+    free(memoryReportPath);
     memoryReportPath = nullptr;
   }
 
 #ifdef XP_MACOSX
   posix_spawnattr_destroy(&spawnattr);
 #endif
 
   if (!gExceptionHandler)
@@ -2240,17 +2240,17 @@ SetCrashEventsDir(nsIFile* aDir)
   const char *env = PR_GetEnv("CRASHES_EVENTS_DIR");
   if (env && *env) {
     NS_NewNativeLocalFile(nsDependentCString(env),
                           false, getter_AddRefs(eventsDir));
     EnsureDirectoryExists(eventsDir);
   }
 
   if (eventsDirectory) {
-    NS_Free(eventsDirectory);
+    free(eventsDirectory);
   }
 
 #ifdef XP_WIN
   nsString path;
   eventsDir->GetPath(path);
   eventsDirectory = reinterpret_cast<wchar_t*>(ToNewUnicode(path));
 
   // Save the path in the environment for the crash reporter application.
@@ -2268,17 +2268,17 @@ SetCrashEventsDir(nsIFile* aDir)
 
   // PR_SetEnv() wants the string to be available for the lifetime
   // of the app, so dup it here.
   char* oldEventsEnv = eventsEnv;
   eventsEnv = ToNewCString(eventsDirEnv);
   PR_SetEnv(eventsEnv);
 
   if (oldEventsEnv) {
-    NS_Free(oldEventsEnv);
+    free(oldEventsEnv);
   }
 #endif
 }
 
 void
 SetProfileDirectory(nsIFile* aDir)
 {
   nsCOMPtr<nsIFile> dir;
--- a/toolkit/xre/nsAppRunner.cpp
+++ b/toolkit/xre/nsAppRunner.cpp
@@ -2039,17 +2039,17 @@ ShowProfileManager(nsIToolkitProfileServ
 
       rv = lock->GetLocalDirectory(getter_AddRefs(profLD));
       NS_ENSURE_SUCCESS(rv, rv);
 
       rv = ioParamBlock->GetString(0, &profileNamePtr);
       NS_ENSURE_SUCCESS(rv, rv);
 
       CopyUTF16toUTF8(profileNamePtr, profileName);
-      NS_Free(profileNamePtr);
+      free(profileNamePtr);
 
       lock->Unlock();
     }
   }
 
   SaveFileToEnv("XRE_PROFILE_PATH", profD);
   SaveFileToEnv("XRE_PROFILE_LOCAL_PATH", profLD);
   SaveWordToEnv("XRE_PROFILE_NAME", profileName);
--- a/toolkit/xre/nsConsoleWriter.cpp
+++ b/toolkit/xre/nsConsoleWriter.cpp
@@ -86,10 +86,10 @@ WriteConsoleLog()
     if (NS_SUCCEEDED(rv)) {
       NS_CopyUnicodeToNative(msg, nativemsg);
       PR_fprintf(file, "%s" NS_LINEBREAK, nativemsg.get());
     }
     NS_IF_RELEASE(messages[i]);
   }
 
   PR_Close(file);
-  NS_Free(messages);
+  free(messages);
 }
--- a/uriloader/exthandler/android/nsExternalSharingAppService.cpp
+++ b/uriloader/exthandler/android/nsExternalSharingAppService.cpp
@@ -45,17 +45,17 @@ nsExternalSharingAppService::GetSharingA
   nsCOMPtr<nsIMutableArray> array = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
   if (!AndroidBridge::Bridge())
     return NS_OK;
   AndroidBridge::Bridge()->GetHandlersForMimeType(aMIMEType, array,
                                                   nullptr, sendAction);
   array->GetLength(aLen);
   *aHandlers =
-    static_cast<nsISharingHandlerApp**>(NS_Alloc(sizeof(nsISharingHandlerApp*)
-                                                 * *aLen));
+    static_cast<nsISharingHandlerApp**>(moz_xmalloc(sizeof(nsISharingHandlerApp*)
+                                                    * *aLen));
   for (uint32_t i = 0; i < *aLen; i++) {
     rv = array->QueryElementAt(i, NS_GET_IID(nsISharingHandlerApp),
                                (void**)(*aHandlers + i));
     NS_ENSURE_SUCCESS(rv, rv);
   }
   return NS_OK;
 }
--- a/uriloader/exthandler/nsExternalHelperAppService.cpp
+++ b/uriloader/exthandler/nsExternalHelperAppService.cpp
@@ -1400,17 +1400,17 @@ nsresult nsExternalAppHandler::SetUpTemp
 
   uint8_t *buffer;
   rv = rg->GenerateRandomBytes(requiredBytesLength, &buffer);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsAutoCString tempLeafName;
   nsDependentCSubstring randomData(reinterpret_cast<const char*>(buffer), requiredBytesLength);
   rv = Base64Encode(randomData, tempLeafName);
-  NS_Free(buffer);
+  free(buffer);
   buffer = nullptr;
   NS_ENSURE_SUCCESS(rv, rv);
 
   tempLeafName.Truncate(wantedFileNameLength);
 
   // Base64 characters are alphanumeric (a-zA-Z0-9) and '+' and '/', so we need
   // to replace illegal characters -- notably '/'
   tempLeafName.ReplaceChar(KNOWN_PATH_SEPARATORS FILE_ILLEGAL_CHARACTERS, '_');
--- a/widget/cocoa/nsPrintDialogX.mm
+++ b/widget/cocoa/nsPrintDialogX.mm
@@ -56,19 +56,19 @@ nsPrintDialogServiceX::Show(nsIDOMWindow
   if (NS_SUCCEEDED(rv) && titleCount > 0) {
     CFStringRef cfTitleString = CFStringCreateWithCharacters(NULL, reinterpret_cast<const UniChar*>(docTitles[0]),
                                                              NS_strlen(docTitles[0]));
     if (cfTitleString) {
       ::PMPrintSettingsSetJobName(settingsX->GetPMPrintSettings(), cfTitleString);
       CFRelease(cfTitleString);
     }
     for (int32_t i = titleCount - 1; i >= 0; i--) {
-      NS_Free(docTitles[i]);
+      free(docTitles[i]);
     }
-    NS_Free(docTitles);
+    free(docTitles);
     docTitles = NULL;
     titleCount = 0;
   }
 
   NSPrintInfo* printInfo = settingsX->GetCocoaPrintInfo();
 
   // Put the print info into the current print operation, since that's where
   // [panel runModal] will look for it. We create the view because otherwise
--- a/widget/windows/nsFilePicker.cpp
+++ b/widget/windows/nsFilePicker.cpp
@@ -174,17 +174,17 @@ nsFilePicker::nsFilePicker() :
   , mFDECookie(0)
 {
    CoInitialize(nullptr);
 }
 
 nsFilePicker::~nsFilePicker()
 {
   if (mLastUsedUnicodeDirectory) {
-    NS_Free(mLastUsedUnicodeDirectory);
+    free(mLastUsedUnicodeDirectory);
     mLastUsedUnicodeDirectory = nullptr;
   }
   CoUninitialize();
 }
 
 NS_IMPL_ISUPPORTS(nsFilePicker, nsIFilePicker)
 
 NS_IMETHODIMP nsFilePicker::Init(nsIDOMWindow *aParent, const nsAString& aTitle, int16_t aMode)
@@ -1271,17 +1271,17 @@ nsFilePicker::RememberLastUsedDirectory(
       !(mDisplayDirectory = do_QueryInterface(dir)) ||
       NS_FAILED(mDisplayDirectory->GetPath(newDir)) ||
       newDir.IsEmpty()) {
     NS_WARNING("RememberLastUsedDirectory failed to get parent directory.");
     return;
   }
 
   if (mLastUsedUnicodeDirectory) {
-    NS_Free(mLastUsedUnicodeDirectory);
+    free(mLastUsedUnicodeDirectory);
     mLastUsedUnicodeDirectory = nullptr;
   }
   mLastUsedUnicodeDirectory = ToNewUnicode(newDir);
 }
 
 bool
 nsFilePicker::IsPrivacyModeEnabled()
 {
--- a/xpcom/base/nsCycleCollector.cpp
+++ b/xpcom/base/nsCycleCollector.cpp
@@ -628,17 +628,17 @@ class NodePool
 {
 private:
   // The -2 allows us to use |BlockSize + 1| for |mEntries|, and fit |mNext|,
   // all without causing slop.
   enum { BlockSize = 8 * 1024 - 2 };
 
   struct Block
   {
-    // We create and destroy Block using NS_Alloc/NS_Free rather
+    // We create and destroy Block using moz_xmalloc/free rather
     // than new and delete to avoid calling its constructor and
     // destructor.
     Block()
     {
       NS_NOTREACHED("should never be called");
 
       // Ensure Block is the right size (see the comment on BlockSize above).
       static_assert(
@@ -668,17 +668,17 @@ public:
     MOZ_ASSERT(!mBlocks, "Didn't call Clear()?");
   }
 
   void Clear()
   {
     Block* b = mBlocks;
     while (b) {
       Block* n = b->mNext;
-      NS_Free(b);
+      free(b);
       b = n;
     }
 
     mBlocks = nullptr;
     mLast = nullptr;
   }
 
 #ifdef DEBUG
@@ -698,17 +698,17 @@ public:
       , mNext(aPool.mLast)
       , mBlockEnd(nullptr)
     {
       MOZ_ASSERT(!aPool.mBlocks && !aPool.mLast, "pool not empty");
     }
     PtrInfo* Add(void* aPointer, nsCycleCollectionParticipant* aParticipant)
     {
       if (mNext == mBlockEnd) {
-        Block* block = static_cast<Block*>(NS_Alloc(sizeof(Block)));
+        Block* block = static_cast<Block*>(moz_xmalloc(sizeof(Block)));
         *mNextBlock = block;
         mNext = block->mEntries;
         mBlockEnd = block->mEntries + BlockSize;
         block->mNext = nullptr;
         mNextBlock = &block->mNext;
       }
       return new (mNext++) PtrInfo(aPointer, aParticipant);
     }
--- a/xpcom/base/nsIMemory.idl
+++ b/xpcom/base/nsIMemory.idl
@@ -5,17 +5,17 @@
 
 #include "nsISupports.idl"
 
 /**
  *
  * nsIMemory: interface to allocate and deallocate memory. Also provides
  * for notifications in low-memory situations.
  *
- * The frozen exported symbols NS_Alloc, NS_Realloc, and NS_Free
+ * The frozen exported symbols moz_xmalloc, moz_xrealloc, and free
  * provide a more efficient way to access XPCOM memory allocation. Using
  * those symbols is preferred to using the methods on this interface.
  *
  * A client that wishes to be notified of low memory situations (for
  * example, because the client maintains a large memory cache that
  * could be released when memory is tight) should register with the
  * observer service (see nsIObserverService) using the topic 
  * "memory-pressure". There are three specific types of notications 
--- a/xpcom/base/nsMemoryImpl.cpp
+++ b/xpcom/base/nsMemoryImpl.cpp
@@ -180,31 +180,13 @@ mozilla::Atomic<bool>
 nsMemoryImpl::sIsFlushing;
 
 PRIntervalTime
 nsMemoryImpl::sLastFlushTime = 0;
 
 nsMemoryImpl::FlushEvent
 nsMemoryImpl::sFlushEvent;
 
-XPCOM_API(void*)
-NS_Alloc(size_t aSize)
-{
-  return moz_xmalloc(aSize);
-}
-
-XPCOM_API(void*)
-NS_Realloc(void* aPtr, size_t aSize)
-{
-  return moz_xrealloc(aPtr, aSize);
-}
-
-XPCOM_API(void)
-NS_Free(void* aPtr)
-{
-  free(aPtr);
-}
-
 nsresult
 NS_GetMemoryManager(nsIMemory** aResult)
 {
   return sGlobalMemory.QueryInterface(NS_GET_IID(nsIMemory), (void**)aResult);
 }
--- a/xpcom/base/nsUUIDGenerator.cpp
+++ b/xpcom/base/nsUUIDGenerator.cpp
@@ -79,24 +79,24 @@ nsUUIDGenerator::Init()
 #endif /* non XP_WIN and non XP_MACOSX and non ARC4RANDOM */
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsUUIDGenerator::GenerateUUID(nsID** aRet)
 {
-  nsID* id = static_cast<nsID*>(NS_Alloc(sizeof(nsID)));
+  nsID* id = static_cast<nsID*>(moz_xmalloc(sizeof(nsID)));
   if (!id) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   nsresult rv = GenerateUUIDInPlace(id);
   if (NS_FAILED(rv)) {
-    NS_Free(id);
+    free(id);
     return rv;
   }
 
   *aRet = id;
   return rv;
 }
 
 NS_IMETHODIMP
--- a/xpcom/build/FrozenFunctions.cpp
+++ b/xpcom/build/FrozenFunctions.cpp
@@ -57,19 +57,19 @@ static const XPCOMFunctions kFrozenFunct
   &NS_CStringSetDataRange,
   &NS_CStringCopy,
   &NS_CStringToUTF16,
   &NS_UTF16ToCString,
   &NS_StringCloneData,
   &NS_CStringCloneData,
 
   // these functions were added post 1.7 (post Firefox 1.0)
-  &NS_Alloc,
-  &NS_Realloc,
-  &NS_Free,
+  &moz_xmalloc,
+  &moz_xrealloc,
+  &free,
   &NS_StringContainerInit2,
   &NS_CStringContainerInit2,
   &NS_StringGetMutableData,
   &NS_CStringGetMutableData,
   nullptr,
 
   // these functions were added post 1.8
   &NS_DebugBreak,
--- a/xpcom/build/PoisonIOInterposerMac.cpp
+++ b/xpcom/build/PoisonIOInterposerMac.cpp
@@ -81,17 +81,17 @@ public:
 
   // Custom implementation of IOInterposeObserver::Observation::Filename
   const char16_t* Filename() override;
 
   ~MacIOAutoObservation()
   {
     Report();
     if (mFilename) {
-      NS_Free(mFilename);
+      free(mFilename);
       mFilename = nullptr;
     }
   }
 
 private:
   int                 mFd;
   bool                mHasQueriedFilename;
   char16_t*           mFilename;
--- a/xpcom/build/PoisonIOInterposerWin.cpp
+++ b/xpcom/build/PoisonIOInterposerWin.cpp
@@ -175,17 +175,17 @@ public:
   // Custom implementation of IOInterposeObserver::Observation::Filename
   const char16_t* Filename() override;
 
   ~WinIOAutoObservation()
   {
     Report();
     if (mFilename) {
       MOZ_ASSERT(mHasQueriedFilename);
-      NS_Free(mFilename);
+      free(mFilename);
       mFilename = nullptr;
     }
   }
 
 private:
   HANDLE              mFileHandle;
   LARGE_INTEGER       mOffset;
   bool                mHasQueriedFilename;
--- a/xpcom/build/XPCOMInit.cpp
+++ b/xpcom/build/XPCOMInit.cpp
@@ -912,17 +912,17 @@ ShutdownXPCOM(nsIServiceManager* aServMg
   // Shutdown global servicemanager
   if (nsComponentManagerImpl::gComponentManager) {
     nsComponentManagerImpl::gComponentManager->FreeServices();
   }
 
   // Release the directory service
   NS_IF_RELEASE(nsDirectoryService::gService);
 
-  NS_Free(gGREBinPath);
+  free(gGREBinPath);
   gGREBinPath = nullptr;
 
   if (moduleLoaders) {
     bool more;
     nsCOMPtr<nsISupports> el;
     while (NS_SUCCEEDED(moduleLoaders->HasMoreElements(&more)) && more) {
       moduleLoaders->GetNext(getter_AddRefs(el));
 
--- a/xpcom/build/nsXPCOM.h
+++ b/xpcom/build/nsXPCOM.h
@@ -158,16 +158,22 @@ XPCOM_API(nsresult) NS_NewLocalFile(cons
 
 XPCOM_API(nsresult) NS_NewNativeLocalFile(const nsACString& aPath,
                                           bool aFollowLinks,
                                           nsIFile** aResult);
 
 #endif
 
 /**
+ * Allocator functions for the standalone glue.
+ * Do not use outside the xpcom glue code.
+ * Use moz_xmalloc/moz_xrealloc/free, or new/delete instead.
+ */
+#ifdef XPCOM_GLUE
+/**
  * Allocates a block of memory of a particular size. If the memory cannot
  * be allocated (because of an out-of-memory condition), the process aborts.
  *
  * @param aSize  The size of the block to allocate
  * @result       The block of memory
  * @note         This function is thread-safe.
  */
 XPCOM_API(void*) NS_Alloc(size_t aSize);
@@ -193,16 +199,21 @@ XPCOM_API(void*) NS_Realloc(void* aPtr, 
  * Frees a block of memory. Null is a permissible value, in which case no
  * action is taken.
  *
  * @param aPtr  The block of memory to free. This block must originally have
  *              been allocated by NS_Alloc or NS_Realloc
  * @note        This function is thread-safe.
  */
 XPCOM_API(void) NS_Free(void* aPtr);
+#else
+#define NS_Alloc moz_xmalloc
+#define NS_Realloc moz_xrealloc
+#define NS_Free free
+#endif
 
 /**
  * Support for warnings, assertions, and debugging breaks.
  */
 
 enum
 {
   NS_DEBUG_WARNING = 0,
--- a/xpcom/build/nsXREAppData.h
+++ b/xpcom/build/nsXREAppData.h
@@ -11,17 +11,17 @@
 #include "mozilla/Attributes.h"
 
 class nsIFile;
 
 /**
  * Application-specific data needed to start the apprunner.
  *
  * @note When this structure is allocated and manipulated by XRE_CreateAppData,
- *       string fields will be allocated with NS_Alloc, and interface pointers
+ *       string fields will be allocated with moz_xmalloc, and interface pointers
  *       are strong references.
  */
 struct nsXREAppData
 {
   /**
    * This should be set to sizeof(nsXREAppData). This structure may be
    * extended in future releases, and this ensures that binary compatibility
    * is maintained.
--- a/xpcom/components/nsCategoryManager.cpp
+++ b/xpcom/components/nsCategoryManager.cpp
@@ -690,17 +690,17 @@ nsCategoryManager::AddCategoryEntry(cons
                       aCategoryName, aEntryName);
     }
     NotifyObservers(NS_XPCOM_CATEGORY_ENTRY_ADDED_OBSERVER_ID,
                     aCategoryName, aEntryName);
 
     if (aOldValue) {
       *aOldValue = oldEntry;
     } else {
-      NS_Free(oldEntry);
+      free(oldEntry);
     }
   }
 }
 
 NS_IMETHODIMP
 nsCategoryManager::DeleteCategoryEntry(const char* aCategoryName,
                                        const char* aEntryName,
                                        bool aDontPersist)
--- a/xpcom/components/nsComponentManager.cpp
+++ b/xpcom/components/nsComponentManager.cpp
@@ -1031,17 +1031,17 @@ nsComponentManagerImpl::GetClassObject(c
 {
   nsresult rv;
 
 #ifdef PR_LOGGING
   if (PR_LOG_TEST(nsComponentManagerLog, PR_LOG_DEBUG)) {
     char* buf = aClass.ToString();
     PR_LogPrint("nsComponentManager: GetClassObject(%s)", buf);
     if (buf) {
-      NS_Free(buf);
+      free(buf);
     }
   }
 #endif
 
   PR_ASSERT(aResult != nullptr);
 
   nsCOMPtr<nsIFactory> factory = FindFactory(aClass);
   if (!factory) {
@@ -1155,17 +1155,17 @@ nsComponentManagerImpl::CreateInstance(c
 
 #ifdef PR_LOGGING
   if (PR_LOG_TEST(nsComponentManagerLog, PR_LOG_WARNING)) {
     char* buf = aClass.ToString();
     PR_LOG(nsComponentManagerLog, PR_LOG_WARNING,
            ("nsComponentManager: CreateInstance(%s) %s", buf,
             NS_SUCCEEDED(rv) ? "succeeded" : "FAILED"));
     if (buf) {
-      NS_Free(buf);
+      free(buf);
     }
   }
 #endif
 
   return rv;
 }
 
 /**
@@ -1827,17 +1827,17 @@ nsComponentManagerImpl::CIDToContractID(
 NS_IMETHODIMP
 nsComponentManagerImpl::ContractIDToCID(const char* aContractID,
                                         nsCID** aResult)
 {
   {
     SafeMutexAutoLock lock(mLock);
     nsFactoryEntry* entry = mContractIDs.Get(nsDependentCString(aContractID));
     if (entry) {
-      *aResult = (nsCID*)NS_Alloc(sizeof(nsCID));
+      *aResult = (nsCID*)moz_xmalloc(sizeof(nsCID));
       **aResult = *entry->mCIDEntry->cid;
       return NS_OK;
     }
   }
   *aResult = nullptr;
   return NS_ERROR_FACTORY_NOT_REGISTERED;
 }
 
--- a/xpcom/ds/nsVariant.cpp
+++ b/xpcom/ds/nsVariant.cpp
@@ -1556,17 +1556,17 @@ nsVariant::SetFromWStringWithSize(nsDisc
   aData->u.wstr.mWStringLength = aSize;
   DATA_SETTER_EPILOGUE(aData, VTYPE_WSTRING_SIZE_IS);
 }
 /* static */ nsresult
 nsVariant::AllocateWStringWithSize(nsDiscriminatedUnion* aData, uint32_t aSize)
 {
   DATA_SETTER_PROLOGUE(aData);
   if (!(aData->u.wstr.mWStringValue =
-          (char16_t*)NS_Alloc((aSize + 1) * sizeof(char16_t)))) {
+          (char16_t*)moz_xmalloc((aSize + 1) * sizeof(char16_t)))) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   aData->u.wstr.mWStringValue[aSize] = '\0';
   aData->u.wstr.mWStringLength = aSize;
   DATA_SETTER_EPILOGUE(aData, VTYPE_WSTRING_SIZE_IS);
 }
 /* static */ nsresult
 nsVariant::SetToVoid(nsDiscriminatedUnion* aData)
--- a/xpcom/io/nsBinaryStream.cpp
+++ b/xpcom/io/nsBinaryStream.cpp
@@ -310,17 +310,17 @@ nsBinaryOutputStream::WriteCompoundObjec
     nsCID* cidptr = nullptr;
     rv = classInfo->GetClassID(&cidptr);
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
 
     rv = WriteID(*cidptr);
 
-    NS_Free(cidptr);
+    free(cidptr);
   }
 
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
   rv = WriteID(aIID);
   if (NS_WARN_IF(NS_FAILED(rv))) {
--- a/xpcom/io/nsEscape.cpp
+++ b/xpcom/io/nsEscape.cpp
@@ -99,19 +99,16 @@ 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 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 moz_xmalloc()
   if (dstSize > UINT32_MAX) {
     return 0;
   }
 
   char* result = (char*)moz_xmalloc(dstSize);
   if (!result) {
     return 0;
   }
@@ -228,17 +225,17 @@ nsEscapeHTML(const char* aString)
 {
   char* rv = nullptr;
   /* XXX Hardcoded max entity len. The +1 is for the trailing null. */
   uint32_t len = strlen(aString);
   if (len >= (UINT32_MAX / 6)) {
     return nullptr;
   }
 
-  rv = (char*)NS_Alloc((6 * len) + 1);
+  rv = (char*)moz_xmalloc((6 * len) + 1);
   char* ptr = rv;
 
   if (rv) {
     for (; *aString != '\0'; ++aString) {
       if (*aString == '<') {
         *ptr++ = '&';
         *ptr++ = 'l';
         *ptr++ = 't';
--- a/xpcom/io/nsWildCard.cpp
+++ b/xpcom/io/nsWildCard.cpp
@@ -235,17 +235,17 @@ static int
   T* e2;
 
   /* Find the closing parenthesis that ends this union in the expression */
   cp = ::_scan_and_copy(aExpr, T(')'), T('\0'), static_cast<T*>(nullptr));
   if (cp == ABORTED || cp < 4) { /* must be at least "(a|b" before ')' */
     return ABORTED;
   }
   ++cp;                /* now index of char after closing parenthesis */
-  e2 = (T*)NS_Alloc((1 + nsCharTraits<T>::length(aExpr)) * sizeof(T));
+  e2 = (T*)moz_xmalloc((1 + nsCharTraits<T>::length(aExpr)) * sizeof(T));
   if (!e2) {
     return ABORTED;
   }
   for (sx = 1; ; ++sx) {
     /* Here, aExpr[sx] is one character past the preceding '(' or '|'. */
     /* Copy everything up to the next delimiter to e2 */
     count = ::_scan_and_copy(aExpr + sx, T(')'), T('|'), e2);
     if (count == ABORTED || !count) {
@@ -256,17 +256,17 @@ static int
     /* Append everything after closing parenthesis to e2. This is safe. */
     nsCharTraits<T>::copy(e2 + count, aExpr + cp,
                           nsCharTraits<T>::length(aExpr + cp) + 1);
     ret = ::_shexp_match(aStr, e2, aCaseInsensitive, aLevel + 1);
     if (ret != NOMATCH || !aExpr[sx] || aExpr[sx] == ')') {
       break;
     }
   }
-  NS_Free(e2);
+  free(e2);
   if (sx < 2) {
     ret = ABORTED;
   }
   return ret;
 }
 
 /* returns 1 if val is in range from start..end, case insensitive. */
 static int
@@ -421,17 +421,17 @@ ns_WildCardMatch(const T* aStr, const T*
 {
   T* expr = nullptr;
   int ret = MATCH;
 
   if (!nsCharTraits<T>::find(aXp, nsCharTraits<T>::length(aXp), T('~'))) {
     return ::_shexp_match(aStr, aXp, aCaseInsensitive, 0);
   }
 
-  expr = (T*)NS_Alloc((nsCharTraits<T>::length(aXp) + 1) * sizeof(T));
+  expr = (T*)moz_xmalloc((nsCharTraits<T>::length(aXp) + 1) * sizeof(T));
   if (!expr) {
     return NOMATCH;
   }
   memcpy(expr, aXp, (nsCharTraits<T>::length(aXp) + 1) * sizeof(T));
 
   int x = ::_scan_and_copy(expr, T('~'), T('\0'), static_cast<T*>(nullptr));
   if (x != ABORTED && expr[x] == '~') {
     expr[x++] = '\0';
@@ -446,17 +446,17 @@ ns_WildCardMatch(const T* aStr, const T*
       default:
         break;
     }
   }
   if (ret == MATCH) {
     ret = ::_shexp_match(aStr, expr, aCaseInsensitive, 0);
   }
 
-  NS_Free(expr);
+  free(expr);
   return ret;
 }
 
 template<class T>
 int
 NS_WildCardMatch_(const T* aStr, const T* aExpr, bool aCaseInsensitive)
 {
   int is_valid = NS_WildCardValid(aExpr);
--- a/xpcom/string/nsTString.h
+++ b/xpcom/string/nsTString.h
@@ -695,17 +695,17 @@ public:
 };
 
 /**
  * nsTXPIDLString extends nsTString such that:
  *
  *   (1) mData can be null
  *   (2) objects of this type can be automatically cast to |const CharT*|
  *   (3) getter_Copies method is supported to adopt data allocated with
- *       NS_Alloc, such as "out string" parameters in XPIDL.
+ *       moz_xmalloc, such as "out string" parameters in XPIDL.
  *
  * NAMES:
  *   nsXPIDLString for wide characters
  *   nsXPIDLCString for narrow characters
  */
 class nsTXPIDLString_CharT : public nsTString_CharT
 {
 public:
--- a/xpcom/tests/external/TestMinStringAPI.cpp
+++ b/xpcom/tests/external/TestMinStringAPI.cpp
@@ -45,17 +45,17 @@ static bool test_basic_1()
       }
 
     clone = NS_CStringCloneData(s);
     if (ptr == nullptr || strcmp(ptr, kAsciiData) != 0)
       {
         NS_ERROR("unexpected result");
         return false;
       }
-    NS_Free(clone);
+    free(clone);
 
     nsCStringContainer temp;
     NS_CStringContainerInit(temp);
     NS_CStringCopy(temp, s);
 
     len = NS_CStringGetData(temp, &ptr);
     if (ptr == nullptr || strcmp(ptr, kAsciiData) != 0)
       {
@@ -104,17 +104,17 @@ static bool test_basic_2()
       }
 
     clone = NS_StringCloneData(s);
     if (ptr == nullptr || memcmp(ptr, kUnicodeData, sizeof(kUnicodeData)) != 0)
       {
         NS_ERROR("unexpected result");
         return false;
       }
-    NS_Free(clone);
+    free(clone);
 
     nsStringContainer temp;
     NS_StringContainerInit(temp);
     NS_StringCopy(temp, s);
 
     len = NS_StringGetData(temp, &ptr);
     if (len != sizeof(kUnicodeData)/2 - 1)
       {
--- a/xpcom/tests/gtest/TestEncoding.cpp
+++ b/xpcom/tests/gtest/TestEncoding.cpp
@@ -25,17 +25,17 @@ TEST(Encoding, GoodSurrogatePair)
     { 0xF0, 0x90, 0x8C, 0x82, 0x65, 0x78, 0x0 };
   EXPECT_EQ(0, memcmp(expected8, goodPair8, sizeof(expected8)));
 
   // This takes a different code path from the above, so test it to make sure
   // the UTF-16 enumeration remains in sync with the UTF-8 enumeration.
   nsDependentCString expected((const char*)expected8);
   EXPECT_EQ(0, CompareUTF8toUTF16(expected, goodPair16));
 
-  NS_Free(goodPair8);
+  free(goodPair8);
 }
 
 TEST(Encoding, BackwardsSurrogatePair)
 {
   // When this string is decoded, the two surrogates are wrongly ordered and
   // must each be interpreted as U+FFFD.
   const char16_t backwardsPairData[] = { 0xDDDD, 0xD863, 0x65, 0x78, 0x0 };
   nsDependentString backwardsPair16(backwardsPairData);
@@ -50,17 +50,17 @@ TEST(Encoding, BackwardsSurrogatePair)
     { 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0x65, 0x78, 0x0 };
   EXPECT_EQ(0, memcmp(expected8, backwardsPair8, sizeof(expected8)));
 
   // This takes a different code path from the above, so test it to make sure
   // the UTF-16 enumeration remains in sync with the UTF-8 enumeration.
   nsDependentCString expected((const char*)expected8);
   EXPECT_EQ(0, CompareUTF8toUTF16(expected, backwardsPair16));
 
-  NS_Free(backwardsPair8);
+  free(backwardsPair8);
 }
 
 TEST(Encoding, MalformedUTF16OrphanHighSurrogate)
 {
   // When this string is decoded, the high surrogate should be replaced and the
   // rest of the string is specified by indexes 1 onward.
   const char16_t highSurrogateData[] = { 0xD863, 0x74, 0x65, 0x78, 0x74, 0x0 };
   nsDependentString highSurrogate16(highSurrogateData);
@@ -75,17 +75,17 @@ TEST(Encoding, MalformedUTF16OrphanHighS
     { 0xEF, 0xBF, 0xBD, 0x74, 0x65, 0x78, 0x74, 0x0 };
   EXPECT_EQ(0, memcmp(expected8, highSurrogate8, sizeof(expected8)));
 
   // This takes a different code path from the above, so test it to make sure
   // the UTF-16 enumeration remains in sync with the UTF-8 enumeration.
   nsDependentCString expected((const char*)expected8);
   EXPECT_EQ(0, CompareUTF8toUTF16(expected, highSurrogate16));
 
-  NS_Free(highSurrogate8);
+  free(highSurrogate8);
 }
 
 TEST(Encoding, MalformedUTF16OrphanLowSurrogate)
 {
   // When this string is decoded, the low surrogate should be replaced and the
   // rest of the string is specified by indexes 1 onward.
   const char16_t lowSurrogateData[] = { 0xDDDD, 0x74, 0x65, 0x78, 0x74, 0x0 };
   nsDependentString lowSurrogate16(lowSurrogateData);
@@ -100,10 +100,10 @@ TEST(Encoding, MalformedUTF16OrphanLowSu
     { 0xEF, 0xBF, 0xBD, 0x74, 0x65, 0x78, 0x74, 0x0 };
   EXPECT_EQ(0, memcmp(expected8, lowSurrogate8, sizeof(expected8)));
 
   // This takes a different code path from the above, so test it to make sure
   // the UTF-16 enumeration remains in sync with the UTF-8 enumeration.
   nsDependentCString expected((const char*)expected8);
   EXPECT_EQ(0, CompareUTF8toUTF16(expected, lowSurrogate16));
 
-  NS_Free(lowSurrogate8);
+  free(lowSurrogate8);
 }
--- a/xpcom/threads/nsProcessCommon.cpp
+++ b/xpcom/threads/nsProcessCommon.cpp
@@ -359,33 +359,33 @@ nsProcess::RunAsync(const char** aArgs, 
 
 nsresult
 nsProcess::CopyArgsAndRunProcess(bool aBlocking, const char** aArgs,
                                  uint32_t aCount, nsIObserver* aObserver,
                                  bool aHoldWeak)
 {
   // Add one to the aCount for the program name and one for null termination.
   char** my_argv = nullptr;
-  my_argv = (char**)NS_Alloc(sizeof(char*) * (aCount + 2));
+  my_argv = (char**)moz_xmalloc(sizeof(char*) * (aCount + 2));
   if (!my_argv) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   my_argv[0] = ToNewUTF8String(mTargetPath);
 
   for (uint32_t i = 0; i < aCount; ++i) {
     my_argv[i + 1] = const_cast<char*>(aArgs[i]);
   }
 
   my_argv[aCount + 1] = nullptr;
 
   nsresult rv = RunProcess(aBlocking, my_argv, aObserver, aHoldWeak, false);
 
-  NS_Free(my_argv[0]);
-  NS_Free(my_argv);
+  free(my_argv[0]);
+  free(my_argv);
   return rv;
 }
 
 // XXXldb |aArgs| has the wrong const-ness
 NS_IMETHODIMP
 nsProcess::Runw(bool aBlocking, const char16_t** aArgs, uint32_t aCount)
 {
   return CopyArgsAndRunProcessw(aBlocking, aArgs, aCount, nullptr, false);
@@ -401,35 +401,35 @@ nsProcess::RunwAsync(const char16_t** aA
 
 nsresult
 nsProcess::CopyArgsAndRunProcessw(bool aBlocking, const char16_t** aArgs,
                                   uint32_t aCount, nsIObserver* aObserver,
                                   bool aHoldWeak)
 {
   // Add one to the aCount for the program name and one for null termination.
   char** my_argv = nullptr;
-  my_argv = (char**)NS_Alloc(sizeof(char*) * (aCount + 2));
+  my_argv = (char**)moz_xmalloc(sizeof(char*) * (aCount + 2));
   if (!my_argv) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   my_argv[0] = ToNewUTF8String(mTargetPath);
 
   for (uint32_t i = 0; i < aCount; i++) {
     my_argv[i + 1] = ToNewUTF8String(nsDependentString(aArgs[i]));
   }
 
   my_argv[aCount + 1] = nullptr;
 
   nsresult rv = RunProcess(aBlocking, my_argv, aObserver, aHoldWeak, true);
 
   for (uint32_t i = 0; i <= aCount; ++i) {
-    NS_Free(my_argv[i]);
+    free(my_argv[i]);
   }
-  NS_Free(my_argv);
+  free(my_argv);
   return rv;
 }
 
 nsresult
 nsProcess::RunProcess(bool aBlocking, char** aMyArgv, nsIObserver* aObserver,
                       bool aHoldWeak, bool aArgsUTF8)
 {
   if (NS_WARN_IF(!mExecutable)) {