errors.c 16 KB
Newer Older
1
/* GIMP - The GNU Image Manipulation Program
Elliot Lee's avatar
Elliot Lee committed
2 3
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
 *
4
 * This program is free software: you can redistribute it and/or modify
Elliot Lee's avatar
Elliot Lee committed
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 3 of the License, or
Elliot Lee's avatar
Elliot Lee committed
7 8 9 10 11 12 13 14
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
15
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
Elliot Lee's avatar
Elliot Lee committed
16
 */
17

18 19
#include "config.h"

20
#define _GNU_SOURCE  /* need the POSIX signal API */
21

22
#include <stdlib.h>
23
#include <string.h>
24
#ifdef HAVE_UNISTD_H
Elliot Lee's avatar
Elliot Lee committed
25
#include <unistd.h>
26
#endif
Elliot Lee's avatar
Elliot Lee committed
27

28
#include <gio/gio.h>
29
#include <glib/gstdio.h>
30

31 32 33
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <gegl.h>

34
#include "libgimpbase/gimpbase.h"
35

36
#include "core/core-types.h"
Sven Neumann's avatar
Sven Neumann committed
37

38
#include "core/gimp.h"
39 40 41 42 43 44
#include "core/gimpdrawable.h"
#include "core/gimpimage.h"
#include "core/gimpitem.h"
#include "core/gimpparamspecs.h"

#include "pdb/gimppdb.h"
Michael Natterer's avatar
Michael Natterer committed
45

Elliot Lee's avatar
Elliot Lee committed
46
#include "errors.h"
47

48
#ifdef G_OS_WIN32
49 50 51
#include <windows.h>
#endif

52 53
/*  private variables  */

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
static const gchar * const log_domains[] =
{
  "Gimp",
  "Gimp-Actions",
  "Gimp-Base",
  "Gimp-Composite",
  "Gimp-Config",
  "Gimp-Core",
  "Gimp-Dialogs",
  "Gimp-Display",
  "Gimp-File",
  "Gimp-GEGL",
  "Gimp-GUI",
  "Gimp-Menus",
  "Gimp-Operations",
  "Gimp-PDB",
  "Gimp-Paint",
  "Gimp-Paint-Funcs",
  "Gimp-Plug-In",
  "Gimp-Text",
  "Gimp-Tools",
  "Gimp-Vectors",
  "Gimp-Widgets",
  "Gimp-XCF",
  "LibGimpBase",
  "LibGimpColor",
  "LibGimpConfig",
  "LibGimpMath",
  "LibGimpModule",
  "LibGimpThumb",
  "LibGimpWidgets"
};

87
static Gimp                *the_errors_gimp   = NULL;
88 89 90
static gboolean             use_debug_handler = FALSE;
static GimpStackTraceMode   stack_trace_mode  = GIMP_STACK_TRACE_QUERY;
static gchar               *full_prog_name    = NULL;
91
static gchar               *backtrace_file    = NULL;
92
static gchar               *backup_path       = NULL;
93 94 95
static guint                log_domain_handler_ids[G_N_ELEMENTS (log_domains)];
static guint                gegl_handler_id   = 0;
static guint                global_handler_id = 0;
96

97 98 99

/*  local function prototypes  */

100 101 102 103 104 105 106 107
static void    gimp_message_log_func             (const gchar        *log_domain,
                                                  GLogLevelFlags      flags,
                                                  const gchar        *message,
                                                  gpointer            data);
static void    gimp_error_log_func               (const gchar        *domain,
                                                  GLogLevelFlags      flags,
                                                  const gchar        *message,
                                                  gpointer            data) G_GNUC_NORETURN;
108

109 110 111
static G_GNUC_NORETURN void  gimp_eek            (const gchar        *reason,
                                                  const gchar        *message,
                                                  gboolean            use_handler);
112

113

114 115
/*  public functions  */

116
void
117 118 119
errors_init (Gimp               *gimp,
             const gchar        *_full_prog_name,
             gboolean            _use_debug_handler,
120 121
             GimpStackTraceMode  _stack_trace_mode,
             const gchar        *_backtrace_file)
122
{
123 124
  gint i;

125
  g_return_if_fail (GIMP_IS_GIMP (gimp));
126
  g_return_if_fail (_full_prog_name != NULL);
127
  g_return_if_fail (full_prog_name == NULL);
128

129
#ifdef GIMP_UNSTABLE
130
  g_printerr ("This is a development version of GIMP.  "
131
              "Debug messages may appear here.\n\n");
132
#endif /* GIMP_UNSTABLE */
133

134
  the_errors_gimp   = gimp;
135 136 137
  use_debug_handler = _use_debug_handler ? TRUE : FALSE;
  stack_trace_mode  = _stack_trace_mode;
  full_prog_name    = g_strdup (_full_prog_name);
138 139 140

  /* Create parent directories for both the crash and backup files. */
  backtrace_file    = g_path_get_dirname (_backtrace_file);
141 142
  backup_path       = g_build_filename (gimp_directory (), "backups", NULL);

143 144 145 146
  g_mkdir_with_parents (backtrace_file, S_IRUSR | S_IWUSR | S_IXUSR);
  g_free (backtrace_file);
  backtrace_file = g_strdup (_backtrace_file);

147 148 149 150
  g_mkdir_with_parents (backup_path, S_IRUSR | S_IWUSR | S_IXUSR);
  g_free (backup_path);
  backup_path = g_build_filename (gimp_directory (), "backups",
                                  "backup-XXX.xcf", NULL);
151

152
  for (i = 0; i < G_N_ELEMENTS (log_domains); i++)
153 154 155 156 157 158 159 160 161 162 163 164 165 166
    log_domain_handler_ids[i] = g_log_set_handler (log_domains[i],
                                                   G_LOG_LEVEL_WARNING |
                                                   G_LOG_LEVEL_MESSAGE |
                                                   G_LOG_LEVEL_CRITICAL,
                                                   gimp_message_log_func, gimp);

  gegl_handler_id   = g_log_set_handler ("GEGL",
                                         G_LOG_LEVEL_WARNING |
                                         G_LOG_LEVEL_MESSAGE |
                                         G_LOG_LEVEL_CRITICAL,
                                         gimp_message_log_func, gimp);
  global_handler_id = g_log_set_handler (NULL,
                                         G_LOG_LEVEL_ERROR | G_LOG_FLAG_FATAL,
                                         gimp_error_log_func, gimp);
167
}
Elliot Lee's avatar
Elliot Lee committed
168

169 170 171
void
errors_exit (void)
{
172 173 174 175 176 177 178 179
  gint i;

  for (i = 0; i < G_N_ELEMENTS (log_domains); i++)
    g_log_remove_handler (log_domains[i], log_domain_handler_ids[i]);

  g_log_remove_handler ("GEGL", gegl_handler_id);
  g_log_remove_handler (NULL, global_handler_id);

180
  the_errors_gimp = NULL;
181 182 183

  if (backtrace_file)
    g_free (backtrace_file);
184 185 186 187
  if (full_prog_name)
    g_free (full_prog_name);
  if (backup_path)
    g_free (backup_path);
188 189
}

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
GList *
errors_recovered (void)
{
  GList *recovered   = NULL;
  gchar *backup_path = g_build_filename (gimp_directory (), "backups", NULL);
  GDir  *backup_dir  = NULL;

  if ((backup_dir = g_dir_open (backup_path, 0, NULL)))
    {
      const gchar *file;

      while ((file = g_dir_read_name (backup_dir)))
        {
          if (g_str_has_suffix (file, ".xcf"))
            {
              gchar *path = g_build_filename (backup_path, file, NULL);

              if (g_file_test (path, G_FILE_TEST_IS_REGULAR) &&
                  ! g_file_test (path, G_FILE_TEST_IS_SYMLINK))
                {
                  /* A quick basic security check. It is not foolproof,
                   * but better than nothing to make sure we are not
                   * trying to read, then delete a folder or a symlink
                   * to a file outside the backup directory.
                   */
                  recovered = g_list_append (recovered, path);
                }
              else
                {
                  g_free (path);
                }
            }
        }

      g_dir_close (backup_dir);
    }
  g_free (backup_path);

  return recovered;
}

231
void
232
gimp_fatal_error (const gchar *message)
233
{
234
  gimp_eek ("fatal error", message, TRUE);
Elliot Lee's avatar
Elliot Lee committed
235
}
236 237

void
238
gimp_terminate (const gchar *message)
239
{
240 241 242 243 244 245
  gimp_eek ("terminated", message, use_debug_handler);
}


/*  private functions  */

246 247 248 249 250 251
static void
gimp_message_log_func (const gchar    *log_domain,
                       GLogLevelFlags  flags,
                       const gchar    *message,
                       gpointer        data)
{
252 253 254 255 256
  Gimp                *gimp        = data;
  GimpCoreConfig      *config      = gimp->config;
  const gchar         *msg_domain  = NULL;
  GimpMessageSeverity  severity    = GIMP_MESSAGE_WARNING;
  gboolean             gui_message = TRUE;
257
  GimpDebugPolicy      debug_policy;
258 259 260 261 262 263 264 265

  /* All GIMP messages are processed under the same domain, but
   * we need to keep the log domain information for third party
   * messages.
   */
  if (! g_str_has_prefix (log_domain, "Gimp") &&
      ! g_str_has_prefix (log_domain, "LibGimp"))
    msg_domain = log_domain;
266

267 268 269 270 271 272 273 274
  /* If debug policy requires it, WARNING and CRITICAL errors must be
   * routed for appropriate debugging.
   */
  g_object_get (G_OBJECT (config),
                "debug-policy", &debug_policy,
                NULL);

  switch (flags & G_LOG_LEVEL_MASK)
275
    {
276
    case G_LOG_LEVEL_WARNING:
277 278 279
      severity = GIMP_MESSAGE_BUG_WARNING;
      if (debug_policy > GIMP_DEBUG_POLICY_WARNING)
        gui_message = FALSE;
280 281
      break;
    case G_LOG_LEVEL_CRITICAL:
282 283 284
      severity = GIMP_MESSAGE_BUG_CRITICAL;
      if (debug_policy > GIMP_DEBUG_POLICY_CRITICAL)
        gui_message = FALSE;
285
      break;
286
    }
287

288
  if (gimp && gui_message)
289
    {
290
      gimp_show_message (gimp, NULL, severity, msg_domain, message);
291 292 293
    }
  else
    {
294 295 296 297
      const gchar *reason = "Message";

      gimp_enum_get_value (GIMP_TYPE_MESSAGE_SEVERITY, severity,
                           NULL, NULL, &reason, NULL);
298 299 300 301

      g_printerr ("%s: %s-%s: %s\n",
                  gimp_filename_to_utf8 (full_prog_name),
                  log_domain, reason, message);
302 303 304 305 306 307 308 309 310 311 312 313
    }
}

static void
gimp_error_log_func (const gchar    *domain,
                     GLogLevelFlags  flags,
                     const gchar    *message,
                     gpointer        data)
{
  gimp_fatal_error (message);
}

314 315 316 317 318
static void
gimp_eek (const gchar *reason,
          const gchar *message,
          gboolean     use_handler)
{
319 320 321 322 323 324
  GimpCoreConfig  *config        = the_errors_gimp->config;
  gboolean         eek_handled   = FALSE;
  GimpDebugPolicy  debug_policy;
  GList           *iter;
  gint             num_idx;
  gint             i = 0;
325 326 327 328 329 330 331 332 333 334

  /* GIMP has 2 ways to handle termination signals and fatal errors: one
   * is the stack trace mode which is set at start as command line
   * option --stack-trace-mode, this won't change for the length of the
   * session and outputs a trace in terminal; the other is set in
   * preferences, outputs a trace in a GUI and can change anytime during
   * the session.
   * The GUI backtrace has priority if it is set.
   */
  g_object_get (G_OBJECT (config),
335
                "debug-policy", &debug_policy,
336 337
                NULL);

338 339
  /* Let's just always output on stdout at least so that there is a
   * trace if the rest fails. */
340
  g_printerr ("%s: %s: %s\n", full_prog_name, reason, message);
341

342 343
#if ! defined (G_OS_WIN32) || defined (HAVE_EXCHNDL)

344
  if (use_handler)
345
    {
346
#ifndef GIMP_CONSOLE_COMPILATION
347
      if (debug_policy != GIMP_DEBUG_POLICY_NEVER &&
348 349
          ! the_errors_gimp->no_interface         &&
          backtrace_file)
350
        {
351 352 353
          FILE     *fd;
          gboolean  has_backtrace = TRUE;

354
          /* If GUI backtrace enabled (it is disabled by default), it
355 356
           * takes precedence over the command line argument.
           */
357
#ifdef G_OS_WIN32
358
          const gchar *gimpdebug = "gimp-debug-tool-" GIMP_TOOL_VERSION ".exe";
359
#elif defined (PLATFORM_OSX)
360
          const gchar *gimpdebug = "gimp-debug-tool-" GIMP_TOOL_VERSION;
361
#else
362
          const gchar *gimpdebug = LIBEXECDIR "/gimp-debug-tool-" GIMP_TOOL_VERSION;
363 364
#endif
          gchar *args[7] = { (gchar *) gimpdebug, full_prog_name, NULL,
365 366
                             (gchar *) reason, (gchar *) message,
                             backtrace_file, NULL };
367 368 369 370 371
          gchar  pid[16];

          g_snprintf (pid, 16, "%u", (guint) getpid ());
          args[2] = pid;

372 373 374 375 376
#ifndef G_OS_WIN32
          /* On Win32, the trace has already been processed by ExcHnl
           * and is waiting for us in a text file.
           */
          fd = g_fopen (backtrace_file, "w");
377
          has_backtrace = gimp_stack_trace_print ((const gchar *) full_prog_name,
378
                                                  fd, NULL);
379 380 381
          fclose (fd);
#endif

382 383 384 385 386
          /* We don't care about any return value. If it fails, too
           * bad, we just won't have any stack trace.
           * We still need to use the sync() variant because we have
           * to keep GIMP up long enough for the debugger to get its
           * trace.
387
           */
388 389
          if (has_backtrace &&
              g_file_test (backtrace_file, G_FILE_TEST_IS_REGULAR) &&
390 391 392 393
              g_spawn_async (NULL, args, NULL,
                             G_SPAWN_SEARCH_PATH | G_SPAWN_STDERR_TO_DEV_NULL | G_SPAWN_STDOUT_TO_DEV_NULL,
                             NULL, NULL, NULL, NULL))
            eek_handled = TRUE;
394
        }
395 396 397 398
#endif /* !GIMP_CONSOLE_COMPILATION */

#ifndef G_OS_WIN32
      if (! eek_handled)
399 400 401 402 403 404 405 406 407 408 409 410 411
        {
          switch (stack_trace_mode)
            {
            case GIMP_STACK_TRACE_NEVER:
              break;

            case GIMP_STACK_TRACE_QUERY:
                {
                  sigset_t sigset;

                  sigemptyset (&sigset);
                  sigprocmask (SIG_SETMASK, &sigset, NULL);

412 413 414
                  if (the_errors_gimp)
                    gimp_gui_ungrab (the_errors_gimp);

415
                  gimp_stack_trace_query ((const gchar *) full_prog_name);
416 417 418 419 420 421 422 423 424 425
                }
              break;

            case GIMP_STACK_TRACE_ALWAYS:
                {
                  sigset_t sigset;

                  sigemptyset (&sigset);
                  sigprocmask (SIG_SETMASK, &sigset, NULL);

426
                  gimp_stack_trace_print ((const gchar *) full_prog_name,
427
                                          stdout, NULL);
428 429
                }
              break;
430

431 432 433
            default:
              break;
            }
434
        }
435
#endif /* ! G_OS_WIN32 */
436
    }
437
#endif /* ! G_OS_WIN32 || HAVE_EXCHNDL */
438

439
#if defined (G_OS_WIN32) && ! defined (GIMP_CONSOLE_COMPILATION)
440
  /* g_on_error_* don't do anything reasonable on Win32. */
441 442 443 444
  if (! eek_handled && ! the_errors_gimp->no_interface)
    MessageBox (NULL, g_strdup_printf ("%s: %s", reason, message),
                full_prog_name, MB_OK|MB_ICONERROR);
#endif
445

446 447 448 449 450 451 452 453 454
  /* Let's try to back-up all unsaved images!
   * It is not 100%: when I tested with various bugs created on purpose,
   * I had cases where saving failed. I am not sure if this is because
   * of some memory management along the way to XCF saving or some other
   * messed up state of GIMP, but this is normal not to expect too much
   * during a crash.
   * Nevertheless in various test cases, I had successful backups XCF of
   * the work in progress. Yeah!
   */
455 456
  if (backup_path)
    {
457 458 459 460 461 462
      /* increase the busy counter, so XCF saving calling
       * gimp_set_busy() and gimp_unset_busy() won't call the GUI
       * layer and do whatever windowing system calls to set cursors.
       */
      the_errors_gimp->busy++;

463 464 465 466 467 468 469 470
      /* The index of 'XXX' in backup_path string. */
      num_idx = strlen (backup_path) - 7;

      iter = gimp_get_image_iter (the_errors_gimp);
      for (; iter && i < 1000; iter = iter->next)
        {
          GimpImage *image = iter->data;
          GimpItem  *item;
471

472 473
          if (! gimp_image_is_dirty (image))
            continue;
474

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
          item = GIMP_ITEM (gimp_image_get_active_drawable (image));

          /* This is a trick because we want to avoid any memory
           * allocation when the process is abnormally terminated.
           * We just assume that you'll never have more than 1000 images
           * open (which is already far fetched).
           */
          backup_path[num_idx + 2] = '0' + (i % 10);
          backup_path[num_idx + 1] = '0' + ((i/10) % 10);
          backup_path[num_idx]     = '0' + ((i/100) % 10);

          /* Saving. */
          gimp_pdb_execute_procedure_by_name (the_errors_gimp->pdb,
                                              gimp_get_user_context (the_errors_gimp),
                                              NULL, NULL,
                                              "gimp-xcf-save",
                                              GIMP_TYPE_INT32, 0,
                                              GIMP_TYPE_IMAGE_ID,    gimp_image_get_ID (image),
                                              GIMP_TYPE_DRAWABLE_ID, gimp_item_get_ID (item),
                                              G_TYPE_STRING,         backup_path,
                                              G_TYPE_STRING,         backup_path,
                                              G_TYPE_NONE);
          i++;
        }
499 500
    }

501
  exit (EXIT_FAILURE);
502
}