bug add a fallible SharedBuffer::Create() r?padenot draft
authorKarl Tomlinson <karlt+@karlt.net>
Fri, 11 Aug 2017 10:57:04 +1200
changeset 645169 40155ca0359a087f7140bc82109d96e9753ccdf5
parent 645168 37bbd7cc94954fee142c5d46c86e379df6ed9e3f
child 645170 91d362093d8ee98543b047059154194600882890
push id73684
push userktomlinson@mozilla.com
push dateFri, 11 Aug 2017 22:29:12 +0000
reviewerspadenot
milestone57.0a1
bug add a fallible SharedBuffer::Create() r?padenot
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_ */