Bug 1486690 - Rename nsMemory::Clone() and remove unnecessary checks after it. r=glandium
authorNicholas Nethercote <nnethercote@mozilla.com>
Tue, 28 Aug 2018 15:59:19 +1000
changeset 482007 8257797fd2d80b0954d44d8eebcb33459a9a569a
parent 482006 d6ccf1492e714566c84bb63de3fae0405cc465d9
child 482008 74318e0ebe1ecc477cc9ffb8870420721ecc42f6
push id232
push userfmarier@mozilla.com
push dateWed, 05 Sep 2018 20:45:54 +0000
reviewersglandium
bugs1486690
milestone63.0a1
Bug 1486690 - Rename nsMemory::Clone() and remove unnecessary checks after it. r=glandium The 'x' in the new name makes it clearer that it's infallible.
extensions/auth/nsAuthGSSAPI.cpp
extensions/auth/nsAuthSSPI.cpp
extensions/auth/nsAuthSambaNTLM.cpp
js/xpconnect/src/XPCJSID.cpp
memory/mozalloc/mozalloc.cpp
memory/mozalloc/mozalloc.h
modules/libpref/Preferences.cpp
netwerk/mime/nsMIMEHeaderParamImpl.cpp
storage/Variant.h
storage/mozStorageArgValueArray.cpp
storage/mozStorageStatement.cpp
widget/GfxInfoBase.cpp
xpcom/base/nsMemory.cpp
xpcom/base/nsMemory.h
xpcom/ds/nsVariant.cpp
--- a/extensions/auth/nsAuthGSSAPI.cpp
+++ b/extensions/auth/nsAuthGSSAPI.cpp
@@ -511,17 +511,17 @@ nsAuthGSSAPI::GetNextToken(const void *i
         // The important thing is that we do NOT reset the
         // context here because it will be needed on the
         // next call.
         //
     }
 
     *outTokenLen = output_token.length;
     if (output_token.length != 0)
-        *outToken = nsMemory::Clone(output_token.value, output_token.length);
+        *outToken = moz_xmemdup(output_token.value, output_token.length);
     else
         *outToken = nullptr;
 
     gss_release_buffer_ptr(&minor_status, &output_token);
 
     if (major_status == GSS_S_COMPLETE)
         rv = NS_SUCCESS_AUTH_FINISHED;
     else
@@ -560,17 +560,17 @@ nsAuthGSSAPI::Unwrap(const void *inToken
         Reset();
         gss_release_buffer_ptr(&minor_status, &output_token);
         return NS_ERROR_FAILURE;
     }
 
     *outTokenLen = output_token.length;
 
     if (output_token.length)
-        *outToken = nsMemory::Clone(output_token.value, output_token.length);
+        *outToken = moz_xmemdup(output_token.value, output_token.length);
     else
         *outToken = nullptr;
 
     gss_release_buffer_ptr(&minor_status, &output_token);
 
     return NS_OK;
 }
 
@@ -602,14 +602,14 @@ nsAuthGSSAPI::Wrap(const void *inToken,
         Reset();
         gss_release_buffer_ptr(&minor_status, &output_token);
         return NS_ERROR_FAILURE;
     }
 
     *outTokenLen = output_token.length;
 
     /* it is not possible for output_token.length to be zero */
-    *outToken = nsMemory::Clone(output_token.value, output_token.length);
+    *outToken = moz_xmemdup(output_token.value, output_token.length);
     gss_release_buffer_ptr(&minor_status, &output_token);
 
     return NS_OK;
 }
 
--- a/extensions/auth/nsAuthSSPI.cpp
+++ b/extensions/auth/nsAuthSSPI.cpp
@@ -537,20 +537,18 @@ nsAuthSSPI::Unwrap(const void *inToken,
     if (SEC_SUCCESS(rc)) {
         // check if ib[1].pvBuffer is really just ib[0].pvBuffer, in which
         // case we can let the caller free it. Otherwise, we need to
         // clone it, and free the original
         if (ib[0].pvBuffer == ib[1].pvBuffer) {
             *outToken = ib[1].pvBuffer;
         }
         else {
-            *outToken = nsMemory::Clone(ib[1].pvBuffer, ib[1].cbBuffer);
+            *outToken = moz_xmemdup(ib[1].pvBuffer, ib[1].cbBuffer);
             free(ib[0].pvBuffer);
-            if (!*outToken)
-                return NS_ERROR_OUT_OF_MEMORY;
         }
         *outTokenLen = ib[1].cbBuffer;
     }
     else
         free(ib[0].pvBuffer);
 
     if (!SEC_SUCCESS(rc))
         return NS_ERROR_FAILURE;
--- a/extensions/auth/nsAuthSambaNTLM.cpp
+++ b/extensions/auth/nsAuthSambaNTLM.cpp
@@ -230,19 +230,17 @@ nsAuthSambaNTLM::Init(const char *servic
 NS_IMETHODIMP
 nsAuthSambaNTLM::GetNextToken(const void *inToken,
                               uint32_t    inTokenLen,
                               void      **outToken,
                               uint32_t   *outTokenLen)
 {
     if (!inToken) {
         /* someone wants our initial message */
-        *outToken = nsMemory::Clone(mInitialMessage, mInitialMessageLen);
-        if (!*outToken)
-            return NS_ERROR_OUT_OF_MEMORY;
+        *outToken = moz_xmemdup(mInitialMessage, mInitialMessageLen);
         *outTokenLen = mInitialMessageLen;
         return NS_OK;
     }
 
     /* inToken must be a type 2 message. Get ntlm_auth to generate our response */
     char* encoded = PL_Base64Encode(static_cast<const char*>(inToken), inTokenLen, nullptr);
     if (!encoded)
         return NS_ERROR_OUT_OF_MEMORY;
@@ -261,21 +259,18 @@ nsAuthSambaNTLM::GetNextToken(const void
     if (!StringBeginsWith(line, NS_LITERAL_CSTRING("KK ")) &&
         !StringBeginsWith(line, NS_LITERAL_CSTRING("AF "))) {
         // Something went wrong. Perhaps no credentials are accessible.
         return NS_ERROR_FAILURE;
     }
     uint8_t* buf = ExtractMessage(line, outTokenLen);
     if (!buf)
         return NS_ERROR_FAILURE;
-    *outToken = nsMemory::Clone(buf, *outTokenLen);
+    *outToken = moz_xmemdup(buf, *outTokenLen);
     PR_Free(buf);
-    if (!*outToken) {
-        return NS_ERROR_OUT_OF_MEMORY;
-    }
 
     // We're done. Close our file descriptors now and reap the helper
     // process.
     Shutdown();
     return NS_SUCCESS_AUTH_FINISHED;
 }
 
 NS_IMETHODIMP
--- a/js/xpconnect/src/XPCJSID.cpp
+++ b/js/xpconnect/src/XPCJSID.cpp
@@ -301,18 +301,18 @@ NS_IMETHODIMP nsJSIID::GetName(char * *a
 }
 
 NS_IMETHODIMP nsJSIID::GetNumber(char * *aNumber)
 {
     char str[NSID_LENGTH];
     const nsIID* id;
     mInfo->GetIIDShared(&id);
     id->ToProvidedString(str);
-    *aNumber = (char*) nsMemory::Clone(str, NSID_LENGTH);
-    return *aNumber ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
+    *aNumber = (char*) moz_xmemdup(str, NSID_LENGTH);
+    return NS_OK;
 }
 
 NS_IMETHODIMP_(const nsID*) nsJSIID::GetID()
 {
     const nsIID* id;
     mInfo->GetIIDShared(&id);
     return id;
 }
--- a/memory/mozalloc/mozalloc.cpp
+++ b/memory/mozalloc/mozalloc.cpp
@@ -117,16 +117,24 @@ moz_xstrndup(const char* str, size_t str
     if (MOZ_UNLIKELY(!dup)) {
         mozalloc_handle_oom(strsize);
         return moz_xstrndup(str, strsize);
     }
     return dup;
 }
 #endif  // if defined(HAVE_STRNDUP)
 
+void*
+moz_xmemdup(const void* ptr, size_t size)
+{
+  void* newPtr = moz_xmalloc(size);
+  memcpy(newPtr, ptr, size);
+  return newPtr;
+}
+
 #ifndef HAVE_MEMALIGN
 // We always have a definition of memalign, but system headers don't
 // necessarily come with a declaration.
 extern "C" void* memalign(size_t, size_t);
 #endif
 
 void*
 moz_xmemalign(size_t boundary, size_t size)
--- a/memory/mozalloc/mozalloc.h
+++ b/memory/mozalloc/mozalloc.h
@@ -67,34 +67,37 @@ MFBT_API void* moz_xcalloc(size_t nmemb,
     MOZ_ALLOCATOR;
 
 MFBT_API void* moz_xrealloc(void* ptr, size_t size)
     MOZ_ALLOCATOR;
 
 MFBT_API char* moz_xstrdup(const char* str)
     MOZ_ALLOCATOR;
 
+#if defined(HAVE_STRNDUP)
+MFBT_API char* moz_xstrndup(const char* str, size_t strsize)
+    MOZ_ALLOCATOR;
+#endif /* if defined(HAVE_STRNDUP) */
+
+MFBT_API void* moz_xmemdup(const void* ptr, size_t size)
+    MOZ_ALLOCATOR;
+
+MFBT_API void* moz_xmemalign(size_t boundary, size_t size)
+    MOZ_ALLOCATOR;
+
 MFBT_API size_t moz_malloc_usable_size(void *ptr);
 
 MFBT_API size_t moz_malloc_size_of(const void *ptr);
 
 /*
  * Like moz_malloc_size_of(), but works reliably with interior pointers, i.e.
  * pointers into the middle of a live allocation.
  */
 MFBT_API size_t moz_malloc_enclosing_size_of(const void *ptr);
 
-#if defined(HAVE_STRNDUP)
-MFBT_API char* moz_xstrndup(const char* str, size_t strsize)
-    MOZ_ALLOCATOR;
-#endif /* if defined(HAVE_STRNDUP) */
-
-MFBT_API void* moz_xmemalign(size_t boundary, size_t size)
-    MOZ_ALLOCATOR;
-
 MOZ_END_EXTERN_C
 
 
 #ifdef __cplusplus
 
 /*
  * We implement the default operators new/delete as part of
  * libmozalloc, replacing their definitions in libstdc++.  The
--- a/modules/libpref/Preferences.cpp
+++ b/modules/libpref/Preferences.cpp
@@ -2938,24 +2938,18 @@ nsPrefBranch::GetChildList(const char* a
   if (numPrefs) {
     outArray = (char**)moz_xmalloc(numPrefs * sizeof(char*));
 
     for (dwIndex = 0; dwIndex < numPrefs; ++dwIndex) {
       // we need to lop off mPrefRoot in case the user is planning to pass this
       // back to us because if they do we are going to add mPrefRoot again.
       const nsCString& element = prefArray[dwIndex];
       outArray[dwIndex] =
-        (char*)nsMemory::Clone(element.get() + mPrefRoot.Length(),
-                               element.Length() - mPrefRoot.Length() + 1);
-
-      if (!outArray[dwIndex]) {
-        // We ran out of memory... this is annoying.
-        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(dwIndex, outArray);
-        return NS_ERROR_OUT_OF_MEMORY;
-      }
+        (char*) moz_xmemdup(element.get() + mPrefRoot.Length(),
+                            element.Length() - mPrefRoot.Length() + 1);
     }
     *aChildArray = outArray;
   }
   *aCount = numPrefs;
 
   return NS_OK;
 }
 
--- a/netwerk/mime/nsMIMEHeaderParamImpl.cpp
+++ b/netwerk/mime/nsMIMEHeaderParamImpl.cpp
@@ -402,18 +402,17 @@ nsMIMEHeaderParamImpl::DoParameterIntern
   // Content-Disposition: inline; filename=.....
   if (!aParamName || !*aParamName)
     {
       for (; *str && *str != ';' && !nsCRT::IsAsciiSpace(*str); ++str)
         ;
       if (str == start)
         return NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY;
 
-      *aResult = (char *) nsMemory::Clone(start, (str - start) + 1);
-      NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
+      *aResult = (char*) moz_xmemdup(start, (str - start) + 1);
       (*aResult)[str - start] = '\0';  // null-terminate
       return NS_OK;
     }
 
   /* Skip forward to first ';' */
   for (; *str && *str != ';' && *str != ','; ++str)
     ;
   if (*str)
@@ -625,20 +624,18 @@ nsMIMEHeaderParamImpl::DoParameterIntern
         // non-empty value part
         if (rawValLength > 0) {
           if (!caseBResult && caseB) {
             if (!IsValidPercentEscaped(rawValStart, rawValLength)) {
               goto increment_str;
             }
 
             // allocate buffer for the raw value
-            char *tmpResult = (char *) nsMemory::Clone(rawValStart, rawValLength + 1);
-            if (!tmpResult) {
-              goto increment_str;
-            }
+            char* tmpResult =
+              (char*) moz_xmemdup(rawValStart, rawValLength + 1);
             *(tmpResult + rawValLength) = 0;
 
             nsUnescape(tmpResult);
             caseBResult = tmpResult;
           } else {
             // caseC
             bool added = addContinuation(segments, 0, rawValStart,
                                          rawValLength, needExtDecoding,
@@ -719,27 +716,23 @@ increment_str:
   free(caseBResult);
   free(caseCDResult);
 
   // if we have a result
   if (*aResult) {
     // then return charset and lang as well
     if (aLang && !lang.IsEmpty()) {
       uint32_t len = lang.Length();
-      *aLang = (char *) nsMemory::Clone(lang.BeginReading(), len + 1);
-      if (*aLang) {
-        *(*aLang + len) = 0;
-      }
+      *aLang = (char*) moz_xmemdup(lang.BeginReading(), len + 1);
+      *(*aLang + len) = 0;
    }
     if (aCharset && !charset.IsEmpty()) {
       uint32_t len = charset.Length();
-      *aCharset = (char *) nsMemory::Clone(charset.BeginReading(), len + 1);
-      if (*aCharset) {
-        *(*aCharset + len) = 0;
-      }
+      *aCharset = (char*) moz_xmemdup(charset.BeginReading(), len + 1);
+      *(*aCharset + len) = 0;
     }
   }
 
   return *aResult ? NS_OK : NS_ERROR_INVALID_ARG;
 }
 
 nsresult
 internalDecodeRFC2047Header(const char* aHeaderVal, const char* aDefaultCharset,
--- a/storage/Variant.h
+++ b/storage/Variant.h
@@ -298,18 +298,17 @@ struct variant_blob_traits<uint8_t[], fa
     if (aData.Length() == 0) {
       *_result = nullptr;
       *_type = nsIDataType::VTYPE_UINT8;
       *_size = 0;
       return NS_OK;
     }
 
     // Otherwise, we copy the array.
-    *_result = nsMemory::Clone(aData.Elements(), aData.Length() * sizeof(uint8_t));
-    NS_ENSURE_TRUE(*_result, NS_ERROR_OUT_OF_MEMORY);
+    *_result = moz_xmemdup(aData.Elements(), aData.Length() * sizeof(uint8_t));
 
     // Set type and size
     *_type = nsIDataType::VTYPE_UINT8;
     *_size = aData.Length();
     return NS_OK;
   }
 };
 
--- a/storage/mozStorageArgValueArray.cpp
+++ b/storage/mozStorageArgValueArray.cpp
@@ -137,19 +137,17 @@ ArgValueArray::GetString(uint32_t aIndex
 NS_IMETHODIMP
 ArgValueArray::GetBlob(uint32_t aIndex,
                        uint32_t *_size,
                        uint8_t **_blob)
 {
   ENSURE_INDEX_VALUE(aIndex, mArgc);
 
   int size = ::sqlite3_value_bytes(mArgv[aIndex]);
-  void *blob = nsMemory::Clone(::sqlite3_value_blob(mArgv[aIndex]), size);
-  NS_ENSURE_TRUE(blob, NS_ERROR_OUT_OF_MEMORY);
-
+  void* blob = moz_xmemdup(::sqlite3_value_blob(mArgv[aIndex]), size);
   *_blob = static_cast<uint8_t *>(blob);
   *_size = size;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 ArgValueArray::GetBlobAsString(uint32_t aIndex, nsAString& aValue)
 {
--- a/storage/mozStorageStatement.cpp
+++ b/storage/mozStorageStatement.cpp
@@ -778,18 +778,17 @@ Statement::GetBlob(uint32_t aIndex,
   ENSURE_INDEX_VALUE(aIndex, mResultColumnCount);
 
   if (!mExecuting)
      return NS_ERROR_UNEXPECTED;
 
   int size = ::sqlite3_column_bytes(mDBStatement, aIndex);
   void *blob = nullptr;
   if (size) {
-    blob = nsMemory::Clone(::sqlite3_column_blob(mDBStatement, aIndex), size);
-    NS_ENSURE_TRUE(blob, NS_ERROR_OUT_OF_MEMORY);
+    blob = moz_xmemdup(::sqlite3_column_blob(mDBStatement, aIndex), size);
   }
 
   *_blob = static_cast<uint8_t *>(blob);
   *_size = size;
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/widget/GfxInfoBase.cpp
+++ b/widget/GfxInfoBase.cpp
@@ -1100,25 +1100,19 @@ NS_IMETHODIMP GfxInfoBase::GetFailures(u
     if (indices) {
       *indices = (int32_t*)moz_xmalloc(*failureCount * sizeof(int32_t));
     }
 
     /* copy over the failure messages into the array we just allocated */
     LoggingRecord::const_iterator it;
     uint32_t i=0;
     for(it = loggedStrings.begin() ; it != loggedStrings.end(); ++it, i++) {
-      (*failures)[i] = (char*)nsMemory::Clone(Get<1>(*it).c_str(), Get<1>(*it).size() + 1);
+      (*failures)[i] =
+        (char*) moz_xmemdup(Get<1>(*it).c_str(), Get<1>(*it).size() + 1);
       if (indices) (*indices)[i] = Get<0>(*it);
-
-      if (!(*failures)[i]) {
-        /* <sarcasm> I'm too afraid to use an inline function... </sarcasm> */
-        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(i, (*failures));
-        *failureCount = i;
-        return NS_ERROR_OUT_OF_MEMORY;
-      }
     }
   }
 
   return NS_OK;
 }
 
 nsTArray<GfxInfoCollectorBase*> *sCollectors;
 
--- a/xpcom/base/nsMemory.cpp
+++ b/xpcom/base/nsMemory.cpp
@@ -22,24 +22,16 @@ nsMemory::HeapMinimize(bool aImmediate)
   nsresult rv = NS_GetMemoryManager(getter_AddRefs(mem));
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
   return mem->HeapMinimize(aImmediate);
 }
 
-void*
-nsMemory::Clone(const void* aPtr, size_t aSize)
-{
-  void* newPtr = moz_xmalloc(aSize);
-  memcpy(newPtr, aPtr, aSize);
-  return newPtr;
-}
-
 nsIMemory*
 nsMemory::GetGlobalMemoryService()
 {
   nsIMemory* mem;
   nsresult rv = NS_GetMemoryManager(&mem);
   if (NS_FAILED(rv)) {
     return nullptr;
   }
--- a/xpcom/base/nsMemory.h
+++ b/xpcom/base/nsMemory.h
@@ -29,17 +29,16 @@ class nsIMemory;
  *
  * This class is not threadsafe and is intented for use only on the main
  * thread.
  */
 class nsMemory
 {
 public:
   static nsresult   HeapMinimize(bool aImmediate);
-  static void*      Clone(const void* aPtr, size_t aSize);
   static nsIMemory* GetGlobalMemoryService();       // AddRefs
 };
 
 /**
  * Macro to free all elements of an XPCOM array of a given size using
  * freeFunc, then frees the array itself using free().
  *
  * Note that this macro (and its wrappers) can be used to deallocate a
--- a/xpcom/ds/nsVariant.cpp
+++ b/xpcom/ds/nsVariant.cpp
@@ -1488,36 +1488,31 @@ nsDiscriminatedUnion::SetFromArray(uint1
 nsresult
 nsDiscriminatedUnion::SetFromStringWithSize(uint32_t aSize,
                                             const char* aValue)
 {
   DATA_SETTER_PROLOGUE;
   if (!aValue) {
     return NS_ERROR_NULL_POINTER;
   }
-  if (!(u.str.mStringValue =
-        (char*)nsMemory::Clone(aValue, (aSize + 1) * sizeof(char)))) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
+  u.str.mStringValue = (char*) moz_xmemdup(aValue, (aSize + 1) * sizeof(char));
   u.str.mStringLength = aSize;
   DATA_SETTER_EPILOGUE(VTYPE_STRING_SIZE_IS);
   return NS_OK;
 }
 nsresult
 nsDiscriminatedUnion::SetFromWStringWithSize(uint32_t aSize,
                                              const char16_t* aValue)
 {
   DATA_SETTER_PROLOGUE;
   if (!aValue) {
     return NS_ERROR_NULL_POINTER;
   }
-  if (!(u.wstr.mWStringValue =
-        (char16_t*)nsMemory::Clone(aValue, (aSize + 1) * sizeof(char16_t)))) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
+  u.wstr.mWStringValue =
+    (char16_t*) moz_xmemdup(aValue, (aSize + 1) * sizeof(char16_t));
   u.wstr.mWStringLength = aSize;
   DATA_SETTER_EPILOGUE(VTYPE_WSTRING_SIZE_IS);
   return NS_OK;
 }
 void
 nsDiscriminatedUnion::AllocateWStringWithSize(uint32_t aSize)
 {
   DATA_SETTER_PROLOGUE;