view lib/strerror_r.c @ 16366:bb182ee4a09d

maint: replace FSF snail-mail addresses with URLs * config/argz.mk, lib/accept4.c, lib/alignof.h, lib/alloca.in.h: * lib/alphasort.c, lib/arcfour.c, lib/arcfour.h, lib/arctwo.c: * lib/arctwo.h, lib/argz.c, lib/arpa_inet.in.h, lib/asnprintf.c: * lib/asprintf.c, lib/assert.in.h, lib/base32.c, lib/base32.h: * lib/base64.c, lib/base64.h, lib/c-ctype.c, lib/c-ctype.h: * lib/c-strcase.h, lib/c-strcasecmp.c, lib/c-strncasecmp.c: * lib/check-version.c, lib/check-version.h, lib/config.charset: * lib/ctype.in.h, lib/des.c, lib/des.h, lib/dup3.c, lib/errno.in.h: * lib/float+.h, lib/fnmatch.c, lib/fnmatch.in.h, lib/fnmatch_loop.c: * lib/fseeko.c, lib/gai_strerror.c, lib/gc-gnulib.c: * lib/gc-libgcrypt.c, lib/gc-pbkdf2-sha1.c, lib/gc.h: * lib/getaddrinfo.c, lib/getdelim.c, lib/getfilecon.c, lib/getline.c: * lib/getlogin_r.c, lib/getpass.c, lib/getpass.h, lib/gettext.h: * lib/gettimeofday.c, lib/glob.in.h, lib/glthread/cond.c: * lib/glthread/cond.h, lib/glthread/lock.c, lib/glthread/lock.h: * lib/glthread/thread.c, lib/glthread/thread.h: * lib/glthread/threadlib.c, lib/glthread/yield.h, lib/hmac-md5.c: * lib/hmac-sha1.c, lib/hmac.h, lib/iconv.c, lib/iconv.in.h: * lib/iconv_close.c, lib/iconv_open.c, lib/inet_ntop.c, lib/isfinite.c: * lib/isinf.c, lib/iswblank.c, lib/langinfo.in.h, lib/link.c: * lib/localcharset.c, lib/localcharset.h, lib/lseek.c, lib/malloc.c: * lib/malloca.c, lib/malloca.h, lib/md2.c, lib/md2.h, lib/md4.c: * lib/md4.h, lib/md5.c, lib/md5.h, lib/memmem.c, lib/mempcpy.c: * lib/memset.c, lib/memxor.c, lib/memxor.h, lib/minmax.h, lib/mktime.c: * lib/msvc-inval.c, lib/msvc-inval.h, lib/msvc-nothrow.c: * lib/msvc-nothrow.h, lib/netdb.in.h, lib/netinet_in.in.h, lib/nproc.c: * lib/nproc.h, lib/obstack_printf.c, lib/pathmax.h, lib/pipe.c: * lib/pipe2.c, lib/poll.c, lib/poll.in.h, lib/printf-args.c: * lib/printf-args.h, lib/printf-parse.c, lib/printf-parse.h: * lib/pselect.c, lib/pthread.in.h, lib/pty-private.h, lib/pty.in.h: * lib/read-file.c, lib/read-file.h, lib/ref-add.sin, lib/ref-del.sin: * lib/regcomp.c, lib/regex.c, lib/regex.h, lib/regex_internal.c: * lib/regex_internal.h, lib/regexec.c, lib/rijndael-alg-fst.c: * lib/rijndael-alg-fst.h, lib/rijndael-api-fst.c: * lib/rijndael-api-fst.h, lib/rint.c, lib/rintf.c, lib/rintl.c: * lib/round.c, lib/roundf.c, lib/roundl.c, lib/scandir.c, lib/select.c: * lib/sha1.c, lib/sha1.h, lib/size_max.h, lib/snprintf.c: * lib/stdalign.in.h, lib/stdarg.in.h, lib/stdbool.in.h: * lib/stddef.in.h, lib/stdint.in.h, lib/stdio.in.h, lib/str-kmp.h: * lib/str-two-way.h, lib/strcasecmp.c, lib/strcasestr.c, lib/strdup.c: * lib/striconv.c, lib/striconv.h, lib/string.in.h, lib/strings.in.h: * lib/strncasecmp.c, lib/strndup.c, lib/strnlen.c, lib/strpbrk.c: * lib/strptime.c, lib/strsep.c, lib/strstr.c, lib/strverscmp.c: * lib/sys_file.in.h, lib/sys_ioctl.in.h, lib/sys_select.in.h: * lib/sys_socket.in.h, lib/sys_stat.in.h, lib/sys_time.in.h: * lib/sys_times.in.h, lib/sys_types.in.h, lib/sys_uio.in.h: * lib/sys_utsname.in.h, lib/sys_wait.in.h, lib/tcgetsid.c: * lib/termios.in.h, lib/time.in.h, lib/time_r.c, lib/timegm.c: * lib/times.c, lib/unictype/3level.h, lib/unictype/3levelbit.h: * lib/unistd.in.h, lib/vasnprintf.c, lib/vasnprintf.h, lib/vasprintf.c: * lib/vsnprintf.c, lib/waitpid.c, lib/wchar.in.h, lib/wctype.in.h: * lib/xsize.h, tests/test-closein.c, tests/test-des.c: * tests/test-fclose.c, tests/test-fgetc.c, tests/test-filevercmp.c: * tests/test-fputc.c, tests/test-fread.c, tests/test-fwrite.c: * tests/test-gc-arcfour.c, tests/test-gc-arctwo.c, tests/test-gc-des.c: * tests/test-gc-hmac-md5.c, tests/test-gc-hmac-sha1.c: * tests/test-gc-md2.c, tests/test-gc-md4.c, tests/test-gc-md5.c: * tests/test-gc-pbkdf2-sha1.c, tests/test-gc-rijndael.c: * tests/test-gc-sha1.c, tests/test-gc.c, tests/test-getdelim.c: * tests/test-getline.c, tests/test-getndelim2.c, tests/test-md2.c: * tests/test-md4.c, tests/test-parse-datetime.c, tests/test-perror.c: * tests/test-perror2.c, tests/test-pipe.c, tests/test-pipe2.c: * tests/test-poll.c, tests/test-quotearg-simple.c: * tests/test-quotearg.c, tests/test-quotearg.h: * tests/test-round-ieee.c, tests/test-round1.c: * tests/test-roundf-ieee.c, tests/test-roundf1.c: * tests/test-roundl-ieee.c, tests/test-roundl.c: * tests/test-safe-alloc.c, tests/test-sigpipe.c: * tests/test-spawn-pipe-child.c, tests/test-spawn-pipe-main.c: * tests/test-strerror.c, tests/test-strerror_r.c: * tests/test-strsignal.c, tests/test-strverscmp.c: * tests/test-xmemdup0.c: Replace FSF snail mail addresses with URLs, as per GNU coding standards. See glibc bug <http://sourceware.org/bugzilla/show_bug.cgi?id=13673>.
author Paul Eggert <eggert@cs.ucla.edu>
date Thu, 09 Feb 2012 21:39:05 -0800
parents ec738d6aeef5
children fb659d60019f
line wrap: on
line source

/* strerror_r.c --- POSIX compatible system error routine

   Copyright (C) 2010-2012 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

/* Written by Bruno Haible <bruno@clisp.org>, 2010.  */

#include <config.h>

/* Enable declaration of sys_nerr and sys_errlist in <errno.h> on NetBSD.  */
#define _NETBSD_SOURCE 1

/* Specification.  */
#include <string.h>

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

#include "strerror-override.h"

#if (__GLIBC__ >= 2 || defined __UCLIBC__ || defined __CYGWIN__) && HAVE___XPG_STRERROR_R /* glibc >= 2.3.4, cygwin >= 1.7.9 */

# define USE_XPG_STRERROR_R 1

#elif HAVE_DECL_STRERROR_R && !(__GLIBC__ >= 2 || defined __UCLIBC__ || defined __CYGWIN__)

/* The system's strerror_r function is OK, except that its third argument
   is 'int', not 'size_t', or its return type is wrong.  */

# include <limits.h>

# define USE_SYSTEM_STRERROR_R 1

#else /* (__GLIBC__ >= 2 || defined __UCLIBC__ || defined __CYGWIN__ ? !HAVE___XPG_STRERROR_R : !HAVE_DECL_STRERROR_R) */

/* Use the system's strerror().  Exclude glibc and cygwin because the
   system strerror_r has the wrong return type, and cygwin 1.7.9
   strerror_r clobbers strerror.  */
# undef strerror

# define USE_SYSTEM_STRERROR 1

# if defined __NetBSD__ || defined __hpux || ((defined _WIN32 || defined __WIN32__) && !defined __CYGWIN__) || defined __sgi || (defined __sun && !defined _LP64) || defined __CYGWIN__

/* No locking needed.  */

/* Get catgets internationalization functions.  */
#  if HAVE_CATGETS
#   include <nl_types.h>
#  endif

/* Get sys_nerr, sys_errlist on HP-UX (otherwise only declared in C++ mode).
   Get sys_nerr, sys_errlist on IRIX (otherwise only declared with _SGIAPI).  */
#  if defined __hpux || defined __sgi
extern int sys_nerr;
extern char *sys_errlist[];
#  endif

/* Get sys_nerr on Solaris.  */
#  if defined __sun && !defined _LP64
extern int sys_nerr;
#  endif

# else

#  include "glthread/lock.h"

/* This lock protects the buffer returned by strerror().  We assume that
   no other uses of strerror() exist in the program.  */
gl_lock_define_initialized(static, strerror_lock)

# endif

#endif

/* On MSVC, there is no snprintf() function, just a _snprintf().
   It is of lower quality, but sufficient for the simple use here.
   We only have to make sure to NUL terminate the result (_snprintf
   does not NUL terminate, like strncpy).  */
#if !HAVE_SNPRINTF
static int
local_snprintf (char *buf, size_t buflen, const char *format, ...)
{
  va_list args;
  int result;

  va_start (args, format);
  result = _vsnprintf (buf, buflen, format, args);
  va_end (args);
  if (buflen > 0 && (result < 0 || result >= buflen))
    buf[buflen - 1] = '\0';
  return result;
}
# define snprintf local_snprintf
#endif

/* Copy as much of MSG into BUF as possible, without corrupting errno.
   Return 0 if MSG fit in BUFLEN, otherwise return ERANGE.  */
static int
safe_copy (char *buf, size_t buflen, const char *msg)
{
  size_t len = strlen (msg);
  int ret;

  if (len < buflen)
    {
      /* Although POSIX allows memcpy() to corrupt errno, we don't
         know of any implementation where this is a real problem.  */
      memcpy (buf, msg, len + 1);
      ret = 0;
    }
  else
    {
      memcpy (buf, msg, buflen - 1);
      buf[buflen - 1] = '\0';
      ret = ERANGE;
    }
  return ret;
}


int
strerror_r (int errnum, char *buf, size_t buflen)
#undef strerror_r
{
  /* Filter this out now, so that rest of this replacement knows that
     there is room for a non-empty message and trailing NUL.  */
  if (buflen <= 1)
    {
      if (buflen)
        *buf = '\0';
      return ERANGE;
    }
  *buf = '\0';

  /* Check for gnulib overrides.  */
  {
    char const *msg = strerror_override (errnum);

    if (msg)
      return safe_copy (buf, buflen, msg);
  }

  {
    int ret;
    int saved_errno = errno;

#if USE_XPG_STRERROR_R

    {
      extern int __xpg_strerror_r (int errnum, char *buf, size_t buflen);

      ret = __xpg_strerror_r (errnum, buf, buflen);
      if (ret < 0)
        ret = errno;
      if (!*buf)
        {
          /* glibc 2.13 would not touch buf on err, so we have to fall
             back to GNU strerror_r which always returns a thread-safe
             untruncated string to (partially) copy into our buf.  */
          safe_copy (buf, buflen, strerror_r (errnum, buf, buflen));
        }
    }

#elif USE_SYSTEM_STRERROR_R

    if (buflen > INT_MAX)
      buflen = INT_MAX;

# ifdef __hpux
    /* On HP-UX 11.31, strerror_r always fails when buflen < 80; it
       also fails to change buf on EINVAL.  */
    {
      char stackbuf[80];

      if (buflen < sizeof stackbuf)
        {
          ret = strerror_r (errnum, stackbuf, sizeof stackbuf);
          if (ret == 0)
            ret = safe_copy (buf, buflen, stackbuf);
        }
      else
        ret = strerror_r (errnum, buf, buflen);
    }
# else
    ret = strerror_r (errnum, buf, buflen);

    /* Some old implementations may return (-1, EINVAL) instead of EINVAL.  */
    if (ret < 0)
      ret = errno;
# endif

# ifdef _AIX
    /* AIX returns 0 rather than ERANGE when truncating strings; try
       again until we are sure we got the entire string.  */
    if (!ret && strlen (buf) == buflen - 1)
      {
        char stackbuf[STACKBUF_LEN];
        size_t len;
        strerror_r (errnum, stackbuf, sizeof stackbuf);
        len = strlen (stackbuf);
        /* STACKBUF_LEN should have been large enough.  */
        if (len + 1 == sizeof stackbuf)
          abort ();
        if (buflen <= len)
          ret = ERANGE;
      }
# else
    /* Solaris 10 does not populate buf on ERANGE.  OpenBSD 4.7
       truncates early on ERANGE rather than return a partial integer.
       We prefer the maximal string.  We set buf[0] earlier, and we
       know of no implementation that modifies buf to be an
       unterminated string, so this strlen should be portable in
       practice (rather than pulling in a safer strnlen).  */
    if (ret == ERANGE && strlen (buf) < buflen - 1)
      {
        char stackbuf[STACKBUF_LEN];

        /* STACKBUF_LEN should have been large enough.  */
        if (strerror_r (errnum, stackbuf, sizeof stackbuf) == ERANGE)
          abort ();
        safe_copy (buf, buflen, stackbuf);
      }
# endif

#else /* USE_SYSTEM_STRERROR */

    /* Try to do what strerror (errnum) does, but without clobbering the
       buffer used by strerror().  */

# if defined __NetBSD__ || defined __hpux || ((defined _WIN32 || defined __WIN32__) && !defined __CYGWIN__) || defined __CYGWIN__ /* NetBSD, HP-UX, native Windows, Cygwin */

    /* NetBSD:         sys_nerr, sys_errlist are declared through _NETBSD_SOURCE
                       and <errno.h> above.
       HP-UX:          sys_nerr, sys_errlist are declared explicitly above.
       native Windows: sys_nerr, sys_errlist are declared in <stdlib.h>.
       Cygwin:         sys_nerr, sys_errlist are declared in <errno.h>.  */
    if (errnum >= 0 && errnum < sys_nerr)
      {
#  if HAVE_CATGETS && (defined __NetBSD__ || defined __hpux)
#   if defined __NetBSD__
        nl_catd catd = catopen ("libc", NL_CAT_LOCALE);
        const char *errmsg =
          (catd != (nl_catd)-1
           ? catgets (catd, 1, errnum, sys_errlist[errnum])
           : sys_errlist[errnum]);
#   endif
#   if defined __hpux
        nl_catd catd = catopen ("perror", NL_CAT_LOCALE);
        const char *errmsg =
          (catd != (nl_catd)-1
           ? catgets (catd, 1, 1 + errnum, sys_errlist[errnum])
           : sys_errlist[errnum]);
#   endif
#  else
        const char *errmsg = sys_errlist[errnum];
#  endif
        if (errmsg == NULL || *errmsg == '\0')
          ret = EINVAL;
        else
          ret = safe_copy (buf, buflen, errmsg);
#  if HAVE_CATGETS && (defined __NetBSD__ || defined __hpux)
        if (catd != (nl_catd)-1)
          catclose (catd);
#  endif
      }
    else
      ret = EINVAL;

# elif defined __sgi || (defined __sun && !defined _LP64) /* IRIX, Solaris <= 9 32-bit */

    /* For a valid error number, the system's strerror() function returns
       a pointer to a not copied string, not to a buffer.  */
    if (errnum >= 0 && errnum < sys_nerr)
      {
        char *errmsg = strerror (errnum);

        if (errmsg == NULL || *errmsg == '\0')
          ret = EINVAL;
        else
          ret = safe_copy (buf, buflen, errmsg);
      }
    else
      ret = EINVAL;

# else

    gl_lock_lock (strerror_lock);

    {
      char *errmsg = strerror (errnum);

      /* For invalid error numbers, strerror() on
           - IRIX 6.5 returns NULL,
           - HP-UX 11 returns an empty string.  */
      if (errmsg == NULL || *errmsg == '\0')
        ret = EINVAL;
      else
        ret = safe_copy (buf, buflen, errmsg);
    }

    gl_lock_unlock (strerror_lock);

# endif

#endif

    if (ret == EINVAL && !*buf)
      snprintf (buf, buflen, "Unknown error %d", errnum);

    errno = saved_errno;
    return ret;
  }
}