gbacktrace.c 9.22 KB
Newer Older
Owen Taylor's avatar
Owen Taylor committed
1 2 3 4
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * This library is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU Lesser General Public
Owen Taylor's avatar
Owen Taylor committed
6
 * License as published by the Free Software Foundation; either
7
 * version 2.1 of the License, or (at your option) any later version.
Owen Taylor's avatar
Owen Taylor committed
8 9 10 11
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12
 * Lesser General Public License for more details.
Owen Taylor's avatar
Owen Taylor committed
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/>.
Owen Taylor's avatar
Owen Taylor committed
16
 */
17

18
/*
19
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
20 21
 * file for a list of people on the GLib Team.  See the ChangeLog
 * 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 28 29
 * then
 */

30
#include "config.h"
31
#include "glibconfig.h"
32

Owen Taylor's avatar
Owen Taylor committed
33 34 35 36
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
37

38
#ifdef HAVE_SYS_TIME_H
Owen Taylor's avatar
Owen Taylor committed
39
#include <sys/time.h>
40
#endif
Owen Taylor's avatar
Owen Taylor committed
41 42 43 44
#include <sys/types.h>

#include <time.h>

45 46 47
#ifdef G_OS_UNIX
#include <unistd.h>
#include <sys/wait.h>
Owen Taylor's avatar
Owen Taylor committed
48 49 50
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif /* HAVE_SYS_SELECT_H */
51
#endif
Owen Taylor's avatar
Owen Taylor committed
52

53
#include <string.h>
Owen Taylor's avatar
Owen Taylor committed
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 61
#else
#  include <fcntl.h>
62
#endif
Owen Taylor's avatar
Owen Taylor committed
63

64 65
#include "gbacktrace.h"

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
Owen Taylor's avatar
Owen Taylor committed
74

75 76
/* People want to hit this from their debugger... */
GLIB_AVAILABLE_IN_ALL volatile gboolean glib_on_error_halt;
77
volatile gboolean glib_on_error_halt = TRUE;
Owen Taylor's avatar
Owen Taylor committed
78

79 80
/**
 * g_on_error_query:
81 82 83 84
 * @prg_name: the program name, needed by gdb for the "[S]tack trace"
 *     option. If @prg_name is %NULL, g_get_prgname() is called to get
 *     the program name (which will work correctly if gdk_init() or
 *     gtk_init() has been called)
85 86
 *
 * Prompts the user with
87
 * `[E]xit, [H]alt, show [S]tack trace or [P]roceed`.
88 89 90 91
 * This function is intended to be used for debugging use only.
 * The following example shows how it can be used together with
 * the g_log() functions.
 *
92
 * |[<!-- language="C" -->
93
 * #include <glib.h>
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
 *
 * static void
 * log_handler (const gchar   *log_domain,
 *              GLogLevelFlags log_level,
 *              const gchar   *message,
 *              gpointer       user_data)
 * {
 *   g_log_default_handler (log_domain, log_level, message, user_data);
 *
 *   g_on_error_query (MY_PROGRAM_NAME);
 * }
 *
 * int
 * main (int argc, char *argv[])
 * {
 *   g_log_set_handler (MY_LOG_DOMAIN,
 *                      G_LOG_LEVEL_WARNING |
 *                      G_LOG_LEVEL_ERROR |
 *                      G_LOG_LEVEL_CRITICAL,
 *                      log_handler,
 *                      NULL);
115
 *   ...
116 117
 * ]|
 *
118 119
 * If "[E]xit" is selected, the application terminates with a call
 * to _exit(0).
120
 *
121 122 123
 * If "[S]tack" trace is selected, g_on_error_stack_trace() is called.
 * This invokes gdb, which attaches to the current process and shows
 * 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 130 131
 *
 * On Windows consider using the `G_DEBUGGER` environment
 * variable (see [Running GLib Applications](glib-running.html)) and
 * calling g_on_error_stack_trace() instead.
132
 */
Owen Taylor's avatar
Owen Taylor committed
133
void
134
g_on_error_query (const gchar *prg_name)
Owen Taylor's avatar
Owen Taylor committed
135
{
136
#ifndef G_OS_WIN32
137 138 139
  static const gchar * const query1 = "[E]xit, [H]alt";
  static const gchar * const query2 = ", show [S]tack trace";
  static const gchar * const query3 = " or [P]roceed";
140 141 142 143
  gchar buf[16];

  if (!prg_name)
    prg_name = g_get_prgname ();
144

145
 retry:
146

147
  if (prg_name)
148
    _g_fprintf (stdout,
149 150 151 152 153 154
                "%s (pid:%u): %s%s%s: ",
                prg_name,
                (guint) getpid (),
                query1,
                query2,
                query3);
155
  else
156
    _g_fprintf (stdout,
157 158 159 160
                "(process:%u): %s%s: ",
                (guint) getpid (),
                query1,
                query3);
Owen Taylor's avatar
Owen Taylor committed
161
  fflush (stdout);
162

163
  if (isatty(0) && isatty(1))
164
    fgets (buf, 8, stdin);
165 166
  else
    strcpy (buf, "E\n");
167 168 169 170 171

  if ((buf[0] == 'E' || buf[0] == 'e')
      && buf[1] == '\n')
    _exit (0);
  else if ((buf[0] == 'P' || buf[0] == 'p')
172
           && buf[1] == '\n')
Owen Taylor's avatar
Owen Taylor committed
173
    return;
174
  else if (prg_name
175 176
           && (buf[0] == 'S' || buf[0] == 's')
           && buf[1] == '\n')
177 178 179 180 181
    {
      g_on_error_stack_trace (prg_name);
      goto retry;
    }
  else if ((buf[0] == 'H' || buf[0] == 'h')
182
           && buf[1] == '\n')
183 184
    {
      while (glib_on_error_halt)
185
        ;
186 187 188
      glib_on_error_halt = TRUE;
      return;
    }
Owen Taylor's avatar
Owen Taylor committed
189
  else
190
    goto retry;
191 192 193
#else
  if (!prg_name)
    prg_name = g_get_prgname ();
194

195
  MessageBox (NULL, "g_on_error_query called, program terminating",
196 197
              (prg_name && *prg_name) ? prg_name : NULL,
              MB_OK|MB_ICONERROR);
198 199
  _exit(0);
#endif
Owen Taylor's avatar
Owen Taylor committed
200 201
}

202 203
/**
 * g_on_error_stack_trace:
204 205
 * @prg_name: the program name, needed by gdb for the "[S]tack trace"
 *     option
206
 *
207 208 209 210 211
 * Invokes gdb, which attaches to the current process and shows a
 * stack trace. Called by g_on_error_query() when the "[S]tack trace"
 * option is selected. You can get the current process's program name
 * with g_get_prgname(), assuming that you have called gtk_init() or
 * gdk_init().
212 213
 *
 * This function may cause different actions on non-UNIX platforms.
214 215 216 217 218 219
 *
 * When running on Windows, this function is *not* called by
 * g_on_error_query(). If called directly, it will raise an
 * exception, which will crash the program. If the `G_DEBUGGER` environment
 * variable is set, a debugger will be invoked to attach and
 * handle that exception (see [Running GLib Applications](glib-running.html)).
220
 */
Owen Taylor's avatar
Owen Taylor committed
221
void
222
g_on_error_stack_trace (const gchar *prg_name)
Owen Taylor's avatar
Owen Taylor committed
223
{
224
#if defined(G_OS_UNIX)
Owen Taylor's avatar
Owen Taylor committed
225
  pid_t pid;
226
  gchar buf[16];
227
  const gchar *args[4] = { "gdb", NULL, NULL, NULL };
228
  int status;
229 230 231

  if (!prg_name)
    return;
Owen Taylor's avatar
Owen Taylor committed
232

233
  _g_sprintf (buf, "%u", (guint) getpid ());
Owen Taylor's avatar
Owen Taylor committed
234

235
  args[1] = prg_name;
Owen Taylor's avatar
Owen Taylor committed
236 237
  args[2] = buf;

238 239
  pid = fork ();
  if (pid == 0)
Owen Taylor's avatar
Owen Taylor committed
240
    {
241 242
      stack_trace (args);
      _exit (0);
Owen Taylor's avatar
Owen Taylor committed
243
    }
244 245 246 247 248
  else if (pid == (pid_t) -1)
    {
      perror ("unable to fork gdb");
      return;
    }
249 250

  waitpid (pid, &status, 0);
251
#else
252 253 254
  if (IsDebuggerPresent ())
    G_BREAKPOINT ();
  else
255
    g_abort ();
256
#endif
257 258
}

259 260
#ifndef G_OS_WIN32

261 262 263 264 265 266
static gboolean stack_trace_done = FALSE;

static void
stack_trace_sigchld (int signum)
{
  stack_trace_done = TRUE;
Owen Taylor's avatar
Owen Taylor committed
267 268 269
}

static void
270
stack_trace (const char * const *args)
Owen Taylor's avatar
Owen Taylor committed
271 272 273 274
{
  pid_t pid;
  int in_fd[2];
  int out_fd[2];
275 276
  fd_set fdset;
  fd_set readset;
Owen Taylor's avatar
Owen Taylor committed
277
  struct timeval tv;
278
  int sel, idx, state;
Owen Taylor's avatar
Owen Taylor committed
279 280 281
  char buffer[256];
  char c;

282
  stack_trace_done = FALSE;
Owen Taylor's avatar
Owen Taylor committed
283 284 285 286
  signal (SIGCHLD, stack_trace_sigchld);

  if ((pipe (in_fd) == -1) || (pipe (out_fd) == -1))
    {
287
      perror ("unable to open pipe");
Owen Taylor's avatar
Owen Taylor committed
288 289 290 291 292 293
      _exit (0);
    }

  pid = fork ();
  if (pid == 0)
    {
294 295 296 297
      /* Save stderr for printing failure below */
      int old_err = dup (2);
      fcntl (old_err, F_SETFD, fcntl (old_err, F_GETFD) | FD_CLOEXEC);

Owen Taylor's avatar
Owen Taylor committed
298 299 300 301
      close (0); dup (in_fd[0]);   /* set the stdin to the in pipe */
      close (1); dup (out_fd[1]);  /* set the stdout to the out pipe */
      close (2); dup (out_fd[1]);  /* set the stderr to the out pipe */

302
      execvp (args[0], (char **) args);      /* exec gdb */
303 304 305 306

      /* Print failure to original stderr */
      close (2); dup (old_err);
      perror ("exec gdb failed");
Owen Taylor's avatar
Owen Taylor committed
307 308 309 310
      _exit (0);
    }
  else if (pid == (pid_t) -1)
    {
311
      perror ("unable to fork");
Owen Taylor's avatar
Owen Taylor committed
312 313 314 315 316 317 318 319 320 321
      _exit (0);
    }

  FD_ZERO (&fdset);
  FD_SET (out_fd[0], &fdset);

  write (in_fd[1], "backtrace\n", 10);
  write (in_fd[1], "p x = 0\n", 8);
  write (in_fd[1], "quit\n", 5);

322
  idx = 0;
Owen Taylor's avatar
Owen Taylor committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
  state = 0;

  while (1)
    {
      readset = fdset;
      tv.tv_sec = 1;
      tv.tv_usec = 0;

      sel = select (FD_SETSIZE, &readset, NULL, NULL, &tv);
      if (sel == -1)
        break;

      if ((sel > 0) && (FD_ISSET (out_fd[0], &readset)))
        {
          if (read (out_fd[0], &c, 1))
            {
              switch (state)
                {
                case 0:
                  if (c == '#')
                    {
                      state = 1;
345 346
                      idx = 0;
                      buffer[idx++] = c;
Owen Taylor's avatar
Owen Taylor committed
347 348 349
                    }
                  break;
                case 1:
350
                  buffer[idx++] = c;
Owen Taylor's avatar
Owen Taylor committed
351 352
                  if ((c == '\n') || (c == '\r'))
                    {
353
                      buffer[idx] = 0;
354
                      _g_fprintf (stdout, "%s", buffer);
Owen Taylor's avatar
Owen Taylor committed
355
                      state = 0;
356
                      idx = 0;
Owen Taylor's avatar
Owen Taylor committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
                    }
                  break;
                default:
                  break;
                }
            }
        }
      else if (stack_trace_done)
        break;
    }

  close (in_fd[0]);
  close (in_fd[1]);
  close (out_fd[0]);
  close (out_fd[1]);
  _exit (0);
}
374 375

#endif /* !G_OS_WIN32 */