1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
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/.
33 * @Title: Message Output and Debugging Functions
34 * @Short_description: functions to output messages and help debug applications
36 * These functions provide support for outputting messages.
38 * The <function>g_return</function> family of macros (g_return_if_fail(),
39 * g_return_val_if_fail(), g_return_if_reached(), g_return_val_if_reached())
40 * should only be used for programming errors, a typical use case is
41 * checking for invalid parameters at the beginning of a public function.
42 * They should not be used if you just mean "if (error) return", they
43 * should only be used if you mean "if (bug in program) return".
44 * The program behavior is generally considered undefined after one
45 * of these checks fails. They are not intended for normal control
46 * flow, only to give a perhaps-helpful warning before giving up.
62 #include "gmessages.h"
63 #include "glib-init.h"
65 #include "gbacktrace.h"
68 #include "gprintfint.h"
69 #include "gtestutils.h"
71 #include "gstrfuncs.h"
75 #include <process.h> /* For getpid() */
77 # define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
82 /* --- structures --- */
83 typedef struct _GLogDomain GLogDomain;
84 typedef struct _GLogHandler GLogHandler;
88 GLogLevelFlags fatal_mask;
89 GLogHandler *handlers;
95 GLogLevelFlags log_level;
102 /* --- variables --- */
103 static GMutex g_messages_lock;
104 static GLogDomain *g_log_domains = NULL;
105 static GPrintFunc glib_print_func = NULL;
106 static GPrintFunc glib_printerr_func = NULL;
107 static GPrivate g_log_depth;
108 static GLogFunc default_log_func = g_log_default_handler;
109 static gpointer default_log_data = NULL;
110 static GTestLogFatalFunc fatal_log_func = NULL;
111 static gpointer fatal_log_data;
113 /* --- functions --- */
115 # include <windows.h>
116 static gboolean win32_keep_fatal_message = FALSE;
118 /* This default message will usually be overwritten. */
119 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
120 * called with huge strings, is it?
122 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
123 static gchar *fatal_msg_ptr = fatal_msg_buf;
131 if (win32_keep_fatal_message)
133 memcpy (fatal_msg_ptr, buf, len);
134 fatal_msg_ptr += len;
139 write (fd, buf, len);
143 #define write(fd, buf, len) dowrite(fd, buf, len)
148 write_string (int fd,
151 write (fd, string, strlen (string));
155 g_log_find_domain_L (const gchar *log_domain)
157 register GLogDomain *domain;
159 domain = g_log_domains;
162 if (strcmp (domain->log_domain, log_domain) == 0)
164 domain = domain->next;
170 g_log_domain_new_L (const gchar *log_domain)
172 register GLogDomain *domain;
174 domain = g_new (GLogDomain, 1);
175 domain->log_domain = g_strdup (log_domain);
176 domain->fatal_mask = G_LOG_FATAL_MASK;
177 domain->handlers = NULL;
179 domain->next = g_log_domains;
180 g_log_domains = domain;
186 g_log_domain_check_free_L (GLogDomain *domain)
188 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
189 domain->handlers == NULL)
191 register GLogDomain *last, *work;
195 work = g_log_domains;
201 last->next = domain->next;
203 g_log_domains = domain->next;
204 g_free (domain->log_domain);
215 g_log_domain_get_handler_L (GLogDomain *domain,
216 GLogLevelFlags log_level,
219 if (domain && log_level)
221 register GLogHandler *handler;
223 handler = domain->handlers;
226 if ((handler->log_level & log_level) == log_level)
228 *data = handler->data;
229 return handler->log_func;
231 handler = handler->next;
235 *data = default_log_data;
236 return default_log_func;
240 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
242 GLogLevelFlags old_mask;
244 /* restrict the global mask to levels that are known to glib
245 * since this setting applies to all domains
247 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
248 /* force errors to be fatal */
249 fatal_mask |= G_LOG_LEVEL_ERROR;
250 /* remove bogus flag */
251 fatal_mask &= ~G_LOG_FLAG_FATAL;
253 g_mutex_lock (&g_messages_lock);
254 old_mask = g_log_always_fatal;
255 g_log_always_fatal = fatal_mask;
256 g_mutex_unlock (&g_messages_lock);
262 g_log_set_fatal_mask (const gchar *log_domain,
263 GLogLevelFlags fatal_mask)
265 GLogLevelFlags old_flags;
266 register GLogDomain *domain;
271 /* force errors to be fatal */
272 fatal_mask |= G_LOG_LEVEL_ERROR;
273 /* remove bogus flag */
274 fatal_mask &= ~G_LOG_FLAG_FATAL;
276 g_mutex_lock (&g_messages_lock);
278 domain = g_log_find_domain_L (log_domain);
280 domain = g_log_domain_new_L (log_domain);
281 old_flags = domain->fatal_mask;
283 domain->fatal_mask = fatal_mask;
284 g_log_domain_check_free_L (domain);
286 g_mutex_unlock (&g_messages_lock);
292 g_log_set_handler (const gchar *log_domain,
293 GLogLevelFlags log_levels,
297 static guint handler_id = 0;
299 GLogHandler *handler;
301 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
302 g_return_val_if_fail (log_func != NULL, 0);
307 handler = g_new (GLogHandler, 1);
309 g_mutex_lock (&g_messages_lock);
311 domain = g_log_find_domain_L (log_domain);
313 domain = g_log_domain_new_L (log_domain);
315 handler->id = ++handler_id;
316 handler->log_level = log_levels;
317 handler->log_func = log_func;
318 handler->data = user_data;
319 handler->next = domain->handlers;
320 domain->handlers = handler;
322 g_mutex_unlock (&g_messages_lock);
328 g_log_set_default_handler (GLogFunc log_func,
331 GLogFunc old_log_func;
333 g_mutex_lock (&g_messages_lock);
334 old_log_func = default_log_func;
335 default_log_func = log_func;
336 default_log_data = user_data;
337 g_mutex_unlock (&g_messages_lock);
343 * g_test_log_set_fatal_handler:
344 * @log_func: the log handler function.
345 * @user_data: data passed to the log handler.
347 * Installs a non-error fatal log handler which can be
348 * used to decide whether log messages which are counted
349 * as fatal abort the program.
351 * The use case here is that you are running a test case
352 * that depends on particular libraries or circumstances
353 * and cannot prevent certain known critical or warning
354 * messages. So you install a handler that compares the
355 * domain and message to precisely not abort in such a case.
357 * Note that the handler is reset at the beginning of
358 * any test case, so you have to set it inside each test
359 * function which needs the special behavior.
361 * This handler has no effect on g_error messages.
366 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
369 g_mutex_lock (&g_messages_lock);
370 fatal_log_func = log_func;
371 fatal_log_data = user_data;
372 g_mutex_unlock (&g_messages_lock);
376 g_log_remove_handler (const gchar *log_domain,
379 register GLogDomain *domain;
381 g_return_if_fail (handler_id > 0);
386 g_mutex_lock (&g_messages_lock);
387 domain = g_log_find_domain_L (log_domain);
390 GLogHandler *work, *last;
393 work = domain->handlers;
396 if (work->id == handler_id)
399 last->next = work->next;
401 domain->handlers = work->next;
402 g_log_domain_check_free_L (domain);
403 g_mutex_unlock (&g_messages_lock);
411 g_mutex_unlock (&g_messages_lock);
412 g_warning ("%s: could not find handler with id `%d' for domain \"%s\"",
413 G_STRLOC, handler_id, log_domain);
417 g_logv (const gchar *log_domain,
418 GLogLevelFlags log_level,
422 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
423 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
426 log_level &= G_LOG_LEVEL_MASK;
430 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
432 register GLogLevelFlags test_level;
435 if (log_level & test_level)
439 GLogLevelFlags domain_fatal_mask;
440 gpointer data = NULL;
441 gboolean masquerade_fatal = FALSE;
445 test_level |= G_LOG_FLAG_FATAL;
447 test_level |= G_LOG_FLAG_RECURSION;
449 /* check recursion and lookup handler */
450 g_mutex_lock (&g_messages_lock);
451 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
452 domain = g_log_find_domain_L (log_domain ? log_domain : "");
454 test_level |= G_LOG_FLAG_RECURSION;
456 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
457 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
458 test_level |= G_LOG_FLAG_FATAL;
459 if (test_level & G_LOG_FLAG_RECURSION)
460 log_func = _g_log_fallback_handler;
462 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
464 g_mutex_unlock (&g_messages_lock);
466 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
469 if (test_level & G_LOG_FLAG_RECURSION)
471 /* we use a stack buffer of fixed size, since we're likely
472 * in an out-of-memory situation
475 gsize size G_GNUC_UNUSED;
478 G_VA_COPY (args2, args1);
479 size = _g_vsnprintf (buffer, 1024, format, args2);
482 log_func (log_domain, test_level, buffer, data);
489 G_VA_COPY (args2, args1);
490 msg = g_strdup_vprintf (format, args2);
493 log_func (log_domain, test_level, msg, data);
495 if ((test_level & G_LOG_FLAG_FATAL)
496 && !(test_level & G_LOG_LEVEL_ERROR))
498 masquerade_fatal = fatal_log_func
499 && !fatal_log_func (log_domain, test_level, msg, data);
505 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
508 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
510 MessageBox (NULL, locale_msg, NULL,
511 MB_ICONERROR|MB_SETFOREGROUND);
512 if (IsDebuggerPresent () && !(test_level & G_LOG_FLAG_RECURSION))
517 if (!(test_level & G_LOG_FLAG_RECURSION))
521 #endif /* !G_OS_WIN32 */
525 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
531 g_log (const gchar *log_domain,
532 GLogLevelFlags log_level,
538 va_start (args, format);
539 g_logv (log_domain, log_level, format, args);
544 g_return_if_fail_warning (const char *log_domain,
545 const char *pretty_function,
546 const char *expression)
549 G_LOG_LEVEL_CRITICAL,
550 "%s: assertion `%s' failed",
556 g_warn_message (const char *domain,
560 const char *warnexpr)
563 g_snprintf (lstr, 32, "%d", line);
565 s = g_strconcat ("(", file, ":", lstr, "):",
566 func, func[0] ? ":" : "",
567 " runtime check failed: (", warnexpr, ")", NULL);
569 s = g_strconcat ("(", file, ":", lstr, "):",
570 func, func[0] ? ":" : "",
571 " ", "code should not be reached", NULL);
572 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
577 g_assert_warning (const char *log_domain,
580 const char *pretty_function,
581 const char *expression)
586 ? "file %s: line %d (%s): assertion failed: (%s)"
587 : "file %s: line %d (%s): should not be reached",
595 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
597 (wc >= 0x80 && wc < 0xa0)))
600 strdup_convert (const gchar *string,
601 const gchar *charset)
603 if (!g_utf8_validate (string, -1, NULL))
605 GString *gstring = g_string_new ("[Invalid UTF-8] ");
608 for (p = (guchar *)string; *p; p++)
610 if (CHAR_IS_SAFE(*p) &&
611 !(*p == '\r' && *(p + 1) != '\n') &&
613 g_string_append_c (gstring, *p);
615 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
618 return g_string_free (gstring, FALSE);
624 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
629 /* Not thread-safe, but doesn't matter if we print the warning twice
631 static gboolean warned = FALSE;
635 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
639 return g_strdup (string);
644 /* For a radix of 8 we need at most 3 output bytes for 1 input
645 * byte. Additionally we might need up to 2 output bytes for the
646 * readix prefix and 1 byte for the trailing NULL.
648 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
651 format_unsigned (gchar *buf,
659 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
661 if (radix != 8 && radix != 10 && radix != 16)
694 /* Again we can't use g_assert; actually this check should _never_ fail. */
695 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
708 buf[i] = c + 'a' - 10;
715 /* string size big enough to hold level prefix */
716 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
718 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
721 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
722 GLogLevelFlags log_level)
724 gboolean to_stdout = TRUE;
726 /* we may not call _any_ GLib functions here */
728 switch (log_level & G_LOG_LEVEL_MASK)
730 case G_LOG_LEVEL_ERROR:
731 strcpy (level_prefix, "ERROR");
734 case G_LOG_LEVEL_CRITICAL:
735 strcpy (level_prefix, "CRITICAL");
738 case G_LOG_LEVEL_WARNING:
739 strcpy (level_prefix, "WARNING");
742 case G_LOG_LEVEL_MESSAGE:
743 strcpy (level_prefix, "Message");
746 case G_LOG_LEVEL_INFO:
747 strcpy (level_prefix, "INFO");
749 case G_LOG_LEVEL_DEBUG:
750 strcpy (level_prefix, "DEBUG");
755 strcpy (level_prefix, "LOG-");
756 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
759 strcpy (level_prefix, "LOG");
762 if (log_level & G_LOG_FLAG_RECURSION)
763 strcat (level_prefix, " (recursed)");
764 if (log_level & ALERT_LEVELS)
765 strcat (level_prefix, " **");
768 win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
770 return to_stdout ? 1 : 2;
774 _g_log_fallback_handler (const gchar *log_domain,
775 GLogLevelFlags log_level,
776 const gchar *message,
777 gpointer unused_data)
779 gchar level_prefix[STRING_BUFFER_SIZE];
781 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
785 /* we cannot call _any_ GLib functions in this fallback handler,
786 * which is why we skip UTF-8 conversion, etc.
787 * since we either recursed or ran out of memory, we're in a pretty
788 * pathologic situation anyways, what we can do is giving the
789 * the process ID unconditionally however.
792 fd = mklevel_prefix (level_prefix, log_level);
794 message = "(NULL) message";
797 format_unsigned (pid_string, getpid (), 10);
801 write_string (fd, "\n");
803 write_string (fd, "\n** ");
806 write_string (fd, "(process:");
807 write_string (fd, pid_string);
808 write_string (fd, "): ");
813 write_string (fd, log_domain);
814 write_string (fd, "-");
816 write_string (fd, level_prefix);
817 write_string (fd, ": ");
818 write_string (fd, message);
822 escape_string (GString *string)
824 const char *p = string->str;
827 while (p < string->str + string->len)
831 wc = g_utf8_get_char_validated (p, -1);
832 if (wc == (gunichar)-1 || wc == (gunichar)-2)
837 pos = p - string->str;
839 /* Emit invalid UTF-8 as hex escapes
841 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
842 g_string_erase (string, pos, 1);
843 g_string_insert (string, pos, tmp);
845 p = string->str + (pos + 4); /* Skip over escape sequence */
852 safe = *(p + 1) == '\n';
856 safe = CHAR_IS_SAFE (wc);
864 pos = p - string->str;
866 /* Largest char we escape is 0x0a, so we don't have to worry
867 * about 8-digit \Uxxxxyyyy
869 tmp = g_strdup_printf ("\\u%04x", wc);
870 g_string_erase (string, pos, g_utf8_next_char (p) - p);
871 g_string_insert (string, pos, tmp);
874 p = string->str + (pos + 6); /* Skip over escape sequence */
877 p = g_utf8_next_char (p);
882 g_log_default_handler (const gchar *log_domain,
883 GLogLevelFlags log_level,
884 const gchar *message,
885 gpointer unused_data)
887 gchar level_prefix[STRING_BUFFER_SIZE], *string;
891 /* we can be called externally with recursion for whatever reason */
892 if (log_level & G_LOG_FLAG_RECURSION)
894 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
898 fd = mklevel_prefix (level_prefix, log_level);
900 gstring = g_string_new (NULL);
901 if (log_level & ALERT_LEVELS)
902 g_string_append (gstring, "\n");
904 g_string_append (gstring, "** ");
906 if ((g_log_msg_prefix & log_level) == log_level)
908 const gchar *prg_name = g_get_prgname ();
911 g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
913 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
918 g_string_append (gstring, log_domain);
919 g_string_append_c (gstring, '-');
921 g_string_append (gstring, level_prefix);
923 g_string_append (gstring, ": ");
925 g_string_append (gstring, "(NULL) message");
929 const gchar *charset;
931 msg = g_string_new (message);
934 if (g_get_charset (&charset))
935 g_string_append (gstring, msg->str); /* charset is UTF-8 already */
938 string = strdup_convert (msg->str, charset);
939 g_string_append (gstring, string);
943 g_string_free (msg, TRUE);
945 g_string_append (gstring, "\n");
947 string = g_string_free (gstring, FALSE);
949 write_string (fd, string);
954 * g_set_print_handler:
955 * @func: the new print handler
957 * Sets the print handler.
959 * Any messages passed to g_print() will be output via
960 * the new handler. The default handler simply outputs
961 * the message to stdout. By providing your own handler
962 * you can redirect the output, to a GTK+ widget or a
963 * log file for example.
965 * Returns: the old print handler
968 g_set_print_handler (GPrintFunc func)
970 GPrintFunc old_print_func;
972 g_mutex_lock (&g_messages_lock);
973 old_print_func = glib_print_func;
974 glib_print_func = func;
975 g_mutex_unlock (&g_messages_lock);
977 return old_print_func;
982 * @format: the message format. See the printf() documentation
983 * @...: the parameters to insert into the format string
985 * Outputs a formatted message via the print handler.
986 * The default print handler simply outputs the message to stdout.
988 * g_print() should not be used from within libraries for debugging
989 * messages, since it may be redirected by applications to special
990 * purpose message windows or even files. Instead, libraries should
991 * use g_log(), or the convenience functions g_message(), g_warning()
995 g_print (const gchar *format,
1000 GPrintFunc local_glib_print_func;
1002 g_return_if_fail (format != NULL);
1004 va_start (args, format);
1005 string = g_strdup_vprintf (format, args);
1008 g_mutex_lock (&g_messages_lock);
1009 local_glib_print_func = glib_print_func;
1010 g_mutex_unlock (&g_messages_lock);
1012 if (local_glib_print_func)
1013 local_glib_print_func (string);
1016 const gchar *charset;
1018 if (g_get_charset (&charset))
1019 fputs (string, stdout); /* charset is UTF-8 already */
1022 gchar *lstring = strdup_convert (string, charset);
1024 fputs (lstring, stdout);
1033 * g_set_printerr_handler:
1034 * @func: the new error message handler
1036 * Sets the handler for printing error messages.
1038 * Any messages passed to g_printerr() will be output via
1039 * the new handler. The default handler simply outputs the
1040 * message to stderr. By providing your own handler you can
1041 * redirect the output, to a GTK+ widget or a log file for
1044 * Returns: the old error message handler
1047 g_set_printerr_handler (GPrintFunc func)
1049 GPrintFunc old_printerr_func;
1051 g_mutex_lock (&g_messages_lock);
1052 old_printerr_func = glib_printerr_func;
1053 glib_printerr_func = func;
1054 g_mutex_unlock (&g_messages_lock);
1056 return old_printerr_func;
1061 * @format: the message format. See the printf() documentation
1062 * @...: the parameters to insert into the format string
1064 * Outputs a formatted message via the error message handler.
1065 * The default handler simply outputs the message to stderr.
1067 * g_printerr() should not be used from within libraries.
1068 * Instead g_log() should be used, or the convenience functions
1069 * g_message(), g_warning() and g_error().
1072 g_printerr (const gchar *format,
1077 GPrintFunc local_glib_printerr_func;
1079 g_return_if_fail (format != NULL);
1081 va_start (args, format);
1082 string = g_strdup_vprintf (format, args);
1085 g_mutex_lock (&g_messages_lock);
1086 local_glib_printerr_func = glib_printerr_func;
1087 g_mutex_unlock (&g_messages_lock);
1089 if (local_glib_printerr_func)
1090 local_glib_printerr_func (string);
1093 const gchar *charset;
1095 if (g_get_charset (&charset))
1096 fputs (string, stderr); /* charset is UTF-8 already */
1099 gchar *lstring = strdup_convert (string, charset);
1101 fputs (lstring, stderr);
1110 * g_printf_string_upper_bound:
1111 * @format: the format string. See the printf() documentation
1112 * @args: the parameters to be inserted into the format string
1114 * Calculates the maximum space needed to store the output
1115 * of the sprintf() function.
1117 * Returns: the maximum space needed to store the formatted string
1120 g_printf_string_upper_bound (const gchar *format,
1124 return _g_vsnprintf (&c, 1, format, args) + 1;