Merge branch 'stable'
[gnulib.git] / lib / error.c
1 /* Error handler for noninteractive utilities
2    Copyright (C) 1990-1998, 2000-2007, 2009-2011 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
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 David MacKenzie <djm@gnu.ai.mit.edu>.  */
19
20 #if !_LIBC
21 # include <config.h>
22 #endif
23
24 #include "error.h"
25
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #if !_LIBC && ENABLE_NLS
32 # include "gettext.h"
33 # define _(msgid) gettext (msgid)
34 #endif
35
36 #ifdef _LIBC
37 # include <libintl.h>
38 # include <stdbool.h>
39 # include <stdint.h>
40 # include <wchar.h>
41 # define mbsrtowcs __mbsrtowcs
42 #endif
43
44 #if USE_UNLOCKED_IO
45 # include "unlocked-io.h"
46 #endif
47
48 #ifndef _
49 # define _(String) String
50 #endif
51
52 /* If NULL, error will flush stdout, then print on stderr the program
53    name, a colon and a space.  Otherwise, error will call this
54    function without parameters instead.  */
55 void (*error_print_progname) (void);
56
57 /* This variable is incremented each time `error' is called.  */
58 unsigned int error_message_count;
59
60 #ifdef _LIBC
61 /* In the GNU C library, there is a predefined variable for this.  */
62
63 # define program_name program_invocation_name
64 # include <errno.h>
65 # include <limits.h>
66 # include <libio/libioP.h>
67
68 /* In GNU libc we want do not want to use the common name `error' directly.
69    Instead make it a weak alias.  */
70 extern void __error (int status, int errnum, const char *message, ...)
71      __attribute__ ((__format__ (__printf__, 3, 4)));
72 extern void __error_at_line (int status, int errnum, const char *file_name,
73                              unsigned int line_number, const char *message,
74                              ...)
75      __attribute__ ((__format__ (__printf__, 5, 6)));;
76 # define error __error
77 # define error_at_line __error_at_line
78
79 # include <libio/iolibio.h>
80 # define fflush(s) INTUSE(_IO_fflush) (s)
81 # undef putc
82 # define putc(c, fp) INTUSE(_IO_putc) (c, fp)
83
84 # include <bits/libc-lock.h>
85
86 #else /* not _LIBC */
87
88 # include <fcntl.h>
89 # include <unistd.h>
90
91 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
92 /* Get declarations of the Win32 API functions.  */
93 #  define WIN32_LEAN_AND_MEAN
94 #  include <windows.h>
95 /* Get _get_osfhandle.  */
96 #  include "msvc-nothrow.h"
97 # endif
98
99 /* The gnulib override of fcntl is not needed in this file.  */
100 # undef fcntl
101
102 # if !HAVE_DECL_STRERROR_R
103 #  ifndef HAVE_DECL_STRERROR_R
104 "this configure-time declaration test was not run"
105 #  endif
106 #  if STRERROR_R_CHAR_P
107 char *strerror_r ();
108 #  else
109 int strerror_r ();
110 #  endif
111 # endif
112
113 /* The calling program should define program_name and set it to the
114    name of the executing program.  */
115 extern char *program_name;
116
117 # if HAVE_STRERROR_R || defined strerror_r
118 #  define __strerror_r strerror_r
119 # endif /* HAVE_STRERROR_R || defined strerror_r */
120 #endif  /* not _LIBC */
121
122 #if !_LIBC
123 /* Return non-zero if FD is open.  */
124 static inline int
125 is_open (int fd)
126 {
127 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
128   /* On Win32: The initial state of unassigned standard file descriptors is
129      that they are open but point to an INVALID_HANDLE_VALUE.  There is no
130      fcntl, and the gnulib replacement fcntl does not support F_GETFL.  */
131   return (HANDLE) _get_osfhandle (fd) != INVALID_HANDLE_VALUE;
132 # else
133 #  ifndef F_GETFL
134 #   error Please port fcntl to your platform
135 #  endif
136   return 0 <= fcntl (fd, F_GETFL);
137 # endif
138 }
139 #endif
140
141 static inline void
142 flush_stdout (void)
143 {
144 #if !_LIBC
145   int stdout_fd;
146
147 # if GNULIB_FREOPEN_SAFER
148   /* Use of gnulib's freopen-safer module normally ensures that
149        fileno (stdout) == 1
150      whenever stdout is open.  */
151   stdout_fd = STDOUT_FILENO;
152 # else
153   /* POSIX states that fileno (stdout) after fclose is unspecified.  But in
154      practice it is not a problem, because stdout is statically allocated and
155      the fd of a FILE stream is stored as a field in its allocated memory.  */
156   stdout_fd = fileno (stdout);
157 # endif
158   /* POSIX states that fflush (stdout) after fclose is unspecified; it
159      is safe in glibc, but not on all other platforms.  fflush (NULL)
160      is always defined, but too draconian.  */
161   if (0 <= stdout_fd && is_open (stdout_fd))
162 #endif
163     fflush (stdout);
164 }
165
166 static void
167 print_errno_message (int errnum)
168 {
169   char const *s;
170
171 #if defined HAVE_STRERROR_R || _LIBC
172   char errbuf[1024];
173 # if STRERROR_R_CHAR_P || _LIBC
174   s = __strerror_r (errnum, errbuf, sizeof errbuf);
175 # else
176   if (__strerror_r (errnum, errbuf, sizeof errbuf) == 0)
177     s = errbuf;
178   else
179     s = 0;
180 # endif
181 #else
182   s = strerror (errnum);
183 #endif
184
185 #if !_LIBC
186   if (! s)
187     s = _("Unknown system error");
188 #endif
189
190 #if _LIBC
191   __fxprintf (NULL, ": %s", s);
192 #else
193   fprintf (stderr, ": %s", s);
194 #endif
195 }
196
197 static void
198 error_tail (int status, int errnum, const char *message, va_list args)
199 {
200 #if _LIBC
201   if (_IO_fwide (stderr, 0) > 0)
202     {
203 # define ALLOCA_LIMIT 2000
204       size_t len = strlen (message) + 1;
205       wchar_t *wmessage = NULL;
206       mbstate_t st;
207       size_t res;
208       const char *tmp;
209       bool use_malloc = false;
210
211       while (1)
212         {
213           if (__libc_use_alloca (len * sizeof (wchar_t)))
214             wmessage = (wchar_t *) alloca (len * sizeof (wchar_t));
215           else
216             {
217               if (!use_malloc)
218                 wmessage = NULL;
219
220               wchar_t *p = (wchar_t *) realloc (wmessage,
221                                                 len * sizeof (wchar_t));
222               if (p == NULL)
223                 {
224                   free (wmessage);
225                   fputws_unlocked (L"out of memory\n", stderr);
226                   return;
227                 }
228               wmessage = p;
229               use_malloc = true;
230             }
231
232           memset (&st, '\0', sizeof (st));
233           tmp = message;
234
235           res = mbsrtowcs (wmessage, &tmp, len, &st);
236           if (res != len)
237             break;
238
239           if (__builtin_expect (len >= SIZE_MAX / 2, 0))
240             {
241               /* This really should not happen if everything is fine.  */
242               res = (size_t) -1;
243               break;
244             }
245
246           len *= 2;
247         }
248
249       if (res == (size_t) -1)
250         {
251           /* The string cannot be converted.  */
252           if (use_malloc)
253             {
254               free (wmessage);
255               use_malloc = false;
256             }
257           wmessage = (wchar_t *) L"???";
258         }
259
260       __vfwprintf (stderr, wmessage, args);
261
262       if (use_malloc)
263         free (wmessage);
264     }
265   else
266 #endif
267     vfprintf (stderr, message, args);
268   va_end (args);
269
270   ++error_message_count;
271   if (errnum)
272     print_errno_message (errnum);
273 #if _LIBC
274   __fxprintf (NULL, "\n");
275 #else
276   putc ('\n', stderr);
277 #endif
278   fflush (stderr);
279   if (status)
280     exit (status);
281 }
282
283
284 /* Print the program name and error message MESSAGE, which is a printf-style
285    format string with optional args.
286    If ERRNUM is nonzero, print its corresponding system error message.
287    Exit with status STATUS if it is nonzero.  */
288 void
289 error (int status, int errnum, const char *message, ...)
290 {
291   va_list args;
292
293 #if defined _LIBC && defined __libc_ptf_call
294   /* We do not want this call to be cut short by a thread
295      cancellation.  Therefore disable cancellation for now.  */
296   int state = PTHREAD_CANCEL_ENABLE;
297   __libc_ptf_call (pthread_setcancelstate, (PTHREAD_CANCEL_DISABLE, &state),
298                    0);
299 #endif
300
301   flush_stdout ();
302 #ifdef _LIBC
303   _IO_flockfile (stderr);
304 #endif
305   if (error_print_progname)
306     (*error_print_progname) ();
307   else
308     {
309 #if _LIBC
310       __fxprintf (NULL, "%s: ", program_name);
311 #else
312       fprintf (stderr, "%s: ", program_name);
313 #endif
314     }
315
316   va_start (args, message);
317   error_tail (status, errnum, message, args);
318
319 #ifdef _LIBC
320   _IO_funlockfile (stderr);
321 # ifdef __libc_ptf_call
322   __libc_ptf_call (pthread_setcancelstate, (state, NULL), 0);
323 # endif
324 #endif
325 }
326 \f
327 /* Sometimes we want to have at most one error per line.  This
328    variable controls whether this mode is selected or not.  */
329 int error_one_per_line;
330
331 void
332 error_at_line (int status, int errnum, const char *file_name,
333                unsigned int line_number, const char *message, ...)
334 {
335   va_list args;
336
337   if (error_one_per_line)
338     {
339       static const char *old_file_name;
340       static unsigned int old_line_number;
341
342       if (old_line_number == line_number
343           && (file_name == old_file_name
344               || strcmp (old_file_name, file_name) == 0))
345         /* Simply return and print nothing.  */
346         return;
347
348       old_file_name = file_name;
349       old_line_number = line_number;
350     }
351
352 #if defined _LIBC && defined __libc_ptf_call
353   /* We do not want this call to be cut short by a thread
354      cancellation.  Therefore disable cancellation for now.  */
355   int state = PTHREAD_CANCEL_ENABLE;
356   __libc_ptf_call (pthread_setcancelstate, (PTHREAD_CANCEL_DISABLE, &state),
357                    0);
358 #endif
359
360   flush_stdout ();
361 #ifdef _LIBC
362   _IO_flockfile (stderr);
363 #endif
364   if (error_print_progname)
365     (*error_print_progname) ();
366   else
367     {
368 #if _LIBC
369       __fxprintf (NULL, "%s:", program_name);
370 #else
371       fprintf (stderr, "%s:", program_name);
372 #endif
373     }
374
375 #if _LIBC
376   __fxprintf (NULL, file_name != NULL ? "%s:%d: " : " ",
377               file_name, line_number);
378 #else
379   fprintf (stderr, file_name != NULL ? "%s:%d: " : " ",
380            file_name, line_number);
381 #endif
382
383   va_start (args, message);
384   error_tail (status, errnum, message, args);
385
386 #ifdef _LIBC
387   _IO_funlockfile (stderr);
388 # ifdef __libc_ptf_call
389   __libc_ptf_call (pthread_setcancelstate, (state, NULL), 0);
390 # endif
391 #endif
392 }
393
394 #ifdef _LIBC
395 /* Make the weak alias.  */
396 # undef error
397 # undef error_at_line
398 weak_alias (__error, error)
399 weak_alias (__error_at_line, error_at_line)
400 #endif