gbacktrace: Print out gdb exec errors correctly
[platform/upstream/glib.git] / glib / gbacktrace.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/.
25  */
26
27 /*
28  * MT safe ; except for g_on_error_stack_trace, but who wants thread safety
29  * then
30  */
31
32 #include "config.h"
33 #include "glibconfig.h"
34
35 #include <signal.h>
36 #include <stdarg.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39
40 #ifdef HAVE_SYS_TIME_H
41 #include <sys/time.h>
42 #endif
43 #ifdef HAVE_SYS_TIMES_H
44 #include <sys/times.h>
45 #endif
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_WAIT_H
48 #include <sys/wait.h>
49 #endif
50
51 #include <time.h>
52 #ifdef HAVE_UNISTD_H
53 #include <unistd.h>
54 #endif
55
56 #ifdef HAVE_SYS_SELECT_H
57 #include <sys/select.h>
58 #endif /* HAVE_SYS_SELECT_H */
59
60 #include <string.h> /* for bzero on BSD systems */
61
62 #ifdef G_OS_WIN32
63 #  define STRICT                /* Strict typing, please */
64 #  define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
65 #  include <windows.h>
66 #  undef STRICT
67 #else
68 #  include <fcntl.h>
69 #endif
70
71 #include "gbacktrace.h"
72
73 #include "gtypes.h"
74 #include "gmain.h"
75 #include "gprintfint.h"
76 #include "gutils.h"
77
78
79 #ifndef NO_FD_SET
80 #  define SELECT_MASK fd_set
81 #else
82 #  if defined(_IBMR2)
83 #    define SELECT_MASK void
84 #  else
85 #    define SELECT_MASK int
86 #  endif
87 #endif
88
89
90 #ifndef G_OS_WIN32
91 static void stack_trace (char **args);
92 #endif
93
94 /* People want to hit this from their debugger... */
95 GLIB_AVAILABLE_IN_ALL volatile gboolean glib_on_error_halt;
96 volatile gboolean glib_on_error_halt = TRUE;
97
98 /**
99  * g_on_error_query:
100  * @prg_name: the program name, needed by <command>gdb</command>
101  *     for the [S]tack trace option. If @prg_name is %NULL, g_get_prgname()
102  *     is called to get the program name (which will work correctly if
103  *     gdk_init() or gtk_init() has been called)
104  *
105  * Prompts the user with
106  * <computeroutput>[E]xit, [H]alt, show [S]tack trace or [P]roceed</computeroutput>.
107  * This function is intended to be used for debugging use only.
108  * The following example shows how it can be used together with
109  * the g_log() functions.
110  *
111  * |[
112  * &num;include &lt;glib.h&gt;
113  *
114  * static void
115  * log_handler (const gchar   *log_domain,
116  *              GLogLevelFlags log_level,
117  *              const gchar   *message,
118  *              gpointer       user_data)
119  * {
120  *   g_log_default_handler (log_domain, log_level, message, user_data);
121  *
122  *   g_on_error_query (MY_PROGRAM_NAME);
123  * }
124  *
125  * int
126  * main (int argc, char *argv[])
127  * {
128  *   g_log_set_handler (MY_LOG_DOMAIN,
129  *                      G_LOG_LEVEL_WARNING |
130  *                      G_LOG_LEVEL_ERROR |
131  *                      G_LOG_LEVEL_CRITICAL,
132  *                      log_handler,
133  *                      NULL);
134  *   /&ast; ... &ast;/
135  * ]|
136  *
137  * If [E]xit is selected, the application terminates with a call
138  * to <literal>_exit(0)</literal>.
139  *
140  * If [S]tack trace is selected, g_on_error_stack_trace() is called.
141  * This invokes <command>gdb</command>, which attaches to the current
142  * process and shows a stack trace. The prompt is then shown again.
143  *
144  * If [P]roceed is selected, the function returns.
145  *
146  * This function may cause different actions on non-UNIX platforms.
147  */
148 void
149 g_on_error_query (const gchar *prg_name)
150 {
151 #ifndef G_OS_WIN32
152   static const gchar * const query1 = "[E]xit, [H]alt";
153   static const gchar * const query2 = ", show [S]tack trace";
154   static const gchar * const query3 = " or [P]roceed";
155   gchar buf[16];
156
157   if (!prg_name)
158     prg_name = g_get_prgname ();
159
160  retry:
161
162   if (prg_name)
163     _g_fprintf (stdout,
164                 "%s (pid:%u): %s%s%s: ",
165                 prg_name,
166                 (guint) getpid (),
167                 query1,
168                 query2,
169                 query3);
170   else
171     _g_fprintf (stdout,
172                 "(process:%u): %s%s: ",
173                 (guint) getpid (),
174                 query1,
175                 query3);
176   fflush (stdout);
177
178   if (isatty(0) && isatty(1))
179     fgets (buf, 8, stdin);
180   else
181     strcpy (buf, "E\n");
182
183   if ((buf[0] == 'E' || buf[0] == 'e')
184       && buf[1] == '\n')
185     _exit (0);
186   else if ((buf[0] == 'P' || buf[0] == 'p')
187            && buf[1] == '\n')
188     return;
189   else if (prg_name
190            && (buf[0] == 'S' || buf[0] == 's')
191            && buf[1] == '\n')
192     {
193       g_on_error_stack_trace (prg_name);
194       goto retry;
195     }
196   else if ((buf[0] == 'H' || buf[0] == 'h')
197            && buf[1] == '\n')
198     {
199       while (glib_on_error_halt)
200         ;
201       glib_on_error_halt = TRUE;
202       return;
203     }
204   else
205     goto retry;
206 #else
207   if (!prg_name)
208     prg_name = g_get_prgname ();
209
210   MessageBox (NULL, "g_on_error_query called, program terminating",
211               (prg_name && *prg_name) ? prg_name : NULL,
212               MB_OK|MB_ICONERROR);
213   _exit(0);
214 #endif
215 }
216
217 /**
218  * g_on_error_stack_trace:
219  * @prg_name: the program name, needed by <command>gdb</command>
220  *     for the [S]tack trace option.
221  *
222  * Invokes <command>gdb</command>, which attaches to the current
223  * process and shows a stack trace. Called by g_on_error_query()
224  * when the [S]tack trace option is selected. You can get the current
225  * process's "program name" with g_get_prgname(), assuming that you
226  * have called gtk_init() or gdk_init().
227  *
228  * This function may cause different actions on non-UNIX platforms.
229  */
230 void
231 g_on_error_stack_trace (const gchar *prg_name)
232 {
233 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
234   pid_t pid;
235   gchar buf[16];
236   gchar *args[4] = { "gdb", NULL, NULL, NULL };
237   int status;
238
239   if (!prg_name)
240     return;
241
242   _g_sprintf (buf, "%u", (guint) getpid ());
243
244   args[1] = (gchar*) prg_name;
245   args[2] = buf;
246
247   pid = fork ();
248   if (pid == 0)
249     {
250       stack_trace (args);
251       _exit (0);
252     }
253   else if (pid == (pid_t) -1)
254     {
255       perror ("unable to fork gdb");
256       return;
257     }
258
259   waitpid (pid, &status, 0);
260 #else
261   if (IsDebuggerPresent ())
262     G_BREAKPOINT ();
263   else
264     abort ();
265 #endif
266 }
267
268 #ifndef G_OS_WIN32
269
270 static gboolean stack_trace_done = FALSE;
271
272 static void
273 stack_trace_sigchld (int signum)
274 {
275   stack_trace_done = TRUE;
276 }
277
278 static void
279 stack_trace (char **args)
280 {
281   pid_t pid;
282   int in_fd[2];
283   int out_fd[2];
284   SELECT_MASK fdset;
285   SELECT_MASK readset;
286   struct timeval tv;
287   int sel, idx, state;
288   char buffer[256];
289   char c;
290
291   stack_trace_done = FALSE;
292   signal (SIGCHLD, stack_trace_sigchld);
293
294   if ((pipe (in_fd) == -1) || (pipe (out_fd) == -1))
295     {
296       perror ("unable to open pipe");
297       _exit (0);
298     }
299
300   pid = fork ();
301   if (pid == 0)
302     {
303       /* Save stderr for printing failure below */
304       int old_err = dup (2);
305       fcntl (old_err, F_SETFD, fcntl (old_err, F_GETFD) | FD_CLOEXEC);
306
307       close (0); dup (in_fd[0]);   /* set the stdin to the in pipe */
308       close (1); dup (out_fd[1]);  /* set the stdout to the out pipe */
309       close (2); dup (out_fd[1]);  /* set the stderr to the out pipe */
310
311       execvp (args[0], args);      /* exec gdb */
312
313       /* Print failure to original stderr */
314       close (2); dup (old_err);
315       perror ("exec gdb failed");
316       _exit (0);
317     }
318   else if (pid == (pid_t) -1)
319     {
320       perror ("unable to fork");
321       _exit (0);
322     }
323
324   FD_ZERO (&fdset);
325   FD_SET (out_fd[0], &fdset);
326
327   write (in_fd[1], "backtrace\n", 10);
328   write (in_fd[1], "p x = 0\n", 8);
329   write (in_fd[1], "quit\n", 5);
330
331   idx = 0;
332   state = 0;
333
334   while (1)
335     {
336       readset = fdset;
337       tv.tv_sec = 1;
338       tv.tv_usec = 0;
339
340       sel = select (FD_SETSIZE, &readset, NULL, NULL, &tv);
341       if (sel == -1)
342         break;
343
344       if ((sel > 0) && (FD_ISSET (out_fd[0], &readset)))
345         {
346           if (read (out_fd[0], &c, 1))
347             {
348               switch (state)
349                 {
350                 case 0:
351                   if (c == '#')
352                     {
353                       state = 1;
354                       idx = 0;
355                       buffer[idx++] = c;
356                     }
357                   break;
358                 case 1:
359                   buffer[idx++] = c;
360                   if ((c == '\n') || (c == '\r'))
361                     {
362                       buffer[idx] = 0;
363                       _g_fprintf (stdout, "%s", buffer);
364                       state = 0;
365                       idx = 0;
366                     }
367                   break;
368                 default:
369                   break;
370                 }
371             }
372         }
373       else if (stack_trace_done)
374         break;
375     }
376
377   close (in_fd[0]);
378   close (in_fd[1]);
379   close (out_fd[0]);
380   close (out_fd[1]);
381   _exit (0);
382 }
383
384 #endif /* !G_OS_WIN32 */