Gralloc: Validate buffer parameters during importBuffer call

Validate buffer parameters like numInts, numFds, version etc of buffer
handle while importing the buffer

Change-Id: Ia1cb1cf05d845b5ef5b2feb476c2c924fa3bbf17
CRs-Fixed: 2288349
diff --git a/gralloc/gr_buf_mgr.cpp b/gralloc/gr_buf_mgr.cpp
index a569184..9a25a8e 100644
--- a/gralloc/gr_buf_mgr.cpp
+++ b/gralloc/gr_buf_mgr.cpp
@@ -101,6 +101,10 @@
 }
 
 Error BufferManager::ImportHandleLocked(private_handle_t *hnd) {
+  if (private_handle_t::validate(hnd) != 0) {
+    ALOGE("ImportHandleLocked: Invalid handle: %p", hnd);
+    return Error::BAD_BUFFER;
+  }
   ALOGD_IF(DEBUG, "Importing handle:%p id: %" PRIu64, hnd, hnd->id);
   int ion_handle = allocator_->ImportBuffer(hnd->fd);
   if (ion_handle < 0) {
diff --git a/gralloc/gr_priv_handle.h b/gralloc/gr_priv_handle.h
index 39e5e20..ace762e 100644
--- a/gralloc/gr_priv_handle.h
+++ b/gralloc/gr_priv_handle.h
@@ -132,12 +132,14 @@
   static int validate(const native_handle *h) {
     auto *hnd = static_cast<const private_handle_t *>(h);
     if (!h || h->version != sizeof(native_handle) || h->numInts != NumInts() ||
-        h->numFds != kNumFds || hnd->magic != kMagic) {
-      ALOGE(
-          "Invalid gralloc handle (at %p): ver(%d/%zu) ints(%d/%d) fds(%d/%d) "
-          "magic(%c%c%c%c/%c%c%c%c)",
+        h->numFds != kNumFds) {
+      ALOGE("Invalid gralloc handle (at %p): ver(%d/%zu) ints(%d/%d) fds(%d/%d) ",
           h, h ? h->version : -1, sizeof(native_handle), h ? h->numInts : -1, NumInts(),
-          h ? h->numFds : -1, kNumFds,
+          h ? h->numFds : -1, kNumFds);
+      return -EINVAL;
+    }
+    if (hnd->magic != kMagic) {
+       ALOGE("magic(%c%c%c%c/%c%c%c%c)",
           hnd ? (((hnd->magic >> 24) & 0xFF) ? ((hnd->magic >> 24) & 0xFF) : '-') : '?',
           hnd ? (((hnd->magic >> 16) & 0xFF) ? ((hnd->magic >> 16) & 0xFF) : '-') : '?',
           hnd ? (((hnd->magic >> 8) & 0xFF) ? ((hnd->magic >> 8) & 0xFF) : '-') : '?',