bug 1391482 add a fallible SharedBuffer::Create() r?padenot draft
authorKarl Tomlinson <karlt+@karlt.net>
Fri, 11 Aug 2017 10:57:04 +1200
changeset 648600 601727c524675f2e007abec566410c284c6bf61e
parent 648599 e42ede828bb6f7f1cadbd0e8f5b6eb15ebc6a5ea
child 648601 9d9c4c3405437d7b435268dc276a348e5fcd6d1b
push id74809
push userktomlinson@mozilla.com
push dateFri, 18 Aug 2017 01:10:01 +0000
reviewerspadenot
bugs1391482
milestone57.0a1
bug 1391482 add a fallible SharedBuffer::Create() r?padenot MozReview-Commit-ID: HZGjSKnV8I2
dom/media/SharedBuffer.h
--- a/dom/media/SharedBuffer.h
+++ b/dom/media/SharedBuffer.h
@@ -52,34 +52,50 @@ protected:
  * This only guarantees 4-byte alignment of the data. For alignment we simply
  * assume that the memory from malloc is at least 4-byte aligned and the
  * refcount's size is large enough that SharedBuffer's size is divisible by 4.
  */
 class SharedBuffer : public ThreadSharedObject {
 public:
   void* Data() { return this + 1; }
 
+  static already_AddRefed<SharedBuffer> Create(size_t aSize, const fallible_t&)
+  {
+    return InternalCreate(&malloc, aSize);
+  }
+
   static already_AddRefed<SharedBuffer> Create(size_t aSize)
   {
-    CheckedInt<size_t> size = sizeof(SharedBuffer);
-    size += aSize;
-    if (!size.isValid()) {
-      MOZ_CRASH();
-    }
-    void* m = moz_xmalloc(size.value());
-    RefPtr<SharedBuffer> p = new (m) SharedBuffer();
-    NS_ASSERTION((reinterpret_cast<char*>(p.get() + 1) - reinterpret_cast<char*>(p.get())) % 4 == 0,
-                 "SharedBuffers should be at least 4-byte aligned");
-    return p.forget();
+    // Use moz_x_malloc() to include its diagnostic message indicating the
+    // size of any failed allocations.
+    return InternalCreate(&moz_xmalloc, aSize);
   }
 
   size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const override
   {
     return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
   }
 
 private:
+  static already_AddRefed<SharedBuffer>
+  InternalCreate(void* aMalloc(size_t), size_t aSize)
+  {
+    CheckedInt<size_t> size = sizeof(SharedBuffer);
+    size += aSize;
+    if (!size.isValid()) {
+      MOZ_CRASH();
+    }
+    void* m = (*aMalloc)(size.value());
+    if (!m) {
+      return nullptr;
+    }
+    RefPtr<SharedBuffer> p = new (m) SharedBuffer();
+    NS_ASSERTION((reinterpret_cast<char*>(p.get() + 1) - reinterpret_cast<char*>(p.get())) % 4 == 0,
+                 "SharedBuffers should be at least 4-byte aligned");
+    return p.forget();
+  }
+
   SharedBuffer() {}
 };
 
 } // namespace mozilla
 
 #endif /* MOZILLA_SHAREDBUFFER_H_ */