be76b0d37a42c30e6607ebf2812ed3b15b235b02
[gnulib.git] / lib / strerror_r.c
1 /* strerror_r.c --- POSIX compatible system error routine
2
3    Copyright (C) 2010-2012 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Written by Bruno Haible <bruno@clisp.org>, 2010.  */
19
20 #include <config.h>
21
22 /* Enable declaration of sys_nerr and sys_errlist in <errno.h> on NetBSD.  */
23 #define _NETBSD_SOURCE 1
24
25 /* Specification.  */
26 #include <string.h>
27
28 #include <errno.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31
32 #include "strerror-override.h"
33
34 #if (__GLIBC__ >= 2 || defined __UCLIBC__ || defined __CYGWIN__) && HAVE___XPG_STRERROR_R /* glibc >= 2.3.4, cygwin >= 1.7.9 */
35
36 # define USE_XPG_STRERROR_R 1
37
38 #elif HAVE_DECL_STRERROR_R && !(__GLIBC__ >= 2 || defined __UCLIBC__ || defined __CYGWIN__)
39
40 /* The system's strerror_r function is OK, except that its third argument
41    is 'int', not 'size_t', or its return type is wrong.  */
42
43 # include <limits.h>
44
45 # define USE_SYSTEM_STRERROR_R 1
46
47 #else /* (__GLIBC__ >= 2 || defined __UCLIBC__ || defined __CYGWIN__ ? !HAVE___XPG_STRERROR_R : !HAVE_DECL_STRERROR_R) */
48
49 /* Use the system's strerror().  Exclude glibc and cygwin because the
50    system strerror_r has the wrong return type, and cygwin 1.7.9
51    strerror_r clobbers strerror.  */
52 # undef strerror
53
54 # define USE_SYSTEM_STRERROR 1
55
56 # if defined __NetBSD__ || defined __hpux || ((defined _WIN32 || defined __WIN32__) && !defined __CYGWIN__) || defined __sgi || (defined __sun && !defined _LP64) || defined __CYGWIN__
57
58 /* No locking needed.  */
59
60 /* Get catgets internationalization functions.  */
61 #  if HAVE_CATGETS
62 #   include <nl_types.h>
63 #  endif
64
65 /* Get sys_nerr, sys_errlist on HP-UX (otherwise only declared in C++ mode).
66    Get sys_nerr, sys_errlist on IRIX (otherwise only declared with _SGIAPI).  */
67 #  if defined __hpux || defined __sgi
68 extern int sys_nerr;
69 extern char *sys_errlist[];
70 #  endif
71
72 /* Get sys_nerr on Solaris.  */
73 #  if defined __sun && !defined _LP64
74 extern int sys_nerr;
75 #  endif
76
77 # else
78
79 #  include "glthread/lock.h"
80
81 /* This lock protects the buffer returned by strerror().  We assume that
82    no other uses of strerror() exist in the program.  */
83 gl_lock_define_initialized(static, strerror_lock)
84
85 # endif
86
87 #endif
88
89 /* On MSVC, there is no snprintf() function, just a _snprintf().
90    It is of lower quality, but sufficient for the simple use here.
91    We only have to make sure to NUL terminate the result (_snprintf
92    does not NUL terminate, like strncpy).  */
93 #if !HAVE_SNPRINTF
94 static int
95 local_snprintf (char *buf, size_t buflen, const char *format, ...)
96 {
97   va_list args;
98   int result;
99
100   va_start (args, format);
101   result = _vsnprintf (buf, buflen, format, args);
102   va_end (args);
103   if (buflen > 0 && (result < 0 || result >= buflen))
104     buf[buflen - 1] = '\0';
105   return result;
106 }
107 # define snprintf local_snprintf
108 #endif
109
110 /* Copy as much of MSG into BUF as possible, without corrupting errno.
111    Return 0 if MSG fit in BUFLEN, otherwise return ERANGE.  */
112 static int
113 safe_copy (char *buf, size_t buflen, const char *msg)
114 {
115   size_t len = strlen (msg);
116   int ret;
117
118   if (len < buflen)
119     {
120       /* Although POSIX allows memcpy() to corrupt errno, we don't
121          know of any implementation where this is a real problem.  */
122       memcpy (buf, msg, len + 1);
123       ret = 0;
124     }
125   else
126     {
127       memcpy (buf, msg, buflen - 1);
128       buf[buflen - 1] = '\0';
129       ret = ERANGE;
130     }
131   return ret;
132 }
133
134
135 int
136 strerror_r (int errnum, char *buf, size_t buflen)
137 #undef strerror_r
138 {
139   /* Filter this out now, so that rest of this replacement knows that
140      there is room for a non-empty message and trailing NUL.  */
141   if (buflen <= 1)
142     {
143       if (buflen)
144         *buf = '\0';
145       return ERANGE;
146     }
147   *buf = '\0';
148
149   /* Check for gnulib overrides.  */
150   {
151     char const *msg = strerror_override (errnum);
152
153     if (msg)
154       return safe_copy (buf, buflen, msg);
155   }
156
157   {
158     int ret;
159     int saved_errno = errno;
160
161 #if USE_XPG_STRERROR_R
162
163     {
164       extern int __xpg_strerror_r (int errnum, char *buf, size_t buflen);
165
166       ret = __xpg_strerror_r (errnum, buf, buflen);
167       if (ret < 0)
168         ret = errno;
169       if (!*buf)
170         {
171           /* glibc 2.13 would not touch buf on err, so we have to fall
172              back to GNU strerror_r which always returns a thread-safe
173              untruncated string to (partially) copy into our buf.  */
174           safe_copy (buf, buflen, strerror_r (errnum, buf, buflen));
175         }
176     }
177
178 #elif USE_SYSTEM_STRERROR_R
179
180     if (buflen > INT_MAX)
181       buflen = INT_MAX;
182
183 # ifdef __hpux
184     /* On HP-UX 11.31, strerror_r always fails when buflen < 80; it
185        also fails to change buf on EINVAL.  */
186     {
187       char stackbuf[80];
188
189       if (buflen < sizeof stackbuf)
190         {
191           ret = strerror_r (errnum, stackbuf, sizeof stackbuf);
192           if (ret == 0)
193             ret = safe_copy (buf, buflen, stackbuf);
194         }
195       else
196         ret = strerror_r (errnum, buf, buflen);
197     }
198 # else
199     ret = strerror_r (errnum, buf, buflen);
200
201     /* Some old implementations may return (-1, EINVAL) instead of EINVAL.  */
202     if (ret < 0)
203       ret = errno;
204 # endif
205
206 # ifdef _AIX
207     /* AIX returns 0 rather than ERANGE when truncating strings; try
208        again until we are sure we got the entire string.  */
209     if (!ret && strlen (buf) == buflen - 1)
210       {
211         char stackbuf[STACKBUF_LEN];
212         size_t len;
213         strerror_r (errnum, stackbuf, sizeof stackbuf);
214         len = strlen (stackbuf);
215         /* STACKBUF_LEN should have been large enough.  */
216         if (len + 1 == sizeof stackbuf)
217           abort ();
218         if (buflen <= len)
219           ret = ERANGE;
220       }
221 # else
222     /* Solaris 10 does not populate buf on ERANGE.  OpenBSD 4.7
223        truncates early on ERANGE rather than return a partial integer.
224        We prefer the maximal string.  We set buf[0] earlier, and we
225        know of no implementation that modifies buf to be an
226        unterminated string, so this strlen should be portable in
227        practice (rather than pulling in a safer strnlen).  */
228     if (ret == ERANGE && strlen (buf) < buflen - 1)
229       {
230         char stackbuf[STACKBUF_LEN];
231
232         /* STACKBUF_LEN should have been large enough.  */
233         if (strerror_r (errnum, stackbuf, sizeof stackbuf) == ERANGE)
234           abort ();
235         safe_copy (buf, buflen, stackbuf);
236       }
237 # endif
238
239 #else /* USE_SYSTEM_STRERROR */
240
241     /* Try to do what strerror (errnum) does, but without clobbering the
242        buffer used by strerror().  */
243
244 # if defined __NetBSD__ || defined __hpux || ((defined _WIN32 || defined __WIN32__) && !defined __CYGWIN__) || defined __CYGWIN__ /* NetBSD, HP-UX, native Windows, Cygwin */
245
246     /* NetBSD:         sys_nerr, sys_errlist are declared through _NETBSD_SOURCE
247                        and <errno.h> above.
248        HP-UX:          sys_nerr, sys_errlist are declared explicitly above.
249        native Windows: sys_nerr, sys_errlist are declared in <stdlib.h>.
250        Cygwin:         sys_nerr, sys_errlist are declared in <errno.h>.  */
251     if (errnum >= 0 && errnum < sys_nerr)
252       {
253 #  if HAVE_CATGETS && (defined __NetBSD__ || defined __hpux)
254 #   if defined __NetBSD__
255         nl_catd catd = catopen ("libc", NL_CAT_LOCALE);
256         const char *errmsg =
257           (catd != (nl_catd)-1
258            ? catgets (catd, 1, errnum, sys_errlist[errnum])
259            : sys_errlist[errnum]);
260 #   endif
261 #   if defined __hpux
262         nl_catd catd = catopen ("perror", NL_CAT_LOCALE);
263         const char *errmsg =
264           (catd != (nl_catd)-1
265            ? catgets (catd, 1, 1 + errnum, sys_errlist[errnum])
266            : sys_errlist[errnum]);
267 #   endif
268 #  else
269         const char *errmsg = sys_errlist[errnum];
270 #  endif
271         if (errmsg == NULL || *errmsg == '\0')
272           ret = EINVAL;
273         else
274           ret = safe_copy (buf, buflen, errmsg);
275 #  if HAVE_CATGETS && (defined __NetBSD__ || defined __hpux)
276         if (catd != (nl_catd)-1)
277           catclose (catd);
278 #  endif
279       }
280     else
281       ret = EINVAL;
282
283 # elif defined __sgi || (defined __sun && !defined _LP64) /* IRIX, Solaris <= 9 32-bit */
284
285     /* For a valid error number, the system's strerror() function returns
286        a pointer to a not copied string, not to a buffer.  */
287     if (errnum >= 0 && errnum < sys_nerr)
288       {
289         char *errmsg = strerror (errnum);
290
291         if (errmsg == NULL || *errmsg == '\0')
292           ret = EINVAL;
293         else
294           ret = safe_copy (buf, buflen, errmsg);
295       }
296     else
297       ret = EINVAL;
298
299 # else
300
301     gl_lock_lock (strerror_lock);
302
303     {
304       char *errmsg = strerror (errnum);
305
306       /* For invalid error numbers, strerror() on
307            - IRIX 6.5 returns NULL,
308            - HP-UX 11 returns an empty string.  */
309       if (errmsg == NULL || *errmsg == '\0')
310         ret = EINVAL;
311       else
312         ret = safe_copy (buf, buflen, errmsg);
313     }
314
315     gl_lock_unlock (strerror_lock);
316
317 # endif
318
319 #endif
320
321     if (ret == EINVAL && !*buf)
322       snprintf (buf, buflen, "Unknown error %d", errnum);
323
324     errno = saved_errno;
325     return ret;
326   }
327 }