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 STRICT /* Strict typing, please */
78 # define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
84 /* --- structures --- */
85 typedef struct _GLogDomain GLogDomain;
86 typedef struct _GLogHandler GLogHandler;
90 GLogLevelFlags fatal_mask;
91 GLogHandler *handlers;
97 GLogLevelFlags log_level;
104 /* --- variables --- */
105 static GMutex g_messages_lock;
106 static GLogDomain *g_log_domains = NULL;
107 static GPrintFunc glib_print_func = NULL;
108 static GPrintFunc glib_printerr_func = NULL;
109 static GPrivate g_log_depth;
110 static GLogFunc default_log_func = g_log_default_handler;
111 static gpointer default_log_data = NULL;
112 static GTestLogFatalFunc fatal_log_func = NULL;
113 static gpointer fatal_log_data;
115 /* --- functions --- */
118 # include <windows.h>
120 static gboolean win32_keep_fatal_message = FALSE;
122 /* This default message will usually be overwritten. */
123 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
124 * called with huge strings, is it?
126 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
127 static gchar *fatal_msg_ptr = fatal_msg_buf;
135 if (win32_keep_fatal_message)
137 memcpy (fatal_msg_ptr, buf, len);
138 fatal_msg_ptr += len;
143 write (fd, buf, len);
147 #define write(fd, buf, len) dowrite(fd, buf, len)
152 write_string (int fd,
155 write (fd, string, strlen (string));
159 g_log_find_domain_L (const gchar *log_domain)
161 register GLogDomain *domain;
163 domain = g_log_domains;
166 if (strcmp (domain->log_domain, log_domain) == 0)
168 domain = domain->next;
174 g_log_domain_new_L (const gchar *log_domain)
176 register GLogDomain *domain;
178 domain = g_new (GLogDomain, 1);
179 domain->log_domain = g_strdup (log_domain);
180 domain->fatal_mask = G_LOG_FATAL_MASK;
181 domain->handlers = NULL;
183 domain->next = g_log_domains;
184 g_log_domains = domain;
190 g_log_domain_check_free_L (GLogDomain *domain)
192 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
193 domain->handlers == NULL)
195 register GLogDomain *last, *work;
199 work = g_log_domains;
205 last->next = domain->next;
207 g_log_domains = domain->next;
208 g_free (domain->log_domain);
219 g_log_domain_get_handler_L (GLogDomain *domain,
220 GLogLevelFlags log_level,
223 if (domain && log_level)
225 register GLogHandler *handler;
227 handler = domain->handlers;
230 if ((handler->log_level & log_level) == log_level)
232 *data = handler->data;
233 return handler->log_func;
235 handler = handler->next;
239 *data = default_log_data;
240 return default_log_func;
244 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
246 GLogLevelFlags old_mask;
248 /* restrict the global mask to levels that are known to glib
249 * since this setting applies to all domains
251 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
252 /* force errors to be fatal */
253 fatal_mask |= G_LOG_LEVEL_ERROR;
254 /* remove bogus flag */
255 fatal_mask &= ~G_LOG_FLAG_FATAL;
257 g_mutex_lock (&g_messages_lock);
258 old_mask = g_log_always_fatal;
259 g_log_always_fatal = fatal_mask;
260 g_mutex_unlock (&g_messages_lock);
266 g_log_set_fatal_mask (const gchar *log_domain,
267 GLogLevelFlags fatal_mask)
269 GLogLevelFlags old_flags;
270 register GLogDomain *domain;
275 /* force errors to be fatal */
276 fatal_mask |= G_LOG_LEVEL_ERROR;
277 /* remove bogus flag */
278 fatal_mask &= ~G_LOG_FLAG_FATAL;
280 g_mutex_lock (&g_messages_lock);
282 domain = g_log_find_domain_L (log_domain);
284 domain = g_log_domain_new_L (log_domain);
285 old_flags = domain->fatal_mask;
287 domain->fatal_mask = fatal_mask;
288 g_log_domain_check_free_L (domain);
290 g_mutex_unlock (&g_messages_lock);
296 g_log_set_handler (const gchar *log_domain,
297 GLogLevelFlags log_levels,
301 static guint handler_id = 0;
303 GLogHandler *handler;
305 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
306 g_return_val_if_fail (log_func != NULL, 0);
311 handler = g_new (GLogHandler, 1);
313 g_mutex_lock (&g_messages_lock);
315 domain = g_log_find_domain_L (log_domain);
317 domain = g_log_domain_new_L (log_domain);
319 handler->id = ++handler_id;
320 handler->log_level = log_levels;
321 handler->log_func = log_func;
322 handler->data = user_data;
323 handler->next = domain->handlers;
324 domain->handlers = handler;
326 g_mutex_unlock (&g_messages_lock);
332 g_log_set_default_handler (GLogFunc log_func,
335 GLogFunc old_log_func;
337 g_mutex_lock (&g_messages_lock);
338 old_log_func = default_log_func;
339 default_log_func = log_func;
340 default_log_data = user_data;
341 g_mutex_unlock (&g_messages_lock);
347 * g_test_log_set_fatal_handler:
348 * @log_func: the log handler function.
349 * @user_data: data passed to the log handler.
351 * Installs a non-error fatal log handler which can be
352 * used to decide whether log messages which are counted
353 * as fatal abort the program.
355 * The use case here is that you are running a test case
356 * that depends on particular libraries or circumstances
357 * and cannot prevent certain known critical or warning
358 * messages. So you install a handler that compares the
359 * domain and message to precisely not abort in such a case.
361 * Note that the handler is reset at the beginning of
362 * any test case, so you have to set it inside each test
363 * function which needs the special behavior.
365 * This handler has no effect on g_error messages.
370 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
373 g_mutex_lock (&g_messages_lock);
374 fatal_log_func = log_func;
375 fatal_log_data = user_data;
376 g_mutex_unlock (&g_messages_lock);
380 g_log_remove_handler (const gchar *log_domain,
383 register GLogDomain *domain;
385 g_return_if_fail (handler_id > 0);
390 g_mutex_lock (&g_messages_lock);
391 domain = g_log_find_domain_L (log_domain);
394 GLogHandler *work, *last;
397 work = domain->handlers;
400 if (work->id == handler_id)
403 last->next = work->next;
405 domain->handlers = work->next;
406 g_log_domain_check_free_L (domain);
407 g_mutex_unlock (&g_messages_lock);
415 g_mutex_unlock (&g_messages_lock);
416 g_warning ("%s: could not find handler with id `%d' for domain \"%s\"",
417 G_STRLOC, handler_id, log_domain);
421 g_logv (const gchar *log_domain,
422 GLogLevelFlags log_level,
426 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
427 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
430 log_level &= G_LOG_LEVEL_MASK;
434 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
436 register GLogLevelFlags test_level;
439 if (log_level & test_level)
443 GLogLevelFlags domain_fatal_mask;
444 gpointer data = NULL;
445 gboolean masquerade_fatal = FALSE;
449 test_level |= G_LOG_FLAG_FATAL;
451 test_level |= G_LOG_FLAG_RECURSION;
453 /* check recursion and lookup handler */
454 g_mutex_lock (&g_messages_lock);
455 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
456 domain = g_log_find_domain_L (log_domain ? log_domain : "");
458 test_level |= G_LOG_FLAG_RECURSION;
460 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
461 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
462 test_level |= G_LOG_FLAG_FATAL;
463 if (test_level & G_LOG_FLAG_RECURSION)
464 log_func = _g_log_fallback_handler;
466 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
468 g_mutex_unlock (&g_messages_lock);
470 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
473 if (test_level & G_LOG_FLAG_RECURSION)
475 /* we use a stack buffer of fixed size, since we're likely
476 * in an out-of-memory situation
479 gsize size G_GNUC_UNUSED;
482 G_VA_COPY (args2, args1);
483 size = _g_vsnprintf (buffer, 1024, format, args2);
486 log_func (log_domain, test_level, buffer, data);
493 G_VA_COPY (args2, args1);
494 msg = g_strdup_vprintf (format, args2);
497 log_func (log_domain, test_level, msg, data);
499 if ((test_level & G_LOG_FLAG_FATAL)
500 && !(test_level & G_LOG_LEVEL_ERROR))
502 masquerade_fatal = fatal_log_func
503 && !fatal_log_func (log_domain, test_level, msg, data);
509 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
512 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
514 MessageBox (NULL, locale_msg, NULL,
515 MB_ICONERROR|MB_SETFOREGROUND);
516 if (IsDebuggerPresent () && !(test_level & G_LOG_FLAG_RECURSION))
521 if (!(test_level & G_LOG_FLAG_RECURSION))
525 #endif /* !G_OS_WIN32 */
529 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
535 g_log (const gchar *log_domain,
536 GLogLevelFlags log_level,
542 va_start (args, format);
543 g_logv (log_domain, log_level, format, args);
548 g_return_if_fail_warning (const char *log_domain,
549 const char *pretty_function,
550 const char *expression)
553 G_LOG_LEVEL_CRITICAL,
554 "%s: assertion `%s' failed",
560 g_warn_message (const char *domain,
564 const char *warnexpr)
567 g_snprintf (lstr, 32, "%d", line);
569 s = g_strconcat ("(", file, ":", lstr, "):",
570 func, func[0] ? ":" : "",
571 " runtime check failed: (", warnexpr, ")", NULL);
573 s = g_strconcat ("(", file, ":", lstr, "):",
574 func, func[0] ? ":" : "",
575 " ", "code should not be reached", NULL);
576 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
581 g_assert_warning (const char *log_domain,
584 const char *pretty_function,
585 const char *expression)
590 ? "file %s: line %d (%s): assertion failed: (%s)"
591 : "file %s: line %d (%s): should not be reached",
599 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
601 (wc >= 0x80 && wc < 0xa0)))
604 strdup_convert (const gchar *string,
605 const gchar *charset)
607 if (!g_utf8_validate (string, -1, NULL))
609 GString *gstring = g_string_new ("[Invalid UTF-8] ");
612 for (p = (guchar *)string; *p; p++)
614 if (CHAR_IS_SAFE(*p) &&
615 !(*p == '\r' && *(p + 1) != '\n') &&
617 g_string_append_c (gstring, *p);
619 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
622 return g_string_free (gstring, FALSE);
628 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
633 /* Not thread-safe, but doesn't matter if we print the warning twice
635 static gboolean warned = FALSE;
639 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
643 return g_strdup (string);
648 /* For a radix of 8 we need at most 3 output bytes for 1 input
649 * byte. Additionally we might need up to 2 output bytes for the
650 * readix prefix and 1 byte for the trailing NULL.
652 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
655 format_unsigned (gchar *buf,
663 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
665 if (radix != 8 && radix != 10 && radix != 16)
698 /* Again we can't use g_assert; actually this check should _never_ fail. */
699 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
712 buf[i] = c + 'a' - 10;
719 /* string size big enough to hold level prefix */
720 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
722 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
725 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
726 GLogLevelFlags log_level)
728 gboolean to_stdout = TRUE;
730 /* we may not call _any_ GLib functions here */
732 switch (log_level & G_LOG_LEVEL_MASK)
734 case G_LOG_LEVEL_ERROR:
735 strcpy (level_prefix, "ERROR");
738 case G_LOG_LEVEL_CRITICAL:
739 strcpy (level_prefix, "CRITICAL");
742 case G_LOG_LEVEL_WARNING:
743 strcpy (level_prefix, "WARNING");
746 case G_LOG_LEVEL_MESSAGE:
747 strcpy (level_prefix, "Message");
750 case G_LOG_LEVEL_INFO:
751 strcpy (level_prefix, "INFO");
753 case G_LOG_LEVEL_DEBUG:
754 strcpy (level_prefix, "DEBUG");
759 strcpy (level_prefix, "LOG-");
760 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
763 strcpy (level_prefix, "LOG");
766 if (log_level & G_LOG_FLAG_RECURSION)
767 strcat (level_prefix, " (recursed)");
768 if (log_level & ALERT_LEVELS)
769 strcat (level_prefix, " **");
772 win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
774 return to_stdout ? 1 : 2;
778 _g_log_fallback_handler (const gchar *log_domain,
779 GLogLevelFlags log_level,
780 const gchar *message,
781 gpointer unused_data)
783 gchar level_prefix[STRING_BUFFER_SIZE];
785 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
789 /* we cannot call _any_ GLib functions in this fallback handler,
790 * which is why we skip UTF-8 conversion, etc.
791 * since we either recursed or ran out of memory, we're in a pretty
792 * pathologic situation anyways, what we can do is giving the
793 * the process ID unconditionally however.
796 fd = mklevel_prefix (level_prefix, log_level);
798 message = "(NULL) message";
801 format_unsigned (pid_string, getpid (), 10);
805 write_string (fd, "\n");
807 write_string (fd, "\n** ");
810 write_string (fd, "(process:");
811 write_string (fd, pid_string);
812 write_string (fd, "): ");
817 write_string (fd, log_domain);
818 write_string (fd, "-");
820 write_string (fd, level_prefix);
821 write_string (fd, ": ");
822 write_string (fd, message);
826 escape_string (GString *string)
828 const char *p = string->str;
831 while (p < string->str + string->len)
835 wc = g_utf8_get_char_validated (p, -1);
836 if (wc == (gunichar)-1 || wc == (gunichar)-2)
841 pos = p - string->str;
843 /* Emit invalid UTF-8 as hex escapes
845 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
846 g_string_erase (string, pos, 1);
847 g_string_insert (string, pos, tmp);
849 p = string->str + (pos + 4); /* Skip over escape sequence */
856 safe = *(p + 1) == '\n';
860 safe = CHAR_IS_SAFE (wc);
868 pos = p - string->str;
870 /* Largest char we escape is 0x0a, so we don't have to worry
871 * about 8-digit \Uxxxxyyyy
873 tmp = g_strdup_printf ("\\u%04x", wc);
874 g_string_erase (string, pos, g_utf8_next_char (p) - p);
875 g_string_insert (string, pos, tmp);
878 p = string->str + (pos + 6); /* Skip over escape sequence */
881 p = g_utf8_next_char (p);
886 g_log_default_handler (const gchar *log_domain,
887 GLogLevelFlags log_level,
888 const gchar *message,
889 gpointer unused_data)
891 gchar level_prefix[STRING_BUFFER_SIZE], *string;
895 /* we can be called externally with recursion for whatever reason */
896 if (log_level & G_LOG_FLAG_RECURSION)
898 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
902 fd = mklevel_prefix (level_prefix, log_level);
904 gstring = g_string_new (NULL);
905 if (log_level & ALERT_LEVELS)
906 g_string_append (gstring, "\n");
908 g_string_append (gstring, "** ");
910 if ((g_log_msg_prefix & log_level) == log_level)
912 const gchar *prg_name = g_get_prgname ();
915 g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
917 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
922 g_string_append (gstring, log_domain);
923 g_string_append_c (gstring, '-');
925 g_string_append (gstring, level_prefix);
927 g_string_append (gstring, ": ");
929 g_string_append (gstring, "(NULL) message");
933 const gchar *charset;
935 msg = g_string_new (message);
938 if (g_get_charset (&charset))
939 g_string_append (gstring, msg->str); /* charset is UTF-8 already */
942 string = strdup_convert (msg->str, charset);
943 g_string_append (gstring, string);
947 g_string_free (msg, TRUE);
949 g_string_append (gstring, "\n");
951 string = g_string_free (gstring, FALSE);
953 write_string (fd, string);
958 * g_set_print_handler:
959 * @func: the new print handler
961 * Sets the print handler.
963 * Any messages passed to g_print() will be output via
964 * the new handler. The default handler simply outputs
965 * the message to stdout. By providing your own handler
966 * you can redirect the output, to a GTK+ widget or a
967 * log file for example.
969 * Returns: the old print handler
972 g_set_print_handler (GPrintFunc func)
974 GPrintFunc old_print_func;
976 g_mutex_lock (&g_messages_lock);
977 old_print_func = glib_print_func;
978 glib_print_func = func;
979 g_mutex_unlock (&g_messages_lock);
981 return old_print_func;
986 * @format: the message format. See the printf() documentation
987 * @...: the parameters to insert into the format string
989 * Outputs a formatted message via the print handler.
990 * The default print handler simply outputs the message to stdout.
992 * g_print() should not be used from within libraries for debugging
993 * messages, since it may be redirected by applications to special
994 * purpose message windows or even files. Instead, libraries should
995 * use g_log(), or the convenience functions g_message(), g_warning()
999 g_print (const gchar *format,
1004 GPrintFunc local_glib_print_func;
1006 g_return_if_fail (format != NULL);
1008 va_start (args, format);
1009 string = g_strdup_vprintf (format, args);
1012 g_mutex_lock (&g_messages_lock);
1013 local_glib_print_func = glib_print_func;
1014 g_mutex_unlock (&g_messages_lock);
1016 if (local_glib_print_func)
1017 local_glib_print_func (string);
1020 const gchar *charset;
1022 if (g_get_charset (&charset))
1023 fputs (string, stdout); /* charset is UTF-8 already */
1026 gchar *lstring = strdup_convert (string, charset);
1028 fputs (lstring, stdout);
1037 * g_set_printerr_handler:
1038 * @func: the new error message handler
1040 * Sets the handler for printing error messages.
1042 * Any messages passed to g_printerr() will be output via
1043 * the new handler. The default handler simply outputs the
1044 * message to stderr. By providing your own handler you can
1045 * redirect the output, to a GTK+ widget or a log file for
1048 * Returns: the old error message handler
1051 g_set_printerr_handler (GPrintFunc func)
1053 GPrintFunc old_printerr_func;
1055 g_mutex_lock (&g_messages_lock);
1056 old_printerr_func = glib_printerr_func;
1057 glib_printerr_func = func;
1058 g_mutex_unlock (&g_messages_lock);
1060 return old_printerr_func;
1065 * @format: the message format. See the printf() documentation
1066 * @...: the parameters to insert into the format string
1068 * Outputs a formatted message via the error message handler.
1069 * The default handler simply outputs the message to stderr.
1071 * g_printerr() should not be used from within libraries.
1072 * Instead g_log() should be used, or the convenience functions
1073 * g_message(), g_warning() and g_error().
1076 g_printerr (const gchar *format,
1081 GPrintFunc local_glib_printerr_func;
1083 g_return_if_fail (format != NULL);
1085 va_start (args, format);
1086 string = g_strdup_vprintf (format, args);
1089 g_mutex_lock (&g_messages_lock);
1090 local_glib_printerr_func = glib_printerr_func;
1091 g_mutex_unlock (&g_messages_lock);
1093 if (local_glib_printerr_func)
1094 local_glib_printerr_func (string);
1097 const gchar *charset;
1099 if (g_get_charset (&charset))
1100 fputs (string, stderr); /* charset is UTF-8 already */
1103 gchar *lstring = strdup_convert (string, charset);
1105 fputs (lstring, stderr);
1114 * g_printf_string_upper_bound:
1115 * @format: the format string. See the printf() documentation
1116 * @args: the parameters to be inserted into the format string
1118 * Calculates the maximum space needed to store the output
1119 * of the sprintf() function.
1121 * Returns: the maximum space needed to store the formatted string
1124 g_printf_string_upper_bound (const gchar *format,
1128 return _g_vsnprintf (&c, 1, format, args) + 1;