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