avoid crash in emptyBuffer when input buffer handle is invalid

Try to fail with error instead of crashing when the input buffer
handle to TWOmxNode::emptyBuffer is invalid. Save an unnecessary
handle clone, and let the convertTo to GraphicBuffer do the clone.
If the clone fails, return with error.

bug: 133254412
test: atest CtsMediaTestCases -- --module-arg CtsMediaTestCases:size:small
    Change-Id: I6abb5526d8df1e57b70c96f5b32d132e4a5de389

Change-Id: If5ca8fae449a3cdf790c967add3713ad73369f03
diff --git a/media/libmedia/include/media/omx/1.0/Conversion.h b/media/libmedia/include/media/omx/1.0/Conversion.h
index 80e8f3a..6dc46b7 100644
--- a/media/libmedia/include/media/omx/1.0/Conversion.h
+++ b/media/libmedia/include/media/omx/1.0/Conversion.h
@@ -625,8 +625,18 @@
 // convert: AnwBuffer -> GraphicBuffer
 // Ref: frameworks/native/libs/ui/GraphicBuffer.cpp: GraphicBuffer::flatten
 inline bool convertTo(GraphicBuffer* l, AnwBuffer const& t) {
-    native_handle_t* handle = t.nativeHandle == nullptr ?
-            nullptr : native_handle_clone(t.nativeHandle);
+    native_handle_t* handle = nullptr;
+
+    if (t.nativeHandle != nullptr) {
+        handle = native_handle_clone(t.nativeHandle);
+        if (handle == nullptr) {
+            ALOGE("Failed to clone handle: numFds=%d, data[0]=%d, data[1]=%d",
+                    t.nativeHandle->numFds,
+                    (t.nativeHandle->numFds > 0) ? t.nativeHandle->data[0] : -1,
+                    (t.nativeHandle->numFds > 1) ? t.nativeHandle->data[1] : -1);
+            return false;
+        }
+    }
 
     size_t const numInts = 12 + (handle ? handle->numInts : 0);
     int32_t* ints = new int32_t[numInts];
@@ -756,7 +766,12 @@
                 return true;
             }
             AnwBuffer anwBuffer;
-            anwBuffer.nativeHandle = t.nativeHandle;
+            // Explicitly get the native_handle_t* (in stead of assigning t.nativeHandle)
+            // so that we don't do an extra native_handle_clone() in this step, as the
+            // convertion to GraphicBuffer below will do a clone regardless.
+            // If we encounter an invalid handle, the convertTo() below would fail (while
+            // the assigning of hidl_handle would abort and cause a crash).
+            anwBuffer.nativeHandle = t.nativeHandle.getNativeHandle();
             anwBuffer.attr = t.attr.anwBuffer;
             sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
             if (!convertTo(graphicBuffer.get(), anwBuffer)) {