win32: wrap socket close() with an exception handler
authorMarc-André Lureau <marcandre.lureau@redhat.com>
Mon, 15 May 2023 13:24:40 +0000 (17:24 +0400)
committerMarc-André Lureau <marcandre.lureau@redhat.com>
Sun, 28 May 2023 09:08:25 +0000 (13:08 +0400)
Since commit abe34282 ("win32: avoid mixing SOCKET and file descriptor
space"), we set HANDLE_FLAG_PROTECT_FROM_CLOSE on the socket FD, to
prevent closing the HANDLE with CloseHandle. This raises an exception
which under gdb is fatal, and qemu exits.

Let's catch the expected error instead.

Note: this appears to work, but the mingw64 macro is not well documented
or tested, and it's not obvious how it is meant to be used.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Message-Id: <20230515132440.1025315-1-marcandre.lureau@redhat.com>

include/sysemu/os-win32.h
util/oslib-win32.c

index 15c296e0eb1f66de165254a926c5ef9ffe97081c..65f6c9ea57e06839221f4d0d48fb7e51ca1f6c8f 100644 (file)
@@ -259,6 +259,10 @@ ssize_t qemu_recv_wrap(int sockfd, void *buf, size_t len, int flags);
 ssize_t qemu_recvfrom_wrap(int sockfd, void *buf, size_t len, int flags,
                            struct sockaddr *addr, socklen_t *addrlen);
 
+EXCEPTION_DISPOSITION
+win32_close_exception_handler(struct _EXCEPTION_RECORD*, void*,
+                              struct _CONTEXT*, void*);
+
 #ifdef __cplusplus
 }
 #endif
index a98638729a15d0758dd3f85d815d8dc2de281f27..fafbab80b42cbd6cb236a4e26431aa231b57a0df 100644 (file)
@@ -479,6 +479,13 @@ int qemu_bind_wrap(int sockfd, const struct sockaddr *addr,
     return ret;
 }
 
+EXCEPTION_DISPOSITION
+win32_close_exception_handler(struct _EXCEPTION_RECORD*,
+                              void*, struct _CONTEXT*, void*)
+{
+    return EXCEPTION_EXECUTE_HANDLER;
+}
+
 #undef close
 int qemu_close_socket_osfhandle(int fd)
 {
@@ -504,12 +511,16 @@ int qemu_close_socket_osfhandle(int fd)
         return -1;
     }
 
-    /*
-     * close() returns EBADF since we PROTECT_FROM_CLOSE the underlying handle,
-     * but the FD is actually freed
-     */
-    if (close(fd) < 0 && errno != EBADF) {
-        return -1;
+    __try1(win32_close_exception_handler) {
+        /*
+         * close() returns EBADF since we PROTECT_FROM_CLOSE the underlying
+         * handle, but the FD is actually freed
+         */
+        if (close(fd) < 0 && errno != EBADF) {
+            return -1;
+        }
+    }
+    __except1 {
     }
 
     if (!SetHandleInformation((HANDLE)s, flags, flags)) {