aaudio: fix ownership problems with file descriptors

Use unique_fd to track file descriptors.
Fix extra close of file descriptor in SharedMemoryParcelable.cpp.
This bug was causing unrelated file descriptors to be closed!

Bug: 64311216
Test: write_sine.cpp, FD should survive aaudio close
Change-Id: I4f38c83510a49ea22b79b96d970ee48153417249
diff --git a/media/libaaudio/src/binding/AudioEndpointParcelable.cpp b/media/libaaudio/src/binding/AudioEndpointParcelable.cpp
index d05abb0..1a97555 100644
--- a/media/libaaudio/src/binding/AudioEndpointParcelable.cpp
+++ b/media/libaaudio/src/binding/AudioEndpointParcelable.cpp
@@ -28,6 +28,7 @@
 #include "binding/RingBufferParcelable.h"
 #include "binding/AudioEndpointParcelable.h"
 
+using android::base::unique_fd;
 using android::NO_ERROR;
 using android::status_t;
 using android::Parcel;
@@ -49,7 +50,8 @@
  * Add the file descriptor to the table.
  * @return index in table or negative error
  */
-int32_t AudioEndpointParcelable::addFileDescriptor(int fd, int32_t sizeInBytes) {
+int32_t AudioEndpointParcelable::addFileDescriptor(const unique_fd& fd,
+                                                   int32_t sizeInBytes) {
     if (mNumSharedMemories >= MAX_SHARED_MEMORIES) {
         return AAUDIO_ERROR_OUT_OF_RANGE;
     }
diff --git a/media/libaaudio/src/binding/AudioEndpointParcelable.h b/media/libaaudio/src/binding/AudioEndpointParcelable.h
index 993075c7..aa8573f 100644
--- a/media/libaaudio/src/binding/AudioEndpointParcelable.h
+++ b/media/libaaudio/src/binding/AudioEndpointParcelable.h
@@ -20,6 +20,7 @@
 #include <stdint.h>
 
 //#include <sys/mman.h>
+#include <android-base/unique_fd.h>
 #include <binder/Parcel.h>
 #include <binder/Parcelable.h>
 
@@ -47,7 +48,7 @@
      * Add the file descriptor to the table.
      * @return index in table or negative error
      */
-    int32_t addFileDescriptor(int fd, int32_t sizeInBytes);
+    int32_t addFileDescriptor(const android::base::unique_fd& fd, int32_t sizeInBytes);
 
     virtual status_t writeToParcel(Parcel* parcel) const override;
 
diff --git a/media/libaaudio/src/binding/SharedMemoryParcelable.cpp b/media/libaaudio/src/binding/SharedMemoryParcelable.cpp
index b582b99..90217ab 100644
--- a/media/libaaudio/src/binding/SharedMemoryParcelable.cpp
+++ b/media/libaaudio/src/binding/SharedMemoryParcelable.cpp
@@ -24,11 +24,13 @@
 #include <sys/mman.h>
 #include <aaudio/AAudio.h>
 
+#include <android-base/unique_fd.h>
 #include <binder/Parcelable.h>
 #include <utility/AAudioUtilities.h>
 
 #include "binding/SharedMemoryParcelable.h"
 
+using android::base::unique_fd;
 using android::NO_ERROR;
 using android::status_t;
 using android::Parcel;
@@ -39,17 +41,19 @@
 SharedMemoryParcelable::SharedMemoryParcelable() {}
 SharedMemoryParcelable::~SharedMemoryParcelable() {};
 
-void SharedMemoryParcelable::setup(int fd, int32_t sizeInBytes) {
-    mFd = fd;
+void SharedMemoryParcelable::setup(const unique_fd& fd, int32_t sizeInBytes) {
+    mFd.reset(dup(fd.get())); // store a duplicate fd
+    ALOGV("SharedMemoryParcelable::setup(%d -> %d, %d) this = %p\n",
+          fd.get(), mFd.get(), sizeInBytes, this);
     mSizeInBytes = sizeInBytes;
-
 }
 
 status_t SharedMemoryParcelable::writeToParcel(Parcel* parcel) const {
     status_t status = parcel->writeInt32(mSizeInBytes);
     if (status != NO_ERROR) return status;
     if (mSizeInBytes > 0) {
-        status = parcel->writeDupFileDescriptor(mFd);
+        ALOGV("SharedMemoryParcelable::writeToParcel() mFd = %d, this = %p\n", mFd.get(), this);
+        status = parcel->writeUniqueFileDescriptor(mFd);
         ALOGE_IF(status != NO_ERROR, "SharedMemoryParcelable writeDupFileDescriptor failed : %d",
                  status);
     }
@@ -62,15 +66,16 @@
         return status;
     }
     if (mSizeInBytes > 0) {
-        // Keep the original FD until you are done with the mFd.
-        // If you close it in here then it will prevent mFd from working.
-        int originalFd = parcel->readFileDescriptor();
-        ALOGV("SharedMemoryParcelable::readFromParcel() LEAK? originalFd = %d\n", originalFd);
-        mFd = fcntl(originalFd, F_DUPFD_CLOEXEC, 0);
-        ALOGV("SharedMemoryParcelable::readFromParcel() LEAK? mFd = %d\n", mFd);
-        if (mFd == -1) {
-            status = -errno;
-            ALOGE("SharedMemoryParcelable readFromParcel fcntl() failed : %d", status);
+        // The Parcel owns the file descriptor and will close it later.
+        unique_fd mmapFd;
+        status = parcel->readUniqueFileDescriptor(&mmapFd);
+        if (status != NO_ERROR) {
+            ALOGE("SharedMemoryParcelable::readFromParcel() readUniqueFileDescriptor() failed : %d",
+                  status);
+        } else {
+            // Resolve the memory now while we still have the FD from the Parcel.
+            // Closing the FD will not affect the shared memory once mmap() has been called.
+            status = AAudioConvert_androidToAAudioResult(resolveSharedMemory(mmapFd));
         }
     }
     return status;
@@ -85,44 +90,50 @@
         }
         mResolvedAddress = MMAP_UNRESOLVED_ADDRESS;
     }
-    if (mFd != -1) {
-        ALOGV("SharedMemoryParcelable::close() LEAK? mFd = %d\n", mFd);
-        if(::close(mFd) < 0) {
-            int err = errno;
-            ALOGE("SharedMemoryParcelable close failed for fd = %d, errno = %d (%s)",
-                  mFd, err, strerror(err));
-        }
-        mFd = -1;
+    return AAUDIO_OK;
+}
+
+aaudio_result_t SharedMemoryParcelable::resolveSharedMemory(const unique_fd& fd) {
+    mResolvedAddress = (uint8_t *) mmap(0, mSizeInBytes, PROT_READ | PROT_WRITE,
+                                        MAP_SHARED, fd.get(), 0);
+    if (mResolvedAddress == MMAP_UNRESOLVED_ADDRESS) {
+        ALOGE("SharedMemoryParcelable mmap() failed for fd = %d, errno = %s",
+              fd.get(), strerror(errno));
+        return AAUDIO_ERROR_INTERNAL;
     }
     return AAUDIO_OK;
 }
 
 aaudio_result_t SharedMemoryParcelable::resolve(int32_t offsetInBytes, int32_t sizeInBytes,
                                               void **regionAddressPtr) {
-
     if (offsetInBytes < 0) {
         ALOGE("SharedMemoryParcelable illegal offsetInBytes = %d", offsetInBytes);
         return AAUDIO_ERROR_OUT_OF_RANGE;
     } else if ((offsetInBytes + sizeInBytes) > mSizeInBytes) {
         ALOGE("SharedMemoryParcelable out of range, offsetInBytes = %d, "
-              "sizeInBytes = %d, mSizeInBytes = %d",
+                      "sizeInBytes = %d, mSizeInBytes = %d",
               offsetInBytes, sizeInBytes, mSizeInBytes);
         return AAUDIO_ERROR_OUT_OF_RANGE;
     }
+
+    aaudio_result_t result = AAUDIO_OK;
+
     if (mResolvedAddress == MMAP_UNRESOLVED_ADDRESS) {
-        mResolvedAddress = (uint8_t *) mmap(0, mSizeInBytes, PROT_READ|PROT_WRITE,
-                                          MAP_SHARED, mFd, 0);
-        if (mResolvedAddress == MMAP_UNRESOLVED_ADDRESS) {
-            ALOGE("SharedMemoryParcelable mmap failed for fd = %d, errno = %s",
-                  mFd, strerror(errno));
-            return AAUDIO_ERROR_INTERNAL;
+        if (mFd.get() != -1) {
+            result = resolveSharedMemory(mFd);
+        } else {
+            ALOGE("SharedMemoryParcelable has no file descriptor for shared memory.");
+            result = AAUDIO_ERROR_INTERNAL;
         }
     }
-    *regionAddressPtr = mResolvedAddress + offsetInBytes;
-    ALOGV("SharedMemoryParcelable mResolvedAddress = %p", mResolvedAddress);
-    ALOGV("SharedMemoryParcelable offset by %d, *regionAddressPtr = %p",
-          offsetInBytes, *regionAddressPtr);
-    return AAUDIO_OK;
+
+    if (result == AAUDIO_OK && mResolvedAddress != MMAP_UNRESOLVED_ADDRESS) {
+        *regionAddressPtr = mResolvedAddress + offsetInBytes;
+        ALOGV("SharedMemoryParcelable mResolvedAddress = %p", mResolvedAddress);
+        ALOGV("SharedMemoryParcelable offset by %d, *regionAddressPtr = %p",
+              offsetInBytes, *regionAddressPtr);
+    }
+    return result;
 }
 
 int32_t SharedMemoryParcelable::getSizeInBytes() {
@@ -134,17 +145,11 @@
         ALOGE("SharedMemoryParcelable invalid mSizeInBytes = %d", mSizeInBytes);
         return AAUDIO_ERROR_OUT_OF_RANGE;
     }
-    if (mSizeInBytes > 0) {
-        if (mFd == -1) {
-            ALOGE("SharedMemoryParcelable uninitialized mFd = %d", mFd);
-            return AAUDIO_ERROR_INTERNAL;
-        }
-    }
     return AAUDIO_OK;
 }
 
 void SharedMemoryParcelable::dump() {
-    ALOGD("SharedMemoryParcelable mFd = %d", mFd);
+    ALOGD("SharedMemoryParcelable mFd = %d", mFd.get());
     ALOGD("SharedMemoryParcelable mSizeInBytes = %d", mSizeInBytes);
     ALOGD("SharedMemoryParcelable mResolvedAddress = %p", mResolvedAddress);
 }
diff --git a/media/libaaudio/src/binding/SharedMemoryParcelable.h b/media/libaaudio/src/binding/SharedMemoryParcelable.h
index c5107d3..2a634e0 100644
--- a/media/libaaudio/src/binding/SharedMemoryParcelable.h
+++ b/media/libaaudio/src/binding/SharedMemoryParcelable.h
@@ -18,15 +18,12 @@
 #define ANDROID_AAUDIO_SHARED_MEMORY_PARCELABLE_H
 
 #include <stdint.h>
-
 #include <sys/mman.h>
+
+#include <android-base/unique_fd.h>
 #include <binder/Parcel.h>
 #include <binder/Parcelable.h>
 
-using android::status_t;
-using android::Parcel;
-using android::Parcelable;
-
 namespace aaudio {
 
 // Arbitrary limits for sanity checks. TODO remove after debugging.
@@ -37,17 +34,24 @@
 /**
  * This is a parcelable description of a shared memory referenced by a file descriptor.
  * It may be divided into several regions.
+ * The memory can be shared using Binder or simply shared between threads.
  */
-class SharedMemoryParcelable : public Parcelable {
+class SharedMemoryParcelable : public android::Parcelable {
 public:
     SharedMemoryParcelable();
     virtual ~SharedMemoryParcelable();
 
-    void setup(int fd, int32_t sizeInBytes);
+    /**
+     * Make a dup() of the fd and store it for later use.
+     *
+     * @param fd
+     * @param sizeInBytes
+     */
+    void setup(const android::base::unique_fd& fd, int32_t sizeInBytes);
 
-    virtual status_t writeToParcel(Parcel* parcel) const override;
+    virtual android::status_t writeToParcel(android::Parcel* parcel) const override;
 
-    virtual status_t readFromParcel(const Parcel* parcel) override;
+    virtual android::status_t readFromParcel(const android::Parcel* parcel) override;
 
     // mmap() shared memory
     aaudio_result_t resolve(int32_t offsetInBytes, int32_t sizeInBytes, void **regionAddressPtr);
@@ -55,8 +59,6 @@
     // munmap() any mapped memory
     aaudio_result_t close();
 
-    bool isFileDescriptorSafe();
-
     int32_t getSizeInBytes();
 
     aaudio_result_t validate();
@@ -67,9 +69,11 @@
 
 #define MMAP_UNRESOLVED_ADDRESS    reinterpret_cast<uint8_t*>(MAP_FAILED)
 
-    int      mFd = -1;
-    int32_t  mSizeInBytes = 0;
-    uint8_t *mResolvedAddress = MMAP_UNRESOLVED_ADDRESS;
+    aaudio_result_t resolveSharedMemory(const android::base::unique_fd& fd);
+
+    android::base::unique_fd   mFd;
+    int32_t     mSizeInBytes = 0;
+    uint8_t    *mResolvedAddress = MMAP_UNRESOLVED_ADDRESS;
 };
 
 } /* namespace aaudio */