Bug 1258298 - Switch more Scoped.h templates in PSM to UniquePtr equivalents. draft
authorCykesiopka <cykesiopka.bmo@gmail.com>
Thu, 24 Mar 2016 18:30:37 -0700
changeset 344637 ee1a84681578ae2e30476d2a717f38da19f07ec1
parent 344635 517f25117d11ba60dd0b2eb135eff6e89f6c6e68
child 517011 0880b257bd0ffb1c6640dabdebb138b8272667b0
push id13888
push usercykesiopka.bmo@gmail.com
push dateFri, 25 Mar 2016 01:30:54 +0000
bugs1258298
milestone48.0a1
Bug 1258298 - Switch more Scoped.h templates in PSM to UniquePtr equivalents. MozReview-Commit-ID: 8VOhiuNOlBX
security/certverifier/OCSPRequestor.cpp
security/manager/ssl/ScopedNSSTypes.h
security/manager/ssl/nsKeyModule.cpp
security/manager/ssl/nsKeyModule.h
security/manager/ssl/nsNSSCertificate.cpp
security/manager/ssl/nsNSSIOLayer.cpp
security/manager/ssl/tests/unit/tlsserver/cmd/BadCertServer.cpp
security/manager/ssl/tests/unit/tlsserver/cmd/GenerateOCSPResponse.cpp
security/manager/ssl/tests/unit/tlsserver/lib/OCSPCommon.cpp
security/manager/ssl/tests/unit/tlsserver/lib/TLSServer.cpp
security/manager/ssl/tests/unit/tlsserver/lib/TLSServer.h
--- a/security/certverifier/OCSPRequestor.cpp
+++ b/security/certverifier/OCSPRequestor.cpp
@@ -3,18 +3,18 @@
 /* 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 "OCSPRequestor.h"
 
 #include <limits>
 
+#include "ScopedNSSTypes.h"
 #include "mozilla/Base64.h"
-#include "mozilla/Scoped.h"
 #include "nsIURLParser.h"
 #include "nsNSSCallbacks.h"
 #include "nsNetCID.h"
 #include "nsServiceManagerUtils.h"
 #include "secerr.h"
 
 extern mozilla::LazyLogModule gCertVerifierLog;
 
@@ -27,23 +27,23 @@ ReleaseHttpServerSession(nsNSSHttpServer
 }
 
 void
 ReleaseHttpRequestSession(nsNSSHttpRequestSession* httpRequestSession)
 {
   httpRequestSession->Release();
 }
 
-MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedHTTPServerSession,
-                                          nsNSSHttpServerSession,
-                                          ReleaseHttpServerSession)
+MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueHTTPServerSession,
+                                      nsNSSHttpServerSession,
+                                      ReleaseHttpServerSession)
 
-MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedHTTPRequestSession,
-                                          nsNSSHttpRequestSession,
-                                          ReleaseHttpRequestSession)
+MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueHTTPRequestSession,
+                                      nsNSSHttpRequestSession,
+                                      ReleaseHttpRequestSession)
 
 } // namespace mozilla
 
 namespace mozilla { namespace psm {
 
 static nsresult
 AppendEscapedBase64Item(const SECItem* encodedRequest, nsACString& path)
 {
@@ -137,17 +137,17 @@ DoOCSPRequest(PLArenaPool* arena, const 
              static_cast<nsACString_internal::size_type>(hostnameLen));
 
   SEC_HTTP_SERVER_SESSION serverSessionPtr = nullptr;
   Result rv = nsNSSHttpInterface::createSessionFcn(
     hostname.BeginReading(), static_cast<uint16_t>(port), &serverSessionPtr);
   if (rv != Success) {
     return rv;
   }
-  ScopedHTTPServerSession serverSession(
+  UniqueHTTPServerSession serverSession(
     reinterpret_cast<nsNSSHttpServerSession*>(serverSessionPtr));
 
   nsAutoCString path;
   if (pathLen > 0) {
     path.Assign(url + pathPos, static_cast<nsAutoCString::size_type>(pathLen));
   } else {
     path.Assign("/");
   }
@@ -168,17 +168,17 @@ DoOCSPRequest(PLArenaPool* arena, const 
 
   SEC_HTTP_REQUEST_SESSION requestSessionPtr;
   rv = nsNSSHttpInterface::createFcn(serverSession.get(), "http", path.get(),
                                      method.get(), timeout, &requestSessionPtr);
   if (rv != Success) {
     return rv;
   }
 
-  ScopedHTTPRequestSession requestSession(
+  UniqueHTTPRequestSession requestSession(
     reinterpret_cast<nsNSSHttpRequestSession*>(requestSessionPtr));
 
   if (!useGET) {
     rv = nsNSSHttpInterface::setPostDataFcn(
       requestSession.get(), reinterpret_cast<char*>(encodedRequest->data),
       encodedRequest->len, "application/ocsp-request");
     if (rv != Success) {
       return rv;
--- a/security/manager/ssl/ScopedNSSTypes.h
+++ b/security/manager/ssl/ScopedNSSTypes.h
@@ -324,16 +324,19 @@ struct name##DeletePolicy \
 { \
   void operator()(Type* aValue) { Deleter(aValue); } \
 }; \
 typedef UniquePtr<Type, name##DeletePolicy> name;
 
 MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueCERTCertificate,
                                       CERTCertificate,
                                       CERT_DestroyCertificate)
+MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueCERTCertificateList,
+                                      CERTCertificateList,
+                                      CERT_DestroyCertificateList)
 MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueCERTCertificatePolicies,
                                       CERTCertificatePolicies,
                                       CERT_DestroyCertificatePoliciesExtension)
 MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueCERTCertList,
                                       CERTCertList,
                                       CERT_DestroyCertList)
 MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueCERTCertNicknames,
                                       CERTCertNicknames,
@@ -353,24 +356,36 @@ MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(Un
                                       NSS_CMSSignedData_Destroy)
 
 MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniquePK11SlotInfo,
                                       PK11SlotInfo,
                                       PK11_FreeSlot)
 MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniquePK11SlotList,
                                       PK11SlotList,
                                       PK11_FreeSlotList)
+MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniquePK11SymKey,
+                                      PK11SymKey,
+                                      PK11_FreeSymKey)
 
 MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniquePLArenaPool,
                                       PLArenaPool,
                                       internal::PORT_FreeArena_false)
+MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniquePORTString,
+                                      char,
+                                      PORT_Free);
+MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniquePRFileDesc,
+                                      PRFileDesc,
+                                      PR_Close)
 
 MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueSECItem,
                                       SECItem,
                                       internal::SECITEM_FreeItem_true)
+MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueSECKEYPrivateKey,
+                                      SECKEYPrivateKey,
+                                      SECKEY_DestroyPrivateKey)
 MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueSECKEYPublicKey,
                                       SECKEYPublicKey,
                                       SECKEY_DestroyPublicKey)
 MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueSECMODModule,
                                       SECMODModule,
                                       SECMOD_DestroyModule)
 
 MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniqueVFYContext,
--- a/security/manager/ssl/nsKeyModule.cpp
+++ b/security/manager/ssl/nsKeyModule.cpp
@@ -49,17 +49,17 @@ nsKeyObject::InitKey(int16_t aAlgorithm,
     return NS_ERROR_INVALID_ARG;
   }
 
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
-  mSymKey = aKey;
+  mSymKey.reset(aKey);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsKeyObject::GetKeyObj(PK11SymKey** _retval)
 {
   if (!_retval) {
     return NS_ERROR_INVALID_ARG;
@@ -71,17 +71,17 @@ nsKeyObject::GetKeyObj(PK11SymKey** _ret
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   if (!mSymKey) {
     return NS_ERROR_NOT_INITIALIZED;
   }
 
-  *_retval = mSymKey;
+  *_retval = mSymKey.get();
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsKeyObject::GetType(int16_t *_retval)
 {
   if (!_retval) {
     return NS_ERROR_INVALID_ARG;
@@ -137,23 +137,23 @@ nsKeyObjectFactory::KeyFromString(int16_
   keyItem.data = (unsigned char*)flatKey.get();
   keyItem.len = flatKey.Length();
 
   ScopedPK11SlotInfo slot(PK11_GetBestSlot(cipherMech, nullptr));
   if (!slot) {
     return NS_ERROR_FAILURE;
   }
 
-  ScopedPK11SymKey symKey(PK11_ImportSymKey(slot, cipherMech,
+  UniquePK11SymKey symKey(PK11_ImportSymKey(slot.get(), cipherMech,
                                             PK11_OriginUnwrap, cipherOperation,
                                             &keyItem, nullptr));
   if (!symKey) {
     return NS_ERROR_FAILURE;
   }
 
-  rv = key->InitKey(aAlgorithm, symKey.forget());
+  rv = key->InitKey(aAlgorithm, symKey.release());
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   key.swap(*_retval);
   return NS_OK;
 }
--- a/security/manager/ssl/nsKeyModule.h
+++ b/security/manager/ssl/nsKeyModule.h
@@ -29,17 +29,17 @@ public:
   NS_DECL_NSIKEYOBJECT
 
 private:
   ~nsKeyObject();
 
   // Disallow copy constructor
   nsKeyObject(nsKeyObject&);
 
-  ScopedPK11SymKey mSymKey;
+  UniquePK11SymKey mSymKey;
 
   virtual void virtualDestroyNSSReference() override;
   void destructorSafeDestroyNSSReference();
 };
 
 
 class nsKeyObjectFactory final : public nsIKeyObjectFactory
                                , public nsNSSShutDownObject
--- a/security/manager/ssl/nsNSSCertificate.cpp
+++ b/security/manager/ssl/nsNSSCertificate.cpp
@@ -1188,21 +1188,22 @@ nsNSSCertificate::ExportAsCMS(uint32_t c
       chainMode == nsIX509Cert::CMS_CHAIN_MODE_CertChainWithRoot) {
     ScopedCERTCertificate issuerCert(
         CERT_FindCertIssuer(mCert.get(), PR_Now(), certUsageAnyCA));
     // the issuerCert of a self signed root is the cert itself,
     // so make sure we're not adding duplicates, again
     if (issuerCert && issuerCert != mCert.get()) {
       bool includeRoot =
         (chainMode == nsIX509Cert::CMS_CHAIN_MODE_CertChainWithRoot);
-      ScopedCERTCertificateList certChain(
+      UniqueCERTCertificateList certChain(
           CERT_CertChainFromCert(issuerCert, certUsageAnyCA, includeRoot));
       if (certChain) {
-        if (NSS_CMSSignedData_AddCertList(sigd.get(), certChain) == SECSuccess) {
-          certChain.forget();
+        if (NSS_CMSSignedData_AddCertList(sigd.get(), certChain.get())
+              == SECSuccess) {
+          Unused << certChain.release();
         }
         else {
           MOZ_LOG(gPIPNSSLog, LogLevel::Debug,
                  ("nsNSSCertificate::ExportAsCMS - can't add chain\n"));
           return NS_ERROR_FAILURE;
         }
       }
       else {
--- a/security/manager/ssl/nsNSSIOLayer.cpp
+++ b/security/manager/ssl/nsNSSIOLayer.cpp
@@ -2089,17 +2089,17 @@ nsNSS_SSLGetClientAuthData(void* arg, PR
 }
 
 void
 ClientAuthDataRunnable::RunOnTargetThread()
 {
   PLArenaPool* arena = nullptr;
   char** caNameStrings;
   ScopedCERTCertificate cert;
-  ScopedSECKEYPrivateKey privKey;
+  UniqueSECKEYPrivateKey privKey;
   ScopedCERTCertList certList;
   CERTCertListNode* node;
   UniqueCERTCertNicknames nicknames;
   int keyError = 0; // used for private key retrieval error
   SSM_UserCertChoice certChoice;
   int32_t NumberOfCerts = 0;
   void* wincx = mSocketInfo;
   nsresult rv;
@@ -2111,23 +2111,23 @@ ClientAuthDataRunnable::RunOnTargetThrea
   // the client cert UI and/or search of the user's past cert decisions.
   if (socketClientCert) {
     cert = socketClientCert->GetCert();
     if (!cert) {
       goto loser;
     }
 
     // Get the private key
-    privKey = PK11_FindKeyByAnyCert(cert.get(), wincx);
+    privKey.reset(PK11_FindKeyByAnyCert(cert.get(), wincx));
     if (!privKey) {
       goto loser;
     }
 
     *mPRetCert = cert.forget();
-    *mPRetKey = privKey.forget();
+    *mPRetKey = privKey.release();
     mRV = SECSuccess;
     return;
   }
 
   // create caNameStrings
   arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   if (!arena) {
     goto loser;
@@ -2175,17 +2175,17 @@ ClientAuthDataRunnable::RunOnTargetThrea
     }
 
     ScopedCERTCertificate 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
-      privKey = PK11_FindKeyByAnyCert(node->cert, wincx);
+      privKey.reset(PK11_FindKeyByAnyCert(node->cert, wincx));
       if (privKey) {
         if (hasExplicitKeyUsageNonRepudiation(node->cert)) {
           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 {
@@ -2200,17 +2200,17 @@ ClientAuthDataRunnable::RunOnTargetThrea
         goto loser;
       }
 
       node = CERT_LIST_NEXT(node);
     }
 
     if (!cert && low_prio_nonrep_cert) {
       cert = low_prio_nonrep_cert.forget();
-      privKey = PK11_FindKeyByAnyCert(cert.get(), wincx);
+      privKey.reset(PK11_FindKeyByAnyCert(cert.get(), wincx));
     }
 
     if (!cert) {
       goto noCert;
     }
   } else { // Not Auto => ask
     // Get the SSL Certificate
 
@@ -2424,17 +2424,17 @@ ClientAuthDataRunnable::RunOnTargetThrea
 
     if (canceled) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; }
 
     if (!cert) {
       goto loser;
     }
 
     // go get the private key
-    privKey = PK11_FindKeyByAnyCert(cert.get(), wincx);
+    privKey.reset(PK11_FindKeyByAnyCert(cert.get(), wincx));
     if (!privKey) {
       keyError = PR_GetError();
       if (keyError == SEC_ERROR_BAD_PASSWORD) {
         // problem with password: bail
         goto loser;
       } else {
         goto noCert;
       }
@@ -2450,17 +2450,17 @@ loser:
 done:
   int error = PR_GetError();
 
   if (arena) {
     PORT_FreeArena(arena, false);
   }
 
   *mPRetCert = cert.forget();
-  *mPRetKey = privKey.forget();
+  *mPRetKey = privKey.release();
 
   if (mRV == SECFailure) {
     mErrorCodeToReport = error;
   }
 }
 
 static PRFileDesc*
 nsSSLIOLayerImportFD(PRFileDesc* fd,
--- a/security/manager/ssl/tests/unit/tlsserver/cmd/BadCertServer.cpp
+++ b/security/manager/ssl/tests/unit/tlsserver/cmd/BadCertServer.cpp
@@ -78,21 +78,22 @@ const BadCertHost sBadCertHosts[] =
   { nullptr, nullptr }
 };
 
 int32_t
 DoSNISocketConfigBySubjectCN(PRFileDesc* aFd, const SECItem* aSrvNameArr,
                              uint32_t aSrvNameArrSize)
 {
   for (uint32_t i = 0; i < aSrvNameArrSize; i++) {
-    ScopedPORTString name((char*)PORT_ZAlloc(aSrvNameArr[i].len + 1));
+    UniquePORTString name(
+      static_cast<char*>(PORT_ZAlloc(aSrvNameArr[i].len + 1)));
     if (name) {
-      PORT_Memcpy(name, aSrvNameArr[i].data, aSrvNameArr[i].len);
-      if (SECSuccess == ConfigSecureServerWithNamedCert(aFd, name,
-                                                        nullptr, nullptr)) {
+      PORT_Memcpy(name.get(), aSrvNameArr[i].data, aSrvNameArr[i].len);
+      if (ConfigSecureServerWithNamedCert(aFd, name.get(), nullptr, nullptr)
+            == SECSuccess) {
         return 0;
       }
     }
   }
 
   return SSL_SNI_SEND_ALERT;
 }
 
--- a/security/manager/ssl/tests/unit/tlsserver/cmd/GenerateOCSPResponse.cpp
+++ b/security/manager/ssl/tests/unit/tlsserver/cmd/GenerateOCSPResponse.cpp
@@ -89,24 +89,24 @@ StringToOCSPResponseType(const char* res
 bool
 WriteResponse(const char* filename, const SECItem* item)
 {
   if (!filename || !item || !item->data) {
     PR_fprintf(PR_STDERR, "invalid parameters to WriteResponse");
     return false;
   }
 
-  ScopedPRFileDesc outFile(PR_Open(filename,
+  UniquePRFileDesc outFile(PR_Open(filename,
                                    PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
                                    0644));
   if (!outFile) {
     PrintPRError("cannot open file for writing");
     return false;
   }
-  int32_t rv = PR_Write(outFile, item->data, item->len);
+  int32_t rv = PR_Write(outFile.get(), item->data, item->len);
   if (rv < 0 || (uint32_t) rv != item->len) {
     PrintPRError("File write failure");
     return false;
   }
 
   return true;
 }
 
--- a/security/manager/ssl/tests/unit/tlsserver/lib/OCSPCommon.cpp
+++ b/security/manager/ssl/tests/unit/tlsserver/lib/OCSPCommon.cpp
@@ -24,25 +24,25 @@ TestKeyPair* CreateTestKeyPair(const Tes
 using namespace mozilla;
 using namespace mozilla::pkix;
 using namespace mozilla::pkix::test;
 using namespace mozilla::test;
 
 static TestKeyPair*
 CreateTestKeyPairFromCert(CERTCertificate& cert)
 {
-  ScopedSECKEYPrivateKey privateKey(PK11_FindKeyByAnyCert(&cert, nullptr));
+  UniqueSECKEYPrivateKey privateKey(PK11_FindKeyByAnyCert(&cert, nullptr));
   if (!privateKey) {
     return nullptr;
   }
   ScopedSECKEYPublicKey publicKey(CERT_ExtractPublicKey(&cert));
   if (!publicKey) {
     return nullptr;
   }
-  return CreateTestKeyPair(RSA_PKCS1(), *publicKey, privateKey.forget());
+  return CreateTestKeyPair(RSA_PKCS1(), *publicKey, privateKey.release());
 }
 
 SECItemArray *
 GetOCSPResponseForType(OCSPResponseType aORT, CERTCertificate *aCert,
                        PLArenaPool *aArena, const char *aAdditionalCertName)
 {
   if (aORT == ORTNone) {
     if (gDebugLevel >= DEBUG_WARNINGS) {
--- a/security/manager/ssl/tests/unit/tlsserver/lib/TLSServer.cpp
+++ b/security/manager/ssl/tests/unit/tlsserver/lib/TLSServer.cpp
@@ -69,31 +69,31 @@ template <size_t N>
 SECStatus
 ReadFileToBuffer(const char* basePath, const char* filename, char (&buf)[N])
 {
   static_assert(N > 0, "input buffer too small for ReadFileToBuffer");
   if (snprintf(buf, N - 1, "%s/%s", basePath, filename) == 0) {
     PrintPRError("snprintf failed");
     return SECFailure;
   }
-  ScopedPRFileDesc fd(PR_OpenFile(buf, PR_RDONLY, 0));
+  UniquePRFileDesc fd(PR_OpenFile(buf, PR_RDONLY, 0));
   if (!fd) {
     PrintPRError("PR_Open failed");
     return SECFailure;
   }
-  int32_t fileSize = PR_Available(fd);
+  int32_t fileSize = PR_Available(fd.get());
   if (fileSize < 0) {
     PrintPRError("PR_Available failed");
     return SECFailure;
   }
   if (static_cast<size_t>(fileSize) > N - 1) {
     PR_fprintf(PR_STDERR, "file too large - not reading\n");
     return SECFailure;
   }
-  int32_t bytesRead = PR_Read(fd, buf, fileSize);
+  int32_t bytesRead = PR_Read(fd.get(), buf, fileSize);
   if (bytesRead != fileSize) {
     PrintPRError("PR_Read failed");
     return SECFailure;
   }
   buf[bytesRead] = 0;
   return SECSuccess;
 }
 
@@ -123,27 +123,28 @@ AddKeyFromFile(const char* basePath, con
     if (*bufPtr != '\r' && *bufPtr != '\n') {
       *base64Ptr = *bufPtr;
       base64Ptr++;
     }
     bufPtr++;
   }
 
   unsigned int binLength;
-  ScopedPORTString bin((char*)ATOB_AsciiToData(base64, &binLength));
+  UniquePORTString bin(
+    reinterpret_cast<char*>(ATOB_AsciiToData(base64, &binLength)));
   if (!bin || binLength == 0) {
     PrintPRError("ATOB_AsciiToData failed");
     return SECFailure;
   }
   ScopedSECItem secitem(::SECITEM_AllocItem(nullptr, nullptr, binLength));
   if (!secitem) {
     PrintPRError("SECITEM_AllocItem failed");
     return SECFailure;
   }
-  PORT_Memcpy(secitem->data, bin, binLength);
+  PORT_Memcpy(secitem->data, bin.get(), binLength);
   ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
   if (!slot) {
     PrintPRError("PK11_GetInternalKeySlot failed");
     return SECFailure;
   }
   if (PK11_NeedUserInit(slot)) {
     if (PK11_InitPin(slot, nullptr, nullptr) != SECSuccess) {
       PrintPRError("PK11_InitPin failed");
@@ -215,34 +216,34 @@ SECStatus
 LoadCertificatesAndKeys(const char* basePath)
 {
   // The NSS cert DB path could have been specified as "sql:path". Trim off
   // the leading "sql:" if so.
   if (strncmp(basePath, "sql:", 4) == 0) {
     basePath = basePath + 4;
   }
 
-  ScopedPRDir fdDir(PR_OpenDir(basePath));
+  UniquePRDir fdDir(PR_OpenDir(basePath));
   if (!fdDir) {
     PrintPRError("PR_OpenDir failed");
     return SECFailure;
   }
   // On the B2G ICS emulator, operations taken in AddCertificateFromFile
   // appear to interact poorly with readdir (more specifically, something is
   // causing readdir to never return null - it indefinitely loops through every
   // file in the directory, which causes timeouts). Rather than waste more time
   // chasing this down, loading certificates and keys happens in two phases:
   // filename collection and then loading. (This is probably a good
   // idea anyway because readdir isn't reentrant. Something could change later
   // such that it gets called as a result of calling AddCertificateFromFile or
   // AddKeyFromFile.)
   std::vector<std::string> certificates;
   std::vector<std::string> keys;
-  for (PRDirEntry* dirEntry = PR_ReadDir(fdDir, PR_SKIP_BOTH); dirEntry;
-       dirEntry = PR_ReadDir(fdDir, PR_SKIP_BOTH)) {
+  for (PRDirEntry* dirEntry = PR_ReadDir(fdDir.get(), PR_SKIP_BOTH); dirEntry;
+       dirEntry = PR_ReadDir(fdDir.get(), PR_SKIP_BOTH)) {
     size_t nameLength = strlen(dirEntry->name);
     if (nameLength > 4) {
       if (strncmp(dirEntry->name + nameLength - 4, ".pem", 4) == 0) {
         certificates.push_back(dirEntry->name);
       } else if (strncmp(dirEntry->name + nameLength - 4, ".key", 4) == 0) {
         keys.push_back(dirEntry->name);
       }
     }
@@ -347,20 +348,20 @@ ReadRequest(Connection *aConn)
     if (gDebugLevel >= DEBUG_VERBOSE) {
       fprintf(stderr, "read '0x%hhx'\n", aConn->mByte);
     }
   }
   return NS_OK;
 }
 
 void
-HandleConnection(PRFileDesc *aSocket, PRFileDesc *aModelSocket)
+HandleConnection(PRFileDesc* aSocket, const UniquePRFileDesc& aModelSocket)
 {
   Connection conn(aSocket);
-  nsresult rv = SetupTLS(&conn, aModelSocket);
+  nsresult rv = SetupTLS(&conn, aModelSocket.get());
   if (NS_FAILED(rv)) {
     PR_SetError(PR_INVALID_STATE_ERROR, 0);
     PrintPRError("PR_Recv failed");
     exit(1);
   }
 
   // TODO: On tests that are expected to fail (e.g. due to a revoked
   // certificate), the client will close the connection wtihout sending us the
@@ -372,34 +373,34 @@ HandleConnection(PRFileDesc *aSocket, PR
     rv = ReplyToRequest(&conn);
   }
 }
 
 // returns 0 on success, non-zero on error
 int
 DoCallback()
 {
-  ScopedPRFileDesc socket(PR_NewTCPSocket());
+  UniquePRFileDesc socket(PR_NewTCPSocket());
   if (!socket) {
     PrintPRError("PR_NewTCPSocket failed");
     return 1;
   }
 
   PRNetAddr addr;
   PR_InitializeNetAddr(PR_IpAddrLoopback, gCallbackPort, &addr);
-  if (PR_Connect(socket, &addr, PR_INTERVAL_NO_TIMEOUT) != PR_SUCCESS) {
+  if (PR_Connect(socket.get(), &addr, PR_INTERVAL_NO_TIMEOUT) != PR_SUCCESS) {
     PrintPRError("PR_Connect failed");
     return 1;
   }
 
   const char *request = "GET / HTTP/1.0\r\n\r\n";
-  SendAll(socket, request, strlen(request));
+  SendAll(socket.get(), request, strlen(request));
   char buf[4096];
   memset(buf, 0, sizeof(buf));
-  int32_t bytesRead = PR_Recv(socket, buf, sizeof(buf) - 1, 0,
+  int32_t bytesRead = PR_Recv(socket.get(), buf, sizeof(buf) - 1, 0,
                               PR_INTERVAL_NO_TIMEOUT);
   if (bytesRead < 0) {
     PrintPRError("PR_Recv failed 1");
     return 1;
   }
   if (bytesRead == 0) {
     fprintf(stderr, "PR_Recv eof 1\n");
     return 1;
@@ -417,32 +418,32 @@ ConfigSecureServerWithNamedCert(PRFileDe
   if (!cert) {
     PrintPRError("PK11_FindCertFromNickname failed");
     return SECFailure;
   }
   // If an intermediate certificate issued the server certificate (rather than
   // directly by a trust anchor), we want to send it along in the handshake so
   // we don't encounter unknown issuer errors when that's not what we're
   // testing.
-  ScopedCERTCertificateList certList;
+  UniqueCERTCertificateList certList;
   ScopedCERTCertificate issuerCert(
     CERT_FindCertByName(CERT_GetDefaultCertDB(), &cert->derIssuer));
   // If we can't find the issuer cert, continue without it.
   if (issuerCert) {
     // Sadly, CERTCertificateList does not have a CERT_NewCertificateList
     // utility function, so we must create it ourselves. This consists
     // of creating an arena, allocating space for the CERTCertificateList,
     // and then transferring ownership of the arena to that list.
     ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
     if (!arena) {
       PrintPRError("PORT_NewArena failed");
       return SECFailure;
     }
-    certList = reinterpret_cast<CERTCertificateList*>(
-      PORT_ArenaAlloc(arena, sizeof(CERTCertificateList)));
+    certList.reset(static_cast<CERTCertificateList*>(
+      PORT_ArenaAlloc(arena.get(), sizeof(CERTCertificateList))));
     if (!certList) {
       PrintPRError("PORT_ArenaAlloc failed");
       return SECFailure;
     }
     certList->arena = arena.forget();
     // We also have to manually copy the certificates we care about to the
     // list, because there aren't any utility functions for that either.
     certList->certs = reinterpret_cast<SECItem*>(
@@ -456,26 +457,27 @@ ConfigSecureServerWithNamedCert(PRFileDe
                          &issuerCert->derCert) != SECSuccess) {
       PrintPRError("SECITEM_CopyItem failed");
       return SECFailure;
     }
     certList->len = 2;
   }
 
   ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
-  ScopedSECKEYPrivateKey key(PK11_FindKeyByDERCert(slot, cert, nullptr));
+  UniqueSECKEYPrivateKey key(
+    PK11_FindKeyByDERCert(slot.get(), cert.get(), nullptr));
   if (!key) {
     PrintPRError("PK11_FindKeyByDERCert failed");
     return SECFailure;
   }
 
   SSLKEAType certKEA = NSS_FindCertKEAType(cert);
 
-  if (SSL_ConfigSecureServerWithCertChain(fd, cert, certList, key, certKEA)
-        != SECSuccess) {
+  if (SSL_ConfigSecureServerWithCertChain(fd, cert.get(), certList.get(),
+                                          key.get(), certKEA) != SECSuccess) {
     PrintPRError("SSL_ConfigSecureServer failed");
     return SECFailure;
   }
 
   if (certOut) {
     *certOut = cert.forget();
   }
 
@@ -518,75 +520,74 @@ StartServer(const char *nssCertDBDir, SS
     return 1;
   }
 
   if (SSL_ConfigServerSessionIDCache(0, 0, 0, nullptr) != SECSuccess) {
     PrintPRError("SSL_ConfigServerSessionIDCache failed");
     return 1;
   }
 
-  ScopedPRFileDesc serverSocket(PR_NewTCPSocket());
+  UniquePRFileDesc serverSocket(PR_NewTCPSocket());
   if (!serverSocket) {
     PrintPRError("PR_NewTCPSocket failed");
     return 1;
   }
 
   PRSocketOptionData socketOption;
   socketOption.option = PR_SockOpt_Reuseaddr;
   socketOption.value.reuse_addr = true;
-  PR_SetSocketOption(serverSocket, &socketOption);
+  PR_SetSocketOption(serverSocket.get(), &socketOption);
 
   PRNetAddr serverAddr;
   PR_InitializeNetAddr(PR_IpAddrLoopback, LISTEN_PORT, &serverAddr);
-  if (PR_Bind(serverSocket, &serverAddr) != PR_SUCCESS) {
+  if (PR_Bind(serverSocket.get(), &serverAddr) != PR_SUCCESS) {
     PrintPRError("PR_Bind failed");
     return 1;
   }
 
-  if (PR_Listen(serverSocket, 1) != PR_SUCCESS) {
+  if (PR_Listen(serverSocket.get(), 1) != PR_SUCCESS) {
     PrintPRError("PR_Listen failed");
     return 1;
   }
 
-  ScopedPRFileDesc rawModelSocket(PR_NewTCPSocket());
+  UniquePRFileDesc rawModelSocket(PR_NewTCPSocket());
   if (!rawModelSocket) {
     PrintPRError("PR_NewTCPSocket failed for rawModelSocket");
     return 1;
   }
 
-  ScopedPRFileDesc modelSocket(SSL_ImportFD(nullptr, rawModelSocket.forget()));
+  UniquePRFileDesc modelSocket(SSL_ImportFD(nullptr, rawModelSocket.release()));
   if (!modelSocket) {
     PrintPRError("SSL_ImportFD of rawModelSocket failed");
     return 1;
   }
 
-  if (SECSuccess != SSL_SNISocketConfigHook(modelSocket, sniSocketConfig,
-                                            sniSocketConfigArg)) {
+  if (SSL_SNISocketConfigHook(modelSocket.get(), sniSocketConfig,
+                              sniSocketConfigArg) != SECSuccess) {
     PrintPRError("SSL_SNISocketConfigHook failed");
     return 1;
   }
 
   // We have to configure the server with a certificate, but it's not one
   // we're actually going to end up using. In the SNI callback, we pick
   // the right certificate for the connection.
-  if (SECSuccess != ConfigSecureServerWithNamedCert(modelSocket,
-                                                    DEFAULT_CERT_NICKNAME,
-                                                    nullptr, nullptr)) {
+  if (ConfigSecureServerWithNamedCert(modelSocket.get(), DEFAULT_CERT_NICKNAME,
+                                      nullptr, nullptr) != SECSuccess) {
     return 1;
   }
 
   if (gCallbackPort != 0) {
     if (DoCallback()) {
       return 1;
     }
   }
 
   while (true) {
     PRNetAddr clientAddr;
-    PRFileDesc *clientSocket = PR_Accept(serverSocket, &clientAddr,
+    PRFileDesc* clientSocket = PR_Accept(serverSocket.get(), &clientAddr,
                                          PR_INTERVAL_NO_TIMEOUT);
     HandleConnection(clientSocket, modelSocket);
   }
 
   return 0;
 }
 
 } } // namespace mozilla::test
--- a/security/manager/ssl/tests/unit/tlsserver/lib/TLSServer.h
+++ b/security/manager/ssl/tests/unit/tlsserver/lib/TLSServer.h
@@ -1,14 +1,14 @@
 /* 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 mozilla_test__TLSServer_h
-#define mozilla_test__TLSServer_h
+#ifndef TLSServer_h
+#define TLSServer_h
 
 // This is a standalone server for testing SSL features of Gecko.
 // The client is expected to connect and initiate an SSL handshake (with SNI
 // to indicate which "server" to connect to). If all is good, the client then
 // sends one encrypted byte and receives that same byte back.
 // This server also has the ability to "call back" another process waiting on
 // it. That is, when the server is all set up and ready to receive connections,
 // it will connect to a specified port and issue a simple HTTP request.
@@ -16,18 +16,17 @@
 #include <stdint.h>
 #include "prio.h"
 #include "ScopedNSSTypes.h"
 #include "secerr.h"
 #include "ssl.h"
 
 namespace mozilla {
 
-MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedPRDir, PRDir, PR_CloseDir);
-MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedPORTString, char, PORT_Free);
+MOZ_TYPE_SPECIFIC_UNIQUE_PTR_TEMPLATE(UniquePRDir, PRDir, PR_CloseDir);
 
 } // namespace mozilla
 
 namespace mozilla { namespace test {
 
 enum DebugLevel
 {
   DEBUG_ERRORS = 1,
@@ -80,9 +79,9 @@ GetHostForSNI(const SECItem *aSrvNameArr
   }
 
   PR_SetError(SEC_ERROR_INVALID_ARGS, 0);
   return nullptr;
 }
 
 } } // namespace mozilla::test
 
-#endif // mozilla_test__TLSServer_h
+#endif // TLSServer_h