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