From 9d995a362009ae01bca14c781e14d5623ad27cd6 Mon Sep 17 00:00:00 2001
From: Colin Walters <walters@verbum.org>
Date: Mon, 11 Sep 2017 17:17:12 -0400
Subject: [PATCH] fdio: Support taking ownership of tmpfile fd

While reading a strace I noticed a double close in the tests; this was because
we were missing an assignment to `-1` in the tests. However, let's make
supporting this clearer by explicitly supporting the fd being `-1` while still
setting the `initialized` variable to `FALSE`. We also add the `EBADF` assertion
checking.
---
 glnx-fdio.c               | 8 +++++---
 tests/test-libglnx-fdio.c | 1 +
 2 files changed, 6 insertions(+), 3 deletions(-)

diff --git a/glnx-fdio.c b/glnx-fdio.c
index e8e2167f5..0046807ad 100644
--- a/glnx-fdio.c
+++ b/glnx-fdio.c
@@ -168,9 +168,11 @@ glnx_tmpfile_clear (GLnxTmpfile *tmpf)
     return;
   if (!tmpf->initialized)
     return;
-  if (tmpf->fd == -1)
-    return;
-  (void) close (tmpf->fd);
+  if (tmpf->fd != -1)
+    {
+      if (close (tmpf->fd) < 0)
+        g_assert (errno != EBADF);
+    }
   /* If ->path is set, we're likely aborting due to an error. Clean it up */
   if (tmpf->path)
     {
diff --git a/tests/test-libglnx-fdio.c b/tests/test-libglnx-fdio.c
index 4b81a9573..36ded80c3 100644
--- a/tests/test-libglnx-fdio.c
+++ b/tests/test-libglnx-fdio.c
@@ -171,6 +171,7 @@ test_stdio_file (void)
   if (!glnx_open_anonymous_tmpfile (O_RDWR|O_CLOEXEC, &tmpf, error))
     goto out;
   f = fdopen (tmpf.fd, "w");
+  tmpf.fd = -1; /* Ownership was transferred via fdopen() */
   if (!f)
     {
       (void)glnx_throw_errno_prefix (error, "fdopen");
-- 
GitLab