delete socket on vfu_ctx_destroy (#702)

fixes #660

Signed-off-by: Thanos Makatos <thanos.makatos@nutanix.com>
Reviewed-by: John Levon <john.levon@nutanix.com>
Reviewed-by: Swapnil Ingle <swapnil.ingle@nutanix.com>
diff --git a/lib/libvfio-user.c b/lib/libvfio-user.c
index 5ce5767..3b3f9a6 100644
--- a/lib/libvfio-user.c
+++ b/lib/libvfio-user.c
@@ -1637,7 +1637,6 @@
         vfu_log(vfu_ctx, LOG_WARNING, "failed to reset context: %m");
     }
 
-    free(vfu_ctx->uuid);
     free(vfu_ctx->pci.config_space);
 
     if (vfu_ctx->tran->fini != NULL) {
@@ -1651,6 +1650,7 @@
     free_regions(vfu_ctx);
     free(vfu_ctx->migration);
     free(vfu_ctx->irqs);
+    free(vfu_ctx->uuid);
     free(vfu_ctx);
 }
 
diff --git a/lib/tran_sock.c b/lib/tran_sock.c
index b894fb3..7c4e30b 100644
--- a/lib/tran_sock.c
+++ b/lib/tran_sock.c
@@ -414,6 +414,7 @@
     ret = listen(ts->listen_fd, 0);
     if (ret < 0) {
         ret = errno;
+        (void) unlink(vfu_ctx->uuid);
     }
 
 out:
@@ -651,10 +652,13 @@
 
     ts = vfu_ctx->tran_data;
 
-    if (ts != NULL && ts->listen_fd != -1) {
-        // FIXME: handle EINTR
-        (void) close(ts->listen_fd);
-        ts->listen_fd = -1;
+    if (ts != NULL) {
+        (void) unlink(vfu_ctx->uuid);
+        if (ts->listen_fd != -1) {
+            // FIXME: handle EINTR
+            (void) close(ts->listen_fd);
+            ts->listen_fd = -1;
+        }
     }
 
     free(vfu_ctx->tran_data);
diff --git a/samples/gpio-pci-idio-16.c b/samples/gpio-pci-idio-16.c
index 4872d3b..b50f407 100644
--- a/samples/gpio-pci-idio-16.c
+++ b/samples/gpio-pci-idio-16.c
@@ -243,6 +243,9 @@
 
     ret = vfu_attach_ctx(vfu_ctx);
     if (ret < 0) {
+        int _errno = errno;
+        vfu_destroy_ctx(vfu_ctx);
+        errno = _errno;
         err(EXIT_FAILURE, "failed to attach device");
     }
 
diff --git a/test/py/test_destroy.py b/test/py/test_destroy.py
index 713c1fb..ffe4506 100644
--- a/test/py/test_destroy.py
+++ b/test/py/test_destroy.py
@@ -53,6 +53,7 @@
     vfu_destroy_ctx(ctx)
     assert mock_quiesce.call_count == 0
     mock_reset.assert_called_once_with(ctx, VFU_RESET_LOST_CONN)
+    assert not os.path.exists(SOCK_PATH)
 
 
 # ex: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab: #