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