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