From d7f0380f53a20d29b665972f19182417f4621fa8 Mon Sep 17 00:00:00 2001
From: zhibinw <zhibin@codeaurora.org>
Date: Tue, 6 Apr 2021 17:59:50 +0800
Subject: [PATCH] ipc/android: Dup the socket fd in native side, close the fd
 on java side.

---
 .../main/java/org/freedesktop/monado/ipc/Client.java   | 10 ++++++++--
 src/xrt/ipc/client/ipc_client_instance.c               |  8 ++++++++
 2 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/src/xrt/ipc/android/src/main/java/org/freedesktop/monado/ipc/Client.java b/src/xrt/ipc/android/src/main/java/org/freedesktop/monado/ipc/Client.java
index 068c50101..7bd217dbc 100644
--- a/src/xrt/ipc/android/src/main/java/org/freedesktop/monado/ipc/Client.java
+++ b/src/xrt/ipc/android/src/main/java/org/freedesktop/monado/ipc/Client.java
@@ -100,8 +100,14 @@ public class Client implements ServiceConnection {
         }
         intent = null;
 
-        //! @todo do we close this first?
-        fd = null;
+        if (fd != null) {
+            try {
+                fd.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+            fd = null;
+        }
     }
 
     /**
diff --git a/src/xrt/ipc/client/ipc_client_instance.c b/src/xrt/ipc/client/ipc_client_instance.c
index 94ff7cb5b..5dce95eed 100644
--- a/src/xrt/ipc/client/ipc_client_instance.c
+++ b/src/xrt/ipc/client/ipc_client_instance.c
@@ -28,6 +28,7 @@
 #include <sys/stat.h>
 #include <sys/mman.h>
 #include <sys/un.h>
+#include <errno.h>
 #include <fcntl.h>
 #include <unistd.h>
 
@@ -91,6 +92,13 @@ ipc_connect(struct ipc_connection *ipc_c)
 		IPC_ERROR(ipc_c, "Service Connect error!");
 		return false;
 	}
+	// The ownership belongs to the Java object. Dup because the fd will be
+	// closed when client destroy.
+	socket = dup(socket);
+	if (socket < 0) {
+		IPC_ERROR(ipc_c, "Failed to dup fd with error %d!", errno);
+		return false;
+	}
 
 	ipc_c->imc.socket_fd = socket;
 	ipc_c->imc.ll = ipc_c->ll;