From 371172bcfd869867cf1c2847fcbbb3aa22adddb6 Mon Sep 17 00:00:00 2001
From: Colin Walters <walters@verbum.org>
Date: Tue, 14 Apr 2015 08:40:42 -0400
Subject: [PATCH] fdio: Fix errno handling from posix_fallocate() and
 loop_write()

For extra fun, both of these functions have different error handling
schemes.  `posix_fallocate` does *not* set `errno` because...  I'm not
sure.  Maybe POSIX was trying a new function design?

`loop_write` uses the systemd error handling style which returns
`-errno`, so we need to set errno back so that the macro can propagate
it into the `GError`.
---
 glnx-fdio.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/glnx-fdio.c b/glnx-fdio.c
index ca2c01065..a4362094a 100644
--- a/glnx-fdio.c
+++ b/glnx-fdio.c
@@ -647,6 +647,7 @@ glnx_file_replace_contents_with_perms_at (int                   dfd,
                                           GError              **error)
 {
   gboolean ret = FALSE;
+  int r;
   /* We use the /proc/self trick as there's no mkostemp_at() yet */
   g_autofree char *tmppath = g_strdup_printf ("/proc/self/fd/%d/.tmpXXXXXX", dfd);
   glnx_fd_close int fd = -1;
@@ -663,14 +664,18 @@ glnx_file_replace_contents_with_perms_at (int                   dfd,
   if (len == -1)
     len = strlen ((char*)buf);
 
-  if (posix_fallocate (fd, 0, len))
+  /* Note that posix_fallocate does *not* set errno but returns it. */
+  r = posix_fallocate (fd, 0, len);
+  if (r != 0)
     {
+      errno = r;
       glnx_set_error_from_errno (error);
       goto out;
     }
 
-  if (loop_write (fd, buf, len) != 0)
+  if ((r = loop_write (fd, buf, len)) != 0)
     {
+      errno = -r;
       glnx_set_error_from_errno (error);
       goto out;
     }
-- 
GitLab