error: More reliable output on mingw.
[gnulib.git] / lib / error.c
1 /* Error handler for noninteractive utilities
2    Copyright (C) 1990-1998, 2000-2007, 2009-2010 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 # endif
96
97 # if !HAVE_DECL_STRERROR_R && STRERROR_R_CHAR_P
98 #  ifndef HAVE_DECL_STRERROR_R
99 "this configure-time declaration test was not run"
100 #  endif
101 char *strerror_r ();
102 # endif
103
104 /* The calling program should define program_name and set it to the
105    name of the executing program.  */
106 extern char *program_name;
107
108 # if HAVE_STRERROR_R || defined strerror_r
109 #  define __strerror_r strerror_r
110 # endif /* HAVE_STRERROR_R || defined strerror_r */
111 #endif  /* not _LIBC */
112
113 #if !_LIBC
114 /* Return non-zero if FD is open.  */
115 static inline int
116 is_open (int fd)
117 {
118 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
119   /* On Win32: The initial state of unassigned standard file descriptors is
120      that they are open but point to an INVALID_HANDLE_VALUE.  There is no
121      fcntl, and the gnulib replacement fcntl does not support F_GETFL.  */
122   return (HANDLE) _get_osfhandle (fd) != INVALID_HANDLE_VALUE;
123 # else
124 #  ifndef F_GETFL
125 #   error Please port fcntl to your platform
126 #  endif
127   return 0 <= fcntl (fd, F_GETFL);
128 # endif
129 }
130 #endif
131
132 static inline void
133 flush_stdout (void)
134 {
135 #if !_LIBC
136   int stdout_fd;
137
138 # if GNULIB_FREOPEN_SAFER
139   /* Use of gnulib's freopen-safer module normally ensures that
140        fileno (stdout) == 1
141      whenever stdout is open.  */
142   stdout_fd = STDOUT_FILENO;
143 # else
144   /* POSIX states that fileno (stdout) after fclose is unspecified.  But in
145      practice it is not a problem, because stdout is statically allocated and
146      the fd of a FILE stream is stored as a field in its allocated memory.  */
147   stdout_fd = fileno (stdout);
148 # endif
149   /* POSIX states that fflush (stdout) after fclose is unspecified; it
150      is safe in glibc, but not on all other platforms.  fflush (NULL)
151      is always defined, but too draconian.  */
152   if (0 <= stdout_fd && is_open (stdout_fd))
153 #endif
154     fflush (stdout);
155 }
156
157 static void
158 print_errno_message (int errnum)
159 {
160   char const *s;
161
162 #if defined HAVE_STRERROR_R || _LIBC
163   char errbuf[1024];
164 # if STRERROR_R_CHAR_P || _LIBC
165   s = __strerror_r (errnum, errbuf, sizeof errbuf);
166 # else
167   if (__strerror_r (errnum, errbuf, sizeof errbuf) == 0)
168     s = errbuf;
169   else
170     s = 0;
171 # endif
172 #else
173   s = strerror (errnum);
174 #endif
175
176 #if !_LIBC
177   if (! s)
178     s = _("Unknown system error");
179 #endif
180
181 #if _LIBC
182   __fxprintf (NULL, ": %s", s);
183 #else
184   fprintf (stderr, ": %s", s);
185 #endif
186 }
187
188 static void
189 error_tail (int status, int errnum, const char *message, va_list args)
190 {
191 #if _LIBC
192   if (_IO_fwide (stderr, 0) > 0)
193     {
194 # define ALLOCA_LIMIT 2000
195       size_t len = strlen (message) + 1;
196       wchar_t *wmessage = NULL;
197       mbstate_t st;
198       size_t res;
199       const char *tmp;
200       bool use_malloc = false;
201
202       while (1)
203         {
204           if (__libc_use_alloca (len * sizeof (wchar_t)))
205             wmessage = (wchar_t *) alloca (len * sizeof (wchar_t));
206           else
207             {
208               if (!use_malloc)
209                 wmessage = NULL;
210
211               wchar_t *p = (wchar_t *) realloc (wmessage,
212                                                 len * sizeof (wchar_t));
213               if (p == NULL)
214                 {
215                   free (wmessage);
216                   fputws_unlocked (L"out of memory\n", stderr);
217                   return;
218                 }
219               wmessage = p;
220               use_malloc = true;
221             }
222
223           memset (&st, '\0', sizeof (st));
224           tmp = message;
225
226           res = mbsrtowcs (wmessage, &tmp, len, &st);
227           if (res != len)
228             break;
229
230           if (__builtin_expect (len >= SIZE_MAX / 2, 0))
231             {
232               /* This really should not happen if everything is fine.  */
233               res = (size_t) -1;
234               break;
235             }
236
237           len *= 2;
238         }
239
240       if (res == (size_t) -1)
241         {
242           /* The string cannot be converted.  */
243           if (use_malloc)
244             {
245               free (wmessage);
246               use_malloc = false;
247             }
248           wmessage = (wchar_t *) L"???";
249         }
250
251       __vfwprintf (stderr, wmessage, args);
252
253       if (use_malloc)
254         free (wmessage);
255     }
256   else
257 #endif
258     vfprintf (stderr, message, args);
259   va_end (args);
260
261   ++error_message_count;
262   if (errnum)
263     print_errno_message (errnum);
264 #if _LIBC
265   __fxprintf (NULL, "\n");
266 #else
267   putc ('\n', stderr);
268 #endif
269   fflush (stderr);
270   if (status)
271     exit (status);
272 }
273
274
275 /* Print the program name and error message MESSAGE, which is a printf-style
276    format string with optional args.
277    If ERRNUM is nonzero, print its corresponding system error message.
278    Exit with status STATUS if it is nonzero.  */
279 void
280 error (int status, int errnum, const char *message, ...)
281 {
282   va_list args;
283
284 #if defined _LIBC && defined __libc_ptf_call
285   /* We do not want this call to be cut short by a thread
286      cancellation.  Therefore disable cancellation for now.  */
287   int state = PTHREAD_CANCEL_ENABLE;
288   __libc_ptf_call (pthread_setcancelstate, (PTHREAD_CANCEL_DISABLE, &state),
289                    0);
290 #endif
291
292   flush_stdout ();
293 #ifdef _LIBC
294   _IO_flockfile (stderr);
295 #endif
296   if (error_print_progname)
297     (*error_print_progname) ();
298   else
299     {
300 #if _LIBC
301       __fxprintf (NULL, "%s: ", program_name);
302 #else
303       fprintf (stderr, "%s: ", program_name);
304 #endif
305     }
306
307   va_start (args, message);
308   error_tail (status, errnum, message, args);
309
310 #ifdef _LIBC
311   _IO_funlockfile (stderr);
312 # ifdef __libc_ptf_call
313   __libc_ptf_call (pthread_setcancelstate, (state, NULL), 0);
314 # endif
315 #endif
316 }
317 \f
318 /* Sometimes we want to have at most one error per line.  This
319    variable controls whether this mode is selected or not.  */
320 int error_one_per_line;
321
322 void
323 error_at_line (int status, int errnum, const char *file_name,
324                unsigned int line_number, const char *message, ...)
325 {
326   va_list args;
327
328   if (error_one_per_line)
329     {
330       static const char *old_file_name;
331       static unsigned int old_line_number;
332
333       if (old_line_number == line_number
334           && (file_name == old_file_name
335               || strcmp (old_file_name, file_name) == 0))
336         /* Simply return and print nothing.  */
337         return;
338
339       old_file_name = file_name;
340       old_line_number = line_number;
341     }
342
343 #if defined _LIBC && defined __libc_ptf_call
344   /* We do not want this call to be cut short by a thread
345      cancellation.  Therefore disable cancellation for now.  */
346   int state = PTHREAD_CANCEL_ENABLE;
347   __libc_ptf_call (pthread_setcancelstate, (PTHREAD_CANCEL_DISABLE, &state),
348                    0);
349 #endif
350
351   flush_stdout ();
352 #ifdef _LIBC
353   _IO_flockfile (stderr);
354 #endif
355   if (error_print_progname)
356     (*error_print_progname) ();
357   else
358     {
359 #if _LIBC
360       __fxprintf (NULL, "%s:", program_name);
361 #else
362       fprintf (stderr, "%s:", program_name);
363 #endif
364     }
365
366 #if _LIBC
367   __fxprintf (NULL, file_name != NULL ? "%s:%d: " : " ",
368               file_name, line_number);
369 #else
370   fprintf (stderr, file_name != NULL ? "%s:%d: " : " ",
371            file_name, line_number);
372 #endif
373
374   va_start (args, message);
375   error_tail (status, errnum, message, args);
376
377 #ifdef _LIBC
378   _IO_funlockfile (stderr);
379 # ifdef __libc_ptf_call
380   __libc_ptf_call (pthread_setcancelstate, (state, NULL), 0);
381 # endif
382 #endif
383 }
384
385 #ifdef _LIBC
386 /* Make the weak alias.  */
387 # undef error
388 # undef error_at_line
389 weak_alias (__error, error)
390 weak_alias (__error_at_line, error_at_line)
391 #endif