gralloc: Avoid setting out handle before allocate finishes

... otherwise a buffer would be leaked if `mDriver->allocate()`
succeeds but `initializeMetadata()` fails as the error handling
in the multi-buffer `CrosGralloc4Allocate::allocate()` would
fail to `mDriver->release();`.

BUG=b:219757060
TEST=cvd start
TEST=vts -m VtsHalGraphicsMapperV4_0Target

Change-Id: I375da2c959dd9df2667503a040ed1dcbd2aa12b1
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/minigbm/+/3501132
Reviewed-by: Yiwei Zhang <zzyiwei@chromium.org>
Tested-by: Jason Macnak <natsu@google.com>
Commit-Queue: Jason Macnak <natsu@google.com>
diff --git a/cros_gralloc/gralloc4/CrosGralloc4Allocator.cc b/cros_gralloc/gralloc4/CrosGralloc4Allocator.cc
index 6610c5e..43c0b0c 100644
--- a/cros_gralloc/gralloc4/CrosGralloc4Allocator.cc
+++ b/cros_gralloc/gralloc4/CrosGralloc4Allocator.cc
@@ -95,18 +95,17 @@
         return Error::NO_RESOURCES;
     }
 
-    outHandle->setTo(handle, /*shouldOwn=*/true);
-
     cros_gralloc_handle_t crosHandle = cros_gralloc_convert_handle(handle);
-    if (!crosHandle) {
-        return Error::NO_RESOURCES;
-    }
 
     Error error = initializeMetadata(crosHandle, crosDescriptor);
     if (error != Error::NONE) {
+        mDriver->release(handle);
+        native_handle_close(handle);
+        native_handle_delete(handle);
         return error;
     }
 
+    outHandle->setTo(handle, /*shouldOwn=*/true);
     *outStride = crosHandle->pixel_stride;
 
     return Error::NONE;