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