Fix SharedBuffer. Remove aref.

Add comment that SharedBuffer is deprecated.

Both aref and SharedBuffer had memory ordering bugs.  Aref has no
clients.

SharedBuffer had several bugs, which are fixed here:

mRefs was declared neither volatile, not atomic, allowing the
compiler to, for example, reuse a stale previously loaded value.

It used the default android_atomic release memory ordering, which
is insufficient for reference count decrements.

It used an ordinary memory read in onlyOwner() to check whether
an object is safe to deallocate, without any attempt to ensure
memory ordering.

Comments claimed that SharedBuffer was exactly 16 bytes, but
this was neither checked, nor correct on 64-bit platforms.

This turns mRef into a std::atomic and removes the android_atomic
dependency.

Bug: 28826227
Change-Id: I39fa0b4f70ac0471b14ad274806fc4e0c0802e78
diff --git a/libutils/SharedBuffer.h b/libutils/SharedBuffer.h
index b670953..48358cd 100644
--- a/libutils/SharedBuffer.h
+++ b/libutils/SharedBuffer.h
@@ -14,9 +14,14 @@
  * limitations under the License.
  */
 
+/*
+ * DEPRECATED.  DO NOT USE FOR NEW CODE.
+ */
+
 #ifndef ANDROID_SHARED_BUFFER_H
 #define ANDROID_SHARED_BUFFER_H
 
+#include <atomic>
 #include <stdint.h>
 #include <sys/types.h>
 
@@ -43,7 +48,7 @@
      * In other words, the buffer must have been release by all its
      * users.
      */
-    static          ssize_t                 dealloc(const SharedBuffer* released);
+    static          void                    dealloc(const SharedBuffer* released);
 
     //! access the data for read
     inline          const void*             data() const;
@@ -94,12 +99,16 @@
         SharedBuffer(const SharedBuffer&);
         SharedBuffer& operator = (const SharedBuffer&);
  
-        // 16 bytes. must be sized to preserve correct alignment.
-        mutable int32_t        mRefs;
-                size_t         mSize;
-                uint32_t       mReserved[2];
+        // Must be sized to preserve correct alignment.
+        mutable std::atomic<int32_t>        mRefs;
+                size_t                      mSize;
+                uint32_t                    mReserved[2];
 };
 
+static_assert(sizeof(SharedBuffer) % 8 == 0
+        && (sizeof(size_t) > 4 || sizeof(SharedBuffer) == 16),
+        "SharedBuffer has unexpected size");
+
 // ---------------------------------------------------------------------------
 
 const void* SharedBuffer::data() const {
@@ -127,7 +136,7 @@
 }
 
 bool SharedBuffer::onlyOwner() const {
-    return (mRefs == 1);
+    return (mRefs.load(std::memory_order_acquire) == 1);
 }
 
 }; // namespace android