Bug 802378: Make PSM coding patterns more consistent, and more consistent with Mozilla Coding Style, r=keeler
authorBrian Smith <bsmith@mozilla.com>
Wed, 17 Oct 2012 13:48:36 -0700
changeset 110720 a8ff177abfbe71368cb5963b316f1cd5879402e4
parent 110719 130f0da363c80d3e535e3188aa9c36c01f83cf4e
child 110721 d3a655f609caee9fa831060d310d1ac354450e88
push id93
push usernmatsakis@mozilla.com
push dateWed, 31 Oct 2012 21:26:57 +0000
reviewerskeeler
bugs802378
milestone19.0a1
Bug 802378: Make PSM coding patterns more consistent, and more consistent with Mozilla Coding Style, r=keeler
security/manager/boot/src/nsBOOTModule.cpp
security/manager/boot/src/nsEntropyCollector.cpp
security/manager/boot/src/nsSecurityWarningDialogs.cpp
security/manager/pki/src/nsPKIModule.cpp
security/manager/pki/src/nsPKIParamBlock.cpp
security/manager/ssl/src/SSLServerCertVerification.cpp
security/manager/ssl/src/ScopedNSSTypes.h
security/manager/ssl/src/TransportSecurityInfo.cpp
security/manager/ssl/src/TransportSecurityInfo.h
security/manager/ssl/src/nsCERTValInParamWrapper.h
security/manager/ssl/src/nsCMS.cpp
security/manager/ssl/src/nsCMSSecureMessage.cpp
security/manager/ssl/src/nsCRLInfo.cpp
security/manager/ssl/src/nsCRLManager.cpp
security/manager/ssl/src/nsCertOverrideService.cpp
security/manager/ssl/src/nsCertTree.cpp
security/manager/ssl/src/nsCertTree.h
security/manager/ssl/src/nsCertVerificationThread.cpp
security/manager/ssl/src/nsClientAuthRemember.cpp
security/manager/ssl/src/nsClientAuthRemember.h
security/manager/ssl/src/nsCrypto.cpp
security/manager/ssl/src/nsDataSignatureVerifier.cpp
security/manager/ssl/src/nsIdentityChecking.cpp
security/manager/ssl/src/nsKeygenHandler.cpp
security/manager/ssl/src/nsNSSASN1Object.cpp
security/manager/ssl/src/nsNSSCallbacks.cpp
security/manager/ssl/src/nsNSSCertHelper.cpp
security/manager/ssl/src/nsNSSCertificate.cpp
security/manager/ssl/src/nsNSSCertificate.h
security/manager/ssl/src/nsNSSCertificateDB.cpp
security/manager/ssl/src/nsNSSComponent.cpp
security/manager/ssl/src/nsNSSComponent.h
security/manager/ssl/src/nsNSSIOLayer.cpp
security/manager/ssl/src/nsNSSIOLayer.h
security/manager/ssl/src/nsNSSModule.cpp
security/manager/ssl/src/nsNSSShutDown.h
security/manager/ssl/src/nsNTLMAuthModule.cpp
security/manager/ssl/src/nsPK11TokenDB.cpp
security/manager/ssl/src/nsPKCS11Slot.cpp
security/manager/ssl/src/nsPKCS12Blob.cpp
security/manager/ssl/src/nsPKCS12Blob.h
security/manager/ssl/src/nsProtectedAuthThread.cpp
security/manager/ssl/src/nsRecentBadCerts.cpp
security/manager/ssl/src/nsSDR.cpp
security/manager/ssl/src/nsSSLStatus.h
security/manager/ssl/src/nsSmartCardMonitor.cpp
security/manager/ssl/src/nsStreamCipher.cpp
security/manager/ssl/src/nsUsageArrayHelper.cpp
--- a/security/manager/boot/src/nsBOOTModule.cpp
+++ b/security/manager/boot/src/nsBOOTModule.cpp
@@ -16,29 +16,29 @@ NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsSe
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsStrictTransportSecurityService, Init)
 
 NS_DEFINE_NAMED_CID(NS_ENTROPYCOLLECTOR_CID);
 NS_DEFINE_NAMED_CID(NS_SECURITYWARNINGDIALOGS_CID);
 NS_DEFINE_NAMED_CID(NS_SECURE_BROWSER_UI_CID);
 NS_DEFINE_NAMED_CID(NS_STRICT_TRANSPORT_SECURITY_CID);
 
 static const mozilla::Module::CIDEntry kBOOTCIDs[] = {
-  { &kNS_ENTROPYCOLLECTOR_CID, false, NULL, nsEntropyCollectorConstructor },
-  { &kNS_SECURITYWARNINGDIALOGS_CID, false, NULL, nsSecurityWarningDialogsConstructor },
-  { &kNS_SECURE_BROWSER_UI_CID, false, NULL, nsSecureBrowserUIImplConstructor },
-  { &kNS_STRICT_TRANSPORT_SECURITY_CID, false, NULL, nsStrictTransportSecurityServiceConstructor },
-  { NULL }
+  { &kNS_ENTROPYCOLLECTOR_CID, false, nullptr, nsEntropyCollectorConstructor },
+  { &kNS_SECURITYWARNINGDIALOGS_CID, false, nullptr, nsSecurityWarningDialogsConstructor },
+  { &kNS_SECURE_BROWSER_UI_CID, false, nullptr, nsSecureBrowserUIImplConstructor },
+  { &kNS_STRICT_TRANSPORT_SECURITY_CID, false, nullptr, nsStrictTransportSecurityServiceConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kBOOTContracts[] = {
   { NS_ENTROPYCOLLECTOR_CONTRACTID, &kNS_ENTROPYCOLLECTOR_CID },
   { NS_SECURITYWARNINGDIALOGS_CONTRACTID, &kNS_SECURITYWARNINGDIALOGS_CID },
   { NS_SECURE_BROWSER_UI_CONTRACTID, &kNS_SECURE_BROWSER_UI_CID },
   { NS_STSSERVICE_CONTRACTID, &kNS_STRICT_TRANSPORT_SECURITY_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kBootModule = {
   mozilla::Module::kVersion,
   kBOOTCIDs,
   kBOOTContracts
 };
 
--- a/security/manager/boot/src/nsEntropyCollector.cpp
+++ b/security/manager/boot/src/nsEntropyCollector.cpp
@@ -1,16 +1,15 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "prlog.h"
 #include "nsEntropyCollector.h"
-#include "nsMemory.h"
 #include "nsAlgorithm.h"
 
 nsEntropyCollector::nsEntropyCollector()
 :mBytesCollected(0), mWritePointer(mEntropyCache)
 {
   // We could use the uninitialized memory in mEntropyCache as initial
   // random data, but that means (if any entropy is collected before NSS
   // initialization and then forwarded) that we'll get warnings from
--- a/security/manager/boot/src/nsSecurityWarningDialogs.cpp
+++ b/security/manager/boot/src/nsSecurityWarningDialogs.cpp
@@ -10,17 +10,16 @@
 #include "nsReadableUtils.h"
 #include "nsString.h"
 #include "nsIPrompt.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsThreadUtils.h"
-#include "nsAutoPtr.h"
 
 #include "mozilla/Telemetry.h"
 #include "nsISecurityUITelemetry.h"
 
 NS_IMPL_THREADSAFE_ISUPPORTS1(nsSecurityWarningDialogs, nsISecurityWarningDialogs)
 
 #define STRING_BUNDLE_URL    "chrome://pipnss/locale/security.properties"
 
@@ -259,17 +258,17 @@ nsSecurityWarningDialogs::ConfirmDialog(
                             bool* _result)
 {
   nsresult rv;
 
   // Get user's preference for this alert
   // prefName, showAgainName are null if there is no preference for this dialog
   bool prefValue = true;
   
-  if (prefName != nullptr) {
+  if (prefName) {
     rv = mPrefBranch->GetBoolPref(prefName, &prefValue);
     if (NS_FAILED(rv)) prefValue = true;
   }
   
   // Stop if confirm is not requested
   if (!prefValue) {
     *_result = true;
     return NS_OK;
@@ -293,17 +292,17 @@ nsSecurityWarningDialogs::ConfirmDialog(
 
   // Get messages strings from localization file
   nsXPIDLString windowTitle, message, alertMe, cont;
 
   mStringBundle->GetStringFromName(NS_LITERAL_STRING("Title").get(),
                                    getter_Copies(windowTitle));
   mStringBundle->GetStringFromName(messageName,
                                    getter_Copies(message));
-  if (showAgainName != nullptr) {
+  if (showAgainName) {
     mStringBundle->GetStringFromName(showAgainName,
                                      getter_Copies(alertMe));
   }
   mStringBundle->GetStringFromName(NS_LITERAL_STRING("Continue").get(),
                                    getter_Copies(cont));
   // alertMe is allowed to be null
   if (!windowTitle || !message || !cont) return NS_ERROR_FAILURE;
       
@@ -334,17 +333,17 @@ nsSecurityWarningDialogs::ConfirmDialog(
 
   *_result = (buttonPressed != 1);
   if (*_result) {
   // For confirmation dialogs, the clickthrough constant is 1 more
   // than the constant for the dialog.
   mozilla::Telemetry::Accumulate(mozilla::Telemetry::SECURITY_UI, aBucket + 1);
   }
 
-  if (!prefValue && prefName != nullptr) {
+  if (!prefValue && prefName) {
     mPrefBranch->SetBoolPref(prefName, false);
   } else if (prefValue && showOnce) {
     mPrefBranch->SetBoolPref(showOncePref.get(), false);
   }
 
   return rv;
 }
 
--- a/security/manager/pki/src/nsPKIModule.cpp
+++ b/security/manager/pki/src/nsPKIModule.cpp
@@ -19,36 +19,36 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(nsFormSig
 
 NS_DEFINE_NAMED_CID(NS_NSSDIALOGS_CID);
 NS_DEFINE_NAMED_CID(NS_NSSASN1OUTINER_CID);
 NS_DEFINE_NAMED_CID(NS_PKIPARAMBLOCK_CID);
 NS_DEFINE_NAMED_CID(NS_FORMSIGNINGDIALOG_CID);
 
 
 static const mozilla::Module::CIDEntry kPKICIDs[] = {
-  { &kNS_NSSDIALOGS_CID, false, NULL, nsNSSDialogsConstructor },
-  { &kNS_NSSASN1OUTINER_CID, false, NULL, nsNSSASN1TreeConstructor },
-  { &kNS_PKIPARAMBLOCK_CID, false, NULL, nsPKIParamBlockConstructor },
-  { &kNS_FORMSIGNINGDIALOG_CID, false, NULL, nsFormSigningDialogConstructor },
-  { NULL }
+  { &kNS_NSSDIALOGS_CID, false, nullptr, nsNSSDialogsConstructor },
+  { &kNS_NSSASN1OUTINER_CID, false, nullptr, nsNSSASN1TreeConstructor },
+  { &kNS_PKIPARAMBLOCK_CID, false, nullptr, nsPKIParamBlockConstructor },
+  { &kNS_FORMSIGNINGDIALOG_CID, false, nullptr, nsFormSigningDialogConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kPKIContracts[] = {
   { NS_SSLCERTERRORDIALOG_CONTRACTID, &kNS_NSSDIALOGS_CID },
   { NS_TOKENPASSWORDSDIALOG_CONTRACTID, &kNS_NSSDIALOGS_CID },
   { NS_CERTIFICATEDIALOGS_CONTRACTID, &kNS_NSSDIALOGS_CID },
   { NS_CLIENTAUTHDIALOGS_CONTRACTID, &kNS_NSSDIALOGS_CID },
   { NS_CERTPICKDIALOGS_CONTRACTID, &kNS_NSSDIALOGS_CID },
   { NS_TOKENDIALOGS_CONTRACTID, &kNS_NSSDIALOGS_CID },
   { NS_DOMCRYPTODIALOGS_CONTRACTID, &kNS_NSSDIALOGS_CID },
   { NS_GENERATINGKEYPAIRINFODIALOGS_CONTRACTID, &kNS_NSSDIALOGS_CID },
   { NS_ASN1TREE_CONTRACTID, &kNS_NSSASN1OUTINER_CID },
   { NS_PKIPARAMBLOCK_CONTRACTID, &kNS_PKIPARAMBLOCK_CID },
   { NS_FORMSIGNINGDIALOG_CONTRACTID, &kNS_FORMSIGNINGDIALOG_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kPKIModule = {
   mozilla::Module::kVersion,
   kPKICIDs,
   kPKIContracts
 };
 
--- a/security/manager/pki/src/nsPKIParamBlock.cpp
+++ b/security/manager/pki/src/nsPKIParamBlock.cpp
@@ -15,17 +15,17 @@ NS_IMPL_THREADSAFE_ISUPPORTS2(nsPKIParam
 nsPKIParamBlock::nsPKIParamBlock()
 {
 }
 
 nsresult
 nsPKIParamBlock::Init()
 {
   mDialogParamBlock = do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);
-  return (mDialogParamBlock == nullptr) ? NS_ERROR_OUT_OF_MEMORY : NS_OK;
+  return !mDialogParamBlock ? NS_ERROR_OUT_OF_MEMORY : NS_OK;
 }
 
 nsPKIParamBlock::~nsPKIParamBlock()
 {
 }
 
 
 NS_IMETHODIMP 
@@ -74,17 +74,17 @@ nsPKIParamBlock::SetObjects(nsIMutableAr
 
 
 /* void setISupportAtIndex (in int32_t index, in nsISupports object); */
 NS_IMETHODIMP 
 nsPKIParamBlock::SetISupportAtIndex(int32_t index, nsISupports *object)
 {
   if (!mSupports) {
     mSupports = do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID);
-    if (mSupports == nullptr) {
+    if (!mSupports) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
   }
   // Ignore any InsertElementAt error, because this function always did that
   mSupports->InsertElementAt(object, index-1);
   return NS_OK;
 }
 
--- a/security/manager/ssl/src/SSLServerCertVerification.cpp
+++ b/security/manager/ssl/src/SSLServerCertVerification.cpp
@@ -216,17 +216,17 @@ public:
 
   SSLServerCertVerificationResult(TransportSecurityInfo * infoObject,
                                   PRErrorCode errorCode,
                                   SSLErrorMessageType errorMessageType = 
                                       PlainErrorMessage);
 
   void Dispatch();
 private:
-  const nsRefPtr<TransportSecurityInfo> mInfoObject;
+  const RefPtr<TransportSecurityInfo> mInfoObject;
 public:
   const PRErrorCode mErrorCode;
   const SSLErrorMessageType mErrorMessageType;
 };
 
 class CertErrorRunnable : public SyncRunnableBase
 {
  public:
@@ -243,23 +243,23 @@ class CertErrorRunnable : public SyncRun
       mCollectedErrors(collectedErrors),
       mErrorCodeTrust(errorCodeTrust),
       mErrorCodeMismatch(errorCodeMismatch),
       mErrorCodeExpired(errorCodeExpired)
   {
   }
 
   virtual void RunOnTargetThread();
-  nsRefPtr<SSLServerCertVerificationResult> mResult; // out
+  RefPtr<SSLServerCertVerificationResult> mResult; // out
 private:
   SSLServerCertVerificationResult *CheckCertOverrides();
   
   const void * const mFdForLogging; // may become an invalid pointer; do not dereference
   const nsCOMPtr<nsIX509Cert> mCert;
-  const nsRefPtr<TransportSecurityInfo> mInfoObject;
+  const RefPtr<TransportSecurityInfo> mInfoObject;
   const PRErrorCode mDefaultErrorCodeToReport;
   const uint32_t mCollectedErrors;
   const PRErrorCode mErrorCodeTrust;
   const PRErrorCode mErrorCodeMismatch;
   const PRErrorCode mErrorCodeExpired;
 };
 
 SSLServerCertVerificationResult *
@@ -422,35 +422,34 @@ CreateCertErrorRunnable(PRErrorCode defa
   }
 
   if (defaultErrorCodeToReport == 0) {
     NS_ERROR("No error code set during certificate validation failure.");
     PR_SetError(PR_INVALID_STATE_ERROR, 0);
     return nullptr;
   }
 
-  nsRefPtr<nsNSSCertificate> nssCert;
-  nssCert = nsNSSCertificate::Create(cert);
+  RefPtr<nsNSSCertificate> nssCert(nsNSSCertificate::Create(cert));
   if (!nssCert) {
     NS_ERROR("nsNSSCertificate::Create failed");
     PR_SetError(SEC_ERROR_NO_MEMORY, 0);
     return nullptr;
   }
 
   SECStatus srv;
   nsresult nsrv;
 
   nsCOMPtr<nsINSSComponent> inss = do_GetService(kNSSComponentCID, &nsrv);
   if (!inss) {
     NS_ERROR("do_GetService(kNSSComponentCID) failed");
     PR_SetError(defaultErrorCodeToReport, 0);
     return nullptr;
   }
 
-  nsRefPtr<nsCERTValInParamWrapper> survivingParams;
+  RefPtr<nsCERTValInParamWrapper> survivingParams;
   nsrv = inss->GetDefaultCERTValInParam(survivingParams);
   if (NS_FAILED(nsrv)) {
     NS_ERROR("GetDefaultCERTValInParam failed");
     PR_SetError(defaultErrorCodeToReport, 0);
     return nullptr;
   }
   
   PLArenaPool *log_arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
@@ -467,17 +466,17 @@ CreateCertErrorRunnable(PRErrorCode defa
   }
   CERTVerifyLogContentsCleaner verify_log_cleaner(verify_log);
   verify_log->arena = log_arena;
 
   if (!nsNSSComponent::globalConstFlagUsePKIXVerification) {
     srv = CERT_VerifyCertificate(CERT_GetDefaultCertDB(), cert,
                                 true, certificateUsageSSLServer,
                                 PR_Now(), static_cast<void*>(infoObject),
-                                verify_log, NULL);
+                                verify_log, nullptr);
   }
   else {
     CERTValOutParam cvout[2];
     cvout[0].type = cert_po_errorLog;
     cvout[0].value.pointer.log = verify_log;
     cvout[1].type = cert_po_end;
 
     srv = CERT_PKIXVerifyCert(cert, certificateUsageSSLServer,
@@ -586,17 +585,17 @@ private:
     // The result must run on the socket transport thread, which we are already
     // on, so we can just run it directly, instead of dispatching it.
     if (NS_SUCCEEDED(rv)) {
       rv = mCertErrorRunnable->mResult ? mCertErrorRunnable->mResult->Run()
                                        : NS_ERROR_UNEXPECTED;
     }
     return rv;
   }
-  nsRefPtr<CertErrorRunnable> mCertErrorRunnable;
+  RefPtr<CertErrorRunnable> mCertErrorRunnable;
 };
 
 class SSLServerCertVerificationJob : public nsRunnable
 {
 public:
   // Must be called only on the socket transport thread
   static SECStatus Dispatch(const void * fdForLogging,
                             TransportSecurityInfo * infoObject,
@@ -606,17 +605,17 @@ private:
 
   // Must be called only on the socket transport thread
   SSLServerCertVerificationJob(const void * fdForLogging,
                                TransportSecurityInfo * infoObject, 
                                CERTCertificate * cert);
   ~SSLServerCertVerificationJob();
 
   const void * const mFdForLogging;
-  const nsRefPtr<TransportSecurityInfo> mInfoObject;
+  const RefPtr<TransportSecurityInfo> mInfoObject;
   CERTCertificate * const mCert;
 };
 
 SSLServerCertVerificationJob::SSLServerCertVerificationJob(
     const void * fdForLogging, TransportSecurityInfo * infoObject,
     CERTCertificate * cert)
   : mFdForLogging(fdForLogging)
   , mInfoObject(infoObject)
@@ -639,17 +638,17 @@ PSM_SSL_PKIX_AuthCertificate(CERTCertifi
         rv = CERT_VerifyCertNow(CERT_GetDefaultCertDB(), peerCert, true,
                                 certUsageSSLServer, pinarg);
     }
     else {
         nsresult nsrv;
         nsCOMPtr<nsINSSComponent> inss = do_GetService(kNSSComponentCID, &nsrv);
         if (!inss)
           return SECFailure;
-        nsRefPtr<nsCERTValInParamWrapper> survivingParams;
+        RefPtr<nsCERTValInParamWrapper> survivingParams;
         if (NS_FAILED(inss->GetDefaultCERTValInParam(survivingParams)))
           return SECFailure;
 
         CERTValOutParam cvout[1];
         cvout[0].type = cert_po_end;
 
         rv = CERT_PKIXVerifyCert(peerCert, certificateUsageSSLServer,
                                 survivingParams->GetRawPointerForNSS(),
@@ -772,17 +771,17 @@ static SECStatus
 BlockServerCertChangeForSpdy(nsNSSSocketInfo *infoObject,
                              CERTCertificate *serverCert)
 {
   // Get the existing cert. If there isn't one, then there is
   // no cert change to worry about.
   nsCOMPtr<nsIX509Cert> cert;
   nsCOMPtr<nsIX509Cert2> cert2;
 
-  nsRefPtr<nsSSLStatus> status = infoObject->SSLStatus();
+  RefPtr<nsSSLStatus> status(infoObject->SSLStatus());
   if (!status) {
     // If we didn't have a status, then this is the
     // first handshake on this connection, not a
     // renegotiation.
     return SECSuccess;
   }
   
   status->GetServerCert(getter_AddRefs(cert));
@@ -868,18 +867,18 @@ AuthCertificate(TransportSecurityInfo * 
 
   SECStatus rv = PSM_SSL_PKIX_AuthCertificate(cert, infoObject,
                                               infoObject->GetHostName());
 
   // We want to remember the CA certs in the temp db, so that the application can find the
   // complete chain at any time it might need it.
   // But we keep only those CA certs in the temp db, that we didn't already know.
 
-  nsRefPtr<nsSSLStatus> status = infoObject->SSLStatus();
-  nsRefPtr<nsNSSCertificate> nsc;
+  RefPtr<nsSSLStatus> status(infoObject->SSLStatus());
+  RefPtr<nsNSSCertificate> nsc;
 
   if (!status || !status->mServerCert) {
     nsc = nsNSSCertificate::Create(cert);
   }
 
   CERTCertList *certList = nullptr;
   certList = CERT_GetCertChainFromCert(cert, PR_Now(), certUsageSSLCA);
   if (!certList) {
@@ -987,18 +986,18 @@ SSLServerCertVerificationJob::Dispatch(c
 {
   // Runs on the socket transport thread
   if (!infoObject || !serverCert) {
     NS_ERROR("Invalid parameters for SSL server cert validation");
     PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
     return SECFailure;
   }
   
-  nsRefPtr<SSLServerCertVerificationJob> job
-    = new SSLServerCertVerificationJob(fdForLogging, infoObject, serverCert);
+  RefPtr<SSLServerCertVerificationJob> job(
+    new SSLServerCertVerificationJob(fdForLogging, infoObject, serverCert));
 
   nsresult nrv;
   if (!gCertVerificationThreadPool) {
     nrv = NS_ERROR_NOT_INITIALIZED;
   } else {
     nrv = gCertVerificationThreadPool->Dispatch(job, NS_DISPATCH_NORMAL);
   }
   if (NS_FAILED(nrv)) {
@@ -1034,26 +1033,26 @@ SSLServerCertVerificationJob::Run()
   if (mInfoObject->isAlreadyShutDown()) {
     error = SEC_ERROR_USER_CANCELLED;
   } else {
     // Reset the error code here so we can detect if AuthCertificate fails to
     // set the error code if/when it fails.
     PR_SetError(0, 0); 
     SECStatus rv = AuthCertificate(mInfoObject, mCert);
     if (rv == SECSuccess) {
-      nsRefPtr<SSLServerCertVerificationResult> restart 
-        = new SSLServerCertVerificationResult(mInfoObject, 0);
+      RefPtr<SSLServerCertVerificationResult> restart(
+        new SSLServerCertVerificationResult(mInfoObject, 0));
       restart->Dispatch();
       return NS_OK;
     }
 
     error = PR_GetError();
     if (error != 0) {
-      nsRefPtr<CertErrorRunnable> runnable = CreateCertErrorRunnable(
-              error, mInfoObject, mCert, mFdForLogging);
+      RefPtr<CertErrorRunnable> runnable(CreateCertErrorRunnable(
+        error, mInfoObject, mCert, mFdForLogging));
       if (!runnable) {
         // CreateCertErrorRunnable set a new error code
         error = PR_GetError(); 
       } else {
         // We must block the the socket transport service thread while the
         // main thread executes the CertErrorRunnable. The CertErrorRunnable
         // will dispatch the result asynchronously, so we don't have to block
         // this thread waiting for it.
@@ -1079,18 +1078,18 @@ SSLServerCertVerificationJob::Run()
     }
   }
 
   if (error == 0) {
     NS_NOTREACHED("no error set during certificate validation failure");
     error = PR_INVALID_STATE_ERROR;
   }
 
-  nsRefPtr<SSLServerCertVerificationResult> failure
-    = new SSLServerCertVerificationResult(mInfoObject, error);
+  RefPtr<SSLServerCertVerificationResult> failure(
+    new SSLServerCertVerificationResult(mInfoObject, error));
   failure->Dispatch();
   return NS_OK;
 }
 
 } // unnamed namespace
 
 // Extracts whatever information we need out of fd (using SSL_*) and passes it
 // to SSLServerCertVerificationJob::Dispatch. SSLServerCertVerificationJob should
@@ -1160,19 +1159,19 @@ AuthCertificateHook(void *arg, PRFileDes
   // a non-blocking socket.
   SECStatus rv = AuthCertificate(socketInfo, serverCert);
   if (rv == SECSuccess) {
     return SECSuccess;
   }
 
   PRErrorCode error = PR_GetError();
   if (error != 0) {
-    nsRefPtr<CertErrorRunnable> runnable = CreateCertErrorRunnable(
+    RefPtr<CertErrorRunnable> runnable(CreateCertErrorRunnable(
                     error, socketInfo, serverCert,
-                    static_cast<const void *>(fd));
+                    static_cast<const void *>(fd)));
     if (!runnable) {
       // CreateCertErrorRunnable sets a new error code when it fails
       error = PR_GetError();
     } else {
       // We have to return SECSuccess or SECFailure based on the result of the
       // override processing, so we must block this thread waiting for it. The
       // CertErrorRunnable will NOT dispatch the result at all, since we passed
       // false for CreateCertErrorRunnable's async parameter
--- a/security/manager/ssl/src/ScopedNSSTypes.h
+++ b/security/manager/ssl/src/ScopedNSSTypes.h
@@ -4,25 +4,22 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_ScopedNSSTypes_h
 #define mozilla_ScopedNSSTypes_h
 
 #include "mozilla/Scoped.h"
 
-extern "C" {
 #include "prio.h"
 #include "cert.h"
 #include "cms.h"
 #include "keyhi.h"
 #include "pk11pub.h"
 #include "sechash.h"
-} // extern "C"
-
 
 // Alphabetical order by NSS type
 MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedPRFileDesc,
                                           PRFileDesc,
                                           PR_Close)
 MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedCERTCertificate,
                                           CERTCertificate,
                                           CERT_DestroyCertificate)
--- a/security/manager/ssl/src/TransportSecurityInfo.cpp
+++ b/security/manager/ssl/src/TransportSecurityInfo.cpp
@@ -248,17 +248,17 @@ TransportSecurityInfo::GetErrorMessage(P
   if (mErrorMessageCached.IsEmpty()) {
     nsresult rv = formatErrorMessage(lock, 
                                      mErrorCode, mErrorMessageType,
                                      true, true, mErrorMessageCached);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   *aText = ToNewUnicode(mErrorMessageCached);
-  return *aText != nullptr ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+  return *aText ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
 }
 
 void
 TransportSecurityInfo::GetErrorLogMessage(PRErrorCode errorCode,
                                           SSLErrorMessageType errorMessageType,
                                           nsString &result)
 {
   if (!NS_IsMainThread()) {
@@ -333,19 +333,16 @@ TransportSecurityInfo::GetInterface(cons
   if (!NS_IsMainThread()) {
     NS_ERROR("nsNSSSocketInfo::GetInterface called off the main thread");
     return NS_ERROR_NOT_SAME_THREAD;
   }
 
   nsresult rv;
   if (!mCallbacks) {
     nsCOMPtr<nsIInterfaceRequestor> ir = new PipUIContext();
-    if (!ir)
-      return NS_ERROR_OUT_OF_MEMORY;
-
     rv = ir->GetInterface(uuid, result);
   } else {
     rv = mCallbacks->GetInterface(uuid, result);
   }
   return rv;
 }
 
 static NS_DEFINE_CID(kNSSCertificateCID, NS_X509CERT_CID);
@@ -355,17 +352,17 @@ static NS_DEFINE_CID(kTransportSecurityI
 
 NS_IMETHODIMP
 TransportSecurityInfo::Write(nsIObjectOutputStream* stream)
 {
   stream->WriteID(kTransportSecurityInfoMagic);
 
   MutexAutoLock lock(mMutex);
 
-  nsRefPtr<nsSSLStatus> status = mSSLStatus;
+  RefPtr<nsSSLStatus> status(mSSLStatus);
   nsCOMPtr<nsISerializable> certSerializable;
 
   // Write a redundant copy of the certificate for backward compatibility
   // with previous versions, which also unnecessarily wrote it.
   //
   // As we are reading the object our self, not using ReadObject, we have
   // to store it here 'manually' as well, mimicking our object stream
   // implementation.
@@ -737,17 +734,17 @@ GetSubjectAltNames(CERTCertificate *nssC
                    nsINSSComponent *component,
                    nsString &allNames,
                    uint32_t &nameCount)
 {
   allNames.Truncate();
   nameCount = 0;
 
   PLArenaPool *san_arena = nullptr;
-  SECItem altNameExtension = {siBuffer, NULL, 0 };
+  SECItem altNameExtension = {siBuffer, nullptr, 0 };
   CERTGeneralName *sanNameList = nullptr;
 
   SECStatus rv = CERT_FindCertExtension(nssCert, SEC_OID_X509_SUBJECT_ALT_NAME,
                                         &altNameExtension);
   if (rv != SECSuccess)
     return false;
 
   san_arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
@@ -815,17 +812,17 @@ AppendErrorTextMismatch(const nsString &
                         nsIX509Cert* ix509,
                         nsINSSComponent *component,
                         bool wantsHtml,
                         nsString &returnedMessage)
 {
   const PRUnichar *params[1];
   nsresult rv;
 
-  CERTCertificate *nssCert = NULL;
+  CERTCertificate *nssCert = nullptr;
   CERTCertificateCleaner nssCertCleaner(nssCert);
 
   nsCOMPtr<nsIX509Cert2> cert2 = do_QueryInterface(ix509, &rv);
   if (cert2)
     nssCert = cert2->GetCert();
 
   if (!nssCert) {
     // We are unable to extract the valid names, say "not valid for name".
@@ -1050,18 +1047,18 @@ formatOverridableCertErrorMessage(nsISSL
 
   returnedMessage.Truncate();
   rv = component->PIPBundleFormatStringFromName("certErrorIntro", params, 1,
                                                 returnedMessage);
   NS_ENSURE_SUCCESS(rv, rv);
 
   returnedMessage.Append(NS_LITERAL_STRING("\n\n"));
 
-  nsRefPtr<nsIX509Cert> ix509;
-  rv = sslStatus.GetServerCert(getter_AddRefs(ix509));
+  RefPtr<nsIX509Cert> ix509;
+  rv = sslStatus.GetServerCert(byRef(ix509));
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool isUntrusted;
   rv = sslStatus.GetIsUntrusted(&isUntrusted);
   NS_ENSURE_SUCCESS(rv, rv);
   if (isUntrusted) {
     AppendErrorTextUntrusted(errorCodeToReport, hostWithoutPort, ix509, 
                              component, returnedMessage);
--- a/security/manager/ssl/src/TransportSecurityInfo.h
+++ b/security/manager/ssl/src/TransportSecurityInfo.h
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef _MOZILLA_PSM_TRANSPORTSECURITYINFO_H
 #define _MOZILLA_PSM_TRANSPORTSECURITYINFO_H
 
 #include "certt.h"
 #include "mozilla/Mutex.h"
+#include "mozilla/RefPtr.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsITransportSecurityInfo.h"
 #include "nsSSLStatus.h"
 #include "nsISSLStatusProvider.h"
 #include "nsIAssociatedContentSecurity.h"
 #include "nsNSSShutDown.h"
 #include "nsDataHashtable.h"
 
@@ -102,17 +103,17 @@ private:
                               bool wantsHtml, bool suppressPort443, 
                               nsString &result);
 
   int32_t mPort;
   nsXPIDLCString mHostName;
   PRErrorCode mIsCertIssuerBlacklisted;
 
   /* SSL Status */
-  nsRefPtr<nsSSLStatus> mSSLStatus;
+  mozilla::RefPtr<nsSSLStatus> mSSLStatus;
 
   virtual void virtualDestroyNSSReference();
   void destructorSafeDestroyNSSReference();
 };
 
 class RememberCertErrorsTable
 {
 private:
--- a/security/manager/ssl/src/nsCERTValInParamWrapper.h
+++ b/security/manager/ssl/src/nsCERTValInParamWrapper.h
@@ -21,17 +21,17 @@
  * and "must switch to new defaults".
  *
  * The global default object may be replaced at any time with a new object.
  * The contents of inner CERTValInParam are supposed to be stable (const).
  *
  * In order to protect against the race, we use a reference counted wrapper.
  * Each user of a foreign nsCERTValInParamWrapper object
  * (e.g. the current global default object)
- * must use nsRefPtr<nsCERTValInParamWrapper> = other-object
+ * must use RefPtr<nsCERTValInParamWrapper> = other-object
  * prior to calling CERT_PKIXVerifyCert.
  * 
  * This guarantees the object will still be alive after the call,
  * and if the default object has been replaced in the meantime,
  * the reference counter will go to zero, and the old default
  * object will get destroyed automatically.
  */
 class nsCERTValInParamWrapper
--- a/security/manager/ssl/src/nsCMS.cpp
+++ b/security/manager/ssl/src/nsCMS.cpp
@@ -11,22 +11,26 @@
 #include "cms.h"
 #include "nsICMSMessageErrors.h"
 #include "nsIArray.h"
 #include "nsArrayUtils.h"
 #include "nsCertVerificationThread.h"
 #include "nsCERTValInParamWrapper.h"
 
 #include "prlog.h"
+
+#include "nsNSSCleaner.h"
+#include "nsNSSComponent.h"
+
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gPIPNSSLog;
 #endif
 
-#include "nsNSSCleaner.h"
-#include "nsNSSComponent.h"
+using namespace mozilla;
+
 static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
 
 NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate)
 
 NS_IMPL_THREADSAFE_ISUPPORTS2(nsCMSMessage, nsICMSMessage, 
                                             nsICMSMessage2)
 
 nsCMSMessage::nsCMSMessage()
@@ -175,17 +179,17 @@ NS_IMETHODIMP nsCMSMessage::GetSignerCer
 
     *scert = nsNSSCertificate::Create(si->cert);
     if (*scert) {
       (*scert)->AddRef();
     }
   }
   else {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::GetSignerCert no signer cert, do we have a cert list? %s\n",
-      (si->certList != nullptr ? "yes" : "no") ));
+      (si->certList ? "yes" : "no") ));
 
     *scert = nullptr;
   }
   
   return NS_OK;
 }
 
 NS_IMETHODIMP nsCMSMessage::GetEncryptionCert(nsIX509Cert **ecert)
@@ -212,17 +216,17 @@ nsresult nsCMSMessage::CommonVerifySigna
     return NS_ERROR_NOT_AVAILABLE;
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CommonVerifySignature, content level count %d\n", NSS_CMSMessage_ContentLevelCount(m_cmsMsg)));
   NSSCMSContentInfo *cinfo = nullptr;
   NSSCMSSignedData *sigd = nullptr;
   NSSCMSSignerInfo *si;
   int32_t nsigners;
   nsresult rv = NS_ERROR_FAILURE;
-  nsRefPtr<nsCERTValInParamWrapper> survivingParams;
+  RefPtr<nsCERTValInParamWrapper> survivingParams;
   nsCOMPtr<nsINSSComponent> inss;
 
   if (!NSS_CMSMessage_IsSigned(m_cmsMsg)) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CommonVerifySignature - not signed\n"));
     return NS_ERROR_CMS_VERIFY_NOT_SIGNED;
   } 
 
   cinfo = NSS_CMSMessage_ContentLevel(m_cmsMsg, 0);
@@ -260,17 +264,17 @@ nsresult nsCMSMessage::CommonVerifySigna
   si = NSS_CMSSignedData_GetSignerInfo(sigd, 0);
 
   // See bug 324474. We want to make sure the signing cert is 
   // still valid at the current time.
 
   if (!nsNSSComponent::globalConstFlagUsePKIXVerification) {
     if (CERT_VerifyCertificateNow(CERT_GetDefaultCertDB(), si->cert, true, 
                                   certificateUsageEmailSigner,
-                                  si->cmsg->pwfn_arg, NULL) != SECSuccess) {
+                                  si->cmsg->pwfn_arg, nullptr) != SECSuccess) {
       PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CommonVerifySignature - signing cert not trusted now\n"));
       rv = NS_ERROR_CMS_VERIFY_UNTRUSTED;
       goto loser;
     }
   }
   else {
     CERTValOutParam cvout[1];
     cvout[0].type = cert_po_end;
@@ -362,28 +366,20 @@ NS_IMETHODIMP nsCMSMessage::AsyncVerifyD
 
   return CommonAsyncVerifySignature(aListener, aDigestData, aDigestDataLen);
 }
 
 nsresult nsCMSMessage::CommonAsyncVerifySignature(nsISMimeVerificationListener *aListener,
                                                   unsigned char* aDigestData, uint32_t aDigestDataLen)
 {
   nsSMimeVerificationJob *job = new nsSMimeVerificationJob;
-  if (!job)
-    return NS_ERROR_OUT_OF_MEMORY;
   
   if (aDigestData)
   {
     job->digest_data = new unsigned char[aDigestDataLen];
-    if (!job->digest_data)
-    {
-      delete job;
-      return NS_ERROR_OUT_OF_MEMORY;
-    }
-    
     memcpy(job->digest_data, aDigestData, aDigestDataLen);
   }
   else
   {
     job->digest_data = nullptr;
   }
   
   job->digest_len = aDigestDataLen;
@@ -552,18 +548,18 @@ NS_IMETHODIMP nsCMSMessage::CreateEncryp
   // Find a bulk key algorithm //
   if (NSS_SMIMEUtil_FindBulkAlgForRecipients(recipientCerts.getRawArray(), &bulkAlgTag,
                                             &keySize) != SECSuccess) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't find bulk alg for recipients\n"));
     rv = NS_ERROR_CMS_ENCRYPT_NO_BULK_ALG;
     goto loser;
   }
 
-  m_cmsMsg = NSS_CMSMessage_Create(NULL);
-  if (m_cmsMsg == nullptr) {
+  m_cmsMsg = NSS_CMSMessage_Create(nullptr);
+  if (!m_cmsMsg) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't create new cms message\n"));
     rv = NS_ERROR_OUT_OF_MEMORY;
     goto loser;
   }
 
   if ((envd = NSS_CMSEnvelopedData_Create(m_cmsMsg, bulkAlgTag, keySize)) == nullptr) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't create enveloped data\n"));
     goto loser;
@@ -635,27 +631,27 @@ NS_IMETHODIMP nsCMSMessage::CreateSigned
   }
 
   CERTCertificateCleaner ecertCleaner(ecert);
   CERTCertificateCleaner scertCleaner(scert);
 
   /*
    * create the message object
    */
-  m_cmsMsg = NSS_CMSMessage_Create(NULL); /* create a message on its own pool */
-  if (m_cmsMsg == NULL) {
+  m_cmsMsg = NSS_CMSMessage_Create(nullptr); /* create a message on its own pool */
+  if (!m_cmsMsg) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't create new message\n"));
     rv = NS_ERROR_OUT_OF_MEMORY;
     goto loser;
   }
 
   /*
    * build chain of objects: message->signedData->data
    */
-  if ((sigd = NSS_CMSSignedData_Create(m_cmsMsg)) == NULL) {
+  if ((sigd = NSS_CMSSignedData_Create(m_cmsMsg)) == nullptr) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't create signed data\n"));
     goto loser;
   }
   cinfo = NSS_CMSMessage_GetContentInfo(m_cmsMsg);
   if (NSS_CMSContentInfo_SetContent_SignedData(m_cmsMsg, cinfo, sigd) 
           != SECSuccess) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't set content signed data\n"));
     goto loser;
@@ -669,17 +665,17 @@ NS_IMETHODIMP nsCMSMessage::CreateSigned
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't set content data\n"));
     goto loser;
   }
 
   /* 
    * create & attach signer information
    */
   if ((signerinfo = NSS_CMSSignerInfo_Create(m_cmsMsg, scert, SEC_OID_SHA1)) 
-          == NULL) {
+          == nullptr) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't create signer info\n"));
     goto loser;
   }
 
   /* we want the cert chain included for this one */
   if (NSS_CMSSignerInfo_IncludeCerts(signerinfo, NSSCMSCM_CertChain, 
                                        certUsageEmailSigner) 
           != SECSuccess) {
@@ -876,17 +872,17 @@ NS_IMETHODIMP nsCMSEncoder::Start(nsICMS
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSEncoder::Start\n"));
   nsCMSMessage *cmsMsg = static_cast<nsCMSMessage*>(aMsg);
   m_ctx = new PipUIContext();
 
   m_ecx = NSS_CMSEncoder_Start(cmsMsg->getCMS(), cb, arg, 0, 0, 0, m_ctx, 0, 0, 0, 0);
-  if (m_ecx == nullptr) {
+  if (!m_ecx) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSEncoder::Start - can't start encoder\n"));
     return NS_ERROR_FAILURE;
   }
   return NS_OK;
 }
 
 /* void update (in string aBuf, in long aLen); */
 NS_IMETHODIMP nsCMSEncoder::Update(const char *aBuf, int32_t aLen)
--- a/security/manager/ssl/src/nsCMSSecureMessage.cpp
+++ b/security/manager/ssl/src/nsCMSSecureMessage.cpp
@@ -1,14 +1,13 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "nsMemory.h"
 #include "nsXPIDLString.h"
 #include "nsCOMPtr.h"
 #include "nsISupports.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsCRT.h"
 
 #include "nsICMSSecureMessage.h"
 
@@ -142,17 +141,17 @@ SendMessage(const char *msg, const char 
   NSSCMSContentInfo *cinfo;
   NSSCMSRecipientInfo *rcpt;
   SECItem output;
   PLArenaPool *arena = PORT_NewArena(1024);
   SECStatus s;
   nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
 
   /* Step 0. Create a CMS Message */
-  cmsMsg = NSS_CMSMessage_Create(NULL);
+  cmsMsg = NSS_CMSMessage_Create(nullptr);
   if (!cmsMsg) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't create NSSCMSMessage\n"));
     rv = NS_ERROR_FAILURE;
     goto done;
   }
 
   /* Step 1.  Import the certificate into NSS */
   rv = decode(base64Cert, &certDER, &derLen);
@@ -311,17 +310,17 @@ done:
   return rv;
 }
 
 nsresult nsCMSSecureMessage::
 encode(const unsigned char *data, int32_t dataLen, char **_retval)
 {
   nsresult rv = NS_OK;
 
-  *_retval = PL_Base64Encode((const char *)data, dataLen, NULL);
+  *_retval = PL_Base64Encode((const char *)data, dataLen, nullptr);
   if (!*_retval) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; }
 
 loser:
   return rv;
 }
 
 nsresult nsCMSSecureMessage::
 decode(const char *data, unsigned char **result, int32_t * _retval)
@@ -332,17 +331,17 @@ decode(const char *data, unsigned char *
   int adjust = 0;
 
   /* Compute length adjustment */
   if (data[len-1] == '=') {
     adjust++;
     if (data[len-2] == '=') adjust++;
   }
 
-  *result = (unsigned char *)PL_Base64Decode(data, len, NULL);
+  *result = (unsigned char *)PL_Base64Decode(data, len, nullptr);
   if (!*result) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::decode - error decoding base64\n"));
     rv = NS_ERROR_ILLEGAL_VALUE;
     goto loser;
   }
 
   *_retval = (len*3)/4 - adjust;
 
--- a/security/manager/ssl/src/nsCRLInfo.cpp
+++ b/security/manager/ssl/src/nsCRLInfo.cpp
@@ -9,25 +9,23 @@
 #include "nsIDateTimeFormat.h"
 #include "nsDateTimeFormatCID.h"
 #include "nsCOMPtr.h"
 #include "nsComponentManagerUtils.h"
 #include "nsReadableUtils.h"
 #include "nsNSSShutDown.h"
 
 #include "nspr.h"
-extern "C" {
 #include "pk11func.h"
 #include "certdb.h"
 #include "cert.h"
 #include "secerr.h"
 #include "nssb64.h"
 #include "secasn1.h"
 #include "secder.h"
-}
 
 NS_IMPL_ISUPPORTS1(nsCRLInfo, nsICRLInfo)
 
 nsCRLInfo::nsCRLInfo()
 {
   /* member initializers and constructor code */
 }
 
--- a/security/manager/ssl/src/nsCRLManager.cpp
+++ b/security/manager/ssl/src/nsCRLManager.cpp
@@ -15,25 +15,23 @@
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsNSSShutDown.h"
 #include "nsThreadUtils.h"
 
 #include "nsNSSCertHeader.h"
 
 #include "nspr.h"
-extern "C" {
 #include "pk11func.h"
 #include "certdb.h"
 #include "cert.h"
 #include "secerr.h"
 #include "nssb64.h"
 #include "secasn1.h"
 #include "secder.h"
-}
 #include "ssl.h"
 #include "ocsp.h"
 #include "plbase64.h"
 
 static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
 
 NS_IMPL_ISUPPORTS1(nsCRLManager, nsICRLManager)
 
@@ -50,19 +48,19 @@ nsCRLManager::ImportCrl (uint8_t *aData,
 {
   if (!NS_IsMainThread()) {
     NS_ERROR("nsCRLManager::ImportCrl called off the main thread");
     return NS_ERROR_NOT_SAME_THREAD;
   }
   
   nsNSSShutDownPreventionLock locker;
   nsresult rv;
-  PLArenaPool *arena = NULL;
+  PLArenaPool *arena = nullptr;
   CERTCertificate *caCert;
-  SECItem derName = { siBuffer, NULL, 0 };
+  SECItem derName = { siBuffer, nullptr, 0 };
   SECItem derCrl;
   CERTSignedData sd;
   SECStatus sec_rv;
   CERTSignedCrl *crl;
   nsAutoCString url;
   nsCOMPtr<nsICRLInfo> crlData;
   bool importSuccessful;
   int32_t errorCode;
@@ -177,17 +175,17 @@ done:
         }
       }
       if (NS_SUCCEEDED(rv)) {
         nsCOMPtr<nsIInterfaceRequestor> cxt = new PipUIContext();
         certDialogs->CrlImportStatusDialog(cxt, crlData);
       }
     }
   } else {
-    if(crlKey == nullptr){
+    if (!crlKey) {
       return NS_ERROR_FAILURE;
     }
     nsCOMPtr<nsIPrefService> prefSvc = do_GetService(NS_PREFSERVICE_CONTRACTID,&rv);
     nsCOMPtr<nsIPrefBranch> pref = do_GetService(NS_PREFSERVICE_CONTRACTID,&rv);
     if (NS_FAILED(rv)){
       return rv;
     }
     
@@ -323,17 +321,17 @@ nsCRLManager::GetCrls(nsIArray ** aCrls)
 
   // Get the list of certs //
   sec_rv = SEC_LookupCrls(CERT_GetDefaultCertDB(), &head, -1);
   if (sec_rv != SECSuccess) {
     return NS_ERROR_FAILURE;
   }
 
   if (head) {
-    for (node=head->first; node != nullptr; node = node->next) {
+    for (node=head->first; node; node = node->next) {
 
       nsCOMPtr<nsICRLInfo> entry = new nsCRLInfo((node->crl));
       crlsArray->AppendElement(entry, false);
     }
     PORT_FreeArena(head->arena, false);
   }
 
   *aCrls = crlsArray;
@@ -358,17 +356,17 @@ nsCRLManager::DeleteCrl(uint32_t aCrlInd
 
   // Get the list of certs //
   sec_rv = SEC_LookupCrls(CERT_GetDefaultCertDB(), &head, -1);
   if (sec_rv != SECSuccess) {
     return NS_ERROR_FAILURE;
   }
 
   if (head) {
-    for (i = 0, node=head->first; node != nullptr; i++, node = node->next) {
+    for (i = 0, node=head->first; node; i++, node = node->next) {
       if (i != aCrlIndex) {
         continue;
       }
       realCrl = SEC_FindCrlByName(CERT_GetDefaultCertDB(), &(node->crl->crl.derName), node->type);
       SEC_DeletePermCRL(realCrl);
       SEC_DestroyCrl(realCrl);
       SSL_ClearSessionCache();
     }
--- a/security/manager/ssl/src/nsCertOverrideService.cpp
+++ b/security/manager/ssl/src/nsCertOverrideService.cpp
@@ -13,17 +13,16 @@
 #include "nsNetUtil.h"
 #include "nsILineInputStream.h"
 #include "nsIObserver.h"
 #include "nsIObserverService.h"
 #include "nsISupportsPrimitives.h"
 #include "nsPromiseFlatString.h"
 #include "nsThreadUtils.h"
 #include "nsStringBuffer.h"
-#include "nsAutoPtr.h"
 #include "nspr.h"
 #include "pk11pub.h"
 #include "certdb.h"
 #include "sechash.h"
 #include "ssl.h" // For SSL_ClearSessionCache
 
 #include "nsNSSCleaner.h"
 NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate)
@@ -505,17 +504,17 @@ nsCertOverrideService::RememberValidityO
   PR_FREEIF(nickname);
 
   nsAutoCString fpStr;
   nsresult rv = GetCertFingerprintByOidTag(nsscert, 
                   mOidTagForStoringNewHashes, fpStr);
   if (NS_FAILED(rv))
     return rv;
 
-  char *dbkey = NULL;
+  char *dbkey = nullptr;
   rv = aCert->GetDbKey(&dbkey);
   if (NS_FAILED(rv) || !dbkey)
     return rv;
 
   // change \n and \r to spaces in the possibly multi-line-base64-encoded key
   for (char *dbkey_walk = dbkey;
        *dbkey_walk;
       ++dbkey_walk) {
@@ -692,17 +691,17 @@ nsCertOverrideService::GetAllOverrideHos
                                                         PRUnichar ***aHostsWithPortsArray)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 static bool
 matchesDBKey(nsIX509Cert *cert, const char *match_dbkey)
 {
-  char *dbkey = NULL;
+  char *dbkey = nullptr;
   nsresult rv = cert->GetDbKey(&dbkey);
   if (NS_FAILED(rv) || !dbkey)
     return false;
 
   bool found_mismatch = false;
   const char *key1 = dbkey;
   const char *key2 = match_dbkey;
 
--- a/security/manager/ssl/src/nsCertTree.cpp
+++ b/security/manager/ssl/src/nsCertTree.cpp
@@ -17,23 +17,25 @@
 #include "nsINSSCertCache.h"
 #include "nsIMutableArray.h"
 #include "nsArrayUtils.h"
 #include "nsISupportsPrimitives.h"
 #include "nsXPCOMCID.h"
 #include "nsTHashtable.h"
 #include "nsHashKeys.h"
 
+#include "prlog.h"
+#include "nsNSSCleaner.h"
 
-#include "prlog.h"
+using namespace mozilla;
+
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gPIPNSSLog;
 #endif
 
-#include "nsNSSCleaner.h"
 NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate)
 
 static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
 static NS_DEFINE_CID(kCertOverrideCID, NS_CERTOVERRIDE_CID);
 
 // treeArrayElStr
 //
 // structure used to hold map of tree.  Each thread (an organization
@@ -156,17 +158,17 @@ nsCertTreeDispInfo::GetHostPort(nsAStrin
   nsAutoCString hostPort;
   nsCertOverrideService::GetHostWithPort(mAsciiHost, mPort, hostPort);
   aHostPort = NS_ConvertUTF8toUTF16(hostPort);
   return NS_OK;
 }
 
 NS_IMPL_ISUPPORTS2(nsCertTree, nsICertTree, nsITreeView)
 
-nsCertTree::nsCertTree() : mTreeArray(NULL)
+nsCertTree::nsCertTree() : mTreeArray(nullptr)
 {
   mCompareCache.ops = nullptr;
   mNSSComponent = do_GetService(kNSSComponentCID);
   mOverrideService = do_GetService("@mozilla.org/security/certoverride;1");
   // Might be a different service if someone is overriding the contract
   nsCOMPtr<nsICertOverrideService> origCertOverride =
     do_GetService(kCertOverrideCID);
   mOriginalOverrideService =
@@ -207,17 +209,17 @@ nsCertTree::FreeCertArray()
 
 CompareCacheHashEntry *
 nsCertTree::getCacheEntry(void *cache, void *aCert)
 {
   PLDHashTable &aCompareCache = *reinterpret_cast<PLDHashTable*>(cache);
   CompareCacheHashEntryPtr *entryPtr = 
     static_cast<CompareCacheHashEntryPtr*>
                (PL_DHashTableOperate(&aCompareCache, aCert, PL_DHASH_ADD));
-  return entryPtr ? entryPtr->entry : NULL;
+  return entryPtr ? entryPtr->entry : nullptr;
 }
 
 void nsCertTree::RemoveCacheEntry(void *key)
 {
   PL_DHashTableOperate(&mCompareCache, key, PL_DHASH_REMOVE);
 }
 
 // CountOrganizations
@@ -234,17 +236,17 @@ nsCertTree::CountOrganizations()
   nsCertAddonInfo *addonInfo = mDispInfo.ElementAt(0)->mAddonInfo;
   if (addonInfo) {
     orgCert = addonInfo->mCert;
   }
   nsCOMPtr<nsIX509Cert> nextCert = nullptr;
   int32_t orgCount = 1;
   for (i=1; i<certCount; i++) {
     nextCert = nullptr;
-    addonInfo = mDispInfo.SafeElementAt(i, NULL)->mAddonInfo;
+    addonInfo = mDispInfo.SafeElementAt(i, nullptr)->mAddonInfo;
     if (addonInfo) {
       nextCert = addonInfo->mCert;
     }
     // XXX we assume issuer org is always criterion 1
     if (CmpBy(&mCompareCache, orgCert, nextCert, sort_IssuerOrg, sort_None, sort_None) != 0) {
       orgCert = nextCert;
       orgCount++;
     }
@@ -275,48 +277,49 @@ nsCertTree::GetThreadDescAtIndex(int32_t
 }
 
 //  GetCertAtIndex
 //
 //  If the row at index is a cert, return that cert.  Otherwise, return null.
 already_AddRefed<nsIX509Cert>
 nsCertTree::GetCertAtIndex(int32_t index, int32_t *outAbsoluteCertOffset)
 {
-  nsRefPtr<nsCertTreeDispInfo> certdi =
-    GetDispInfoAtIndex(index, outAbsoluteCertOffset);
+  RefPtr<nsCertTreeDispInfo> certdi(
+    GetDispInfoAtIndex(index, outAbsoluteCertOffset));
   if (!certdi)
     return nullptr;
 
   nsIX509Cert *rawPtr = nullptr;
   if (certdi->mCert) {
     rawPtr = certdi->mCert;
   } else if (certdi->mAddonInfo) {
     rawPtr = certdi->mAddonInfo->mCert;
   }
   NS_IF_ADDREF(rawPtr);
   return rawPtr;
 }
 
 //  If the row at index is a cert, return that cert.  Otherwise, return null.
-already_AddRefed<nsCertTreeDispInfo>
+TemporaryRef<nsCertTreeDispInfo>
 nsCertTree::GetDispInfoAtIndex(int32_t index, 
                                int32_t *outAbsoluteCertOffset)
 {
   int i, idx = 0, cIndex = 0, nc;
   if (index < 0) return nullptr;
   // Loop over the threads
   for (i=0; i<mNumOrgs; i++) {
     if (index == idx) return nullptr; // index is for thread
     idx++; // get past the thread
     nc = (mTreeArray[i].open) ? mTreeArray[i].numChildren : 0;
     if (index < idx + nc) { // cert is within range of this thread
       int32_t certIndex = cIndex + index - idx;
       if (outAbsoluteCertOffset)
         *outAbsoluteCertOffset = certIndex;
-      nsRefPtr<nsCertTreeDispInfo> certdi = mDispInfo.SafeElementAt(certIndex, NULL);
+      RefPtr<nsCertTreeDispInfo> certdi(mDispInfo.SafeElementAt(certIndex,
+                                                                nullptr));
       if (certdi) {
         nsCertTreeDispInfo *raw = certdi.get();
         NS_IF_ADDREF(raw);
         return raw;
       }
       break;
     }
     if (mTreeArray[i].open)
@@ -341,18 +344,18 @@ nsCertTree::GetCompareFuncFromCertType(u
     case nsIX509Cert::SERVER_CERT:
     default:
       return CmpWebSiteCert;
   }
 }
 
 struct nsCertAndArrayAndPositionAndCounterAndTracker
 {
-  nsRefPtr<nsCertAddonInfo> certai;
-  nsTArray< nsRefPtr<nsCertTreeDispInfo> > *array;
+  RefPtr<nsCertAddonInfo> certai;
+  nsTArray< RefPtr<nsCertTreeDispInfo> > *array;
   int position;
   int counter;
   nsTHashtable<nsCStringHashKey> *tracker;
 };
 
 // Used to enumerate host:port overrides that match a stored
 // certificate, creates and adds a display-info-object to the
 // provided array. Increments insert position and entry counter.
@@ -405,17 +408,17 @@ CollectAllHostPortOverridesCallback(cons
 
   nsAutoCString hostPort;
   nsCertOverrideService::GetHostWithPort(aSettings.mAsciiHost, aSettings.mPort, hostPort);
   collectorTable->PutEntry(hostPort);
 }
 
 struct nsArrayAndPositionAndCounterAndTracker
 {
-  nsTArray< nsRefPtr<nsCertTreeDispInfo> > *array;
+  nsTArray< RefPtr<nsCertTreeDispInfo> > *array;
   int position;
   int counter;
   nsTHashtable<nsCStringHashKey> *tracker;
 };
 
 // Used when enumerating the stored host:port overrides where
 // no associated certificate was found in the NSS database.
 static void
@@ -571,40 +574,35 @@ nsCertTree::GetCertsByTypeFromCertList(C
       if (wantThisCertIfHaveOverrides) {
         if (NS_SUCCEEDED(rv) && ocount > 0) {
           // there are overrides for this cert
           wantThisCert = true;
         }
       }
     }
 
-    nsRefPtr<nsCertAddonInfo> certai = new nsCertAddonInfo;
-    if (!certai)
-      return NS_ERROR_OUT_OF_MEMORY;
-
+    RefPtr<nsCertAddonInfo> certai(new nsCertAddonInfo);
     certai->mCert = pipCert;
     certai->mUsageCount = 0;
 
     if (wantThisCert || addOverrides) {
       int InsertPosition = 0;
       for (; InsertPosition < count; ++InsertPosition) {
         nsCOMPtr<nsIX509Cert> cert = nullptr;
-        nsRefPtr<nsCertTreeDispInfo> elem = mDispInfo.SafeElementAt(InsertPosition, NULL);
+        RefPtr<nsCertTreeDispInfo> elem(
+          mDispInfo.SafeElementAt(InsertPosition, nullptr));
         if (elem && elem->mAddonInfo) {
           cert = elem->mAddonInfo->mCert;
         }
         if ((*aCertCmpFn)(aCertCmpFnArg, pipCert, cert) < 0) {
           break;
         }
       }
       if (wantThisCert) {
         nsCertTreeDispInfo *certdi = new nsCertTreeDispInfo;
-        if (!certdi)
-          return NS_ERROR_OUT_OF_MEMORY;
-
         certdi->mAddonInfo = certai;
         certai->mUsageCount++;
         certdi->mTypeOfEntry = nsCertTreeDispInfo::direct_db;
         // not necessary: certdi->mAsciiHost.Clear(); certdi->mPort = -1;
         certdi->mOverrideBits = nsCertOverride::ob_None;
         certdi->mIsTemporary = false;
         mDispInfo.InsertElementAt(InsertPosition, certdi);
         ++count;
@@ -639,17 +637,17 @@ nsCertTree::GetCertsByTypeFromCertList(C
 }
 
 nsresult 
 nsCertTree::GetCertsByType(uint32_t           aType,
                            nsCertCompareFunc  aCertCmpFn,
                            void              *aCertCmpFnArg)
 {
   nsNSSShutDownPreventionLock locker;
-  CERTCertList *certList = NULL;
+  CERTCertList *certList = nullptr;
   nsCOMPtr<nsIInterfaceRequestor> cxt = new PipUIContext();
   certList = PK11_ListCerts(PK11CertListUnique, cxt);
   nsresult rv = GetCertsByTypeFromCertList(certList, aType, aCertCmpFn, aCertCmpFnArg);
   if (certList)
     CERT_DestroyCertList(certList);
   return rv;
 }
 
@@ -707,18 +705,16 @@ nsCertTree::LoadCerts(uint32_t aType)
 }
 
 nsresult
 nsCertTree::UpdateUIContents()
 {
   uint32_t count = mDispInfo.Length();
   mNumOrgs = CountOrganizations();
   mTreeArray = new treeArrayEl[mNumOrgs];
-  if (!mTreeArray)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   mCellText = do_CreateInstance(NS_ARRAY_CONTRACTID);
 
 if (count) {
   uint32_t j = 0;
   nsCOMPtr<nsIX509Cert> orgCert = nullptr;
   nsCertAddonInfo *addonInfo = mDispInfo.ElementAt(j)->mAddonInfo;
   if (addonInfo) {
@@ -734,25 +730,25 @@ if (count) {
       if (orgNameRef.IsEmpty())
         orgCert->GetCommonName(orgNameRef);
     }
     mTreeArray[i].open = true;
     mTreeArray[i].certIndex = j;
     mTreeArray[i].numChildren = 1;
     if (++j >= count) break;
     nsCOMPtr<nsIX509Cert> nextCert = nullptr;
-    nsCertAddonInfo *addonInfo = mDispInfo.SafeElementAt(j, NULL)->mAddonInfo;
+    nsCertAddonInfo *addonInfo = mDispInfo.SafeElementAt(j, nullptr)->mAddonInfo;
     if (addonInfo) {
       nextCert = addonInfo->mCert;
     }
     while (0 == CmpBy(&mCompareCache, orgCert, nextCert, sort_IssuerOrg, sort_None, sort_None)) {
       mTreeArray[i].numChildren++;
       if (++j >= count) break;
       nextCert = nullptr;
-      addonInfo = mDispInfo.SafeElementAt(j, NULL)->mAddonInfo;
+      addonInfo = mDispInfo.SafeElementAt(j, nullptr)->mAddonInfo;
       if (addonInfo) {
         nextCert = addonInfo->mCert;
       }
     }
     orgCert = nextCert;
   }
 }
   if (mTree) {
@@ -785,17 +781,18 @@ nsCertTree::DeleteEntryObject(uint32_t i
     if (index == idx)
       return NS_OK; // index is for thread
     idx++; // get past the thread
     nc = (mTreeArray[i].open) ? mTreeArray[i].numChildren : 0;
     if (index < idx + nc) { // cert is within range of this thread
       int32_t certIndex = cIndex + index - idx;
 
       bool canRemoveEntry = false;
-      nsRefPtr<nsCertTreeDispInfo> certdi = mDispInfo.SafeElementAt(certIndex, NULL);
+      RefPtr<nsCertTreeDispInfo> certdi(mDispInfo.SafeElementAt(certIndex,
+                                                                nullptr));
       
       // We will remove the element from the visual tree.
       // Only if we have a certdi, then we can check for additional actions.
       nsCOMPtr<nsIX509Cert> cert = nullptr;
       if (certdi) {
         if (certdi->mAddonInfo) {
           cert = certdi->mAddonInfo->mCert;
         }
@@ -878,33 +875,31 @@ nsCertTree::GetCert(uint32_t aIndex, nsI
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCertTree::GetTreeItem(uint32_t aIndex, nsICertTreeItem **_treeitem)
 {
   NS_ENSURE_ARG(_treeitem);
 
-  nsRefPtr<nsCertTreeDispInfo> certdi = 
-    GetDispInfoAtIndex(aIndex);
+  RefPtr<nsCertTreeDispInfo> certdi(GetDispInfoAtIndex(aIndex));
   if (!certdi)
     return NS_ERROR_FAILURE;
 
   *_treeitem = certdi;
   NS_IF_ADDREF(*_treeitem);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCertTree::IsHostPortOverride(uint32_t aIndex, bool *_retval)
 {
   NS_ENSURE_ARG(_retval);
 
-  nsRefPtr<nsCertTreeDispInfo> certdi = 
-    GetDispInfoAtIndex(aIndex);
+  RefPtr<nsCertTreeDispInfo> certdi(GetDispInfoAtIndex(aIndex));
   if (!certdi)
     return NS_ERROR_FAILURE;
 
   *_retval = (certdi->mTypeOfEntry == nsCertTreeDispInfo::host_port_override);
   return NS_OK;
 }
 
 /* readonly attribute long rowCount; */
@@ -1105,27 +1100,26 @@ nsCertTree::GetCellText(int32_t row, nsI
 
   nsresult rv;
   _retval.Truncate();
 
   const PRUnichar* colID;
   col->GetIdConst(&colID);
 
   treeArrayEl *el = GetThreadDescAtIndex(row);
-  if (el != nullptr) {
+  if (el) {
     if (NS_LITERAL_STRING("certcol").Equals(colID))
       _retval.Assign(el->orgName);
     else
       _retval.Truncate();
     return NS_OK;
   }
 
   int32_t absoluteCertOffset;
-  nsRefPtr<nsCertTreeDispInfo> certdi = 
-    GetDispInfoAtIndex(row, &absoluteCertOffset);
+  RefPtr<nsCertTreeDispInfo> certdi(GetDispInfoAtIndex(row, &absoluteCertOffset));
   if (!certdi)
     return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIX509Cert> cert = certdi->mCert;
   if (!cert && certdi->mAddonInfo) {
     cert = certdi->mAddonInfo->mCert;
   }
 
@@ -1402,22 +1396,22 @@ nsCertTree::dumpMap()
     nsAutoString org(mTreeArray[i].orgName);
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("ORG[%s]", NS_LossyConvertUTF16toASCII(org).get()));
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("OPEN[%d]", mTreeArray[i].open));
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("INDEX[%d]", mTreeArray[i].certIndex));
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("NCHILD[%d]", mTreeArray[i].numChildren));
   }
   for (int i=0; i<mNumRows; i++) {
     treeArrayEl *el = GetThreadDescAtIndex(i);
-    if (el != nullptr) {
+    if (el) {
       nsAutoString td(el->orgName);
       PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("thread desc[%d]: %s", i, NS_LossyConvertUTF16toASCII(td).get()));
     }
     nsCOMPtr<nsIX509Cert> ct = GetCertAtIndex(i);
-    if (ct != nullptr) {
+    if (ct) {
       PRUnichar *goo;
       ct->GetCommonName(&goo);
       nsAutoString doo(goo);
       PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("cert [%d]: %s", i, NS_LossyConvertUTF16toASCII(doo).get()));
     }
   }
 }
 #endif
@@ -1456,17 +1450,17 @@ NS_IMETHODIMP nsCertTree::IsSorted(bool 
 }
 
 #define RETURN_NOTHING
 
 void 
 nsCertTree::CmpInitCriterion(nsIX509Cert *cert, CompareCacheHashEntry *entry,
                              sortCriterion crit, int32_t level)
 {
-  NS_ENSURE_TRUE( (cert!=0 && entry!=0), RETURN_NOTHING );
+  NS_ENSURE_TRUE(cert && entry, RETURN_NOTHING);
 
   entry->mCritInit[level] = true;
   nsXPIDLString &str = entry->mCrit[level];
   
   switch (crit) {
     case sort_IssuerOrg:
       cert->GetIssuerOrganization(str);
       if (str.IsEmpty())
@@ -1511,17 +1505,17 @@ nsCertTree::CmpInitCriterion(nsIX509Cert
   }
 }
 
 int32_t
 nsCertTree::CmpByCrit(nsIX509Cert *a, CompareCacheHashEntry *ace, 
                       nsIX509Cert *b, CompareCacheHashEntry *bce, 
                       sortCriterion crit, int32_t level)
 {
-  NS_ENSURE_TRUE( (a!=0 && ace!=0 && b!=0 && bce!=0), 0 );
+  NS_ENSURE_TRUE(a && ace && b && bce, 0);
 
   if (!ace->mCritInit[level]) {
     CmpInitCriterion(a, ace, crit, level);
   }
 
   if (!bce->mCritInit[level]) {
     CmpInitCriterion(b, bce, crit, level);
   }
@@ -1556,17 +1550,17 @@ nsCertTree::CmpBy(void *cache, nsIX509Ce
     return 0;
 
   if (!a)
     return -1;
 
   if (!b)
     return 1;
 
-  NS_ENSURE_TRUE( (cache!=0 && a!=0 && b!=0), 0 );
+  NS_ENSURE_TRUE(cache && a && b, 0);
 
   CompareCacheHashEntry *ace = getCacheEntry(cache, a);
   CompareCacheHashEntry *bce = getCacheEntry(cache, b);
 
   int32_t cmp;
   cmp = CmpByCrit(a, ace, b, bce, c0, 0);
   if (cmp != 0)
     return cmp;
--- a/security/manager/ssl/src/nsCertTree.h
+++ b/security/manager/ssl/src/nsCertTree.h
@@ -1,17 +1,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef _NS_CERTTREE_H_
 #define _NS_CERTTREE_H_
 
 #include "nsCOMPtr.h"
-#include "nsAutoPtr.h"
 #include "nsIServiceManager.h"
 #include "nsICertTree.h"
 #include "nsITreeView.h"
 #include "nsITreeBoxObject.h"
 #include "nsITreeSelection.h"
 #include "nsISupportsArray.h"
 #include "nsIMutableArray.h"
 #include "nsTArray.h"
@@ -40,33 +39,33 @@ struct CompareCacheHashEntryPtr : PLDHas
 
 class nsCertAddonInfo MOZ_FINAL : public nsISupports
 {
 public:
   NS_DECL_ISUPPORTS
 
   nsCertAddonInfo() : mUsageCount(0) {}
 
-  nsRefPtr<nsIX509Cert> mCert;
+  mozilla::RefPtr<nsIX509Cert> mCert;
   // how many display entries reference this?
   // (and therefore depend on the underlying cert)
   int32_t mUsageCount;
 };
 
 class nsCertTreeDispInfo : public nsICertTreeItem
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSICERTTREEITEM
 
   nsCertTreeDispInfo();
   nsCertTreeDispInfo(nsCertTreeDispInfo &other);
   virtual ~nsCertTreeDispInfo();
 
-  nsRefPtr<nsCertAddonInfo> mAddonInfo;
+  mozilla::RefPtr<nsCertAddonInfo> mAddonInfo;
   enum {
     direct_db, host_port_override
   } mTypeOfEntry;
   nsCString mAsciiHost;
   int32_t mPort;
   nsCertOverride::OverrideBits mOverrideBits;
   bool mIsTemporary;
   nsCOMPtr<nsIX509Cert> mCert;
@@ -108,31 +107,31 @@ protected:
   int32_t CountOrganizations();
 
   nsresult GetCertsByType(uint32_t aType, nsCertCompareFunc aCertCmpFn,
                           void *aCertCmpFnArg);
 
   nsresult GetCertsByTypeFromCache(nsINSSCertCache *aCache, uint32_t aType,
                                    nsCertCompareFunc aCertCmpFn, void *aCertCmpFnArg);
 private:
-  nsTArray< nsRefPtr<nsCertTreeDispInfo> > mDispInfo;
+  nsTArray< mozilla::RefPtr<nsCertTreeDispInfo> > mDispInfo;
   nsCOMPtr<nsITreeBoxObject>  mTree;
   nsCOMPtr<nsITreeSelection>  mSelection;
   treeArrayEl                *mTreeArray;
   int32_t                         mNumOrgs;
   int32_t                         mNumRows;
   PLDHashTable mCompareCache;
   nsCOMPtr<nsINSSComponent> mNSSComponent;
   nsCOMPtr<nsICertOverrideService> mOverrideService;
-  nsRefPtr<nsCertOverrideService> mOriginalOverrideService;
+  mozilla::RefPtr<nsCertOverrideService> mOriginalOverrideService;
 
   treeArrayEl *GetThreadDescAtIndex(int32_t _index);
   already_AddRefed<nsIX509Cert> 
     GetCertAtIndex(int32_t _index, int32_t *outAbsoluteCertOffset = nullptr);
-  already_AddRefed<nsCertTreeDispInfo> 
+  mozilla::TemporaryRef<nsCertTreeDispInfo>
     GetDispInfoAtIndex(int32_t index, int32_t *outAbsoluteCertOffset = nullptr);
   void FreeCertArray();
   nsresult UpdateUIContents();
 
   nsresult GetCertsByTypeFromCertList(CERTCertList *aCertList,
                                       uint32_t aType,
                                       nsCertCompareFunc  aCertCmpFn,
                                       void              *aCertCmpFnArg);
--- a/security/manager/ssl/src/nsCertVerificationThread.cpp
+++ b/security/manager/ssl/src/nsCertVerificationThread.cpp
@@ -1,14 +1,12 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "nsMemory.h"
-#include "nsAutoPtr.h"
 #include "nsCertVerificationThread.h"
 #include "nsThreadUtils.h"
 
 using namespace mozilla;
 
 nsCertVerificationThread *nsCertVerificationThread::verification_thread_singleton;
 
 NS_IMPL_THREADSAFE_ISUPPORTS1(nsCertVerificationResult, nsICertVerificationResult)
@@ -42,17 +40,17 @@ void nsCertVerificationJob::Run()
   if (!mListener || !mCert)
     return;
 
   uint32_t verified;
   uint32_t count;
   PRUnichar **usages;
 
   nsCOMPtr<nsICertVerificationResult> ires;
-  nsRefPtr<nsCertVerificationResult> vres = new nsCertVerificationResult;
+  RefPtr<nsCertVerificationResult> vres(new nsCertVerificationResult);
   if (vres)
   {
     nsresult rv = mCert->GetUsagesArray(false, // do not ignore OCSP
                                         &verified,
                                         &count,
                                         &usages);
     vres->mRV = rv;
     if (NS_SUCCEEDED(rv))
--- a/security/manager/ssl/src/nsClientAuthRemember.cpp
+++ b/security/manager/ssl/src/nsClientAuthRemember.cpp
@@ -2,16 +2,17 @@
  *
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsClientAuthRemember.h"
 
 #include "nsIX509Cert.h"
+#include "mozilla/RefPtr.h"
 #include "nsCRT.h"
 #include "nsNetUtil.h"
 #include "nsIObserverService.h"
 #include "nsNetUtil.h"
 #include "nsISupportsPrimitives.h"
 #include "nsPromiseFlatString.h"
 #include "nsThreadUtils.h"
 #include "nsStringBuffer.h"
@@ -89,17 +90,17 @@ nsClientAuthRememberService::RemoveAllFr
 }
 
 static nsresult
 GetCertFingerprintByOidTag(CERTCertificate* nsscert,
                            SECOidTag aOidTag, 
                            nsCString &fp)
 {
   unsigned int hash_len = HASH_ResultLenByOidTag(aOidTag);
-  nsRefPtr<nsStringBuffer> fingerprint = nsStringBuffer::Alloc(hash_len);
+  RefPtr<nsStringBuffer> fingerprint(nsStringBuffer::Alloc(hash_len));
   if (!fingerprint)
     return NS_ERROR_OUT_OF_MEMORY;
 
   PK11_HashBuf(aOidTag, (unsigned char*)fingerprint->Data(), 
                nsscert->derCert.data, nsscert->derCert.len);
 
   SECItem fpItem;
   fpItem.data = (unsigned char*)fingerprint->Data();
@@ -108,31 +109,31 @@ GetCertFingerprintByOidTag(CERTCertifica
   fp.Adopt(CERT_Hexify(&fpItem, 1));
   return NS_OK;
 }
 
 nsresult
 nsClientAuthRememberService::RememberDecision(const nsACString & aHostName, 
                                               CERTCertificate *aServerCert, CERTCertificate *aClientCert)
 {
-  // aClientCert == NULL means: remember that user does not want to use a cert
+  // aClientCert == nullptr means: remember that user does not want to use a cert
   NS_ENSURE_ARG_POINTER(aServerCert);
   if (aHostName.IsEmpty())
     return NS_ERROR_INVALID_ARG;
 
   nsAutoCString fpStr;
   nsresult rv = GetCertFingerprintByOidTag(aServerCert, SEC_OID_SHA256, fpStr);
   if (NS_FAILED(rv))
     return rv;
 
   {
     ReentrantMonitorAutoEnter lock(monitor);
     if (aClientCert) {
       nsNSSCertificate pipCert(aClientCert);
-      char *dbkey = NULL;
+      char *dbkey = nullptr;
       rv = pipCert.GetDbKey(&dbkey);
       if (NS_SUCCEEDED(rv) && dbkey) {
         AddEntryToList(aHostName, fpStr, 
                        nsDependentCString(dbkey));
       }
       if (dbkey) {
         PORT_Free(dbkey);
       }
--- a/security/manager/ssl/src/nsClientAuthRemember.h
+++ b/security/manager/ssl/src/nsClientAuthRemember.h
@@ -6,17 +6,16 @@
 
 #ifndef __NSCLIENTAUTHREMEMBER_H__
 #define __NSCLIENTAUTHREMEMBER_H__
 
 #include "mozilla/ReentrantMonitor.h"
 #include "nsTHashtable.h"
 #include "nsIObserver.h"
 #include "nsIX509Cert.h"
-#include "nsAutoPtr.h"
 #include "nsNSSCertificate.h"
 #include "nsString.h"
 #include "nsWeakReference.h"
 #include "mozilla/Attributes.h"
 
 class nsClientAuthRemember
 {
 public:
--- a/security/manager/ssl/src/nsCrypto.cpp
+++ b/security/manager/ssl/src/nsCrypto.cpp
@@ -9,17 +9,16 @@
 #include "nsKeygenThread.h"
 #include "nsNSSCertificate.h"
 #include "nsNSSCertificateDB.h"
 #include "nsPKCS12Blob.h"
 #include "nsPK11TokenDB.h"
 #include "nsThreadUtils.h"
 #include "nsIServiceManager.h"
 #include "nsIMemory.h"
-#include "nsAutoPtr.h"
 #include "nsAlgorithm.h"
 #include "nsCRT.h"
 #include "prprf.h"
 #include "nsDOMCID.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMClassInfo.h"
 #include "nsIDOMDocument.h"
 #include "nsIDocument.h"
@@ -45,42 +44,43 @@
 #include <ctype.h>
 #include "nsReadableUtils.h"
 #include "pk11func.h"
 #include "keyhi.h"
 #include "cryptohi.h"
 #include "seccomon.h"
 #include "secerr.h"
 #include "sechash.h"
-extern "C" {
 #include "crmf.h"
 #include "pk11pqg.h"
-}
 #include "cmmf.h"
 #include "nssb64.h"
 #include "base64.h"
 #include "cert.h"
 #include "certdb.h"
 #include "secmod.h"
 #include "nsISaveAsCharset.h"
 #include "nsNativeCharsetUtils.h"
 
 #include "ssl.h" // For SSL_ClearSessionCache
 
 #include "nsNSSCleaner.h"
+
+#include "nsNSSShutDown.h"
+#include "nsNSSCertHelper.h"
+
+using namespace mozilla;
+
 NSSCleanupAutoPtrClass(SECKEYPrivateKey, SECKEY_DestroyPrivateKey)
 NSSCleanupAutoPtrClass(PK11SlotInfo, PK11_FreeSlot)
 NSSCleanupAutoPtrClass(CERTCertNicknames, CERT_FreeNicknames)
 NSSCleanupAutoPtrClass(PK11SymKey, PK11_FreeSymKey)
 NSSCleanupAutoPtrClass_WithParam(PK11Context, PK11_DestroyContext, TrueParam, true)
 NSSCleanupAutoPtrClass_WithParam(SECItem, SECITEM_FreeItem, TrueParam, true)
 
-#include "nsNSSShutDown.h"
-#include "nsNSSCertHelper.h"
-
 /*
  * These are the most common error strings that are returned
  * by the JavaScript methods in case of error.
  */
 
 #define JS_ERROR       "error:"
 #define JS_ERROR_INTERNAL  JS_ERROR"internalError"
 
@@ -331,23 +331,23 @@ cryptojs_convert_to_mechanism(nsKeyGenTy
  * This function converts a string read through JavaScript parameters
  * and translates it to the internal enumeration representing the
  * key gen type.
  */
 static nsKeyGenType
 cryptojs_interpret_key_gen_type(char *keyAlg)
 {
   char *end;
-  if (keyAlg == nullptr) {
+  if (!keyAlg) {
     return invalidKeyGen;
   }
   /* First let's remove all leading and trailing white space */
   while (isspace(keyAlg[0])) keyAlg++;
   end = strchr(keyAlg, '\0');
-  if (end == nullptr) {
+  if (!end) {
     return invalidKeyGen;
   }
   end--;
   while (isspace(*end)) end--;
   end[1] = '\0';
   if (strcmp(keyAlg, "rsa-ex") == 0) {
     return rsaEnc;
   } else if (strcmp(keyAlg, "rsa-dual-use") == 0) {
@@ -452,17 +452,17 @@ nsConvertToActualKeyGenParams(uint32_t k
     // the JS code just yet.
     if (params)
       return nullptr;
 
     PK11RSAGenParams *rsaParams;
     rsaParams = static_cast<PK11RSAGenParams*>
                            (nsMemory::Alloc(sizeof(PK11RSAGenParams)));
                               
-    if (rsaParams == nullptr) {
+    if (!rsaParams) {
       return nullptr;
     }
     /* I'm just taking the same parameters used in 
      * certdlgs.c:GenKey
      */
     if (keySize > 0) {
       rsaParams->keySizeInBits = keySize;
     } else {
@@ -721,32 +721,32 @@ cryptojs_generateOneKeyPair(JSContext *c
     if (KeygenRunnable) {
       NS_ADDREF(KeygenRunnable);
     }
   }
   
   // "firstAttemptSlot" and "secondAttemptSlot" are alternative names
   // for better code readability, we don't increase the reference counts.
   
-  PK11SlotInfo *firstAttemptSlot = NULL;
+  PK11SlotInfo *firstAttemptSlot = nullptr;
   PK11AttrFlags firstAttemptFlags = 0;
 
   PK11SlotInfo *secondAttemptSlot = slot;
   PK11AttrFlags secondAttemptFlags = sensitiveFlags | permanentTokenFlags;
   
   if (willEscrow) {
     secondAttemptFlags |= extractableFlags;
   }
   
   if (!intSlot || PK11_IsInternal(slot)) {
     // if we cannot use the internal slot, then there is only one attempt
     // if the destination slot is the internal slot, then there is only one attempt
     firstAttemptSlot = secondAttemptSlot;
     firstAttemptFlags = secondAttemptFlags;
-    secondAttemptSlot = NULL;
+    secondAttemptSlot = nullptr;
     secondAttemptFlags = 0;
   }
   else {
     firstAttemptSlot = intSlot;
     firstAttemptFlags = sensitiveFlags | temporarySessionFlags;
     
     // We always need the extractable flag on the first attempt,
     // because we want to move the key to another slot - ### is this correct?
@@ -796,33 +796,33 @@ cryptojs_generateOneKeyPair(JSContext *c
           // We call join on the thread, 
           // so we can be sure that no simultaneous access to the passed parameters will happen.
           KeygenRunnable->Join();
         }
       }
 
       NS_RELEASE(dialogs);
       if (NS_SUCCEEDED(rv)) {
-        PK11SlotInfo *used_slot = NULL;
+        PK11SlotInfo *used_slot = nullptr;
         rv = KeygenRunnable->ConsumeResult(&used_slot, 
                                            &keyPairInfo->privKey, &keyPairInfo->pubKey);
 
         if (NS_SUCCEEDED(rv)) {
-          if ((used_slot == firstAttemptSlot) && (secondAttemptSlot != NULL)) {
+          if ((used_slot == firstAttemptSlot) && secondAttemptSlot) {
             mustMoveKey = true;
           }
         
           PK11_FreeSlot(used_slot);
         }
       }
     }
   }
 
-  firstAttemptSlot = NULL;
-  secondAttemptSlot = NULL;
+  firstAttemptSlot = nullptr;
+  secondAttemptSlot = nullptr;
   
   nsFreeKeyGenParams(mechanism, keyGenParams);
 
   if (KeygenRunnable) {
     NS_RELEASE(KeygenRunnable);
   }
 
   if (!keyPairInfo->privKey || !keyPairInfo->pubKey) {
@@ -943,19 +943,19 @@ cryptojs_ReadArgsAndGenerateKey(JSContex
   NS_ENSURE_TRUE(!!keyGenAlg, NS_ERROR_OUT_OF_MEMORY);
   keyGenType->keyGenType = cryptojs_interpret_key_gen_type(keyGenAlg.ptr());
   if (keyGenType->keyGenType == invalidKeyGen) {
     JS_ReportError(cx, "%s%s%s", JS_ERROR,
                    "invalid key generation argument:",
                    keyGenAlg.ptr());
     goto loser;
   }
-  if (*slot == nullptr) {
+  if (!*slot) {
     *slot = nsGetSlotForKeyGen(keyGenType->keyGenType, uiCxt);
-    if (*slot == nullptr)
+    if (!*slot)
       goto loser;
   }
 
   rv = cryptojs_generateOneKeyPair(cx,keyGenType,keySize,params.ptr(),uiCxt,
                                    *slot,willEscrow);
 
   if (rv != NS_OK) {
     JS_ReportError(cx,"%s%s%s", JS_ERROR,
@@ -1159,21 +1159,21 @@ nsSetKeyUsageExtension(CRMFCertRequest *
   SEC_ASN1Template         bitStrTemplate = {SEC_ASN1_BIT_STRING, 0, nullptr,
                                              sizeof(SECItem)};
 
   keyUsageValue.data = &keyUsage;
   keyUsageValue.len  = 1;
   nsPrepareBitStringForEncoding(&bitsmap, &keyUsageValue);
 
   encodedExt = SEC_ASN1EncodeItem(nullptr, nullptr, &bitsmap,&bitStrTemplate);
-  if (encodedExt == nullptr) {
+  if (!encodedExt) {
     goto loser;
   }
   ext = CRMF_CreateCertExtension(SEC_OID_X509_KEY_USAGE, true, encodedExt);
-  if (ext == nullptr) {
+  if (!ext) {
       goto loser;
   }
   extAddParams.numExtensions = 1;
   extAddParams.extensions = &ext;
   srv = CRMF_CertRequestSetTemplateField(crmfReq, crmfExtension,
                                          &extAddParams);
   if (srv != SECSuccess) {
       goto loser;
@@ -1483,17 +1483,17 @@ nsSet_EC_DHMAC_ProofOfPossession(CRMFCer
   // the "text" input for HMAC shall be the DER encoded version of
   // of the single cert request.
   // We'll produce that encoding and destroy it afterwards,
   // because when sending the complete package to the CA,
   // we'll use a different encoding, one that includes POP and
   // allows multiple requests to be sent in one step.
 
   unsigned long der_request_len = 0;
-  SECItem *der_request = NULL;
+  SECItem *der_request = nullptr;
   SECItemCleanerTrueParam der_request_cleaner(der_request);
 
   if (SECSuccess != CRMF_EncodeCertRequest(certReq, 
                                            nsCRMFEncoderItemCount, 
                                            &der_request_len))
     return NS_ERROR_FAILURE;
 
   der_request = SECITEM_AllocItem(nullptr, nullptr, der_request_len);
@@ -1511,41 +1511,41 @@ nsSet_EC_DHMAC_ProofOfPossession(CRMFCer
                                            der_request))
     return NS_ERROR_FAILURE;
 
   // RFC 2511 Appendix A section 2 c):
   // "A key K is derived from the shared secret Kec and the subject and
   //  issuer names in the CA's certificate as follows:
   //  K = SHA1(DER-encoded-subjectName | Kec | DER-encoded-issuerName)"
 
-  PK11SymKey *shared_secret = NULL;
+  PK11SymKey *shared_secret = nullptr;
   PK11SymKeyCleaner shared_secret_cleaner(shared_secret);
 
-  PK11SymKey *subject_and_secret = NULL;
+  PK11SymKey *subject_and_secret = nullptr;
   PK11SymKeyCleaner subject_and_secret_cleaner(subject_and_secret);
 
-  PK11SymKey *subject_and_secret_and_issuer = NULL;
+  PK11SymKey *subject_and_secret_and_issuer = nullptr;
   PK11SymKeyCleaner subject_and_secret_and_issuer_cleaner(subject_and_secret_and_issuer);
 
-  PK11SymKey *sha1_of_subject_and_secret_and_issuer = NULL;
+  PK11SymKey *sha1_of_subject_and_secret_and_issuer = nullptr;
   PK11SymKeyCleaner sha1_of_subject_and_secret_and_issuer_cleaner(sha1_of_subject_and_secret_and_issuer);
 
   shared_secret = 
     PK11_PubDeriveWithKDF(keyInfo->privKey, // SECKEYPrivateKey *privKey
                           keyInfo->ecPopPubKey,  // SECKEYPublicKey *pubKey
                           false, // bool isSender
-                          NULL, // SECItem *randomA
-                          NULL, // SECItem *randomB
+                          nullptr, // SECItem *randomA
+                          nullptr, // SECItem *randomB
                           CKM_ECDH1_DERIVE, // CK_MECHANISM_TYPE derive
                           CKM_CONCATENATE_DATA_AND_BASE, // CK_MECHANISM_TYPE target
                           CKA_DERIVE, // CK_ATTRIBUTE_TYPE operation
                           0, // int keySize
                           CKD_NULL, // CK_ULONG kdf
-                          NULL, // SECItem *sharedData
-                          NULL); // void *wincx
+                          nullptr, // SECItem *sharedData
+                          nullptr); // void *wincx
 
   if (!shared_secret)
     return NS_ERROR_FAILURE;
 
   CK_KEY_DERIVATION_STRING_DATA concat_data_base;
   concat_data_base.pData = keyInfo->ecPopCert->derSubject.data;
   concat_data_base.ulLen = keyInfo->ecPopCert->derSubject.len;
   SECItem concat_data_base_item;
@@ -1579,25 +1579,25 @@ nsSet_EC_DHMAC_ProofOfPossession(CRMFCer
                 0); // int keySize
 
   if (!subject_and_secret_and_issuer)
     return NS_ERROR_FAILURE;
 
   sha1_of_subject_and_secret_and_issuer =
     PK11_Derive(subject_and_secret_and_issuer, // PK11SymKey *baseKey
                 CKM_SHA1_KEY_DERIVATION, // CK_MECHANISM_TYPE mechanism
-                NULL, // SECItem *param
+                nullptr, // SECItem *param
                 CKM_SHA_1_HMAC, // CK_MECHANISM_TYPE target
                 CKA_SIGN, // CK_ATTRIBUTE_TYPE operation
                 0); // int keySize
 
   if (!sha1_of_subject_and_secret_and_issuer)
     return NS_ERROR_FAILURE;
 
-  PK11Context *context = NULL;
+  PK11Context *context = nullptr;
   PK11ContextCleanerTrueParam context_cleaner(context);
 
   SECItem ignore;
   ignore.data = 0;
   ignore.len = 0;
 
   context = 
     PK11_CreateContextBySymKey(CKM_SHA_1_HMAC, // CK_MECHANISM_TYPE type
@@ -1610,17 +1610,17 @@ nsSet_EC_DHMAC_ProofOfPossession(CRMFCer
 
   if (SECSuccess != PK11_DigestBegin(context))
     return NS_ERROR_FAILURE;
 
   if (SECSuccess != 
       PK11_DigestOp(context, der_request->data, der_request->len))
     return NS_ERROR_FAILURE;
 
-  SECItem *result_hmac_sha1_item = NULL;
+  SECItem *result_hmac_sha1_item = nullptr;
   SECItemCleanerTrueParam result_hmac_sha1_item_cleaner(result_hmac_sha1_item);
 
   result_hmac_sha1_item = SECITEM_AllocItem(nullptr, nullptr, SHA1_LENGTH);
   if (!result_hmac_sha1_item)
     return NS_ERROR_FAILURE;
 
   if (SECSuccess !=
       PK11_DigestFinal(context, 
@@ -1751,22 +1751,22 @@ static SECItem*
 nsEncodeCertReqMessages(CRMFCertReqMsg **certReqMsgs)
 {
   unsigned long len = 0;
   if (CRMF_EncodeCertReqMessages(certReqMsgs, nsCRMFEncoderItemCount, &len)
       != SECSuccess) {
     return nullptr;
   }
   SECItem *dest = (SECItem *)PORT_Alloc(sizeof(SECItem));
-  if (dest == nullptr) {
+  if (!dest) {
     return nullptr;
   }
   dest->type = siBuffer;
   dest->data = (unsigned char *)PORT_Alloc(len);
-  if (dest->data == nullptr) {
+  if (!dest->data) {
     PORT_Free(dest);
     return nullptr;
   }
   dest->len = 0;
 
   if (CRMF_EncodeCertReqMessages(certReqMsgs, nsCRMFEncoderItemStore, dest)
       != SECSuccess) {
     SECITEM_FreeItem(dest, true);
@@ -1783,17 +1783,17 @@ static char*
 nsCreateReqFromKeyPairs(nsKeyPairInfo *keyids, int32_t numRequests,
                         char *reqDN, char *regToken, char *authenticator,
                         nsNSSCertificate *wrappingCert) 
 {
   // We'use the goto notation for clean-up purposes in this function
   // that calls the C API of NSS.
   int32_t i;
   // The ASN1 encoder in NSS wants the last entry in the array to be
-  // NULL so that it knows when the last element is.
+  // nullptr so that it knows when the last element is.
   CRMFCertReqMsg **certReqMsgs = new CRMFCertReqMsg*[numRequests+1];
   CRMFCertRequest *certReq;
   if (!certReqMsgs)
     return nullptr;
   memset(certReqMsgs, 0, sizeof(CRMFCertReqMsg*)*(1+numRequests));
   SECStatus srv;
   nsresult rv;
   SECItem *encodedReq;
@@ -1981,20 +1981,16 @@ nsCrypto::GenerateCRMFRequest(nsIDOMCRMF
     }
     if (!okay)
       return NS_OK;
     willEscrow = true;
   }
   nsCOMPtr<nsIInterfaceRequestor> uiCxt = new PipUIContext;
   int32_t numRequests = (argc - 5)/3;
   nsKeyPairInfo *keyids = new nsKeyPairInfo[numRequests];
-  if (keyids == nullptr) {
-    JS_ReportError(cx, "%s\n", JS_ERROR_INTERNAL);
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
   memset(keyids, 0, sizeof(nsKeyPairInfo)*numRequests);
   int keyInfoIndex;
   uint32_t i;
   PK11SlotInfo *slot = nullptr;
   // Go through all of the arguments and generate the appropriate key pairs.
   for (i=5,keyInfoIndex=0; i<argc; i+=3,keyInfoIndex++) {
     nrv = cryptojs_ReadArgsAndGenerateKey(cx, &argv[i], &keyids[keyInfoIndex],
                                          uiCxt, &slot, willEscrow);
@@ -2018,22 +2014,16 @@ nsCrypto::GenerateCRMFRequest(nsIDOMCRMF
 #ifdef DEBUG_javi
   printf ("Created the folloing CRMF request:\n%s\n", encodedRequest);
 #endif
   if (!encodedRequest) {
     nsFreeKeyPairInfo(keyids, numRequests);
     return NS_ERROR_FAILURE;
   }                                                    
   nsCRMFObject *newObject = new nsCRMFObject();
-  if (newObject == nullptr) {
-    JS_ReportError(cx, "%s%s\n", JS_ERROR, "could not create crmf JS object");
-
-    nsFreeKeyPairInfo(keyids,numRequests);
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
   newObject->SetCRMFRequest(encodedRequest);
   *aReturn = newObject;
   //Give a reference to the returnee.
   NS_ADDREF(*aReturn);
   nsFreeKeyPairInfo(keyids, numRequests);
 
   // 
   // Post an event on the UI queue so that the JS gets called after
@@ -2052,29 +2042,25 @@ nsCrypto::GenerateCRMFRequest(nsIDOMCRMF
   NS_ENSURE_TRUE(secMan, NS_ERROR_UNEXPECTED);
   
   nsCOMPtr<nsIPrincipal> principals;
   nsresult rv = secMan->GetSubjectPrincipal(getter_AddRefs(principals));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(principals, NS_ERROR_UNEXPECTED);
   
   nsCryptoRunArgs *args = new nsCryptoRunArgs();
-  if (!args)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   args->m_cx         = cx;
   args->m_kungFuDeathGrip = GetISupportsFromContext(cx);
   args->m_scope      = JS_GetParent(script_obj);
 
   args->m_jsCallback.Adopt(!!jsCallback ? nsCRT::strdup(jsCallback.ptr()) : 0);
   args->m_principals = principals;
   
   nsCryptoRunnable *cryptoRunnable = new nsCryptoRunnable(args);
-  if (!cryptoRunnable)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   rv = NS_DispatchToMainThread(cryptoRunnable);
   if (NS_FAILED(rv))
     delete cryptoRunnable;
 
   return rv;
 }
 
@@ -2355,30 +2341,30 @@ nsCrypto::ImportUserCertificates(const n
       continue;
     }
     // Let's figure out which nickname to give the cert.  If 
     // a certificate with the same subject name already exists,
     // then just use that one, otherwise, get the default nickname.
     if (currCert->nickname) {
       localNick = currCert->nickname;
     }
-    else if (nickname == nullptr || nickname[0] == '\0') {
+    else if (!nickname || nickname[0] == '\0') {
       nsNSSCertificateDB::get_default_nickname(currCert, ctx, localNick);
     } else {
       //This is the case where we're getting a brand new
       //cert that doesn't have the same subjectName as a cert
       //that already exists in our db and the CA page has 
       //designated a nickname to use for the newly issued cert.
       localNick = nickname;
     }
     {
       char *cast_const_away = const_cast<char*>(localNick.get());
       slot = PK11_ImportCertForKey(currCert, cast_const_away, ctx);
     }
-    if (slot == nullptr) {
+    if (!slot) {
       rv = NS_ERROR_FAILURE;
       goto loser;
     }
     if (aDoForcedBackup) {
       certArr[i] = nsNSSCertificate::Create(currCert);
       if (!certArr[i])
         goto loser;
       NS_ADDREF(certArr[i]);
@@ -2674,17 +2660,17 @@ nsCrypto::SignText(const nsAString& aStr
   }
 
   PRUnichar** certDetailsList = certNicknameList.get() + nicknames->numnicknames;
 
   int32_t certsToUse;
   for (node = CERT_LIST_HEAD(certList), certsToUse = 0;
        !CERT_LIST_END(node, certList) && certsToUse < nicknames->numnicknames;
        node = CERT_LIST_NEXT(node)) {
-    nsRefPtr<nsNSSCertificate> tempCert = nsNSSCertificate::Create(node->cert);
+    RefPtr<nsNSSCertificate> tempCert(nsNSSCertificate::Create(node->cert));
     if (tempCert) {
       nsAutoString nickWithSerial, details;
       rv = tempCert->FormatUIStrings(NS_ConvertUTF8toUTF16(nicknames->nicknames[certsToUse]),
                                      nickWithSerial, details);
       if (NS_SUCCEEDED(rv)) {
         certNicknameList[certsToUse] = ToNewUnicode(nickWithSerial);
         if (certNicknameList[certsToUse]) {
           certDetailsList[certsToUse] = ToNewUnicode(details);
--- a/security/manager/ssl/src/nsDataSignatureVerifier.cpp
+++ b/security/manager/ssl/src/nsDataSignatureVerifier.cpp
@@ -14,17 +14,17 @@
 
 SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate)
 
 NS_IMPL_ISUPPORTS1(nsDataSignatureVerifier, nsIDataSignatureVerifier)
 
 const SEC_ASN1Template CERT_SignatureDataTemplate[] =
 {
     { SEC_ASN1_SEQUENCE,
-        0, NULL, sizeof(CERTSignedData) },
+        0, nullptr, sizeof(CERTSignedData) },
     { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
         offsetof(CERTSignedData,signatureAlgorithm),
         SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate), },
     { SEC_ASN1_BIT_STRING,
         offsetof(CERTSignedData,signature), },
     { 0, }
 };
 
@@ -89,17 +89,17 @@ nsDataSignatureVerifier::VerifyData(cons
     }
     
     // Perform the final verification
     DER_ConvertBitString(&(sigData.signature));
     ss = VFY_VerifyDataWithAlgorithmID((const unsigned char*)nsPromiseFlatCString(aData).get(),
                                        aData.Length(), publicKey,
                                        &(sigData.signature),
                                        &(sigData.signatureAlgorithm),
-                                       NULL, NULL);
+                                       nullptr, nullptr);
     
     // Clean up remaining objects
     SECKEY_DestroyPublicKey(publicKey);
     PORT_FreeArena(arena, false);
     
     *_retval = (ss == SECSuccess);
 
     return NS_OK;
--- a/security/manager/ssl/src/nsIdentityChecking.cpp
+++ b/security/manager/ssl/src/nsIdentityChecking.cpp
@@ -1021,17 +1021,17 @@ nsNSSComponent::IdentityInfoInit()
 
 // Find the first policy OID that is known to be an EV policy OID.
 static SECStatus getFirstEVPolicy(CERTCertificate *cert, SECOidTag &outOidTag)
 {
   if (!cert)
     return SECFailure;
 
   if (cert->extensions) {
-    for (int i=0; cert->extensions[i] != nullptr; i++) {
+    for (int i=0; cert->extensions[i]; i++) {
       const SECItem *oid = &cert->extensions[i]->id;
 
       SECOidTag oidTag = SECOID_FindOIDTag(oid);
       if (oidTag != SEC_OID_X509_CERTIFICATE_POLICIES)
         continue;
 
       SECItem *value = &cert->extensions[i]->value;
 
@@ -1040,17 +1040,17 @@ static SECStatus getFirstEVPolicy(CERTCe
     
       policies = CERT_DecodeCertificatePoliciesExtension(value);
       if (!policies)
         continue;
     
       policyInfos = policies->policyInfos;
 
       bool found = false;
-      while (*policyInfos != NULL) {
+      while (*policyInfos) {
         policyInfo = *policyInfos++;
 
         SECOidTag oid_tag = policyInfo->oid;
         if (oid_tag != SEC_OID_UNKNOWN && isEVPolicy(oid_tag)) {
           // in our list of OIDs accepted for EV
           outOidTag = oid_tag;
           found = true;
           break;
--- a/security/manager/ssl/src/nsKeygenHandler.cpp
+++ b/security/manager/ssl/src/nsKeygenHandler.cpp
@@ -1,27 +1,23 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  *
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-extern "C" {
 #include "secdert.h"
-}
 #include "nspr.h"
 #include "nsNSSComponent.h" // for PIPNSS string bundle calls.
 #include "keyhi.h"
 #include "secder.h"
 #include "cryptohi.h"
 #include "base64.h"
 #include "secasn1.h"
-extern "C" {
 #include "pk11pqg.h"
-}
 #include "nsKeygenHandler.h"
 #include "nsVoidArray.h"
 #include "nsIServiceManager.h"
 #include "nsIDOMHTMLSelectElement.h"
 #include "nsIContent.h"
 #include "nsKeygenThread.h"
 #include "nsReadableUtils.h"
 #include "nsUnicharUtils.h"
@@ -32,17 +28,17 @@ extern "C" {
 
 //These defines are taken from the PKCS#11 spec
 #define CKM_RSA_PKCS_KEY_PAIR_GEN     0x00000000
 #define CKM_DH_PKCS_KEY_PAIR_GEN      0x00000020
 #define CKM_DSA_KEY_PAIR_GEN          0x00000010
 
 DERTemplate SECAlgorithmIDTemplate[] = {
     { DER_SEQUENCE,
-          0, NULL, sizeof(SECAlgorithmID) },
+          0, nullptr, sizeof(SECAlgorithmID) },
     { DER_OBJECT_ID,
           offsetof(SECAlgorithmID,algorithm), },
     { DER_OPTIONAL | DER_ANY,
           offsetof(SECAlgorithmID,parameters), },
     { 0, }
 };
 
 DERTemplate CERTSubjectPublicKeyInfoTemplate[] = {
@@ -60,17 +56,17 @@ DERTemplate CERTPublicKeyAndChallengeTem
 {
     { DER_SEQUENCE, 0, nullptr, sizeof(CERTPublicKeyAndChallenge) },
     { DER_ANY, offsetof(CERTPublicKeyAndChallenge,spki), },
     { DER_IA5_STRING, offsetof(CERTPublicKeyAndChallenge,challenge), },
     { 0, }
 };
 
 const SEC_ASN1Template SECKEY_PQGParamsTemplate[] = {
-    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(PQGParams) },
+    { SEC_ASN1_SEQUENCE, 0, nullptr, sizeof(PQGParams) },
     { SEC_ASN1_INTEGER, offsetof(PQGParams,prime) },
     { SEC_ASN1_INTEGER, offsetof(PQGParams,subPrime) },
     { SEC_ASN1_INTEGER, offsetof(PQGParams,base) },
     { 0, }
 };
 
 
 static NS_DEFINE_IID(kIDOMHTMLSelectElementIID, NS_IDOMHTMLSELECTELEMENT_IID);
@@ -221,36 +217,36 @@ static CurveNameTagPair nameTagPair[] =
   { "nistb571", SEC_OID_SECG_EC_SECT571R1},
 
 };
 
 SECKEYECParams * 
 decode_ec_params(const char *curve)
 {
     SECKEYECParams *ecparams;
-    SECOidData *oidData = NULL;
+    SECOidData *oidData = nullptr;
     SECOidTag curveOidTag = SEC_OID_UNKNOWN; /* default */
     int i, numCurves;
 
     if (curve && *curve) {
         numCurves = sizeof(nameTagPair)/sizeof(CurveNameTagPair);
         for (i = 0; ((i < numCurves) && (curveOidTag == SEC_OID_UNKNOWN)); 
              i++) {
             if (PL_strcmp(curve, nameTagPair[i].curveName) == 0)
                 curveOidTag = nameTagPair[i].curveOidTag;
         }
     }
 
-    /* Return NULL if curve name is not recognized */
+    /* Return nullptr if curve name is not recognized */
     if ((curveOidTag == SEC_OID_UNKNOWN) || 
-        (oidData = SECOID_FindOIDByTag(curveOidTag)) == NULL) {
+        (oidData = SECOID_FindOIDByTag(curveOidTag)) == nullptr) {
         return nullptr;
     }
 
-    ecparams = SECITEM_AllocItem(NULL, NULL, (2 + oidData->oid.len));
+    ecparams = SECITEM_AllocItem(nullptr, nullptr, (2 + oidData->oid.len));
 
     if (!ecparams)
       return nullptr;
 
     /* 
      * ecparams->data needs to contain the ASN encoding of an object ID (OID)
      * representing the named curve. The actual OID is in 
      * oidData->oid.data so we simply prepend 0x06 and OID length
@@ -275,18 +271,16 @@ nsKeygenFormProcessor::~nsKeygenFormProc
 }
 
 nsresult
 nsKeygenFormProcessor::Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult)
 {
   nsresult rv;
   NS_ENSURE_NO_AGGREGATION(aOuter);
   nsKeygenFormProcessor* formProc = new nsKeygenFormProcessor();
-  if (!formProc)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   nsCOMPtr<nsISupports> stabilize = formProc;
   rv = formProc->Init();
   if (NS_SUCCEEDED(rv)) {
     rv = formProc->QueryInterface(aIID, aResult);
   }
   return rv;
 }
@@ -528,25 +522,25 @@ nsKeygenFormProcessor::GetPublicKey(nsAS
 
         keyGenMechanism = CKM_DSA_KEY_PAIR_GEN;
         if (strcmp(keyparamsString, "null") == 0)
             goto loser;
         str = keyparamsString;
         bool found_match = false;
         do {
             end = strchr(str, ',');
-            if (end != nullptr)
+            if (end)
                 *end = '\0';
             primeBits = pqg_prime_bits(str);
             if (keysize == primeBits) {
                 found_match = true;
                 break;
             }
             str = end + 1;
-        } while (end != nullptr);
+        } while (end);
         if (!found_match) {
             goto loser;
         }
     } else if (aKeyType.LowerCaseEqualsLiteral("ec")) {
         keyparamsString = ToNewCString(aKeyParams);
         if (!keyparamsString) {
             rv = NS_ERROR_OUT_OF_MEMORY;
             goto loser;
@@ -749,17 +743,17 @@ loser:
         SECKEY_DestroyPublicKey(publicKey);
     }
     if ( privateKey ) {
         SECKEY_DestroyPrivateKey(privateKey);
     }
     if ( arena ) {
         PORT_FreeArena(arena, true);
     }
-    if (slot != nullptr) {
+    if (slot) {
         PK11_FreeSlot(slot);
     }
     if (KeygenRunnable) {
         NS_RELEASE(KeygenRunnable);
     }
     if (keyparamsString) {
         nsMemory::Free(keyparamsString);
     }
--- a/security/manager/ssl/src/nsNSSASN1Object.cpp
+++ b/security/manager/ssl/src/nsNSSASN1Object.cpp
@@ -111,17 +111,17 @@ buildASN1ObjectFromDER(unsigned char *da
   // data is a buffer that is len bytes long and has to be
   //      interpreted according to its type.
   unsigned long bytesUsed;
   bool indefinite;
   int32_t len;
   uint32_t type;
 
   rv = parent->GetASN1Objects(getter_AddRefs(parentObjects));
-  if (NS_FAILED(rv) || parentObjects == nullptr)
+  if (NS_FAILED(rv) || !parentObjects)
     return NS_ERROR_FAILURE;
   while (data < end) {
     code = *data;
     tagnum = code & SEC_ASN1_TAGNUM_MASK;
 
     /*
      * NOTE: This code does not (yet) handle the high-tag-number form!
      */
@@ -188,17 +188,17 @@ CreateFromDER(unsigned char *data,
   if (NS_SUCCEEDED(rv)) {
     // The actual object will be the first element inserted
     // into the sequence of the sequence variable we created.
     nsCOMPtr<nsIMutableArray> elements;
 
     sequence->GetASN1Objects(getter_AddRefs(elements));
     nsCOMPtr<nsIASN1Object> asn1Obj = do_QueryElementAt(elements, 0);
     *retval = asn1Obj;
-    if (*retval == nullptr)
+    if (!*retval)
       return NS_ERROR_FAILURE;
 
     NS_ADDREF(*retval);
       
   }
   return rv; 
 }
 
@@ -213,17 +213,17 @@ nsNSSASN1Sequence::nsNSSASN1Sequence() :
 nsNSSASN1Sequence::~nsNSSASN1Sequence()
 {
   /* destructor code */
 }
 
 NS_IMETHODIMP 
 nsNSSASN1Sequence::GetASN1Objects(nsIMutableArray * *aASN1Objects)
 {
-  if (mASN1Objects == nullptr) {
+  if (!mASN1Objects) {
     mASN1Objects = do_CreateInstance(NS_ARRAY_CONTRACTID);
   }
   *aASN1Objects = mASN1Objects;
   NS_IF_ADDREF(*aASN1Objects);
   return NS_OK;
 }
 
 NS_IMETHODIMP 
--- a/security/manager/ssl/src/nsNSSCallbacks.cpp
+++ b/security/manager/ssl/src/nsNSSCallbacks.cpp
@@ -332,17 +332,17 @@ nsNSSHttpRequestSession::internal_send_r
   if (!mListener)
     return SECFailure;
 
   Mutex& waitLock = mListener->mLock;
   CondVar& waitCondition = mListener->mCondition;
   volatile bool &waitFlag = mListener->mWaitFlag;
   waitFlag = true;
 
-  nsRefPtr<nsHTTPDownloadEvent> event = new nsHTTPDownloadEvent;
+  RefPtr<nsHTTPDownloadEvent> event(new nsHTTPDownloadEvent);
   if (!event)
     return SECFailure;
 
   event->mListener = mListener;
   this->AddRef();
   event->mRequestSession = this;
 
   nsresult rv = NS_DispatchToMainThread(event);
@@ -396,17 +396,18 @@ nsNSSHttpRequestSession::internal_send_r
       {
         bool timeout = 
           (PRIntervalTime)(PR_IntervalNow() - start_time) > mTimeoutInterval;
  
         if (timeout)
         {
           request_canceled = true;
 
-          nsRefPtr<nsCancelHTTPDownloadEvent> cancelevent = new nsCancelHTTPDownloadEvent;
+          RefPtr<nsCancelHTTPDownloadEvent> cancelevent(
+            new nsCancelHTTPDownloadEvent);
           cancelevent->mListener = mListener;
           rv = NS_DispatchToMainThread(cancelevent);
           if (NS_FAILED(rv)) {
             NS_WARNING("cannot post cancel event");
           }
           break;
         }
       }
@@ -718,17 +719,17 @@ void PK11PasswordPromptRunnable::RunOnTa
 
   if (!mIR)
   {
     nsNSSComponent::GetNewPrompter(getter_AddRefs(prompt));
   }
   else
   {
     prompt = do_GetInterface(mIR);
-    NS_ASSERTION(prompt != nullptr, "callbacks does not implement nsIPrompt");
+    NS_ASSERTION(prompt, "callbacks does not implement nsIPrompt");
   }
 
   if (!prompt)
     return;
 
   if (PK11_ProtectedAuthenticationPath(mSlot)) {
     mResult = ShowProtectedAuthPrompt(mSlot, mIR);
     return;
@@ -769,19 +770,19 @@ void PK11PasswordPromptRunnable::RunOnTa
     mResult = ToNewUTF8String(nsDependentString(password));
     NS_Free(password);
   }
 }
 
 char*
 PK11PasswordPrompt(PK11SlotInfo* slot, PRBool retry, void* arg)
 {
-  nsRefPtr<PK11PasswordPromptRunnable> runnable = 
+  RefPtr<PK11PasswordPromptRunnable> runnable(
     new PK11PasswordPromptRunnable(slot,
-                                   static_cast<nsIInterfaceRequestor*>(arg));
+                                   static_cast<nsIInterfaceRequestor*>(arg)));
   runnable->DispatchToMainThreadAndWait();
   return runnable->mResult;
 }
 
 void HandshakeCallback(PRFileDesc* fd, void* client_data) {
   nsNSSShutDownPreventionLock locker;
   int32_t sslStatus;
   char* signer = nullptr;
@@ -865,28 +866,28 @@ void HandshakeCallback(PRFileDesc* fd, v
 
     nsMemory::Free(const_cast<PRUnichar*>(formatStrings[0]));
 
     nsNSSSocketInfo* infoObject = (nsNSSSocketInfo*) fd->higher->secret;
     infoObject->SetSecurityState(secStatus);
     infoObject->SetShortSecurityDescription(shortDesc.get());
 
     /* Set the SSL Status information */
-    nsRefPtr<nsSSLStatus> status = infoObject->SSLStatus();
+    RefPtr<nsSSLStatus> status(infoObject->SSLStatus());
     if (!status) {
       status = new nsSSLStatus();
       infoObject->SetSSLStatus(status);
     }
 
     RememberCertErrorsTable::GetInstance().LookupCertErrorBits(infoObject,
                                                                status);
 
     CERTCertificate *serverCert = SSL_PeerCertificate(fd);
     if (serverCert) {
-      nsRefPtr<nsNSSCertificate> nssc = nsNSSCertificate::Create(serverCert);
+      RefPtr<nsNSSCertificate> nssc(nsNSSCertificate::Create(serverCert));
       CERT_DestroyCertificate(serverCert);
       serverCert = nullptr;
 
       nsCOMPtr<nsIX509Cert> prevcert;
       infoObject->GetPreviousCert(getter_AddRefs(prevcert));
 
       bool equals_previous = false;
       if (prevcert && nssc) {
--- a/security/manager/ssl/src/nsNSSCertHelper.cpp
+++ b/security/manager/ssl/src/nsNSSCertHelper.cpp
@@ -1,27 +1,30 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "prerror.h"
 #include "prprf.h"
 
+#include "mozilla/Scoped.h"
 #include "nsNSSCertHelper.h"
 #include "nsCOMPtr.h"
 #include "nsNSSCertificate.h"
 #include "cert.h"
 #include "keyhi.h"
 #include "secder.h"
 #include "nsNSSCertValidity.h"
 #include "nsNSSASN1Object.h"
 #include "nsNSSComponent.h"
 #include "nsNSSCertTrust.h"
 #include "nsIDateTimeFormat.h"
 #include "nsDateTimeFormatCID.h"
+
+using namespace mozilla;
  
 static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
 
 /* Object Identifier constants */
 #define CONST_OID static const unsigned char
 #define MICROSOFT_OID 0x2b, 0x6, 0x1, 0x4, 0x1, 0x82, 0x37
 #define PKIX_OID 0x2b, 0x6, 0x01, 0x05, 0x05, 0x07
 CONST_OID msCertExtCerttype[]      = { MICROSOFT_OID, 20, 2};
@@ -81,18 +84,16 @@ GetIntValue(SECItem *versionItem,
 static nsresult
 ProcessVersion(SECItem         *versionItem,
                nsINSSComponent *nssComponent,
                nsIASN1PrintableItem **retItem)
 {
   nsresult rv;
   nsAutoString text;
   nsCOMPtr<nsIASN1PrintableItem> printableItem = new nsNSSASN1PrintableItem();
-  if (printableItem == nullptr)
-    return NS_ERROR_OUT_OF_MEMORY;
  
   nssComponent->GetPIPNSSBundleString("CertDumpVersion", text);
   rv = printableItem->SetDisplayName(text);
   if (NS_FAILED(rv))
     return rv;
 
   // Now to figure out what version this certificate is.
   unsigned long version;
@@ -138,30 +139,27 @@ static nsresult
 ProcessSerialNumberDER(SECItem         *serialItem, 
                        nsINSSComponent *nssComponent,
                        nsIASN1PrintableItem **retItem)
 {
   nsresult rv;
   nsAutoString text;
   nsCOMPtr<nsIASN1PrintableItem> printableItem = new nsNSSASN1PrintableItem();
 
-  if (printableItem == nullptr)
-    return NS_ERROR_OUT_OF_MEMORY;
-
   rv = nssComponent->GetPIPNSSBundleString("CertDumpSerialNo", text); 
   if (NS_FAILED(rv))
     return rv;
 
   rv = printableItem->SetDisplayName(text);
   if (NS_FAILED(rv))
     return rv;
 
   nsXPIDLCString serialNumber;
   serialNumber.Adopt(CERT_Hexify(serialItem, 1));
-  if (serialNumber == nullptr)
+  if (!serialNumber)
     return NS_ERROR_OUT_OF_MEMORY;
 
   rv = printableItem->SetDisplayValue(NS_ConvertASCIItoUTF16(serialNumber));
   *retItem = printableItem;
   NS_ADDREF(*retItem);
   return rv;
 }
 
@@ -826,27 +824,27 @@ ProcessBasicConstraints(SECItem  *extDat
 }
 
 static nsresult
 ProcessExtKeyUsage(SECItem  *extData, 
                    nsAString &text,
                    nsINSSComponent *nssComponent)
 {
   nsAutoString local;
-  CERTOidSequence *extKeyUsage = NULL;
+  CERTOidSequence *extKeyUsage = nullptr;
   SECItem **oids;
   SECItem *oid;
   nsresult rv;
   
   extKeyUsage = CERT_DecodeOidSequence(extData);
-  if (extKeyUsage == NULL)
+  if (!extKeyUsage)
     return NS_ERROR_FAILURE;
 
   oids = extKeyUsage->oids;
-  while (oids != NULL && *oids != NULL) {
+  while (oids && *oids) {
     // For each OID, try to find a bundle string
     // of the form CertDumpEKU_<underlined-OID>
     nsAutoString oidname;
     oid = *oids;
     rv = GetDefaultOIDFormat(oid, nssComponent, oidname, '_');
     if (NS_FAILED(rv))
       return rv;
     nsAutoString bundlekey = NS_LITERAL_STRING("CertDumpEKU_")+ oidname;
@@ -896,22 +894,17 @@ ProcessRDN(CERTRDN* rdn, nsAString &fina
     decodeItem = CERT_DecodeAVAValue(&ava->value);
     if(!decodeItem) {
       return NS_ERROR_FAILURE;
     }
 
     // We know we can fit buffer of this length. CERT_RFC1485_EscapeAndQuote
     // will fail if we provide smaller buffer then the result can fit to.
     int escapedValueCapacity = decodeItem->len * 3 + 3;
-    nsAutoArrayPtr<char> escapedValue;
-    escapedValue = new char[escapedValueCapacity];
-    if (!escapedValue) {
-      SECITEM_FreeItem(decodeItem, true);
-      return NS_ERROR_OUT_OF_MEMORY;
-    }
+    ScopedDeleteArray<char> escapedValue(new char[escapedValueCapacity]);
 
     SECStatus status = CERT_RFC1485_EscapeAndQuote(
           escapedValue.get(),
           escapedValueCapacity, 
           (char*)decodeItem->data, 
           decodeItem->len);
     if (SECSuccess != status) {
       SECITEM_FreeItem(decodeItem, true);
@@ -1277,26 +1270,26 @@ ProcessAuthKeyId(SECItem  *extData,
   return rv;
 }
 
 static nsresult
 ProcessUserNotice(SECItem *der_notice,
 		  nsAString &text,
 		  nsINSSComponent *nssComponent)
 {
-  CERTUserNotice *notice = NULL;
+  CERTUserNotice *notice = nullptr;
   SECItem **itemList;
   PLArenaPool *arena;
 
   arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   if (!arena)
     return NS_ERROR_FAILURE;
 
   notice = CERT_DecodeUserNotice(der_notice);
-  if (notice == NULL) {
+  if (!notice) {
     ProcessRawBytes(nssComponent, der_notice, text);
     goto finish;
   }
 
   if (notice->noticeReference.organization.len != 0) {
     switch (notice->noticeReference.organization.type) {
     case siAsciiString:
     case siVisibleString:
@@ -1359,21 +1352,21 @@ ProcessCertificatePolicies(SECItem  *ext
 {
   CERTCertificatePolicies *policies;
   CERTPolicyInfo **policyInfos, *policyInfo;
   CERTPolicyQualifier **policyQualifiers, *policyQualifier;
   nsAutoString local;
   nsresult rv = NS_OK;
 
   policies = CERT_DecodeCertificatePoliciesExtension(extData);
-  if ( policies == NULL )
+  if (!policies)
     return NS_ERROR_FAILURE;
 
   policyInfos = policies->policyInfos;
-  while (*policyInfos != NULL ) {
+  while (*policyInfos) {
     policyInfo = *policyInfos++;
     switch (policyInfo->oid) {
     case SEC_OID_VERISIGN_USER_NOTICES:
       nssComponent->GetPIPNSSBundleString("CertDumpVerisignNotices", local);
       text.Append(local);
       break;
     default:
       GetDefaultOIDFormat(&policyInfo->policyID, nssComponent, local, '.');
@@ -1396,17 +1389,17 @@ ProcessCertificatePolicies(SECItem  *ext
     }
 
     if (policyInfo->policyQualifiers) {
       /* Add all qualifiers on separate lines, indented */
       policyQualifiers = policyInfo->policyQualifiers;
       if (needColon)
         text.Append(NS_LITERAL_STRING(":"));
       text.Append(NS_LITERAL_STRING(SEPARATOR));
-      while (*policyQualifiers != NULL) {
+      while (*policyQualifiers) {
 	text.Append(NS_LITERAL_STRING("  "));
 	policyQualifier = *policyQualifiers++;
 	switch(policyQualifier->oid) {
 	case SEC_OID_PKIX_CPS_POINTER_QUALIFIER:
 	  nssComponent->GetPIPNSSBundleString("CertDumpCPSPointer", local);
 	  text.Append(local);
 	  text.Append(NS_LITERAL_STRING(":"));
 	  text.Append(NS_LITERAL_STRING(SEPARATOR));
@@ -1546,20 +1539,20 @@ ProcessAuthInfoAccess(SECItem  *extData,
   nsresult rv = NS_OK;
   nsAutoString local;
 
   arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   if (!arena)
     return NS_ERROR_FAILURE;
 
   aia = CERT_DecodeAuthInfoAccessExtension(arena, extData);
-  if (aia == NULL)
+  if (!aia)
     goto finish;
 
-  while (*aia != NULL) {
+  while (*aia) {
     desc = *aia++;
     switch (SECOID_FindOIDTag(&desc->method)) {
     case SEC_OID_PKIX_OCSP:
       nssComponent->GetPIPNSSBundleString("CertDumpOCSPResponder", local);
       break;
     case SEC_OID_PKIX_CA_ISSUERS:
       nssComponent->GetPIPNSSBundleString("CertDumpCAIssuers", local);
       break;
@@ -1680,23 +1673,21 @@ static nsresult
 ProcessSingleExtension(CERTCertExtension *extension,
                        SECOidTag ev_oid_tag, // SEC_OID_UNKNOWN means: not EV
                        nsINSSComponent *nssComponent,
                        nsIASN1PrintableItem **retExtension)
 {
   nsAutoString text, extvalue;
   GetOIDText(&extension->id, nssComponent, text);
   nsCOMPtr<nsIASN1PrintableItem>extensionItem = new nsNSSASN1PrintableItem();
-  if (extensionItem == nullptr)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   extensionItem->SetDisplayName(text);
   SECOidTag oidTag = SECOID_FindOIDTag(&extension->id);
   text.Truncate();
-  if (extension->critical.data != nullptr) {
+  if (extension->critical.data) {
     if (extension->critical.data[0]) {
       nssComponent->GetPIPNSSBundleString("CertDumpCritical", text);
     } else {
       nssComponent->GetPIPNSSBundleString("CertDumpNonCritical", text);
     }
   } else {
     nssComponent->GetPIPNSSBundleString("CertDumpNonCritical", text);
   }
@@ -1716,42 +1707,36 @@ ProcessSingleExtension(CERTCertExtension
 }
 
 static nsresult
 ProcessSECAlgorithmID(SECAlgorithmID *algID,
                       nsINSSComponent *nssComponent,
                       nsIASN1Sequence **retSequence)
 {
   SECOidTag algOIDTag = SECOID_FindOIDTag(&algID->algorithm);
-  SECItem paramsOID = { siBuffer, NULL, 0 };
+  SECItem paramsOID = { siBuffer, nullptr, 0 };
   nsCOMPtr<nsIASN1Sequence> sequence = new nsNSSASN1Sequence();
-  if (sequence == nullptr)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   *retSequence = nullptr;
   nsString text;
   GetOIDText(&algID->algorithm, nssComponent, text);
   if (!algID->parameters.len || algID->parameters.data[0] == nsIASN1Object::ASN1_NULL) {
     sequence->SetDisplayValue(text);
     sequence->SetIsValidContainer(false);
   } else {
     nsCOMPtr<nsIASN1PrintableItem> printableItem = new nsNSSASN1PrintableItem();
-    if (printableItem == nullptr)
-      return NS_ERROR_OUT_OF_MEMORY;
 
     printableItem->SetDisplayValue(text);
     nsCOMPtr<nsIMutableArray> asn1Objects;
     sequence->GetASN1Objects(getter_AddRefs(asn1Objects));
     asn1Objects->AppendElement(printableItem, false);
     nssComponent->GetPIPNSSBundleString("CertDumpAlgID", text);
     printableItem->SetDisplayName(text);
 
     printableItem = new nsNSSASN1PrintableItem();
-    if (printableItem == nullptr)
-      return NS_ERROR_OUT_OF_MEMORY;
 
     asn1Objects->AppendElement(printableItem, false);
     nssComponent->GetPIPNSSBundleString("CertDumpParams", text);
     printableItem->SetDisplayName(text);
     if ((algOIDTag == SEC_OID_ANSIX962_EC_PUBLIC_KEY) &&
         (algID->parameters.len > 2) && 
         (algID->parameters.data[0] == nsIASN1Object::ASN1_OBJECT_ID)) {
        paramsOID.len = algID->parameters.len - 2;
@@ -1794,61 +1779,54 @@ ProcessTime(PRTime dispTime, const PRUni
 
   dateFormatter->FormatPRExplodedTime(nullptr, kDateFormatShort, kTimeFormatSecondsForce24Hour,
                               &explodedTimeGMT, tempString);
 
   text.Append(tempString);
   text.Append(NS_LITERAL_STRING(" GMT)"));
 
   nsCOMPtr<nsIASN1PrintableItem> printableItem = new nsNSSASN1PrintableItem();
-  if (printableItem == nullptr)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   printableItem->SetDisplayValue(text);
   printableItem->SetDisplayName(nsDependentString(displayName));
   nsCOMPtr<nsIMutableArray> asn1Objects;
   parentSequence->GetASN1Objects(getter_AddRefs(asn1Objects));
   asn1Objects->AppendElement(printableItem, false);
   return NS_OK;
 }
 
 static nsresult
 ProcessSubjectPublicKeyInfo(CERTSubjectPublicKeyInfo *spki, 
                             nsIASN1Sequence *parentSequence,
                             nsINSSComponent *nssComponent)
 {
   nsCOMPtr<nsIASN1Sequence> spkiSequence = new nsNSSASN1Sequence();
 
-  if (spkiSequence == nullptr)
-    return NS_ERROR_OUT_OF_MEMORY;
-
   nsString text;
   nssComponent->GetPIPNSSBundleString("CertDumpSPKI", text);
   spkiSequence->SetDisplayName(text);
 
   nssComponent->GetPIPNSSBundleString("CertDumpSPKIAlg", text);
   nsCOMPtr<nsIASN1Sequence> sequenceItem;
   nsresult rv = ProcessSECAlgorithmID(&spki->algorithm, nssComponent,
                                       getter_AddRefs(sequenceItem));
   if (NS_FAILED(rv))
     return rv;
   sequenceItem->SetDisplayName(text);
   nsCOMPtr<nsIMutableArray> asn1Objects;
   spkiSequence->GetASN1Objects(getter_AddRefs(asn1Objects));
   asn1Objects->AppendElement(sequenceItem, false);
 
   nsCOMPtr<nsIASN1PrintableItem> printableItem = new nsNSSASN1PrintableItem();
-  if (printableItem == nullptr)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   text.Truncate();
  
   SECKEYPublicKey *key = SECKEY_ExtractPublicKey(spki);
   bool displayed = false;
-  if (key != NULL) {
+  if (key) {
       switch (key->keyType) {
       case rsaKey: {
          displayed = true;
          nsAutoString length1, length2, data1, data2;
          length1.AppendInt(key->u.rsa.modulus.len * 8);
          length2.AppendInt(key->u.rsa.publicExponent.len * 8);
          ProcessRawBytes(nssComponent, &key->u.rsa.modulus, data1, 
                          false);
@@ -1912,18 +1890,16 @@ ProcessSubjectPublicKeyInfo(CERTSubjectP
 
 static nsresult
 ProcessExtensions(CERTCertExtension **extensions, 
                   nsIASN1Sequence *parentSequence,
                   SECOidTag ev_oid_tag, // SEC_OID_UNKNOWN means: not EV
                   nsINSSComponent *nssComponent)
 {
   nsCOMPtr<nsIASN1Sequence> extensionSequence = new nsNSSASN1Sequence;
-  if (extensionSequence == nullptr)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   nsString text;
   nssComponent->GetPIPNSSBundleString("CertDumpExtensions", text);
   extensionSequence->SetDisplayName(text);
   int32_t i;
   nsresult rv;
   nsCOMPtr<nsIASN1PrintableItem> newExtension;
   nsCOMPtr<nsIMutableArray> asn1Objects;
@@ -1991,18 +1967,16 @@ nsNSSCertificate::CreateTBSCertificateAS
   //        extensions      [3]  EXPLICIT Extensions OPTIONAL
   //                            -- If present, version shall be v3
   //        }
   //
   // This is the ASN1 structure we should be dealing with at this point.
   // The code in this method will assert this is the structure we're dealing
   // and then add more user friendly text for that field.
   nsCOMPtr<nsIASN1Sequence> sequence = new nsNSSASN1Sequence();
-  if (sequence == nullptr)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   nsString text;
   nssComponent->GetPIPNSSBundleString("CertDumpCertificate", text);
   sequence->SetDisplayName(text);
   nsCOMPtr<nsIASN1PrintableItem> printableItem;
   
   nsCOMPtr<nsIMutableArray> asn1Objects;
   sequence->GetASN1Objects(getter_AddRefs(asn1Objects));
@@ -2030,18 +2004,16 @@ nsNSSCertificate::CreateTBSCertificateAS
   nssComponent->GetPIPNSSBundleString("CertDumpSigAlg", text);
   algID->SetDisplayName(text);
   asn1Objects->AppendElement(algID, false);
 
   nsXPIDLString value;
   ProcessName(&mCert->issuer, nssComponent, getter_Copies(value));
 
   printableItem = new nsNSSASN1PrintableItem();
-  if (printableItem == nullptr)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   printableItem->SetDisplayValue(value);
   nssComponent->GetPIPNSSBundleString("CertDumpIssuer", text);
   printableItem->SetDisplayName(text);
   asn1Objects->AppendElement(printableItem, false);
   
   nsCOMPtr<nsIASN1Sequence> validitySequence = new nsNSSASN1Sequence();
   nssComponent->GetPIPNSSBundleString("CertDumpValidity", text);
@@ -2062,43 +2034,39 @@ nsNSSCertificate::CreateTBSCertificateAS
   nssComponent->GetPIPNSSBundleString("CertDumpNotAfter", text);
   rv = ProcessTime(notAfter, text.get(), validitySequence);
   if (NS_FAILED(rv))
     return rv;
 
   nssComponent->GetPIPNSSBundleString("CertDumpSubject", text);
 
   printableItem = new nsNSSASN1PrintableItem();
-  if (printableItem == nullptr)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   printableItem->SetDisplayName(text);
   ProcessName(&mCert->subject, nssComponent,getter_Copies(value));
   printableItem->SetDisplayValue(value);
   asn1Objects->AppendElement(printableItem, false);
 
   rv = ProcessSubjectPublicKeyInfo(&mCert->subjectPublicKeyInfo, sequence,
                                    nssComponent); 
   if (NS_FAILED(rv))
     return rv;
  
   SECItem data; 
   // Is there an issuerUniqueID?
-  if (mCert->issuerID.data != nullptr) {
+  if (mCert->issuerID.data) {
     // The issuerID is encoded as a bit string.
     // The function ProcessRawBytes expects the
     // length to be in bytes, so let's convert the
     // length in a temporary SECItem
     data.data = mCert->issuerID.data;
     data.len  = (mCert->issuerID.len + 7) / 8;
 
     ProcessRawBytes(nssComponent, &data, text);
     printableItem = new nsNSSASN1PrintableItem();
-    if (printableItem == nullptr)
-      return NS_ERROR_OUT_OF_MEMORY;
 
     printableItem->SetDisplayValue(text);
     nssComponent->GetPIPNSSBundleString("CertDumpIssuerUniqueID", text);
     printableItem->SetDisplayName(text);
     asn1Objects->AppendElement(printableItem, false);
   }
 
   if (mCert->subjectID.data) {
@@ -2106,18 +2074,16 @@ nsNSSCertificate::CreateTBSCertificateAS
     // The function ProcessRawBytes expects the
     // length to be in bytes, so let's convert the
     // length in a temporary SECItem
     data.data = mCert->subjectID.data;
     data.len  = (mCert->subjectID.len + 7) / 8;
 
     ProcessRawBytes(nssComponent, &data, text);
     printableItem = new nsNSSASN1PrintableItem();
-    if (printableItem == nullptr)
-      return NS_ERROR_OUT_OF_MEMORY;
 
     printableItem->SetDisplayValue(text);
     nssComponent->GetPIPNSSBundleString("CertDumpSubjectUniqueID", text);
     printableItem->SetDisplayName(text);
     asn1Objects->AppendElement(printableItem, false);
 
   }
   if (mCert->extensions) {
@@ -2144,19 +2110,16 @@ nsNSSCertificate::CreateASN1Struct()
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   nsCOMPtr<nsIASN1Sequence> sequence = new nsNSSASN1Sequence();
 
   mASN1Structure = sequence; 
-  if (mASN1Structure == nullptr) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
 
   nsCOMPtr<nsIMutableArray> asn1Objects;
   sequence->GetASN1Objects(getter_AddRefs(asn1Objects));
   nsXPIDLCString title;
   GetWindowTitle(getter_Copies(title));
   
   mASN1Structure->SetDisplayName(NS_ConvertUTF8toUTF16(title));
   // This sequence will be contain the tbsCertificate, signatureAlgorithm,
@@ -2206,17 +2169,17 @@ getCertType(CERTCertificate *cert)
   if (cert->nickname && trust.HasAnyUser())
     return nsIX509Cert::USER_CERT;
   if (trust.HasAnyCA())
     return nsIX509Cert::CA_CERT;
   if (trust.HasPeer(true, false, false))
     return nsIX509Cert::SERVER_CERT;
   if (trust.HasPeer(false, true, false) && cert->emailAddr)
     return nsIX509Cert::EMAIL_CERT;
-  if (CERT_IsCACert(cert,NULL))
+  if (CERT_IsCACert(cert, nullptr))
     return nsIX509Cert::CA_CERT;
   if (cert->emailAddr)
     return nsIX509Cert::EMAIL_CERT;
   return nsIX509Cert::UNKNOWN_CERT;
 }
 
 CERTCertNicknames *
 getNSSCertNicknamesFromCertList(CERTCertList *certList)
--- a/security/manager/ssl/src/nsNSSCertificate.cpp
+++ b/security/manager/ssl/src/nsNSSCertificate.cpp
@@ -33,31 +33,31 @@
 #include "nsCertVerificationThread.h"
 #include "nsIObjectOutputStream.h"
 #include "nsIObjectInputStream.h"
 #include "nsIProgrammingLanguage.h"
 
 #include "nsXULAppAPI.h"
 
 #include "nspr.h"
-extern "C" {
 #include "pk11func.h"
 #include "certdb.h"
 #include "cert.h"
 #include "secerr.h"
 #include "nssb64.h"
 #include "secasn1.h"
 #include "secder.h"
-}
 #include "ssl.h"
 #include "ocsp.h"
 #include "plbase64.h"
 #include "cms.h"
 #include "cert.h"
 
+using namespace mozilla;
+
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gPIPNSSLog;
 #endif
 
 static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
 
 NSSCleanupAutoPtrClass(CERTCertificateList, CERT_DestroyCertificateList)
 NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate)
@@ -122,17 +122,17 @@ nsNSSCertificate::InitFromDER(char *cert
   if (!certDER || !derLen)
     return false;
 
   CERTCertificate *aCert = CERT_DecodeCertFromPackage(certDER, derLen);
   
   if (!aCert)
     return false;
 
-  if(aCert->dbhandle == nullptr)
+  if (!aCert->dbhandle)
   {
     aCert->dbhandle = CERT_GetDefaultCertDB();
   }
 
   mCert = aCert;
   return true;
 }
 
@@ -253,17 +253,17 @@ nsNSSCertificate::MarkForPermDeletion()
 
 nsresult
 GetKeyUsagesString(CERTCertificate *cert, nsINSSComponent *nssComponent, 
                    nsString &text)
 {
   text.Truncate();
 
   SECItem keyUsageItem;
-  keyUsageItem.data = NULL;
+  keyUsageItem.data = nullptr;
 
   SECStatus srv;
 
   /* There is no extension, v1 or v2 certificate */
   if (!cert->extensions)
     return NS_OK;
 
 
@@ -817,17 +817,17 @@ nsNSSCertificate::GetChain(nsIArray **_r
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   NS_ENSURE_ARG(_rvChain);
   nsresult rv;
   /* Get the cert chain from NSS */
-  CERTCertList *nssChain = NULL;
+  CERTCertList *nssChain = nullptr;
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting chain for \"%s\"\n", mCert->nickname));
   nssChain = CERT_GetCertChainFromCert(mCert, PR_Now(), certUsageSSLClient);
   if (!nssChain)
     return NS_ERROR_FAILURE;
   /* enumerate the chain for scripting purposes */
   nsCOMPtr<nsIMutableArray> array =
     do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
   if (NS_FAILED(rv)) { 
@@ -855,23 +855,23 @@ nsNSSCertificate::GetAllTokenNames(uint3
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   NS_ENSURE_ARG(aLength);
   NS_ENSURE_ARG(aTokenNames);
   *aLength = 0;
-  *aTokenNames = NULL;
+  *aTokenNames = nullptr;
 
   /* Get the slots from NSS */
-  PK11SlotList *slots = NULL;
+  PK11SlotList *slots = nullptr;
   PK11SlotListCleaner slotCleaner(slots);
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting slots for \"%s\"\n", mCert->nickname));
-  slots = PK11_GetAllSlotsForCert(mCert, NULL);
+  slots = PK11_GetAllSlotsForCert(mCert, nullptr);
   if (!slots) {
     if (PORT_GetError() == SEC_ERROR_NO_TOKEN)
       return NS_OK; // List of slots is empty, return empty array
     else
       return NS_ERROR_FAILURE;
   }
 
   /* read the token names from slots */
@@ -889,17 +889,17 @@ nsNSSCertificate::GetAllTokenNames(uint3
 
   uint32_t iToken;
   for (le = slots->head, iToken = 0; le; le = le->next, ++iToken) {
     char *token = PK11_GetTokenName(le->slot);
     (*aTokenNames)[iToken] = ToNewUnicode(NS_ConvertUTF8toUTF16(token));
     if (!(*aTokenNames)[iToken]) {
       NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(iToken, *aTokenNames);
       *aLength = 0;
-      *aTokenNames = NULL;
+      *aTokenNames = nullptr;
       return NS_ERROR_OUT_OF_MEMORY;
     }
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -1196,18 +1196,16 @@ NS_IMETHODIMP
 nsNSSCertificate::GetValidity(nsIX509CertValidity **aValidity)
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   NS_ENSURE_ARG(aValidity);
   nsX509CertValidity *validity = new nsX509CertValidity(mCert);
-  if (nullptr == validity)
-   return  NS_ERROR_OUT_OF_MEMORY; 
 
   NS_ADDREF(validity);
   *aValidity = static_cast<nsIX509CertValidity*>(validity);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNSSCertificate::VerifyForUsage(uint32_t usage, uint32_t *verificationResult)
@@ -1217,17 +1215,17 @@ nsNSSCertificate::VerifyForUsage(uint32_
     return NS_ERROR_NOT_AVAILABLE;
 
   NS_ENSURE_ARG(verificationResult);
 
   nsresult nsrv;
   nsCOMPtr<nsINSSComponent> inss = do_GetService(kNSSComponentCID, &nsrv);
   if (!inss)
     return nsrv;
-  nsRefPtr<nsCERTValInParamWrapper> survivingParams;
+  RefPtr<nsCERTValInParamWrapper> survivingParams;
   nsrv = inss->GetDefaultCERTValInParam(survivingParams);
   if (NS_FAILED(nsrv))
     return nsrv;
   
   SECCertificateUsage nss_usage;
   
   switch (usage)
   {
@@ -1282,24 +1280,24 @@ nsNSSCertificate::VerifyForUsage(uint32_
     default:
       return NS_ERROR_FAILURE;
   }
 
   SECStatus verify_result;
   if (!nsNSSComponent::globalConstFlagUsePKIXVerification) {
     CERTCertDBHandle *defaultcertdb = CERT_GetDefaultCertDB();
     verify_result = CERT_VerifyCertificateNow(defaultcertdb, mCert, true, 
-                                              nss_usage, NULL, NULL);
+                                              nss_usage, nullptr, nullptr);
   }
   else {
     CERTValOutParam cvout[1];
     cvout[0].type = cert_po_end;
     verify_result = CERT_PKIXVerifyCert(mCert, nss_usage,
                                         survivingParams->GetRawPointerForNSS(),
-                                        cvout, NULL);
+                                        cvout, nullptr);
   }
   
   if (verify_result == SECSuccess)
   {
     *verificationResult = VERIFIED_OK;
   }
   else
   {
@@ -1390,18 +1388,16 @@ nsNSSCertificate::GetUsagesArray(bool lo
 
 NS_IMETHODIMP
 nsNSSCertificate::RequestUsagesArrayAsync(nsICertVerificationListener *aResultListener)
 {
   if (!aResultListener)
     return NS_ERROR_FAILURE;
   
   nsCertVerificationJob *job = new nsCertVerificationJob;
-  if (!job)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   job->mCert = this;
   job->mListener = aResultListener;
 
   nsresult rv = nsCertVerificationThread::addJob(job);
   if (NS_FAILED(rv))
     delete job;
 
@@ -1476,17 +1472,17 @@ DumpASN1Object(nsIASN1Object *object, un
 
 /* readonly attribute nsIASN1Object ASN1Structure; */
 NS_IMETHODIMP 
 nsNSSCertificate::GetASN1Structure(nsIASN1Object * *aASN1Structure)
 {
   nsNSSShutDownPreventionLock locker;
   nsresult rv = NS_OK;
   NS_ENSURE_ARG_POINTER(aASN1Structure);
-  if (mASN1Structure == nullptr) {
+  if (!mASN1Structure) {
     // First create the recursive structure os ASN1Objects
     // which tells us the layout of the cert.
     rv = CreateASN1Struct();
     if (NS_FAILED(rv)) {
       return rv;
     }
 #ifdef DEBUG_javi
     DumpASN1Object(mASN1Structure, 0);
@@ -1568,17 +1564,17 @@ char* nsNSSCertificate::defaultServerNic
   count = 1;
   while (1) {
     if (count == 1) {
       nickname = PR_smprintf("%s", servername);
     }
     else {
       nickname = PR_smprintf("%s #%d", servername, count);
     }
-    if (nickname == NULL) {
+    if (!nickname) {
       break;
     }
 
     conflict = SEC_CertNicknameConflict(nickname, &cert->derSubject,
                                         cert->dbhandle);
     if (!conflict) {
       break;
     }
@@ -1616,22 +1612,22 @@ NS_IMETHODIMP
 nsNSSCertList::AddCert(nsIX509Cert *aCert) 
 {
   /* This should be a query interface, but currently this his how the
    * rest of PSM is working */
   nsCOMPtr<nsIX509Cert2> nssCert = do_QueryInterface(aCert);
   CERTCertificate *cert;
 
   cert = nssCert->GetCert();
-  if (cert == nullptr) {
+  if (!cert) {
     NS_ERROR("Somehow got nullptr for mCertificate in nsNSSCertificate.");
     return NS_ERROR_FAILURE;
   }
 
-  if (mCertList == nullptr) {
+  if (!mCertList) {
     NS_ERROR("Somehow got nullptr for mCertList in nsNSSCertList.");
     return NS_ERROR_FAILURE;
   }
   CERT_AddCertToListTail(mCertList,cert);
   return NS_OK;
 }
 
 /* void deleteCert (in nsIX509Cert cert); */
@@ -1639,22 +1635,22 @@ NS_IMETHODIMP
 nsNSSCertList::DeleteCert(nsIX509Cert *aCert)
 {
   /* This should be a query interface, but currently this his how the
    * rest of PSM is working */
   nsCOMPtr<nsIX509Cert2> nssCert = do_QueryInterface(aCert);
   CERTCertificate *cert = nssCert->GetCert();
   CERTCertListNode *node;
 
-  if (cert == nullptr) {
+  if (!cert) {
     NS_ERROR("Somehow got nullptr for mCertificate in nsNSSCertificate.");
     return NS_ERROR_FAILURE;
   }
 
-  if (mCertList == nullptr) {
+  if (!mCertList) {
     NS_ERROR("Somehow got nullptr for mCertList in nsNSSCertList.");
     return NS_ERROR_FAILURE;
   }
 
   for (node = CERT_LIST_HEAD(mCertList); !CERT_LIST_END(node,mCertList);
                                              node = CERT_LIST_NEXT(node)) {
     if (node->cert == cert) {
 	CERT_RemoveCertListNode(node);
@@ -1667,17 +1663,17 @@ nsNSSCertList::DeleteCert(nsIX509Cert *a
 CERTCertList *
 nsNSSCertList::DupCertList(CERTCertList *aCertList)
 {
   if (!aCertList)
     return nullptr;
 
   CERTCertList *newList = CERT_NewCertList();
 
-  if (newList == nullptr) {
+  if (!newList) {
     return nullptr;
   }
 
   CERTCertListNode *node;
   for (node = CERT_LIST_HEAD(aCertList); !CERT_LIST_END(node, aCertList);
                                               node = CERT_LIST_NEXT(node)) {
     CERTCertificate *cert = CERT_DupCertificate(node->cert);
     CERT_AddCertToListTail(newList, cert);
@@ -1691,19 +1687,16 @@ nsNSSCertList::GetRawCertList()
   return mCertList;
 }
 
 /* nsISimpleEnumerator getEnumerator (); */
 NS_IMETHODIMP
 nsNSSCertList::GetEnumerator(nsISimpleEnumerator **_retval) 
 {
   nsCOMPtr<nsISimpleEnumerator> enumerator = new nsNSSCertListEnumerator(mCertList);
-  if (!enumerator) { 
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
 
   *_retval = enumerator;
   NS_ADDREF(*_retval);
   return NS_OK;
 }
 
 NS_IMPL_THREADSAFE_ISUPPORTS1(nsNSSCertListEnumerator, 
                               nsISimpleEnumerator)
--- a/security/manager/ssl/src/nsNSSCertificate.h
+++ b/security/manager/ssl/src/nsNSSCertificate.h
@@ -9,16 +9,17 @@
 #include "nsIX509Cert.h"
 #include "nsIX509Cert2.h"
 #include "nsIX509Cert3.h"
 #include "nsIX509CertDB.h"
 #include "nsIX509CertList.h"
 #include "nsIASN1Object.h"
 #include "nsISMimeCert.h"
 #include "nsIIdentityInfo.h"
+#include "nsCOMPtr.h"
 #include "nsNSSShutDown.h"
 #include "nsISimpleEnumerator.h"
 #include "nsISerializable.h"
 #include "nsIClassInfo.h"
 
 #include "nsNSSCertHeader.h"
 
 class nsINSSComponent;
--- a/security/manager/ssl/src/nsNSSCertificateDB.cpp
+++ b/security/manager/ssl/src/nsNSSCertificateDB.cpp
@@ -22,34 +22,35 @@
 #include "nsNSSShutDown.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsComponentManagerUtils.h"
 #include "nsIPrompt.h"
 #include "nsThreadUtils.h"
 
 #include "nspr.h"
-extern "C" {
 #include "pk11func.h"
 #include "certdb.h"
 #include "cert.h"
 #include "secerr.h"
 #include "nssb64.h"
 #include "secasn1.h"
 #include "secder.h"
-}
 #include "ssl.h"
 #include "ocsp.h"
 #include "plbase64.h"
 
+#include "nsNSSCleaner.h"
+
+using namespace mozilla;
+
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gPIPNSSLog;
 #endif
 
-#include "nsNSSCleaner.h"
 NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate)
 NSSCleanupAutoPtrClass(CERTCertList, CERT_DestroyCertList)
 NSSCleanupAutoPtrClass(CERTCertificateList, CERT_DestroyCertificateList)
 NSSCleanupAutoPtrClass(PK11SlotInfo, PK11_FreeSlot)
 
 static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
 
 
@@ -64,30 +65,30 @@ nsNSSCertificateDB::~nsNSSCertificateDB(
 }
 
 NS_IMETHODIMP
 nsNSSCertificateDB::FindCertByNickname(nsISupports *aToken,
                                       const nsAString &nickname,
                                       nsIX509Cert **_rvCert)
 {
   nsNSSShutDownPreventionLock locker;
-  CERTCertificate *cert = NULL;
-  char *asciiname = NULL;
+  CERTCertificate *cert = nullptr;
+  char *asciiname = nullptr;
   NS_ConvertUTF16toUTF8 aUtf8Nickname(nickname);
   asciiname = const_cast<char*>(aUtf8Nickname.get());
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting \"%s\"\n", asciiname));
 #if 0
   // what it should be, but for now...
   if (aToken) {
-    cert = PK11_FindCertFromNickname(asciiname, NULL);
+    cert = PK11_FindCertFromNickname(asciiname, nullptr);
   } else {
     cert = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), asciiname);
   }
 #endif
-  cert = PK11_FindCertFromNickname(asciiname, NULL);
+  cert = PK11_FindCertFromNickname(asciiname, nullptr);
   if (!cert) {
     cert = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), asciiname);
   }
   if (cert) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("got it\n"));
     nsCOMPtr<nsIX509Cert> pCert = nsNSSCertificate::Create(cert);
     CERT_DestroyCertificate(cert);
     if (pCert) {
@@ -138,17 +139,17 @@ nsNSSCertificateDB::FindCertByDBKey(cons
   issuerSN.derIssuer.data= &keyItem.data[NS_NSS_LONG*4+
                                               issuerSN.serialNumber.len];
 
   cert = CERT_FindCertByIssuerAndSN(CERT_GetDefaultCertDB(), &issuerSN);
   PR_FREEIF(keyItem.data);
   if (cert) {
     nsNSSCertificate *nssCert = nsNSSCertificate::Create(cert);
     CERT_DestroyCertificate(cert);
-    if (nssCert == nullptr)
+    if (!nssCert)
       return NS_ERROR_OUT_OF_MEMORY;
     NS_ADDREF(nssCert);
     *_cert = static_cast<nsIX509Cert*>(nssCert);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP 
@@ -157,27 +158,27 @@ nsNSSCertificateDB::FindCertNicknames(ns
                                      uint32_t     *_count,
                                      PRUnichar  ***_certNames)
 {
   nsNSSShutDownPreventionLock locker;
   nsresult rv = NS_ERROR_FAILURE;
   /*
    * obtain the cert list from NSS
    */
-  CERTCertList *certList = NULL;
+  CERTCertList *certList = nullptr;
   PK11CertListType pk11type;
 #if 0
   // this would seem right, but it didn't work...
   // oh, I know why - bonks out on internal slot certs
   if (aType == nsIX509Cert::USER_CERT)
     pk11type = PK11CertListUser;
   else 
 #endif
     pk11type = PK11CertListUnique;
-  certList = PK11_ListCerts(pk11type, NULL);
+  certList = PK11_ListCerts(pk11type, nullptr);
   if (!certList)
     goto cleanup;
   /*
    * get list of cert names from list of certs
    * XXX also cull the list (NSS only distinguishes based on user/non-user
    */
   getCertNames(certList, aType, _count, _certNames);
   rv = NS_OK;
@@ -197,17 +198,17 @@ collect_certs(void *arg, SECItem **certs
   SECItem *cert;
   SECStatus rv;
 
   collectArgs = (CERTDERCerts *)arg;
 
   collectArgs->numcerts = numcerts;
   collectArgs->rawCerts = (SECItem *) PORT_ArenaZAlloc(collectArgs->arena,
                                            sizeof(SECItem) * numcerts);
-  if ( collectArgs->rawCerts == NULL )
+  if (!collectArgs->rawCerts)
     return(SECFailure);
 
   cert = collectArgs->rawCerts;
 
   while ( numcerts-- ) {
     rv = SECITEM_CopyItem(collectArgs->arena, cert, *certs);
     if ( rv == SECFailure )
       return(SECFailure);
@@ -220,17 +221,17 @@ collect_certs(void *arg, SECItem **certs
 
 CERTDERCerts*
 nsNSSCertificateDB::getCertsFromPackage(PLArenaPool *arena, uint8_t *data, 
                                         uint32_t length)
 {
   nsNSSShutDownPreventionLock locker;
   CERTDERCerts *collectArgs = 
                (CERTDERCerts *)PORT_ArenaZAlloc(arena, sizeof(CERTDERCerts));
-  if ( collectArgs == nullptr ) 
+  if (!collectArgs)
     return nullptr;
 
   collectArgs->arena = arena;
   SECStatus sec_rv = CERT_DecodeCertPackage(reinterpret_cast<char *>(data), 
                                             length, collect_certs, 
                                             (void *)collectArgs);
   if (sec_rv != SECSuccess)
     return nullptr;
@@ -342,17 +343,17 @@ nsNSSCertificateDB::handleCACertDownload
   
   if (!tmpCert) {
     NS_ERROR("Couldn't create cert from DER blob");
     return NS_ERROR_FAILURE;
   }
 
   CERTCertificateCleaner tmpCertCleaner(tmpCert);
 
-  if (!CERT_IsCACert(tmpCert, NULL)) {
+  if (!CERT_IsCACert(tmpCert, nullptr)) {
     DisplayCertificateAlert(ctx, "NotACACert", certToShow);
     return NS_ERROR_FAILURE;
   }
 
   if (tmpCert->isperm) {
     DisplayCertificateAlert(ctx, "CaCertExists", certToShow);
     return NS_ERROR_FAILURE;
   }
@@ -384,17 +385,17 @@ nsNSSCertificateDB::handleCACertDownload
 
   if (srv != SECSuccess)
     return NS_ERROR_FAILURE;
 
   // Import additional delivered certificates that can be verified.
 
   // build a CertList for filtering
   CERTCertList *certList = CERT_NewCertList();
-  if (certList == NULL) {
+  if (!certList) {
     return NS_ERROR_FAILURE;
   }
 
   CERTCertListCleaner listCleaner(certList);
 
   // get all remaining certs into temp store
 
   for (uint32_t i=0; i<numCerts; i++) {
@@ -488,32 +489,32 @@ NS_IMETHODIMP
 nsNSSCertificateDB::ImportEmailCertificate(uint8_t * data, uint32_t length, 
                                        nsIInterfaceRequestor *ctx)
 
 {
   nsNSSShutDownPreventionLock locker;
   SECStatus srv = SECFailure;
   nsresult nsrv = NS_OK;
   CERTCertDBHandle *certdb;
-  CERTCertificate **certArray = NULL;
-  CERTCertList *certList = NULL;
+  CERTCertificate **certArray = nullptr;
+  CERTCertList *certList = nullptr;
   CERTCertListNode *node;
   PRTime now;
   SECCertUsage certusage;
   SECCertificateUsage certificateusage;
   SECItem **rawArray;
   int numcerts;
   int i;
   CERTValOutParam cvout[1];
   cvout[0].type = cert_po_end;
 
   nsCOMPtr<nsINSSComponent> inss = do_GetService(kNSSComponentCID, &nsrv);
   if (!inss)
     return nsrv;
-  nsRefPtr<nsCERTValInParamWrapper> survivingParams;
+  RefPtr<nsCERTValInParamWrapper> survivingParams;
   nsrv = inss->GetDefaultCERTValInParam(survivingParams);
   if (NS_FAILED(nsrv))
     return nsrv;
  
   PLArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   if (!arena)
     return NS_ERROR_OUT_OF_MEMORY;
 
@@ -535,29 +536,29 @@ nsNSSCertificateDB::ImportEmailCertifica
     goto loser;
   }
 
   for (i=0; i < numcerts; i++) {
     rawArray[i] = &certCollection->rawCerts[i];
   }
 
   srv = CERT_ImportCerts(certdb, certusage, numcerts, rawArray, 
-                         &certArray, false, false, NULL);
+                         &certArray, false, false, nullptr);
 
   PORT_Free(rawArray);
-  rawArray = NULL;
+  rawArray = nullptr;
 
   if (srv != SECSuccess) {
     nsrv = NS_ERROR_FAILURE;
     goto loser;
   }
 
   // build a CertList for filtering
   certList = CERT_NewCertList();
-  if (certList == NULL) {
+  if (!certList) {
     nsrv = NS_ERROR_FAILURE;
     goto loser;
   }
   for (i=0; i < numcerts; i++) {
     CERTCertificate *cert = certArray[i];
     if (cert)
       cert = CERT_DupCertificate(cert);
     if (cert)
@@ -576,17 +577,17 @@ nsNSSCertificateDB::ImportEmailCertifica
     bool alert_and_skip = false;
 
     if (!node->cert) {
       continue;
     }
 
     if (!nsNSSComponent::globalConstFlagUsePKIXVerification) {
       if (CERT_VerifyCert(certdb, node->cert,
-          true, certusage, now, ctx, NULL) != SECSuccess) {
+          true, certusage, now, ctx, nullptr) != SECSuccess) {
         alert_and_skip = true;
       }
     }
     else {
       if (CERT_PKIXVerifyCert(node->cert, certificateusage,
                               survivingParams->GetRawPointerForNSS(),
                               cvout, ctx)
           != SECSuccess) {
@@ -618,19 +619,19 @@ nsNSSCertificateDB::ImportEmailCertifica
     rawArray = (SECItem **) PORT_Alloc(certChain->len * sizeof(SECItem *));
     if (!rawArray) {
       continue;
     }
     for (i=0; i < certChain->len; i++) {
       rawArray[i] = &certChain->certs[i];
     }
     CERT_ImportCerts(certdb, certusage, certChain->len, 
-                            rawArray,  NULL, true, false, NULL);
+                            rawArray,  nullptr, true, false, nullptr);
 
-    CERT_SaveSMimeProfile(node->cert, NULL, NULL);
+    CERT_SaveSMimeProfile(node->cert, nullptr, nullptr);
 
     PORT_Free(rawArray);
   }
 
 loser:
   if (certArray) {
     CERT_DestroyCertArray(certArray, numcerts);
   }
@@ -662,17 +663,17 @@ nsNSSCertificateDB::ImportServerCertific
     return NS_ERROR_OUT_OF_MEMORY;
 
   CERTDERCerts *certCollection = getCertsFromPackage(arena, data, length);
   if (!certCollection) {
     PORT_FreeArena(arena, false);
     return NS_ERROR_FAILURE;
   }
   cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(), certCollection->rawCerts,
-                          (char *)NULL, false, true);
+                                 nullptr, false, true);
   if (!cert) {
     nsrv = NS_ERROR_FAILURE;
     goto loser;
   }
   numcerts = certCollection->numcerts;
   rawCerts = (SECItem **) PORT_Alloc(sizeof(SECItem *) * numcerts);
   if ( !rawCerts ) {
     nsrv = NS_ERROR_FAILURE;
@@ -680,17 +681,17 @@ nsNSSCertificateDB::ImportServerCertific
   }
 
   for ( i = 0; i < numcerts; i++ ) {
     rawCerts[i] = &certCollection->rawCerts[i];
   }
 
   serverNickname = nsNSSCertificate::defaultServerNickname(cert);
   srv = CERT_ImportCerts(CERT_GetDefaultCertDB(), certUsageSSLServer,
-             numcerts, rawCerts, NULL, true, false,
+             numcerts, rawCerts, nullptr, true, false,
              serverNickname);
   PR_FREEIF(serverNickname);
   if ( srv != SECSuccess ) {
     nsrv = NS_ERROR_FAILURE;
     goto loser;
   }
 
   trust.SetValidServerPeer();
@@ -706,45 +707,45 @@ loser:
   if (arena) 
     PORT_FreeArena(arena, true);
   return nsrv;
 }
 
 nsresult
 nsNSSCertificateDB::ImportValidCACerts(int numCACerts, SECItem *CACerts, nsIInterfaceRequestor *ctx)
 {
-  CERTCertList *certList = NULL;
+  CERTCertList *certList = nullptr;
   SECItem **rawArray;
 
   // build a CertList for filtering
   certList = CERT_NewCertList();
-  if (certList == NULL) {
+  if (!certList) {
     return NS_ERROR_FAILURE;
   }
 
   CERTCertListCleaner listCleaner(certList);
 
   // get all certs into temp store
   SECStatus srv = SECFailure;
-  CERTCertificate **certArray = NULL;
+  CERTCertificate **certArray = nullptr;
 
   rawArray = (SECItem **) PORT_Alloc(sizeof(SECItem *) * numCACerts);
   if ( !rawArray ) {
     return NS_ERROR_FAILURE;
   }
 
   for (int i=0; i < numCACerts; i++) {
     rawArray[i] = &CACerts[i];
   }
 
   srv = CERT_ImportCerts(CERT_GetDefaultCertDB(), certUsageAnyCA, numCACerts, rawArray, 
-                         &certArray, false, true, NULL);
+                         &certArray, false, true, nullptr);
 
   PORT_Free(rawArray);
-  rawArray = NULL;
+  rawArray = nullptr;
 
   if (srv != SECSuccess) {
     return NS_ERROR_FAILURE;
   }
 
   for (int i2=0; i2 < numCACerts; i2++) {
     CERTCertificate *cacert = certArray[i2];
     if (cacert)
@@ -761,17 +762,17 @@ nsNSSCertificateDB::ImportValidCACerts(i
 nsresult
 nsNSSCertificateDB::ImportValidCACertsInList(CERTCertList *certList, nsIInterfaceRequestor *ctx)
 {
   SECItem **rawArray;
   nsresult nsrv;
   nsCOMPtr<nsINSSComponent> inss = do_GetService(kNSSComponentCID, &nsrv);
   if (!inss)
     return nsrv;
-  nsRefPtr<nsCERTValInParamWrapper> survivingParams;
+  RefPtr<nsCERTValInParamWrapper> survivingParams;
   nsrv = inss->GetDefaultCERTValInParam(survivingParams);
   if (NS_FAILED(nsrv))
     return nsrv;
 
   /* filter out the certs we don't want */
   SECStatus srv = CERT_FilterCertListByUsage(certList, certUsageAnyCA, true);
   if (srv != SECSuccess) {
     return NS_ERROR_FAILURE;
@@ -787,17 +788,17 @@ nsNSSCertificateDB::ImportValidCACertsIn
   for (node = CERT_LIST_HEAD(certList);
        !CERT_LIST_END(node,certList);
        node = CERT_LIST_NEXT(node)) {
 
     bool alert_and_skip = false;
 
     if (!nsNSSComponent::globalConstFlagUsePKIXVerification) {
       if (CERT_VerifyCert(CERT_GetDefaultCertDB(), node->cert, 
-          true, certUsageVerifyCA, PR_Now(), ctx, NULL) != SECSuccess) {
+          true, certUsageVerifyCA, PR_Now(), ctx, nullptr) != SECSuccess) {
         alert_and_skip = true;
       }
     }
     else {
       if (CERT_PKIXVerifyCert(node->cert, certificateUsageVerifyCA,
                               survivingParams->GetRawPointerForNSS(),
                               cvout, ctx)
           != SECSuccess) {
@@ -829,17 +830,17 @@ nsNSSCertificateDB::ImportValidCACertsIn
     rawArray = (SECItem **) PORT_Alloc(certChain->len * sizeof(SECItem *));
     if (!rawArray) {
       continue;
     }
     for (int i=0; i < certChain->len; i++) {
       rawArray[i] = &certChain->certs[i];
     }
     CERT_ImportCerts(CERT_GetDefaultCertDB(), certUsageAnyCA, certChain->len, 
-                            rawArray,  NULL, true, true, NULL);
+                            rawArray,  nullptr, true, true, nullptr);
 
     PORT_Free(rawArray);
   }
   
   return NS_OK;
 }
 
 void nsNSSCertificateDB::DisplayCertificateAlert(nsIInterfaceRequestor *ctx, 
@@ -888,36 +889,36 @@ nsNSSCertificateDB::ImportUserCertificat
   nsNSSShutDownPreventionLock locker;
   PK11SlotInfo *slot;
   nsAutoCString nickname;
   nsresult rv = NS_ERROR_FAILURE;
   int numCACerts;
   SECItem *CACerts;
   CERTDERCerts * collectArgs;
   PLArenaPool *arena;
-  CERTCertificate * cert=NULL;
+  CERTCertificate * cert = nullptr;
 
   arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
-  if ( arena == NULL ) {
+  if (!arena) {
     goto loser;
   }
 
   collectArgs = getCertsFromPackage(arena, data, length);
   if (!collectArgs) {
     goto loser;
   }
 
   cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(), collectArgs->rawCerts,
-                	       (char *)NULL, false, true);
+                                 nullptr, false, true);
   if (!cert) {
     goto loser;
   }
 
-  slot = PK11_KeyForCertExists(cert, NULL, ctx);
-  if ( slot == NULL ) {
+  slot = PK11_KeyForCertExists(cert, nullptr, ctx);
+  if (!slot) {
     nsCOMPtr<nsIX509Cert> certToShow = nsNSSCertificate::Create(cert);
     DisplayCertificateAlert(ctx, "UserCertIgnoredNoPrivateKey", certToShow);
     goto loser;
   }
   PK11_FreeSlot(slot);
 
   /* pick a nickname for the cert */
   if (cert->nickname) {
@@ -1130,18 +1131,16 @@ nsNSSCertificateDB::ImportCertsFromFile(
   if (!fd)
     return NS_ERROR_FAILURE;
 
   PRFileInfo file_info;
   if (PR_SUCCESS != PR_GetOpenFileInfo(fd, &file_info))
     return NS_ERROR_FAILURE;
   
   unsigned char *buf = new unsigned char[file_info.size];
-  if (!buf)
-    return NS_ERROR_OUT_OF_MEMORY;
   
   int32_t bytes_obtained = PR_Read(fd, buf, file_info.size);
   PR_Close(fd);
   
   if (bytes_obtained != file_info.size)
     rv = NS_ERROR_FAILURE;
   else {
 	  nsCOMPtr<nsIInterfaceRequestor> cxt = new PipUIContext();
@@ -1302,17 +1301,17 @@ void
 nsNSSCertificateDB::getCertNames(CERTCertList *certList,
                                  uint32_t      type, 
                                  uint32_t     *_count,
                                  PRUnichar  ***_certNames)
 {
   nsNSSShutDownPreventionLock locker;
   CERTCertListNode *node;
   uint32_t numcerts = 0, i=0;
-  PRUnichar **tmpArray = NULL;
+  PRUnichar **tmpArray = nullptr;
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("List of certs %d:\n", type));
   for (node = CERT_LIST_HEAD(certList);
        !CERT_LIST_END(node, certList);
        node = CERT_LIST_NEXT(node)) {
     if (getCertType(node->cert) == type) {
       numcerts++;
     }
   }
@@ -1320,18 +1319,18 @@ nsNSSCertificateDB::getCertNames(CERTCer
   int nc = (numcerts == 0) ? 1 : numcerts;
   tmpArray = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *) * nc);
   if (numcerts == 0) goto finish;
   for (node = CERT_LIST_HEAD(certList);
        !CERT_LIST_END(node, certList);
        node = CERT_LIST_NEXT(node)) {
     if (getCertType(node->cert) == type) {
       nsNSSCertificate pipCert(node->cert);
-      char *dbkey = NULL;
-      char *namestr = NULL;
+      char *dbkey = nullptr;
+      char *namestr = nullptr;
       nsAutoString certstr;
       pipCert.GetDbKey(&dbkey);
       nsAutoString keystr = NS_ConvertASCIItoUTF16(dbkey);
       PR_FREEIF(dbkey);
       if (type == nsIX509Cert::EMAIL_CERT) {
         namestr = node->cert->emailAddr;
       } else {
         namestr = node->cert->nickname;
@@ -1379,28 +1378,28 @@ nsNSSCertificateDB::FindEmailEncryptionC
   if (aNickname.IsEmpty())
     return NS_OK;
 
   nsNSSShutDownPreventionLock locker;
   nsresult rv = NS_OK;
   CERTCertificate *cert = 0;
   nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
   nsNSSCertificate *nssCert = nullptr;
-  char *asciiname = NULL;
+  char *asciiname = nullptr;
   NS_ConvertUTF16toUTF8 aUtf8Nickname(aNickname);
   asciiname = const_cast<char*>(aUtf8Nickname.get());
 
   /* Find a good cert in the user's database */
   cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(), asciiname, 
            certUsageEmailRecipient, true, ctx);
 
   if (!cert) { goto loser; }  
 
   nssCert = nsNSSCertificate::Create(cert);
-  if (nssCert == nullptr) {
+  if (!nssCert) {
     rv = NS_ERROR_OUT_OF_MEMORY;
   }
   NS_ADDREF(nssCert);
 
   *_retval = static_cast<nsIX509Cert*>(nssCert);
 
 loser:
   if (cert) CERT_DestroyCertificate(cert);
@@ -1419,28 +1418,28 @@ nsNSSCertificateDB::FindEmailSigningCert
   if (aNickname.IsEmpty())
     return NS_OK;
 
   nsNSSShutDownPreventionLock locker;
   nsresult rv = NS_OK;
   CERTCertificate *cert = 0;
   nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
   nsNSSCertificate *nssCert = nullptr;
-  char *asciiname = NULL;
+  char *asciiname = nullptr;
   NS_ConvertUTF16toUTF8 aUtf8Nickname(aNickname);
   asciiname = const_cast<char*>(aUtf8Nickname.get());
 
   /* Find a good cert in the user's database */
   cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(), asciiname, 
            certUsageEmailSigner, true, ctx);
 
   if (!cert) { goto loser; }  
 
   nssCert = nsNSSCertificate::Create(cert);
-  if (nssCert == nullptr) {
+  if (!nssCert) {
     rv = NS_ERROR_OUT_OF_MEMORY;
   }
   NS_ADDREF(nssCert);
 
   *_retval = static_cast<nsIX509Cert*>(nssCert);
 
 loser:
   if (cert) CERT_DestroyCertificate(cert);
@@ -1448,17 +1447,17 @@ loser:
 }
 
 NS_IMETHODIMP
 nsNSSCertificateDB::FindCertByEmailAddress(nsISupports *aToken, const char *aEmailAddress, nsIX509Cert **_retval)
 {
   nsNSSShutDownPreventionLock locker;
   
   nsCOMPtr<nsINSSComponent> inss;
-  nsRefPtr<nsCERTValInParamWrapper> survivingParams;
+  RefPtr<nsCERTValInParamWrapper> survivingParams;
   nsresult nsrv;
   
   if (nsNSSComponent::globalConstFlagUsePKIXVerification) {
     inss = do_GetService(kNSSComponentCID, &nsrv);
     if (!inss)
       return nsrv;
     nsrv = inss->GetDefaultCERTValInParam(survivingParams);
     if (NS_FAILED(nsrv))
@@ -1523,17 +1522,17 @@ NS_IMETHODIMP
 nsNSSCertificateDB::ConstructX509FromBase64(const char *base64,
                                             nsIX509Cert **_retval)
 {
   NS_ENSURE_ARG_POINTER(_retval);
 
   // sure would be nice to have a smart pointer class for PL_ allocations
   // unfortunately, we cannot distinguish out-of-memory from bad-input here
   uint32_t len = PL_strlen(base64);
-  char *certDER = PL_Base64Decode(base64, len, NULL);
+  char *certDER = PL_Base64Decode(base64, len, nullptr);
   if (!certDER)
     return NS_ERROR_ILLEGAL_VALUE;
   if (!*certDER) {
     PL_strfree(certDER);
     return NS_ERROR_ILLEGAL_VALUE;
   }
 
   // If we get to this point, we know we had well-formed base64 input;
@@ -1660,29 +1659,29 @@ nsNSSCertificateDB::get_default_nickname
       dummycert = CERT_FindCertByNickname(defaultcertdb, nickname.get());
 
     } else {
       /*
        * Check the cert against others that already live on the smart 
        * card.
        */
       dummycert = PK11_FindCertFromNickname(nickname.get(), ctx);
-      if (dummycert != NULL) {
+      if (dummycert) {
 	/*
 	 * Make sure the subject names are different.
 	 */ 
 	if (CERT_CompareName(&cert->subject, &dummycert->subject) == SECEqual)
 	{
 	  /*
 	   * There is another certificate with the same nickname and
 	   * the same subject name on the smart card, so let's use this
 	   * nickname.
 	   */
 	  CERT_DestroyCertificate(dummycert);
-	  dummycert = NULL;
+	  dummycert = nullptr;
 	}
       }
     }
     if (!dummycert) 
       break;
     
     count++;
   }
@@ -1748,17 +1747,16 @@ NS_IMETHODIMP
 nsNSSCertificateDB::GetCerts(nsIX509CertList **_retval)
 {
   CERTCertList *certList;
 
   nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
   nsCOMPtr<nsIX509CertList> nssCertList;
   certList = PK11_ListCerts(PK11CertListUnique, ctx);
 
-  // nsNSSCertList 1) adopts certList, and 2) handles the NULL case fine.
+  // nsNSSCertList 1) adopts certList, and 2) handles the nullptr case fine.
   // (returns an empty list) 
   nssCertList = new nsNSSCertList(certList, true);
-  if (!nssCertList) { return NS_ERROR_OUT_OF_MEMORY; }
 
   *_retval = nssCertList;
   NS_ADDREF(*_retval);
   return NS_OK;
 }
--- a/security/manager/ssl/src/nsNSSComponent.cpp
+++ b/security/manager/ssl/src/nsNSSComponent.cpp
@@ -31,17 +31,16 @@
 #include "nsDateTimeFormatCID.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMWindowCollection.h"
 #include "nsIDOMSmartCardEvent.h"
 #include "nsIDOMCrypto.h"
 #include "nsThreadUtils.h"
-#include "nsAutoPtr.h"
 #include "nsCRT.h"
 #include "nsCRLInfo.h"
 #include "nsCertOverrideService.h"
 
 #include "nsIWindowWatcher.h"
 #include "nsIPrompt.h"
 #include "nsIPrincipal.h"
 #include "nsReadableUtils.h"
@@ -73,20 +72,18 @@
 #include "cert.h"
 
 #include "nsXULAppAPI.h"
 
 #ifdef XP_WIN
 #include "nsILocalFileWin.h"
 #endif
 
-extern "C" {
 #include "pkcs12.h"
 #include "p12plcy.h"
-}
 
 using namespace mozilla;
 using namespace mozilla::psm;
 
 #ifdef PR_LOGGING
 PRLogModuleInfo* gPIPNSSLog = nullptr;
 #endif
 
@@ -317,17 +314,17 @@ bool EnsureNSSInitialized(EnsureNSSOpera
   }
 }
 
 nsNSSComponent::nsNSSComponent()
   :mutex("nsNSSComponent.mutex"),
    mNSSInitialized(false),
    mCrlTimerLock("nsNSSComponent.mCrlTimerLock"),
    mThreadList(nullptr),
-   mCertVerificationThread(NULL)
+   mCertVerificationThread(nullptr)
 {
 #ifdef PR_LOGGING
   if (!gPIPNSSLog)
     gPIPNSSLog = PR_NewLogModule("pipnss");
 #endif
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsNSSComponent::ctor\n"));
   mUpdateTimerInitialized = false;
   crlDownloadTimerOn = false;
@@ -355,17 +352,17 @@ nsNSSComponent::deleteBackgroundThreads(
     delete mCertVerificationThread;
     mCertVerificationThread = nullptr;
   }
 }
 
 void
 nsNSSComponent::createBackgroundThreads()
 {
-  NS_ASSERTION(mCertVerificationThread == nullptr,
+  NS_ASSERTION(!mCertVerificationThread,
                "Cert verification thread already created.");
 
   mCertVerificationThread = new nsCertVerificationThread;
   nsresult rv = mCertVerificationThread->startThread(
     NS_LITERAL_CSTRING("Cert Verify"));
 
   if (NS_FAILED(rv)) {
     delete mCertVerificationThread;
@@ -382,17 +379,17 @@ nsNSSComponent::~nsNSSComponent()
   if (mUpdateTimerInitialized) {
     {
       MutexAutoLock lock(mCrlTimerLock);
       if (crlDownloadTimerOn) {
         mTimer->Cancel();
       }
       crlDownloadTimerOn = false;
     }
-    if(crlsScheduledForDownload != nullptr){
+    if (crlsScheduledForDownload) {
       crlsScheduledForDownload->Reset();
       delete crlsScheduledForDownload;
     }
 
     mUpdateTimerInitialized = false;
   }
 
   // All cleanup code requiring services needs to happen in xpcom_shutdown
@@ -411,19 +408,16 @@ nsNSSComponent::~nsNSSComponent()
 }
 
 NS_IMETHODIMP
 nsNSSComponent::PostEvent(const nsAString &eventType, 
                                                   const nsAString &tokenName)
 {
   nsCOMPtr<nsIRunnable> runnable = 
                                new nsTokenEventRunnable(eventType, tokenName);
-  if (!runnable) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
 
   return NS_DispatchToMainThread(runnable);
 }
 
 
 NS_IMETHODIMP
 nsNSSComponent::DispatchEvent(const nsAString &eventType,
                                                  const nsAString &tokenName)
@@ -509,17 +503,17 @@ nsNSSComponent::DispatchEventToWindow(ns
   }
 
   // dispatch the event ...
 
   nsresult rv;
   // find the document
   nsCOMPtr<nsIDOMDocument> doc;
   rv = domWin->GetDocument(getter_AddRefs(doc));
-  if (doc == nullptr) {
+  if (!doc) {
     return NS_FAILED(rv) ? rv : NS_ERROR_FAILURE;
   }
 
   // create the event
   nsCOMPtr<nsIDOMEvent> event;
   rv = doc->CreateEvent(NS_LITERAL_STRING("Events"), 
                         getter_AddRefs(event));
   if (NS_FAILED(rv)) {
@@ -528,20 +522,16 @@ nsNSSComponent::DispatchEventToWindow(ns
 
   event->InitEvent(eventType, false, true);
 
   // create the Smart Card Event;
   nsCOMPtr<nsIDOMSmartCardEvent> smartCardEvent = 
                                           new nsSmartCardEvent(tokenName);
   // init the smart card event, fail here if we can't complete the 
   // initialization.
-  if (!smartCardEvent) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
   rv = smartCardEvent->Init(event);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   // Send it 
   nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(doc, &rv);
   if (NS_FAILED(rv)) {
@@ -658,26 +648,20 @@ nsNSSComponent::LaunchSmartCardThreads()
   }
 }
 
 NS_IMETHODIMP
 nsNSSComponent::LaunchSmartCardThread(SECMODModule *module)
 {
   SmartCardMonitoringThread *newThread;
   if (SECMOD_HasRemovableSlots(module)) {
-    if (mThreadList == nullptr) {
+    if (!mThreadList) {
       mThreadList = new SmartCardThreadList();
-      if (!mThreadList) {
-        return NS_ERROR_OUT_OF_MEMORY;
-      }
     }
     newThread = new SmartCardMonitoringThread(module);
-    if (!newThread) {
-	return NS_ERROR_OUT_OF_MEMORY;
-    }
     // newThread is adopted by the add.
     return mThreadList->Add(newThread);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNSSComponent::ShutdownSmartCardThread(SECMODModule *module)
@@ -707,18 +691,18 @@ nss_addEscape(const char *string, char q
     for (src=string; *src ; src++) {
         if ((*src == quote) || (*src == '\\')) {
           escapes++;
         }
         size++;
     }
 
     newString = (char*)PORT_ZAlloc(escapes+size+1);
-    if (newString == NULL) {
-        return NULL;
+    if (!newString) {
+        return nullptr;
     }
 
     for (src=string, dest=newString; *src; src++,dest++) {
         if ((*src == quote) || (*src == '\\')) {
             *dest++ = '\\';
         }
         *dest = *src;
     }
@@ -1049,17 +1033,17 @@ static CipherPref CipherPrefs[] = {
  {"security.ssl3.rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA}, // 128-bit AES encryption with RSA and a SHA1 MAC
  {"security.ssl3.dhe_rsa_des_ede3_sha", SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA}, // 168-bit Triple DES with RSA, DHE, and a SHA1 MAC
  {"security.ssl3.dhe_dss_des_ede3_sha", SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA}, // 168-bit Triple DES with DSA, DHE, and a SHA1 MAC
  {"security.ssl3.dhe_rsa_des_sha", SSL_DHE_RSA_WITH_DES_CBC_SHA}, // 56-bit DES encryption with RSA, DHE, and a SHA1 MAC
  {"security.ssl3.dhe_dss_des_sha", SSL_DHE_DSS_WITH_DES_CBC_SHA}, // 56-bit DES encryption with DSA, DHE, and a SHA1 MAC
  {"security.ssl3.rsa_null_sha", SSL_RSA_WITH_NULL_SHA}, // No encryption with RSA authentication and a SHA1 MAC
  {"security.ssl3.rsa_null_md5", SSL_RSA_WITH_NULL_MD5}, // No encryption with RSA authentication and an MD5 MAC
  {"security.ssl3.rsa_seed_sha", TLS_RSA_WITH_SEED_CBC_SHA}, // SEED encryption with RSA and a SHA1 MAC
- {NULL, 0} /* end marker */
+ {nullptr, 0} /* end marker */
 };
 
 static void
 setNonPkixOcspEnabled(int32_t ocspEnabled, nsIPrefBranch * pref)
 {
   switch (ocspEnabled) {
   case 0:
     CERT_DisableOCSPChecking(CERT_GetDefaultCertDB());
@@ -1137,17 +1121,17 @@ void nsNSSComponent::setValidationOption
     firstNetworkRevo = FIRST_REVO_METHOD_DEFAULT;
   
   setNonPkixOcspEnabled(ocspEnabled, pref);
   
   CERT_SetOCSPFailureMode( ocspRequired ?
                            ocspMode_FailureIsVerificationFailure
                            : ocspMode_FailureIsNotAVerificationFailure);
 
-  nsRefPtr<nsCERTValInParamWrapper> newCVIN = new nsCERTValInParamWrapper;
+  RefPtr<nsCERTValInParamWrapper> newCVIN(new nsCERTValInParamWrapper);
   if (NS_SUCCEEDED(newCVIN->Construct(
       aiaDownloadEnabled ? 
         nsCERTValInParamWrapper::missing_cert_download_on : nsCERTValInParamWrapper::missing_cert_download_off,
       crlDownloading ?
         nsCERTValInParamWrapper::crl_download_allowed : nsCERTValInParamWrapper::crl_local_only,
       ocspEnabled ? 
         nsCERTValInParamWrapper::ocsp_on : nsCERTValInParamWrapper::ocsp_off,
       ocspRequired ? 
@@ -1196,18 +1180,16 @@ nsNSSComponent::SkipOcspOff()
 }
 
 nsresult
 nsNSSComponent::PostCRLImportEvent(const nsCSubstring &urlString,
                                    nsIStreamListener *listener)
 {
   //Create the event
   nsCOMPtr<nsIRunnable> event = new CRLDownloadEvent(urlString, listener);
-  if (!event)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   //Get a handle to the ui thread
   return NS_DispatchToMainThread(event);
 }
 
 nsresult
 nsNSSComponent::DownloadCRLDirectly(nsAutoString url, nsAutoString key)
 {
@@ -1222,18 +1204,18 @@ nsNSSComponent::DownloadCRLDirectly(nsAu
 
 nsresult nsNSSComponent::DownloadCrlSilently()
 {
   //Add this attempt to the hashtable
   nsStringKey hashKey(mCrlUpdateKey.get());
   crlsScheduledForDownload->Put(&hashKey,(void *)nullptr);
     
   //Set up the download handler
-  nsRefPtr<PSMContentDownloader> psmDownloader =
-      new PSMContentDownloader(PSMContentDownloader::PKCS7_CRL);
+  RefPtr<PSMContentDownloader> psmDownloader(
+      new PSMContentDownloader(PSMContentDownloader::PKCS7_CRL));
   psmDownloader->setSilentDownload(true);
   psmDownloader->setCrlAutodownloadKey(mCrlUpdateKey);
   
   //Now get the url string
   NS_ConvertUTF16toUTF8 url8(mDownloadURL);
   return PostCRLImportEvent(url8, psmDownloader);
 }
 
@@ -1434,17 +1416,17 @@ nsNSSComponent::DefineNextTimer()
 //simultaneously from diff threads - they are NOT threadsafe. But, since there is no chance of 
 //that happening, there is not much benefit it trying to make it so at this point
 nsresult
 nsNSSComponent::StopCRLUpdateTimer()
 {
   
   //If it is at all running. 
   if (mUpdateTimerInitialized) {
-    if(crlsScheduledForDownload != nullptr){
+    if (crlsScheduledForDownload) {
       crlsScheduledForDownload->Reset();
       delete crlsScheduledForDownload;
       crlsScheduledForDownload = nullptr;
     }
     {
       MutexAutoLock lock(mCrlTimerLock);
       if (crlDownloadTimerOn) {
         mTimer->Cancel();
@@ -1640,17 +1622,17 @@ nsNSSComponent::InitializeNSS(bool showW
     nsAutoCString profileStr;
     nsCOMPtr<nsIFile> profilePath;
 
     rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
                                 getter_AddRefs(profilePath));
     if (NS_FAILED(rv)) {
       PR_LOG(gPIPNSSLog, PR_LOG_ERROR, ("Unable to get profile directory\n"));
       ConfigureInternalPKCS11Token();
-      SECStatus init_rv = NSS_NoDB_Init(NULL);
+      SECStatus init_rv = NSS_NoDB_Init(nullptr);
       if (init_rv != SECSuccess) {
         nsPSMInitPanic::SetPanic();
         return NS_ERROR_NOT_AVAILABLE;
       }
     }
     else
     {
 
@@ -2059,17 +2041,17 @@ static PK11SymKey * GetDecryptKeyCallbac
 static PRBool DecryptionAllowedCallback(SECAlgorithmID *algid,  
                                                PK11SymKey *bulkkey)
 {
   return SECMIME_DecryptionAllowed(algid, bulkkey);
 }
 
 static void * GetPasswordKeyCallback(void *arg, void *handle)
 {
-  return NULL;
+  return nullptr;
 }
 
 NS_IMETHODIMP
 nsNSSComponent::VerifySignature(const char* aRSABuf, uint32_t aRSABufLen,
                                 const char* aPlaintext, uint32_t aPlaintextLen,
                                 int32_t* aErrorCode,
                                 nsIPrincipal** aPrincipal)
 {
@@ -2634,27 +2616,27 @@ NS_IMETHODIMP
 nsNSSComponent::IsNSSInitialized(bool *initialized)
 {
   MutexAutoLock lock(mutex);
   *initialized = mNSSInitialized;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsNSSComponent::GetDefaultCERTValInParam(nsRefPtr<nsCERTValInParamWrapper> &out)
+nsNSSComponent::GetDefaultCERTValInParam(RefPtr<nsCERTValInParamWrapper> &out)
 {
   MutexAutoLock lock(mutex);
   if (!mNSSInitialized)
       return NS_ERROR_NOT_INITIALIZED;
   out = mDefaultCERTValInParam;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsNSSComponent::GetDefaultCERTValInParamLocalOnly(nsRefPtr<nsCERTValInParamWrapper> &out)
+nsNSSComponent::GetDefaultCERTValInParamLocalOnly(RefPtr<nsCERTValInParamWrapper> &out)
 {
   MutexAutoLock lock(mutex);
   if (!mNSSInitialized)
       return NS_ERROR_NOT_INITIALIZED;
   out = mDefaultCERTValInParamLocalOnly;
   return NS_OK;
 }
 
@@ -3188,17 +3170,17 @@ PSMContentDownloader::OnDataAvailable(ns
   
   uint32_t amt;
   nsresult err;
   //Do a check to see if we need to allocate more memory.
   if ((mBufferOffset + (int32_t)aLength) > mBufferSize) {
       size_t newSize = (mBufferOffset + aLength) *2; // grow some more than needed
       char *newBuffer;
       newBuffer = (char*)nsMemory::Realloc(mByteData, newSize);
-      if (newBuffer == nullptr) {
+      if (!newBuffer) {
         return NS_ERROR_OUT_OF_MEMORY;
       }
       mByteData = newBuffer;
       mBufferSize = newSize;
   }
   
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CertDownloader::OnDataAvailable\n"));
   do {
--- a/security/manager/ssl/src/nsNSSComponent.h
+++ b/security/manager/ssl/src/nsNSSComponent.h
@@ -3,16 +3,17 @@
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef _nsNSSComponent_h_
 #define _nsNSSComponent_h_
 
 #include "mozilla/Mutex.h"
+#include "mozilla/RefPtr.h"
 #include "nsCOMPtr.h"
 #include "nsISignatureVerifier.h"
 #include "nsIURIContentListener.h"
 #include "nsIStreamListener.h"
 #include "nsIEntropyCollector.h"
 #include "nsString.h"
 #include "nsIStringBundle.h"
 #include "nsIDOMEventTarget.h"
@@ -154,18 +155,20 @@ class NS_NO_VTABLE nsINSSComponent : pub
   NS_IMETHOD DispatchEvent(const nsAString &eventType, const nsAString &token) = 0;
   
   NS_IMETHOD GetClientAuthRememberService(nsClientAuthRememberService **cars) = 0;
 
   NS_IMETHOD EnsureIdentityInfoLoaded() = 0;
 
   NS_IMETHOD IsNSSInitialized(bool *initialized) = 0;
 
-  NS_IMETHOD GetDefaultCERTValInParam(nsRefPtr<nsCERTValInParamWrapper> &out) = 0;
-  NS_IMETHOD GetDefaultCERTValInParamLocalOnly(nsRefPtr<nsCERTValInParamWrapper> &out) = 0;
+  NS_IMETHOD GetDefaultCERTValInParam(
+                  mozilla::RefPtr<nsCERTValInParamWrapper> &out) = 0;
+  NS_IMETHOD GetDefaultCERTValInParamLocalOnly(
+                  mozilla::RefPtr<nsCERTValInParamWrapper> &out) = 0;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsINSSComponent, NS_INSSCOMPONENT_IID)
 
 class nsCryptoHash : public nsICryptoHash, public nsNSSShutDownObject
 {
 public:
   NS_DECL_ISUPPORTS
@@ -255,18 +258,20 @@ public:
   NS_IMETHOD LaunchSmartCardThread(SECMODModule *module);
   NS_IMETHOD ShutdownSmartCardThread(SECMODModule *module);
   NS_IMETHOD PostEvent(const nsAString &eventType, const nsAString &token);
   NS_IMETHOD DispatchEvent(const nsAString &eventType, const nsAString &token);
   NS_IMETHOD GetClientAuthRememberService(nsClientAuthRememberService **cars);
   NS_IMETHOD EnsureIdentityInfoLoaded();
   NS_IMETHOD IsNSSInitialized(bool *initialized);
 
-  NS_IMETHOD GetDefaultCERTValInParam(nsRefPtr<nsCERTValInParamWrapper> &out);
-  NS_IMETHOD GetDefaultCERTValInParamLocalOnly(nsRefPtr<nsCERTValInParamWrapper> &out);
+  NS_IMETHOD GetDefaultCERTValInParam(
+                  mozilla::RefPtr<nsCERTValInParamWrapper> &out);
+  NS_IMETHOD GetDefaultCERTValInParamLocalOnly(
+                  mozilla::RefPtr<nsCERTValInParamWrapper> &out);
 private:
 
   nsresult InitializeNSS(bool showWarningBox);
   nsresult ShutdownNSS();
 
 #ifdef XP_MACOSX
   void TryCFM2MachOMigration(nsIFile *cfmPath, nsIFile *machoPath);
 #endif
@@ -317,19 +322,19 @@ private:
   SmartCardThreadList *mThreadList;
   bool mIsNetworkDown;
 
   void deleteBackgroundThreads();
   void createBackgroundThreads();
   nsCertVerificationThread *mCertVerificationThread;
 
   nsNSSHttpInterface mHttpForNSS;
-  nsRefPtr<nsClientAuthRememberService> mClientAuthRememberService;
-  nsRefPtr<nsCERTValInParamWrapper> mDefaultCERTValInParam;
-  nsRefPtr<nsCERTValInParamWrapper> mDefaultCERTValInParamLocalOnly;
+  mozilla::RefPtr<nsClientAuthRememberService> mClientAuthRememberService;
+  mozilla::RefPtr<nsCERTValInParamWrapper> mDefaultCERTValInParam;
+  mozilla::RefPtr<nsCERTValInParamWrapper> mDefaultCERTValInParamLocalOnly;
 
   static PRStatus IdentityInfoInit(void);
   PRCallOnceType mIdentityInfoCallOnce;
 
 public:
   static bool globalConstFlagUsePKIXVerification;
 };
 
--- a/security/manager/ssl/src/nsNSSIOLayer.cpp
+++ b/security/manager/ssl/src/nsNSSIOLayer.cpp
@@ -142,17 +142,17 @@ nsNSSSocketInfo::SetNotificationCallback
 
   return NS_OK;
 }
 
 static void
 getSecureBrowserUI(nsIInterfaceRequestor * callbacks,
                    nsISecureBrowserUI ** result)
 {
-  NS_ASSERTION(result != nullptr, "result parameter to getSecureBrowserUI is null");
+  NS_ASSERTION(result, "result parameter to getSecureBrowserUI is null");
   *result = nullptr;
 
   NS_ASSERTION(NS_IsMainThread(),
                "getSecureBrowserUI called off the main thread");
 
   if (!callbacks)
     return;
 
@@ -368,17 +368,17 @@ private:
   nsCOMPtr<nsIInterfaceRequestor> mCallbacks; // in
 };
 
 void nsNSSSocketInfo::GetPreviousCert(nsIX509Cert** _result)
 {
   NS_ASSERTION(_result, "_result parameter to GetPreviousCert is null");
   *_result = nullptr;
 
-  nsRefPtr<PreviousCertRunnable> runnable = new PreviousCertRunnable(mCallbacks);
+  RefPtr<PreviousCertRunnable> runnable(new PreviousCertRunnable(mCallbacks));
   nsresult rv = runnable->DispatchToMainThreadAndWait();
   NS_ASSERTION(NS_SUCCEEDED(rv), "runnable->DispatchToMainThreadAndWait() failed");
   runnable->mPreviousCert.forget(_result);
 }
 
 void
 nsNSSSocketInfo::SetCertVerificationWaiting()
 {
@@ -829,17 +829,17 @@ class SSLErrorRunnable : public SyncRunn
   {
   }
 
   virtual void RunOnTargetThread()
   {
     nsHandleSSLError(mInfoObject, mErrType, mErrorCode);
   }
   
-  nsRefPtr<nsNSSSocketInfo> mInfoObject;
+  RefPtr<nsNSSSocketInfo> mInfoObject;
   ::mozilla::psm::SSLErrorMessageType mErrType;
   const PRErrorCode mErrorCode;
 };
 
 namespace {
 
 int32_t checkHandshake(int32_t bytesTransfered, bool wasReading,
                        PRFileDesc* ssl_layer_fd,
@@ -903,19 +903,19 @@ int32_t checkHandshake(int32_t bytesTran
     // The socketInfo->GetErrorCode() check is here to ensure we don't try to
     // do the synchronous dispatch to the main thread unnecessarily after we've
     // already handled a certificate error. (SSLErrorRunnable calls
     // nsHandleSSLError, which has logic to avoid replacing the error message,
     // so without the !socketInfo->GetErrorCode(), it would just be an
     // expensive no-op.)
     if (!wantRetry && (IS_SSL_ERROR(err) || IS_SEC_ERROR(err)) &&
         !socketInfo->GetErrorCode()) {
-      nsRefPtr<SyncRunnableBase> runnable = new SSLErrorRunnable(socketInfo,
-                                                                 PlainErrorMessage,
-                                                                 err);
+      RefPtr<SyncRunnableBase> runnable(new SSLErrorRunnable(socketInfo,
+                                                             PlainErrorMessage,
+                                                             err));
       (void) runnable->DispatchToMainThreadAndWait();
     }
   }
   else if (wasReading && 0 == bytesTransfered) // zero bytes on reading, socket closed
   {
     if (handleHandshakeResultNow)
     {
       if (!wantRetry // no decision yet
@@ -1037,17 +1037,17 @@ static PRStatus _PSM_InvalidStatus(void)
     PR_SetError(PR_INVALID_METHOD_ERROR, 0);
     return PR_FAILURE;
 }
 
 static PRFileDesc *_PSM_InvalidDesc(void)
 {
     PR_ASSERT(!"I/O method is invalid");
     PR_SetError(PR_INVALID_METHOD_ERROR, 0);
-    return NULL;
+    return nullptr;
 }
 
 static PRStatus PSMGetsockname(PRFileDesc *fd, PRNetAddr *addr)
 {
   nsNSSShutDownPreventionLock locker;
   if (!getSocketInfoIfRunning(fd, not_reading_or_writing, locker))
     return PR_FAILURE;
 
@@ -1207,34 +1207,25 @@ nsresult nsSSLIOLayerHelpers::Init()
     nsSSLIOLayerMethods.write = nsSSLIOLayerWrite;
     nsSSLIOLayerMethods.read = nsSSLIOLayerRead;
     nsSSLIOLayerMethods.poll = nsSSLIOLayerPoll;
   }
 
   mutex = new Mutex("nsSSLIOLayerHelpers.mutex");
 
   mTLSIntolerantSites = new nsTHashtable<nsCStringHashKey>();
-  if (!mTLSIntolerantSites)
-    return NS_ERROR_OUT_OF_MEMORY;
-
   mTLSIntolerantSites->Init(1);
 
   mTLSTolerantSites = new nsTHashtable<nsCStringHashKey>();
-  if (!mTLSTolerantSites)
-    return NS_ERROR_OUT_OF_MEMORY;
-
   // Initialize the tolerant site hashtable to 16 items at the start seems
   // reasonable as most servers are TLS tolerant. We just want to lower 
   // the rate of hashtable array reallocation.
   mTLSTolerantSites->Init(16);
 
   mRenegoUnrestrictedSites = new nsTHashtable<nsCStringHashKey>();
-  if (!mRenegoUnrestrictedSites)
-    return NS_ERROR_OUT_OF_MEMORY;
-
   mRenegoUnrestrictedSites->Init(1);
 
   mTreatUnsafeNegotiationAsBroken = false;
   
   return NS_OK;
 }
 
 void nsSSLIOLayerHelpers::addIntolerantSite(const nsCString &str)
@@ -1357,86 +1348,86 @@ SECStatus nsConvertCANamesToStrings(PLAr
     SECStatus rv;
     int headerlen;
     uint32_t contentlen;
     SECItem newitem;
     int n;
     char* namestring;
 
     for (n = 0; n < caNames->nnames; n++) {
-        newitem.data = NULL;
+        newitem.data = nullptr;
         dername = &caNames->names[n];
 
         rv = DER_Lengths(dername, &headerlen, &contentlen);
 
         if (rv != SECSuccess) {
             goto loser;
         }
 
         if (headerlen + contentlen != dername->len) {
             /* This must be from an enterprise 2.x server, which sent
              * incorrectly formatted der without the outer wrapper of
              * type and length.  Fix it up by adding the top level
              * header.
              */
             if (dername->len <= 127) {
                 newitem.data = (unsigned char *) PR_Malloc(dername->len + 2);
-                if (newitem.data == NULL) {
+                if (!newitem.data) {
                     goto loser;
                 }
                 newitem.data[0] = (unsigned char)0x30;
                 newitem.data[1] = (unsigned char)dername->len;
                 (void)memcpy(&newitem.data[2], dername->data, dername->len);
             }
             else if (dername->len <= 255) {
                 newitem.data = (unsigned char *) PR_Malloc(dername->len + 3);
-                if (newitem.data == NULL) {
+                if (!newitem.data) {
                     goto loser;
                 }
                 newitem.data[0] = (unsigned char)0x30;
                 newitem.data[1] = (unsigned char)0x81;
                 newitem.data[2] = (unsigned char)dername->len;
                 (void)memcpy(&newitem.data[3], dername->data, dername->len);
             }
             else {
                 /* greater than 256, better be less than 64k */
                 newitem.data = (unsigned char *) PR_Malloc(dername->len + 4);
-                if (newitem.data == NULL) {
+                if (!newitem.data) {
                     goto loser;
                 }
                 newitem.data[0] = (unsigned char)0x30;
                 newitem.data[1] = (unsigned char)0x82;
                 newitem.data[2] = (unsigned char)((dername->len >> 8) & 0xff);
                 newitem.data[3] = (unsigned char)(dername->len & 0xff);
                 memcpy(&newitem.data[4], dername->data, dername->len);
             }
             dername = &newitem;
         }
 
         namestring = CERT_DerNameToAscii(dername);
-        if (namestring == NULL) {
+        if (!namestring) {
             /* XXX - keep going until we fail to convert the name */
             caNameStrings[n] = const_cast<char*>("");
         }
         else {
             caNameStrings[n] = PORT_ArenaStrdup(arena, namestring);
             PR_Free(namestring);
-            if (caNameStrings[n] == NULL) {
+            if (!caNameStrings[n]) {
                 goto loser;
             }
         }
 
-        if (newitem.data != NULL) {
+        if (newitem.data) {
             PR_Free(newitem.data);
         }
     }
 
     return SECSuccess;
 loser:
-    if (newitem.data != NULL) {
+    if (newitem.data) {
         PR_Free(newitem.data);
     }
     return SECFailure;
 }
 
 /*
  * structs and ASN1 templates for the limited scope-of-use extension
  *
@@ -1460,17 +1451,17 @@ typedef struct {
 
 typedef struct {
     CERTCertificateScopeEntry** entries;
 } certCertificateScopeOfUse;
 
 /* corresponding ASN1 templates */
 static const SEC_ASN1Template cert_CertificateScopeEntryTemplate[] = {
     { SEC_ASN1_SEQUENCE, 
-      0, NULL, sizeof(CERTCertificateScopeEntry) },
+      0, nullptr, sizeof(CERTCertificateScopeEntry) },
     { SEC_ASN1_ANY,
       offsetof(CERTCertificateScopeEntry, derConstraint) },
     { SEC_ASN1_OPTIONAL | SEC_ASN1_INTEGER,
       offsetof(CERTCertificateScopeEntry, derPort) },
     { 0 }
 };
 
 static const SEC_ASN1Template cert_CertificateScopeOfUseTemplate[] = {
@@ -1482,50 +1473,50 @@ static const SEC_ASN1Template cert_Certi
  * decodes the extension data and create CERTCertificateScopeEntry that can
  * be consumed by the code
  */
 static
 SECStatus cert_DecodeScopeOfUseEntries(PRArenaPool* arena, SECItem* extData,
                                        CERTCertificateScopeEntry*** entries,
                                        int* numEntries)
 {
-    certCertificateScopeOfUse* scope = NULL;
+    certCertificateScopeOfUse* scope = nullptr;
     SECStatus rv = SECSuccess;
     int i;
 
-    *entries = NULL; /* in case of failure */
+    *entries = nullptr; /* in case of failure */
     *numEntries = 0; /* ditto */
 
     scope = (certCertificateScopeOfUse*)
         PORT_ArenaZAlloc(arena, sizeof(certCertificateScopeOfUse));
-    if (scope == NULL) {
+    if (!scope) {
         goto loser;
     }
 
     rv = SEC_ASN1DecodeItem(arena, (void*)scope, 
                             cert_CertificateScopeOfUseTemplate, extData);
     if (rv != SECSuccess) {
         goto loser;
     }
 
     *entries = scope->entries;
-    PR_ASSERT(*entries != NULL);
+    PR_ASSERT(*entries);
 
     /* first, let's count 'em. */
-    for (i = 0; (*entries)[i] != NULL; i++) ;
+    for (i = 0; (*entries)[i]; i++) ;
     *numEntries = i;
 
     /* convert certCertificateScopeEntry sequence into what we can readily
      * use
      */
     for (i = 0; i < *numEntries; i++) {
         (*entries)[i]->constraint = 
             CERT_DecodeGeneralName(arena, &((*entries)[i]->derConstraint), 
-                                   NULL);
-        if ((*entries)[i]->derPort.data != NULL) {
+                                   nullptr);
+        if ((*entries)[i]->derPort.data) {
             (*entries)[i]->port = 
                 (int)DER_GetInteger(&((*entries)[i]->derPort));
         }
         else {
             (*entries)[i]->port = 0;
         }
     }
 
@@ -1540,18 +1531,18 @@ done:
 
 static SECStatus cert_DecodeCertIPAddress(SECItem* genname, 
                                           uint32_t* constraint, uint32_t* mask)
 {
     /* in case of failure */
     *constraint = 0;
     *mask = 0;
 
-    PR_ASSERT(genname->data != NULL);
-    if (genname->data == NULL) {
+    PR_ASSERT(genname->data);
+    if (!genname->data) {
         return SECFailure;
     }
     if (genname->len != 8) {
         /* the length must be 4 byte IP address with 4 byte subnet mask */
         return SECFailure;
     }
 
     /* get them in the right order */
@@ -1581,39 +1572,39 @@ static char* _str_to_lower(char* string)
  * the port) does not satisfy the restriction
  */
 static bool CERT_MatchesScopeOfUse(CERTCertificate* cert, char* hostname,
                                      char* hostIP, int port)
 {
     bool rv = true; /* whether the cert can be presented */
     SECStatus srv;
     SECItem extData;
-    PLArenaPool* arena = NULL;
-    CERTCertificateScopeEntry** entries = NULL;
+    PLArenaPool* arena = nullptr;
+    CERTCertificateScopeEntry** entries = nullptr;
     /* arrays of decoded scope entries */
     int numEntries = 0;
     int i;
-    char* hostLower = NULL;
+    char* hostLower = nullptr;
     uint32_t hostIPAddr = 0;
 
-    PR_ASSERT((cert != NULL) && (hostname != NULL) && (hostIP != NULL));
+    PR_ASSERT(cert && hostname && hostIP);
 
     /* find cert extension */
     srv = CERT_FindCertExtension(cert, SEC_OID_NS_CERT_EXT_SCOPE_OF_USE,
                                  &extData);
     if (srv != SECSuccess) {
         /* most of the time, this means the extension was not found: also,
          * since this is not a critical extension (as of now) we may simply
          * return true
          */
         goto done;
     }
 
     arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
-    if (arena == NULL) {
+    if (!arena) {
         goto done;
     }
 
     /* decode the scope of use entries into pairs of GeneralNames and
      * an optional port numbers
      */
     srv = cert_DecodeScopeOfUseEntries(arena, &extData, &entries, &numEntries);
     if (srv != SECSuccess) {
@@ -1628,41 +1619,41 @@ static bool CERT_MatchesScopeOfUse(CERTC
 
     /* loop over these structures */
     for (i = 0; i < numEntries; i++) {
         /* determine whether the GeneralName is a DNS pattern, an IP address 
          * constraint, or else
          */
         CERTGeneralName* genname = entries[i]->constraint;
 
-        /* if constraint is NULL, don't bother looking */
-        if (genname == NULL) {
+        /* if constraint is nullptr, don't bother looking */
+        if (!genname) {
             /* this is not a failure: just continue */
             continue;
         }
 
         switch (genname->type) {
         case certDNSName: {
             /* we have a DNS name constraint; we should use only the host name
              * information
              */
-            char* pattern = NULL;
-            char* substring = NULL;
+            char* pattern = nullptr;
+            char* substring = nullptr;
 
             /* null-terminate the string */
             genname->name.other.data[genname->name.other.len] = '\0';
             pattern = _str_to_lower((char*)genname->name.other.data);
 
-            if (hostLower == NULL) {
+            if (!hostLower) {
                 /* so that it's done only if necessary and only once */
                 hostLower = _str_to_lower(PL_strdup(hostname));
             }
 
             /* the hostname satisfies the constraint */
-            if (((substring = strstr(hostLower, pattern)) != NULL) &&
+            if (((substring = strstr(hostLower, pattern)) != nullptr) &&
                 /* the hostname contains the pattern */
                 (strlen(substring) == strlen(pattern)) &&
                 /* the hostname ends with the pattern */
                 ((substring == hostLower) || (*(substring-1) == '.'))) {
                 /* the hostname either is identical to the pattern or
                  * belongs to a subdomain
                  */
                 rv = true;
@@ -1714,20 +1705,20 @@ static bool CERT_MatchesScopeOfUse(CERTC
         }
 
         /* we have a match */
         PR_ASSERT(rv);
         break;
     }
 done:
     /* clean up entries */
-    if (arena != NULL) {
+    if (arena) {
         PORT_FreeArena(arena, false);
     }
-    if (hostLower != NULL) {
+    if (hostLower) {
         PR_Free(hostLower);
     }
     return rv;
 }
 #endif
 
 /*
  * Function: SSMStatus SSM_SetUserCertChoice()
@@ -1742,17 +1733,17 @@ done:
  *		 for ASK and AUTO modes, read the selected strings from the
  *		 preference, compare the strings, and determine in which mode it is
  *		 in.
  *       We currently use ASK mode for UI apps and AUTO mode for UI-less
  *       apps without really asking for preferences.
  */
 nsresult nsGetUserCertChoice(SSM_UserCertChoice* certChoice)
 {
-	char *mode=NULL;
+	char *mode = nullptr;
 	nsresult ret;
 
 	NS_ENSURE_ARG_POINTER(certChoice);
 
 	nsCOMPtr<nsIPrefBranch> pref = do_GetService(NS_PREFSERVICE_CONTRACTID);
 
 	ret = pref->GetCharPref("security.default_personal_cert", &mode);
 	if (NS_FAILED(ret)) {
@@ -1781,17 +1772,17 @@ loser:
 static bool hasExplicitKeyUsageNonRepudiation(CERTCertificate *cert)
 {
   /* There is no extension, v1 or v2 certificate */
   if (!cert->extensions)
     return false;
 
   SECStatus srv;
   SECItem keyUsageItem;
-  keyUsageItem.data = NULL;
+  keyUsageItem.data = nullptr;
 
   srv = CERT_FindKeyUsageExtension(cert, &keyUsageItem);
   if (srv == SECFailure)
     return false;
 
   unsigned char keyUsage = keyUsageItem.data[0];
   PORT_Free (keyUsageItem.data);
 
@@ -1850,18 +1841,18 @@ SECStatus nsNSS_SSLGetClientAuthData(voi
 {
   nsNSSShutDownPreventionLock locker;
 
   if (!socket || !caNames || !pRetCert || !pRetKey) {
     PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
     return SECFailure;
   }
 
-  nsRefPtr<nsNSSSocketInfo> info
-        = reinterpret_cast<nsNSSSocketInfo*>(socket->higher->secret);
+  RefPtr<nsNSSSocketInfo> info(
+    reinterpret_cast<nsNSSSocketInfo*>(socket->higher->secret));
 
   CERTCertificate* serverCert = SSL_PeerCertificate(socket);
   if (!serverCert) {
     NS_NOTREACHED("Missing server certificate should have been detected during "
                   "server cert authentication.");
     PR_SetError(SSL_ERROR_NO_CERTIFICATE, 0);
     return SECFailure;
   }
@@ -1874,18 +1865,18 @@ SECStatus nsNSS_SSLGetClientAuthData(voi
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
            ("[%p] Not returning client cert due to previous join\n", socket));
     *pRetCert = nullptr;
     *pRetKey = nullptr;
     return SECSuccess;
   }
 
   // XXX: This should be done asynchronously; see bug 696976
-  nsRefPtr<ClientAuthDataRunnable> runnable =
-    new ClientAuthDataRunnable(caNames, pRetCert, pRetKey, info, serverCert);
+  RefPtr<ClientAuthDataRunnable> runnable(
+    new ClientAuthDataRunnable(caNames, pRetCert, pRetKey, info, serverCert));
   nsresult rv = runnable->DispatchToMainThreadAndWait();
   if (NS_FAILED(rv)) {
     PR_SetError(SEC_ERROR_NO_MEMORY, 0);
     return SECFailure;
   }
   
   if (runnable->mRV != SECSuccess) {
     PR_SetError(runnable->mErrorCodeToReport, 0);
@@ -1894,38 +1885,38 @@ SECStatus nsNSS_SSLGetClientAuthData(voi
     info->SetSentClientCert();
   }
 
   return runnable->mRV;
 }
 
 void ClientAuthDataRunnable::RunOnTargetThread()
 {
-  PLArenaPool* arena = NULL;
+  PLArenaPool* arena = nullptr;
   char** caNameStrings;
-  CERTCertificate* cert = NULL;
-  SECKEYPrivateKey* privKey = NULL;
-  CERTCertList* certList = NULL;
+  CERTCertificate* cert = nullptr;
+  SECKEYPrivateKey* privKey = nullptr;
+  CERTCertList* certList = nullptr;
   CERTCertListNode* node;
-  CERTCertNicknames* nicknames = NULL;
-  char* extracted = NULL;
+  CERTCertNicknames* nicknames = nullptr;
+  char* extracted = nullptr;
   int keyError = 0; /* used for private key retrieval error */
   SSM_UserCertChoice certChoice;
   int32_t NumberOfCerts = 0;
   void * wincx = mSocketInfo;
 
   /* create caNameStrings */
   arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
-  if (arena == NULL) {
+  if (!arena) {
     goto loser;
   }
 
   caNameStrings = (char**)PORT_ArenaAlloc(arena, 
                                           sizeof(char*)*(mCANames->nnames));
-  if (caNameStrings == NULL) {
+  if (!caNameStrings) {
     goto loser;
   }
 
   mRV = nsConvertCANamesToStrings(arena, caNameStrings, mCANames);
   if (mRV != SECSuccess) {
     goto loser;
   }
 
@@ -1937,54 +1928,54 @@ void ClientAuthDataRunnable::RunOnTarget
   /* find valid user cert and key pair */	
   if (certChoice == AUTO) {
     /* automatically find the right cert */
 
     /* find all user certs that are valid and for SSL */
     certList = CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(), 
                                          certUsageSSLClient, false,
                                          true, wincx);
-    if (certList == NULL) {
+    if (!certList) {
       goto noCert;
     }
 
     /* filter the list to those issued by CAs supported by the server */
     mRV = CERT_FilterCertListByCANames(certList, mCANames->nnames,
                                        caNameStrings, certUsageSSLClient);
     if (mRV != SECSuccess) {
       goto noCert;
     }
 
     /* make sure the list is not empty */
     node = CERT_LIST_HEAD(certList);
     if (CERT_LIST_END(node, certList)) {
       goto noCert;
     }
 
-    CERTCertificate* low_prio_nonrep_cert = NULL;
+    CERTCertificate* low_prio_nonrep_cert = nullptr;
     CERTCertificateCleaner low_prio_cleaner(low_prio_nonrep_cert);
 
     /* loop through the list until we find a cert with a key */
     while (!CERT_LIST_END(node, certList)) {
       /* if the certificate has restriction and we do not satisfy it
        * we do not use it
        */
 #if 0		/* XXX This must be re-enabled */
       if (!CERT_MatchesScopeOfUse(node->cert, mSocketInfo->GetHostName,
                                   info->GetHostIP, info->GetHostPort)) {
           node = CERT_LIST_NEXT(node);
           continue;
       }
 #endif
 
       privKey = PK11_FindKeyByAnyCert(node->cert, wincx);
-      if (privKey != NULL) {
+      if (privKey) {
         if (hasExplicitKeyUsageNonRepudiation(node->cert)) {
           SECKEY_DestroyPrivateKey(privKey);
-          privKey = NULL;
+          privKey = nullptr;
           // Not a prefered cert
           if (!low_prio_nonrep_cert) // did not yet find a low prio cert
             low_prio_nonrep_cert = CERT_DupCertificate(node->cert);
         }
         else {
           // this is a good cert to present
           cert = CERT_DupCertificate(node->cert);
           break;
@@ -1996,36 +1987,36 @@ void ClientAuthDataRunnable::RunOnTarget
           goto loser;
       }
 
       node = CERT_LIST_NEXT(node);
     }
 
     if (!cert && low_prio_nonrep_cert) {
       cert = low_prio_nonrep_cert;
-      low_prio_nonrep_cert = NULL; // take it away from the cleaner
+      low_prio_nonrep_cert = nullptr; // take it away from the cleaner
       privKey = PK11_FindKeyByAnyCert(cert, wincx);
     }
 
-    if (cert == NULL) {
+    if (!cert) {
         goto noCert;
     }
   }
   else { // Not Auto => ask
     /* Get the SSL Certificate */
 
     nsXPIDLCString hostname;
     mSocketInfo->GetHostName(getter_Copies(hostname));
 
     nsresult rv;
     NS_DEFINE_CID(nssComponentCID, NS_NSSCOMPONENT_CID);
     nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(nssComponentCID, &rv));
-    nsRefPtr<nsClientAuthRememberService> cars;
+    RefPtr<nsClientAuthRememberService> cars;
     if (nssComponent) {
-      nssComponent->GetClientAuthRememberService(getter_AddRefs(cars));
+      nssComponent->GetClientAuthRememberService(byRef(cars));
     }
 
     bool hasRemembered = false;
     nsCString rememberedDBKey;
     if (cars) {
       bool found;
       nsresult rv = cars->HasRememberedDecision(hostname, mServerCert,
                                                 rememberedDBKey, &found);
@@ -2075,27 +2066,27 @@ if (hasRemembered)
         }
       }
     }
 }
 
 if (!hasRemembered)
 {
     /* user selects a cert to present */
-    nsIClientAuthDialogs *dialogs = NULL;
+    nsIClientAuthDialogs *dialogs = nullptr;
     int32_t selectedIndex = -1;
-    PRUnichar **certNicknameList = NULL;
-    PRUnichar **certDetailsList = NULL;
+    PRUnichar **certNicknameList = nullptr;
+    PRUnichar **certDetailsList = nullptr;
 
     /* find all user certs that are for SSL */
     /* note that we are allowing expired certs in this list */
     certList = CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(), 
                                          certUsageSSLClient, false, 
                                          false, wincx);
-    if (certList == NULL) {
+    if (!certList) {
       goto noCert;
     }
 
     if (mCANames->nnames != 0) {
       /* filter the list to those issued by CAs supported by the 
        * server 
        */
       mRV = CERT_FilterCertListByCANames(certList, mCANames->nnames, 
@@ -2129,17 +2120,17 @@ if (!hasRemembered)
       node = CERT_LIST_NEXT(node);
     }
     if (CERT_LIST_END(CERT_LIST_HEAD(certList), certList)) {
       goto noCert;
     }
 
     nicknames = getNSSCertNicknamesFromCertList(certList);
 
-    if (nicknames == NULL) {
+    if (!nicknames) {
       goto loser;
     }
 
     NS_ASSERTION(nicknames->numnicknames == NumberOfCerts, "nicknames->numnicknames != NumberOfCerts");
 
     /* Get CN and O of the subject and O of the issuer */
     char *ccn = CERT_GetCommonName(&mServerCert->subject);
     void *v = ccn;
@@ -2181,17 +2172,17 @@ if (!hasRemembered)
     }
 
     int32_t CertsToUse;
     for (CertsToUse = 0, node = CERT_LIST_HEAD(certList);
          !CERT_LIST_END(node, certList) && CertsToUse < nicknames->numnicknames;
          node = CERT_LIST_NEXT(node)
         )
     {
-      nsRefPtr<nsNSSCertificate> tempCert = nsNSSCertificate::Create(node->cert);
+      RefPtr<nsNSSCertificate> tempCert(nsNSSCertificate::Create(node->cert));
 
       if (!tempCert)
         continue;
       
       NS_ConvertUTF8toUTF16 i_nickname(nicknames->nicknames[CertsToUse]);
       nsAutoString nickWithSerial, details;
       
       if (NS_FAILED(tempCert->FormatUIStrings(i_nickname, nickWithSerial, details)))
@@ -2258,23 +2249,23 @@ if (!hasRemembered)
 
     if (cars && wantRemember) {
       cars->RememberDecision(hostname, mServerCert, canceled ? 0 : cert);
     }
 }
 
     if (canceled) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; }
 
-    if (cert == NULL) {
+    if (!cert) {
       goto loser;
     }
 
     /* go get the private key */
     privKey = PK11_FindKeyByAnyCert(cert, wincx);
-    if (privKey == NULL) {
+    if (!privKey) {
       keyError = PR_GetError();
       if (keyError == SEC_ERROR_BAD_PASSWORD) {
           /* problem with password: bail */
           goto loser;
       }
       else {
           goto noCert;
       }
@@ -2282,33 +2273,33 @@ if (!hasRemembered)
   }
   goto done;
 
 noCert:
 loser:
   if (mRV == SECSuccess) {
     mRV = SECFailure;
   }
-  if (cert != NULL) {
+  if (cert) {
     CERT_DestroyCertificate(cert);
-    cert = NULL;
+    cert = nullptr;
   }
 done:
   int error = PR_GetError();
 
-  if (extracted != NULL) {
+  if (extracted) {
     PR_Free(extracted);
   }
-  if (nicknames != NULL) {
+  if (nicknames) {
     CERT_FreeNicknames(nicknames);
   }
-  if (certList != NULL) {
+  if (certList) {
     CERT_DestroyCertList(certList);
   }
-  if (arena != NULL) {
+  if (arena) {
     PORT_FreeArena(arena, false);
   }
 
   *mPRetCert = cert;
   *mPRetKey = privKey;
 
   if (mRV == SECFailure) {
     mErrorCodeToReport = error;
@@ -2327,17 +2318,17 @@ nsSSLIOLayerImportFD(PRFileDesc *fd,
     NS_ASSERTION(false, "NSS: Error importing socket");
     return nullptr;
   }
   SSL_SetPKCS11PinArg(sslSock, (nsIInterfaceRequestor*)infoObject);
   SSL_HandshakeCallback(sslSock, HandshakeCallback, infoObject);
 
   // Disable this hook if we connect anonymously. See bug 466080.
   if (anonymousLoad) {
-      SSL_GetClientAuthDataHook(sslSock, NULL, infoObject);
+      SSL_GetClientAuthDataHook(sslSock, nullptr, infoObject);
   } else {
       SSL_GetClientAuthDataHook(sslSock, 
                             (SSLGetClientAuthData)nsNSS_SSLGetClientAuthData,
                             infoObject);
   }
   if (SECSuccess != SSL_AuthCertificateHook(sslSock, AuthCertificateHook,
                                             infoObject)) {
     NS_NOTREACHED("failed to configure AuthCertificateHook");
--- a/security/manager/ssl/src/nsNSSIOLayer.h
+++ b/security/manager/ssl/src/nsNSSIOLayer.h
@@ -5,17 +5,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef _NSNSSIOLAYER_H
 #define _NSNSSIOLAYER_H
 
 #include "TransportSecurityInfo.h"
 #include "nsISSLSocketControl.h"
 #include "nsIClientAuthDialogs.h"
-#include "nsAutoPtr.h"
 #include "nsNSSCertificate.h"
 #include "nsDataHashtable.h"
 #include "nsTHashtable.h"
 
 class nsNSSSocketInfo : public mozilla::psm::TransportSecurityInfo,
                         public nsISSLSocketControl,
                         public nsIClientAuthUserDecision
 {
--- a/security/manager/ssl/src/nsNSSModule.cpp
+++ b/security/manager/ssl/src/nsNSSModule.cpp
@@ -47,37 +47,25 @@
 #include "nsXULAppAPI.h"
 #define NS_IS_PROCESS_DEFAULT                                                 \
     (GeckoProcessType_Default == XRE_GetProcessType())
 
 #define NS_NSS_INSTANTIATE(ensureOperator, _InstanceClass)                    \
     PR_BEGIN_MACRO                                                            \
         _InstanceClass * inst;                                                \
         inst = new _InstanceClass();                                          \
-        if (NULL == inst) {                                                   \
-            if (ensureOperator == nssLoadingComponent)                        \
-                EnsureNSSInitialized(nssInitFailed);                          \
-            rv = NS_ERROR_OUT_OF_MEMORY;                                      \
-            return rv;                                                        \
-        }                                                                     \
         NS_ADDREF(inst);                                                      \
         rv = inst->QueryInterface(aIID, aResult);                             \
         NS_RELEASE(inst);                                                     \
     PR_END_MACRO
 
 #define NS_NSS_INSTANTIATE_INIT(ensureOperator, _InstanceClass, _InitMethod)  \
     PR_BEGIN_MACRO                                                            \
         _InstanceClass * inst;                                                \
         inst = new _InstanceClass();                                          \
-        if (NULL == inst) {                                                   \
-            if (ensureOperator == nssLoadingComponent)                        \
-                EnsureNSSInitialized(nssInitFailed);                          \
-            rv = NS_ERROR_OUT_OF_MEMORY;                                      \
-            return rv;                                                        \
-        }                                                                     \
         NS_ADDREF(inst);                                                      \
         rv = inst->_InitMethod();                                             \
         if(NS_SUCCEEDED(rv)) {                                                \
             rv = inst->QueryInterface(aIID, aResult);                         \
         }                                                                     \
         NS_RELEASE(inst);                                                     \
    PR_END_MACRO
 
@@ -94,18 +82,18 @@
                                                      _InstanceClassChrome,    \
                                                      _InstanceClassContent)   \
 static nsresult                                                               \
 _InstanceClassChrome##Constructor(nsISupports *aOuter, REFNSIID aIID,         \
                                   void **aResult)                             \
 {                                                                             \
     nsresult rv;                                                              \
                                                                               \
-    *aResult = NULL;                                                          \
-    if (NULL != aOuter) {                                                     \
+    *aResult = nullptr;                                                          \
+    if (nullptr != aOuter) {                                                     \
         rv = NS_ERROR_NO_AGGREGATION;                                         \
         return rv;                                                            \
     }                                                                         \
                                                                               \
     if (!EnsureNSSInitialized(ensureOperator))                                \
         return NS_ERROR_FAILURE;                                              \
                                                                               \
     if (NS_IS_PROCESS_DEFAULT)                                                \
@@ -138,18 +126,18 @@ static nsresult                         
                                                 _InstanceClassContent,        \
                                                 _InitMethod)                  \
 static nsresult                                                               \
 _InstanceClassChrome##Constructor(nsISupports *aOuter, REFNSIID aIID,         \
                                   void **aResult)                             \
 {                                                                             \
     nsresult rv;                                                              \
                                                                               \
-    *aResult = NULL;                                                          \
-    if (NULL != aOuter) {                                                     \
+    *aResult = nullptr;                                                          \
+    if (nullptr != aOuter) {                                                     \
         rv = NS_ERROR_NO_AGGREGATION;                                         \
         return rv;                                                            \
     }                                                                         \
                                                                               \
     if (!EnsureNSSInitialized(ensureOperator))                                \
         return NS_ERROR_FAILURE;                                              \
                                                                               \
     if (NS_IS_PROCESS_DEFAULT)                                                \
@@ -257,53 +245,53 @@ NS_DEFINE_NAMED_CID(NS_CERTOVERRIDE_CID)
 NS_DEFINE_NAMED_CID(NS_RANDOMGENERATOR_CID);
 NS_DEFINE_NAMED_CID(NS_RECENTBADCERTS_CID);
 NS_DEFINE_NAMED_CID(NS_SSLSTATUS_CID);
 NS_DEFINE_NAMED_CID(TRANSPORTSECURITYINFO_CID);
 NS_DEFINE_NAMED_CID(NS_NSSERRORSSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_NSSVERSION_CID);
 
 static const mozilla::Module::CIDEntry kNSSCIDs[] = {
-  { &kNS_NSSCOMPONENT_CID, false, NULL, nsNSSComponentConstructor },
-  { &kNS_SSLSOCKETPROVIDER_CID, false, NULL, nsSSLSocketProviderConstructor },
-  { &kNS_STARTTLSSOCKETPROVIDER_CID, false, NULL, nsTLSSocketProviderConstructor },
-  { &kNS_SDR_CID, false, NULL, nsSecretDecoderRingConstructor },
-  { &kNS_PK11TOKENDB_CID, false, NULL, nsPK11TokenDBConstructor },
-  { &kNS_PKCS11MODULEDB_CID, false, NULL, nsPKCS11ModuleDBConstructor },
-  { &kNS_PSMCONTENTLISTEN_CID, false, NULL, PSMContentListenerConstructor },
-  { &kNS_X509CERT_CID, false, NULL, nsNSSCertificateConstructor },
-  { &kNS_X509CERTDB_CID, false, NULL, nsNSSCertificateDBConstructor },
-  { &kNS_NSSCERTCACHE_CID, false, NULL, nsNSSCertCacheConstructor },
-  { &kNS_FORMPROCESSOR_CID, false, NULL, nsKeygenFormProcessor::Create },
+  { &kNS_NSSCOMPONENT_CID, false, nullptr, nsNSSComponentConstructor },
+  { &kNS_SSLSOCKETPROVIDER_CID, false, nullptr, nsSSLSocketProviderConstructor },
+  { &kNS_STARTTLSSOCKETPROVIDER_CID, false, nullptr, nsTLSSocketProviderConstructor },
+  { &kNS_SDR_CID, false, nullptr, nsSecretDecoderRingConstructor },
+  { &kNS_PK11TOKENDB_CID, false, nullptr, nsPK11TokenDBConstructor },
+  { &kNS_PKCS11MODULEDB_CID, false, nullptr, nsPKCS11ModuleDBConstructor },
+  { &kNS_PSMCONTENTLISTEN_CID, false, nullptr, PSMContentListenerConstructor },
+  { &kNS_X509CERT_CID, false, nullptr, nsNSSCertificateConstructor },
+  { &kNS_X509CERTDB_CID, false, nullptr, nsNSSCertificateDBConstructor },
+  { &kNS_NSSCERTCACHE_CID, false, nullptr, nsNSSCertCacheConstructor },
+  { &kNS_FORMPROCESSOR_CID, false, nullptr, nsKeygenFormProcessor::Create },
 #ifdef MOZ_XUL
-  { &kNS_CERTTREE_CID, false, NULL, nsCertTreeConstructor },
+  { &kNS_CERTTREE_CID, false, nullptr, nsCertTreeConstructor },
 #endif
-  { &kNS_PKCS11_CID, false, NULL, nsPkcs11Constructor },
-  { &kNS_CRYPTO_CID, false, NULL, nsCryptoConstructor },
-  { &kNS_CMSSECUREMESSAGE_CID, false, NULL, nsCMSSecureMessageConstructor },
-  { &kNS_CMSDECODER_CID, false, NULL, nsCMSDecoderConstructor },
-  { &kNS_CMSENCODER_CID, false, NULL, nsCMSEncoderConstructor },
-  { &kNS_CMSMESSAGE_CID, false, NULL, nsCMSMessageConstructor },
-  { &kNS_CRYPTO_HASH_CID, false, NULL, nsCryptoHashConstructor },
-  { &kNS_CRYPTO_HMAC_CID, false, NULL, nsCryptoHMACConstructor },
-  { &kNS_CERT_PICKER_CID, false, NULL, nsCertPickerConstructor },
-  { &kNS_CRLMANAGER_CID, false, NULL, nsCRLManagerConstructor },
-  { &kNS_NTLMAUTHMODULE_CID, false, NULL, nsNTLMAuthModuleConstructor },
-  { &kNS_STREAMCIPHER_CID, false, NULL, nsStreamCipherConstructor },
-  { &kNS_KEYMODULEOBJECT_CID, false, NULL, nsKeyObjectConstructor },
-  { &kNS_KEYMODULEOBJECTFACTORY_CID, false, NULL, nsKeyObjectFactoryConstructor },
-  { &kNS_DATASIGNATUREVERIFIER_CID, false, NULL, nsDataSignatureVerifierConstructor },
-  { &kNS_CERTOVERRIDE_CID, false, NULL, nsCertOverrideServiceConstructor },
-  { &kNS_RANDOMGENERATOR_CID, false, NULL, nsRandomGeneratorConstructor },
-  { &kNS_RECENTBADCERTS_CID, false, NULL, nsRecentBadCertsServiceConstructor },
-  { &kNS_SSLSTATUS_CID, false, NULL, nsSSLStatusConstructor },
-  { &kTRANSPORTSECURITYINFO_CID, false, NULL, TransportSecurityInfoConstructor },
-  { &kNS_NSSERRORSSERVICE_CID, false, NULL, NSSErrorsServiceConstructor },
-  { &kNS_NSSVERSION_CID, false, NULL, nsNSSVersionConstructor },
-  { NULL }
+  { &kNS_PKCS11_CID, false, nullptr, nsPkcs11Constructor },
+  { &kNS_CRYPTO_CID, false, nullptr, nsCryptoConstructor },
+  { &kNS_CMSSECUREMESSAGE_CID, false, nullptr, nsCMSSecureMessageConstructor },
+  { &kNS_CMSDECODER_CID, false, nullptr, nsCMSDecoderConstructor },
+  { &kNS_CMSENCODER_CID, false, nullptr, nsCMSEncoderConstructor },
+  { &kNS_CMSMESSAGE_CID, false, nullptr, nsCMSMessageConstructor },
+  { &kNS_CRYPTO_HASH_CID, false, nullptr, nsCryptoHashConstructor },
+  { &kNS_CRYPTO_HMAC_CID, false, nullptr, nsCryptoHMACConstructor },
+  { &kNS_CERT_PICKER_CID, false, nullptr, nsCertPickerConstructor },
+  { &kNS_CRLMANAGER_CID, false, nullptr, nsCRLManagerConstructor },
+  { &kNS_NTLMAUTHMODULE_CID, false, nullptr, nsNTLMAuthModuleConstructor },
+  { &kNS_STREAMCIPHER_CID, false, nullptr, nsStreamCipherConstructor },
+  { &kNS_KEYMODULEOBJECT_CID, false, nullptr, nsKeyObjectConstructor },
+  { &kNS_KEYMODULEOBJECTFACTORY_CID, false, nullptr, nsKeyObjectFactoryConstructor },
+  { &kNS_DATASIGNATUREVERIFIER_CID, false, nullptr, nsDataSignatureVerifierConstructor },
+  { &kNS_CERTOVERRIDE_CID, false, nullptr, nsCertOverrideServiceConstructor },
+  { &kNS_RANDOMGENERATOR_CID, false, nullptr, nsRandomGeneratorConstructor },
+  { &kNS_RECENTBADCERTS_CID, false, nullptr, nsRecentBadCertsServiceConstructor },
+  { &kNS_SSLSTATUS_CID, false, nullptr, nsSSLStatusConstructor },
+  { &kTRANSPORTSECURITYINFO_CID, false, nullptr, TransportSecurityInfoConstructor },
+  { &kNS_NSSERRORSSERVICE_CID, false, nullptr, NSSErrorsServiceConstructor },
+  { &kNS_NSSVERSION_CID, false, nullptr, nsNSSVersionConstructor },
+  { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kNSSContracts[] = {
   { PSM_COMPONENT_CONTRACTID, &kNS_NSSCOMPONENT_CID },
   { NS_NSS_ERRORS_SERVICE_CONTRACTID, &kNS_NSSERRORSSERVICE_CID },
   { NS_NSSVERSION_CONTRACTID, &kNS_NSSVERSION_CID },
   { NS_SSLSOCKETPROVIDER_CONTRACTID, &kNS_SSLSOCKETPROVIDER_CID },
   { NS_STARTTLSSOCKETPROVIDER_CONTRACTID, &kNS_STARTTLSSOCKETPROVIDER_CID },
@@ -332,28 +320,28 @@ static const mozilla::Module::ContractID
   { NS_NTLMAUTHMODULE_CONTRACTID, &kNS_NTLMAUTHMODULE_CID },
   { NS_STREAMCIPHER_CONTRACTID, &kNS_STREAMCIPHER_CID },
   { NS_KEYMODULEOBJECT_CONTRACTID, &kNS_KEYMODULEOBJECT_CID },
   { NS_KEYMODULEOBJECTFACTORY_CONTRACTID, &kNS_KEYMODULEOBJECTFACTORY_CID },
   { NS_DATASIGNATUREVERIFIER_CONTRACTID, &kNS_DATASIGNATUREVERIFIER_CID },
   { NS_CERTOVERRIDE_CONTRACTID, &kNS_CERTOVERRIDE_CID },
   { NS_RANDOMGENERATOR_CONTRACTID, &kNS_RANDOMGENERATOR_CID },
   { NS_RECENTBADCERTS_CONTRACTID, &kNS_RECENTBADCERTS_CID },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module::CategoryEntry kNSSCategories[] = {
   { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-x509-ca-cert", "@mozilla.org/uriloader/psm-external-content-listener;1" },
   { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-x509-server-cert", "@mozilla.org/uriloader/psm-external-content-listener;1" },
   { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-x509-user-cert", "@mozilla.org/uriloader/psm-external-content-listener;1" },
   { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-x509-email-cert", "@mozilla.org/uriloader/psm-external-content-listener;1" },
   { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-pkcs7-crl", "@mozilla.org/uriloader/psm-external-content-listener;1" },
   { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-x509-crl", "@mozilla.org/uriloader/psm-external-content-listener;1" },
   { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/pkix-crl", "@mozilla.org/uriloader/psm-external-content-listener;1" },
-  { NULL }
+  { nullptr }
 };
 
 static const mozilla::Module kNSSModule = {
   mozilla::Module::kVersion,
   kNSSCIDs,
   kNSSContracts,
   kNSSCategories
 };
--- a/security/manager/ssl/src/nsNSSShutDown.h
+++ b/security/manager/ssl/src/nsNSSShutDown.h
@@ -71,17 +71,17 @@ private:
   // The number of scopes holding resources while blocked
   // showing an UI.
   int mBlockingUICounter;
 
   // Whether bringing up UI is currently forbidden
   bool mIsUIForbidden;
 
   // nullptr means "no restriction"
-  // if != nullptr, activity is only allowed on that thread
+  // if not null, activity is only allowed on that thread
   PRThread* mNSSRestrictedThread;
 };
 
 // Helper class that automatically enters/leaves the global activity state
 class nsNSSShutDownPreventionLock
 {
 public:
   nsNSSShutDownPreventionLock();
--- a/security/manager/ssl/src/nsNTLMAuthModule.cpp
+++ b/security/manager/ssl/src/nsNTLMAuthModule.cpp
@@ -218,17 +218,17 @@ LogBuf(const char *tag, const uint8_t *b
  * @param token The token to print
  * @param tokenLen length of the data in token
  */
 static void LogToken(const char *name, const void *token, uint32_t tokenLen)
 {
   if (!LOG_ENABLED())
     return;
 
-  char *b64data = PL_Base64Encode((const char *) token, tokenLen, NULL);
+  char *b64data = PL_Base64Encode((const char *) token, tokenLen, nullptr);
   if (b64data)
   {
     PR_LogPrint("%s: %s\n", name, b64data);
     PR_Free(b64data);
   }
 }
 
 #else
@@ -523,17 +523,17 @@ ParseType2Msg(const void *inBuf, uint32_
   if (NS_LIKELY(offset < offset + targetLen && offset + targetLen <= inLen)) {
     msg->targetLen = targetLen;
     msg->target = ((const uint8_t *) inBuf) + offset;
   }
   else
   {
     // Do not error out, for (conservative) backward compatibility.
     msg->targetLen = 0;
-    msg->target = NULL;
+    msg->target = nullptr;
   }
 
   // read flags
   msg->flags = ReadUint32(cursor);
 
   // read challenge
   memcpy(msg->challenge, cursor, sizeof(msg->challenge));
   cursor += sizeof(msg->challenge);
--- a/security/manager/ssl/src/nsPK11TokenDB.cpp
+++ b/security/manager/ssl/src/nsPK11TokenDB.cpp
@@ -369,18 +369,18 @@ NS_IMETHODIMP nsPK11Token::ChangePasswor
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   SECStatus rv;
   NS_ConvertUTF16toUTF8 aUtf8OldPassword(oldPassword);
   NS_ConvertUTF16toUTF8 aUtf8NewPassword(newPassword);
 
   rv = PK11_ChangePW(mSlot, 
-         (oldPassword != NULL ? const_cast<char *>(aUtf8OldPassword.get()) : NULL), 
-         (newPassword != NULL ? const_cast<char *>(aUtf8NewPassword.get()) : NULL));
+         (oldPassword ? const_cast<char *>(aUtf8OldPassword.get()) : nullptr),
+         (newPassword ? const_cast<char *>(aUtf8NewPassword.get()) : nullptr));
   return (rv == SECSuccess) ? NS_OK : NS_ERROR_FAILURE;
 }
 
 /* boolean isHardwareToken (); */
 NS_IMETHODIMP nsPK11Token::IsHardwareToken(bool *_retval)
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
@@ -442,18 +442,16 @@ NS_IMETHODIMP nsPK11TokenDB::GetInternal
   nsresult rv = NS_OK;
   PK11SlotInfo *slot = 0;
   nsCOMPtr<nsIPK11Token> token;
 
   slot = PK11_GetInternalKeySlot();
   if (!slot) { rv = NS_ERROR_FAILURE; goto done; }
 
   token = new nsPK11Token(slot);
-  if (!token) { rv = NS_ERROR_OUT_OF_MEMORY; goto done; }
-
   *_retval = token;
   NS_ADDREF(*_retval);
 
 done:
   if (slot) PK11_FreeSlot(slot);
   return rv;
 }
 
@@ -464,18 +462,16 @@ FindTokenByName(const PRUnichar* tokenNa
   nsNSSShutDownPreventionLock locker;
   nsresult rv = NS_OK;
   PK11SlotInfo *slot = 0;
   NS_ConvertUTF16toUTF8 aUtf8TokenName(tokenName);
   slot = PK11_FindSlotByName(const_cast<char*>(aUtf8TokenName.get()));
   if (!slot) { rv = NS_ERROR_FAILURE; goto done; }
 
   *_retval = new nsPK11Token(slot);
-  if (!*_retval) { rv = NS_ERROR_OUT_OF_MEMORY; goto done; }
-
   NS_ADDREF(*_retval);
 
 done:
   if (slot) PK11_FreeSlot(slot);
   return rv;
 }
 
 /* nsIEnumerator listTokens (); */
@@ -493,20 +489,17 @@ NS_IMETHODIMP nsPK11TokenDB::ListTokens(
   /* List all tokens, creating PK11Token objects and putting them
    * into the array.
    */
   list = PK11_GetAllTokens(CKM_INVALID_MECHANISM, false, false, 0);
   if (!list) { rv = NS_ERROR_FAILURE; goto done; }
 
   for (le = PK11_GetFirstSafe(list); le; le = PK11_GetNextSafe(list, le, false)) {
     nsCOMPtr<nsIPK11Token> token = new nsPK11Token(le->slot);
-    rv = token
-      ? array->AppendElement(token)
-      : NS_ERROR_OUT_OF_MEMORY;
-
+    rv = array->AppendElement(token);
     if (NS_FAILED(rv)) {
       PK11_FreeSlotListElement(list, le);
       rv = NS_ERROR_OUT_OF_MEMORY;
       goto done;
     }
   }
 
   rv = array->Enumerate(_retval);
--- a/security/manager/ssl/src/nsPKCS11Slot.cpp
+++ b/security/manager/ssl/src/nsPKCS11Slot.cpp
@@ -171,18 +171,16 @@ nsPKCS11Slot::GetFWVersion(PRUnichar **a
 NS_IMETHODIMP 
 nsPKCS11Slot::GetToken(nsIPK11Token **_retval)
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   nsCOMPtr<nsIPK11Token> token = new nsPK11Token(mSlot);
-  if (!token)
-    return NS_ERROR_OUT_OF_MEMORY;
   *_retval = token;
   NS_ADDREF(*_retval);
   return NS_OK;
 }
 
 /* readonly attribute wstring tokenName; */
 NS_IMETHODIMP 
 nsPKCS11Slot::GetTokenName(PRUnichar **aName)
@@ -214,17 +212,17 @@ nsPKCS11Slot::GetStatus(uint32_t *_retva
     return NS_ERROR_NOT_AVAILABLE;
 
   if (PK11_IsDisabled(mSlot))
     *_retval = SLOT_DISABLED;
   else if (!PK11_IsPresent(mSlot))
     *_retval = SLOT_NOT_PRESENT;
   else if (PK11_NeedLogin(mSlot) && PK11_NeedUserInit(mSlot))
     *_retval = SLOT_UNINITIALIZED;
-  else if (PK11_NeedLogin(mSlot) && !PK11_IsLoggedIn(mSlot, NULL))
+  else if (PK11_NeedLogin(mSlot) && !PK11_IsLoggedIn(mSlot, nullptr))
     *_retval = SLOT_NOT_LOGGED_IN;
   else if (PK11_NeedLogin(mSlot))
     *_retval = SLOT_LOGGED_IN;
   else
     *_retval = SLOT_READY;
   return NS_OK;
 }
 
@@ -284,64 +282,62 @@ nsPKCS11Module::GetLibName(PRUnichar **a
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   if ( mModule->dllName ) {
     *aName = ToNewUnicode(NS_ConvertUTF8toUTF16(mModule->dllName));
   } else {
-    *aName = NULL;
+    *aName = nullptr;
   }
   return NS_OK;
 }
 
 /*  nsIPKCS11Slot findSlotByName(in wstring name); */
 NS_IMETHODIMP 
 nsPKCS11Module::FindSlotByName(const PRUnichar *aName,
                                nsIPKCS11Slot **_retval)
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   char *asciiname = ToNewUTF8String(nsDependentString(aName));
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting \"%s\"\n", asciiname));
-  PK11SlotInfo *slotinfo = NULL;
+  PK11SlotInfo *slotinfo = nullptr;
   PK11SlotList *slotList = PK11_FindSlotsByNames(mModule->dllName, 
-        asciiname /* slotName */, NULL /* token Name */, false);
+        asciiname /* slotName */, nullptr /* token Name */, false);
   if (!slotList) {
     /* name must be the token name */
     slotList = PK11_FindSlotsByNames(mModule->dllName, 
-        NULL /*slot Name */, asciiname /* token Name */, false);
+        nullptr /*slot Name */, asciiname /* token Name */, false);
   }
   if (slotList) {
     /* should only be one */
     if (slotList->head && slotList->head->slot) {
       slotinfo =  PK11_ReferenceSlot(slotList->head->slot);
     }
     PK11_FreeSlotList(slotList);
   }
   if (!slotinfo) {
     // workaround - the builtin module has no name
-    if (asciiname == nullptr) {
+    if (!asciiname) {
       return NS_ERROR_FAILURE;
     } else if (nsCRT::strcmp(asciiname, "Root Certificates") == 0) {
       slotinfo = PK11_ReferenceSlot(mModule->slots[0]);
     } else {
       // give up
       nsMemory::Free(asciiname);
       return NS_ERROR_FAILURE;
     }
   } 
   nsMemory::Free(asciiname);
   nsCOMPtr<nsIPKCS11Slot> slot = new nsPKCS11Slot(slotinfo);
   PK11_FreeSlot(slotinfo);
-  if (!slot)
-    return NS_ERROR_OUT_OF_MEMORY;
   *_retval = slot;
   NS_ADDREF(*_retval);
   return NS_OK;
 }
 
 /* nsIEnumerator listSlots (); */
 NS_IMETHODIMP 
 nsPKCS11Module::ListSlots(nsIEnumerator **_retval)
@@ -384,37 +380,33 @@ nsPKCS11ModuleDB::~nsPKCS11ModuleDB()
 }
 
 /* nsIPKCS11Module getInternal (); */
 NS_IMETHODIMP 
 nsPKCS11ModuleDB::GetInternal(nsIPKCS11Module **_retval)
 {
   nsNSSShutDownPreventionLock locker;
   SECMODModule *nssMod = 
-    SECMOD_CreateModule(NULL,SECMOD_INT_NAME, NULL,SECMOD_INT_FLAGS);
+    SECMOD_CreateModule(nullptr, SECMOD_INT_NAME, nullptr, SECMOD_INT_FLAGS);
   nsCOMPtr<nsIPKCS11Module> module = new nsPKCS11Module(nssMod);
   SECMOD_DestroyModule(nssMod);
-  if (!module)
-    return NS_ERROR_OUT_OF_MEMORY;
   *_retval = module;
   NS_ADDREF(*_retval);
   return NS_OK;
 }
 
 /* nsIPKCS11Module getInternalFIPS (); */
 NS_IMETHODIMP 
 nsPKCS11ModuleDB::GetInternalFIPS(nsIPKCS11Module **_retval)
 {
   nsNSSShutDownPreventionLock locker;
   SECMODModule *nssMod = 
-    SECMOD_CreateModule(NULL, SECMOD_FIPS_NAME, NULL, SECMOD_FIPS_FLAGS);
+    SECMOD_CreateModule(nullptr, SECMOD_FIPS_NAME, nullptr, SECMOD_FIPS_FLAGS);
   nsCOMPtr<nsIPKCS11Module> module = new nsPKCS11Module(nssMod);
   SECMOD_DestroyModule(nssMod);
-  if (!module)
-    return NS_ERROR_OUT_OF_MEMORY;
   *_retval = module;
   NS_ADDREF(*_retval);
   return NS_OK;
 }
 
 /* nsIPKCS11Module findModuleByName(in wstring name); */
 NS_IMETHODIMP 
 nsPKCS11ModuleDB::FindModuleByName(const PRUnichar *aName,
@@ -423,18 +415,16 @@ nsPKCS11ModuleDB::FindModuleByName(const
   nsNSSShutDownPreventionLock locker;
   NS_ConvertUTF16toUTF8 aUtf8Name(aName);
   SECMODModule *mod =
     SECMOD_FindModule(const_cast<char *>(aUtf8Name.get()));
   if (!mod)
     return NS_ERROR_FAILURE;
   nsCOMPtr<nsIPKCS11Module> module = new nsPKCS11Module(mod);
   SECMOD_DestroyModule(mod);
-  if (!module)
-    return NS_ERROR_OUT_OF_MEMORY;
   *_retval = module;
   NS_ADDREF(*_retval);
   return NS_OK;
 }
 
 /* This is essentially the same as nsIPK11Token::findTokenByName, except
  * that it returns an nsIPKCS11Slot, which may be desired.
  */
@@ -446,18 +436,16 @@ nsPKCS11ModuleDB::FindSlotByName(const P
   nsNSSShutDownPreventionLock locker;
   NS_ConvertUTF16toUTF8 aUtf8Name(aName);
   PK11SlotInfo *slotinfo =
    PK11_FindSlotByName(const_cast<char*>(aUtf8Name.get()));
   if (!slotinfo)
     return NS_ERROR_FAILURE;
   nsCOMPtr<nsIPKCS11Slot> slot = new nsPKCS11Slot(slotinfo);
   PK11_FreeSlot(slotinfo);
-  if (!slot)
-    return NS_ERROR_OUT_OF_MEMORY;
   *_retval = slot;
   NS_ADDREF(*_retval);
   return NS_OK;
 }
 
 /* nsIEnumerator listModules (); */
 NS_IMETHODIMP 
 nsPKCS11ModuleDB::ListModules(nsIEnumerator **_retval)
--- a/security/manager/ssl/src/nsPKCS12Blob.cpp
+++ b/security/manager/ssl/src/nsPKCS12Blob.cpp
@@ -97,17 +97,17 @@ nsPKCS12Blob::SetToken(nsIPK11Token *tok
 nsresult
 nsPKCS12Blob::ImportFromFile(nsIFile *file)
 {
   nsNSSShutDownPreventionLock locker;
   nsresult rv = NS_OK;
 
   if (!mToken) {
     if (!mTokenSet) {
-      rv = SetToken(NULL); // Ask the user to pick a slot
+      rv = SetToken(nullptr); // Ask the user to pick a slot
       if (NS_FAILED(rv)) {
         handleError(PIP_PKCS12_USER_CANCELED);
         return rv;
       }
     }
   }
 
   if (!mToken) {
@@ -137,52 +137,52 @@ nsPKCS12Blob::ImportFromFile(nsIFile *fi
 nsresult
 nsPKCS12Blob::ImportFromFileHelper(nsIFile *file, 
                                    nsPKCS12Blob::ImportMode aImportMode,
                                    nsPKCS12Blob::RetryReason &aWantRetry)
 {
   nsNSSShutDownPreventionLock locker;
   nsresult rv;
   SECStatus srv = SECSuccess;
-  SEC_PKCS12DecoderContext *dcx = NULL;
+  SEC_PKCS12DecoderContext *dcx = nullptr;
   SECItem unicodePw;
 
   PK11SlotInfo *slot=nullptr;
   nsXPIDLString tokenName;
-  unicodePw.data = NULL;
+  unicodePw.data = nullptr;
   
   aWantRetry = rr_do_not_retry;
 
   if (aImportMode == im_try_zero_length_secitem)
   {
     unicodePw.len = 0;
   }
   else
   {
     // get file password (unicode)
     rv = getPKCS12FilePassword(&unicodePw);
     if (NS_FAILED(rv)) goto finish;
-    if (unicodePw.data == NULL) {
+    if (!unicodePw.data) {
       handleError(PIP_PKCS12_USER_CANCELED);
       return NS_OK;
     }
   }
   
   mToken->GetTokenName(getter_Copies(tokenName));
   {
     NS_ConvertUTF16toUTF8 tokenNameCString(tokenName);
     slot = PK11_FindSlotByName(tokenNameCString.get());
   }
   if (!slot) {
     srv = SECFailure;
     goto finish;
   }
 
   // initialize the decoder
-  dcx = SEC_PKCS12DecoderStart(&unicodePw, slot, NULL,
+  dcx = SEC_PKCS12DecoderStart(&unicodePw, slot, nullptr,
                                digest_open, digest_close,
                                digest_read, digest_write,
                                this);
   if (!dcx) {
     srv = SECFailure;
     goto finish;
   }
   // read input file and feed it to the decoder
@@ -255,17 +255,17 @@ nsPKCS12Blob::LoadCerts(const PRUnichar 
     if (NS_FAILED(rv)) {
       if (!handleError())
         return NS_ERROR_OUT_OF_MEMORY;
     }
   }
   /* Add the certs */
   for (int i=0; i<numCerts; i++) {
     strcpy(namecpy, NS_ConvertUTF16toUTF8(certNames[i]));
-    CERTCertificate *nssCert = PK11_FindCertFromNickname(namecpy, NULL);
+    CERTCertificate *nssCert = PK11_FindCertFromNickname(namecpy, nullptr);
     if (!nssCert) {
       if (!handleError())
         return NS_ERROR_FAILURE;
       else continue; /* user may request to keep going */
     }
     nsCOMPtr<nsIX509Cert> cert = nsNSSCertificate::Create(nssCert);
     CERT_DestroyCertificate(nssCert);
     if (!cert) {
@@ -285,17 +285,17 @@ isExtractable(SECKEYPrivateKey *privKey)
   SECItem value;
   bool    isExtractable = false;
   SECStatus rv;
 
   rv=PK11_ReadRawAttribute(PK11_TypePrivKey, privKey, CKA_EXTRACTABLE, &value);
   if (rv != SECSuccess) {
     return false;
   }
-  if ((value.len == 1) && (value.data != NULL)) {
+  if ((value.len == 1) && value.data) {
     isExtractable = !!(*(CK_BBOOL*)value.data);
   }
   SECITEM_FreeItem(&value, false);
   return isExtractable;
 }
   
 // nsPKCS12Blob::ExportToFile
 //
@@ -309,41 +309,41 @@ isExtractable(SECKEYPrivateKey *privKey)
 //       set appropriate error codes
 nsresult
 nsPKCS12Blob::ExportToFile(nsIFile *file, 
                            nsIX509Cert **certs, int numCerts)
 {
   nsNSSShutDownPreventionLock locker;
   nsresult rv;
   SECStatus srv = SECSuccess;
-  SEC_PKCS12ExportContext *ecx = NULL;
-  SEC_PKCS12SafeInfo *certSafe = NULL, *keySafe = NULL;
+  SEC_PKCS12ExportContext *ecx = nullptr;
+  SEC_PKCS12SafeInfo *certSafe = nullptr, *keySafe = nullptr;
   SECItem unicodePw;
   nsAutoString filePath;
   int i;
   nsCOMPtr<nsIFile> localFileRef;
   NS_ASSERTION(mToken, "Need to set the token before exporting");
   // init slot
 
   bool InformedUserNoSmartcardBackup = false;
   int numCertsExported = 0;
 
   rv = mToken->Login(true);
   if (NS_FAILED(rv)) goto finish;
   // get file password (unicode)
-  unicodePw.data = NULL;
+  unicodePw.data = nullptr;
   rv = newPKCS12FilePassword(&unicodePw);
   if (NS_FAILED(rv)) goto finish;
-  if (unicodePw.data == NULL) {
+  if (!unicodePw.data) {
     handleError(PIP_PKCS12_USER_CANCELED);
     return NS_OK;
   }
   // what about slotToUse in psm 1.x ???
   // create export context
-  ecx = SEC_PKCS12CreateExportContext(NULL, NULL, NULL /*slot*/, NULL);
+  ecx = SEC_PKCS12CreateExportContext(nullptr, nullptr, nullptr /*slot*/, nullptr);
   if (!ecx) {
     srv = SECFailure;
     goto finish;
   }
   // add password integrity
   srv = SEC_PKCS12AddPasswordIntegrity(ecx, &unicodePw, SEC_OID_SHA1);
   if (srv) goto finish;
 #if 0
@@ -388,43 +388,43 @@ nsPKCS12Blob::ExportToFile(nsIFile *file
             handleError(PIP_PKCS12_NOSMARTCARD_EXPORT);
           }
           continue;
         }
       }
     }
 
     // XXX this is why, to verify the slot is the same
-    // PK11_FindObjectForCert(nssCert, NULL, slot);
+    // PK11_FindObjectForCert(nssCert, nullptr, slot);
     // create the cert and key safes
     keySafe = SEC_PKCS12CreateUnencryptedSafe(ecx);
     if (!SEC_PKCS12IsEncryptionAllowed() || PK11_IsFIPS()) {
       certSafe = keySafe;
     } else {
       certSafe = SEC_PKCS12CreatePasswordPrivSafe(ecx, &unicodePw,
                            SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC);
     }
     if (!certSafe || !keySafe) {
       rv = NS_ERROR_FAILURE;
       goto finish;
     }
     // add the cert and key to the blob
-    srv = SEC_PKCS12AddCertAndKey(ecx, certSafe, NULL, nssCert,
+    srv = SEC_PKCS12AddCertAndKey(ecx, certSafe, nullptr, nssCert,
                                   CERT_GetDefaultCertDB(), // XXX
-                                  keySafe, NULL, true, &unicodePw,
+                                  keySafe, nullptr, true, &unicodePw,
                       SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC);
     if (srv) goto finish;
     // cert was dup'ed, so release it
     ++numCertsExported;
   }
   
   if (!numCertsExported) goto finish;
   
   // prepare the instance to write to an export file
-  this->mTmpFile = NULL;
+  this->mTmpFile = nullptr;
   file->GetPath(filePath);
   // Use the nsCOMPtr var localFileRef so that
   // the reference to the nsIFile we create gets released as soon as
   // we're out of scope, ie when this function exits.
   if (filePath.RFind(".p12", true, -1, 4) < 0) {
     // We're going to add the .p12 extension to the file name just like
     // Communicator used to.  We create a new nsIFile and initialize
     // it with the new patch.
@@ -444,17 +444,17 @@ nsPKCS12Blob::ExportToFile(nsIFile *file
 finish:
   if (NS_FAILED(rv) || srv != SECSuccess) {
     handleError(PIP_PKCS12_BACKUP_FAILED);
   }
   if (ecx)
     SEC_PKCS12DestroyExportContext(ecx);
   if (this->mTmpFile) {
     PR_Close(this->mTmpFile);
-    this->mTmpFile = NULL;
+    this->mTmpFile = nullptr;
   }
   SECITEM_ZfreeItem(&unicodePw, false);
   return rv;
 }
 
 ///////////////////////////////////////////////////////////////////////
 //
 //  private members
@@ -466,17 +466,17 @@ finish:
 // For the NSS PKCS#12 library, must convert PRUnichars (shorts) to
 // a buffer of octets.  Must handle byte order correctly.
 // TODO: Is there a mozilla way to do this?  In the string lib?
 void
 nsPKCS12Blob::unicodeToItem(const PRUnichar *uni, SECItem *item)
 {
   int len = 0;
   while (uni[len++] != 0);
-  SECITEM_AllocItem(NULL, item, sizeof(PRUnichar) * len);
+  SECITEM_AllocItem(nullptr, item, sizeof(PRUnichar) * len);
 #ifdef IS_LITTLE_ENDIAN
   int i = 0;
   for (i=0; i<len; i++) {
     item->data[2*i  ] = (unsigned char )(uni[i] << 8);
     item->data[2*i+1] = (unsigned char )(uni[i]);
   }
 #else
   memcpy(item->data, uni, item->len);
--- a/security/manager/ssl/src/nsPKCS12Blob.h
+++ b/security/manager/ssl/src/nsPKCS12Blob.h
@@ -10,20 +10,18 @@
 #include "nsIFile.h"
 #include "nsIPK11TokenDB.h"
 #include "nsNSSHelper.h"
 #include "nsIPK11Token.h"
 #include "nsIMutableArray.h"
 
 #include "nss.h"
 
-extern "C" {
 #include "pkcs12.h"
 #include "p12plcy.h"
-}
 
 class nsIX509Cert;
 
 //
 // nsPKCS12Blob
 //
 // Class for importing/exporting PKCS#12 blobs
 //
--- a/security/manager/ssl/src/nsProtectedAuthThread.cpp
+++ b/security/manager/ssl/src/nsProtectedAuthThread.cpp
@@ -1,15 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "pk11func.h"
+#include "mozilla/RefPtr.h"
 #include "nsCOMPtr.h"
-#include "nsAutoPtr.h"
 #include "PSMRunnable.h"
 #include "nsString.h"
 #include "nsReadableUtils.h"
 #include "nsPKCS11Slot.h"
 #include "nsProtectedAuthThread.h"
 
 using namespace mozilla;
 using namespace mozilla::psm;
@@ -79,23 +79,21 @@ NS_IMETHODIMP nsProtectedAuthThread::Get
     // Get token name
     CopyUTF8toUTF16(nsDependentCString(PK11_GetTokenName(mSlot)), _retval);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP nsProtectedAuthThread::GetSlot(nsIPKCS11Slot **_retval)
 {
-    nsRefPtr<nsPKCS11Slot> slot;
+    RefPtr<nsPKCS11Slot> slot;
     {
         MutexAutoLock lock(mMutex);
         slot = new nsPKCS11Slot(mSlot);
     }
-    if (!slot)
-      return NS_ERROR_OUT_OF_MEMORY;
 
     return CallQueryInterface (slot.get(), _retval);
 }
 
 void nsProtectedAuthThread::SetParams(PK11SlotInfo* aSlot)
 {
     MutexAutoLock lock(mMutex);
 
--- a/security/manager/ssl/src/nsRecentBadCerts.cpp
+++ b/security/manager/ssl/src/nsRecentBadCerts.cpp
@@ -1,24 +1,23 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  *
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsRecentBadCerts.h"
 #include "nsIX509Cert.h"
+#include "mozilla/RefPtr.h"
 #include "nsSSLStatus.h"
 #include "nsCOMPtr.h"
-#include "nsAutoPtr.h"
 #include "nsNSSCertificate.h"
 #include "nsCRT.h"
 #include "nsPromiseFlatString.h"
 #include "nsStringBuffer.h"
-#include "nsAutoPtr.h"
 #include "nspr.h"
 #include "pk11pub.h"
 #include "certdb.h"
 #include "sechash.h"
 
 #include "nsNSSCleaner.h"
 
 using namespace mozilla;
@@ -48,19 +47,17 @@ NS_IMETHODIMP
 nsRecentBadCertsService::GetRecentBadCert(const nsAString & aHostNameWithPort, 
                                           nsISSLStatus **aStatus)
 {
   NS_ENSURE_ARG_POINTER(aStatus);
   if (!aHostNameWithPort.Length())
     return NS_ERROR_INVALID_ARG;
 
   *aStatus = nullptr;
-  nsRefPtr<nsSSLStatus> status = new nsSSLStatus();
-  if (!status)
-    return NS_ERROR_OUT_OF_MEMORY;
+  RefPtr<nsSSLStatus> status(new nsSSLStatus());
 
   SECItem foundDER;
   foundDER.len = 0;
   foundDER.data = nullptr;
 
   bool isDomainMismatch = false;
   bool isNotValidAtThisTime = false;
   bool isUntrusted = false;
--- a/security/manager/ssl/src/nsSDR.cpp
+++ b/security/manager/ssl/src/nsSDR.cpp
@@ -53,17 +53,16 @@ Encrypt(unsigned char * data, int32_t da
   nsresult rv = NS_OK;
   PK11SlotInfo *slot = 0;
   PK11SlotInfoCleaner tmpSlotCleaner(slot);
   SECItem keyid;
   SECItem request;
   SECItem reply;
   SECStatus s;
   nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
-  if (!ctx) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; }
 
   slot = PK11_GetInternalKeySlot();
   if (!slot) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; }
 
   /* Make sure token is initialized. */
   rv = setPassword(slot, ctx);
   if (NS_FAILED(rv))
     goto loser;
@@ -96,17 +95,16 @@ Decrypt(unsigned char * data, int32_t da
   nsNSSShutDownPreventionLock locker;
   nsresult rv = NS_OK;
   PK11SlotInfo *slot = 0;
   PK11SlotInfoCleaner tmpSlotCleaner(slot);
   SECStatus s;
   SECItem request;
   SECItem reply;
   nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
-  if (!ctx) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; }
 
   *result = 0;
   *_retval = 0;
 
   /* Find token with SDR key */
   slot = PK11_GetInternalKeySlot();
   if (!slot) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; }
 
@@ -135,17 +133,17 @@ loser:
 NS_IMETHODIMP nsSecretDecoderRing::
 EncryptString(const char *text, char **_retval)
 {
   nsNSSShutDownPreventionLock locker;
   nsresult rv = NS_OK;
   unsigned char *encrypted = 0;
   int32_t eLen;
 
-  if (text == nullptr || _retval == nullptr) {
+  if (!text || !_retval) {
     rv = NS_ERROR_INVALID_POINTER;
     goto loser;
   }
 
   rv = Encrypt((unsigned char *)text, PL_strlen(text), &encrypted, &eLen);
   if (rv != NS_OK) { goto loser; }
 
   rv = encode(encrypted, eLen, _retval);
@@ -163,17 +161,17 @@ DecryptString(const char *crypt, char **
   nsNSSShutDownPreventionLock locker;
   nsresult rv = NS_OK;
   char *r = 0;
   unsigned char *decoded = 0;
   int32_t decodedLen;
   unsigned char *decrypted = 0;
   int32_t decryptedLen;
 
-  if (crypt == nullptr || _retval == nullptr) {
+  if (!crypt || !_retval) {
     rv = NS_ERROR_INVALID_POINTER;
     goto loser;
   }
 
   rv = decode(crypt, &decoded, &decodedLen);
   if (rv != NS_OK) goto loser;
 
   rv = Decrypt(decoded, decodedLen, &decrypted, &decryptedLen);
@@ -292,17 +290,17 @@ SetWindow(nsISupports *w)
 
 // Support routines
 
 nsresult nsSecretDecoderRing::
 encode(const unsigned char *data, int32_t dataLen, char **_retval)
 {
   nsresult rv = NS_OK;
 
-  char *result = PL_Base64Encode((const char *)data, dataLen, NULL);
+  char *result = PL_Base64Encode((const char *)data, dataLen, nullptr);
   if (!result) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; }
 
   *_retval = NS_strdup(result);
   PR_DELETE(result);
   if (!*_retval) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; }
 
 loser:
   return rv;
@@ -316,16 +314,16 @@ decode(const char *data, unsigned char *
   int adjust = 0;
 
   /* Compute length adjustment */
   if (data[len-1] == '=') {
     adjust++;
     if (data[len-2] == '=') adjust++;
   }
 
-  *result = (unsigned char *)PL_Base64Decode(data, len, NULL);
+  *result = (unsigned char *)PL_Base64Decode(data, len, nullptr);
   if (!*result) { rv = NS_ERROR_ILLEGAL_VALUE; goto loser; }
 
   *_retval = (len*3)/4 - adjust;
 
 loser:
   return rv;
 }
--- a/security/manager/ssl/src/nsSSLStatus.h
+++ b/security/manager/ssl/src/nsSSLStatus.h
@@ -3,18 +3,17 @@
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef _NSSSLSTATUS_H
 #define _NSSSLSTATUS_H
 
 #include "nsISSLStatus.h"
-
-#include "nsAutoPtr.h"
+#include "nsCOMPtr.h"
 #include "nsXPIDLString.h"
 #include "nsIX509Cert.h"
 #include "nsISerializable.h"
 #include "nsIClassInfo.h"
 
 class nsSSLStatus
   : public nsISSLStatus
   , public nsISerializable
--- a/security/manager/ssl/src/nsSmartCardMonitor.cpp
+++ b/security/manager/ssl/src/nsSmartCardMonitor.cpp
@@ -84,21 +84,18 @@ SmartCardThreadList::Remove(SECMODModule
 }
 
 // adopts the thread passwd to it. Starts the thread as well
 nsresult
 SmartCardThreadList::Add(SmartCardMonitoringThread *thread)
 {
   SmartCardThreadEntry *current = new SmartCardThreadEntry(thread, head, nullptr,
                                                            &head);
-  if (current) {  
-     // OK to forget current here, it's on the list
-    return thread->Start();
-  }
-  return NS_ERROR_OUT_OF_MEMORY;
+  // OK to forget current here, it's on the list
+  return thread->Start();
 }
 
 
 // We really should have a Unity PL Hash function...
 static PLHashNumber
 unity(const void *key) { return PLHashNumber(NS_PTR_TO_INT32(key)); }
 
 SmartCardMonitoringThread::SmartCardMonitoringThread(SECMODModule *module_)
@@ -270,17 +267,17 @@ void SmartCardMonitoringThread::Execute(
                   PK11_GetTokenName(sle->slot), PK11_GetSlotSeries(sle->slot));
     }
     PK11_FreeSlotList(sl);
   }
 
   // loop starts..
   do {
     slot = SECMOD_WaitForAnyTokenEvent(mModule, 0, PR_SecondsToInterval(1)  );
-    if (slot == nullptr) {
+    if (!slot) {
       break;
     }
 
     // now we have a potential insertion or removal event, see if the slot
     // is present to determine which it is...
     if (PK11_IsPresent(slot)) {
       // insertion
       CK_SLOT_ID slotID = PK11_GetSlotID(slot);
--- a/security/manager/ssl/src/nsStreamCipher.cpp
+++ b/security/manager/ssl/src/nsStreamCipher.cpp
@@ -5,17 +5,17 @@
 #include "nsIKeyModule.h"
 #include "nsStreamCipher.h"
 #include "nsStreamUtils.h"
 #include "base64.h"
 
 NS_IMPL_ISUPPORTS1(nsStreamCipher, nsIStreamCipher)
 
 nsStreamCipher::nsStreamCipher()
-  : mContext(NULL)
+  : mContext(nullptr)
 {
 }
 
 nsStreamCipher::~nsStreamCipher()
 {
   if (mContext)
     PK11_DestroyContext(mContext, true /* free sub-objects */);
 }
@@ -84,18 +84,16 @@ NS_IMETHODIMP nsStreamCipher::InitWithIV
 }
 
 NS_IMETHODIMP nsStreamCipher::Update(const uint8_t *aData, uint32_t aLen)
 {
   if (!mContext)
     return NS_ERROR_NOT_INITIALIZED;
 
   unsigned char* output = new unsigned char[aLen];
-  if (!output)
-    return NS_ERROR_OUT_OF_MEMORY;
   unsigned char* input = (unsigned char*)aData;
   
   int32_t setLen;
 
 #ifdef DEBUG
   SECStatus rv =
 #endif
     PK11_CipherOp(mContext, output, &setLen, aLen, input, aLen);
@@ -127,18 +125,16 @@ NS_IMETHODIMP nsStreamCipher::UpdateFrom
   if (!mContext)
     return NS_ERROR_NOT_INITIALIZED;
 
   const nsCString& flatInput = PromiseFlatCString(aInput);
   unsigned char* input = (unsigned char*)flatInput.get();
   uint32_t len = aInput.Length();
 
   unsigned char* output = new unsigned char[len];
-  if (!output)
-    return NS_ERROR_OUT_OF_MEMORY;
 
   int32_t setLen;
 
 #ifdef DEBUG
   SECStatus rv =
 #endif
     PK11_CipherOp(mContext, output, &setLen, len, input, len);
   NS_ASSERTION(rv == SECSuccess, "failed to encrypt");
@@ -168,24 +164,17 @@ NS_IMETHODIMP nsStreamCipher::Finish(boo
 }
 
 NS_IMETHODIMP nsStreamCipher::Discard(int32_t aLen)
 {
   if (!mContext)
     return NS_ERROR_NOT_INITIALIZED;
 
   unsigned char* output = new unsigned char[aLen];
-  if (!output)
-    return NS_ERROR_OUT_OF_MEMORY;
-
   unsigned char* input = new unsigned char[aLen];
-  if (!input) {
-    delete [] output;
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
 
   int32_t setLen;
 
 #ifdef DEBUG
   SECStatus rv =
 #endif
     PK11_CipherOp(mContext, output, &setLen, aLen, input, aLen);
   NS_ASSERTION(rv == SECSuccess, "failed to encrypt");
--- a/security/manager/ssl/src/nsUsageArrayHelper.cpp
+++ b/security/manager/ssl/src/nsUsageArrayHelper.cpp
@@ -9,19 +9,19 @@
 #include "nsDateTimeFormatCID.h"
 #include "nsComponentManagerUtils.h"
 #include "nsReadableUtils.h"
 #include "nsNSSCertificate.h"
 
 #include "nspr.h"
 #include "nsNSSCertHeader.h"
 
-extern "C" {
 #include "secerr.h"
-}
+
+using namespace mozilla;
 
 static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
 
 nsUsageArrayHelper::nsUsageArrayHelper(CERTCertificate *aCert)
 :mCert(aCert)
 {
   nsNSSShutDownPreventionLock locker;
   defaultcertdb = CERT_GetDefaultCertDB();
@@ -161,41 +161,41 @@ if (!nsNSSComponent::globalConstFlagUseP
 			    certificateUsageSSLClient |
 			    certificateUsageSSLServer |
 			    certificateUsageSSLServerWithStepUp |
 			    certificateUsageEmailSigner |
 			    certificateUsageEmailRecipient |
 			    certificateUsageObjectSigner |
 			    certificateUsageSSLCA |
 			    certificateUsageStatusResponder,
-			    NULL, &usages);
+			    nullptr, &usages);
   err = PR_GetError();
 }
 else {
   nsresult nsrv;
   nsCOMPtr<nsINSSComponent> inss = do_GetService(kNSSComponentCID, &nsrv);
   if (!inss)
     return nsrv;
-  nsRefPtr<nsCERTValInParamWrapper> survivingParams;
+  RefPtr<nsCERTValInParamWrapper> survivingParams;
   if (localOnly)
     nsrv = inss->GetDefaultCERTValInParamLocalOnly(survivingParams);
   else
     nsrv = inss->GetDefaultCERTValInParam(survivingParams);
   
   if (NS_FAILED(nsrv))
     return nsrv;
 
   CERTValOutParam cvout[2];
   cvout[0].type = cert_po_usages;
   cvout[0].value.scalar.usages = 0;
   cvout[1].type = cert_po_end;
   
   CERT_PKIXVerifyCert(mCert, certificateUsageCheckAllUsages,
                       survivingParams->GetRawPointerForNSS(),
-                      cvout, NULL);
+                      cvout, nullptr);
   err = PR_GetError();
   usages = cvout[0].value.scalar.usages;
 }
 
   // The following list of checks must be < max_returned_out_array_size
   
   check(suffix, usages & certificateUsageSSLClient, count, outUsages);
   check(suffix, usages & certificateUsageSSLServer, count, outUsages);