Camera metadata: Check for inconsistent data count

Resolve merge conflict for nyc-release
Also check for overflow of data/entry count on append.

Bug: 30591838
Change-Id: Ibf4c3c6e236cdb28234f3125055d95ef0a2416a2
(cherry picked from commit e9e44f797742f52996ebf307740dad58c28fd9b5)
diff --git a/camera/src/camera_metadata.c b/camera/src/camera_metadata.c
index c58a966..ee39931 100644
--- a/camera/src/camera_metadata.c
+++ b/camera/src/camera_metadata.c
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#define _GNU_SOURCE // for fdprintf
 #include <inttypes.h>
 #include <system/camera_metadata.h>
 #include <camera_metadata_hidden.h>
@@ -357,8 +358,15 @@
         return ERROR;
     }
 
-    const metadata_uptrdiff_t entries_end =
-        metadata->entries_start + metadata->entry_capacity;
+    if (metadata->data_count > metadata->data_capacity) {
+        ALOGE("%s: Data count (%" PRIu32 ") should be <= data capacity "
+              "(%" PRIu32 ")",
+              __FUNCTION__, metadata->data_count, metadata->data_capacity);
+        android_errorWriteLog(SN_EVENT_LOG_ID, "30591838");
+        return ERROR;
+    }
+
+    const metadata_uptrdiff_t entries_end = metadata->entries_start + metadata->entry_capacity;
     if (entries_end < metadata->entries_start || // overflow check
         entries_end > metadata->data_start) {
 
@@ -459,6 +467,10 @@
         const camera_metadata_t *src) {
     if (dst == NULL || src == NULL ) return ERROR;
 
+    // Check for overflow
+    if (src->entry_count + dst->entry_count < src->entry_count) return ERROR;
+    if (src->data_count + dst->data_count < src->data_count) return ERROR;
+    // Check for space
     if (dst->entry_capacity < src->entry_count + dst->entry_count) return ERROR;
     if (dst->data_capacity < src->data_count + dst->data_count) return ERROR;