Merge cherrypicks of [14947012, 14947430, 14947171, 14947470, 14947471, 14947013, 14947490] into security-aosp-pi-release

Change-Id: Ibd3cdcd1742622f369e8a9874a21ea8a8de7b05c
diff --git a/Parcel.cpp b/Parcel.cpp
index 096913f..f33c4d5 100644
--- a/Parcel.cpp
+++ b/Parcel.cpp
@@ -1564,6 +1564,19 @@
                   static_cast<uint64_t>(buffer_obj->parent_offset), parentOffset);
             return false;
         }
+
+        binder_buffer_object *parentBuffer =
+            reinterpret_cast<binder_buffer_object*>(mData + mObjects[parent]);
+        void* bufferInParent = *reinterpret_cast<void**>(
+            reinterpret_cast<uint8_t*>(parentBuffer->buffer) + parentOffset);
+        void* childBuffer = reinterpret_cast<void*>(buffer_obj->buffer);
+
+        if (bufferInParent != childBuffer) {
+              ALOGE("Buffer in parent %p differs from embedded buffer %p",
+                    bufferInParent, childBuffer);
+              android_errorWriteLog(0x534e4554, "179289794");
+              return false;
+        }
     }
 
     return true;
@@ -1691,12 +1704,31 @@
                                                size_t parent_buffer_handle,
                                                size_t parent_offset) const
 {
-    status_t status;
     uint64_t nativeHandleSize;
-    size_t fdaParent;
+    status_t status = readUint64(&nativeHandleSize);
+    if (status != OK) {
+        return BAD_VALUE;
+    }
 
-    status = readUint64(&nativeHandleSize);
-    if (status != OK || nativeHandleSize == 0) {
+    if (nativeHandleSize == 0) {
+        // If !embedded, then parent_* vars are 0 and don't actually correspond
+        // to anything. In that case, we're actually reading this data into
+        // writable memory, and the handle returned from here will actually be
+        // used (rather than be ignored).
+        if (embedded) {
+            binder_buffer_object *parentBuffer =
+                reinterpret_cast<binder_buffer_object*>(mData + mObjects[parent_buffer_handle]);
+
+            void* bufferInParent = *reinterpret_cast<void**>(
+                reinterpret_cast<uint8_t*>(parentBuffer->buffer) + parent_offset);
+
+            if (bufferInParent != nullptr) {
+                  ALOGE("Buffer in (handle) parent %p is not nullptr.", bufferInParent);
+                  android_errorWriteLog(0x534e4554, "179289794");
+                  return BAD_VALUE;
+            }
+        }
+
         *handle = nullptr;
         return status;
     }
@@ -1706,6 +1738,7 @@
         return BAD_VALUE;
     }
 
+    size_t fdaParent;
     if (embedded) {
         status = readNullableEmbeddedBuffer(nativeHandleSize, &fdaParent,
                                             parent_buffer_handle, parent_offset,