Coverage Report

Created: 2026-03-12 07:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gettext/gettext-tools/libgettextpo/strerror_r.c
Line
Count
Source
1
/* strerror_r.c --- POSIX compatible system error routine
2
3
   Copyright (C) 2010-2026 Free Software Foundation, Inc.
4
5
   This file is free software: you can redistribute it and/or modify
6
   it under the terms of the GNU Lesser General Public License as
7
   published by the Free Software Foundation; either version 2.1 of the
8
   License, or (at your option) any later version.
9
10
   This file 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 Lesser General Public License for more details.
14
15
   You should have received a copy of the GNU Lesser General Public License
16
   along with this program.  If not, see <https://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
#if !HAVE_SNPRINTF
32
# include <stdarg.h>
33
#endif
34
35
#include "strerror-override.h"
36
37
#if STRERROR_R_CHAR_P && !defined _AIX
38
39
# if HAVE___XPG_STRERROR_R
40
_GL_EXTERN_C int __xpg_strerror_r (int errnum, char *buf, size_t buflen);
41
# endif
42
43
#elif HAVE_DECL_STRERROR_R
44
45
/* The system's strerror_r function's API 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
#else
51
52
/* Use the system's strerror().  Exclude glibc and cygwin because the
53
   system strerror_r has the wrong return type, and cygwin 1.7.9
54
   strerror_r clobbers strerror.  */
55
# undef strerror
56
57
# if defined __NetBSD__ || defined __hpux || (defined _WIN32 && !defined __CYGWIN__) || (defined __sun && !defined _LP64) || defined __CYGWIN__
58
59
/* No locking needed.  */
60
61
/* Get catgets internationalization functions.  */
62
#  if HAVE_CATGETS
63
#   include <nl_types.h>
64
#  endif
65
66
#ifdef __cplusplus
67
extern "C" {
68
#endif
69
70
/* Get sys_nerr, sys_errlist on HP-UX (otherwise only declared in C++ mode).  */
71
#  if defined __hpux
72
extern int sys_nerr;
73
extern char *sys_errlist[];
74
#  endif
75
76
/* Get sys_nerr on Solaris.  */
77
#  if defined __sun && !defined _LP64
78
extern int sys_nerr;
79
#  endif
80
81
#ifdef __cplusplus
82
}
83
#endif
84
85
# else
86
87
#  include "glthread/lock.h"
88
89
/* This lock protects the buffer returned by strerror().  We assume that
90
   no other uses of strerror() exist in the program.  */
91
gl_lock_define_initialized(static, strerror_lock)
92
93
# endif
94
95
#endif
96
97
/* On MSVC, there is no snprintf() function, just a _snprintf().
98
   It is of lower quality, but sufficient for the simple use here.
99
   We only have to make sure to NUL terminate the result (_snprintf
100
   does not NUL terminate, like strncpy).  */
101
#if !HAVE_SNPRINTF
102
static int
103
local_snprintf (char *buf, size_t buflen, const char *format, ...)
104
{
105
  va_list args;
106
  va_start (args, format);
107
  int result = _vsnprintf (buf, buflen, format, args);
108
  va_end (args);
109
  if (buflen > 0 && (result < 0 || result >= buflen))
110
    buf[buflen - 1] = '\0';
111
  return result;
112
}
113
# undef snprintf
114
# define snprintf local_snprintf
115
#endif
116
117
/* Copy as much of MSG into BUF as possible, without corrupting errno.
118
   Return 0 if MSG fit in BUFLEN, otherwise return ERANGE.  */
119
static int
120
safe_copy (char *buf, size_t buflen, const char *msg)
121
0
{
122
0
  size_t len = strlen (msg);
123
0
  size_t moved = len < buflen ? len : buflen - 1;
124
125
  /* Although POSIX lets memmove corrupt errno, we don't
126
     know of any implementation where this is a real problem.  */
127
0
  memmove (buf, msg, moved);
128
0
  buf[moved] = '\0';
129
0
  return len < buflen ? 0 : ERANGE;
130
0
}
131
132
133
int
134
strerror_r (int errnum, char *buf, size_t buflen)
135
#undef strerror_r
136
0
{
137
  /* Filter this out now, so that rest of this replacement knows that
138
     there is room for a non-empty message and trailing NUL.  */
139
0
  if (buflen <= 1)
140
0
    {
141
0
      if (buflen)
142
0
        *buf = '\0';
143
0
      return ERANGE;
144
0
    }
145
0
  *buf = '\0';
146
147
  /* Check for gnulib overrides.  */
148
0
  {
149
0
    char const *msg = strerror_override (errnum);
150
151
0
    if (msg)
152
0
      return safe_copy (buf, buflen, msg);
153
0
  }
154
155
0
  {
156
0
    int ret;
157
0
    int saved_errno = errno;
158
159
    /* Due to the '#undef strerror_r' above, on AIX, we're always using
160
       the POSIX-compatible strerror_r function, regardless whether
161
       _LINUX_SOURCE_COMPAT is defined or not.  */
162
0
#if STRERROR_R_CHAR_P && !defined _AIX
163
164
0
    {
165
0
      ret = 0;
166
167
0
# if HAVE___XPG_STRERROR_R
168
0
      ret = __xpg_strerror_r (errnum, buf, buflen);
169
      /* ret is 0 upon success, or EINVAL or ERANGE upon failure.  */
170
0
# endif
171
172
0
      if (!*buf)
173
0
        {
174
          /* glibc 2.13 ... 2.34 (at least) don't touch buf upon failure.
175
             Therefore we have to fall back to strerror_r which, for valid
176
             errnum, returns a thread-safe untruncated string.  For invalid
177
             errnum, though, it returns a truncated string, which does not
178
             allow us to determine whether to return ERANGE or 0.  Thus we
179
             need to pass a sufficiently large buffer.  */
180
0
          char stackbuf[80];
181
0
          char *errstring = strerror_r (errnum, stackbuf, sizeof stackbuf);
182
0
          ret = errstring ? safe_copy (buf, buflen, errstring) : errno;
183
0
        }
184
0
    }
185
186
#elif HAVE_DECL_STRERROR_R
187
188
    if (buflen > INT_MAX)
189
      buflen = INT_MAX;
190
191
# ifdef __hpux
192
    /* On HP-UX 11.31, strerror_r always fails when buflen < 80; it
193
       also fails to change buf on EINVAL.  */
194
    {
195
      char stackbuf[80];
196
197
      if (buflen < sizeof stackbuf)
198
        {
199
          ret = strerror_r (errnum, stackbuf, sizeof stackbuf);
200
          if (ret == 0)
201
            ret = safe_copy (buf, buflen, stackbuf);
202
        }
203
      else
204
        ret = strerror_r (errnum, buf, buflen);
205
    }
206
# else
207
    ret = strerror_r (errnum, buf, buflen);
208
209
    /* Some old implementations may return (-1, EINVAL) instead of EINVAL.
210
       But on Haiku, valid error numbers are negative.  */
211
#  if !defined __HAIKU__
212
    if (ret < 0)
213
      ret = errno;
214
#  endif
215
# endif
216
217
# if defined _AIX || defined __HAIKU__
218
    /* AIX and Haiku return 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
        strerror_r (errnum, stackbuf, sizeof stackbuf);
224
        size_t len = strlen (stackbuf);
225
        /* STACKBUF_LEN should have been large enough.  */
226
        if (len + 1 == sizeof stackbuf)
227
          abort ();
228
        if (buflen <= len)
229
          ret = ERANGE;
230
      }
231
# else
232
    /* Solaris 10 does not populate buf on ERANGE.  OpenBSD 4.7
233
       truncates early on ERANGE rather than return a partial integer.
234
       We prefer the maximal string.  We set buf[0] earlier, and we
235
       know of no implementation that modifies buf to be an
236
       unterminated string, so this strlen should be portable in
237
       practice (rather than pulling in a safer strnlen).  */
238
    if (ret == ERANGE && strlen (buf) < buflen - 1)
239
      {
240
        char stackbuf[STACKBUF_LEN];
241
242
        /* STACKBUF_LEN should have been large enough.  */
243
        if (strerror_r (errnum, stackbuf, sizeof stackbuf) == ERANGE)
244
          abort ();
245
        safe_copy (buf, buflen, stackbuf);
246
      }
247
# endif
248
249
#else /* strerror_r is not declared.  */
250
251
    /* Try to do what strerror (errnum) does, but without clobbering the
252
       buffer used by strerror().  */
253
254
# if defined __NetBSD__ || defined __hpux || (defined _WIN32 && !defined __CYGWIN__) || defined __CYGWIN__ /* NetBSD, HP-UX, native Windows, Cygwin */
255
256
    /* NetBSD:         sys_nerr, sys_errlist are declared through _NETBSD_SOURCE
257
                       and <errno.h> above.
258
       HP-UX:          sys_nerr, sys_errlist are declared explicitly above.
259
       native Windows: sys_nerr, sys_errlist are declared in <stdlib.h>.
260
       Cygwin:         sys_nerr, sys_errlist are declared in <errno.h>.  */
261
    if (errnum >= 0 && errnum < sys_nerr)
262
      {
263
#  if HAVE_CATGETS && (defined __NetBSD__ || defined __hpux)
264
#   if defined __NetBSD__
265
        nl_catd catd = catopen ("libc", NL_CAT_LOCALE);
266
        const char *errmsg =
267
          (catd != (nl_catd)-1
268
           ? catgets (catd, 1, errnum, sys_errlist[errnum])
269
           : sys_errlist[errnum]);
270
#   endif
271
#   if defined __hpux
272
        nl_catd catd = catopen ("perror", NL_CAT_LOCALE);
273
        const char *errmsg =
274
          (catd != (nl_catd)-1
275
           ? catgets (catd, 1, 1 + errnum, sys_errlist[errnum])
276
           : sys_errlist[errnum]);
277
#   endif
278
#  else
279
        const char *errmsg = sys_errlist[errnum];
280
#  endif
281
        if (errmsg == NULL || *errmsg == '\0')
282
          ret = EINVAL;
283
        else
284
          ret = safe_copy (buf, buflen, errmsg);
285
#  if HAVE_CATGETS && (defined __NetBSD__ || defined __hpux)
286
        if (catd != (nl_catd)-1)
287
          catclose (catd);
288
#  endif
289
      }
290
    else
291
      ret = EINVAL;
292
293
# elif defined __sun && !defined _LP64 /* Solaris <= 9 32-bit */
294
295
    /* For a valid error number, the system's strerror() function returns
296
       a pointer to a not copied string, not to a buffer.  */
297
    if (errnum >= 0 && errnum < sys_nerr)
298
      {
299
        char *errmsg = strerror (errnum);
300
301
        if (errmsg == NULL || *errmsg == '\0')
302
          ret = EINVAL;
303
        else
304
          ret = safe_copy (buf, buflen, errmsg);
305
      }
306
    else
307
      ret = EINVAL;
308
309
# else
310
311
    gl_lock_lock (strerror_lock);
312
313
    {
314
      char *errmsg = strerror (errnum);
315
316
      /* For invalid error numbers, strerror() on HP-UX 11 returns an empty
317
         string.  */
318
      if (*errmsg == '\0')
319
        ret = EINVAL;
320
      else
321
        ret = safe_copy (buf, buflen, errmsg);
322
    }
323
324
    gl_lock_unlock (strerror_lock);
325
326
# endif
327
328
#endif
329
330
#if defined _WIN32 && !defined __CYGWIN__
331
    /* MSVC 14 defines names for many error codes in the range 100..140,
332
       but _sys_errlist contains strings only for the error codes
333
       < _sys_nerr = 43.  */
334
    if (ret == EINVAL)
335
      {
336
        const char *errmsg;
337
338
        switch (errnum)
339
          {
340
          case 100 /* EADDRINUSE */:
341
            errmsg = "Address already in use";
342
            break;
343
          case 101 /* EADDRNOTAVAIL */:
344
            errmsg = "Cannot assign requested address";
345
            break;
346
          case 102 /* EAFNOSUPPORT */:
347
            errmsg = "Address family not supported by protocol";
348
            break;
349
          case 103 /* EALREADY */:
350
            errmsg = "Operation already in progress";
351
            break;
352
          case 105 /* ECANCELED */:
353
            errmsg = "Operation canceled";
354
            break;
355
          case 106 /* ECONNABORTED */:
356
            errmsg = "Software caused connection abort";
357
            break;
358
          case 107 /* ECONNREFUSED */:
359
            errmsg = "Connection refused";
360
            break;
361
          case 108 /* ECONNRESET */:
362
            errmsg = "Connection reset by peer";
363
            break;
364
          case 109 /* EDESTADDRREQ */:
365
            errmsg = "Destination address required";
366
            break;
367
          case 110 /* EHOSTUNREACH */:
368
            errmsg = "No route to host";
369
            break;
370
          case 112 /* EINPROGRESS */:
371
            errmsg = "Operation now in progress";
372
            break;
373
          case 113 /* EISCONN */:
374
            errmsg = "Transport endpoint is already connected";
375
            break;
376
          case 114 /* ELOOP */:
377
            errmsg = "Too many levels of symbolic links";
378
            break;
379
          case 115 /* EMSGSIZE */:
380
            errmsg = "Message too long";
381
            break;
382
          case 116 /* ENETDOWN */:
383
            errmsg = "Network is down";
384
            break;
385
          case 117 /* ENETRESET */:
386
            errmsg = "Network dropped connection on reset";
387
            break;
388
          case 118 /* ENETUNREACH */:
389
            errmsg = "Network is unreachable";
390
            break;
391
          case 119 /* ENOBUFS */:
392
            errmsg = "No buffer space available";
393
            break;
394
          case 123 /* ENOPROTOOPT */:
395
            errmsg = "Protocol not available";
396
            break;
397
          case 126 /* ENOTCONN */:
398
            errmsg = "Transport endpoint is not connected";
399
            break;
400
          case 128 /* ENOTSOCK */:
401
            errmsg = "Socket operation on non-socket";
402
            break;
403
          case 129 /* ENOTSUP */:
404
            errmsg = "Not supported";
405
            break;
406
          case 130 /* EOPNOTSUPP */:
407
            errmsg = "Operation not supported";
408
            break;
409
          case 132 /* EOVERFLOW */:
410
            errmsg = "Value too large for defined data type";
411
            break;
412
          case 133 /* EOWNERDEAD */:
413
            errmsg = "Owner died";
414
            break;
415
          case 134 /* EPROTO */:
416
            errmsg = "Protocol error";
417
            break;
418
          case 135 /* EPROTONOSUPPORT */:
419
            errmsg = "Protocol not supported";
420
            break;
421
          case 136 /* EPROTOTYPE */:
422
            errmsg = "Protocol wrong type for socket";
423
            break;
424
          case 138 /* ETIMEDOUT */:
425
            errmsg = "Connection timed out";
426
            break;
427
          case 140 /* EWOULDBLOCK */:
428
            errmsg = "Operation would block";
429
            break;
430
          default:
431
            errmsg = NULL;
432
            break;
433
          }
434
        if (errmsg != NULL)
435
          ret = safe_copy (buf, buflen, errmsg);
436
      }
437
#endif
438
439
0
    if (ret == EINVAL && !*buf)
440
0
      {
441
        /* gcc 14 produces a
442
           "warning: 'Unknown error ' directive output truncated
443
            writing 14 bytes into a region of size 2"
444
           Thanks for the warning, but here the truncation is intentional.  */
445
#if _GL_GNUC_PREREQ (7, 1)
446
# pragma GCC diagnostic ignored "-Wformat-truncation"
447
#endif
448
#if defined __HAIKU__
449
        /* For consistency with perror().  */
450
        snprintf (buf, buflen, "Unknown Application Error (%d)", errnum);
451
#else
452
0
        snprintf (buf, buflen, "Unknown error %d", errnum);
453
0
#endif
454
0
        buf[buflen - 1] = '\0';
455
0
      }
456
457
    errno = saved_errno;
458
0
    return ret;
459
0
  }
460
0
}