Consistently save errno immediately after the operation setting it

Prevent the situation where errno is set by function A, then function B
is called (which is typically _(), but could be anything else) and it
overwrites errno, then errno is checked by the caller.

errno is a horrific API, and we need to be careful to save its value as
soon as a function call (which might set it) returns. i.e. Follow the
pattern:
  int errsv, ret;
  ret = some_call_which_might_set_errno ();
  errsv = errno;

  if (ret < 0)
    puts (strerror (errsv));

This patch implements that pattern throughout GLib. There might be a few
places in the test code which still use errno directly. They should be
ported as necessary. It doesn’t modify all the call sites like this:
  if (some_call_which_might_set_errno () && errno == ESOMETHING)
since the refactoring involved is probably more harmful than beneficial
there. It does, however, refactor other call sites regardless of whether
they were originally buggy.

https://bugzilla.gnome.org/show_bug.cgi?id=785577
This commit is contained in:
Philip Withnall
2017-07-31 11:30:55 +01:00
parent 41a4a70b43
commit 5cddde1fb2
44 changed files with 337 additions and 166 deletions

View File

@@ -232,8 +232,9 @@ run_tests (void)
if ((k = read (pipeup[0], &n, sizeof (n))) != sizeof (n))
{
int errsv = errno;
if (k == -1)
fprintf (stderr, "Read error: %s\n", g_strerror (errno));
fprintf (stderr, "Read error: %s\n", g_strerror (errsv));
else
fprintf (stderr, "Wanted to read %d bytes, got %d\n",
sizeof (n), k);
@@ -242,8 +243,9 @@ run_tests (void)
if ((k = read (pipeup[0], buf, n)) != n)
{
int errsv = errno;
if (k == -1)
fprintf (stderr, "Read error: %s\n", g_strerror (errno));
fprintf (stderr, "Read error: %s\n", g_strerror (errsv));
else
fprintf (stderr, "Wanted to read %d bytes, got %d\n",
n, k);
@@ -254,14 +256,16 @@ run_tests (void)
if (write (pipedown[1], &n, sizeof (n)) == -1 ||
write (pipedown[1], "Bye then", n) == -1)
{
fprintf (stderr, "Write error: %s\n", g_strerror (errno));
int errsv = errno;
fprintf (stderr, "Write error: %s\n", g_strerror (errsv));
exit (1);
}
if ((k = read (pipeup[0], &n, sizeof (n))) != sizeof (n))
{
int errsv = errno;
if (k == -1)
fprintf (stderr, "Read error: %s\n", g_strerror (errno));
fprintf (stderr, "Read error: %s\n", g_strerror (errsv));
else
fprintf (stderr, "Wanted to read %d bytes, got %d\n",
sizeof (n), k);
@@ -270,8 +274,9 @@ run_tests (void)
if ((k = read (pipeup[0], buf, n)) != n)
{
int errsv = errno;
if (k == -1)
fprintf (stderr, "Read error: %s\n", g_strerror (errno));
fprintf (stderr, "Read error: %s\n", g_strerror (errsv));
else
fprintf (stderr, "Wanted to read %d bytes, got %d\n",
n, k);