Add some mainloop instrumentation
[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 #include <sys/types.h>
44
45 #include <time.h>
46
47 #ifdef G_OS_UNIX
48 #include <unistd.h>
49 #include <sys/wait.h>
50 #ifdef HAVE_SYS_SELECT_H
51 #include <sys/select.h>
52 #endif /* HAVE_SYS_SELECT_H */
53 #endif
54
55 #include <string.h>
56
57 #ifdef G_OS_WIN32
58 #  define STRICT                /* Strict typing, please */
59 #  define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
60 #  include <windows.h>
61 #  undef STRICT
62 #else
63 #  include <fcntl.h>
64 #endif
65
66 #include "gbacktrace.h"
67
68 #include "gtypes.h"
69 #include "gmain.h"
70 #include "gprintfint.h"
71 #include "gutils.h"
72
73
74 #ifndef NO_FD_SET
75 #  define SELECT_MASK fd_set
76 #else
77 #  if defined(_IBMR2)
78 #    define SELECT_MASK void
79 #  else
80 #    define SELECT_MASK int
81 #  endif
82 #endif
83
84
85 #ifndef G_OS_WIN32
86 static void stack_trace (char **args);
87 #endif
88
89 /* People want to hit this from their debugger... */
90 GLIB_AVAILABLE_IN_ALL volatile gboolean glib_on_error_halt;
91 volatile gboolean glib_on_error_halt = TRUE;
92
93 /**
94  * g_on_error_query:
95  * @prg_name: the program name, needed by <command>gdb</command>
96  *     for the [S]tack trace option. If @prg_name is %NULL, g_get_prgname()
97  *     is called to get the program name (which will work correctly if
98  *     gdk_init() or gtk_init() has been called)
99  *
100  * Prompts the user with
101  * <computeroutput>[E]xit, [H]alt, show [S]tack trace or [P]roceed</computeroutput>.
102  * This function is intended to be used for debugging use only.
103  * The following example shows how it can be used together with
104  * the g_log() functions.
105  *
106  * |[
107  * &num;include &lt;glib.h&gt;
108  *
109  * static void
110  * log_handler (const gchar   *log_domain,
111  *              GLogLevelFlags log_level,
112  *              const gchar   *message,
113  *              gpointer       user_data)
114  * {
115  *   g_log_default_handler (log_domain, log_level, message, user_data);
116  *
117  *   g_on_error_query (MY_PROGRAM_NAME);
118  * }
119  *
120  * int
121  * main (int argc, char *argv[])
122  * {
123  *   g_log_set_handler (MY_LOG_DOMAIN,
124  *                      G_LOG_LEVEL_WARNING |
125  *                      G_LOG_LEVEL_ERROR |
126  *                      G_LOG_LEVEL_CRITICAL,
127  *                      log_handler,
128  *                      NULL);
129  *   /&ast; ... &ast;/
130  * ]|
131  *
132  * If [E]xit is selected, the application terminates with a call
133  * to <literal>_exit(0)</literal>.
134  *
135  * If [S]tack trace is selected, g_on_error_stack_trace() is called.
136  * This invokes <command>gdb</command>, which attaches to the current
137  * process and shows a stack trace. The prompt is then shown again.
138  *
139  * If [P]roceed is selected, the function returns.
140  *
141  * This function may cause different actions on non-UNIX platforms.
142  */
143 void
144 g_on_error_query (const gchar *prg_name)
145 {
146 #ifndef G_OS_WIN32
147   static const gchar * const query1 = "[E]xit, [H]alt";
148   static const gchar * const query2 = ", show [S]tack trace";
149   static const gchar * const query3 = " or [P]roceed";
150   gchar buf[16];
151
152   if (!prg_name)
153     prg_name = g_get_prgname ();
154
155  retry:
156
157   if (prg_name)
158     _g_fprintf (stdout,
159                 "%s (pid:%u): %s%s%s: ",
160                 prg_name,
161                 (guint) getpid (),
162                 query1,
163                 query2,
164                 query3);
165   else
166     _g_fprintf (stdout,
167                 "(process:%u): %s%s: ",
168                 (guint) getpid (),
169                 query1,
170                 query3);
171   fflush (stdout);
172
173   if (isatty(0) && isatty(1))
174     fgets (buf, 8, stdin);
175   else
176     strcpy (buf, "E\n");
177
178   if ((buf[0] == 'E' || buf[0] == 'e')
179       && buf[1] == '\n')
180     _exit (0);
181   else if ((buf[0] == 'P' || buf[0] == 'p')
182            && buf[1] == '\n')
183     return;
184   else if (prg_name
185            && (buf[0] == 'S' || buf[0] == 's')
186            && buf[1] == '\n')
187     {
188       g_on_error_stack_trace (prg_name);
189       goto retry;
190     }
191   else if ((buf[0] == 'H' || buf[0] == 'h')
192            && buf[1] == '\n')
193     {
194       while (glib_on_error_halt)
195         ;
196       glib_on_error_halt = TRUE;
197       return;
198     }
199   else
200     goto retry;
201 #else
202   if (!prg_name)
203     prg_name = g_get_prgname ();
204
205   MessageBox (NULL, "g_on_error_query called, program terminating",
206               (prg_name && *prg_name) ? prg_name : NULL,
207               MB_OK|MB_ICONERROR);
208   _exit(0);
209 #endif
210 }
211
212 /**
213  * g_on_error_stack_trace:
214  * @prg_name: the program name, needed by <command>gdb</command>
215  *     for the [S]tack trace option.
216  *
217  * Invokes <command>gdb</command>, which attaches to the current
218  * process and shows a stack trace. Called by g_on_error_query()
219  * when the [S]tack trace option is selected. You can get the current
220  * process's "program name" with g_get_prgname(), assuming that you
221  * have called gtk_init() or gdk_init().
222  *
223  * This function may cause different actions on non-UNIX platforms.
224  */
225 void
226 g_on_error_stack_trace (const gchar *prg_name)
227 {
228 #if defined(G_OS_UNIX)
229   pid_t pid;
230   gchar buf[16];
231   gchar *args[4] = { "gdb", NULL, NULL, NULL };
232   int status;
233
234   if (!prg_name)
235     return;
236
237   _g_sprintf (buf, "%u", (guint) getpid ());
238
239   args[1] = (gchar*) prg_name;
240   args[2] = buf;
241
242   pid = fork ();
243   if (pid == 0)
244     {
245       stack_trace (args);
246       _exit (0);
247     }
248   else if (pid == (pid_t) -1)
249     {
250       perror ("unable to fork gdb");
251       return;
252     }
253
254   waitpid (pid, &status, 0);
255 #else
256   if (IsDebuggerPresent ())
257     G_BREAKPOINT ();
258   else
259     abort ();
260 #endif
261 }
262
263 #ifndef G_OS_WIN32
264
265 static gboolean stack_trace_done = FALSE;
266
267 static void
268 stack_trace_sigchld (int signum)
269 {
270   stack_trace_done = TRUE;
271 }
272
273 static void
274 stack_trace (char **args)
275 {
276   pid_t pid;
277   int in_fd[2];
278   int out_fd[2];
279   SELECT_MASK fdset;
280   SELECT_MASK readset;
281   struct timeval tv;
282   int sel, idx, state;
283   char buffer[256];
284   char c;
285
286   stack_trace_done = FALSE;
287   signal (SIGCHLD, stack_trace_sigchld);
288
289   if ((pipe (in_fd) == -1) || (pipe (out_fd) == -1))
290     {
291       perror ("unable to open pipe");
292       _exit (0);
293     }
294
295   pid = fork ();
296   if (pid == 0)
297     {
298       /* Save stderr for printing failure below */
299       int old_err = dup (2);
300       fcntl (old_err, F_SETFD, fcntl (old_err, F_GETFD) | FD_CLOEXEC);
301
302       close (0); dup (in_fd[0]);   /* set the stdin to the in pipe */
303       close (1); dup (out_fd[1]);  /* set the stdout to the out pipe */
304       close (2); dup (out_fd[1]);  /* set the stderr to the out pipe */
305
306       execvp (args[0], args);      /* exec gdb */
307
308       /* Print failure to original stderr */
309       close (2); dup (old_err);
310       perror ("exec gdb failed");
311       _exit (0);
312     }
313   else if (pid == (pid_t) -1)
314     {
315       perror ("unable to fork");
316       _exit (0);
317     }
318
319   FD_ZERO (&fdset);
320   FD_SET (out_fd[0], &fdset);
321
322   write (in_fd[1], "backtrace\n", 10);
323   write (in_fd[1], "p x = 0\n", 8);
324   write (in_fd[1], "quit\n", 5);
325
326   idx = 0;
327   state = 0;
328
329   while (1)
330     {
331       readset = fdset;
332       tv.tv_sec = 1;
333       tv.tv_usec = 0;
334
335       sel = select (FD_SETSIZE, &readset, NULL, NULL, &tv);
336       if (sel == -1)
337         break;
338
339       if ((sel > 0) && (FD_ISSET (out_fd[0], &readset)))
340         {
341           if (read (out_fd[0], &c, 1))
342             {
343               switch (state)
344                 {
345                 case 0:
346                   if (c == '#')
347                     {
348                       state = 1;
349                       idx = 0;
350                       buffer[idx++] = c;
351                     }
352                   break;
353                 case 1:
354                   buffer[idx++] = c;
355                   if ((c == '\n') || (c == '\r'))
356                     {
357                       buffer[idx] = 0;
358                       _g_fprintf (stdout, "%s", buffer);
359                       state = 0;
360                       idx = 0;
361                     }
362                   break;
363                 default:
364                   break;
365                 }
366             }
367         }
368       else if (stack_trace_done)
369         break;
370     }
371
372   close (in_fd[0]);
373   close (in_fd[1]);
374   close (out_fd[0]);
375   close (out_fd[1]);
376   _exit (0);
377 }
378
379 #endif /* !G_OS_WIN32 */